@pgy-eu/react-native-tour-guide 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +993 -2
  3. package/lib/commonjs/SpotlightOverlay.js +712 -0
  4. package/lib/commonjs/SpotlightOverlay.js.map +1 -0
  5. package/lib/commonjs/Tooltip.js +593 -0
  6. package/lib/commonjs/Tooltip.js.map +1 -0
  7. package/lib/commonjs/TourGuideContext.js +535 -0
  8. package/lib/commonjs/TourGuideContext.js.map +1 -0
  9. package/lib/commonjs/TourGuideOverlay.js +1173 -0
  10. package/lib/commonjs/TourGuideOverlay.js.map +1 -0
  11. package/lib/commonjs/TourTarget.js +80 -0
  12. package/lib/commonjs/TourTarget.js.map +1 -0
  13. package/lib/commonjs/accessibility.js +49 -0
  14. package/lib/commonjs/accessibility.js.map +1 -0
  15. package/lib/commonjs/dev.js +48 -0
  16. package/lib/commonjs/dev.js.map +1 -0
  17. package/lib/commonjs/events.js +56 -0
  18. package/lib/commonjs/events.js.map +1 -0
  19. package/lib/commonjs/index.js +169 -0
  20. package/lib/commonjs/index.js.map +1 -0
  21. package/lib/commonjs/package.json +1 -0
  22. package/lib/commonjs/shapes.js +158 -0
  23. package/lib/commonjs/shapes.js.map +1 -0
  24. package/lib/commonjs/storage.js +116 -0
  25. package/lib/commonjs/storage.js.map +1 -0
  26. package/lib/commonjs/themes.js +86 -0
  27. package/lib/commonjs/themes.js.map +1 -0
  28. package/lib/commonjs/types.js +6 -0
  29. package/lib/commonjs/types.js.map +1 -0
  30. package/lib/commonjs/useTourPersistence.js +135 -0
  31. package/lib/commonjs/useTourPersistence.js.map +1 -0
  32. package/lib/commonjs/useTourScroll.js +46 -0
  33. package/lib/commonjs/useTourScroll.js.map +1 -0
  34. package/lib/commonjs/utils.js +372 -0
  35. package/lib/commonjs/utils.js.map +1 -0
  36. package/lib/commonjs/validation.js +143 -0
  37. package/lib/commonjs/validation.js.map +1 -0
  38. package/lib/module/SpotlightOverlay.js +707 -0
  39. package/lib/module/SpotlightOverlay.js.map +1 -0
  40. package/lib/module/Tooltip.js +588 -0
  41. package/lib/module/Tooltip.js.map +1 -0
  42. package/lib/module/TourGuideContext.js +529 -0
  43. package/lib/module/TourGuideContext.js.map +1 -0
  44. package/lib/module/TourGuideOverlay.js +1167 -0
  45. package/lib/module/TourGuideOverlay.js.map +1 -0
  46. package/lib/module/TourTarget.js +74 -0
  47. package/lib/module/TourTarget.js.map +1 -0
  48. package/lib/module/accessibility.js +43 -0
  49. package/lib/module/accessibility.js.map +1 -0
  50. package/lib/module/dev.js +40 -0
  51. package/lib/module/dev.js.map +1 -0
  52. package/lib/module/events.js +51 -0
  53. package/lib/module/events.js.map +1 -0
  54. package/lib/module/index.js +25 -0
  55. package/lib/module/index.js.map +1 -0
  56. package/lib/module/package.json +1 -0
  57. package/lib/module/shapes.js +152 -0
  58. package/lib/module/shapes.js.map +1 -0
  59. package/lib/module/storage.js +111 -0
  60. package/lib/module/storage.js.map +1 -0
  61. package/lib/module/themes.js +81 -0
  62. package/lib/module/themes.js.map +1 -0
  63. package/lib/module/types.js +4 -0
  64. package/lib/module/types.js.map +1 -0
  65. package/lib/module/useTourPersistence.js +130 -0
  66. package/lib/module/useTourPersistence.js.map +1 -0
  67. package/lib/module/useTourScroll.js +41 -0
  68. package/lib/module/useTourScroll.js.map +1 -0
  69. package/lib/module/utils.js +361 -0
  70. package/lib/module/utils.js.map +1 -0
  71. package/lib/module/validation.js +138 -0
  72. package/lib/module/validation.js.map +1 -0
  73. package/lib/typescript/commonjs/package.json +1 -0
  74. package/lib/typescript/commonjs/src/SpotlightOverlay.d.ts +46 -0
  75. package/lib/typescript/commonjs/src/SpotlightOverlay.d.ts.map +1 -0
  76. package/lib/typescript/commonjs/src/Tooltip.d.ts +9 -0
  77. package/lib/typescript/commonjs/src/Tooltip.d.ts.map +1 -0
  78. package/lib/typescript/commonjs/src/TourGuideContext.d.ts +46 -0
  79. package/lib/typescript/commonjs/src/TourGuideContext.d.ts.map +1 -0
  80. package/lib/typescript/commonjs/src/TourGuideOverlay.d.ts +22 -0
  81. package/lib/typescript/commonjs/src/TourGuideOverlay.d.ts.map +1 -0
  82. package/lib/typescript/commonjs/src/TourTarget.d.ts +36 -0
  83. package/lib/typescript/commonjs/src/TourTarget.d.ts.map +1 -0
  84. package/lib/typescript/commonjs/src/accessibility.d.ts +22 -0
  85. package/lib/typescript/commonjs/src/accessibility.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/src/dev.d.ts +22 -0
  87. package/lib/typescript/commonjs/src/dev.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/src/events.d.ts +57 -0
  89. package/lib/typescript/commonjs/src/events.d.ts.map +1 -0
  90. package/lib/typescript/commonjs/src/index.d.ts +21 -0
  91. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/src/shapes.d.ts +50 -0
  93. package/lib/typescript/commonjs/src/shapes.d.ts.map +1 -0
  94. package/lib/typescript/commonjs/src/storage.d.ts +15 -0
  95. package/lib/typescript/commonjs/src/storage.d.ts.map +1 -0
  96. package/lib/typescript/commonjs/src/themes.d.ts +10 -0
  97. package/lib/typescript/commonjs/src/themes.d.ts.map +1 -0
  98. package/lib/typescript/commonjs/src/types.d.ts +599 -0
  99. package/lib/typescript/commonjs/src/types.d.ts.map +1 -0
  100. package/lib/typescript/commonjs/src/useTourPersistence.d.ts +63 -0
  101. package/lib/typescript/commonjs/src/useTourPersistence.d.ts.map +1 -0
  102. package/lib/typescript/commonjs/src/useTourScroll.d.ts +36 -0
  103. package/lib/typescript/commonjs/src/useTourScroll.d.ts.map +1 -0
  104. package/lib/typescript/commonjs/src/utils.d.ts +97 -0
  105. package/lib/typescript/commonjs/src/utils.d.ts.map +1 -0
  106. package/lib/typescript/commonjs/src/validation.d.ts +11 -0
  107. package/lib/typescript/commonjs/src/validation.d.ts.map +1 -0
  108. package/lib/typescript/module/package.json +1 -0
  109. package/lib/typescript/module/src/SpotlightOverlay.d.ts +46 -0
  110. package/lib/typescript/module/src/SpotlightOverlay.d.ts.map +1 -0
  111. package/lib/typescript/module/src/Tooltip.d.ts +9 -0
  112. package/lib/typescript/module/src/Tooltip.d.ts.map +1 -0
  113. package/lib/typescript/module/src/TourGuideContext.d.ts +46 -0
  114. package/lib/typescript/module/src/TourGuideContext.d.ts.map +1 -0
  115. package/lib/typescript/module/src/TourGuideOverlay.d.ts +22 -0
  116. package/lib/typescript/module/src/TourGuideOverlay.d.ts.map +1 -0
  117. package/lib/typescript/module/src/TourTarget.d.ts +36 -0
  118. package/lib/typescript/module/src/TourTarget.d.ts.map +1 -0
  119. package/lib/typescript/module/src/accessibility.d.ts +22 -0
  120. package/lib/typescript/module/src/accessibility.d.ts.map +1 -0
  121. package/lib/typescript/module/src/dev.d.ts +22 -0
  122. package/lib/typescript/module/src/dev.d.ts.map +1 -0
  123. package/lib/typescript/module/src/events.d.ts +57 -0
  124. package/lib/typescript/module/src/events.d.ts.map +1 -0
  125. package/lib/typescript/module/src/index.d.ts +21 -0
  126. package/lib/typescript/module/src/index.d.ts.map +1 -0
  127. package/lib/typescript/module/src/shapes.d.ts +50 -0
  128. package/lib/typescript/module/src/shapes.d.ts.map +1 -0
  129. package/lib/typescript/module/src/storage.d.ts +15 -0
  130. package/lib/typescript/module/src/storage.d.ts.map +1 -0
  131. package/lib/typescript/module/src/themes.d.ts +10 -0
  132. package/lib/typescript/module/src/themes.d.ts.map +1 -0
  133. package/lib/typescript/module/src/types.d.ts +599 -0
  134. package/lib/typescript/module/src/types.d.ts.map +1 -0
  135. package/lib/typescript/module/src/useTourPersistence.d.ts +63 -0
  136. package/lib/typescript/module/src/useTourPersistence.d.ts.map +1 -0
  137. package/lib/typescript/module/src/useTourScroll.d.ts +36 -0
  138. package/lib/typescript/module/src/useTourScroll.d.ts.map +1 -0
  139. package/lib/typescript/module/src/utils.d.ts +97 -0
  140. package/lib/typescript/module/src/utils.d.ts.map +1 -0
  141. package/lib/typescript/module/src/validation.d.ts +11 -0
  142. package/lib/typescript/module/src/validation.d.ts.map +1 -0
  143. package/llms.txt +62 -0
  144. package/package.json +281 -4
  145. package/src/SpotlightOverlay.tsx +742 -0
  146. package/src/Tooltip.tsx +638 -0
  147. package/src/TourGuideContext.tsx +644 -0
  148. package/src/TourGuideOverlay.tsx +1382 -0
  149. package/src/TourTarget.tsx +74 -0
  150. package/src/accessibility.ts +60 -0
  151. package/src/dev.ts +39 -0
  152. package/src/events.ts +76 -0
  153. package/src/index.tsx +64 -0
  154. package/src/shapes.ts +184 -0
  155. package/src/storage.ts +114 -0
  156. package/src/themes.ts +83 -0
  157. package/src/types.ts +648 -0
  158. package/src/useTourPersistence.ts +147 -0
  159. package/src/useTourScroll.ts +60 -0
  160. package/src/utils.ts +401 -0
  161. package/src/validation.ts +248 -0
@@ -0,0 +1,644 @@
1
+ import React, {
2
+ createContext,
3
+ useContext,
4
+ useState,
5
+ useCallback,
6
+ useEffect,
7
+ useMemo,
8
+ useRef,
9
+ type ReactNode,
10
+ } from 'react';
11
+ import type { StyleProp, ViewStyle } from 'react-native';
12
+
13
+ import type {
14
+ MeasurableRef,
15
+ RegisteredTarget,
16
+ ResolvedTourGuideConfig,
17
+ SpotlightTarget,
18
+ TourGuideConfig,
19
+ TourGuideContextValue,
20
+ TourStep,
21
+ } from './types';
22
+ import { resolvePlatformConfig } from './utils';
23
+ import { createTourEvents } from './events';
24
+ import { isDev, warn, warnOnce } from './dev';
25
+ import { validateTour } from './validation';
26
+
27
+ // How long to wait after startTour() before concluding that no overlay is
28
+ // mounted. Generous enough to cover a lazily-rendered or navigation-mounted
29
+ // overlay, short enough to surface the problem while the developer is looking.
30
+ const MISSING_OVERLAY_CHECK_MS = 1000;
31
+
32
+ const TourGuideContext = createContext<TourGuideContextValue | undefined>(undefined);
33
+
34
+ export interface TourGuideProviderProps {
35
+ children: ReactNode;
36
+ }
37
+
38
+ /**
39
+ * Provider component that wraps your app to enable tour guide functionality.
40
+ * Place this at the root of your app, typically in App.tsx.
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * import { TourGuideProvider, TourGuideOverlay } from '@wrack/react-native-tour-guide';
45
+ *
46
+ * export default function App() {
47
+ * return (
48
+ * <TourGuideProvider>
49
+ * <YourApp />
50
+ * <TourGuideOverlay />
51
+ * </TourGuideProvider>
52
+ * );
53
+ * }
54
+ * ```
55
+ */
56
+ export const TourGuideProvider: React.FC<TourGuideProviderProps> = ({ children }) => {
57
+ const [isActive, setIsActive] = useState(false);
58
+ const [isPaused, setIsPaused] = useState(false);
59
+ const [currentStep, setCurrentStep] = useState(0);
60
+ const [steps, setSteps] = useState<TourStep[]>([]);
61
+ const [activeSteps, setActiveSteps] = useState<TourStep[]>([]);
62
+ const [config, setConfig] = useState<ResolvedTourGuideConfig | undefined>(undefined);
63
+ const [targetLayout, setTargetLayout] = useState<SpotlightTarget | null>(null);
64
+ const [activeTourId, setActiveTourId] = useState<string | undefined>(undefined);
65
+
66
+ // Lock to prevent double-taps during async beforeStepChange
67
+ const isTransitioning = useRef(false);
68
+ // Refs for stable access in callbacks without nested setState
69
+ const configRef = useRef<ResolvedTourGuideConfig | undefined>(undefined);
70
+ const activeStepsRef = useRef<TourStep[]>([]);
71
+ const currentStepRef = useRef(0);
72
+
73
+ // Number of mounted <TourGuideOverlay /> instances, used to diagnose the two
74
+ // most common integration mistakes: no overlay at all (tour silently does
75
+ // nothing) and more than one (two stacked modals).
76
+ const overlayCount = useRef(0);
77
+ const missingOverlayTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
78
+ const isActiveRef = useRef(false);
79
+
80
+ // Keep refs in sync with state
81
+ activeStepsRef.current = activeSteps;
82
+ currentStepRef.current = currentStep;
83
+ isActiveRef.current = isActive;
84
+
85
+ const clearMissingOverlayCheck = useCallback(() => {
86
+ if (missingOverlayTimer.current) {
87
+ clearTimeout(missingOverlayTimer.current);
88
+ missingOverlayTimer.current = null;
89
+ }
90
+ }, []);
91
+
92
+ useEffect(() => clearMissingOverlayCheck, [clearMissingOverlayCheck]);
93
+
94
+ // <TourTarget> registry. A ref, not state: registration must never re-render
95
+ // the app, and lookups happen inside measurement callbacks.
96
+ const targetsRef = useRef<Map<string, RegisteredTarget>>(new Map());
97
+
98
+ const registerTarget = useCallback(
99
+ (id: string, ref: MeasurableRef, style?: StyleProp<ViewStyle>) => {
100
+ if (targetsRef.current.has(id)) {
101
+ warnOnce(
102
+ `Two <TourTarget> components share the id "${id}" — the later one wins.`,
103
+ 'Give every TourTarget a unique id.'
104
+ );
105
+ }
106
+ targetsRef.current.set(id, { ref, style });
107
+ },
108
+ []
109
+ );
110
+
111
+ const unregisterTarget = useCallback((id: string, ref?: MeasurableRef) => {
112
+ // Only remove the entry if it belongs to the caller. Duplicate ids are
113
+ // tolerated ("the later one wins"), but an unmounting loser must not
114
+ // clobber the still-mounted winner's registration — e.g. a stack-navigator
115
+ // screen popping while the previous screen keeps the same TourTarget id.
116
+ if (ref && targetsRef.current.get(id)?.ref !== ref) return;
117
+ targetsRef.current.delete(id);
118
+ }, []);
119
+
120
+ const getTarget = useCallback(
121
+ (id: string): RegisteredTarget | undefined => targetsRef.current.get(id),
122
+ []
123
+ );
124
+
125
+ // Lifecycle event emitter — stable for the provider's lifetime. Lazily
126
+ // initialised so the factory doesn't run on every render just to be thrown
127
+ // away by useRef.
128
+ const eventsRef = useRef<ReturnType<typeof createTourEvents> | null>(null);
129
+ if (eventsRef.current === null) {
130
+ eventsRef.current = createTourEvents();
131
+ }
132
+ const events = eventsRef.current;
133
+
134
+ // Guarantees every emitted 'start' is paired with exactly one 'end', no
135
+ // matter which exit path runs (finish, skip, programmatic endTour, or a
136
+ // startTour that replaces a live tour). True when no tour is active or the
137
+ // active tour's 'end' has already been emitted.
138
+ const endEmitted = useRef(true);
139
+
140
+ // Scroll plumbing for useTourScroll: consumers report offsets/momentum-end
141
+ // through the hook; the overlay subscribes for followTarget tracking and the
142
+ // exact settle signal. Refs, not state — scroll must never re-render the app.
143
+ const scrollListeners = useRef(new Set<(y: number) => void>());
144
+ const scrollEndListeners = useRef(new Set<() => void>());
145
+ const trackedScrollY = useRef<number | undefined>(undefined);
146
+
147
+ const __reportScroll = useCallback((y: number) => {
148
+ trackedScrollY.current = y;
149
+ for (const cb of scrollListeners.current) cb(y);
150
+ }, []);
151
+
152
+ const __reportScrollEnd = useCallback(() => {
153
+ for (const cb of scrollEndListeners.current) cb();
154
+ }, []);
155
+
156
+ const __subscribeScroll = useCallback((cb: (y: number) => void) => {
157
+ scrollListeners.current.add(cb);
158
+ return () => {
159
+ scrollListeners.current.delete(cb);
160
+ };
161
+ }, []);
162
+
163
+ const __subscribeScrollEnd = useCallback((cb: () => void) => {
164
+ scrollEndListeners.current.add(cb);
165
+ return () => {
166
+ scrollEndListeners.current.delete(cb);
167
+ };
168
+ }, []);
169
+
170
+ const __getTrackedScrollY = useCallback(() => trackedScrollY.current, []);
171
+
172
+ // Tours registered up front via defineTour, startable by id from anywhere.
173
+ const definedToursRef = useRef<Map<string, { steps: TourStep[]; config?: TourGuideConfig }>>(
174
+ new Map()
175
+ );
176
+
177
+ const defineTour = useCallback(
178
+ (tourId: string, tourSteps: TourStep[], tourConfig?: TourGuideConfig) => {
179
+ if (!tourId || !Array.isArray(tourSteps)) {
180
+ warn(
181
+ 'defineTour(tourId, steps, config?) needs a non-empty id and a steps array.',
182
+ "Example: defineTour('onboarding', steps, { showProgressDots: true })."
183
+ );
184
+ return;
185
+ }
186
+ definedToursRef.current.set(tourId, { steps: tourSteps, config: tourConfig });
187
+ },
188
+ []
189
+ );
190
+
191
+ const removeTour = useCallback((tourId: string) => {
192
+ definedToursRef.current.delete(tourId);
193
+ }, []);
194
+
195
+ const canStartTour = useCallback((tourOrSteps: string | TourStep[]): boolean => {
196
+ const tourSteps =
197
+ typeof tourOrSteps === 'string'
198
+ ? definedToursRef.current.get(tourOrSteps)?.steps
199
+ : tourOrSteps;
200
+ if (!tourSteps || tourSteps.length === 0) return false;
201
+ return tourSteps.every(
202
+ (st) =>
203
+ !st.targetId || // steps without targetId are always ready
204
+ Boolean(st.targetRef) ||
205
+ Boolean(st.targetRegion) ||
206
+ targetsRef.current.has(st.targetId)
207
+ );
208
+ }, []);
209
+
210
+ /**
211
+ * Flip a step's `completed` gate. Updates both the full and active step
212
+ * lists so the tooltip's Next button reflects it immediately.
213
+ */
214
+ const setStepCompleted = useCallback((stepId: string, completed: boolean) => {
215
+ const apply = (list: TourStep[]) => {
216
+ const i = list.findIndex((st) => st.id === stepId);
217
+ if (i < 0) return list;
218
+ const next = list.slice();
219
+ next[i] = { ...(next[i] as TourStep), completed };
220
+ return next;
221
+ };
222
+ setSteps(apply);
223
+ setActiveSteps((prev) => {
224
+ const next = apply(prev);
225
+ activeStepsRef.current = next;
226
+ return next;
227
+ });
228
+ }, []);
229
+
230
+ /**
231
+ * Called by <TourGuideOverlay /> on mount. Returns its unmount cleanup.
232
+ * @internal
233
+ */
234
+ const registerOverlay = useCallback(() => {
235
+ overlayCount.current += 1;
236
+ if (overlayCount.current > 1) {
237
+ warnOnce(
238
+ `${overlayCount.current} <TourGuideOverlay /> components are mounted at once, which stacks multiple modals on top of each other.`,
239
+ 'Render exactly one <TourGuideOverlay /> for the whole app, just inside <TourGuideProvider>.'
240
+ );
241
+ }
242
+ return () => {
243
+ overlayCount.current = Math.max(0, overlayCount.current - 1);
244
+ };
245
+ }, []);
246
+
247
+ const startTour = useCallback(
248
+ (stepsOrId: TourStep[] | string, configOverride?: TourGuideConfig) => {
249
+ // String form: start a tour registered with defineTour, with the passed
250
+ // config overriding the stored one field-by-field.
251
+ let tourSteps: TourStep[];
252
+ let rawConfig: TourGuideConfig | undefined;
253
+ if (typeof stepsOrId === 'string') {
254
+ const defined = definedToursRef.current.get(stepsOrId);
255
+ if (!defined) {
256
+ warn(
257
+ `startTour("${stepsOrId}") was called but no tour with that id was registered.`,
258
+ `Call defineTour('${stepsOrId}', steps, config) first, or pass a steps array directly.`
259
+ );
260
+ return;
261
+ }
262
+ tourSteps = defined.steps;
263
+ rawConfig = configOverride ? { ...defined.config, ...configOverride } : defined.config;
264
+ } else {
265
+ tourSteps = stepsOrId;
266
+ rawConfig = configOverride;
267
+ }
268
+
269
+ // Per-platform values ({ ios, android, web, default }) resolve here, so
270
+ // everything downstream reads plain values.
271
+ const tourConfig = resolvePlatformConfig(rawConfig);
272
+
273
+ // Dev-only: surface malformed steps/config before they fail silently.
274
+ validateTour(tourSteps, tourConfig);
275
+
276
+ if (!Array.isArray(tourSteps)) return;
277
+
278
+ if (isActiveRef.current) {
279
+ warn(
280
+ 'startTour() was called while a tour was already running. The previous tour is replaced without firing its onTourEnd.',
281
+ "Call endTour() or skipTour() first if you need the previous tour's onTourEnd to run."
282
+ );
283
+ // The events API still guarantees start/end pairing even on this path.
284
+ if (!endEmitted.current) {
285
+ events.emit('end', { completed: false, tourId: configRef.current?.tourId });
286
+ endEmitted.current = true;
287
+ }
288
+ }
289
+
290
+ const filtered = tourSteps.filter((s) => s && s.active !== false);
291
+
292
+ if (filtered.length === 0) {
293
+ warn(
294
+ 'No active steps to show, so the tour was not started.',
295
+ 'Check that at least one step does not have active: false.'
296
+ );
297
+ return;
298
+ }
299
+
300
+ // Release the transition lock: a previous tour may have been torn down
301
+ // mid-transition (e.g. an unresolved beforeStepChange promise), which would
302
+ // otherwise leave next/prev permanently dead for this new tour.
303
+ isTransitioning.current = false;
304
+
305
+ setSteps(tourSteps);
306
+ setActiveSteps(filtered);
307
+ activeStepsRef.current = filtered;
308
+ setConfig(tourConfig);
309
+ configRef.current = tourConfig;
310
+ setActiveTourId(tourConfig?.tourId);
311
+ setCurrentStep(0);
312
+ currentStepRef.current = 0;
313
+ setIsPaused(false);
314
+ setIsActive(true);
315
+ isActiveRef.current = true;
316
+ tourConfig?.onTourStart?.();
317
+ endEmitted.current = false;
318
+ events.emit('start', { tourId: tourConfig?.tourId, totalSteps: filtered.length });
319
+
320
+ // Dev-only: a tour with no overlay mounted renders nothing at all, with no
321
+ // error to explain why. Check shortly after start, once mounting settles.
322
+ if (isDev()) {
323
+ clearMissingOverlayCheck();
324
+ missingOverlayTimer.current = setTimeout(() => {
325
+ missingOverlayTimer.current = null;
326
+ if (overlayCount.current === 0 && isActiveRef.current) {
327
+ warnOnce(
328
+ 'startTour() was called but no <TourGuideOverlay /> is mounted, so the tour is running invisibly.',
329
+ 'Render <TourGuideOverlay /> once inside <TourGuideProvider>, after your app content.'
330
+ );
331
+ }
332
+ }, MISSING_OVERLAY_CHECK_MS);
333
+ }
334
+ },
335
+ [clearMissingOverlayCheck]
336
+ );
337
+
338
+ const endTour = useCallback(() => {
339
+ // endTour() is a public exit path: if the finish/skip flows haven't already
340
+ // emitted this tour's 'end', do it here so start/end always pair up —
341
+ // otherwise a custom close button or logout effect leaves analytics with
342
+ // an open-ended tour.
343
+ if (isActiveRef.current && !endEmitted.current) {
344
+ events.emit('end', { completed: false, tourId: configRef.current?.tourId });
345
+ }
346
+ endEmitted.current = true;
347
+ clearMissingOverlayCheck();
348
+ setIsActive(false);
349
+ isActiveRef.current = false;
350
+ setIsPaused(false);
351
+ setCurrentStep(0);
352
+ currentStepRef.current = 0;
353
+ setSteps([]);
354
+ setActiveSteps([]);
355
+ activeStepsRef.current = [];
356
+ setConfig(undefined);
357
+ configRef.current = undefined;
358
+ setActiveTourId(undefined);
359
+ setTargetLayout(null);
360
+ isTransitioning.current = false;
361
+ }, [clearMissingOverlayCheck, events]);
362
+
363
+ const pauseTour = useCallback(() => {
364
+ if (isActive && !isPaused) {
365
+ setIsPaused(true);
366
+ events.emit('pause', { at: currentStepRef.current });
367
+ }
368
+ }, [isActive, isPaused, events]);
369
+
370
+ const resumeTour = useCallback(() => {
371
+ if (isActive && isPaused) {
372
+ setIsPaused(false);
373
+ setTargetLayout(null); // Force re-measurement
374
+ events.emit('resume', { at: currentStepRef.current });
375
+ }
376
+ }, [isActive, isPaused, events]);
377
+
378
+ /**
379
+ * Run a beforeStepChange guard with the transition lock held, releasing the
380
+ * lock on EVERY outcome — allow, block, reject, or a synchronous throw. A
381
+ * throwing guard used to leave the lock permanently engaged, killing
382
+ * next/prev/goToStep for the rest of the session.
383
+ */
384
+ const runGuard = useCallback(
385
+ (
386
+ guard: NonNullable<TourGuideConfig['beforeStepChange']>,
387
+ from: number,
388
+ to: number,
389
+ proceed: () => void
390
+ ) => {
391
+ isTransitioning.current = true;
392
+ let result: boolean | Promise<boolean>;
393
+ try {
394
+ result = guard(from, to);
395
+ } catch (error) {
396
+ isTransitioning.current = false;
397
+ warn(
398
+ `beforeStepChange(${from}, ${to}) threw: ${String(error)}. The step change was blocked.`,
399
+ 'Note that on the final step `to` equals the number of steps (one past the end) — guard against out-of-range indexing.'
400
+ );
401
+ return;
402
+ }
403
+ if (result instanceof Promise) {
404
+ result
405
+ .then((allowed) => {
406
+ if (allowed) {
407
+ proceed();
408
+ } else {
409
+ isTransitioning.current = false;
410
+ }
411
+ })
412
+ .catch((error) => {
413
+ isTransitioning.current = false;
414
+ warn(
415
+ `beforeStepChange(${from}, ${to}) rejected: ${String(error)}. The step change was blocked.`
416
+ );
417
+ });
418
+ } else if (result) {
419
+ proceed();
420
+ } else {
421
+ isTransitioning.current = false;
422
+ }
423
+ },
424
+ []
425
+ );
426
+
427
+ const nextStep = useCallback(() => {
428
+ if (isTransitioning.current) return;
429
+
430
+ const prev = currentStepRef.current;
431
+ const currentActiveSteps = activeStepsRef.current;
432
+ const currentConfig = configRef.current;
433
+ const step = currentActiveSteps[prev];
434
+ const isLastStep = prev >= currentActiveSteps.length - 1;
435
+
436
+ const doTransition = () => {
437
+ if (isLastStep) {
438
+ step?.onNext?.();
439
+ currentConfig?.onTourEnd?.(true);
440
+ events.emit('end', { completed: true, tourId: currentConfig?.tourId });
441
+ endEmitted.current = true;
442
+ endTour();
443
+ } else {
444
+ step?.onNext?.();
445
+ currentConfig?.onStepChange?.(prev, prev + 1);
446
+ events.emit('stepChange', {
447
+ from: prev,
448
+ to: prev + 1,
449
+ step: currentActiveSteps[prev + 1],
450
+ });
451
+ currentStepRef.current = prev + 1;
452
+ setCurrentStep(prev + 1);
453
+ setTargetLayout(null);
454
+ }
455
+ isTransitioning.current = false;
456
+ };
457
+
458
+ if (currentConfig?.beforeStepChange) {
459
+ // On the last step the tour finishes, so the "to" index is one past the
460
+ // end (prev + 1 === totalSteps). Reporting `prev` here instead would make
461
+ // a guard like `(from, to) => to > from` silently block the Done button.
462
+ runGuard(currentConfig.beforeStepChange, prev, prev + 1, doTransition);
463
+ } else {
464
+ doTransition();
465
+ }
466
+ }, [endTour, runGuard]);
467
+
468
+ const prevStep = useCallback(() => {
469
+ if (isTransitioning.current) return;
470
+
471
+ const prev = currentStepRef.current;
472
+ if (prev <= 0) return;
473
+
474
+ const currentActiveSteps = activeStepsRef.current;
475
+ const currentConfig = configRef.current;
476
+ const step = currentActiveSteps[prev];
477
+
478
+ const doTransition = () => {
479
+ step?.onPrev?.();
480
+ currentConfig?.onStepChange?.(prev, prev - 1);
481
+ events.emit('stepChange', {
482
+ from: prev,
483
+ to: prev - 1,
484
+ step: currentActiveSteps[prev - 1],
485
+ });
486
+ currentStepRef.current = prev - 1;
487
+ setCurrentStep(prev - 1);
488
+ setTargetLayout(null);
489
+ isTransitioning.current = false;
490
+ };
491
+
492
+ if (currentConfig?.beforeStepChange) {
493
+ runGuard(currentConfig.beforeStepChange, prev, prev - 1, doTransition);
494
+ } else {
495
+ doTransition();
496
+ }
497
+ }, [runGuard]);
498
+
499
+ const skipTour = useCallback(() => {
500
+ const step = activeStepsRef.current[currentStepRef.current];
501
+ step?.onSkip?.();
502
+ configRef.current?.onTourEnd?.(false);
503
+ events.emit('skip', { at: currentStepRef.current });
504
+ events.emit('end', { completed: false, tourId: configRef.current?.tourId });
505
+ endEmitted.current = true;
506
+ endTour();
507
+ }, [endTour, events]);
508
+
509
+ const goToStep = useCallback(
510
+ (index: number) => {
511
+ if (isTransitioning.current) return;
512
+
513
+ const len = activeStepsRef.current.length;
514
+ if (!Number.isInteger(index) || index < 0 || index >= len) {
515
+ warn(
516
+ `goToStep(${index}) is out of bounds — there ${len === 1 ? 'is' : 'are'} ${len} active step${len === 1 ? '' : 's'} (valid range 0-${Math.max(0, len - 1)}).`,
517
+ 'Pass an index within the active steps; note that steps with active: false are excluded from the index.'
518
+ );
519
+ return;
520
+ }
521
+
522
+ const from = currentStepRef.current;
523
+ if (from === index) return;
524
+
525
+ // goToStep is a step change like any other: it fires onStepChange AND
526
+ // respects the beforeStepChange guard — a custom progress-dots tooltip
527
+ // jumping by index must not bypass a gate that Next/Back honour.
528
+ const doTransition = () => {
529
+ configRef.current?.onStepChange?.(from, index);
530
+ events.emit('stepChange', { from, to: index, step: activeStepsRef.current[index] });
531
+ currentStepRef.current = index;
532
+ setCurrentStep(index);
533
+ setTargetLayout(null);
534
+ isTransitioning.current = false;
535
+ };
536
+
537
+ const guard = configRef.current?.beforeStepChange;
538
+ if (guard) {
539
+ runGuard(guard, from, index, doTransition);
540
+ } else {
541
+ doTransition();
542
+ }
543
+ },
544
+ [runGuard]
545
+ );
546
+
547
+ const value = useMemo<TourGuideContextValue>(
548
+ () => ({
549
+ currentStep,
550
+ isActive,
551
+ isPaused,
552
+ activeTourId,
553
+ steps,
554
+ activeSteps,
555
+ config,
556
+ startTour,
557
+ defineTour,
558
+ removeTour,
559
+ canStartTour,
560
+ nextStep,
561
+ prevStep,
562
+ skipTour,
563
+ endTour,
564
+ goToStep,
565
+ pauseTour,
566
+ resumeTour,
567
+ setStepCompleted,
568
+ registerTarget,
569
+ unregisterTarget,
570
+ getTarget,
571
+ setTargetLayout,
572
+ targetLayout,
573
+ events,
574
+ __reportScroll,
575
+ __reportScrollEnd,
576
+ __subscribeScroll,
577
+ __subscribeScrollEnd,
578
+ __getTrackedScrollY,
579
+ __registerOverlay: registerOverlay,
580
+ }),
581
+ [
582
+ currentStep,
583
+ isActive,
584
+ isPaused,
585
+ activeTourId,
586
+ steps,
587
+ activeSteps,
588
+ config,
589
+ startTour,
590
+ nextStep,
591
+ prevStep,
592
+ skipTour,
593
+ endTour,
594
+ goToStep,
595
+ pauseTour,
596
+ resumeTour,
597
+ targetLayout,
598
+ registerOverlay,
599
+ setStepCompleted,
600
+ registerTarget,
601
+ unregisterTarget,
602
+ getTarget,
603
+ defineTour,
604
+ removeTour,
605
+ canStartTour,
606
+ events,
607
+ __reportScroll,
608
+ __reportScrollEnd,
609
+ __subscribeScroll,
610
+ __subscribeScrollEnd,
611
+ __getTrackedScrollY,
612
+ ]
613
+ );
614
+
615
+ return <TourGuideContext.Provider value={value}>{children}</TourGuideContext.Provider>;
616
+ };
617
+
618
+ /**
619
+ * Hook to access tour guide functionality.
620
+ * Must be used within a TourGuideProvider.
621
+ *
622
+ * @example
623
+ * ```tsx
624
+ * const { startTour, isActive } = useTourGuide();
625
+ *
626
+ * const handleStartTour = () => {
627
+ * startTour([
628
+ * {
629
+ * id: 'step1',
630
+ * targetRef: myButtonRef,
631
+ * title: 'Welcome!',
632
+ * description: 'This is your first step.',
633
+ * },
634
+ * ]);
635
+ * };
636
+ * ```
637
+ */
638
+ export const useTourGuide = (): TourGuideContextValue => {
639
+ const context = useContext(TourGuideContext);
640
+ if (!context) {
641
+ throw new Error('useTourGuide must be used within TourGuideProvider');
642
+ }
643
+ return context;
644
+ };