rn-smart-tour 2.1.0 → 2.2.0-rc.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 (70) hide show
  1. package/README.md +135 -7
  2. package/lib/commonjs/core/TourEngine.js +280 -10
  3. package/lib/commonjs/core/TourEngine.js.map +1 -1
  4. package/lib/commonjs/core/controller.js +6 -0
  5. package/lib/commonjs/core/controller.js.map +1 -1
  6. package/lib/commonjs/index.js +37 -0
  7. package/lib/commonjs/index.js.map +1 -1
  8. package/lib/commonjs/react/TourChecklist.js +218 -0
  9. package/lib/commonjs/react/TourChecklist.js.map +1 -0
  10. package/lib/commonjs/react/TourOverlay.js +126 -2
  11. package/lib/commonjs/react/TourOverlay.js.map +1 -1
  12. package/lib/commonjs/react/TourProvider.js +24 -5
  13. package/lib/commonjs/react/TourProvider.js.map +1 -1
  14. package/lib/commonjs/react/TourTip.js +279 -0
  15. package/lib/commonjs/react/TourTip.js.map +1 -0
  16. package/lib/module/core/TourEngine.js +274 -7
  17. package/lib/module/core/TourEngine.js.map +1 -1
  18. package/lib/module/core/controller.js +6 -0
  19. package/lib/module/core/controller.js.map +1 -1
  20. package/lib/module/index.js +3 -1
  21. package/lib/module/index.js.map +1 -1
  22. package/lib/module/react/TourChecklist.js +210 -0
  23. package/lib/module/react/TourChecklist.js.map +1 -0
  24. package/lib/module/react/TourOverlay.js +125 -2
  25. package/lib/module/react/TourOverlay.js.map +1 -1
  26. package/lib/module/react/TourProvider.js +24 -5
  27. package/lib/module/react/TourProvider.js.map +1 -1
  28. package/lib/module/react/TourTip.js +271 -0
  29. package/lib/module/react/TourTip.js.map +1 -0
  30. package/lib/typescript/commonjs/src/core/TourEngine.d.ts +78 -1
  31. package/lib/typescript/commonjs/src/core/TourEngine.d.ts.map +1 -1
  32. package/lib/typescript/commonjs/src/core/controller.d.ts +14 -2
  33. package/lib/typescript/commonjs/src/core/controller.d.ts.map +1 -1
  34. package/lib/typescript/commonjs/src/index.d.ts +6 -2
  35. package/lib/typescript/commonjs/src/index.d.ts.map +1 -1
  36. package/lib/typescript/commonjs/src/react/TourChecklist.d.ts +47 -0
  37. package/lib/typescript/commonjs/src/react/TourChecklist.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/src/react/TourOverlay.d.ts +7 -6
  39. package/lib/typescript/commonjs/src/react/TourOverlay.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/src/react/TourProvider.d.ts +14 -1
  41. package/lib/typescript/commonjs/src/react/TourProvider.d.ts.map +1 -1
  42. package/lib/typescript/commonjs/src/react/TourTip.d.ts +68 -0
  43. package/lib/typescript/commonjs/src/react/TourTip.d.ts.map +1 -0
  44. package/lib/typescript/commonjs/src/types.d.ts +82 -2
  45. package/lib/typescript/commonjs/src/types.d.ts.map +1 -1
  46. package/lib/typescript/module/src/core/TourEngine.d.ts +78 -1
  47. package/lib/typescript/module/src/core/TourEngine.d.ts.map +1 -1
  48. package/lib/typescript/module/src/core/controller.d.ts +14 -2
  49. package/lib/typescript/module/src/core/controller.d.ts.map +1 -1
  50. package/lib/typescript/module/src/index.d.ts +6 -2
  51. package/lib/typescript/module/src/index.d.ts.map +1 -1
  52. package/lib/typescript/module/src/react/TourChecklist.d.ts +47 -0
  53. package/lib/typescript/module/src/react/TourChecklist.d.ts.map +1 -0
  54. package/lib/typescript/module/src/react/TourOverlay.d.ts +7 -6
  55. package/lib/typescript/module/src/react/TourOverlay.d.ts.map +1 -1
  56. package/lib/typescript/module/src/react/TourProvider.d.ts +14 -1
  57. package/lib/typescript/module/src/react/TourProvider.d.ts.map +1 -1
  58. package/lib/typescript/module/src/react/TourTip.d.ts +68 -0
  59. package/lib/typescript/module/src/react/TourTip.d.ts.map +1 -0
  60. package/lib/typescript/module/src/types.d.ts +82 -2
  61. package/lib/typescript/module/src/types.d.ts.map +1 -1
  62. package/package.json +1 -1
  63. package/src/core/TourEngine.ts +298 -7
  64. package/src/core/controller.ts +19 -1
  65. package/src/index.ts +12 -2
  66. package/src/react/TourChecklist.tsx +167 -0
  67. package/src/react/TourOverlay.tsx +123 -4
  68. package/src/react/TourProvider.tsx +46 -3
  69. package/src/react/TourTip.tsx +298 -0
  70. package/src/types.ts +93 -2
package/README.md CHANGED
@@ -1,10 +1,53 @@
1
1
  # rn-smart-tour
2
2
 
3
3
  <p align="center">
4
- <b>Digital Adoption Platform (DAP) for React Native</b><br>
5
- Easily add product tours, guided walkthroughs, and onboarding overlays without intrusive code changes.
4
+ <b>Product tours, hotspots and onboarding checklists for React Native.</b><br>
5
+ Guide users through real tasks, point out what's new, and see where they get stuck.
6
6
  </p>
7
7
 
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/rn-smart-tour"><img src="https://img.shields.io/npm/v/rn-smart-tour.svg" alt="npm version"></a>
10
+ <a href="https://www.npmjs.com/package/rn-smart-tour"><img src="https://img.shields.io/npm/dm/rn-smart-tour.svg" alt="npm downloads"></a>
11
+ <a href="https://github.com/Vishwasgaur0819/rn-smart-tour/actions/workflows/ci.yml"><img src="https://github.com/Vishwasgaur0819/rn-smart-tour/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
12
+ <a href="https://www.npmjs.com/package/rn-smart-tour"><img src="https://img.shields.io/npm/types/rn-smart-tour.svg" alt="TypeScript types"></a>
13
+ <a href="https://github.com/Vishwasgaur0819/rn-smart-tour/blob/master/package.json"><img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="zero dependencies"></a>
14
+ <a href="https://github.com/Vishwasgaur0819/rn-smart-tour/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/rn-smart-tour.svg" alt="MIT license"></a>
15
+ </p>
16
+
17
+ <p align="center">
18
+ <img src="https://raw.githubusercontent.com/Vishwasgaur0819/rn-smart-tour/master/docs/media/tour.gif" width="250" alt="A tour that starts by itself and scrolls down to a section below the fold">
19
+ &nbsp;
20
+ <img src="https://raw.githubusercontent.com/Vishwasgaur0819/rn-smart-tour/master/docs/media/hotspot-tip.gif" width="250" alt="A hotspot opens its tip, then a Smart Tip explains a field">
21
+ &nbsp;
22
+ <img src="https://raw.githubusercontent.com/Vishwasgaur0819/rn-smart-tour/master/docs/media/checklist.gif" width="250" alt="A checklist item opens a walkthrough and ticks itself off">
23
+ </p>
24
+ <p align="center"><sub>Tours · Hotspots and Smart Tips · Checklists — all with the built-in UI. Recorded from the example app's Showcase screen.</sub></p>
25
+
26
+ - **Pure JavaScript, zero dependencies.** Nothing to link: no `pod install`, no rebuild, no Expo config plugin, no `react-native-svg`.
27
+ - **Built for real apps.** Targets are measured when shown, nested and horizontal lists scroll to them, React Navigation stacks and drawers are understood, steps can point inside modals, and a tour never gets stuck on a missing element.
28
+ - **More than a spotlight.** Task walkthroughs the user does in the real app, hotspots, Smart Tips, checklists, per-user "seen" state with versions, and analytics events for funnels.
29
+
30
+ ---
31
+
32
+ ## ⚖️ How It Compares
33
+
34
+ | | **rn-smart-tour** | react-native-copilot | rn-tourguide |
35
+ | :-- | :-: | :-: | :-: |
36
+ | Spotlight tours with a tooltip | ✅ | ✅ | ✅ |
37
+ | Native dependency | **none** | `react-native-svg` | `react-native-svg` |
38
+ | Scrolls to steps that are off screen | ✅ nested, horizontal, FlatList by index | ⚠️ one ScrollView you pass in | — |
39
+ | Tours across screens (React Navigation) | ✅ | — | — |
40
+ | Ignores screens in the background and closed drawers | ✅ | — | — |
41
+ | Task walkthroughs (waits for the user's tap or an app event) | ✅ | — | — |
42
+ | Shown once per user, saved, with content versions | ✅ | — | — |
43
+ | Hotspots and Smart Tips | ✅ | — | — |
44
+ | Onboarding checklists | ✅ | — | — |
45
+ | Steps inside modals | ✅ | — | — |
46
+ | Analytics events | ✅ every step, exits and why, durations | ⚠️ start / stop / step change | ⚠️ start / stop / step change |
47
+ | Screen readers and Reduce Motion | ✅ | — | — |
48
+
49
+ <sub>✅ supported · ⚠️ partly · — not described in that library's README. Based on each library's README on npm, December 2026. Spotted a mistake? Please open an issue.</sub>
50
+
8
51
  ---
9
52
 
10
53
  ## ✨ Features
@@ -20,6 +63,10 @@
20
63
  - 🪟 **Works With Your Popups**: The tour is drawn over the app, your modals open above it, and steps can point inside them.
21
64
  - 🎨 **Your Design**: Render the card and resume chip with your own components and theme.
22
65
  - 📊 **Analytics**: One callback reports starts, steps, completions, exits (and why) for funnels in your own backend.
66
+ - 📍 **Hotspots and Smart Tips**: A pulsing dot on what's new (shown until opened once), and an "i" next to a field that explains it — nothing dimmed or blocked.
67
+ - ✅ **Onboarding Checklists**: "Getting started" items tick themselves off when the user finishes a walkthrough or does the task.
68
+ - 🚦 **Frequency Rules**: At most N tours start by themselves per session, a quiet gap between them, and priorities.
69
+ - ♿ **Accessible**: Screen reader announcements and focus, Reduce Motion, labelled controls.
23
70
  - 🔁 **Replay on Demand**: `startTour(id, { force: true })`, `resetTour(id)` and `resetAll()`, from components or from outside React.
24
71
 
25
72
  ---
@@ -31,9 +78,11 @@ npm install rn-smart-tour # 2.x (this README)
31
78
  npm install rn-smart-tour@1 # 1.x
32
79
  ```
33
80
 
34
- Requires React 18+ and React Native 0.73+. No native code, so no `pod install` or rebuild is needed. React Navigation (6+) is optional.
81
+ Requires React 18+ and React Native 0.73+. No native code and no dependencies, so there is nothing to link: no `pod install` or rebuild, and no Expo config plugin. React Navigation (6+) is optional.
82
+
83
+ Checked on device on iOS and Android with React Native 0.88 (New Architecture), and on iOS with React Native 0.81 on the old architecture, with React Navigation 7, and piloted in a production enterprise app (React Native 0.85) on iPad and iOS and Android phones. Hotspots, Smart Tips and checklists (2.2) are checked on iPad, the iOS simulator and an Android 12 emulator (edge-to-edge, with real taps and the Back button); a check on an Android phone is still to come. Unit tests run against React Native 0.73.
35
84
 
36
- Checked on device on iOS and Android with React Native 0.88 (New Architecture), and on iOS with React Native 0.81 on the old architecture, with React Navigation 7, and piloted in a production enterprise app (React Native 0.85) on iPad and iOS and Android phones. Unit tests run against React Native 0.73.
85
+ **Try it:** the [example app](example) opens on a Showcase screen with a tour, a hotspot, a Smart Tip and a checklist; "More demos" leads to cross-screen tours, popups and long lists. How to run it: see [Contributing](#-contributing).
37
86
 
38
87
  ---
39
88
 
@@ -91,6 +140,12 @@ const { startTour } = useTour();
91
140
  <Button title="Help" onPress={() => startTour('welcome-tour', { force: true })} />
92
141
  ```
93
142
 
143
+ ---
144
+
145
+ ## 📖 Guides
146
+
147
+ Everything below is optional: add what your app needs.
148
+
94
149
  ### 4. Screens (React Navigation)
95
150
  Wrap each screen that has targets in `NavigationTourScope`. Its targets then only count while the screen is focused and has finished animating in, so a screen kept mounted in the background is never highlighted.
96
151
 
@@ -232,6 +287,18 @@ Each user's seen tours are stored separately. When `userId` changes (sign-in, si
232
287
 
233
288
  **Show a changed tour again.** Give a tour a `version` and raise it when its content changes enough to show again. A tour is seen only if the version the user saw is at least the current one. A tour without `version` counts as version 1, so adding `version: 1` changes nothing and `version: 2` shows it once more.
234
289
 
290
+ **Not too many at once.** With several tours set to `autoStart`, a user can get one right after another. Set house rules for tours that start by themselves (tours started with `startTour`, e.g. from a Help button, are never held back):
291
+
292
+ ```tsx
293
+ <TourProvider
294
+ tours={TOURS}
295
+ maxAutoStartsPerSession={1} // at most one per app session
296
+ autoStartCooldownMs={10 * 60 * 1000} // then a 10-minute quiet gap (kept across restarts)
297
+ >
298
+ ```
299
+
300
+ When several could start, the one with the highest `priority` goes first (`{ id: 'dashboard', autoStart: true, priority: 10, … }`); equal priorities keep the order of `tours`. The quiet gap counts from when the last automatic tour ended, however it ended, and is stored per user with the seen tours (only when it is set). A new user (`setUserId`) starts a new session.
301
+
235
302
  ### 8. Your Own Tooltip Card (Optional)
236
303
  Render the card with your design system and theme. It is placed beside the target for you (below by default, flipping above when there's no room), using its measured height.
237
304
 
@@ -359,7 +426,62 @@ Every event has `type`, `eventId` (unique: drop duplicates when a batch is uploa
359
426
 
360
427
  ---
361
428
 
362
- ### 13. Accessibility
429
+ ### 13. Hotspots and Smart Tips (Optional)
430
+ Two light ways to help without a tour: nothing is dimmed or blocked.
431
+
432
+ **Hotspot**: a pulsing dot on an element, for "something new here". Tapping it shows a short tip beside the element; once the tip is closed (Got it, or a tap anywhere else) the hotspot is marked seen for this user — with the seen tours, per `userId` — and never shows again. Raise `version` to show it again after a change.
433
+
434
+ ```tsx
435
+ import { TourHotspot } from 'rn-smart-tour';
436
+
437
+ <TourHotspot id="mtp-copy-day" title="Copy a day" description="Copy one day's plan to another date.">
438
+ <CopyDayButton />
439
+ </TourHotspot>
440
+ ```
441
+
442
+ The dot sits centred on the element's top-right corner, like a badge (`placement` for another corner; `inside` keeps it inside the element when a parent clips what overflows). Pick a `hotspotColor` on the provider that stands out from your brand colour. Hotspots are hidden while a tour runs, and `enabled={false}` hides one (e.g. behind a feature flag).
443
+
444
+ The dot's touch area is 44 × 44 pt (`hitSlop` 12 around it). Next to other buttons, lower it so a tap meant for them doesn't open the tip, and pick the corner away from them: `<TourHotspot … placement="top-left" hitSlop={{ top: 8, bottom: 8, left: 8, right: 0 }}>`.
445
+
446
+ **Smart Tip**: a small "i" next to a field or label, always there for anyone who wants it (never marked seen). Pass `children` for your own icon.
447
+
448
+ ```tsx
449
+ import { TourSmartTip } from 'rn-smart-tour';
450
+
451
+ <Text>Remark</Text>
452
+ <TourSmartTip id="leave-remark" title="Remark" description="Why your manager needs this request." />
453
+ ```
454
+
455
+ The built-in controls have testIDs for end-to-end tests: `rn-smart-tour-next`, `rn-smart-tour-back`, `rn-smart-tour-skip` (tooltip), `rn-smart-tour-tip-got-it` (tip), `rn-smart-tour-resume`, `rn-smart-tour-resume-dismiss` (resume chip), and `rn-smart-tour-hotspot-<id>` / `rn-smart-tour-smart-tip-<id>` for the dot and the "i".
456
+
457
+ Both cards follow the same rules as steps: drawn beside the visible part of the element, inside a popup when the element is in one (`TourOverlayHost`), announced to screen readers. Draw your own card with `renderTip` on the provider. A tour that starts closes an open tip; a tour that would start by itself waits until the tip is closed. Analytics: `tip_opened` and `tip_closed` (with `reason`), `tourKind: 'hotspot' | 'smartTip'`.
458
+
459
+ ### 14. Checklists (Optional)
460
+ A "Getting started" list of tasks with progress, e.g. for a new joiner's first week. Each item can open its walkthrough, and is ticked off when the user actually does the task:
461
+
462
+ ```tsx
463
+ const CHECKLISTS = {
464
+ start: {
465
+ id: 'start',
466
+ title: 'Getting started',
467
+ items: [
468
+ // Ticked off when the walkthrough is completed (not just seen: skipping doesn't count)…
469
+ { id: 'leave', title: 'Apply for leave', tourId: 'applyLeave', completeOnEvent: 'leaveSubmitted' },
470
+ // …or only when the app reports the real task with emit('mtpSubmitted').
471
+ { id: 'mtp', title: 'Submit your MTP', tourId: 'submitMtp', completeOnTour: false, completeOnEvent: 'mtpSubmitted' },
472
+ { id: 'team', title: 'Review your team', when: ctx => !!ctx.isManager },
473
+ ],
474
+ },
475
+ };
476
+
477
+ <TourProvider tours={TOURS} checklists={CHECKLISTS}>
478
+ …
479
+ <TourChecklist id="start" /> {/* a basic card; or draw your own with useChecklist */}
480
+ ```
481
+
482
+ `useChecklist(id)` returns the items (each with `done`), `done` / `total`, `isComplete`, `dismissed`, `ready`, and `startItem`, `completeItem`, `dismiss`, `reset` — draw your own card with it. It re-renders only when that checklist's progress changes. The app can also tick an item off with `completeChecklistItem(checklistId, itemId)` on the controller. Progress and "hidden" are kept per user with the seen tours. Analytics: `checklist_item_completed` (with `trigger` and `done` / `total`), `checklist_completed`, `checklist_dismissed`, with `tourKind: 'checklist'`.
483
+
484
+ ### 15. Accessibility
363
485
  Works with VoiceOver and TalkBack and the system "reduce motion" setting, with nothing to set up:
364
486
 
365
487
  - **Each step is announced** when it appears (once per step, not again when it is re-measured): title, description, what to do on an action step, and "Step 2 of 5". This also covers custom cards. To translate or change it, pass `getStepAnnouncement`; return `null` to say nothing for a step:
@@ -425,6 +547,8 @@ A tour that is stopped (finished, skipped, or ended because a target was missing
425
547
  | `storageAdapter` | `StorageAdapter` | — | Persists seen tours (AsyncStorage, MMKV, …). Read once on mount. |
426
548
  | `userId` | `string \| null` | — | The signed-in user: each user has their own seen tours. Changing it ends a running tour (unseen) and loads the new user's. See [Remember Seen Tours](#7-remember-seen-tours-optional). |
427
549
  | `missingTargetTimeoutMs` | `number` | `3000` | How long a step waits for its target. |
550
+ | `maxAutoStartsPerSession` | `number` | no limit | Tours that start by themselves (`autoStart`): at most this many per app session. `startTour` is never held back. |
551
+ | `autoStartCooldownMs` | `number` | `0` | After a tour that started by itself ends, wait this long before the next one starts by itself. Kept across restarts, per user. |
428
552
  | `controller` | `TourController` | — | From `createTourController`, instead of `tours` / `storageAdapter`. |
429
553
  | `renderTooltip` | `(props: TourTooltipProps) => ReactNode` | built-in card | Draws the tooltip card. Receives the step, its index and count, and `next` / `prev` / `skip`. |
430
554
  | `tooltipWidth` | `number` | `280` | Card width (capped to the screen). |
@@ -436,13 +560,17 @@ A tour that is stopped (finished, skipped, or ended because a target was missing
436
560
  | `onEvent` | `(event: TourEvent) => void` | — | Analytics: every start, step shown, completion, exit (and why), block, pause, resume and missing target. See [Analytics](#12-analytics-optional). |
437
561
  | `renderResumeChip` | `(props: ResumeChipProps) => ReactNode` | built-in chip | Draws the "Resume" chip shown while a tour is paused (`tour`, `resume`, `dismiss`). |
438
562
  | `highlightColor` | `string` | `'#FFFFFF'` | Ring around an element the user should tap. |
439
- | `getStepAnnouncement` | `(props: TourTooltipProps) => string \| null` | `defaultStepAnnouncement` | What screen readers say when a step appears. See [Accessibility](#13-accessibility). |
563
+ | `getStepAnnouncement` | `(props: TourTooltipProps) => string \| null` | `defaultStepAnnouncement` | What screen readers say when a step appears. See [Accessibility](#15-accessibility). |
564
+ | `renderTip` | `(props: TourTipProps) => ReactNode` | built-in card | Draws a hotspot's / Smart Tip's card (`id`, `kind`, `title`, `description`, `close`). |
565
+ | `hotspotColor` | `string` | `'#2563EB'` | Colour of hotspot dots and the default Smart Tip icon. |
566
+ | `checklists` | `Record<string, Checklist>` | — | Checklists (e.g. "Getting started"). See [Checklists](#14-checklists-optional). |
440
567
 
441
568
  ### Tour Configuration
442
569
  | Property | Type | Description |
443
570
  |:---|:---|:---|
444
571
  | `id` | `string` | Unique identifier for caching. |
445
572
  | `autoStart` | `boolean` | Start the first time the first step with a target appears. |
573
+ | `priority` | `number` | When several tours could start by themselves, the highest starts first. Default `0`. |
446
574
  | `version` | `number` | Content version (from 1). Raise it to show a changed tour again to users who saw an older one. |
447
575
  | `steps` | `TourStep[]` | Sequence of highlight steps. |
448
576
  | `kind` | `'tour' \| 'walkthrough'` | Walkthroughs pause on a missing target and say "Exit". Default `'tour'`. |
@@ -543,7 +671,7 @@ npm run build # outputs lib/ (CommonJS, ES mo
543
671
  npm publish --tag next # prereleases (betas); `npm publish` for stable versions
544
672
  ```
545
673
 
546
- The `example/` app (React Native 0.88, React Navigation) loads the library straight from `src/`, so changes show up without a build:
674
+ The `example/` app (React Native 0.88, React Navigation) opens on the Showcase screen (`example/Showcase.tsx`; the GIFs above are recorded from it) and loads the library straight from `src/`, so changes show up without a build:
547
675
 
548
676
  ```sh
549
677
  cd example && npm install
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.userStorageKey = exports.TourEngine = exports.STORAGE_KEY = exports.PRESS_SLOP = exports.MIGRATED_KEY = void 0;
6
+ exports.userStorageKey = exports.hotspotSeenKey = exports.checklistItemKey = exports.checklistDismissedKey = exports.autoStartStateKey = exports.TourEngine = exports.STORAGE_KEY = exports.PRESS_SLOP = exports.MIGRATED_KEY = void 0;
7
7
  var _store = require("./store.js");
8
8
  var _measure = require("./measure.js");
9
9
  /** A `TourScope`: its targets only count while it (and every parent scope) is ready. */
@@ -18,8 +18,22 @@ var _measure = require("./measure.js");
18
18
  * (null for a step without a target, drawn in the middle of the screen).
19
19
  */
20
20
 
21
- /** A `TourEvent` without the fields the engine fills in. */
21
+ /** The tip currently shown (a hotspot's or Smart Tip's card), anchored to `rect`. */
22
+
23
+ /** What a hotspot / Smart Tip passes to `openTip`. */
24
+
25
+ /** Where a checklist item's "done" is kept, next to the seen tours. */
26
+ const checklistItemKey = (checklistId, itemId) => `checklist:${checklistId}:item:${itemId}`;
27
+ /** Where "the user hid this checklist" is kept. */
28
+ exports.checklistItemKey = checklistItemKey;
29
+ const checklistDismissedKey = checklistId => `checklist:${checklistId}:dismissed`;
22
30
 
31
+ /** Where a hotspot's "seen" is kept, next to the seen tours (a new `version` is a new key). */
32
+ exports.checklistDismissedKey = checklistDismissedKey;
33
+ const hotspotSeenKey = (id, version = 1) => `hotspot:${id}@${version}`;
34
+
35
+ /** A `TourEvent` without the fields the engine fills in. */
36
+ exports.hotspotSeenKey = hotspotSeenKey;
23
37
  let runCounter = 0;
24
38
  /** Unique enough for run and event ids on a backend (not a secure id). */
25
39
  const createId = () => `${Date.now().toString(36)}-${(++runCounter).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
@@ -31,8 +45,11 @@ const PRESS_SLOP = exports.PRESS_SLOP = 10;
31
45
  const STORAGE_KEY = exports.STORAGE_KEY = '@rn-dap:seen_tours';
32
46
  /** Seen tours of one user. */
33
47
  const userStorageKey = userId => `${STORAGE_KEY}:user:${userId}`;
34
- /** Set once the device's seen tours have been copied to a user, so only the first user inherits them. */
48
+ /** When a tour that started by itself last ended, for `autoStartCooldownMs` (per user, like the seen tours). */
35
49
  exports.userStorageKey = userStorageKey;
50
+ const autoStartStateKey = userId => `${userId === null ? STORAGE_KEY : userStorageKey(userId)}:auto`;
51
+ /** Set once the device's seen tours have been copied to a user, so only the first user inherits them. */
52
+ exports.autoStartStateKey = autoStartStateKey;
36
53
  const MIGRATED_KEY = exports.MIGRATED_KEY = `${STORAGE_KEY}:migrated`;
37
54
 
38
55
  /**
@@ -49,6 +66,14 @@ const parseStoredSeen = raw => {
49
66
  }
50
67
  return stored;
51
68
  };
69
+ const readLastAutoEndedAt = raw => {
70
+ try {
71
+ const value = raw ? JSON.parse(raw)?.lastEndedAt : 0;
72
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
73
+ } catch {
74
+ return 0;
75
+ }
76
+ };
52
77
 
53
78
  /** Seen if the version seen (`true` = 1) is at least the tour's (none = 1). */
54
79
  const isSeenVersion = (value, tour) => value !== undefined && (value === true ? 1 : value) >= (tour?.version ?? 1);
@@ -86,9 +111,20 @@ const isScopeReady = scope => !scope || scope.ready && isScopeReady(scope.parent
86
111
  * moving), and again when something may have moved it while it is shown.
87
112
  */
88
113
  class TourEngine {
114
+ maxAutoStartsPerSession = Infinity;
115
+ autoStartCooldownMs = 0;
116
+ /** Tours started by themselves since the app started (or the user changed). */
117
+ autoStartsThisSession = 0;
118
+ /** When the last tour that started by itself ended (ms since epoch; 0: never). */
119
+ lastAutoEndedAt = 0;
120
+ checklists = {};
89
121
  reduceMotion = false;
90
122
  /** The running tour's run, for analytics. */
91
123
  run = null;
124
+ /** The open tip's run, for analytics, and its version (hotspots). */
125
+ tipRun = null;
126
+ /** Changes on every openTip, so a slow measure of an older one is dropped. */
127
+ tipToken = 0;
92
128
  /** The step token whose step_shown event was sent (re-presenting the same step sends none). */
93
129
  shownToken = -1;
94
130
  targets = new Map();
@@ -127,7 +163,10 @@ class TourEngine {
127
163
  this.userId = options.userId ?? null;
128
164
  this.missingTargetTimeoutMs = options.missingTargetTimeoutMs ?? DEFAULT_MISSING_TARGET_TIMEOUT_MS;
129
165
  this.autoStartDelayMs = options.autoStartDelayMs ?? DEFAULT_AUTO_START_DELAY_MS;
166
+ this.maxAutoStartsPerSession = options.maxAutoStartsPerSession ?? Infinity;
167
+ this.autoStartCooldownMs = options.autoStartCooldownMs ?? 0;
130
168
  this.context = options.context ?? {};
169
+ this.checklists = options.checklists ?? {};
131
170
  this.reduceMotion = options.reduceMotion ?? false;
132
171
  this.onStartBlocked = options.onStartBlocked;
133
172
  this.onEvent = options.onEvent;
@@ -138,7 +177,9 @@ class TourEngine {
138
177
  stepIndex: 0,
139
178
  presented: null,
140
179
  paused: false,
141
- toursRevision: 0
180
+ toursRevision: 0,
181
+ tip: null,
182
+ contextRevision: 0
142
183
  });
143
184
  }
144
185
  getState = () => this.store.getState();
@@ -155,8 +196,18 @@ class TourEngine {
155
196
  setOptions(options) {
156
197
  if (options.missingTargetTimeoutMs !== undefined) this.missingTargetTimeoutMs = options.missingTargetTimeoutMs;
157
198
  if (options.autoStartDelayMs !== undefined) this.autoStartDelayMs = options.autoStartDelayMs;
199
+ if ('maxAutoStartsPerSession' in options) {
200
+ this.maxAutoStartsPerSession = options.maxAutoStartsPerSession ?? Infinity;
201
+ }
202
+ if ('autoStartCooldownMs' in options) this.autoStartCooldownMs = options.autoStartCooldownMs ?? 0;
158
203
  if (options.reduceMotion !== undefined) this.reduceMotion = options.reduceMotion;
159
- if (options.context !== undefined) this.context = options.context;
204
+ if (options.context !== undefined && options.context !== this.context || options.checklists !== undefined && options.checklists !== this.checklists) {
205
+ if (options.context !== undefined) this.context = options.context;
206
+ if (options.checklists !== undefined) this.checklists = options.checklists;
207
+ this.store.setState({
208
+ contextRevision: this.getState().contextRevision + 1
209
+ });
210
+ }
160
211
  if ('onStartBlocked' in options) this.onStartBlocked = options.onStartBlocked;
161
212
  if ('onEvent' in options) this.onEvent = options.onEvent;
162
213
  if (options.tours && options.tours !== this.tours) {
@@ -195,8 +246,13 @@ class TourEngine {
195
246
  if (next === this.userId) return;
196
247
  this.userId = next;
197
248
  if (this.getState().tourId) this.finish(false, 'app');
249
+ this.closeTip('app');
198
250
  this.stoppedThisSession.clear();
199
251
  this.storedSeen = {};
252
+ // A new user starts a new session; their own cooldown is loaded with their seen tours.
253
+ this.autoStartsThisSession = 0;
254
+ this.lastAutoEndedAt = 0;
255
+ cancelTimer(this.cooldownTimer);
200
256
  if (!this.storage) {
201
257
  // Nothing is kept between users without storage.
202
258
  this.store.setState({
@@ -220,14 +276,20 @@ class TourEngine {
220
276
  const generation = ++this.loadGeneration;
221
277
  const userId = this.userId;
222
278
  let stored = {};
279
+ let lastAutoEndedAt = 0;
223
280
  try {
224
281
  stored = (await this.readStoredSeen(adapter, userId)) ?? {};
282
+ // Only read when a quiet gap is used (no extra storage read otherwise).
283
+ if (this.autoStartCooldownMs > 0) {
284
+ lastAutoEndedAt = readLastAutoEndedAt(await adapter.getItem(autoStartStateKey(userId)));
285
+ }
225
286
  } catch (e) {
226
287
  console.error('[rn-smart-tour] failed to load storage', e);
227
288
  }
228
289
  // The user changed while this was loading: the newer load applies instead.
229
290
  if (generation !== this.loadGeneration) return;
230
291
  this.storedSeen = stored;
292
+ this.lastAutoEndedAt = lastAutoEndedAt;
231
293
  this.store.setState({
232
294
  seen: this.deriveSeen(),
233
295
  storageReady: true
@@ -290,6 +352,174 @@ class TourEngine {
290
352
  }
291
353
  }
292
354
 
355
+ /** A tour that started by itself has ended: the cooldown runs from now. */
356
+ recordAutoEnd() {
357
+ this.lastAutoEndedAt = Date.now();
358
+ const adapter = this.storage;
359
+ if (!adapter || this.autoStartCooldownMs <= 0) return;
360
+ const key = autoStartStateKey(this.userId);
361
+ const value = JSON.stringify({
362
+ lastEndedAt: this.lastAutoEndedAt
363
+ });
364
+ Promise.resolve().then(() => adapter.setItem(key, value)).catch(e => {
365
+ console.error('[rn-smart-tour] failed to save storage', e);
366
+ });
367
+ }
368
+
369
+ // ---------------------------------------------------------------- checklists
370
+
371
+ getChecklist = id => this.checklists[id] ?? null;
372
+
373
+ /** The checklist's items whose `when` passes now. */
374
+ getChecklistItems = id => {
375
+ const checklist = this.checklists[id];
376
+ if (!checklist) return [];
377
+ return checklist.items.filter(item => {
378
+ if (!item.when) return true;
379
+ try {
380
+ return !!item.when(this.context);
381
+ } catch (e) {
382
+ console.error('[rn-smart-tour] checklist item when() failed', e);
383
+ return true;
384
+ }
385
+ });
386
+ };
387
+ isChecklistItemDone = (checklistId, itemId) => !!this.getState().seen[checklistItemKey(checklistId, itemId)];
388
+
389
+ /** Ticks a checklist item off, e.g. when the app knows the user did the task. */
390
+ completeChecklistItem = (checklistId, itemId, trigger = 'app') => {
391
+ this.whenStorageReady(() => {
392
+ const checklist = this.checklists[checklistId];
393
+ if (!checklist?.items.some(item => item.id === itemId)) return;
394
+ const key = checklistItemKey(checklistId, itemId);
395
+ if (this.storedSeen[key]) return;
396
+ this.persistSeen({
397
+ ...this.storedSeen,
398
+ [key]: true
399
+ });
400
+ const items = this.getChecklistItems(checklistId);
401
+ const done = items.filter(item => this.storedSeen[checklistItemKey(checklistId, item.id)]).length;
402
+ const runId = createId();
403
+ this.track(checklistId, {
404
+ type: 'checklist_item_completed',
405
+ itemId,
406
+ trigger,
407
+ done,
408
+ total: items.length
409
+ }, runId, 'checklist');
410
+ if (items.length > 0 && done === items.length) {
411
+ this.track(checklistId, {
412
+ type: 'checklist_completed',
413
+ total: items.length
414
+ }, runId, 'checklist');
415
+ }
416
+ });
417
+ };
418
+
419
+ /** The user hid the checklist (kept per user). */
420
+ dismissChecklist = checklistId => {
421
+ this.whenStorageReady(() => {
422
+ if (!this.checklists[checklistId] || this.storedSeen[checklistDismissedKey(checklistId)]) return;
423
+ this.persistSeen({
424
+ ...this.storedSeen,
425
+ [checklistDismissedKey(checklistId)]: true
426
+ });
427
+ const items = this.getChecklistItems(checklistId);
428
+ const done = items.filter(item => this.storedSeen[checklistItemKey(checklistId, item.id)]).length;
429
+ this.track(checklistId, {
430
+ type: 'checklist_dismissed',
431
+ done,
432
+ total: items.length
433
+ }, createId(), 'checklist');
434
+ });
435
+ };
436
+
437
+ /** Clears a checklist's progress and shows it again. */
438
+ resetChecklist = checklistId => {
439
+ this.whenStorageReady(() => {
440
+ const prefix = `checklist:${checklistId}:`;
441
+ const next = {
442
+ ...this.storedSeen
443
+ };
444
+ let changed = false;
445
+ for (const key of Object.keys(next)) {
446
+ if (key.startsWith(prefix)) {
447
+ delete next[key];
448
+ changed = true;
449
+ }
450
+ }
451
+ if (changed) this.persistSeen(next);
452
+ });
453
+ };
454
+
455
+ // ---------------------------------------------------------------- tips
456
+
457
+ /** Whether the hotspot (at this version) was opened by this user. */
458
+ isHotspotSeen = (id, version) => !!this.getState().seen[hotspotSeenKey(id, version)];
459
+
460
+ /**
461
+ * Shows a hotspot's or Smart Tip's card next to its element (`handle`), if the element
462
+ * is visible and no tour is running. Replaces a tip that is open.
463
+ */
464
+ openTip = async (spec, handle) => {
465
+ if (this.getState().tourId) return;
466
+ const token = ++this.tipToken;
467
+ const rect = await (0, _measure.measureInWindow)(handle.ref.current);
468
+ const visible = rect ? await this.visiblePart(handle, rect) : null;
469
+ if (token !== this.tipToken || !visible || this.getState().tourId) return;
470
+ this.closeTip('app');
471
+ cancelTimer(this.autoStartTimer);
472
+ this.tipRun = {
473
+ id: createId(),
474
+ startedAt: Date.now(),
475
+ version: spec.version
476
+ };
477
+ this.store.setState({
478
+ tip: {
479
+ id: spec.id,
480
+ kind: spec.kind,
481
+ title: spec.title,
482
+ description: spec.description,
483
+ rect: visible,
484
+ hostId: handle.host?.id ?? null
485
+ }
486
+ });
487
+ this.track(spec.id, {
488
+ type: 'tip_opened'
489
+ }, this.tipRun.id, spec.kind);
490
+ };
491
+
492
+ /**
493
+ * Closes the open tip. Closing a hotspot's tip on purpose (Got it, a tap outside) marks
494
+ * the hotspot seen, so its dot doesn't show again.
495
+ */
496
+ closeTip = (reason = 'app') => {
497
+ const {
498
+ tip
499
+ } = this.getState();
500
+ this.tipToken++;
501
+ if (!tip) return;
502
+ const run = this.tipRun;
503
+ this.tipRun = null;
504
+ this.store.setState({
505
+ tip: null
506
+ });
507
+ if (tip.kind === 'hotspot' && (reason === 'got_it' || reason === 'outside')) {
508
+ this.persistSeen({
509
+ ...this.storedSeen,
510
+ [hotspotSeenKey(tip.id, run?.version)]: true
511
+ });
512
+ }
513
+ if (run) {
514
+ this.track(tip.id, {
515
+ type: 'tip_closed',
516
+ reason,
517
+ durationMs: Date.now() - run.startedAt
518
+ }, run.id, tip.kind);
519
+ }
520
+ if (reason !== 'tour') this.scheduleAutoStart();
521
+ };
522
+
293
523
  // ---------------------------------------------------------------- targets
294
524
 
295
525
  /** Registers a target; returns its unregister function. */
@@ -343,6 +573,12 @@ class TourEngine {
343
573
 
344
574
  /** The app reports something happened; moves on if the current step waits for it. */
345
575
  emit = event => {
576
+ // Checklist items done by the user themselves (whether or not a tour is running).
577
+ for (const checklist of Object.values(this.checklists)) {
578
+ for (const item of checklist.items) {
579
+ if (item.completeOnEvent === event) this.completeChecklistItem(checklist.id, item.id, 'event');
580
+ }
581
+ }
346
582
  const advanceOn = this.currentStep()?.advanceOn;
347
583
  if (!this.getState().paused && typeof advanceOn === 'object' && advanceOn.event === event) {
348
584
  this.nextStep();
@@ -416,6 +652,9 @@ class TourEngine {
416
652
  }
417
653
  return;
418
654
  }
655
+
656
+ // A tour takes over from an open tip.
657
+ this.closeTip('tour');
419
658
  const running = this.getState();
420
659
  if (running.tourId && this.run) {
421
660
  this.track(running.tourId, {
@@ -424,10 +663,13 @@ class TourEngine {
424
663
  stepIndex: running.stepIndex,
425
664
  durationMs: Date.now() - this.run.startedAt
426
665
  });
666
+ if (this.run.auto) this.recordAutoEnd();
427
667
  }
668
+ if (isAutoStart) this.autoStartsThisSession++;
428
669
  this.run = {
429
670
  id: createId(),
430
- startedAt: Date.now()
671
+ startedAt: Date.now(),
672
+ auto: isAutoStart
431
673
  };
432
674
  this.store.setState({
433
675
  tourId,
@@ -652,6 +894,7 @@ class TourEngine {
652
894
  this.stepToken++;
653
895
  this.clearStepTimers();
654
896
  cancelTimer(this.autoStartTimer);
897
+ cancelTimer(this.cooldownTimer);
655
898
  }
656
899
 
657
900
  // ---------------------------------------------------------------- step lifecycle
@@ -995,6 +1238,7 @@ class TourEngine {
995
1238
  stepIndex,
996
1239
  durationMs
997
1240
  });
1241
+ if (this.run.auto) this.recordAutoEnd();
998
1242
  }
999
1243
  this.run = null;
1000
1244
  this.stepToken++;
@@ -1012,12 +1256,22 @@ class TourEngine {
1012
1256
  [tourId]: this.tours[tourId]?.version ?? true
1013
1257
  });
1014
1258
  }
1259
+ if (outcome === 'completed') {
1260
+ // Checklist items whose walkthrough this was.
1261
+ for (const checklist of Object.values(this.checklists)) {
1262
+ for (const item of checklist.items) {
1263
+ if (item.tourId === tourId && item.completeOnTour !== false) {
1264
+ this.completeChecklistItem(checklist.id, item.id, 'tour');
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1015
1269
  this.scheduleAutoStart();
1016
1270
  }
1017
1271
 
1018
1272
  // ---------------------------------------------------------------- analytics
1019
1273
 
1020
- track(tourId, body, runId = this.run?.id) {
1274
+ track(tourId, body, runId = this.run?.id, tourKind) {
1021
1275
  const onEvent = this.onEvent;
1022
1276
  if (!onEvent) return;
1023
1277
  try {
@@ -1026,7 +1280,7 @@ class TourEngine {
1026
1280
  eventId: createId(),
1027
1281
  runId: runId ?? createId(),
1028
1282
  tourId,
1029
- tourKind: this.tours[tourId]?.kind ?? 'tour',
1283
+ tourKind: tourKind ?? this.tours[tourId]?.kind ?? 'tour',
1030
1284
  timestamp: Date.now()
1031
1285
  });
1032
1286
  } catch (e) {
@@ -1066,8 +1320,24 @@ class TourEngine {
1066
1320
  cancelTimer(this.autoStartTimer);
1067
1321
  this.autoStartTimer = setTimeout(() => {
1068
1322
  const state = this.getState();
1069
- if (state.tourId) return;
1070
- for (const id of Object.keys(this.tours)) {
1323
+ // A tip is open: closing it looks again.
1324
+ if (state.tourId || state.tip) return;
1325
+ // House rules for tours that start by themselves (tours the user starts are never held back).
1326
+ if (this.autoStartsThisSession >= this.maxAutoStartsPerSession) return;
1327
+ const wait = this.lastAutoEndedAt + this.autoStartCooldownMs - Date.now();
1328
+ if (wait > 0) {
1329
+ // Look again once the quiet gap is over.
1330
+ cancelTimer(this.cooldownTimer);
1331
+ this.cooldownTimer = setTimeout(() => this.scheduleAutoStart(), wait);
1332
+ return;
1333
+ }
1334
+ // Most important first; equal priority keeps the order of `tours`.
1335
+ const ids = Object.keys(this.tours).map((id, order) => ({
1336
+ id,
1337
+ order,
1338
+ priority: this.tours[id].priority ?? 0
1339
+ })).sort((a, b) => b.priority - a.priority || a.order - b.order).map(entry => entry.id);
1340
+ for (const id of ids) {
1071
1341
  const tour = this.tours[id];
1072
1342
  if (!tour.autoStart || state.seen[id] || this.stoppedThisSession.has(id)) continue;
1073
1343
  // Starts when the first shown step with a target is on screen (centred intro