File size: 9,287 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { Onboard, getThemeIdFromStylesheet } from '@automattic/data-stores';
import { useSelect, useDispatch } from '@wordpress/data';
import { useDispatch as reduxDispatch } from 'calypso/state';
import { WRITE_INTENT_DEFAULT_DESIGN } from '../../../constants';
import { useComingFromThemeActivationParam } from '../../../hooks/use-coming-from-theme-activation';
import { useSite } from '../../../hooks/use-site';
import { useSiteIdParam } from '../../../hooks/use-site-id-param';
import { useSitePluginSlug } from '../../../hooks/use-site-plugin-slug';
import { useSiteSlugParam } from '../../../hooks/use-site-slug-param';
import { useCanUserManageOptions } from '../../../hooks/use-user-can-manage-options';
import { ONBOARD_STORE, SITE_STORE, USER_STORE } from '../../../stores';
import { redirect } from '../../internals/steps-repository/import/util';
import { ProcessingResult } from '../../internals/steps-repository/processing-step/constants';
import {
	AssertConditionResult,
	AssertConditionState,
	FlowV1,
	ProvidedDependencies,
	StepperStep,
} from '../../internals/types';
import {
	initialBundleSteps,
	beforeCustomBundleSteps,
	afterCustomBundleSteps,
	bundleStepsSettings,
} from './plugin-bundle-data';
import type { OnboardSelect, SiteSelect, UserSelect } from '@automattic/data-stores';

const getNextStep = (
	currentStep: StepperStep[ 'slug' ],
	steps: readonly StepperStep[]
): string | undefined => {
	const stepsIndex = steps.map( ( step ) => step.slug );
	const currentStepIndex = stepsIndex.indexOf( currentStep );
	const nextStep = stepsIndex[ currentStepIndex + 1 ];

	return nextStep;
};

const SiteIntent = Onboard.SiteIntent;

const pluginBundleFlow: FlowV1 = {
	name: 'plugin-bundle',
	isSignupFlow: false,

	useSteps() {
		const pluginSlug = useSitePluginSlug();

		let bundlePluginSteps: StepperStep[] = [];

		if ( pluginSlug && bundleStepsSettings.hasOwnProperty( pluginSlug ) ) {
			bundlePluginSteps = [
				...beforeCustomBundleSteps,
				...bundleStepsSettings[ pluginSlug ].customSteps,
				...afterCustomBundleSteps,
			];
		}
		return [ ...initialBundleSteps, ...bundlePluginSteps ];
	},
	useStepNavigation( currentStep, navigate ) {
		const steps = this.useSteps();
		const intent = useSelect(
			( select ) => ( select( ONBOARD_STORE ) as OnboardSelect ).getIntent(),
			[]
		);
		const goals = useSelect(
			( select ) => ( select( ONBOARD_STORE ) as OnboardSelect ).getGoals(),
			[]
		);
		const selectedDesign = useSelect(
			( select ) => ( select( ONBOARD_STORE ) as OnboardSelect ).getSelectedDesign(),
			[]
		);
		const startingPoint = useSelect(
			( select ) => ( select( ONBOARD_STORE ) as OnboardSelect ).getStartingPoint(),
			[]
		);
		const siteSlugParam = useSiteSlugParam();
		const site = useSite();
		const comingFromThemeActivation = useComingFromThemeActivationParam();

		let siteSlug: string | null = null;
		if ( siteSlugParam ) {
			siteSlug = siteSlugParam;
		} else if ( site ) {
			siteSlug = new URL( site.URL ).host;
		}

		const adminUrl = useSelect(
			( select ) =>
				String(
					( site &&
						( select( SITE_STORE ) as SiteSelect ).getSiteOption( site.ID, 'admin_url' ) ) ||
						''
				),
			[ site ]
		);
		const isAtomic = useSelect(
			( select ) => site && ( select( SITE_STORE ) as SiteSelect ).isSiteAtomic( site.ID ),
			[ site ]
		);
		const storeType = useSelect(
			( select ) => ( select( ONBOARD_STORE ) as OnboardSelect ).getStoreType(),
			[]
		);
		const { setPendingAction, resetOnboardStoreWithSkipFlags } = useDispatch( ONBOARD_STORE );
		const { setIntentOnSite, setGoalsOnSite, setDesignOnSite } = useDispatch( SITE_STORE );
		const siteDetails = useSelect(
			( select ) => site && ( select( SITE_STORE ) as SiteSelect ).getSite( site.ID ),
			[ site ]
		);
		const dispatch = reduxDispatch();
		const pluginSlug = useSitePluginSlug();

		const exitFlow = ( to: string ) => {
			setPendingAction( () => {
				/**
				 * This implementation seems very hacky.
				 * The new Promise returned is never resolved or rejected.
				 *
				 * If we were to resolve the promise when all pending actions complete,
				 * I found out this results in setIntentOnSite and setGoalsOnSite being called multiple times
				 * because the exitFlow itself is called more than once on actual flow exits.
				 */
				return new Promise( () => {
					if ( ! siteSlug ) {
						return;
					}

					const pendingActions = [
						setIntentOnSite( siteSlug, intent ),
						setGoalsOnSite( siteSlug, goals ),
					];
					if ( intent === SiteIntent.Write && ! selectedDesign && ! isAtomic ) {
						pendingActions.push(
							setDesignOnSite( siteSlug, WRITE_INTENT_DEFAULT_DESIGN, { enableThemeSetup: true } )
						);
					}

					Promise.all( pendingActions ).then( () => window.location.assign( to ) );
				} );
			} );

			navigate( 'processing' );

			// Clean-up the store so that if onboard for new site will be launched it will be launched with no preselected values
			resetOnboardStoreWithSkipFlags( [ 'skipPendingAction' ] );
		};

		function submit( providedDependencies: ProvidedDependencies = {} ) {
			let defaultExitDest = `/home/${ siteSlug }`;

			if ( siteDetails?.options?.theme_slug ) {
				const themeId = getThemeIdFromStylesheet( siteDetails?.options?.theme_slug );
				defaultExitDest = `/marketplace/thank-you/${ siteSlug }?themes=${ themeId }`;
			}

			if ( 'checkForPlugins' === currentStep ) {
				// If plugins are already installed, we should exit the flow.
				if ( providedDependencies?.hasPlugins ) {
					// If we have the theme for the site, redirect to the theme page. Otherwise redirect to /home.

					return exitFlow( defaultExitDest );
				}
			}

			const nextStep = getNextStep( currentStep, steps );

			if ( 'bundleConfirm' === nextStep ) {
				if ( isAtomic ) {
					return navigate( 'bundleInstallPlugins' );
				}
			}

			switch ( currentStep ) {
				case 'bundleConfirm': {
					const checkoutUrl = providedDependencies.checkoutUrl as string;

					if ( checkoutUrl ) {
						window.location.replace( checkoutUrl.toString() );
					}

					return navigate( 'bundleTransfer' );
				}
				case 'processing': {
					const processingResult = providedDependencies.processingResult;

					if ( processingResult === ProcessingResult.FAILURE ) {
						return navigate( 'error' );
					}

					// If the user skips starting point, redirect them to the post editor
					if ( intent === 'write' && startingPoint !== 'skip-to-my-home' ) {
						if ( startingPoint !== 'write' ) {
							window.sessionStorage.setItem( 'wpcom_signup_complete_show_draft_post_modal', '1' );
						}

						return exitFlow( `/post/${ siteSlug }` );
					}

					// Custom end of flow.
					const settings = bundleStepsSettings[ pluginSlug ];
					const endReturn = settings?.endFlow?.( {
						intent,
						storeType,
						adminUrl,
						dispatch,
						exitFlow,
					} );
					if ( settings?.endFlow && false !== endReturn ) {
						return endReturn;
					}

					return exitFlow( defaultExitDest );
				}
				case 'bundleTransfer': {
					return navigate( 'processing' );
				}
				default: {
					if ( nextStep ) {
						return navigate( nextStep );
					}
				}
			}
		}

		const goBack = () => {
			if ( comingFromThemeActivation ) {
				return exitFlow( `/themes/${ siteSlug }` );
			}

			// Custom back navigation.
			const navigateReturn = bundleStepsSettings[ pluginSlug ]?.goBack?.( currentStep, navigate );
			if ( false !== navigateReturn ) {
				return navigateReturn;
			}

			return navigate( 'checkForPlugins' );
		};

		const goNext = () => {
			switch ( currentStep ) {
				// TODO - Do we need anything here?
				default:
					return navigate( 'checkForPlugins' );
			}
		};

		const goToStep = ( step: string ) => {
			navigate( step );
		};

		return { goNext, goBack, goToStep, submit, exitFlow };
	},

	useAssertConditions(): AssertConditionResult {
		const siteSlug = useSiteSlugParam();
		const siteId = useSiteIdParam();
		const userIsLoggedIn = useSelect(
			( select ) => ( select( USER_STORE ) as UserSelect ).isCurrentUserLoggedIn(),
			[]
		);
		const fetchingSiteError = useSelect(
			( select ) => ( select( SITE_STORE ) as SiteSelect ).getFetchingSiteError(),
			[]
		);
		let result: AssertConditionResult = { state: AssertConditionState.SUCCESS };

		if ( ! userIsLoggedIn ) {
			redirect( '/start' );
			result = {
				state: AssertConditionState.FAILURE,
				message: 'site-setup requires a logged in user',
			};
		}

		if ( ! siteSlug && ! siteId ) {
			redirect( '/' );
			result = {
				state: AssertConditionState.FAILURE,
				message: 'site-setup did not provide the site slug or site id it is configured to.',
			};
		}

		if ( fetchingSiteError ) {
			redirect( '/' );
			result = {
				state: AssertConditionState.FAILURE,
				message: fetchingSiteError.message,
			};
		}

		const { canManageOptions, isLoading } = useCanUserManageOptions();
		if ( isLoading ) {
			result = {
				state: AssertConditionState.CHECKING,
			};
		} else if ( canManageOptions === false ) {
			redirect( '/start' );
			result = {
				state: AssertConditionState.FAILURE,
				message:
					'site-setup the user needs to have the manage_options capability to go through the flow.',
			};
		}

		return result;
	},
};

export default pluginBundleFlow;