File size: 6,267 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
import page from '@automattic/calypso-router';
import { Popover, Button } from '@automattic/components';
import clsx from 'clsx';
import { useTranslate } from 'i18n-calypso';
import { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'calypso/state';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { getJetpackDashboardPreference as getPreference } from 'calypso/state/jetpack-agency-dashboard/selectors';
import { savePreference } from 'calypso/state/preferences/actions';
import { preferencesLastFetchedTimestamp } from 'calypso/state/preferences/selectors';

import './style.scss';

export interface Tour {
	target: string;
	title: string;
	description: string | JSX.Element;
	popoverPosition?:
		| 'top'
		| 'top right'
		| 'right'
		| 'bottom right'
		| 'bottom'
		| 'bottom left'
		| 'left'
		| 'top left';
	nextStepOnTargetClick?: string;
	forceShowSkipButton?: boolean;
}

interface Props {
	className?: string;
	tours: Tour[];
	preferenceName: string;
	redirectAfterTourEnds?: string;
	hideSteps?: boolean;
}

// This hook will return the async element matching the target selector.
// After timeout has passed, it will return null.
//
// @param target - The selector to match the element against
// @param timeoutDuration - The maximum duration (in milliseconds) to wait for the element
//
// @returns The element matching the target selector, or null if the timeout has passed
const useAsyncElement = ( target: string, timeoutDuration: number ): HTMLElement | null => {
	const [ asyncElement, setAsyncElement ] = useState< HTMLElement | null >( null );

	useEffect( () => {
		// Set timeout to ensure we don't wait too long for the element
		const endTime = Date.now() + timeoutDuration;

		const getAsyncElement = ( endTime: number ) => {
			const element = document.querySelector( target ) as HTMLElement | null;
			if ( element ) {
				setAsyncElement( element );
			} else if ( Date.now() < endTime ) {
				requestAnimationFrame( () => getAsyncElement( endTime ) );
			} else {
				setAsyncElement( null );
			}
		};

		getAsyncElement( endTime );
	}, [ target, timeoutDuration ] );

	return asyncElement;
};

const GuidedTour = ( {
	className,
	tours,
	preferenceName,
	redirectAfterTourEnds,
	hideSteps = false,
}: Props ) => {
	const translate = useTranslate();
	const dispatch = useDispatch();

	const [ currentStep, setCurrentStep ] = useState( 0 );
	const [ isVisible, setIsVisible ] = useState( false );

	const preference = useSelector( ( state ) => getPreference( state, preferenceName ) );
	const hasFetched = !! useSelector( preferencesLastFetchedTimestamp );

	const isDismissed = preference?.dismiss;

	const {
		title,
		description,
		target,
		popoverPosition,
		nextStepOnTargetClick,
		forceShowSkipButton = false,
	} = tours[ currentStep ];

	const targetElement = useAsyncElement( target, 3000 );

	useEffect( () => {
		if ( targetElement && ! isDismissed && hasFetched ) {
			setIsVisible( true );
			dispatch(
				recordTracksEvent( 'calypso_jetpack_cloud_start_tour', {
					tour: preferenceName,
				} )
			);
		}
	}, [ dispatch, isDismissed, preferenceName, targetElement, hasFetched ] );

	const endTour = useCallback( () => {
		dispatch( savePreference( preferenceName, { ...preference, dismiss: true } ) );
		dispatch(
			recordTracksEvent( 'calypso_jetpack_cloud_end_tour', {
				tour: preferenceName,
			} )
		);
		if ( redirectAfterTourEnds ) {
			page.redirect( redirectAfterTourEnds );
		}
	}, [ dispatch, preferenceName, preference, redirectAfterTourEnds ] );

	const nextStep = useCallback( () => {
		if ( currentStep < tours.length - 1 ) {
			setCurrentStep( currentStep + 1 );
		} else {
			endTour();
		}
	}, [ currentStep, tours.length, endTour ] );

	useEffect( () => {
		let nextStepClickTargetElement: Element | null = null;
		// We should wait for targetElement before attaching any events to advance to the next step
		if ( nextStepOnTargetClick && targetElement && ! isDismissed && hasFetched ) {
			// Find the target element using the nextStepOnTargetClick selector
			nextStepClickTargetElement = document.querySelector( nextStepOnTargetClick );
			if ( nextStepClickTargetElement ) {
				// Attach the event listener to the nextStepClickTargetElement
				nextStepClickTargetElement.addEventListener( 'click', nextStep );
			}
		}

		// Cleanup function to remove the event listener
		return () => {
			if ( nextStepClickTargetElement ) {
				nextStepClickTargetElement.removeEventListener( 'click', nextStep );
			}
		};
	}, [ nextStepOnTargetClick, nextStep, targetElement, isDismissed, hasFetched ] );

	if ( isDismissed ) {
		return null;
	}

	const lastTourLabel = tours.length === 1 ? translate( 'Got it' ) : translate( 'Done' );

	return (
		<Popover
			isVisible={ isVisible }
			className={ clsx( className, 'guided-tour__popover' ) }
			context={ targetElement }
			position={ popoverPosition }
		>
			<h2 className="guided-tour__popover-heading">{ title }</h2>
			<p className="guided-tour__popover-description">{ description }</p>
			<div className="guided-tour__popover-footer">
				<div>
					{
						// Show the step count if there are multiple steps and we're not on the last step, unless we explicitly choose to hide them
						tours.length > 1 && ! hideSteps && (
							<span className="guided-tour__popover-step-count">
								{ translate( 'Step %(currentStep)d of %(totalSteps)d', {
									args: { currentStep: currentStep + 1, totalSteps: tours.length },
								} ) }
							</span>
						)
					}
				</div>
				<div className="guided-tour__popover-footer-right-content">
					<>
						{ ( ( ! nextStepOnTargetClick && tours.length > 1 && currentStep < tours.length - 1 ) ||
							forceShowSkipButton ) && (
							// Show the skip button if there are multiple steps and we're not on the last step, unless we explicitly choose to add them
							<Button borderless onClick={ endTour }>
								{ translate( 'Skip' ) }
							</Button>
						) }
						{ ! nextStepOnTargetClick && (
							<Button onClick={ nextStep }>
								{ currentStep === tours.length - 1 ? lastTourLabel : translate( 'Next' ) }
							</Button>
						) }
					</>
				</div>
			</div>
		</Popover>
	);
};

export default GuidedTour;