rn-smart-tour 2.1.0 → 2.2.0-rc.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 (70) hide show
  1. package/README.md +71 -2
  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 +120 -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 +271 -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 +119 -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 +263 -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 +61 -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 +61 -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 +109 -2
  68. package/src/react/TourProvider.tsx +46 -3
  69. package/src/react/TourTip.tsx +285 -0
  70. package/src/types.ts +93 -2
package/README.md CHANGED
@@ -232,6 +232,18 @@ Each user's seen tours are stored separately. When `userId` changes (sign-in, si
232
232
 
233
233
  **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
234
 
235
+ **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):
236
+
237
+ ```tsx
238
+ <TourProvider
239
+ tours={TOURS}
240
+ maxAutoStartsPerSession={1} // at most one per app session
241
+ autoStartCooldownMs={10 * 60 * 1000} // then a 10-minute quiet gap (kept across restarts)
242
+ >
243
+ ```
244
+
245
+ 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.
246
+
235
247
  ### 8. Your Own Tooltip Card (Optional)
236
248
  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
249
 
@@ -359,7 +371,58 @@ Every event has `type`, `eventId` (unique: drop duplicates when a batch is uploa
359
371
 
360
372
  ---
361
373
 
362
- ### 13. Accessibility
374
+ ### 13. Hotspots and Smart Tips (Optional)
375
+ Two light ways to help without a tour: nothing is dimmed or blocked.
376
+
377
+ **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.
378
+
379
+ ```tsx
380
+ import { TourHotspot } from 'rn-smart-tour';
381
+
382
+ <TourHotspot id="mtp-copy-day" title="Copy a day" description="Copy one day's plan to another date.">
383
+ <CopyDayButton />
384
+ </TourHotspot>
385
+ ```
386
+
387
+ 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).
388
+
389
+ **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.
390
+
391
+ ```tsx
392
+ import { TourSmartTip } from 'rn-smart-tour';
393
+
394
+ <Text>Remark</Text>
395
+ <TourSmartTip id="leave-remark" title="Remark" description="Why your manager needs this request." />
396
+ ```
397
+
398
+ 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'`.
399
+
400
+ ### 14. Checklists (Optional)
401
+ 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:
402
+
403
+ ```tsx
404
+ const CHECKLISTS = {
405
+ start: {
406
+ id: 'start',
407
+ title: 'Getting started',
408
+ items: [
409
+ // Ticked off when the walkthrough is completed (not just seen: skipping doesn't count)…
410
+ { id: 'leave', title: 'Apply for leave', tourId: 'applyLeave', completeOnEvent: 'leaveSubmitted' },
411
+ // …or only when the app reports the real task with emit('mtpSubmitted').
412
+ { id: 'mtp', title: 'Submit your MTP', tourId: 'submitMtp', completeOnTour: false, completeOnEvent: 'mtpSubmitted' },
413
+ { id: 'team', title: 'Review your team', when: ctx => !!ctx.isManager },
414
+ ],
415
+ },
416
+ };
417
+
418
+ <TourProvider tours={TOURS} checklists={CHECKLISTS}>
419
+ …
420
+ <TourChecklist id="start" /> {/* a basic card; or draw your own with useChecklist */}
421
+ ```
422
+
423
+ `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'`.
424
+
425
+ ### 15. Accessibility
363
426
  Works with VoiceOver and TalkBack and the system "reduce motion" setting, with nothing to set up:
364
427
 
365
428
  - **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 +488,8 @@ A tour that is stopped (finished, skipped, or ended because a target was missing
425
488
  | `storageAdapter` | `StorageAdapter` | — | Persists seen tours (AsyncStorage, MMKV, …). Read once on mount. |
426
489
  | `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
490
  | `missingTargetTimeoutMs` | `number` | `3000` | How long a step waits for its target. |
491
+ | `maxAutoStartsPerSession` | `number` | no limit | Tours that start by themselves (`autoStart`): at most this many per app session. `startTour` is never held back. |
492
+ | `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
493
  | `controller` | `TourController` | — | From `createTourController`, instead of `tours` / `storageAdapter`. |
429
494
  | `renderTooltip` | `(props: TourTooltipProps) => ReactNode` | built-in card | Draws the tooltip card. Receives the step, its index and count, and `next` / `prev` / `skip`. |
430
495
  | `tooltipWidth` | `number` | `280` | Card width (capped to the screen). |
@@ -436,13 +501,17 @@ A tour that is stopped (finished, skipped, or ended because a target was missing
436
501
  | `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
502
  | `renderResumeChip` | `(props: ResumeChipProps) => ReactNode` | built-in chip | Draws the "Resume" chip shown while a tour is paused (`tour`, `resume`, `dismiss`). |
438
503
  | `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). |
504
+ | `getStepAnnouncement` | `(props: TourTooltipProps) => string \| null` | `defaultStepAnnouncement` | What screen readers say when a step appears. See [Accessibility](#15-accessibility). |
505
+ | `renderTip` | `(props: TourTipProps) => ReactNode` | built-in card | Draws a hotspot's / Smart Tip's card (`id`, `kind`, `title`, `description`, `close`). |
506
+ | `hotspotColor` | `string` | `'#2563EB'` | Colour of hotspot dots and the default Smart Tip icon. |
507
+ | `checklists` | `Record<string, Checklist>` | — | Checklists (e.g. "Getting started"). See [Checklists](#14-checklists-optional). |
440
508
 
441
509
  ### Tour Configuration
442
510
  | Property | Type | Description |
443
511
  |:---|:---|:---|
444
512
  | `id` | `string` | Unique identifier for caching. |
445
513
  | `autoStart` | `boolean` | Start the first time the first step with a target appears. |
514
+ | `priority` | `number` | When several tours could start by themselves, the highest starts first. Default `0`. |
446
515
  | `version` | `number` | Content version (from 1). Raise it to show a changed tour again to users who saw an older one. |
447
516
  | `steps` | `TourStep[]` | Sequence of highlight steps. |
448
517
  | `kind` | `'tour' \| 'walkthrough'` | Walkthroughs pause on a missing target and say "Exit". Default `'tour'`. |
@@ -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