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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +993 -2
  3. package/lib/commonjs/SpotlightOverlay.js +712 -0
  4. package/lib/commonjs/SpotlightOverlay.js.map +1 -0
  5. package/lib/commonjs/Tooltip.js +593 -0
  6. package/lib/commonjs/Tooltip.js.map +1 -0
  7. package/lib/commonjs/TourGuideContext.js +535 -0
  8. package/lib/commonjs/TourGuideContext.js.map +1 -0
  9. package/lib/commonjs/TourGuideOverlay.js +1173 -0
  10. package/lib/commonjs/TourGuideOverlay.js.map +1 -0
  11. package/lib/commonjs/TourTarget.js +80 -0
  12. package/lib/commonjs/TourTarget.js.map +1 -0
  13. package/lib/commonjs/accessibility.js +49 -0
  14. package/lib/commonjs/accessibility.js.map +1 -0
  15. package/lib/commonjs/dev.js +48 -0
  16. package/lib/commonjs/dev.js.map +1 -0
  17. package/lib/commonjs/events.js +56 -0
  18. package/lib/commonjs/events.js.map +1 -0
  19. package/lib/commonjs/index.js +169 -0
  20. package/lib/commonjs/index.js.map +1 -0
  21. package/lib/commonjs/package.json +1 -0
  22. package/lib/commonjs/shapes.js +158 -0
  23. package/lib/commonjs/shapes.js.map +1 -0
  24. package/lib/commonjs/storage.js +116 -0
  25. package/lib/commonjs/storage.js.map +1 -0
  26. package/lib/commonjs/themes.js +86 -0
  27. package/lib/commonjs/themes.js.map +1 -0
  28. package/lib/commonjs/types.js +6 -0
  29. package/lib/commonjs/types.js.map +1 -0
  30. package/lib/commonjs/useTourPersistence.js +135 -0
  31. package/lib/commonjs/useTourPersistence.js.map +1 -0
  32. package/lib/commonjs/useTourScroll.js +46 -0
  33. package/lib/commonjs/useTourScroll.js.map +1 -0
  34. package/lib/commonjs/utils.js +372 -0
  35. package/lib/commonjs/utils.js.map +1 -0
  36. package/lib/commonjs/validation.js +143 -0
  37. package/lib/commonjs/validation.js.map +1 -0
  38. package/lib/module/SpotlightOverlay.js +707 -0
  39. package/lib/module/SpotlightOverlay.js.map +1 -0
  40. package/lib/module/Tooltip.js +588 -0
  41. package/lib/module/Tooltip.js.map +1 -0
  42. package/lib/module/TourGuideContext.js +529 -0
  43. package/lib/module/TourGuideContext.js.map +1 -0
  44. package/lib/module/TourGuideOverlay.js +1167 -0
  45. package/lib/module/TourGuideOverlay.js.map +1 -0
  46. package/lib/module/TourTarget.js +74 -0
  47. package/lib/module/TourTarget.js.map +1 -0
  48. package/lib/module/accessibility.js +43 -0
  49. package/lib/module/accessibility.js.map +1 -0
  50. package/lib/module/dev.js +40 -0
  51. package/lib/module/dev.js.map +1 -0
  52. package/lib/module/events.js +51 -0
  53. package/lib/module/events.js.map +1 -0
  54. package/lib/module/index.js +25 -0
  55. package/lib/module/index.js.map +1 -0
  56. package/lib/module/package.json +1 -0
  57. package/lib/module/shapes.js +152 -0
  58. package/lib/module/shapes.js.map +1 -0
  59. package/lib/module/storage.js +111 -0
  60. package/lib/module/storage.js.map +1 -0
  61. package/lib/module/themes.js +81 -0
  62. package/lib/module/themes.js.map +1 -0
  63. package/lib/module/types.js +4 -0
  64. package/lib/module/types.js.map +1 -0
  65. package/lib/module/useTourPersistence.js +130 -0
  66. package/lib/module/useTourPersistence.js.map +1 -0
  67. package/lib/module/useTourScroll.js +41 -0
  68. package/lib/module/useTourScroll.js.map +1 -0
  69. package/lib/module/utils.js +361 -0
  70. package/lib/module/utils.js.map +1 -0
  71. package/lib/module/validation.js +138 -0
  72. package/lib/module/validation.js.map +1 -0
  73. package/lib/typescript/commonjs/package.json +1 -0
  74. package/lib/typescript/commonjs/src/SpotlightOverlay.d.ts +46 -0
  75. package/lib/typescript/commonjs/src/SpotlightOverlay.d.ts.map +1 -0
  76. package/lib/typescript/commonjs/src/Tooltip.d.ts +9 -0
  77. package/lib/typescript/commonjs/src/Tooltip.d.ts.map +1 -0
  78. package/lib/typescript/commonjs/src/TourGuideContext.d.ts +46 -0
  79. package/lib/typescript/commonjs/src/TourGuideContext.d.ts.map +1 -0
  80. package/lib/typescript/commonjs/src/TourGuideOverlay.d.ts +22 -0
  81. package/lib/typescript/commonjs/src/TourGuideOverlay.d.ts.map +1 -0
  82. package/lib/typescript/commonjs/src/TourTarget.d.ts +36 -0
  83. package/lib/typescript/commonjs/src/TourTarget.d.ts.map +1 -0
  84. package/lib/typescript/commonjs/src/accessibility.d.ts +22 -0
  85. package/lib/typescript/commonjs/src/accessibility.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/src/dev.d.ts +22 -0
  87. package/lib/typescript/commonjs/src/dev.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/src/events.d.ts +57 -0
  89. package/lib/typescript/commonjs/src/events.d.ts.map +1 -0
  90. package/lib/typescript/commonjs/src/index.d.ts +21 -0
  91. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/src/shapes.d.ts +50 -0
  93. package/lib/typescript/commonjs/src/shapes.d.ts.map +1 -0
  94. package/lib/typescript/commonjs/src/storage.d.ts +15 -0
  95. package/lib/typescript/commonjs/src/storage.d.ts.map +1 -0
  96. package/lib/typescript/commonjs/src/themes.d.ts +10 -0
  97. package/lib/typescript/commonjs/src/themes.d.ts.map +1 -0
  98. package/lib/typescript/commonjs/src/types.d.ts +599 -0
  99. package/lib/typescript/commonjs/src/types.d.ts.map +1 -0
  100. package/lib/typescript/commonjs/src/useTourPersistence.d.ts +63 -0
  101. package/lib/typescript/commonjs/src/useTourPersistence.d.ts.map +1 -0
  102. package/lib/typescript/commonjs/src/useTourScroll.d.ts +36 -0
  103. package/lib/typescript/commonjs/src/useTourScroll.d.ts.map +1 -0
  104. package/lib/typescript/commonjs/src/utils.d.ts +97 -0
  105. package/lib/typescript/commonjs/src/utils.d.ts.map +1 -0
  106. package/lib/typescript/commonjs/src/validation.d.ts +11 -0
  107. package/lib/typescript/commonjs/src/validation.d.ts.map +1 -0
  108. package/lib/typescript/module/package.json +1 -0
  109. package/lib/typescript/module/src/SpotlightOverlay.d.ts +46 -0
  110. package/lib/typescript/module/src/SpotlightOverlay.d.ts.map +1 -0
  111. package/lib/typescript/module/src/Tooltip.d.ts +9 -0
  112. package/lib/typescript/module/src/Tooltip.d.ts.map +1 -0
  113. package/lib/typescript/module/src/TourGuideContext.d.ts +46 -0
  114. package/lib/typescript/module/src/TourGuideContext.d.ts.map +1 -0
  115. package/lib/typescript/module/src/TourGuideOverlay.d.ts +22 -0
  116. package/lib/typescript/module/src/TourGuideOverlay.d.ts.map +1 -0
  117. package/lib/typescript/module/src/TourTarget.d.ts +36 -0
  118. package/lib/typescript/module/src/TourTarget.d.ts.map +1 -0
  119. package/lib/typescript/module/src/accessibility.d.ts +22 -0
  120. package/lib/typescript/module/src/accessibility.d.ts.map +1 -0
  121. package/lib/typescript/module/src/dev.d.ts +22 -0
  122. package/lib/typescript/module/src/dev.d.ts.map +1 -0
  123. package/lib/typescript/module/src/events.d.ts +57 -0
  124. package/lib/typescript/module/src/events.d.ts.map +1 -0
  125. package/lib/typescript/module/src/index.d.ts +21 -0
  126. package/lib/typescript/module/src/index.d.ts.map +1 -0
  127. package/lib/typescript/module/src/shapes.d.ts +50 -0
  128. package/lib/typescript/module/src/shapes.d.ts.map +1 -0
  129. package/lib/typescript/module/src/storage.d.ts +15 -0
  130. package/lib/typescript/module/src/storage.d.ts.map +1 -0
  131. package/lib/typescript/module/src/themes.d.ts +10 -0
  132. package/lib/typescript/module/src/themes.d.ts.map +1 -0
  133. package/lib/typescript/module/src/types.d.ts +599 -0
  134. package/lib/typescript/module/src/types.d.ts.map +1 -0
  135. package/lib/typescript/module/src/useTourPersistence.d.ts +63 -0
  136. package/lib/typescript/module/src/useTourPersistence.d.ts.map +1 -0
  137. package/lib/typescript/module/src/useTourScroll.d.ts +36 -0
  138. package/lib/typescript/module/src/useTourScroll.d.ts.map +1 -0
  139. package/lib/typescript/module/src/utils.d.ts +97 -0
  140. package/lib/typescript/module/src/utils.d.ts.map +1 -0
  141. package/lib/typescript/module/src/validation.d.ts +11 -0
  142. package/lib/typescript/module/src/validation.d.ts.map +1 -0
  143. package/llms.txt +62 -0
  144. package/package.json +281 -4
  145. package/src/SpotlightOverlay.tsx +742 -0
  146. package/src/Tooltip.tsx +638 -0
  147. package/src/TourGuideContext.tsx +644 -0
  148. package/src/TourGuideOverlay.tsx +1382 -0
  149. package/src/TourTarget.tsx +74 -0
  150. package/src/accessibility.ts +60 -0
  151. package/src/dev.ts +39 -0
  152. package/src/events.ts +76 -0
  153. package/src/index.tsx +64 -0
  154. package/src/shapes.ts +184 -0
  155. package/src/storage.ts +114 -0
  156. package/src/themes.ts +83 -0
  157. package/src/types.ts +648 -0
  158. package/src/useTourPersistence.ts +147 -0
  159. package/src/useTourScroll.ts +60 -0
  160. package/src/utils.ts +401 -0
  161. package/src/validation.ts +248 -0
@@ -0,0 +1,74 @@
1
+ import React, { useEffect, useRef } from 'react';
2
+ import { View } from 'react-native';
3
+ import type { StyleProp, ViewStyle } from 'react-native';
4
+
5
+ import { useTourGuide } from './TourGuideContext';
6
+
7
+ export interface TourTargetProps {
8
+ /** Unique id steps reference via `targetId` */
9
+ id: string;
10
+ children: React.ReactNode;
11
+ /**
12
+ * Style for the wrapper View. Border radius set here is auto-extracted for
13
+ * spotlight shape matching, exactly like a step's `targetStyle`.
14
+ */
15
+ style?: StyleProp<ViewStyle>;
16
+ }
17
+
18
+ /**
19
+ * Declaratively mark a component as a tour target — the alternative to
20
+ * threading refs into your steps array.
21
+ *
22
+ * Wraps its children in a View (with `collapsable={false}`, so Android's view
23
+ * flattening can never make the target unmeasurable) and registers it with the
24
+ * provider. Steps then reference it by id:
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * <TourTarget id="compose" style={{ borderRadius: 24 }}>
29
+ * <ComposeButton />
30
+ * </TourTarget>
31
+ *
32
+ * startTour([{ id: 'step1', targetId: 'compose', title: '…', description: '…' }]);
33
+ * ```
34
+ *
35
+ * The wrapper carries no styles of its own, so layout is unchanged unless you
36
+ * pass `style`. If the target mounts after the tour starts (a later screen),
37
+ * the tour waits briefly for it to register before falling back to a centered
38
+ * tooltip.
39
+ */
40
+ export const TourTarget: React.FC<TourTargetProps> = ({ id, children, style }) => {
41
+ const { registerTarget, unregisterTarget, getTarget } = useTourGuide();
42
+ const ref = useRef<React.ComponentRef<typeof View>>(null);
43
+
44
+ // Keep the registered style current without re-registering: inline styles get
45
+ // a new identity every render, so re-registering on style change would churn
46
+ // the registry — instead the entry is updated in place, so shape extraction
47
+ // always reads the latest style (e.g. a borderRadius that animates on state).
48
+ useEffect(() => {
49
+ const entry = getTarget(id);
50
+ if (entry && entry.ref === ref) {
51
+ entry.style = style;
52
+ }
53
+ });
54
+
55
+ useEffect(() => {
56
+ registerTarget(id, ref, style);
57
+ // Pass our ref so an unmounting duplicate never clobbers a still-mounted
58
+ // TourTarget that re-registered the same id.
59
+ return () => unregisterTarget(id, ref);
60
+ // `style` is intentionally not a dep: identity changes every render for
61
+ // inline styles, and re-registering would churn the registry. The style is
62
+ // read through the registry at measure time, so keeping the first
63
+ // registration's reference is fine for shape extraction.
64
+ // eslint-disable-next-line react-hooks/exhaustive-deps
65
+ }, [id, registerTarget, unregisterTarget]);
66
+
67
+ return (
68
+ // collapsable={false} — Android flattens layout-only Views, which would
69
+ // leave nothing to measure and silently produce a 0x0 target.
70
+ <View ref={ref} collapsable={false} style={style}>
71
+ {children}
72
+ </View>
73
+ );
74
+ };
@@ -0,0 +1,60 @@
1
+ import { AccessibilityInfo, Platform } from 'react-native';
2
+
3
+ import type { TourStep, TourGuideConfig } from './types';
4
+
5
+ /**
6
+ * Announce a step change to screen readers (VoiceOver / TalkBack).
7
+ */
8
+ export const announceStep = (
9
+ step: TourStep,
10
+ stepIndex: number,
11
+ totalSteps: number,
12
+ config?: TourGuideConfig
13
+ ) => {
14
+ const enabled = config?.enableAccessibility !== false;
15
+ if (!enabled) return;
16
+
17
+ const prefix = config?.accessibilityLabelPrefix ?? 'Tour guide';
18
+
19
+ // Use custom label if provided, otherwise build from title/description
20
+ const label =
21
+ step.accessibilityLabel ??
22
+ `${prefix}, step ${stepIndex + 1} of ${totalSteps}. ${step.title}. ${step.description}`;
23
+
24
+ // Small delay to ensure the UI has updated before announcing
25
+ setTimeout(() => {
26
+ // announceForAccessibility is not available on web — use ARIA live regions instead
27
+ if (Platform.OS !== 'web' && typeof AccessibilityInfo.announceForAccessibility === 'function') {
28
+ AccessibilityInfo.announceForAccessibility(label);
29
+ }
30
+ }, 100);
31
+ };
32
+
33
+ /**
34
+ * Build the accessibility label for the tooltip container.
35
+ */
36
+ export const getTooltipAccessibilityProps = (
37
+ step: TourStep,
38
+ stepIndex: number,
39
+ totalSteps: number,
40
+ config?: TourGuideConfig
41
+ ) => {
42
+ const enabled = config?.enableAccessibility !== false;
43
+ if (!enabled) return {};
44
+
45
+ const prefix = config?.accessibilityLabelPrefix ?? 'Tour guide';
46
+
47
+ return {
48
+ accessible: true,
49
+ accessibilityRole: 'alert' as const,
50
+ accessibilityLabel:
51
+ step.accessibilityLabel ??
52
+ `${prefix}, step ${stepIndex + 1} of ${totalSteps}. ${step.title}. ${step.description}`,
53
+ accessibilityHint: Platform.select({
54
+ ios: 'Swipe right for next step, left for previous',
55
+ android: 'Use the buttons to navigate the tour',
56
+ default: 'Use the buttons to navigate the tour',
57
+ }),
58
+ accessibilityLiveRegion: 'polite' as const,
59
+ };
60
+ };
package/src/dev.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Dev-only diagnostics.
3
+ *
4
+ * Every warning the library emits goes through here so that:
5
+ * - it is stripped in production builds (`__DEV__` is false), keeping consumer
6
+ * release logs and crash-reporting breadcrumbs clean;
7
+ * - it is de-duplicated, so a warning inside a render/measure loop is printed
8
+ * once instead of on every frame;
9
+ * - it always carries the package name and an actionable "how to fix" line.
10
+ */
11
+
12
+ const PREFIX = 'react-native-tour-guide';
13
+
14
+ /** True in development. Falls back to NODE_ENV outside React Native (e.g. tests, web SSR). */
15
+ export const isDev = (): boolean =>
16
+ typeof __DEV__ !== 'undefined' ? __DEV__ : process.env.NODE_ENV !== 'production';
17
+
18
+ const seen = new Set<string>();
19
+
20
+ /**
21
+ * Print a dev-only warning at most once per unique message.
22
+ * `fix` is appended as a concrete next step for whoever reads the log.
23
+ */
24
+ export const warnOnce = (message: string, fix?: string) => {
25
+ if (!isDev()) return;
26
+ const text = fix ? `${PREFIX}: ${message}\n → Fix: ${fix}` : `${PREFIX}: ${message}`;
27
+ if (seen.has(text)) return;
28
+ seen.add(text);
29
+ console.warn(text);
30
+ };
31
+
32
+ /** Print a dev-only warning every time (for genuinely per-occurrence problems). */
33
+ export const warn = (message: string, fix?: string) => {
34
+ if (!isDev()) return;
35
+ console.warn(fix ? `${PREFIX}: ${message}\n → Fix: ${fix}` : `${PREFIX}: ${message}`);
36
+ };
37
+
38
+ /** Test-only: clear the de-duplication cache so each test starts clean. */
39
+ export const __resetWarnings = () => seen.clear();
package/src/events.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { TourStep } from './types';
2
+
3
+ /**
4
+ * Events emitted over the tour's lifecycle, with their payloads.
5
+ * Subscribe via `useTourGuide().events.on(...)` — the subscription-based
6
+ * alternative to config callbacks, built for analytics: attach once at app
7
+ * root instead of threading onTourStart/onStepChange through every config.
8
+ */
9
+ export interface TourEventMap {
10
+ /** A tour started */
11
+ start: { tourId?: string; totalSteps: number };
12
+ /** The step changed (next, back, or a goToStep jump). `to` is the new index. */
13
+ stepChange: { from: number; to: number; step?: TourStep };
14
+ /** The tour ended — completed=true when the user finished the last step */
15
+ end: { completed: boolean; tourId?: string };
16
+ /** The user skipped the tour (an `end` with completed=false follows) */
17
+ skip: { at: number };
18
+ /** The tour was paused */
19
+ pause: { at: number };
20
+ /** The tour was resumed */
21
+ resume: { at: number };
22
+ }
23
+
24
+ export type TourEventName = keyof TourEventMap;
25
+ export type TourEventHandler<K extends TourEventName> = (payload: TourEventMap[K]) => void;
26
+
27
+ /** The public subscription surface exposed on the context as `events`. */
28
+ export interface TourEvents {
29
+ /** Subscribe. Returns an unsubscribe function. */
30
+ on<K extends TourEventName>(event: K, handler: TourEventHandler<K>): () => void;
31
+ /** Remove a previously added handler. */
32
+ off<K extends TourEventName>(event: K, handler: TourEventHandler<K>): void;
33
+ }
34
+
35
+ /** @internal The provider-side emitter (public surface + emit). */
36
+ export interface TourEventsInternal extends TourEvents {
37
+ emit<K extends TourEventName>(event: K, payload: TourEventMap[K]): void;
38
+ }
39
+
40
+ /**
41
+ * A tiny dependency-free emitter. A throwing handler is isolated — analytics
42
+ * code must never be able to take the tour down.
43
+ * @internal
44
+ */
45
+ export const createTourEvents = (): TourEventsInternal => {
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ const handlers = new Map<TourEventName, Set<(payload: any) => void>>();
48
+
49
+ const on = <K extends TourEventName>(event: K, handler: TourEventHandler<K>): (() => void) => {
50
+ let set = handlers.get(event);
51
+ if (!set) {
52
+ set = new Set();
53
+ handlers.set(event, set);
54
+ }
55
+ set.add(handler);
56
+ return () => off(event, handler);
57
+ };
58
+
59
+ const off = <K extends TourEventName>(event: K, handler: TourEventHandler<K>): void => {
60
+ handlers.get(event)?.delete(handler);
61
+ };
62
+
63
+ const emit = <K extends TourEventName>(event: K, payload: TourEventMap[K]): void => {
64
+ const set = handlers.get(event);
65
+ if (!set) return;
66
+ for (const handler of [...set]) {
67
+ try {
68
+ handler(payload);
69
+ } catch {
70
+ // Subscriber errors are the subscriber's problem, not the tour's.
71
+ }
72
+ }
73
+ };
74
+
75
+ return { on, off, emit };
76
+ };
package/src/index.tsx ADDED
@@ -0,0 +1,64 @@
1
+ // Main exports
2
+ export { TourGuideProvider, useTourGuide } from './TourGuideContext';
3
+ export { TourTarget } from './TourTarget';
4
+ export { default as TourGuideOverlay } from './TourGuideOverlay';
5
+ export { default as SpotlightOverlay } from './SpotlightOverlay';
6
+ export { default as Tooltip } from './Tooltip';
7
+
8
+ // Hook exports
9
+ export { useTourPersistence } from './useTourPersistence';
10
+ export { useTourScroll } from './useTourScroll';
11
+ export type { TourScrollBinding } from './useTourScroll';
12
+ export { detectStorage } from './storage';
13
+ export type { StorageType } from './storage';
14
+ export type { TourEvents, TourEventMap, TourEventName, TourEventHandler } from './events';
15
+
16
+ // Theme exports
17
+ export { darkTheme, lightTheme, minimalTheme, vibrantTheme, createTheme } from './themes';
18
+
19
+ // Shape exports
20
+ export { computeShape, roundedRectPath, shapeInnerPath } from './shapes';
21
+
22
+ // Utility exports (useful for custom tooltip renderers)
23
+ export {
24
+ computeTooltipPosition,
25
+ validateRef,
26
+ extractBorderRadius,
27
+ resolveInsets,
28
+ resolveSafeAreaInsets,
29
+ osValue,
30
+ } from './utils';
31
+ export { announceStep, getTooltipAccessibilityProps } from './accessibility';
32
+
33
+ // Type exports
34
+ export type {
35
+ TourStep,
36
+ RegisteredTarget,
37
+ TooltipComponents,
38
+ TourButtonProps,
39
+ TourProgressProps,
40
+ TourGuideConfig,
41
+ TourGuideContextValue,
42
+ SpotlightTarget,
43
+ SpotlightStyles,
44
+ TooltipStyles,
45
+ TooltipProps,
46
+ ScrollToTargetConfig,
47
+ BackdropBehavior,
48
+ TourStorage,
49
+ TourTheme,
50
+ MeasurableRef,
51
+ ScrollableRef,
52
+ EdgeInsets,
53
+ SpotlightMotion,
54
+ SpotlightMaskPathFn,
55
+ OSConfig,
56
+ PerPlatform,
57
+ ResolvedTourGuideConfig,
58
+ } from './types';
59
+
60
+ export type { SpotlightBorderRadius, SpotlightPadding, ShapeBounds, ShapeResult } from './shapes';
61
+
62
+ export type { TourGuideProviderProps } from './TourGuideContext';
63
+ export type { TourTargetProps } from './TourTarget';
64
+ export type { SpotlightOverlayProps } from './SpotlightOverlay';
package/src/shapes.ts ADDED
@@ -0,0 +1,184 @@
1
+ import type { EdgeInsets, SpotlightTarget } from './types';
2
+
3
+ /** Padding around the spotlight: uniform number or per-side values. */
4
+ export type SpotlightPadding = number | Partial<EdgeInsets>;
5
+
6
+ /** Resolve a SpotlightPadding to explicit per-side values. */
7
+ export const resolvePadding = (padding: SpotlightPadding | undefined): EdgeInsets => {
8
+ if (typeof padding === 'number') {
9
+ return { top: padding, right: padding, bottom: padding, left: padding };
10
+ }
11
+ return {
12
+ top: padding?.top ?? 0,
13
+ right: padding?.right ?? 0,
14
+ bottom: padding?.bottom ?? 0,
15
+ left: padding?.left ?? 0,
16
+ };
17
+ };
18
+
19
+ /**
20
+ * Internal type for border radius — number for uniform, object for per-corner.
21
+ * Users specify this via `targetStyle` (auto-extracted) or `spotlightBorderRadius` (number override).
22
+ */
23
+ export type SpotlightBorderRadius =
24
+ | number
25
+ | {
26
+ topLeft?: number;
27
+ topRight?: number;
28
+ bottomRight?: number;
29
+ bottomLeft?: number;
30
+ };
31
+
32
+ // --- Result types ---
33
+
34
+ export interface ShapeBounds {
35
+ x: number;
36
+ y: number;
37
+ width: number;
38
+ height: number;
39
+ }
40
+
41
+ export interface RectShapeResult {
42
+ kind: 'rect';
43
+ x: number;
44
+ y: number;
45
+ width: number;
46
+ height: number;
47
+ rx: number;
48
+ ry: number;
49
+ }
50
+
51
+ export interface PathShapeResult {
52
+ kind: 'path';
53
+ d: string;
54
+ bounds: ShapeBounds;
55
+ }
56
+
57
+ export type ShapeResult = RectShapeResult | PathShapeResult;
58
+
59
+ // --- Rect bounds computation ---
60
+
61
+ const computeRectBounds = (target: SpotlightTarget, padding: EdgeInsets) => ({
62
+ x: target.x - padding.left,
63
+ y: target.y - padding.top,
64
+ width: target.width + padding.left + padding.right,
65
+ height: target.height + padding.top + padding.bottom,
66
+ });
67
+
68
+ /**
69
+ * SVG subpath for a uniformly-rounded rectangle (clockwise, closed). Used for
70
+ * the spotlight cutout and for kept spotlights.
71
+ */
72
+ export const roundedRectPath = (x: number, y: number, w: number, h: number, r: number): string => {
73
+ const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2));
74
+ if (rr <= 0) return `M${x},${y} H${x + w} V${y + h} H${x} Z`;
75
+ return (
76
+ `M${x + rr},${y} H${x + w - rr} A${rr},${rr} 0 0 1 ${x + w},${y + rr} ` +
77
+ `V${y + h - rr} A${rr},${rr} 0 0 1 ${x + w - rr},${y + h} ` +
78
+ `H${x + rr} A${rr},${rr} 0 0 1 ${x},${y + h - rr} ` +
79
+ `V${y + rr} A${rr},${rr} 0 0 1 ${x + rr},${y} Z`
80
+ );
81
+ };
82
+
83
+ /** The inner (hole) subpath for any shape result. */
84
+ export const shapeInnerPath = (result: ShapeResult): string =>
85
+ result.kind === 'path'
86
+ ? result.d
87
+ : roundedRectPath(result.x, result.y, result.width, result.height, result.rx);
88
+
89
+ // --- Rounded rect with per-corner radii ---
90
+
91
+ const computeRoundedRectPath = (
92
+ x: number,
93
+ y: number,
94
+ w: number,
95
+ h: number,
96
+ tl: number,
97
+ tr: number,
98
+ br: number,
99
+ bl: number
100
+ ): string => {
101
+ // Clamp radii so they don't exceed half the smallest dimension
102
+ const maxR = Math.min(w, h) / 2;
103
+ const rtl = Math.min(tl, maxR);
104
+ const rtr = Math.min(tr, maxR);
105
+ const rbr = Math.min(br, maxR);
106
+ const rbl = Math.min(bl, maxR);
107
+
108
+ return [
109
+ `M${x + rtl},${y}`,
110
+ `L${x + w - rtr},${y}`,
111
+ rtr > 0 ? `A${rtr},${rtr},0,0,1,${x + w},${y + rtr}` : `L${x + w},${y}`,
112
+ `L${x + w},${y + h - rbr}`,
113
+ rbr > 0 ? `A${rbr},${rbr},0,0,1,${x + w - rbr},${y + h}` : `L${x + w},${y + h}`,
114
+ `L${x + rbl},${y + h}`,
115
+ rbl > 0 ? `A${rbl},${rbl},0,0,1,${x},${y + h - rbl}` : `L${x},${y + h}`,
116
+ `L${x},${y + rtl}`,
117
+ rtl > 0 ? `A${rtl},${rtl},0,0,1,${x + rtl},${y}` : `L${x},${y}`,
118
+ 'Z',
119
+ ].join(' ');
120
+ };
121
+
122
+ // --- Public API ---
123
+
124
+ /**
125
+ * Adjust border radius for the larger spotlight bounds.
126
+ * Fully rounded elements (circle/pill) stay fully rounded at the new size.
127
+ * Partially rounded elements keep their exact original radius.
128
+ */
129
+ const adjustRadius = (
130
+ radius: number,
131
+ targetWidth: number,
132
+ targetHeight: number,
133
+ padding: number
134
+ ): number => {
135
+ if (radius <= 0) return 0;
136
+ const minTarget = Math.min(targetWidth, targetHeight);
137
+ // Fully rounded (circle / pill) — stay fully rounded at the larger size
138
+ if (radius >= minTarget / 2) {
139
+ return Math.min(targetWidth + padding * 2, targetHeight + padding * 2) / 2;
140
+ }
141
+ // Partially rounded — keep exact same radius, only bounds grow
142
+ return radius;
143
+ };
144
+
145
+ /**
146
+ * Compute the spotlight shape for a target.
147
+ * Always produces a rounded rectangle matching the target's border radius.
148
+ * Border radii are scaled proportionally so circles stay circular with padding.
149
+ */
150
+ export const computeShape = (
151
+ target: SpotlightTarget,
152
+ padding: SpotlightPadding = 0,
153
+ customBorderRadius?: SpotlightBorderRadius
154
+ ): ShapeResult => {
155
+ const pad = resolvePadding(padding);
156
+ const { x, y, width, height } = computeRectBounds(target, pad);
157
+ // For radius scaling, treat the average per-axis padding as the uniform
158
+ // equivalent — exact for uniform padding, sensible for per-side.
159
+ const padScale = Math.max((pad.left + pad.right) / 2, (pad.top + pad.bottom) / 2);
160
+
161
+ // Per-corner border radius → generate path with individual corner arcs
162
+ if (typeof customBorderRadius === 'object' && customBorderRadius !== null) {
163
+ const { topLeft = 0, topRight = 0, bottomRight = 0, bottomLeft = 0 } = customBorderRadius;
164
+
165
+ // Scale each corner
166
+ const sTL = adjustRadius(topLeft, target.width, target.height, padScale);
167
+ const sTR = adjustRadius(topRight, target.width, target.height, padScale);
168
+ const sBR = adjustRadius(bottomRight, target.width, target.height, padScale);
169
+ const sBL = adjustRadius(bottomLeft, target.width, target.height, padScale);
170
+
171
+ // If all corners are the same, use rect for smooth animation
172
+ if (sTL === sTR && sTR === sBR && sBR === sBL) {
173
+ return { kind: 'rect', x, y, width, height, rx: sTL, ry: sTL };
174
+ }
175
+
176
+ // Different corners: use path
177
+ const d = computeRoundedRectPath(x, y, width, height, sTL, sTR, sBR, sBL);
178
+ return { kind: 'path', d, bounds: { x, y, width, height } };
179
+ }
180
+
181
+ const br = typeof customBorderRadius === 'number' ? customBorderRadius : 12;
182
+ const scaledBr = adjustRadius(br, target.width, target.height, padScale);
183
+ return { kind: 'rect', x, y, width, height, rx: scaledBr, ry: scaledBr };
184
+ };
package/src/storage.ts ADDED
@@ -0,0 +1,114 @@
1
+ import type { TourStorage } from './types';
2
+ import { warnOnce } from './dev';
3
+
4
+ /** How persistence storage was resolved. */
5
+ export type StorageType = 'mmkv' | 'async-storage' | 'memory' | 'custom';
6
+
7
+ let cached: { type: StorageType; adapter: TourStorage } | null = null;
8
+
9
+ /**
10
+ * MMKV, both API generations:
11
+ * - v4: `createMMKV({ id })` factory
12
+ * - v2/v3: `new MMKV({ id })` class
13
+ */
14
+ const tryMMKV = (): TourStorage | null => {
15
+ try {
16
+ const mod = require('react-native-mmkv');
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ let instance: any = null;
19
+ if (typeof mod?.createMMKV === 'function') {
20
+ instance = mod.createMMKV({ id: 'react-native-tour-guide' });
21
+ } else if (typeof mod?.MMKV === 'function') {
22
+ instance = new mod.MMKV({ id: 'react-native-tour-guide' });
23
+ }
24
+ if (
25
+ instance &&
26
+ typeof instance.getString === 'function' &&
27
+ typeof instance.set === 'function' &&
28
+ (typeof instance.remove === 'function' || typeof instance.delete === 'function')
29
+ ) {
30
+ const removeFn = (instance.remove ?? instance.delete).bind(instance);
31
+ return {
32
+ getItem: (key) => instance.getString(key) ?? null,
33
+ setItem: (key, value) => {
34
+ instance.set(key, value);
35
+ },
36
+ removeItem: (key) => {
37
+ removeFn(key);
38
+ },
39
+ };
40
+ }
41
+ return null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+
47
+ const tryAsyncStorage = (): TourStorage | null => {
48
+ try {
49
+ const mod = require('@react-native-async-storage/async-storage');
50
+ const AsyncStorage = mod?.default ?? mod;
51
+ if (
52
+ AsyncStorage &&
53
+ typeof AsyncStorage.getItem === 'function' &&
54
+ typeof AsyncStorage.setItem === 'function' &&
55
+ typeof AsyncStorage.removeItem === 'function'
56
+ ) {
57
+ return {
58
+ getItem: (key) => AsyncStorage.getItem(key),
59
+ setItem: (key, value) => AsyncStorage.setItem(key, value),
60
+ removeItem: (key) => AsyncStorage.removeItem(key),
61
+ };
62
+ }
63
+ return null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ };
68
+
69
+ /** In-memory last resort: the tour still works, persistence just doesn't survive restarts. */
70
+ const createMemoryStorage = (): TourStorage => {
71
+ const store = new Map<string, string>();
72
+ return {
73
+ getItem: (key) => store.get(key) ?? null,
74
+ setItem: (key, value) => {
75
+ store.set(key, value);
76
+ },
77
+ removeItem: (key) => {
78
+ store.delete(key);
79
+ },
80
+ };
81
+ };
82
+
83
+ /**
84
+ * Detect an available storage backend for tour persistence.
85
+ * Priority: MMKV (fastest) → AsyncStorage → in-memory fallback.
86
+ * The result is cached; the adapters are only probed once.
87
+ */
88
+ export const detectStorage = (): { type: StorageType; adapter: TourStorage } => {
89
+ if (cached) return cached;
90
+
91
+ const mmkv = tryMMKV();
92
+ if (mmkv) {
93
+ cached = { type: 'mmkv', adapter: mmkv };
94
+ return cached;
95
+ }
96
+
97
+ const asyncStorage = tryAsyncStorage();
98
+ if (asyncStorage) {
99
+ cached = { type: 'async-storage', adapter: asyncStorage };
100
+ return cached;
101
+ }
102
+
103
+ warnOnce(
104
+ 'useTourPersistence found neither react-native-mmkv nor @react-native-async-storage/async-storage, so tour completion is only remembered until the app restarts.',
105
+ 'Install one of them, or pass your own storage adapter: useTourPersistence(myStorage).'
106
+ );
107
+ cached = { type: 'memory', adapter: createMemoryStorage() };
108
+ return cached;
109
+ };
110
+
111
+ /** Test-only: clear the detection cache. */
112
+ export const __resetStorageCache = () => {
113
+ cached = null;
114
+ };
package/src/themes.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { TourTheme } from './types';
2
+
3
+ export const darkTheme: TourTheme = {
4
+ tooltipStyles: {
5
+ backgroundColor: '#2C2C2E',
6
+ titleColor: '#FFFFFF',
7
+ descriptionColor: '#EBEBF5',
8
+ buttonTextColor: '#FFFFFF',
9
+ primaryButtonColor: '#007AFF',
10
+ secondaryButtonColor: '#3A3A3C',
11
+ skipButtonColor: '#8E8E93',
12
+ borderRadius: 12,
13
+ },
14
+ spotlightStyles: {
15
+ overlayColor: 'black',
16
+ overlayOpacity: 0.6,
17
+ },
18
+ };
19
+
20
+ export const lightTheme: TourTheme = {
21
+ tooltipStyles: {
22
+ backgroundColor: '#FFFFFF',
23
+ titleColor: '#1C1C1E',
24
+ descriptionColor: '#3A3A3C',
25
+ buttonTextColor: '#FFFFFF',
26
+ primaryButtonColor: '#007AFF',
27
+ secondaryButtonColor: '#E5E5EA',
28
+ skipButtonColor: '#8E8E93',
29
+ borderRadius: 12,
30
+ },
31
+ spotlightStyles: {
32
+ overlayColor: 'black',
33
+ overlayOpacity: 0.4,
34
+ },
35
+ };
36
+
37
+ export const minimalTheme: TourTheme = {
38
+ tooltipStyles: {
39
+ backgroundColor: '#FAFAFA',
40
+ titleColor: '#333333',
41
+ descriptionColor: '#666666',
42
+ buttonTextColor: '#FFFFFF',
43
+ primaryButtonColor: '#555555',
44
+ secondaryButtonColor: '#E0E0E0',
45
+ skipButtonColor: '#999999',
46
+ borderRadius: 8,
47
+ },
48
+ spotlightStyles: {
49
+ overlayColor: 'black',
50
+ overlayOpacity: 0.3,
51
+ },
52
+ };
53
+
54
+ export const vibrantTheme: TourTheme = {
55
+ tooltipStyles: {
56
+ backgroundColor: '#1A1A2E',
57
+ titleColor: '#EAEAEA',
58
+ descriptionColor: '#B0B0C0',
59
+ buttonTextColor: '#FFFFFF',
60
+ primaryButtonColor: '#E94560',
61
+ secondaryButtonColor: '#16213E',
62
+ skipButtonColor: '#8E8E93',
63
+ borderRadius: 16,
64
+ },
65
+ spotlightStyles: {
66
+ overlayColor: '#0F0F23',
67
+ overlayOpacity: 0.7,
68
+ },
69
+ };
70
+
71
+ /**
72
+ * Create a custom theme by deep-merging overrides onto the dark theme base.
73
+ */
74
+ export const createTheme = (overrides: Partial<TourTheme>): TourTheme => ({
75
+ tooltipStyles: {
76
+ ...darkTheme.tooltipStyles,
77
+ ...overrides.tooltipStyles,
78
+ },
79
+ spotlightStyles: {
80
+ ...darkTheme.spotlightStyles,
81
+ ...overrides.spotlightStyles,
82
+ },
83
+ });