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

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,1382 @@
1
+ import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
2
+ import {
3
+ Dimensions,
4
+ InteractionManager,
5
+ Modal,
6
+ Platform,
7
+ StatusBar,
8
+ StyleSheet,
9
+ View,
10
+ findNodeHandle,
11
+ } from 'react-native';
12
+
13
+ import { useTourGuide } from './TourGuideContext';
14
+ import SpotlightOverlay from './SpotlightOverlay';
15
+ import Tooltip from './Tooltip';
16
+ import {
17
+ validateRef,
18
+ computeTooltipPosition,
19
+ extractBorderRadius,
20
+ resolveInsets,
21
+ resolveSafeAreaInsets,
22
+ scrollRefToY,
23
+ isLightColor,
24
+ } from './utils';
25
+ import { computeShape, shapeInnerPath } from './shapes';
26
+ import { announceStep } from './accessibility';
27
+ import { warnOnce } from './dev';
28
+ import type { BackdropBehavior, SpotlightStyles, SpotlightTarget, TourStep } from './types';
29
+
30
+ const isWeb = Platform.OS === 'web';
31
+
32
+ const MAX_MEASURE_RETRIES = 3;
33
+ const MEASURE_RETRY_DELAY = 100;
34
+
35
+ // After a programmatic scroll, the animation finishes at an unpredictable time
36
+ // (varies by distance/device/platform; iOS animated scrolls don't fire reliable
37
+ // scroll-end events). So instead of measuring once after a fixed delay — which
38
+ // captures the target mid-flight and leaves the spotlight/tooltip behind — we
39
+ // poll until the measured position stops changing (settled) or we hit the cap.
40
+ const SETTLE_POLL_INTERVAL = 80;
41
+ const MAX_SETTLE_POLLS = 12; // ~960ms cap — covers long animated scrolls
42
+ const SETTLE_EPSILON = 0.5; // px; two readings this close count as settled
43
+
44
+ // How long a step with a targetId waits for its <TourTarget> to register
45
+ // before falling back to a centered tooltip (covers screens that mount after
46
+ // the tour starts).
47
+ const TARGET_WAIT_INTERVAL = 120;
48
+ const TARGET_WAIT_RETRIES = 10; // ~1.2s total
49
+
50
+ // Measurement watchdog: if a step has started measuring but neither produced a
51
+ // target layout nor fallen back within this window, force the centered
52
+ // fallback. Guards against measure callbacks that never fire at all (detached
53
+ // nodes, exotic hosts) — without it the user is stuck behind the backdrop with
54
+ // no tooltip. Generous on purpose: an animated auto-scroll + settle polling can
55
+ // legitimately take ~2s.
56
+ const MEASURE_WATCHDOG_MS = 4000;
57
+
58
+ /**
59
+ * Cross-platform measurement helper.
60
+ * Uses getBoundingClientRect on web, measureInWindow on native.
61
+ */
62
+ const measureElement = (
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ ref: { current: any },
65
+ callback: (x: number, y: number, width: number, height: number) => void
66
+ ): boolean => {
67
+ const node = ref?.current;
68
+ // A null ref is not measurable. Reading `.current.measureInWindow` here used
69
+ // to throw if the target unmounted between the check and the call.
70
+ if (!node) return false;
71
+
72
+ if (isWeb) {
73
+ try {
74
+ // react-native-web: findNodeHandle returns the DOM node directly
75
+ const handle = findNodeHandle(node);
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ const domNode = (handle ?? node) as any;
78
+ if (domNode && typeof domNode.getBoundingClientRect === 'function') {
79
+ const rect = domNode.getBoundingClientRect();
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ const win = globalThis as any;
82
+ callback(
83
+ rect.left + (win.scrollX ?? 0),
84
+ rect.top + (win.scrollY ?? 0),
85
+ rect.width,
86
+ rect.height
87
+ );
88
+ return true;
89
+ }
90
+ } catch {
91
+ // Fall through to the native path if available
92
+ }
93
+ }
94
+
95
+ // Native path
96
+ if (typeof node.measureInWindow === 'function') {
97
+ node.measureInWindow(callback);
98
+ return true;
99
+ }
100
+
101
+ // Some refs expose only measure() — notably class components that forward to
102
+ // a host view via a legacy API. measure() reports page coordinates in its
103
+ // 5th/6th args, which is what measureInWindow returns.
104
+ if (typeof node.measure === 'function') {
105
+ node.measure(
106
+ (_x: number, _y: number, width: number, height: number, pageX: number, pageY: number) =>
107
+ callback(pageX, pageY, width, height)
108
+ );
109
+ return true;
110
+ }
111
+
112
+ // Nothing measurable. Returning false lets callers fall back to a centered
113
+ // tooltip instead of waiting forever for a callback that never fires — which
114
+ // left the user trapped behind a backdrop with no tooltip and no way out.
115
+ return false;
116
+ };
117
+
118
+ /**
119
+ * Main overlay component that displays the tour guide.
120
+ * This should be placed at the root level of your app, after your main content.
121
+ *
122
+ * @example
123
+ * ```tsx
124
+ * import { TourGuideProvider, TourGuideOverlay } from '@wrack/react-native-tour-guide';
125
+ *
126
+ * export default function App() {
127
+ * return (
128
+ * <TourGuideProvider>
129
+ * <YourApp />
130
+ * <TourGuideOverlay />
131
+ * </TourGuideProvider>
132
+ * );
133
+ * }
134
+ * ```
135
+ */
136
+ const TourGuideOverlay: React.FC = () => {
137
+ const {
138
+ isActive,
139
+ isPaused,
140
+ currentStep,
141
+ activeSteps,
142
+ config,
143
+ targetLayout,
144
+ setTargetLayout,
145
+ nextStep,
146
+ prevStep,
147
+ skipTour,
148
+ getTarget,
149
+ __subscribeScroll,
150
+ __subscribeScrollEnd,
151
+ __getTrackedScrollY,
152
+ __registerOverlay,
153
+ } = useTourGuide();
154
+
155
+ // Let the provider know an overlay exists, so it can warn (in dev) when a tour
156
+ // is started with no overlay mounted — or with more than one.
157
+ useEffect(() => __registerOverlay?.(), [__registerOverlay]);
158
+
159
+ // Track screen dimensions for orientation changes
160
+ const [screenDimensions, setScreenDimensions] = useState<{ width: number; height: number }>(
161
+ () => {
162
+ const { width, height } = Dimensions.get('window');
163
+ return { width, height };
164
+ }
165
+ );
166
+ const currentStepData = activeSteps[currentStep];
167
+
168
+ // Resolve the step's target: an explicit targetRef wins; otherwise a
169
+ // registered <TourTarget> looked up by targetId. The proxy ref reads the
170
+ // registry live on every `.current` access, so a target that registers AFTER
171
+ // the step becomes active (late-mounting screen) is picked up by the
172
+ // measurement retry loops without any extra wiring.
173
+ const effectiveTargetRef = useMemo(() => {
174
+ if (!currentStepData) return undefined;
175
+ if (currentStepData.targetRef) return currentStepData.targetRef;
176
+ const id = currentStepData.targetId;
177
+ if (!id) return undefined;
178
+ return {
179
+ get current() {
180
+ return getTarget(id)?.ref.current ?? null;
181
+ },
182
+ };
183
+ }, [currentStepData, getTarget]);
184
+
185
+ // Shape source: the step's targetStyle wins; otherwise the registered
186
+ // TourTarget's wrapper style (so <TourTarget style={{borderRadius: 24}}>
187
+ // drives shape matching with zero step config).
188
+ const effectiveTargetStyle =
189
+ currentStepData?.targetStyle ??
190
+ (currentStepData?.targetId ? getTarget(currentStepData.targetId)?.style : undefined);
191
+
192
+ // Resolve safe-area + extra insets once per config change. Keeps tooltips on
193
+ // screen and targets clear of the status bar / nav bar / tab bars.
194
+ const insets = useMemo(
195
+ () => resolveInsets({ insets: config?.insets, extraInsets: config?.extraInsets }),
196
+ [config?.insets, config?.extraInsets]
197
+ );
198
+
199
+ // On Android, measureInWindow returns coordinates relative to the app content
200
+ // area, which sits BELOW the status bar — but the overlay Modal is
201
+ // statusBarTranslucent and spans the full screen from y=0. So we add the
202
+ // (dp-correct) status-bar height to align the spotlight with the real element.
203
+ // iOS measureInWindow already uses full-screen coordinates, so no offset.
204
+ // NB: use the safe-area top only (not extraInsets) — a tab bar doesn't shift
205
+ // measureInWindow, and using raw StatusBar.currentHeight risks px-vs-dp bugs.
206
+ // Inline mode: rather than guessing status-bar geometry (OEMs disagree on
207
+ // whether measureInWindow's origin includes the status bar, and edge-to-edge
208
+ // apps span behind it), the overlay measures ITS OWN window position and the
209
+ // correction falls out empirically: overlay-local = window - overlayOrigin.
210
+ const inlineOriginY = useRef(0);
211
+ const inlineRootRef = useRef<React.ComponentRef<typeof View>>(null);
212
+ const [inlineOriginVersion, setInlineOriginVersion] = useState(0);
213
+ const onInlineRootLayout = useCallback(() => {
214
+ const node = inlineRootRef.current as unknown as {
215
+ measureInWindow?: (cb: (x: number, y: number) => void) => void;
216
+ } | null;
217
+ node?.measureInWindow?.((_x, y) => {
218
+ if (!isMounted.current) return;
219
+ if (Math.abs(y - inlineOriginY.current) > 0.5) {
220
+ inlineOriginY.current = y;
221
+ // Force a re-measure of the current step against the new origin.
222
+ setInlineOriginVersion((v) => v + 1);
223
+ }
224
+ });
225
+ }, []);
226
+
227
+ const measureTopOffset = useMemo(() => {
228
+ if (isWeb) return 0;
229
+ if (config?.overlayMode === 'inline') {
230
+ // Same measureInWindow space on both sides — subtract the overlay's own
231
+ // origin. 0 on devices where the spaces already coincide.
232
+ return -inlineOriginY.current;
233
+ }
234
+ if (Platform.OS !== 'android') return 0;
235
+ return resolveSafeAreaInsets({ insets: config?.insets }).top;
236
+ // eslint-disable-next-line react-hooks/exhaustive-deps
237
+ }, [config?.insets, config?.overlayMode, inlineOriginVersion]);
238
+
239
+ // Refs for cleanup
240
+ const delayTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
241
+ // Retry timer for the plain (non-scroll) measurement loop — tracked so step
242
+ // changes can cancel a pending 0x0 retry instead of letting a stale closure
243
+ // fire into the next step.
244
+ const measureRetryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
245
+ const autoAdvanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
246
+ const measureRetryCount = useRef(0);
247
+
248
+ // Monotonic step token: every step change bumps this. Async measurement
249
+ // callbacks compare against it and bail if they belong to a previous step,
250
+ // preventing stale layout from one step landing on another (measurement race).
251
+ const stepEpoch = useRef(0);
252
+ // Last screen-Y seen while polling for a programmatic scroll to settle. Reset
253
+ // to null at the start of each settle loop so the first reading is never
254
+ // mistaken for "settled" against a stale value from a previous step.
255
+ const lastSettleY = useRef<number | null>(null);
256
+ // Pending settle-poll timer. Kept in a ref so a momentum-scroll-end signal
257
+ // (via useTourScroll) can preempt the polling and commit immediately.
258
+ const settleTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
259
+ // Pending InteractionManager handle (waitForInteractions), cancellable on step change.
260
+ const interactionHandle = useRef<{ cancel: () => void } | null>(null);
261
+ // Guards setState after unmount inside async measure callbacks.
262
+ const isMounted = useRef(true);
263
+ useEffect(() => {
264
+ isMounted.current = true;
265
+ return () => {
266
+ isMounted.current = false;
267
+ };
268
+ }, []);
269
+
270
+ // When a step has no measurable target (no ref, or measurement failed), we
271
+ // show a centered tooltip instead of leaving the user trapped behind a
272
+ // non-interactive backdrop with nothing to tap.
273
+ const [centeredFallback, setCenteredFallback] = useState(false);
274
+
275
+ // Follow updates are OVERLAY-LOCAL state: committing each per-scroll-frame
276
+ // measurement through the provider would re-render every useTourGuide()
277
+ // consumer at up to 60fps — the exact jank followTarget exists to avoid.
278
+ // Renders read followLayout ?? targetLayout; the provider only ever sees the
279
+ // real measurement commits.
280
+ const [followLayout, setFollowLayout] = useState<SpotlightTarget | null>(null);
281
+
282
+ // Which step's before() hook has already run. Keyed by index+id so the hook
283
+ // fires once per step VISIT: the main effect legitimately re-runs for the
284
+ // same step (setStepCompleted rebuilds the step object; rotation recreates
285
+ // callbacks), and before() must not navigate/fetch again on those re-runs.
286
+ const beforeRanKey = useRef<string | null>(null);
287
+
288
+ // A new startTour() replaces the config state (setStepCompleted does not),
289
+ // so config identity marks a tour (re)start: clear the before() bookkeeping
290
+ // so the new tour's hooks run even when step ids collide with the last run's.
291
+ useEffect(() => {
292
+ beforeRanKey.current = null;
293
+ }, [config]);
294
+
295
+ // Kept spotlights (step.keepSpotlight): index → the DATA needed to redraw
296
+ // the hole, not a frozen path string. Window coordinates go stale the moment
297
+ // the page scrolls — a frozen hole then sits over unrelated content — so
298
+ // each entry remembers the scroll offset at capture time and the hole is
299
+ // re-generated with the current offset applied.
300
+ interface KeptEntry {
301
+ layout: SpotlightTarget;
302
+ padding: NonNullable<TourStep['spotlightPadding']> | 0;
303
+ radius: ReturnType<typeof extractBorderRadius> | number;
304
+ /** Tracked scroll offset (useTourScroll) when captured, if available */
305
+ scrollYAtCapture?: number;
306
+ /** The capturing step's own maskPath, if it had one */
307
+ maskPath?: SpotlightStyles['maskPath'];
308
+ }
309
+ const keptShapes = useRef<Map<number, KeptEntry>>(new Map());
310
+ const [keptVersion, setKeptVersion] = useState(0);
311
+ // The last layout actually committed for the current step, with everything
312
+ // needed to reconstruct its cutout shape when the tour moves on.
313
+ const lastCommitted = useRef<{
314
+ index: number;
315
+ layout: SpotlightTarget;
316
+ step: TourStep;
317
+ } | null>(null);
318
+
319
+ // Mirrors for the watchdog (it runs in a timeout and must read fresh values).
320
+ const targetLayoutRef = useRef(targetLayout);
321
+ targetLayoutRef.current = targetLayout;
322
+ const centeredFallbackRef = useRef(centeredFallback);
323
+ centeredFallbackRef.current = centeredFallback;
324
+ const watchdogTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
325
+
326
+ // --- Status bar control while the tour is active ---
327
+ useEffect(() => {
328
+ const style = config?.statusBarStyle;
329
+ if (!isActive || !style) return undefined;
330
+ // react-native-web's StatusBar ships only the set* no-ops — the stack API
331
+ // does not exist there and would throw at tour start.
332
+ if (isWeb || typeof StatusBar.pushStackEntry !== 'function') return undefined;
333
+ let resolved: 'light-content' | 'dark-content' = style === 'auto' ? 'light-content' : style;
334
+ if (style === 'auto') {
335
+ // Light backdrop → dark icons; dark (or unparseable) backdrop → light.
336
+ const backdropIsLight =
337
+ isLightColor(config?.spotlightStyles?.overlayColor ?? 'black') === true;
338
+ resolved = backdropIsLight ? 'dark-content' : 'light-content';
339
+ }
340
+ // push/pop keeps whatever style the app had — no unreadable global reset.
341
+ const entry = StatusBar.pushStackEntry({ barStyle: resolved, animated: true });
342
+ return () => {
343
+ StatusBar.popStackEntry(entry);
344
+ };
345
+ }, [isActive, config?.statusBarStyle, config?.spotlightStyles?.overlayColor]);
346
+
347
+ // --- Orientation change handling ---
348
+ useEffect(() => {
349
+ const subscription = Dimensions.addEventListener(
350
+ 'change',
351
+ ({ window: win }: { window: { width: number; height: number } }) => {
352
+ setScreenDimensions(win);
353
+ // Re-measure current target after orientation change
354
+ if (isActive && effectiveTargetRef?.current) {
355
+ setTargetLayout(null);
356
+ }
357
+ }
358
+ );
359
+
360
+ return () => subscription.remove();
361
+ }, [isActive, currentStepData, effectiveTargetRef, setTargetLayout]);
362
+
363
+ // Estimated tooltip height for scroll calculations. Generous on purpose: a
364
+ // tooltip with progress dots + a long description + buttons can be ~280px, and
365
+ // under-reserving makes the tooltip overlap the target after an auto-scroll.
366
+ const ESTIMATED_TOOLTIP_HEIGHT = 260;
367
+
368
+ // --- Resolve the effective scroll ref (per-step overrides global config) ---
369
+ const getScrollRef = useCallback(() => {
370
+ return currentStepData?.scrollToTarget?.scrollRef ?? config?.scrollRef ?? null;
371
+ }, [currentStepData, config]);
372
+
373
+ const getScrollOffset = useCallback(() => {
374
+ return (
375
+ currentStepData?.scrollToTarget?.getCurrentScrollOffset?.() ??
376
+ config?.getCurrentScrollOffset?.() ??
377
+ // Offset observed through useTourScroll, when the consumer wired it.
378
+ __getTrackedScrollY?.() ??
379
+ 0
380
+ );
381
+ }, [currentStepData, config, __getTrackedScrollY]);
382
+
383
+ // A target we can never measure (a ref that never reaches a host component,
384
+ // or one pointing at something without a measure API) must not leave the user
385
+ // staring at a backdrop with no tooltip — fall back to a centered tooltip.
386
+ const fallBackToCentered = useCallback(
387
+ (stepId: string, reason: string) => {
388
+ if (!isMounted.current) return;
389
+ // Whatever loop ended here, the settle phase is over.
390
+ settleTimer.current = null;
391
+ warnOnce(
392
+ `Step "${stepId}" ${reason}, so it cannot be highlighted. Showing a centered tooltip instead.`,
393
+ 'Attach targetRef to a React Native host component (View, Text, Pressable…). Custom components must forward the ref with React.forwardRef.'
394
+ );
395
+ measureRetryCount.current = 0;
396
+ setTargetLayout(null);
397
+ setCenteredFallback(true);
398
+ },
399
+ [setTargetLayout]
400
+ );
401
+
402
+ // --- Scroll to target logic ---
403
+ // Ensures both the target AND tooltip are fully visible in the viewport.
404
+ // If they don't fit, auto-scrolls the parent ScrollView.
405
+ // --- Measure target with retry logic ---
406
+ const measureTarget = useCallback(
407
+ (epoch: number, retryCount = 0) => {
408
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
409
+ if (!currentStepData) return;
410
+ if (!effectiveTargetRef?.current) {
411
+ // No target ref — show tooltip without spotlight
412
+ setTargetLayout(null);
413
+ return;
414
+ }
415
+
416
+ const dispatched = measureElement(
417
+ effectiveTargetRef as { current: Record<string, unknown> },
418
+ (x: number, y: number, width: number, height: number) => {
419
+ // Bail if the step changed or we unmounted while measuring async.
420
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
421
+
422
+ if (width > 0 && height > 0) {
423
+ // Align with the full-screen overlay Modal (see measureTopOffset).
424
+ setTargetLayout({ x, y: y + measureTopOffset, width, height });
425
+ measureRetryCount.current = 0;
426
+ } else if (retryCount < MAX_MEASURE_RETRIES) {
427
+ // Element not laid out yet — retry (tracked, so cleanup can cancel)
428
+ measureRetryTimer.current = setTimeout(
429
+ () => measureTarget(epoch, retryCount + 1),
430
+ MEASURE_RETRY_DELAY
431
+ );
432
+ } else {
433
+ // Don't trap the user — fall back to a centered, dismissible tooltip.
434
+ fallBackToCentered(
435
+ currentStepData.id,
436
+ `measured as 0x0 after ${MAX_MEASURE_RETRIES} retries`
437
+ );
438
+ }
439
+ }
440
+ );
441
+
442
+ // The ref exposes no measurement API at all, so no callback will ever
443
+ // arrive. Fall back now rather than leaving the overlay empty forever.
444
+ if (!dispatched) {
445
+ fallBackToCentered(currentStepData.id, 'has a targetRef that cannot be measured');
446
+ }
447
+ },
448
+ [currentStepData, effectiveTargetRef, setTargetLayout, measureTopOffset, fallBackToCentered]
449
+ );
450
+
451
+ // --- Measure after a scroll, polling until the scroll settles ---
452
+ // The highlight is hidden (targetLayout=null) while the programmatic scroll
453
+ // animates. We poll the target position WITHOUT committing it until two
454
+ // consecutive readings agree (the scroll has stopped), then reveal the
455
+ // spotlight ONCE at its final position. Committing intermediate readings would
456
+ // make the cutout chase the moving target and flicker; waiting for settle also
457
+ // prevents latching onto a mid-animation position (the "left behind" bug).
458
+ const measureUntilSettled = useCallback(
459
+ (epoch: number, attempt = 0) => {
460
+ // A stale closure (older step, or fired after unmount) must do nothing —
461
+ // its unguarded setTargetLayout(null) used to wipe the CURRENT step's
462
+ // committed layout.
463
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
464
+ if (!currentStepData) return;
465
+ if (!effectiveTargetRef?.current) {
466
+ // F4: the settle loop is over for this path — clear the pending marker
467
+ // so followTarget and the scroll-end signal don't act on a dead timer.
468
+ settleTimer.current = null;
469
+ setTargetLayout(null);
470
+ return;
471
+ }
472
+
473
+ const dispatched = measureElement(
474
+ effectiveTargetRef as { current: Record<string, unknown> },
475
+ (x: number, y: number, width: number, height: number) => {
476
+ // Bail if the step changed or we unmounted while measuring async.
477
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
478
+
479
+ if (width > 0 && height > 0) {
480
+ // Align with the full-screen overlay Modal (see measureTopOffset).
481
+ const adjustedY = y + measureTopOffset;
482
+ const prev = lastSettleY.current;
483
+ lastSettleY.current = adjustedY;
484
+ const settled = prev !== null && Math.abs(adjustedY - prev) < SETTLE_EPSILON;
485
+
486
+ if (settled || attempt >= MAX_SETTLE_POLLS) {
487
+ // Scroll has come to rest — reveal the highlight at its final spot.
488
+ settleTimer.current = null;
489
+ setTargetLayout({ x, y: adjustedY, width, height });
490
+ measureRetryCount.current = 0;
491
+ } else {
492
+ // Still moving — keep polling without showing anything yet.
493
+ settleTimer.current = setTimeout(
494
+ () => measureUntilSettled(epoch, attempt + 1),
495
+ SETTLE_POLL_INTERVAL
496
+ );
497
+ }
498
+ } else if (attempt < MAX_SETTLE_POLLS) {
499
+ // Element not laid out yet — keep trying.
500
+ setTimeout(() => measureUntilSettled(epoch, attempt + 1), SETTLE_POLL_INTERVAL);
501
+ } else {
502
+ // Don't trap the user — fall back to a centered, dismissible tooltip.
503
+ fallBackToCentered(currentStepData.id, 'measured as 0x0 after scrolling');
504
+ }
505
+ }
506
+ );
507
+
508
+ if (!dispatched) {
509
+ fallBackToCentered(currentStepData.id, 'has a targetRef that cannot be measured');
510
+ }
511
+ },
512
+ [currentStepData, effectiveTargetRef, setTargetLayout, measureTopOffset, fallBackToCentered]
513
+ );
514
+
515
+ const warnUnusableScrollRef = useCallback(() => {
516
+ warnOnce(
517
+ 'The scrollRef passed to the tour exposes no usable scroll method, so auto-scroll was skipped.',
518
+ 'Pass a ref attached directly to a ScrollView, FlatList or SectionList (ref={scrollViewRef}), not to a wrapper View.'
519
+ );
520
+ }, []);
521
+
522
+ const hasScrollOffsetGetter = Boolean(
523
+ currentStepData?.scrollToTarget?.getCurrentScrollOffset ?? config?.getCurrentScrollOffset
524
+ );
525
+
526
+ // Without an offset getter we derive the destination from layout instead:
527
+ // measureLayout gives the target's Y inside the scroll CONTENT, and
528
+ // measureInWindow on the scroll view gives where the viewport sits. The
529
+ // desired content offset is then contentY - (idealScreenY - scrollViewY) —
530
+ // no knowledge of the current offset needed. This removes the silent
531
+ // mis-scroll when consumers forget getCurrentScrollOffset.
532
+ const scrollViaContentCoords = useCallback(
533
+ (
534
+ epoch: number,
535
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
536
+ scrollRef: { current: any },
537
+ idealTargetScreenY: number,
538
+ extraOffset: number,
539
+ animated: boolean
540
+ ): boolean => {
541
+ const targetNode = effectiveTargetRef?.current;
542
+ const scrollNode = scrollRef.current;
543
+ if (!targetNode || typeof targetNode.measureLayout !== 'function' || !scrollNode) {
544
+ return false;
545
+ }
546
+
547
+ // The host node measureLayout expects: FlatList exposes it via
548
+ // getNativeScrollRef / the underlying host component; findNodeHandle
549
+ // still resolves both architectures.
550
+ let relativeTo: unknown = null;
551
+ try {
552
+ relativeTo = findNodeHandle(scrollNode) ?? scrollNode;
553
+ } catch {
554
+ relativeTo = scrollNode;
555
+ }
556
+ if (!relativeTo) return false;
557
+
558
+ const dispatchedScrollMeasure = measureElement(
559
+ scrollRef as { current: Record<string, unknown> },
560
+ (_sx: number, scrollWinY: number) => {
561
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
562
+ try {
563
+ targetNode.measureLayout(
564
+ relativeTo,
565
+ (_lx: number, contentY: number) => {
566
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
567
+ const scrollToY =
568
+ contentY - (idealTargetScreenY - measureTopOffset - scrollWinY) + extraOffset;
569
+ if (!scrollRefToY(scrollRef, scrollToY, animated)) {
570
+ warnUnusableScrollRef();
571
+ measureTarget(epoch);
572
+ return;
573
+ }
574
+ setTargetLayout(null);
575
+ lastSettleY.current = null;
576
+ settleTimer.current = setTimeout(
577
+ () => measureUntilSettled(epoch),
578
+ animated ? 100 : 50
579
+ );
580
+ },
581
+ () => {
582
+ // measureLayout failed (detached / cross-tree) — measure in place.
583
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
584
+ measureTarget(epoch);
585
+ }
586
+ );
587
+ } catch {
588
+ measureTarget(epoch);
589
+ }
590
+ }
591
+ );
592
+ return dispatchedScrollMeasure;
593
+ },
594
+ [
595
+ effectiveTargetRef,
596
+ measureTarget,
597
+ measureUntilSettled,
598
+ measureTopOffset,
599
+ setTargetLayout,
600
+ warnUnusableScrollRef,
601
+ ]
602
+ );
603
+
604
+ const scrollAndMeasure = useCallback(
605
+ (epoch: number) => {
606
+ if (!currentStepData) return;
607
+ const scrollRef = getScrollRef();
608
+ const stepScrollConfig = currentStepData?.scrollToTarget;
609
+
610
+ // Handle absolute scroll positioning
611
+ if (stepScrollConfig?.absolute && scrollRef?.current) {
612
+ const offset = stepScrollConfig.offset ?? 0;
613
+ const animated = stepScrollConfig.animated ?? true;
614
+ // Works with ScrollView, FlatList, SectionList and wrapped scrollables —
615
+ // assuming scrollTo() crashed on every list component.
616
+ if (!scrollRefToY(scrollRef, offset, animated)) {
617
+ warnUnusableScrollRef();
618
+ measureTarget(epoch);
619
+ return;
620
+ }
621
+ // Hide the highlight while we scroll, then reveal it once settled — this
622
+ // is what stops the spotlight flickering/chasing during the scroll.
623
+ setTargetLayout(null);
624
+ lastSettleY.current = null;
625
+ settleTimer.current = setTimeout(() => measureUntilSettled(epoch), animated ? 100 : 50);
626
+ return;
627
+ }
628
+
629
+ // No target to measure
630
+ if (!effectiveTargetRef?.current) {
631
+ measureTarget(epoch);
632
+ return;
633
+ }
634
+
635
+ // Measure the target, then decide if scrolling is needed
636
+ const dispatched = measureElement(
637
+ effectiveTargetRef as { current: Record<string, unknown> },
638
+ (_: number, y: number, width: number, height: number) => {
639
+ // Bail if the step changed or we unmounted while measuring async.
640
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
641
+
642
+ if (width <= 0 || height <= 0) {
643
+ measureTarget(epoch);
644
+ return;
645
+ }
646
+
647
+ // If no scroll ref available, just measure and render
648
+ if (!scrollRef?.current) {
649
+ measureTarget(epoch);
650
+ return;
651
+ }
652
+
653
+ // Align with the full-screen overlay Modal (see measureTopOffset).
654
+ const adjustedY = y + measureTopOffset;
655
+ const animated = stepScrollConfig?.animated ?? true;
656
+ const extraOffset = stepScrollConfig?.offset ?? 0;
657
+ const currentScrollOffset = getScrollOffset();
658
+
659
+ // How much space tooltip + arrow + gap needs
660
+ const tooltipSpace =
661
+ ESTIMATED_TOOLTIP_HEIGHT + (config?.tooltipOffset ?? 8) + (config?.triangleSize ?? 12);
662
+
663
+ const targetTop = adjustedY;
664
+ const targetBottom = adjustedY + height;
665
+ const sh = screenDimensions.height;
666
+
667
+ // Margins keep the target clear of system chrome: the status bar/notch
668
+ // at the top and the nav bar / home indicator / tab bar at the bottom.
669
+ const topMargin = insets.top + 24;
670
+ const bottomMargin = insets.bottom + 24;
671
+
672
+ // Space available above and below the target for the tooltip
673
+ const spaceAbove = targetTop - topMargin;
674
+ const spaceBelow = sh - targetBottom - bottomMargin;
675
+
676
+ // Is the full target visible with comfortable margins?
677
+ const targetFullyVisible = targetTop >= topMargin && targetBottom <= sh - bottomMargin;
678
+ // Does the tooltip fit on at least one side?
679
+ const tooltipFits = spaceBelow >= tooltipSpace || spaceAbove >= tooltipSpace;
680
+
681
+ if (targetFullyVisible && tooltipFits) {
682
+ // Everything fits — no scroll needed
683
+ measureTarget(epoch);
684
+ return;
685
+ }
686
+
687
+ // Need to scroll. Calculate where the target should be on screen.
688
+ // Strategy: place target so the LARGER space (above or below) gets the tooltip.
689
+ let idealTargetScreenY: number;
690
+
691
+ // Prefer tooltip above: scroll target toward the bottom half
692
+ // This way user sees the target clearly and tooltip appears above
693
+ const targetWithTooltipAbove = tooltipSpace + topMargin;
694
+ const targetWithTooltipBelow = topMargin;
695
+
696
+ if (targetWithTooltipAbove + height + bottomMargin <= sh) {
697
+ // Tooltip above fits — place target below the tooltip space
698
+ idealTargetScreenY = targetWithTooltipAbove;
699
+ } else if (targetWithTooltipBelow + height + tooltipSpace + bottomMargin <= sh) {
700
+ // Tooltip below fits — place target near top
701
+ idealTargetScreenY = targetWithTooltipBelow;
702
+ } else {
703
+ // Tight space — center the target, tooltip will auto-position
704
+ idealTargetScreenY = (sh - height) / 2;
705
+ }
706
+
707
+ // Ensure the target bottom is fully visible on screen
708
+ const maxTargetY = sh - height - bottomMargin;
709
+ idealTargetScreenY = Math.min(idealTargetScreenY, maxTargetY);
710
+
711
+ // No offset getter → derive the destination from content coordinates
712
+ // (measureLayout), which needs no offset at all.
713
+ if (!hasScrollOffsetGetter) {
714
+ if (
715
+ scrollViaContentCoords(epoch, scrollRef, idealTargetScreenY, extraOffset, animated)
716
+ ) {
717
+ return;
718
+ }
719
+ // Fall through to the offset path (offset 0) if unsupported.
720
+ }
721
+
722
+ const scrollDelta = targetTop - idealTargetScreenY;
723
+ const scrollToY = currentScrollOffset + scrollDelta + extraOffset;
724
+
725
+ if (!scrollRefToY(scrollRef, scrollToY, animated)) {
726
+ // The ref is not a usable scrollable — highlight it where it is
727
+ // rather than failing the step.
728
+ warnUnusableScrollRef();
729
+ measureTarget(epoch);
730
+ return;
731
+ }
732
+
733
+ // Hide the highlight while we scroll, then reveal it once settled at the
734
+ // target's new position — no flicker, no chasing the moving target.
735
+ setTargetLayout(null);
736
+ lastSettleY.current = null;
737
+ settleTimer.current = setTimeout(() => measureUntilSettled(epoch), animated ? 100 : 50);
738
+ }
739
+ );
740
+
741
+ // This ref exposes no measurement API, so the callback above will never
742
+ // run. Without this the overlay stayed on screen with no tooltip forever.
743
+ if (!dispatched) {
744
+ fallBackToCentered(currentStepData.id, 'has a targetRef that cannot be measured');
745
+ }
746
+ },
747
+ [
748
+ currentStepData,
749
+ effectiveTargetRef,
750
+ measureTarget,
751
+ measureUntilSettled,
752
+ getScrollRef,
753
+ getScrollOffset,
754
+ screenDimensions.height,
755
+ config,
756
+ insets,
757
+ measureTopOffset,
758
+ warnUnusableScrollRef,
759
+ fallBackToCentered,
760
+ hasScrollOffsetGetter,
761
+ scrollViaContentCoords,
762
+ ]
763
+ );
764
+
765
+ // --- Main effect: step changes ---
766
+ useEffect(() => {
767
+ // Cleanup previous timers
768
+ if (delayTimer.current) {
769
+ clearTimeout(delayTimer.current);
770
+ delayTimer.current = null;
771
+ }
772
+ if (autoAdvanceTimer.current) {
773
+ clearTimeout(autoAdvanceTimer.current);
774
+ autoAdvanceTimer.current = null;
775
+ }
776
+
777
+ if (!isActive || isPaused || !currentStepData) {
778
+ // Tour ended or paused — the next tour (or resume) runs before() afresh.
779
+ beforeRanKey.current = null;
780
+ if (!isActive) {
781
+ // Unconditional: a leaked lastCommitted from tour A (single
782
+ // keepSpotlight step, nothing accumulated) would otherwise punch A's
783
+ // stale rectangle into tour B's backdrop.
784
+ lastCommitted.current = null;
785
+ if (keptShapes.current.size > 0) {
786
+ keptShapes.current.clear();
787
+ setKeptVersion((v) => v + 1);
788
+ }
789
+ }
790
+ return undefined;
791
+ }
792
+
793
+ // New step → bump the epoch so any in-flight measurement from the previous
794
+ // step is ignored, and clear the centered fallback from the previous step.
795
+ const epoch = ++stepEpoch.current;
796
+ setCenteredFallback(false);
797
+ setFollowLayout(null);
798
+
799
+ // keepSpotlight reconciliation: drop kept holes at or after the new index
800
+ // (going back un-keeps), and keep the step we just moved FORWARD past if it
801
+ // asked to stay lit.
802
+ {
803
+ const map = keptShapes.current;
804
+ let changed = false;
805
+ for (const key of [...map.keys()]) {
806
+ if (key >= currentStep) {
807
+ map.delete(key);
808
+ changed = true;
809
+ }
810
+ }
811
+ const prevCommit = lastCommitted.current;
812
+ if (
813
+ prevCommit &&
814
+ prevCommit.index < currentStep &&
815
+ prevCommit.step.keepSpotlight &&
816
+ !map.has(prevCommit.index)
817
+ ) {
818
+ const radius =
819
+ prevCommit.step.spotlightBorderRadius ??
820
+ extractBorderRadius(
821
+ prevCommit.step.targetStyle ??
822
+ (prevCommit.step.targetId ? getTarget(prevCommit.step.targetId)?.style : undefined),
823
+ prevCommit.layout
824
+ );
825
+ map.set(prevCommit.index, {
826
+ layout: prevCommit.layout,
827
+ padding: prevCommit.step.spotlightPadding ?? 0,
828
+ radius,
829
+ // No scroll reported yet ⇒ the offset baseline is 0, not "unknown" —
830
+ // otherwise a hole captured before the first scroll never translates.
831
+ scrollYAtCapture: __getTrackedScrollY?.() ?? 0,
832
+ maskPath: prevCommit.step.spotlightStyles?.maskPath,
833
+ });
834
+ changed = true;
835
+ }
836
+ if (changed) setKeptVersion((v) => v + 1);
837
+ }
838
+
839
+ const startMeasurement = (attempt = 0) => {
840
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
841
+
842
+ // Fixed-region step: no measurement at all — highlight the given window
843
+ // rectangle (maps, camera views, anything without a ref). The region is
844
+ // in measureInWindow coordinates, so it gets the same Android status-bar
845
+ // correction as measured targets — otherwise the identical rect would
846
+ // land ~a status-bar height too high under the translucent Modal.
847
+ if (currentStepData.targetRegion) {
848
+ const region = currentStepData.targetRegion;
849
+ setTargetLayout({ ...region, y: region.y + measureTopOffset });
850
+ return;
851
+ }
852
+
853
+ // A targetId whose <TourTarget> hasn't registered yet (screen still
854
+ // mounting) gets a short grace period before we give up — this is what
855
+ // makes "start the tour, then navigate" work without manual delays.
856
+ if (currentStepData.targetId && !currentStepData.targetRef && !effectiveTargetRef?.current) {
857
+ if (attempt < TARGET_WAIT_RETRIES) {
858
+ delayTimer.current = setTimeout(
859
+ () => startMeasurement(attempt + 1),
860
+ TARGET_WAIT_INTERVAL
861
+ );
862
+ return;
863
+ }
864
+ warnOnce(
865
+ `Step "${currentStepData.id}" references targetId "${currentStepData.targetId}", but no <TourTarget id="${currentStepData.targetId}"> registered in time. Showing a centered tooltip instead.`,
866
+ 'Render a <TourTarget> with that id, or check the id for typos.'
867
+ );
868
+ setTargetLayout(null);
869
+ setCenteredFallback(true);
870
+ return;
871
+ }
872
+
873
+ const hasValidRef = currentStepData.targetId
874
+ ? Boolean(effectiveTargetRef?.current)
875
+ : validateRef(currentStepData.targetRef, currentStepData.id);
876
+
877
+ if (hasValidRef) {
878
+ // Watchdog: no layout and no fallback after the deadline means some
879
+ // measure callback silently never fired — rescue with the centered
880
+ // tooltip rather than leaving the user trapped.
881
+ if (watchdogTimer.current) clearTimeout(watchdogTimer.current);
882
+ watchdogTimer.current = setTimeout(() => {
883
+ watchdogTimer.current = null;
884
+ if (
885
+ epoch === stepEpoch.current &&
886
+ isMounted.current &&
887
+ !targetLayoutRef.current &&
888
+ !centeredFallbackRef.current
889
+ ) {
890
+ fallBackToCentered(currentStepData.id, 'never completed measurement');
891
+ }
892
+ }, MEASURE_WATCHDOG_MS);
893
+ scrollAndMeasure(epoch);
894
+ } else {
895
+ // No valid ref — show a centered tooltip without spotlight.
896
+ setTargetLayout(null);
897
+ setCenteredFallback(true);
898
+ }
899
+ };
900
+
901
+ // The awaited per-step hook runs first: navigate, open a sheet, fetch —
902
+ // the spotlight only appears once it resolves. Errors don't trap the user;
903
+ // we warn and proceed to measure whatever is there.
904
+ const begin = () => {
905
+ const hook = currentStepData.before;
906
+ const visitKey = `${currentStep}:${currentStepData.id}`;
907
+ if (!hook || beforeRanKey.current === visitKey) {
908
+ startMeasurement();
909
+ return;
910
+ }
911
+ beforeRanKey.current = visitKey;
912
+ let result: void | Promise<void>;
913
+ try {
914
+ result = hook();
915
+ } catch (error) {
916
+ warnOnce(
917
+ `Step "${currentStepData.id}" before() threw: ${String(error)}. Proceeding to show the step.`,
918
+ 'Make before() handle its own errors if the step should still be shown.'
919
+ );
920
+ startMeasurement();
921
+ return;
922
+ }
923
+ if (result && typeof (result as Promise<void>).then === 'function') {
924
+ (result as Promise<void>)
925
+ .then(() => startMeasurement())
926
+ .catch((error) => {
927
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
928
+ warnOnce(
929
+ `Step "${currentStepData.id}" before() rejected: ${String(error)}. Proceeding to show the step.`,
930
+ 'Make before() handle its own errors if the step should still be shown.'
931
+ );
932
+ startMeasurement();
933
+ });
934
+ } else {
935
+ startMeasurement();
936
+ }
937
+ };
938
+
939
+ // Optionally let navigation/layout animations finish before measuring —
940
+ // the principled version of guessing a delayBefore.
941
+ const beginAfterInteractions = () => {
942
+ const wants = currentStepData.waitForInteractions ?? config?.waitForInteractions;
943
+ if (!wants) {
944
+ begin();
945
+ return;
946
+ }
947
+ interactionHandle.current = InteractionManager.runAfterInteractions(() => {
948
+ interactionHandle.current = null;
949
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
950
+ begin();
951
+ });
952
+ };
953
+
954
+ // Apply delay if configured
955
+ const delay = currentStepData.delayBefore ?? 0;
956
+ if (delay > 0) {
957
+ delayTimer.current = setTimeout(beginAfterInteractions, delay);
958
+ } else {
959
+ // Small delay to ensure layout is ready
960
+ delayTimer.current = setTimeout(beginAfterInteractions, 100);
961
+ }
962
+
963
+ return () => {
964
+ if (delayTimer.current) {
965
+ clearTimeout(delayTimer.current);
966
+ delayTimer.current = null;
967
+ }
968
+ if (autoAdvanceTimer.current) {
969
+ clearTimeout(autoAdvanceTimer.current);
970
+ autoAdvanceTimer.current = null;
971
+ }
972
+ if (watchdogTimer.current) {
973
+ clearTimeout(watchdogTimer.current);
974
+ watchdogTimer.current = null;
975
+ }
976
+ if (settleTimer.current) {
977
+ clearTimeout(settleTimer.current);
978
+ settleTimer.current = null;
979
+ }
980
+ if (interactionHandle.current) {
981
+ interactionHandle.current.cancel();
982
+ interactionHandle.current = null;
983
+ }
984
+ if (measureRetryTimer.current) {
985
+ clearTimeout(measureRetryTimer.current);
986
+ measureRetryTimer.current = null;
987
+ }
988
+ };
989
+ }, [
990
+ isActive,
991
+ isPaused,
992
+ currentStep,
993
+ currentStepData,
994
+ effectiveTargetRef,
995
+ fallBackToCentered,
996
+ scrollAndMeasure,
997
+ setTargetLayout,
998
+ inlineOriginVersion,
999
+ ]);
1000
+
1001
+ // A fresh real measurement supersedes any stale follow position.
1002
+ useEffect(() => {
1003
+ setFollowLayout(null);
1004
+ }, [targetLayout]);
1005
+
1006
+ // What renders: the live follow position while the user scrolls, else the
1007
+ // last committed measurement.
1008
+ const renderLayout = followLayout ?? targetLayout;
1009
+
1010
+ // Kept holes, re-generated for the CURRENT scroll position. When the page
1011
+ // has scrolled since a hole was captured (tour auto-scroll or a followTarget
1012
+ // free scroll), the hole moves with the content instead of hovering over
1013
+ // whatever scrolled into its old window position. Without a tracked offset
1014
+ // (useTourScroll unwired) the delta is 0 — the previous static behaviour.
1015
+ const keptPaths = useMemo(() => {
1016
+ if (keptShapes.current.size === 0) return [];
1017
+ const nowY = __getTrackedScrollY?.() ?? 0;
1018
+ return [...keptShapes.current.values()].map((entry) => {
1019
+ const maskPath = entry.maskPath ?? config?.spotlightStyles?.maskPath;
1020
+ const dy = entry.scrollYAtCapture !== undefined ? entry.scrollYAtCapture - nowY : 0;
1021
+ const layout = { ...entry.layout, y: entry.layout.y + dy };
1022
+ const shape = computeShape(layout, entry.padding, entry.radius ?? undefined);
1023
+ // A custom maskPath must survive being kept — otherwise a custom
1024
+ // silhouette degrades to a rounded rect the moment the tour moves on.
1025
+ if (maskPath) {
1026
+ const autoBounds =
1027
+ shape.kind === 'rect'
1028
+ ? { x: shape.x, y: shape.y, width: shape.width, height: shape.height }
1029
+ : shape.bounds;
1030
+ try {
1031
+ const d = maskPath({
1032
+ target: layout,
1033
+ bounds: autoBounds,
1034
+ screenWidth: screenDimensions.width,
1035
+ screenHeight: screenDimensions.height,
1036
+ });
1037
+ if (typeof d === 'string' && d.length > 0) return d;
1038
+ } catch {
1039
+ // fall through to the automatic shape
1040
+ }
1041
+ }
1042
+ return shapeInnerPath(shape);
1043
+ });
1044
+ // followLayout re-renders per scroll frame while following, which is what
1045
+ // keeps the delta fresh; keptVersion covers capture/clear.
1046
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1047
+ }, [
1048
+ keptVersion,
1049
+ followLayout,
1050
+ targetLayout,
1051
+ __getTrackedScrollY,
1052
+ config?.spotlightStyles?.maskPath,
1053
+ screenDimensions,
1054
+ ]);
1055
+
1056
+ // Remember the committed layout for keepSpotlight bookkeeping — including
1057
+ // follow updates, so a kept hole lands where the target actually IS.
1058
+ useEffect(() => {
1059
+ const layout = followLayout ?? targetLayout;
1060
+ if (layout && currentStepData) {
1061
+ lastCommitted.current = { index: currentStep, layout, step: currentStepData };
1062
+ }
1063
+ }, [targetLayout, followLayout, currentStep, currentStepData]);
1064
+
1065
+ // The step is on screen once the target is measured OR we've committed to a
1066
+ // centered tooltip. Both paths must drive announcements and auto-advance —
1067
+ // gating on targetLayout alone silently disabled them for centered steps.
1068
+ const isStepVisible = Boolean(targetLayout) || centeredFallback;
1069
+
1070
+ // --- Exact settle signal (useTourScroll) ---
1071
+ // The consumer's onMomentumScrollEnd tells us the programmatic scroll is
1072
+ // done: cancel the position polling and commit the final measurement now.
1073
+ useEffect(() => {
1074
+ if (!__subscribeScrollEnd) return undefined;
1075
+ return __subscribeScrollEnd(() => {
1076
+ // Only act while a settle poll is actually pending — otherwise this is a
1077
+ // user fling with no tour scroll in flight.
1078
+ if (settleTimer.current === null || !isMounted.current) return;
1079
+ clearTimeout(settleTimer.current);
1080
+ settleTimer.current = null;
1081
+ // Poll IMMEDIATELY but keep the normal settle rules (two consecutive
1082
+ // matching readings, full 0x0 retry budget). A force-commit here had two
1083
+ // failure modes: a virtualized row measuring 0x0 the instant the scroll
1084
+ // stopped went straight to the centered fallback, and a USER fling ending
1085
+ // inside the window committed a mid-flight position. With settle rules,
1086
+ // a genuine end matches the previous reading and commits on the spot; a
1087
+ // moving target simply keeps polling.
1088
+ measureUntilSettled(stepEpoch.current, 1);
1089
+ });
1090
+ }, [__subscribeScrollEnd, measureUntilSettled]);
1091
+
1092
+ // --- followTarget: keep the highlight glued to the target while the user
1093
+ // scrolls freely (requires useTourScroll to be wired). JS-driven: re-measure
1094
+ // on each reported scroll event, coalesced to one measurement per frame, and
1095
+ // committed with motion 'none' so the spotlight doesn't chase-animate. ---
1096
+ const followFrame = useRef(false);
1097
+ useEffect(() => {
1098
+ if (!isActive || isPaused || !config?.followTarget || !__subscribeScroll) return undefined;
1099
+ if (!currentStepData || currentStepData.targetRegion) return undefined;
1100
+
1101
+ return __subscribeScroll(() => {
1102
+ if (followFrame.current) return;
1103
+ followFrame.current = true;
1104
+ const schedule =
1105
+ typeof requestAnimationFrame === 'function'
1106
+ ? requestAnimationFrame
1107
+ : (cb: () => void) => setTimeout(cb, 16);
1108
+ schedule(() => {
1109
+ followFrame.current = false;
1110
+ const epoch = stepEpoch.current;
1111
+ if (!isMounted.current || !effectiveTargetRef?.current) return;
1112
+ // Don't fight the programmatic-scroll settle logic; it owns the layout
1113
+ // until it commits.
1114
+ if (settleTimer.current !== null) return;
1115
+ measureElement(
1116
+ effectiveTargetRef as { current: Record<string, unknown> },
1117
+ (x: number, y: number, width: number, height: number) => {
1118
+ if (epoch !== stepEpoch.current || !isMounted.current) return;
1119
+ if (width > 0 && height > 0) {
1120
+ setFollowLayout({ x, y: y + measureTopOffset, width, height });
1121
+ }
1122
+ }
1123
+ );
1124
+ });
1125
+ });
1126
+ }, [
1127
+ isActive,
1128
+ isPaused,
1129
+ config?.followTarget,
1130
+ __subscribeScroll,
1131
+ currentStepData,
1132
+ effectiveTargetRef,
1133
+ measureTopOffset,
1134
+ ]);
1135
+
1136
+ // --- Accessibility announcement ---
1137
+ useEffect(() => {
1138
+ if (isActive && currentStepData && isStepVisible) {
1139
+ announceStep(currentStepData, currentStep, activeSteps.length, config);
1140
+ }
1141
+ }, [isActive, currentStepData, isStepVisible, currentStep, activeSteps.length, config]);
1142
+
1143
+ // --- Auto-advance timer ---
1144
+ useEffect(() => {
1145
+ if (!isActive || isPaused || !currentStepData || !isStepVisible) return undefined;
1146
+
1147
+ const { autoAdvance } = currentStepData;
1148
+ // completed:false gates progression — the timer must not advance past a
1149
+ // step the user hasn't finished. setStepCompleted(id, true) rebuilds the
1150
+ // step object, which re-runs this effect and arms the timer.
1151
+ if (currentStepData.completed === false) return undefined;
1152
+ if (autoAdvance && autoAdvance > 0) {
1153
+ autoAdvanceTimer.current = setTimeout(() => {
1154
+ nextStep();
1155
+ }, autoAdvance);
1156
+
1157
+ return () => {
1158
+ if (autoAdvanceTimer.current) {
1159
+ clearTimeout(autoAdvanceTimer.current);
1160
+ autoAdvanceTimer.current = null;
1161
+ }
1162
+ };
1163
+ }
1164
+
1165
+ return undefined;
1166
+ }, [isActive, isPaused, currentStepData, isStepVisible, nextStep]);
1167
+
1168
+ if (!isActive || isPaused || !currentStepData) return null;
1169
+
1170
+ // --- Backdrop behavior ---
1171
+ const resolveBackdropBehavior = (behavior: BackdropBehavior | undefined) => {
1172
+ const effective = behavior ?? config?.defaultBackdropBehavior ?? 'none';
1173
+ if (effective === 'dismiss') return skipTour;
1174
+ if (effective === 'next') {
1175
+ // completed:false gates progression — a backdrop tap must not advance
1176
+ // past an unfinished step any more than the (disabled) Next button can.
1177
+ // Explicit nextStep() calls from the consumer's own handlers still work.
1178
+ return currentStepData.completed === false ? undefined : nextStep;
1179
+ }
1180
+ if (typeof effective === 'function') return effective;
1181
+ return undefined; // 'none'
1182
+ };
1183
+
1184
+ const onBackdropPress = resolveBackdropBehavior(currentStepData.backdropBehavior);
1185
+
1186
+ // --- Tooltip position resolution ---
1187
+ const resolvedTooltipPosition = (() => {
1188
+ const preferred = currentStepData.tooltipPosition ?? 'auto';
1189
+
1190
+ // Auto-positioning is ON by default so tooltips never render off-screen.
1191
+ // Setting `autoPositionTooltip: false` opts out entirely and honours the
1192
+ // step's explicit position, even where it does not fit.
1193
+ if (config?.autoPositionTooltip === false && preferred !== 'auto') {
1194
+ return preferred;
1195
+ }
1196
+
1197
+ if (preferred === 'auto' || config?.autoPositionTooltip !== false) {
1198
+ if (renderLayout) {
1199
+ // If user set explicit position (not 'auto'), use it as a hint but validate
1200
+ const autoResult = computeTooltipPosition({
1201
+ target: renderLayout,
1202
+ screenWidth: screenDimensions.width,
1203
+ screenHeight: screenDimensions.height,
1204
+ tooltipWidth: config?.tooltipWidth ?? 320,
1205
+ tooltipHeight: 150,
1206
+ offset: (config?.tooltipOffset ?? 8) + (config?.triangleSize ?? 12),
1207
+ insets,
1208
+ });
1209
+
1210
+ // If user explicitly chose a position (not 'auto'), prefer it if it fits
1211
+ if (preferred !== 'auto') {
1212
+ const offset = (config?.tooltipOffset ?? 8) + (config?.triangleSize ?? 12);
1213
+ const tooltipHeight = 150;
1214
+ const fits = (() => {
1215
+ switch (preferred) {
1216
+ case 'bottom':
1217
+ return (
1218
+ screenDimensions.height -
1219
+ insets.bottom -
1220
+ (renderLayout.y + renderLayout.height + offset) >=
1221
+ tooltipHeight
1222
+ );
1223
+ case 'top':
1224
+ return renderLayout.y - offset - insets.top >= tooltipHeight;
1225
+ case 'left':
1226
+ return renderLayout.x - offset - insets.left >= (config?.tooltipWidth ?? 320) * 0.6;
1227
+ case 'right':
1228
+ return (
1229
+ screenDimensions.width -
1230
+ insets.right -
1231
+ (renderLayout.x + renderLayout.width + offset) >=
1232
+ (config?.tooltipWidth ?? 320) * 0.6
1233
+ );
1234
+ default:
1235
+ return false;
1236
+ }
1237
+ })();
1238
+ if (fits) return preferred;
1239
+ }
1240
+
1241
+ return autoResult;
1242
+ }
1243
+ }
1244
+
1245
+ return preferred === 'auto' ? 'bottom' : preferred;
1246
+ })();
1247
+
1248
+ // --- Shared tooltip props ---
1249
+ const tooltipProps = {
1250
+ title: currentStepData.title,
1251
+ description: currentStepData.description,
1252
+ position: renderLayout
1253
+ ? { x: renderLayout.x, y: renderLayout.y }
1254
+ : {
1255
+ // Centered (no-target) step: center within the safe area.
1256
+ x: screenDimensions.width / 2,
1257
+ y: (insets.top + (screenDimensions.height - insets.bottom)) / 2,
1258
+ },
1259
+ tooltipPosition: resolvedTooltipPosition,
1260
+ currentStep,
1261
+ totalSteps: activeSteps.length,
1262
+ targetHeight: renderLayout?.height ?? 0,
1263
+ targetWidth: renderLayout?.width ?? 0,
1264
+ onNext: nextStep,
1265
+ onPrev: currentStep > 0 ? prevStep : undefined,
1266
+ onSkip: skipTour,
1267
+ config,
1268
+ hideNextButton: currentStepData.hideNextButton,
1269
+ hidePrevButton: currentStepData.hidePrevButton,
1270
+ hideSkipButton: currentStepData.hideSkipButton,
1271
+ screenWidth: screenDimensions.width,
1272
+ screenHeight: screenDimensions.height,
1273
+ insets,
1274
+ // completed:false gates the Next button until setStepCompleted(id, true).
1275
+ nextDisabled: currentStepData.completed === false,
1276
+ isLastStep: currentStep === activeSteps.length - 1,
1277
+ };
1278
+
1279
+ // --- Resolve border radius: explicit > extracted from targetStyle > default ---
1280
+ // Pass the measured target so percentage radii (e.g. '50%') resolve to a real
1281
+ // pixel radius — this is what keeps circular targets round instead of square.
1282
+ const effectiveBorderRadius =
1283
+ currentStepData.spotlightBorderRadius ??
1284
+ extractBorderRadius(effectiveTargetStyle, renderLayout ?? undefined);
1285
+
1286
+ // --- Shared spotlight props ---
1287
+ const spotlightProps = {
1288
+ target: renderLayout,
1289
+ padding: currentStepData.spotlightPadding,
1290
+ borderRadius: effectiveBorderRadius,
1291
+ // Per-step styles win over the config's, key by key.
1292
+ styles: currentStepData.spotlightStyles
1293
+ ? { ...config?.spotlightStyles, ...currentStepData.spotlightStyles }
1294
+ : config?.spotlightStyles,
1295
+ screenWidth: screenDimensions.width,
1296
+ screenHeight: screenDimensions.height,
1297
+ animationDuration: config?.animationDuration,
1298
+ // While followTarget is live-tracking, position updates snap (no tween) —
1299
+ // an animated chase would lag a frame behind the finger.
1300
+ motion: followLayout ? ('none' as const) : (currentStepData.motion ?? config?.motion),
1301
+ onBackdropPress,
1302
+ onSpotlightPress: currentStepData.onSpotlightPress,
1303
+ // Touches pass through the hole to the real element (inline mode only —
1304
+ // in a Modal there is nothing underneath to receive them).
1305
+ interactive: currentStepData.interactive === true && config?.overlayMode === 'inline',
1306
+ // Any blurred step in this tour → keep the blur subtree mounted throughout
1307
+ // and cross-fade it, so blur↔no-blur step changes don't pay a mount hitch.
1308
+ mountBlurLayer:
1309
+ Boolean(config?.spotlightStyles?.enableBlur) ||
1310
+ activeSteps.some((st) => st.spotlightStyles?.enableBlur === true),
1311
+ // Spotlights kept lit from earlier keepSpotlight steps.
1312
+ keptPaths,
1313
+ };
1314
+
1315
+ // Show the tooltip once the target is measured, or immediately for a
1316
+ // centered/no-target step. This is what prevents the user from being trapped
1317
+ // behind a backdrop with no tooltip to interact with.
1318
+ const showTooltip = isStepVisible;
1319
+
1320
+ // One Modal for both paths. Previously the custom-renderer branch passed
1321
+ // `navigationBarTranslucent` and the default branch did not, so whether the
1322
+ // overlay covered the Android navigation bar depended on which tooltip you
1323
+ // used. (The prop is ignored on React Native versions that predate it.)
1324
+ const renderTooltipContent = () => {
1325
+ if (!showTooltip) return null;
1326
+ const renderer = currentStepData.renderTooltip ?? config?.renderTooltip;
1327
+ return renderer ? renderer(tooltipProps) : <Tooltip {...tooltipProps} />;
1328
+ };
1329
+
1330
+ // Inline mode: an absolutely-positioned layer instead of a Modal. Interactive
1331
+ // steps need this — a Modal swallows every touch, so nothing underneath is
1332
+ // reachable. Requires <TourGuideOverlay /> to sit at the app root so
1333
+ // absoluteFill covers the whole screen.
1334
+ if (config?.overlayMode === 'inline') {
1335
+ return (
1336
+ <View
1337
+ ref={inlineRootRef}
1338
+ onLayout={onInlineRootLayout}
1339
+ collapsable={false}
1340
+ style={[StyleSheet.absoluteFill, inlineStyles.layer]}
1341
+ pointerEvents="box-none"
1342
+ >
1343
+ <SpotlightOverlay {...spotlightProps} />
1344
+ {renderTooltipContent()}
1345
+ </View>
1346
+ );
1347
+ }
1348
+
1349
+ return (
1350
+ <Modal
1351
+ visible={isActive}
1352
+ transparent
1353
+ animationType="fade"
1354
+ statusBarTranslucent
1355
+ navigationBarTranslucent
1356
+ // iOS intersects these with the app's own allowed orientations, so the
1357
+ // full-list default just means "rotate with the app" instead of the
1358
+ // Modal refusing to leave portrait.
1359
+ supportedOrientations={
1360
+ config?.supportedOrientations ?? [
1361
+ 'portrait',
1362
+ 'portrait-upside-down',
1363
+ 'landscape',
1364
+ 'landscape-left',
1365
+ 'landscape-right',
1366
+ ]
1367
+ }
1368
+ onRequestClose={skipTour}
1369
+ >
1370
+ <SpotlightOverlay {...spotlightProps} />
1371
+ {renderTooltipContent()}
1372
+ </Modal>
1373
+ );
1374
+ };
1375
+
1376
+ const inlineStyles = StyleSheet.create({
1377
+ // High enough to clear app content; transparent, so Android elevation draws
1378
+ // no shadow. zIndex covers iOS/web stacking.
1379
+ layer: { zIndex: 10000, elevation: 1000 },
1380
+ });
1381
+
1382
+ export default TourGuideOverlay;