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