@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,147 @@
1
+ import { useCallback, useRef } from 'react';
2
+
3
+ import type { TourStorage, TourStep, TourGuideConfig } from './types';
4
+ import { useTourGuide } from './TourGuideContext';
5
+ import { detectStorage } from './storage';
6
+ import { warn } from './dev';
7
+
8
+ const STORAGE_PREFIX = '@tour_guide:';
9
+
10
+ /**
11
+ * Hook that adds "show only once" persistence to tours.
12
+ * Wraps `startTour` to check if a tour has been completed before,
13
+ * and automatically marks tours as completed when they finish.
14
+ *
15
+ * @param storage - Optional storage adapter. When omitted, MMKV or
16
+ * AsyncStorage is auto-detected (in that order); with neither installed, an
17
+ * in-memory fallback is used and a dev warning explains persistence won't
18
+ * survive restarts.
19
+ *
20
+ * @example
21
+ * ```tsx
22
+ * import AsyncStorage from '@react-native-async-storage/async-storage';
23
+ * import { useTourPersistence } from '@wrack/react-native-tour-guide';
24
+ *
25
+ * const { startTour, resetTour, isTourCompleted } = useTourPersistence(AsyncStorage);
26
+ *
27
+ * // Only shows the tour if user hasn't seen it before
28
+ * startTour(steps, { tourId: 'onboarding' });
29
+ *
30
+ * // Force show again
31
+ * await resetTour('onboarding');
32
+ * startTour(steps, { tourId: 'onboarding' });
33
+ * ```
34
+ */
35
+ export const useTourPersistence = (storage?: TourStorage) => {
36
+ const tourGuide = useTourGuide();
37
+ // No adapter passed → auto-detect MMKV or AsyncStorage (memory fallback with
38
+ // a dev warning when neither is installed).
39
+ const resolved = storage ?? detectStorage().adapter;
40
+ const storageRef = useRef(resolved);
41
+ storageRef.current = resolved;
42
+
43
+ // Stable ref to the underlying startTour to avoid re-creating our wrapper on every render
44
+ const startTourRef = useRef(tourGuide.startTour);
45
+ startTourRef.current = tourGuide.startTour;
46
+
47
+ /**
48
+ * Check if a tour has been completed
49
+ */
50
+ const isTourCompleted = useCallback(async (tourId: string): Promise<boolean> => {
51
+ try {
52
+ const value = await storageRef.current.getItem(`${STORAGE_PREFIX}${tourId}`);
53
+ return value === 'completed';
54
+ } catch (error) {
55
+ // A storage backend that is unavailable (not yet initialised, quota, web
56
+ // private mode) must not decide whether the user sees the tour, and must
57
+ // not reject into the caller. Treat "unknown" as "not completed".
58
+ warn(
59
+ `Could not read tour state for "${tourId}" from storage: ${String(error)}. Treating the tour as not yet completed.`,
60
+ 'Check that the storage adapter is initialised before calling startTour().'
61
+ );
62
+ return false;
63
+ }
64
+ }, []);
65
+
66
+ /**
67
+ * Mark a tour as completed
68
+ */
69
+ const markCompleted = useCallback(async (tourId: string) => {
70
+ try {
71
+ await storageRef.current.setItem(`${STORAGE_PREFIX}${tourId}`, 'completed');
72
+ } catch (error) {
73
+ warn(
74
+ `Could not persist completion of tour "${tourId}": ${String(error)}. The tour will show again next launch.`,
75
+ 'Check that the storage adapter is writable.'
76
+ );
77
+ }
78
+ }, []);
79
+
80
+ /**
81
+ * Reset a tour so it shows again
82
+ */
83
+ const resetTour = useCallback(async (tourId: string) => {
84
+ try {
85
+ await storageRef.current.removeItem(`${STORAGE_PREFIX}${tourId}`);
86
+ } catch (error) {
87
+ warn(
88
+ `Could not reset tour "${tourId}": ${String(error)}.`,
89
+ 'Check that the storage adapter supports removeItem().'
90
+ );
91
+ }
92
+ }, []);
93
+
94
+ /**
95
+ * Start a tour only if it hasn't been completed.
96
+ * Automatically marks the tour as completed when finished.
97
+ * Requires `config.tourId` to be set.
98
+ *
99
+ * @param force - If true, show the tour even if previously completed
100
+ * @returns true if the tour was started, false if it was skipped
101
+ */
102
+ const startTour = useCallback(
103
+ async (steps: TourStep[], config?: TourGuideConfig, force = false): Promise<boolean> => {
104
+ const tourId = config?.tourId;
105
+ if (!tourId) {
106
+ warn(
107
+ 'useTourPersistence.startTour() was called without config.tourId, so the tour cannot be remembered and will show every time.',
108
+ "Pass a stable id: startTour(steps, { tourId: 'onboarding' })."
109
+ );
110
+ startTourRef.current(steps, config);
111
+ return true;
112
+ }
113
+
114
+ // Check if already completed
115
+ if (!force) {
116
+ const completed = await isTourCompleted(tourId);
117
+ if (completed) return false;
118
+ }
119
+
120
+ // Wrap onTourEnd to mark as completed
121
+ const originalOnTourEnd = config?.onTourEnd;
122
+ const enhancedConfig: TourGuideConfig = {
123
+ ...config,
124
+ onTourEnd: (completed: boolean) => {
125
+ if (completed) {
126
+ // Fire-and-forget, but never as an unhandled rejection: markCompleted
127
+ // already swallows and reports storage failures.
128
+ void markCompleted(tourId);
129
+ }
130
+ originalOnTourEnd?.(completed);
131
+ },
132
+ };
133
+
134
+ startTourRef.current(steps, enhancedConfig);
135
+ return true;
136
+ },
137
+ [isTourCompleted, markCompleted]
138
+ );
139
+
140
+ return {
141
+ ...tourGuide,
142
+ startTour,
143
+ isTourCompleted,
144
+ resetTour,
145
+ markCompleted,
146
+ };
147
+ };
@@ -0,0 +1,60 @@
1
+ import { useCallback, useMemo } from 'react';
2
+ import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native';
3
+
4
+ import { useTourGuide } from './TourGuideContext';
5
+
6
+ export interface TourScrollBinding {
7
+ /**
8
+ * Spread onto the ScrollView/FlatList the tour scrolls (alongside your
9
+ * `ref={scrollRef}`):
10
+ *
11
+ * ```tsx
12
+ * const { scrollProps } = useTourScroll();
13
+ * <ScrollView ref={scrollRef} {...scrollProps}>…</ScrollView>
14
+ * ```
15
+ */
16
+ scrollProps: {
17
+ onScroll: (e: NativeSyntheticEvent<NativeScrollEvent>) => void;
18
+ onMomentumScrollEnd: () => void;
19
+ scrollEventThrottle: number;
20
+ };
21
+ /** The individual handlers, for composing with your own. */
22
+ onScroll: (e: NativeSyntheticEvent<NativeScrollEvent>) => void;
23
+ onMomentumScrollEnd: () => void;
24
+ }
25
+
26
+ /**
27
+ * Binds a scrollable to the tour. Wiring this up gives the tour three things:
28
+ *
29
+ * 1. **`followTarget`** — with `config.followTarget: true`, the spotlight and
30
+ * tooltip stay glued to the target while the user scrolls freely.
31
+ * 2. **Exact auto-scroll settling** — `onMomentumScrollEnd` tells the tour the
32
+ * programmatic scroll finished, so the highlight lands immediately instead
33
+ * of waiting for position polling to detect the stop.
34
+ * 3. **A tracked scroll offset** — `getCurrentScrollOffset` becomes redundant;
35
+ * the tour reads the offset it saw last.
36
+ *
37
+ * Already have your own onScroll? Compose: call both handlers, or spread
38
+ * `scrollProps` and call your handler from a wrapper.
39
+ */
40
+ export const useTourScroll = (): TourScrollBinding => {
41
+ const { __reportScroll, __reportScrollEnd } = useTourGuide();
42
+
43
+ const onScroll = useCallback(
44
+ (e: NativeSyntheticEvent<NativeScrollEvent>) => {
45
+ __reportScroll?.(e.nativeEvent.contentOffset.y);
46
+ },
47
+ [__reportScroll]
48
+ );
49
+
50
+ const onMomentumScrollEnd = useCallback(() => {
51
+ __reportScrollEnd?.();
52
+ }, [__reportScrollEnd]);
53
+
54
+ const scrollProps = useMemo(
55
+ () => ({ onScroll, onMomentumScrollEnd, scrollEventThrottle: 16 }),
56
+ [onScroll, onMomentumScrollEnd]
57
+ );
58
+
59
+ return { scrollProps, onScroll, onMomentumScrollEnd };
60
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,401 @@
1
+ import { StyleSheet, Platform, StatusBar } from 'react-native';
2
+ import type { ViewStyle } from 'react-native';
3
+
4
+ import type {
5
+ EdgeInsets,
6
+ MeasurableRef,
7
+ OSConfig,
8
+ PerPlatform,
9
+ ResolvedTourGuideConfig,
10
+ SpotlightTarget,
11
+ TourGuideConfig,
12
+ } from './types';
13
+ import { warnOnce } from './dev';
14
+ import type { SpotlightBorderRadius } from './shapes';
15
+
16
+ const ZERO_INSETS: EdgeInsets = { top: 0, bottom: 0, left: 0, right: 0 };
17
+
18
+ /**
19
+ * Compute the best tooltip position based on available screen space.
20
+ * Prefers: bottom > top > right > left.
21
+ * `insets` shrink the usable area so the tour avoids system chrome.
22
+ */
23
+ interface TooltipPositionOptions {
24
+ target: SpotlightTarget;
25
+ screenWidth: number;
26
+ screenHeight: number;
27
+ tooltipWidth: number;
28
+ tooltipHeight?: number;
29
+ offset?: number;
30
+ insets?: EdgeInsets;
31
+ }
32
+
33
+ export const computeTooltipPosition = ({
34
+ target,
35
+ screenWidth,
36
+ screenHeight,
37
+ tooltipWidth,
38
+ tooltipHeight = 150,
39
+ offset = 20,
40
+ insets = ZERO_INSETS,
41
+ }: TooltipPositionOptions): 'top' | 'bottom' | 'left' | 'right' => {
42
+ const spaceAbove = target.y - offset - insets.top;
43
+ const spaceBelow = screenHeight - insets.bottom - (target.y + target.height + offset);
44
+ const spaceLeft = target.x - offset - insets.left;
45
+ const spaceRight = screenWidth - insets.right - (target.x + target.width + offset);
46
+
47
+ if (spaceBelow >= tooltipHeight) return 'bottom';
48
+ if (spaceAbove >= tooltipHeight) return 'top';
49
+ if (spaceRight >= tooltipWidth * 0.6) return 'right';
50
+ if (spaceLeft >= tooltipWidth * 0.6) return 'left';
51
+
52
+ return spaceBelow >= spaceAbove ? 'bottom' : 'top';
53
+ };
54
+
55
+ // Cache the safe-area lookup from react-native-safe-area-context (optional dep).
56
+ // `undefined` = not resolved yet, `null` = lib unavailable.
57
+ let _autoInsets: EdgeInsets | null | undefined;
58
+
59
+ const getAutoInsets = (): EdgeInsets => {
60
+ if (_autoInsets === undefined) {
61
+ try {
62
+ // initialWindowMetrics is a synchronous snapshot — no hook required, so
63
+ // this works from plain functions and is set once at app launch.
64
+
65
+ const mod = require('react-native-safe-area-context');
66
+ const metricsInsets = mod?.initialWindowMetrics?.insets;
67
+ _autoInsets = metricsInsets
68
+ ? {
69
+ top: metricsInsets.top ?? 0,
70
+ bottom: metricsInsets.bottom ?? 0,
71
+ left: metricsInsets.left ?? 0,
72
+ right: metricsInsets.right ?? 0,
73
+ }
74
+ : null;
75
+ } catch {
76
+ _autoInsets = null;
77
+ }
78
+ }
79
+ if (_autoInsets) return _autoInsets;
80
+ // Fallback: Android status-bar height for the top edge; nothing reliable for
81
+ // the bottom without the safe-area lib, so consumers should pass `insets`.
82
+ const top = Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) : 0;
83
+ return { top, bottom: 0, left: 0, right: 0 };
84
+ };
85
+
86
+ /**
87
+ * Resolve just the safe-area insets (auto-detected, or overridden via
88
+ * `config.insets`) — WITHOUT any `extraInsets`. This is the value that mirrors
89
+ * system chrome like the status bar, and is what corrects `measureInWindow`
90
+ * coordinates on Android (see TourGuideOverlay).
91
+ */
92
+ export const resolveSafeAreaInsets = (config?: { insets?: Partial<EdgeInsets> }): EdgeInsets => {
93
+ const auto = getAutoInsets();
94
+ return {
95
+ top: config?.insets?.top ?? auto.top,
96
+ bottom: config?.insets?.bottom ?? auto.bottom,
97
+ left: config?.insets?.left ?? auto.left,
98
+ right: config?.insets?.right ?? auto.right,
99
+ };
100
+ };
101
+
102
+ /**
103
+ * Resolve the effective insets the tour should respect for layout/clamping:
104
+ * the safe area plus any `config.extraInsets` for app chrome like tab bars and
105
+ * headers.
106
+ */
107
+ export const resolveInsets = (config?: {
108
+ insets?: Partial<EdgeInsets>;
109
+ extraInsets?: Partial<EdgeInsets>;
110
+ }): EdgeInsets => {
111
+ const base = resolveSafeAreaInsets(config);
112
+ const extra = config?.extraInsets;
113
+ return {
114
+ top: base.top + (extra?.top ?? 0),
115
+ bottom: base.bottom + (extra?.bottom ?? 0),
116
+ left: base.left + (extra?.left ?? 0),
117
+ right: base.right + (extra?.right ?? 0),
118
+ };
119
+ };
120
+
121
+ /**
122
+ * Validate that a ref is valid and points to a mounted component.
123
+ * Returns true if valid, false otherwise.
124
+ */
125
+ export const validateRef = (ref: MeasurableRef | undefined, stepId: string): boolean => {
126
+ // No ref at all is an intentional, supported case: a centered tooltip with no
127
+ // spotlight (e.g. a welcome/finish step). Don't warn — it's not a mistake.
128
+ if (!ref) {
129
+ return false;
130
+ }
131
+
132
+ // A ref was provided but points to nothing — this usually IS a mistake
133
+ // (component not mounted yet / wrong ref), so it's worth a dev warning.
134
+ if (!ref.current) {
135
+ warnOnce(
136
+ `Step "${stepId}" has a targetRef whose .current is null, so there is nothing to highlight. Showing a centered tooltip instead.`,
137
+ 'Attach the ref to a rendered host component (e.g. <View ref={ref}>) and make sure it is mounted before startTour() runs.'
138
+ );
139
+ return false;
140
+ }
141
+
142
+ return true;
143
+ };
144
+
145
+ /**
146
+ * Extract border radius values from a View style.
147
+ * Returns a SpotlightBorderRadius (number if uniform, object if per-corner),
148
+ * or undefined if no border radius is specified.
149
+ *
150
+ * Percentage radii (e.g. `'50%'`, supported by React Native 0.76+) are resolved
151
+ * against the target's shorter side when `target` dimensions are provided — this
152
+ * is what keeps a circular avatar (`borderRadius: '50%'`) round instead of square.
153
+ * Without `target`, percentages fall back to the numeric base/0.
154
+ */
155
+ export const extractBorderRadius = (
156
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
157
+ style: any,
158
+ target?: { width: number; height: number }
159
+ ): SpotlightBorderRadius | undefined => {
160
+ if (!style) return undefined;
161
+
162
+ const flat = StyleSheet.flatten(style) as ViewStyle | undefined;
163
+ if (!flat) return undefined;
164
+
165
+ const {
166
+ borderRadius,
167
+ borderTopLeftRadius,
168
+ borderTopRightRadius,
169
+ borderBottomLeftRadius,
170
+ borderBottomRightRadius,
171
+ } = flat;
172
+
173
+ // No border radius properties at all
174
+ if (
175
+ borderRadius === undefined &&
176
+ borderTopLeftRadius === undefined &&
177
+ borderTopRightRadius === undefined &&
178
+ borderBottomLeftRadius === undefined &&
179
+ borderBottomRightRadius === undefined
180
+ ) {
181
+ return undefined;
182
+ }
183
+
184
+ // The shorter side: a radius of `minDim / 2` produces a circle (square target)
185
+ // or a pill (rectangular target), which is exactly how RN renders `'50%'`.
186
+ const minDim = target ? Math.min(target.width, target.height) : 0;
187
+
188
+ // Coerce to a number, resolving percentage strings against the target.
189
+ const toNum = (v: string | number | undefined, fallback: number): number => {
190
+ if (typeof v === 'number') return v;
191
+ if (typeof v === 'string') {
192
+ const trimmed = v.trim();
193
+ if (trimmed.endsWith('%')) {
194
+ const pct = parseFloat(trimmed);
195
+ if (!Number.isNaN(pct) && minDim > 0) return (pct / 100) * minDim;
196
+ }
197
+ }
198
+ return fallback;
199
+ };
200
+
201
+ const base = toNum(borderRadius, 0);
202
+ const tl = toNum(borderTopLeftRadius, base);
203
+ const tr = toNum(borderTopRightRadius, base);
204
+ const br = toNum(borderBottomRightRadius, base);
205
+ const bl = toNum(borderBottomLeftRadius, base);
206
+
207
+ // All corners the same → return number for smooth rect animation
208
+ if (tl === tr && tr === br && br === bl) {
209
+ return tl;
210
+ }
211
+
212
+ return { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl };
213
+ };
214
+
215
+ /**
216
+ * Scroll a scrollable ref to an absolute Y offset.
217
+ *
218
+ * Consumers pass all kinds of scrollables, and each exposes a different imperative
219
+ * API — assuming `scrollTo` crashes with `scrollTo is not a function` on the most
220
+ * common one (`FlatList`). This normalises across:
221
+ *
222
+ * - `ScrollView` (and gesture-handler / Animated wrappers) → `scrollTo`
223
+ * - `FlatList` / `VirtualizedList` → `scrollToOffset`
224
+ * - `SectionList` and other list wrappers → `getScrollResponder()` / `getScrollRef()`
225
+ * - legacy `Animated.ScrollView` → `getNode()`
226
+ * - `KeyboardAwareScrollView` → `scrollToPosition`
227
+ *
228
+ * @returns true if a scroll was actually issued, false if the ref exposes no
229
+ * usable scroll method (the caller should then continue without scrolling
230
+ * rather than leaving the tour stuck).
231
+ */
232
+ export const scrollRefToY = (
233
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
234
+ scrollRef: { current: any } | null | undefined,
235
+ y: number,
236
+ animated: boolean
237
+ ): boolean => {
238
+ const node = scrollRef?.current;
239
+ if (!node) return false;
240
+
241
+ const targetY = Math.max(0, y);
242
+
243
+ // Unwrap legacy Animated.ScrollView / list wrappers that hide the real
244
+ // scrollable behind a getter.
245
+ const candidates = [node];
246
+ for (const getter of ['getNode', 'getScrollResponder', 'getScrollRef'] as const) {
247
+ try {
248
+ if (typeof node[getter] === 'function') {
249
+ const inner = node[getter]();
250
+ if (inner) candidates.push(inner);
251
+ }
252
+ } catch {
253
+ // A getter that throws (unmounted inner list) is not usable — skip it.
254
+ }
255
+ }
256
+
257
+ for (const c of candidates) {
258
+ try {
259
+ if (typeof c.scrollTo === 'function') {
260
+ c.scrollTo({ x: 0, y: targetY, animated });
261
+ return true;
262
+ }
263
+ if (typeof c.scrollToOffset === 'function') {
264
+ c.scrollToOffset({ offset: targetY, animated });
265
+ return true;
266
+ }
267
+ if (typeof c.scrollToPosition === 'function') {
268
+ c.scrollToPosition(0, targetY, animated);
269
+ return true;
270
+ }
271
+ } catch {
272
+ // Try the next candidate rather than taking the whole tour down.
273
+ }
274
+ }
275
+
276
+ return false;
277
+ };
278
+
279
+ // ─── Color parsing for readable-by-default tooltips ──────────────────────────
280
+
281
+ const NAMED_COLORS: Record<string, string> = {
282
+ white: '#ffffff',
283
+ black: '#000000',
284
+ gray: '#808080',
285
+ grey: '#808080',
286
+ red: '#ff0000',
287
+ blue: '#0000ff',
288
+ green: '#008000',
289
+ yellow: '#ffff00',
290
+ orange: '#ffa500',
291
+ purple: '#800080',
292
+ transparent: '#00000000',
293
+ };
294
+
295
+ /**
296
+ * Whether a background color is light (true), dark (false), or unparseable
297
+ * (null). Supports #rgb/#rgba/#rrggbb/#rrggbbaa, rgb()/rgba(), and a handful of
298
+ * common named colors — enough for the tooltip-background use case; anything
299
+ * exotic returns null and callers keep their existing defaults.
300
+ *
301
+ * Used to pick readable default text colors when a consumer sets a custom
302
+ * tooltip background: a pale background used to get the built-in white title
303
+ * text, which is invisible.
304
+ */
305
+ export const isLightColor = (color: string): boolean | null => {
306
+ if (typeof color !== 'string') return null;
307
+ let c = color.trim().toLowerCase();
308
+ c = NAMED_COLORS[c] ?? c;
309
+
310
+ let r: number, g: number, b: number;
311
+
312
+ const rgbMatch = c.match(/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/);
313
+ if (rgbMatch) {
314
+ r = parseFloat(rgbMatch[1] as string);
315
+ g = parseFloat(rgbMatch[2] as string);
316
+ b = parseFloat(rgbMatch[3] as string);
317
+ } else if (/^#[0-9a-f]{3,8}$/.test(c)) {
318
+ const hex = c.slice(1);
319
+ if (hex.length === 3 || hex.length === 4) {
320
+ r = parseInt((hex[0] as string) + hex[0], 16);
321
+ g = parseInt((hex[1] as string) + hex[1], 16);
322
+ b = parseInt((hex[2] as string) + hex[2], 16);
323
+ } else if (hex.length === 6 || hex.length === 8) {
324
+ r = parseInt(hex.slice(0, 2), 16);
325
+ g = parseInt(hex.slice(2, 4), 16);
326
+ b = parseInt(hex.slice(4, 6), 16);
327
+ } else {
328
+ return null;
329
+ }
330
+ } else {
331
+ return null;
332
+ }
333
+
334
+ if ([r, g, b].some((v) => Number.isNaN(v) || v < 0 || v > 255)) return null;
335
+
336
+ // Perceived brightness (ITU-R BT.601), same scale tinycolor uses: 0-255.
337
+ const brightness = (r * 299 + g * 587 + b * 114) / 1000;
338
+ return brightness > 180;
339
+ };
340
+
341
+ // ─── Per-platform config values ──────────────────────────────────────────────
342
+
343
+ const OS_KEYS = new Set(['ios', 'android', 'web', 'default']);
344
+
345
+ const isOSConfig = (value: unknown): value is OSConfig<unknown> => {
346
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
347
+ const keys = Object.keys(value);
348
+ return keys.length > 0 && keys.every((k) => OS_KEYS.has(k));
349
+ };
350
+
351
+ /**
352
+ * Resolve a possibly per-platform value for the running OS.
353
+ * `{ ios: 12, default: 8 }` → 12 on iOS, 8 elsewhere.
354
+ */
355
+ export const osValue = <T>(value: PerPlatform<T> | undefined): T | undefined => {
356
+ if (value === undefined || !isOSConfig(value)) return value as T | undefined;
357
+ const perOS = value as OSConfig<T>;
358
+ return (perOS as Record<string, T | undefined>)[Platform.OS] ?? perOS.default;
359
+ };
360
+
361
+ // A typo'd OS key ({ iOS: 320 } or { web: 12, macos: 10 }) makes the object
362
+ // fail the OS-config signature check, so it passes through UNRESOLVED and
363
+ // reaches layout math as a raw object. Diagnose that in dev.
364
+ const warnIfMalformedOSConfig = (field: string, value: unknown): void => {
365
+ if (typeof value !== 'object' || value === null || Array.isArray(value) || isOSConfig(value)) {
366
+ return;
367
+ }
368
+ const keys = Object.keys(value);
369
+ // Only flag objects that LOOK like an attempted per-platform value.
370
+ if (keys.some((k) => OS_KEYS.has(k)) || keys.some((k) => /^(ios|android|web)$/i.test(k))) {
371
+ warnOnce(
372
+ `config.${field} looks like a per-platform value but has unrecognised keys (${keys.join(', ')}), so it was not resolved.`,
373
+ 'Use exactly { ios, android, web, default } — lowercase — e.g. { ios: 320, default: 300 }.'
374
+ );
375
+ }
376
+ };
377
+
378
+ /**
379
+ * Resolve every PerPlatform field of a tour config for the running OS.
380
+ * Called once in startTour, so everything downstream reads plain values.
381
+ */
382
+ export const resolvePlatformConfig = (
383
+ config: TourGuideConfig | undefined
384
+ ): ResolvedTourGuideConfig | undefined => {
385
+ if (!config) return config;
386
+ warnIfMalformedOSConfig('animationDuration', config.animationDuration);
387
+ warnIfMalformedOSConfig('motion', config.motion);
388
+ warnIfMalformedOSConfig('safeZoneOffset', config.safeZoneOffset);
389
+ warnIfMalformedOSConfig('tooltipWidth', config.tooltipWidth);
390
+ warnIfMalformedOSConfig('triangleSize', config.triangleSize);
391
+ warnIfMalformedOSConfig('tooltipOffset', config.tooltipOffset);
392
+ return {
393
+ ...config,
394
+ animationDuration: osValue(config.animationDuration),
395
+ motion: osValue(config.motion),
396
+ safeZoneOffset: osValue(config.safeZoneOffset),
397
+ tooltipWidth: osValue(config.tooltipWidth),
398
+ triangleSize: osValue(config.triangleSize),
399
+ tooltipOffset: osValue(config.tooltipOffset),
400
+ };
401
+ };