@dloizides/ui-tour 0.0.0-stage → 1.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,980 @@
1
+ import { createContext, useContext, useMemo, useState, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
2
+ import { Platform } from 'react-native';
3
+ import { createPortal } from 'react-dom';
4
+ import { jsx, jsxs } from 'react/jsx-runtime';
5
+
6
+ // src/components/TourProvider.tsx
7
+
8
+ // src/constants.ts
9
+ var DEFAULT_TIMING = {
10
+ autoMs: 2e3,
11
+ waitMs: 8e3,
12
+ cursorMs: 800,
13
+ typeMs: 45,
14
+ guideAdvanceMs: 600
15
+ };
16
+ var RIPPLE_MS = 700;
17
+ var RING_PADDING = 6;
18
+ var MIN_HIT = 44;
19
+ var LAYER_Z = 2147483640;
20
+ var TourContext = createContext(null);
21
+ function useTour() {
22
+ const value = useContext(TourContext);
23
+ if (value === null) throw new Error("useTour must be used inside TourProvider");
24
+ return value;
25
+ }
26
+
27
+ // src/labels.ts
28
+ var defaultTourLabels = {
29
+ pickerTitle: "Guided tours",
30
+ pickerIntro: "Guide me: you click, the tour highlights. Show me: the tour clicks for you. Auto: plays on its own, Space pauses.",
31
+ groupTitle: "{{p1}} ({{p2}})",
32
+ close: "Close",
33
+ guideMe: "Guide me",
34
+ showMe: "Show me",
35
+ auto: "Auto",
36
+ stepCount: "{{p1}} steps",
37
+ captionMeta: "{{p1}} \xB7 Step {{p2}} of {{p3}} \xB7 {{p4}}",
38
+ modeGuide: "Guide",
39
+ modeShow: "Show",
40
+ modeAuto: "Auto",
41
+ back: "Back",
42
+ next: "Next",
43
+ skip: "Skip",
44
+ end: "End",
45
+ unavailable: "This step isn't available here",
46
+ refused: 'The tour never clicks "{{p1}}". Press Next to continue.',
47
+ paused: "Paused: Space resumes",
48
+ autoPlaying: "Auto-play: Space pauses",
49
+ guideHint: "Click the highlighted item, or press Next",
50
+ continueHint: "Press Next to continue",
51
+ offerTitle: "Take a 1-minute tour",
52
+ offerBody: "See the main screens in a short guided walk-through.",
53
+ offerStart: "Start the tour",
54
+ offerDismiss: "No thanks"
55
+ };
56
+ function formatLabel(template, ...params) {
57
+ return params.reduce((text, value, index) => text.split(`{{p${index + 1}}}`).join(String(value)), template);
58
+ }
59
+
60
+ // src/enums/TargetRole.ts
61
+ var TargetRole = /* @__PURE__ */ ((TargetRole2) => {
62
+ TargetRole2["Button"] = "button";
63
+ TargetRole2["Heading"] = "heading";
64
+ TargetRole2["Group"] = "group";
65
+ TargetRole2["Field"] = "field";
66
+ TargetRole2["Text"] = "text";
67
+ return TargetRole2;
68
+ })(TargetRole || {});
69
+
70
+ // src/dom/text.ts
71
+ var WHITESPACE = /\s+/g;
72
+ var VARIABLE = /\{(\w+)\}/g;
73
+ var QUOTE_OR_SLASH = /["\\]/g;
74
+ function normalise(value) {
75
+ return (value ?? "").replace(WHITESPACE, " ").trim();
76
+ }
77
+ function substitute(text, vars) {
78
+ return text.replace(VARIABLE, (match, key) => vars[key] ?? match);
79
+ }
80
+ function escapeQuotes(value) {
81
+ return value.replace(QUOTE_OR_SLASH, "\\$&");
82
+ }
83
+ function nonEmpty(value) {
84
+ return value !== null && value !== void 0 && value.trim() !== "";
85
+ }
86
+ function accessibleName(node) {
87
+ const label = node.getAttribute("aria-label");
88
+ return normalise(nonEmpty(label) ? label : node.textContent);
89
+ }
90
+ function labelFor(node) {
91
+ if (node.id === "") return null;
92
+ return document.querySelector(`label[for="${escapeQuotes(node.id)}"]`)?.textContent ?? null;
93
+ }
94
+ function labelledBy(node) {
95
+ const id = node.getAttribute("aria-labelledby");
96
+ if (!nonEmpty(id)) return null;
97
+ return document.getElementById(id)?.textContent ?? null;
98
+ }
99
+ function fieldLabel(node) {
100
+ const candidates = [node.getAttribute("aria-label"), labelFor(node), labelledBy(node), node.getAttribute("placeholder")];
101
+ return normalise(candidates.find(nonEmpty));
102
+ }
103
+ function matchesName(value, want, exact) {
104
+ if (want instanceof RegExp) return want.test(value);
105
+ return exact === false ? value.includes(want) : value === want;
106
+ }
107
+
108
+ // src/dom/findTarget.ts
109
+ var OVERLAY_SELECTOR = "[data-tour-overlay]";
110
+ var SKIP_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "STYLE"]);
111
+ var ROLE_SELECTORS = {
112
+ ["button" /* Button */]: 'button,[role="button"],a[href],[role="link"]',
113
+ ["heading" /* Heading */]: 'h1,h2,h3,h4,h5,h6,[role="heading"]',
114
+ ["group" /* Group */]: '[role="group"]',
115
+ ["field" /* Field */]: 'input,textarea,[role="textbox"]',
116
+ ["text" /* Text */]: "*"
117
+ };
118
+ function isVisible(node) {
119
+ const rect = node.getBoundingClientRect();
120
+ if (rect.width < 1 || rect.height < 1) return false;
121
+ const style = window.getComputedStyle(node);
122
+ return style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0";
123
+ }
124
+ function usable(node) {
125
+ return node.closest(OVERLAY_SELECTOR) === null && isVisible(node);
126
+ }
127
+ function findText(root, want) {
128
+ let best = null;
129
+ for (const node of Array.from(root.querySelectorAll("*"))) {
130
+ if (SKIP_TAGS.has(node.tagName) || !usable(node)) continue;
131
+ if (!matchesName(normalise(node.textContent), want, false)) continue;
132
+ if (best === null || best.contains(node)) best = node;
133
+ }
134
+ return best;
135
+ }
136
+ function findByRole(root, target, want) {
137
+ const label = target.role === "field" /* Field */ ? fieldLabel : accessibleName;
138
+ let skip = target.nth ?? 0;
139
+ for (const node of Array.from(root.querySelectorAll(ROLE_SELECTORS[target.role]))) {
140
+ if (!usable(node) || !matchesName(label(node), want, target.exact)) continue;
141
+ if (skip === 0) return node;
142
+ skip -= 1;
143
+ }
144
+ return null;
145
+ }
146
+ function findTarget(target, vars = {}) {
147
+ if (typeof target === "string") {
148
+ const nodes = Array.from(document.querySelectorAll(`[data-testid="${escapeQuotes(target)}"]`));
149
+ return nodes.find(usable) ?? null;
150
+ }
151
+ const root = target.within !== void 0 ? document.querySelector(target.within) : document.body;
152
+ if (root === null) return null;
153
+ const want = typeof target.name === "string" ? substitute(target.name, vars) : target.name;
154
+ return target.role === "text" /* Text */ ? findText(root, want) : findByRole(root, target, want);
155
+ }
156
+
157
+ // src/dom/waitForTarget.ts
158
+ var POLL_MS = 200;
159
+ function sleep(ms) {
160
+ return new Promise((resolve) => setTimeout(resolve, ms));
161
+ }
162
+ async function waitForTarget(target, vars, timeoutMs, isCancelled) {
163
+ const deadline = Date.now() + timeoutMs;
164
+ for (; ; ) {
165
+ const node = findTarget(target, vars);
166
+ const remaining = deadline - Date.now();
167
+ if (node !== null || isCancelled() || remaining <= 0) return node;
168
+ await sleep(Math.min(POLL_MS, remaining));
169
+ }
170
+ }
171
+
172
+ // src/dom/pointer.ts
173
+ function rectOf(node) {
174
+ const rect = node.getBoundingClientRect();
175
+ return { left: rect.left, top: rect.top, width: rect.width, height: rect.height };
176
+ }
177
+ function centreOf(node) {
178
+ const rect = node.getBoundingClientRect();
179
+ return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) };
180
+ }
181
+ function isTextField(node) {
182
+ return node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement;
183
+ }
184
+ function pointerEvent(type, init) {
185
+ return typeof window.PointerEvent === "function" ? new window.PointerEvent(type, init) : new MouseEvent(type, init);
186
+ }
187
+ function dispatchClick(node, point) {
188
+ if (isTextField(node)) {
189
+ node.focus();
190
+ return;
191
+ }
192
+ const init = { bubbles: true, cancelable: true, view: window, clientX: point.x, clientY: point.y, button: 0, pointerId: 1, pointerType: "mouse", isPrimary: true };
193
+ node.dispatchEvent(pointerEvent("pointerdown", init));
194
+ node.dispatchEvent(new MouseEvent("mousedown", init));
195
+ node.dispatchEvent(pointerEvent("pointerup", init));
196
+ node.dispatchEvent(new MouseEvent("mouseup", init));
197
+ node.dispatchEvent(new MouseEvent("click", init));
198
+ }
199
+ function setNativeValue(node, value) {
200
+ const proto = node instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
201
+ const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
202
+ if (setter !== void 0) setter.call(node, value);
203
+ else node.value = value;
204
+ node.dispatchEvent(new Event("input", { bubbles: true }));
205
+ }
206
+ async function typeValue(node, value, typeMs) {
207
+ if (!isTextField(node)) return;
208
+ node.focus();
209
+ setNativeValue(node, "");
210
+ for (let length = 1; length <= value.length; length += 1) {
211
+ setNativeValue(node, value.slice(0, length));
212
+ await sleep(typeMs);
213
+ }
214
+ }
215
+
216
+ // src/enums/StepPhase.ts
217
+ var StepPhase = /* @__PURE__ */ ((StepPhase2) => {
218
+ StepPhase2["Idle"] = "idle";
219
+ StepPhase2["Loading"] = "loading";
220
+ StepPhase2["Ready"] = "ready";
221
+ StepPhase2["Missing"] = "missing";
222
+ StepPhase2["Refused"] = "refused";
223
+ return StepPhase2;
224
+ })(StepPhase || {});
225
+
226
+ // src/engine/stepEffects.ts
227
+ var IDLE_VIEW = { phase: "idle" /* Idle */, rect: null, refusedName: "" };
228
+ var LOADING_VIEW = { phase: "loading" /* Loading */, rect: null, refusedName: "" };
229
+ function tourOf(tours, active) {
230
+ if (active === null) return null;
231
+ return tours.find((tour) => tour.id === active.tourId) ?? null;
232
+ }
233
+ function stepOf(tours, active) {
234
+ const tour = tourOf(tours, active);
235
+ return tour !== null && active !== null ? tour.steps[active.step] ?? null : null;
236
+ }
237
+ function cursorMover(cursorMs, setCursor, setRipple) {
238
+ return async (point) => {
239
+ setCursor(point);
240
+ await sleep(cursorMs);
241
+ setRipple(point);
242
+ setTimeout(() => setRipple(null), RIPPLE_MS);
243
+ };
244
+ }
245
+ function applyOutcome(outcome, nodeRef, setView, onSkip) {
246
+ if (outcome.kind === "skip" /* Skip */) onSkip();
247
+ else if (outcome.kind === "missing" /* Missing */) setView({ phase: "missing" /* Missing */, rect: null, refusedName: "" });
248
+ else if (outcome.kind === "refused" /* Refused */) {
249
+ nodeRef.current = outcome.node;
250
+ setView({ phase: "refused" /* Refused */, rect: rectOf(outcome.node), refusedName: outcome.name });
251
+ } else if (outcome.kind === "ready" /* Ready */) {
252
+ nodeRef.current = outcome.clicked ? null : outcome.node;
253
+ setView({ phase: "ready" /* Ready */, rect: outcome.clicked ? null : rectOf(outcome.node), refusedName: "" });
254
+ }
255
+ }
256
+
257
+ // src/engine/inertTour.ts
258
+ var ignore = () => void 0;
259
+ function inertTour(tours, theme, labels) {
260
+ return {
261
+ active: null,
262
+ paused: false,
263
+ pickerOpen: false,
264
+ start: ignore,
265
+ next: ignore,
266
+ back: ignore,
267
+ end: ignore,
268
+ togglePause: ignore,
269
+ openPicker: ignore,
270
+ closePicker: ignore,
271
+ tours,
272
+ theme,
273
+ labels: { ...defaultTourLabels, ...labels },
274
+ user: null,
275
+ vars: {},
276
+ view: IDLE_VIEW,
277
+ cursor: null,
278
+ ripple: null
279
+ };
280
+ }
281
+
282
+ // src/enums/StepAction.ts
283
+ var StepAction = /* @__PURE__ */ ((StepAction2) => {
284
+ StepAction2["Click"] = "click";
285
+ StepAction2["Type"] = "type";
286
+ StepAction2["None"] = "none";
287
+ return StepAction2;
288
+ })(StepAction || {});
289
+
290
+ // src/enums/TourMode.ts
291
+ var TourMode = /* @__PURE__ */ ((TourMode2) => {
292
+ TourMode2["Guide"] = "guide";
293
+ TourMode2["Show"] = "show";
294
+ TourMode2["Auto"] = "auto";
295
+ return TourMode2;
296
+ })(TourMode || {});
297
+
298
+ // src/hooks/useStepListeners.ts
299
+ function handleTourKey(key, controls) {
300
+ if (key === "F2") controls.openPicker();
301
+ else if (controls.pickerOpen && key === "Escape") controls.closePicker();
302
+ else if (controls.active === null) return false;
303
+ else if (key === "Escape") controls.end();
304
+ else if (key === "ArrowRight") controls.next();
305
+ else if (key === "ArrowLeft") controls.back();
306
+ else if (key === " " && controls.active.mode === "auto" /* Auto */) controls.togglePause();
307
+ else return false;
308
+ return true;
309
+ }
310
+ function useTourKeys(controls) {
311
+ const controlsRef = useRef(controls);
312
+ controlsRef.current = controls;
313
+ useEffect(() => {
314
+ const onKey = (event) => {
315
+ if (!handleTourKey(event.key, controlsRef.current)) return;
316
+ event.preventDefault();
317
+ event.stopPropagation();
318
+ };
319
+ window.addEventListener("keydown", onKey, true);
320
+ return () => window.removeEventListener("keydown", onKey, true);
321
+ }, []);
322
+ }
323
+ function useAutoAdvance(active, phase, paused, autoMs, next) {
324
+ useEffect(() => {
325
+ if (active === null || active.mode !== "auto" /* Auto */ || paused) return void 0;
326
+ if (phase === "idle" /* Idle */ || phase === "loading" /* Loading */) return void 0;
327
+ const timer = setTimeout(next, autoMs);
328
+ return () => clearTimeout(timer);
329
+ }, [active, phase, paused, autoMs, next]);
330
+ }
331
+ function useGuideClick({ active, phase, action, nodeRef, next, delayMs }) {
332
+ useEffect(() => {
333
+ if (active === null || active.mode !== "guide" /* Guide */ || phase !== "ready" /* Ready */ || action !== "click" /* Click */) return void 0;
334
+ let timer;
335
+ const onClick = (event) => {
336
+ const node = nodeRef.current;
337
+ if (node !== null && event.target instanceof Node && node.contains(event.target)) timer = setTimeout(next, delayMs);
338
+ };
339
+ document.addEventListener("click", onClick, true);
340
+ return () => {
341
+ document.removeEventListener("click", onClick, true);
342
+ if (timer !== void 0) clearTimeout(timer);
343
+ };
344
+ }, [active, phase, action, nodeRef, next, delayMs]);
345
+ }
346
+ function useRectTracking(phase, refreshRect) {
347
+ useEffect(() => {
348
+ if (phase !== "ready" /* Ready */ && phase !== "refused" /* Refused */) return void 0;
349
+ window.addEventListener("resize", refreshRect);
350
+ window.addEventListener("scroll", refreshRect, true);
351
+ return () => {
352
+ window.removeEventListener("resize", refreshRect);
353
+ window.removeEventListener("scroll", refreshRect, true);
354
+ };
355
+ }, [phase, refreshRect]);
356
+ }
357
+
358
+ // src/dom/forbidden.ts
359
+ var WRITE_CONTROL = /^(save|submit|approve|reject|delete|reset|pay|send)\b/i;
360
+ var PLAIN_SAVE = /^save$/i;
361
+ function isForbiddenClick(name, allowSave) {
362
+ const clean = normalise(name);
363
+ if (!WRITE_CONTROL.test(clean)) return false;
364
+ return !(allowSave && PLAIN_SAVE.test(clean));
365
+ }
366
+
367
+ // src/engine/runStep.ts
368
+ var CANCELLED = { kind: "cancelled" /* Cancelled */ };
369
+ function ready(node, clicked) {
370
+ return { kind: "ready" /* Ready */, node, clicked };
371
+ }
372
+ async function perform(context, node) {
373
+ const { step, mode } = context;
374
+ const acts = mode !== "guide" /* Guide */;
375
+ if (step.action === "type" /* Type */) {
376
+ if (acts) await context.moveCursor(centreOf(node));
377
+ await typeValue(node, substitute(step.value ?? "", context.vars), context.timing.typeMs);
378
+ return ready(node, false);
379
+ }
380
+ if (step.action !== "click" /* Click */ || !acts) return ready(node, false);
381
+ const name = accessibleName(node);
382
+ if (isForbiddenClick(name, context.allowSave)) return { kind: "refused" /* Refused */, node, name };
383
+ const point = centreOf(node);
384
+ await context.moveCursor(point);
385
+ if (context.isCancelled()) return CANCELLED;
386
+ dispatchClick(node, point);
387
+ return ready(node, true);
388
+ }
389
+ async function runStep(context) {
390
+ const { step } = context;
391
+ if (step.route !== void 0 && context.getPathname() !== step.route) context.navigate(step.route);
392
+ const node = await waitForTarget(step.target, context.vars, step.wait ?? context.timing.waitMs, context.isCancelled);
393
+ if (context.isCancelled()) return CANCELLED;
394
+ if (node === null) return { kind: step.optional === true ? "skip" /* Skip */ : "missing" /* Missing */ };
395
+ if (node instanceof HTMLElement && typeof node.scrollIntoView === "function") node.scrollIntoView({ block: "center" });
396
+ return perform(context, node);
397
+ }
398
+
399
+ // src/hooks/useStepRunner.ts
400
+ function useStepRunner(options) {
401
+ const [view, setView] = useState(IDLE_VIEW);
402
+ const [cursor, setCursor] = useState(null);
403
+ const [ripple, setRipple] = useState(null);
404
+ const nodeRef = useRef(null);
405
+ const optionsRef = useRef(options);
406
+ optionsRef.current = options;
407
+ const { active } = options;
408
+ const refreshRect = useCallback(() => {
409
+ const node = nodeRef.current;
410
+ if (node !== null) setView((current) => ({ ...current, rect: rectOf(node) }));
411
+ }, []);
412
+ useEffect(() => {
413
+ nodeRef.current = null;
414
+ const latest = optionsRef.current;
415
+ const step = stepOf(latest.tours, active);
416
+ if (active === null || step === null) {
417
+ setView(IDLE_VIEW);
418
+ setCursor(null);
419
+ return void 0;
420
+ }
421
+ let cancelled = false;
422
+ setView(LOADING_VIEW);
423
+ const allowSave = latest.allowWrites && tourOf(latest.tours, active)?.allowSave === true;
424
+ void runStep({
425
+ step,
426
+ mode: active.mode,
427
+ vars: latest.vars,
428
+ timing: latest.timing,
429
+ allowSave,
430
+ navigate: latest.navigate,
431
+ getPathname: latest.getPathname,
432
+ isCancelled: () => cancelled,
433
+ moveCursor: cursorMover(latest.timing.cursorMs, setCursor, setRipple)
434
+ }).then((outcome) => {
435
+ if (!cancelled) applyOutcome(outcome, nodeRef, setView, optionsRef.current.onSkip);
436
+ });
437
+ return () => {
438
+ cancelled = true;
439
+ };
440
+ }, [active]);
441
+ return { view, cursor, ripple, nodeRef, refreshRect };
442
+ }
443
+
444
+ // src/engine/firstRunStore.ts
445
+ var OFFER_PREFIX = "__tour-offer-seen:";
446
+ function hasSeenOffer(userId) {
447
+ try {
448
+ return localStorage.getItem(OFFER_PREFIX + userId) !== null;
449
+ } catch {
450
+ return true;
451
+ }
452
+ }
453
+ function markOfferSeen(userId) {
454
+ try {
455
+ localStorage.setItem(OFFER_PREFIX + userId, "1");
456
+ } catch {
457
+ return;
458
+ }
459
+ }
460
+
461
+ // src/engine/tourSession.ts
462
+ var SESSION_KEY = "__tour-state";
463
+ var MODES = Object.values(TourMode);
464
+ function saveSession(active) {
465
+ try {
466
+ if (active === null) sessionStorage.removeItem(SESSION_KEY);
467
+ else sessionStorage.setItem(SESSION_KEY, JSON.stringify(active));
468
+ } catch {
469
+ return;
470
+ }
471
+ }
472
+ function isActiveTour(value) {
473
+ if (typeof value !== "object" || value === null) return false;
474
+ const candidate = value;
475
+ return typeof candidate.tourId === "string" && typeof candidate.step === "number" && MODES.includes(String(candidate.mode));
476
+ }
477
+ function loadSession(tours) {
478
+ try {
479
+ const parsed = JSON.parse(sessionStorage.getItem(SESSION_KEY) ?? "null");
480
+ if (!isActiveTour(parsed)) return null;
481
+ const tour = tours.find((candidate) => candidate.id === parsed.tourId);
482
+ const inRange = tour !== void 0 && parsed.step >= 0 && parsed.step < tour.steps.length;
483
+ return inRange ? { tourId: parsed.tourId, step: parsed.step, mode: parsed.mode } : null;
484
+ } catch {
485
+ return null;
486
+ }
487
+ }
488
+
489
+ // src/enums/TourEventType.ts
490
+ var TourEventType = /* @__PURE__ */ ((TourEventType2) => {
491
+ TourEventType2["Start"] = "tour_start";
492
+ TourEventType2["Finish"] = "tour_finish";
493
+ TourEventType2["Quit"] = "tour_quit";
494
+ return TourEventType2;
495
+ })(TourEventType || {});
496
+
497
+ // src/hooks/useTourControls.ts
498
+ function useTourControls(options) {
499
+ const [active, setActiveState] = useState(() => loadSession(options.tours));
500
+ const [paused, setPaused] = useState(false);
501
+ const [pickerOpen, setPickerOpen] = useState(false);
502
+ const activeRef = useRef(active);
503
+ const optionsRef = useRef(options);
504
+ optionsRef.current = options;
505
+ const setActive = useCallback((next2) => {
506
+ activeRef.current = next2;
507
+ saveSession(next2);
508
+ setActiveState(next2);
509
+ }, []);
510
+ const close = useCallback((type) => {
511
+ const current = activeRef.current;
512
+ if (current === null) return;
513
+ const { onEvent, user } = optionsRef.current;
514
+ onEvent?.({ type, tourId: current.tourId, mode: current.mode });
515
+ if (type === "tour_finish" /* Finish */ && user !== null) markOfferSeen(user.id);
516
+ setPaused(false);
517
+ setActive(null);
518
+ }, [setActive]);
519
+ const start = useCallback((tourId, mode) => {
520
+ if (!optionsRef.current.tours.some((tour) => tour.id === tourId)) return;
521
+ setPickerOpen(false);
522
+ setPaused(false);
523
+ setActive({ tourId, step: 0, mode });
524
+ optionsRef.current.onEvent?.({ type: "tour_start" /* Start */, tourId, mode });
525
+ }, [setActive]);
526
+ const next = useCallback(() => {
527
+ const current = activeRef.current;
528
+ if (current === null) return;
529
+ const tour = optionsRef.current.tours.find((candidate) => candidate.id === current.tourId);
530
+ if (tour === void 0 || current.step + 1 >= tour.steps.length) close("tour_finish" /* Finish */);
531
+ else setActive({ ...current, step: current.step + 1 });
532
+ }, [close, setActive]);
533
+ const back = useCallback(() => {
534
+ const current = activeRef.current;
535
+ if (current !== null && current.step > 0) setActive({ ...current, step: current.step - 1 });
536
+ }, [setActive]);
537
+ const end = useCallback(() => close("tour_quit" /* Quit */), [close]);
538
+ const togglePause = useCallback(() => setPaused((value) => !value), []);
539
+ const openPicker = useCallback(() => setPickerOpen(true), []);
540
+ const closePicker = useCallback(() => setPickerOpen(false), []);
541
+ return { active, paused, pickerOpen, start, next, back, end, togglePause, openPicker, closePicker };
542
+ }
543
+
544
+ // src/hooks/useTourEngine.ts
545
+ function useTourEngine(options) {
546
+ const controls = useTourControls(options);
547
+ const runner = useStepRunner({ ...options, active: controls.active, onSkip: controls.next });
548
+ const action = stepOf(options.tours, controls.active)?.action ?? null;
549
+ useTourKeys(controls);
550
+ useAutoAdvance(controls.active, runner.view.phase, controls.paused, options.timing.autoMs, controls.next);
551
+ useGuideClick({ active: controls.active, phase: runner.view.phase, action, nodeRef: runner.nodeRef, next: controls.next, delayMs: options.timing.guideAdvanceMs });
552
+ useRectTracking(runner.view.phase, runner.refreshRect);
553
+ const labels = useMemo(() => ({ ...defaultTourLabels, ...options.labels }), [options.labels]);
554
+ return {
555
+ ...controls,
556
+ tours: options.tours,
557
+ theme: options.theme,
558
+ labels,
559
+ user: options.user,
560
+ vars: options.vars,
561
+ view: runner.view,
562
+ cursor: runner.cursor,
563
+ ripple: runner.ripple
564
+ };
565
+ }
566
+
567
+ // src/components/styles.ts
568
+ var EASE = "cubic-bezier(.4,0,.2,1)";
569
+ function ringStyle(theme, rect) {
570
+ return {
571
+ position: "fixed",
572
+ zIndex: LAYER_Z,
573
+ pointerEvents: "none",
574
+ left: rect.left - RING_PADDING,
575
+ top: rect.top - RING_PADDING,
576
+ width: rect.width + 2 * RING_PADDING,
577
+ height: rect.height + 2 * RING_PADDING,
578
+ border: `3px solid ${theme.accent}`,
579
+ borderRadius: theme.radius,
580
+ boxShadow: `0 0 0 9999px ${theme.scrim}`,
581
+ transition: `all 350ms ${EASE}`
582
+ };
583
+ }
584
+ function scrimStyle(theme) {
585
+ return { position: "fixed", inset: 0, zIndex: LAYER_Z, pointerEvents: "none", background: theme.scrim };
586
+ }
587
+ function captionStyle(theme, position) {
588
+ return {
589
+ position: "fixed",
590
+ zIndex: LAYER_Z + 5,
591
+ left: position.left,
592
+ top: position.top,
593
+ width: "min(440px, calc(100vw - 24px))",
594
+ boxSizing: "border-box",
595
+ background: theme.surface,
596
+ color: theme.onSurface,
597
+ border: `1px solid ${theme.accent}`,
598
+ borderRadius: theme.radius,
599
+ padding: "14px 16px",
600
+ fontFamily: theme.fontFamily,
601
+ fontSize: 16,
602
+ lineHeight: 1.4,
603
+ overflowWrap: "anywhere",
604
+ transition: `left 350ms ${EASE}, top 350ms ${EASE}`
605
+ };
606
+ }
607
+ function metaStyle(theme) {
608
+ return { color: theme.accent, fontSize: 12, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase", marginBottom: 6 };
609
+ }
610
+ function noteStyle(theme) {
611
+ return { color: theme.accent, fontSize: 14, marginTop: 6 };
612
+ }
613
+ function rowStyle(theme) {
614
+ return { display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8, marginTop: 10, color: theme.muted, fontSize: 13 };
615
+ }
616
+ function buttonStyle(theme, primary) {
617
+ return {
618
+ minHeight: MIN_HIT,
619
+ minWidth: MIN_HIT,
620
+ padding: "8px 14px",
621
+ borderRadius: theme.radius,
622
+ border: `1px solid ${theme.accent}`,
623
+ background: primary ? theme.accent : "transparent",
624
+ color: primary ? theme.onAccent : theme.onSurface,
625
+ fontFamily: theme.fontFamily,
626
+ fontSize: 14,
627
+ fontWeight: 600,
628
+ cursor: "pointer"
629
+ };
630
+ }
631
+ function cursorStyle(point) {
632
+ return {
633
+ position: "fixed",
634
+ left: 0,
635
+ top: 0,
636
+ zIndex: LAYER_Z + 7,
637
+ pointerEvents: "none",
638
+ transform: `translate(${point.x}px, ${point.y}px)`,
639
+ transition: `transform 700ms ${EASE}`
640
+ };
641
+ }
642
+ function rippleStyle(theme, point, grown) {
643
+ return {
644
+ position: "fixed",
645
+ left: point.x - 8,
646
+ top: point.y - 8,
647
+ width: 16,
648
+ height: 16,
649
+ borderRadius: "50%",
650
+ zIndex: LAYER_Z + 6,
651
+ pointerEvents: "none",
652
+ border: `3px solid ${theme.accent}`,
653
+ transform: grown ? "scale(3.2)" : "scale(0.4)",
654
+ opacity: grown ? 0 : 1,
655
+ transition: "transform 600ms ease-out, opacity 600ms ease-out"
656
+ };
657
+ }
658
+
659
+ // src/dom/placement.ts
660
+ var GAP = 16;
661
+ var EDGE = 12;
662
+ var BOTTOM = 24;
663
+ function clamp(value, min, max) {
664
+ return Math.min(Math.max(min, value), max);
665
+ }
666
+ function placeCaption(rect, size, viewport) {
667
+ if (rect === null) return { left: (viewport.width - size.width) / 2, top: viewport.height - size.height - BOTTOM };
668
+ const left = clamp(rect.left + rect.width / 2 - size.width / 2, EDGE, viewport.width - size.width - EDGE);
669
+ const bottom = rect.top + rect.height;
670
+ if (bottom + GAP + size.height < viewport.height) return { left, top: bottom + GAP };
671
+ const above = rect.top - size.height - GAP;
672
+ return { left, top: above > 0 ? above : viewport.height - size.height - EDGE };
673
+ }
674
+ function TourButton({ label, onPress, theme, testID, primary = false, buttonRef }) {
675
+ return /* @__PURE__ */ jsx(
676
+ "button",
677
+ {
678
+ type: "button",
679
+ ref: buttonRef,
680
+ "data-testid": testID,
681
+ "aria-label": label,
682
+ style: buttonStyle(theme, primary),
683
+ onClick: (event) => {
684
+ event.preventDefault();
685
+ event.stopPropagation();
686
+ onPress();
687
+ },
688
+ children: label
689
+ }
690
+ );
691
+ }
692
+ var START = { left: 12, top: 12 };
693
+ function modeName(tour, mode) {
694
+ if (mode === "auto" /* Auto */) return tour.labels.modeAuto;
695
+ return mode === "show" /* Show */ ? tour.labels.modeShow : tour.labels.modeGuide;
696
+ }
697
+ function hintFor(tour, mode, step) {
698
+ if (mode === "auto" /* Auto */) return tour.paused ? tour.labels.paused : tour.labels.autoPlaying;
699
+ return mode === "guide" /* Guide */ && step.action === "click" /* Click */ ? tour.labels.guideHint : tour.labels.continueHint;
700
+ }
701
+ function noteFor(tour) {
702
+ if (tour.view.phase === "missing" /* Missing */) return tour.labels.unavailable;
703
+ return tour.view.phase === "refused" /* Refused */ ? formatLabel(tour.labels.refused, tour.view.refusedName) : "";
704
+ }
705
+ function TourCaption() {
706
+ const tour = useTour();
707
+ const { active, view, theme, labels } = tour;
708
+ const ref = useRef(null);
709
+ const [position, setPosition] = useState(START);
710
+ const stepIndex = active?.step ?? -1;
711
+ useLayoutEffect(() => {
712
+ const node = ref.current;
713
+ if (node === null) return;
714
+ setPosition(placeCaption(view.rect, { width: node.offsetWidth, height: node.offsetHeight }, { width: window.innerWidth, height: window.innerHeight }));
715
+ }, [view.rect, stepIndex]);
716
+ const current = tourOf(tour.tours, active);
717
+ const step = current?.steps[stepIndex];
718
+ if (active === null || current === null || step === void 0) return null;
719
+ const missing = view.phase === "missing" /* Missing */;
720
+ const note = noteFor(tour);
721
+ return /* @__PURE__ */ jsxs("div", { ref, role: "dialog", "aria-live": "polite", "aria-label": current.title, "data-testid": "tour-caption", style: captionStyle(theme, position), children: [
722
+ /* @__PURE__ */ jsx("div", { style: metaStyle(theme), children: formatLabel(labels.captionMeta, current.title, stepIndex + 1, current.steps.length, modeName(tour, active.mode)) }),
723
+ /* @__PURE__ */ jsx("div", { "data-testid": "tour-text", children: substitute(step.text, tour.vars) }),
724
+ note !== "" ? /* @__PURE__ */ jsx("div", { "data-testid": "tour-note", style: noteStyle(theme), children: note }) : null,
725
+ /* @__PURE__ */ jsxs("div", { style: rowStyle(theme), children: [
726
+ /* @__PURE__ */ jsx(TourButton, { label: labels.back, onPress: tour.back, theme, testID: "tour-back" }),
727
+ /* @__PURE__ */ jsx(TourButton, { label: missing ? labels.skip : labels.next, onPress: tour.next, theme, testID: missing ? "tour-skip" : "tour-next", primary: true }),
728
+ /* @__PURE__ */ jsx(TourButton, { label: labels.end, onPress: tour.end, theme, testID: "tour-end" }),
729
+ /* @__PURE__ */ jsx("span", { children: hintFor(tour, active.mode, step) })
730
+ ] })
731
+ ] });
732
+ }
733
+ function TourCursor({ point, theme }) {
734
+ return /* @__PURE__ */ jsx("div", { "data-testid": "tour-cursor", "aria-hidden": "true", style: cursorStyle(point), children: /* @__PURE__ */ jsx("svg", { width: 24, height: 24, viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M3 2l7 19 2.6-7.4L20 11z", fill: theme.surface, stroke: theme.accent, strokeWidth: 1.6 }) }) });
735
+ }
736
+ function TourRipple({ point, theme }) {
737
+ const [grown, setGrown] = useState(false);
738
+ useEffect(() => {
739
+ const frame = requestAnimationFrame(() => setGrown(true));
740
+ return () => cancelAnimationFrame(frame);
741
+ }, []);
742
+ return /* @__PURE__ */ jsx("div", { "data-testid": "tour-ripple", "aria-hidden": "true", style: rippleStyle(theme, point, grown) });
743
+ }
744
+ function TourOverlay() {
745
+ const { active, view, cursor, ripple, theme } = useTour();
746
+ if (active === null || typeof document === "undefined") return null;
747
+ return createPortal(
748
+ /* @__PURE__ */ jsxs("div", { "data-tour-overlay": "", "data-testid": "tour-overlay", children: [
749
+ view.rect !== null ? /* @__PURE__ */ jsx("div", { "data-testid": "tour-ring", style: ringStyle(theme, view.rect) }) : /* @__PURE__ */ jsx("div", { "data-testid": "tour-scrim", style: scrimStyle(theme) }),
750
+ active.mode !== "guide" /* Guide */ && cursor !== null ? /* @__PURE__ */ jsx(TourCursor, { point: cursor, theme }) : null,
751
+ ripple !== null ? /* @__PURE__ */ jsx(TourRipple, { point: ripple, theme }) : null,
752
+ /* @__PURE__ */ jsx(TourCaption, {})
753
+ ] }),
754
+ document.body
755
+ );
756
+ }
757
+ var NO_VARS = {};
758
+ function currentPathname() {
759
+ return typeof window === "undefined" ? "" : window.location.pathname;
760
+ }
761
+ function WebTourProvider(props) {
762
+ const timing = useMemo(() => ({ ...DEFAULT_TIMING, ...props.timing }), [props.timing]);
763
+ const value = useTourEngine({
764
+ tours: props.tours,
765
+ navigate: props.navigate,
766
+ getPathname: props.getPathname ?? currentPathname,
767
+ onEvent: props.onEvent,
768
+ user: props.user ?? null,
769
+ allowWrites: props.allowWrites === true,
770
+ vars: props.vars ?? NO_VARS,
771
+ timing,
772
+ theme: props.theme,
773
+ labels: props.labels
774
+ });
775
+ return /* @__PURE__ */ jsxs(TourContext.Provider, { value, children: [
776
+ props.children,
777
+ /* @__PURE__ */ jsx(TourOverlay, {})
778
+ ] });
779
+ }
780
+ function NativeTourProvider({ tours, theme, labels, children }) {
781
+ const value = useMemo(() => inertTour(tours, theme, labels), [tours, theme, labels]);
782
+ return /* @__PURE__ */ jsx(TourContext.Provider, { value, children });
783
+ }
784
+ function TourProvider(props) {
785
+ return Platform.OS === "web" ? /* @__PURE__ */ jsx(WebTourProvider, { ...props }) : /* @__PURE__ */ jsx(NativeTourProvider, { ...props });
786
+ }
787
+
788
+ // src/components/panelStyles.ts
789
+ function backdropStyle(theme) {
790
+ return { position: "fixed", inset: 0, zIndex: LAYER_Z + 6, background: theme.scrim, display: "flex", alignItems: "center", justifyContent: "center", padding: 12 };
791
+ }
792
+ function panelStyle(theme) {
793
+ return {
794
+ background: theme.surface,
795
+ color: theme.onSurface,
796
+ border: `1px solid ${theme.accent}`,
797
+ borderRadius: theme.radius,
798
+ padding: "20px 22px",
799
+ width: "min(560px, 100%)",
800
+ boxSizing: "border-box",
801
+ maxHeight: "90vh",
802
+ overflow: "auto",
803
+ fontFamily: theme.fontFamily,
804
+ fontSize: 15,
805
+ lineHeight: 1.4
806
+ };
807
+ }
808
+ function titleStyle(theme) {
809
+ return { margin: "0 0 4px", fontSize: 20, fontWeight: 700, color: theme.onSurface };
810
+ }
811
+ function mutedStyle(theme) {
812
+ return { margin: 0, color: theme.muted, fontSize: 13 };
813
+ }
814
+ function groupButtonStyle(theme) {
815
+ return {
816
+ display: "block",
817
+ width: "100%",
818
+ minHeight: MIN_HIT,
819
+ textAlign: "left",
820
+ background: "transparent",
821
+ border: "none",
822
+ borderTop: `1px solid ${theme.divider}`,
823
+ marginTop: 8,
824
+ padding: "12px 0",
825
+ color: theme.accent,
826
+ fontFamily: theme.fontFamily,
827
+ fontSize: 16,
828
+ fontWeight: 700,
829
+ cursor: "pointer"
830
+ };
831
+ }
832
+ function tourRowStyle(theme) {
833
+ return { display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8, padding: "10px 0", borderTop: `1px solid ${theme.divider}` };
834
+ }
835
+ function offerStyle(theme) {
836
+ return {
837
+ position: "fixed",
838
+ right: 12,
839
+ bottom: 12,
840
+ zIndex: LAYER_Z - 1,
841
+ width: "min(360px, calc(100vw - 24px))",
842
+ boxSizing: "border-box",
843
+ background: theme.surface,
844
+ color: theme.onSurface,
845
+ border: `1px solid ${theme.accent}`,
846
+ borderRadius: theme.radius,
847
+ padding: 16,
848
+ fontFamily: theme.fontFamily,
849
+ fontSize: 15,
850
+ lineHeight: 1.4
851
+ };
852
+ }
853
+ function groupTours(tours) {
854
+ const groups = [];
855
+ for (const tour of tours) {
856
+ const group = groups.find((candidate) => candidate.category === tour.category);
857
+ if (group !== void 0) group.tours.push(tour);
858
+ else groups.push({ category: tour.category, tours: [tour] });
859
+ }
860
+ return groups;
861
+ }
862
+ function PickerRow({ tour, firstButtonRef }) {
863
+ const { theme, labels, start } = useTour();
864
+ return /* @__PURE__ */ jsxs("div", { "data-testid": `tour-row-${tour.id}`, style: tourRowStyle(theme), children: [
865
+ /* @__PURE__ */ jsxs("span", { style: { flex: "1 1 160px" }, children: [
866
+ /* @__PURE__ */ jsx("strong", { children: tour.title }),
867
+ /* @__PURE__ */ jsx("br", {}),
868
+ /* @__PURE__ */ jsx("small", { style: mutedStyle(theme), children: formatLabel(labels.stepCount, tour.steps.length) })
869
+ ] }),
870
+ /* @__PURE__ */ jsx(TourButton, { label: labels.guideMe, onPress: () => start(tour.id, "guide" /* Guide */), theme, testID: `tour-start-${tour.id}-guide`, buttonRef: firstButtonRef, primary: true }),
871
+ /* @__PURE__ */ jsx(TourButton, { label: labels.showMe, onPress: () => start(tour.id, "show" /* Show */), theme, testID: `tour-start-${tour.id}-show` }),
872
+ /* @__PURE__ */ jsx(TourButton, { label: labels.auto, onPress: () => start(tour.id, "auto" /* Auto */), theme, testID: `tour-start-${tour.id}-auto` })
873
+ ] });
874
+ }
875
+ function PickerGroup({ group, expanded, onToggle, firstButtonRef }) {
876
+ const { theme, labels } = useTour();
877
+ return /* @__PURE__ */ jsxs("section", { children: [
878
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-expanded": expanded, "data-testid": `tour-group-${group.category}`, style: groupButtonStyle(theme), onClick: onToggle, children: formatLabel(labels.groupTitle, group.category, group.tours.length) }),
879
+ expanded ? group.tours.map((tour, index) => /* @__PURE__ */ jsx(PickerRow, { tour, firstButtonRef: index === 0 ? firstButtonRef : void 0 }, tour.id)) : null
880
+ ] });
881
+ }
882
+ function toggled(set, key) {
883
+ const next = new Set(set);
884
+ if (next.has(key)) next.delete(key);
885
+ else next.add(key);
886
+ return next;
887
+ }
888
+ function TourPicker() {
889
+ const { pickerOpen, closePicker, tours, theme, labels } = useTour();
890
+ const groups = useMemo(() => groupTours(tours), [tours]);
891
+ const [expanded, setExpanded] = useState(() => new Set(groups.slice(0, 1).map((group) => group.category)));
892
+ const firstRef = useRef(null);
893
+ useEffect(() => {
894
+ if (pickerOpen) firstRef.current?.focus();
895
+ }, [pickerOpen]);
896
+ if (!pickerOpen || typeof document === "undefined") return null;
897
+ return createPortal(
898
+ /* @__PURE__ */ jsx(
899
+ "div",
900
+ {
901
+ "data-tour-overlay": "",
902
+ "data-testid": "tour-picker-backdrop",
903
+ style: backdropStyle(theme),
904
+ onClick: (event) => {
905
+ if (event.target === event.currentTarget) closePicker();
906
+ },
907
+ children: /* @__PURE__ */ jsxs("div", { role: "dialog", "aria-modal": "true", "aria-label": labels.pickerTitle, "data-testid": "tour-picker", style: panelStyle(theme), children: [
908
+ /* @__PURE__ */ jsx("h2", { style: titleStyle(theme), children: labels.pickerTitle }),
909
+ /* @__PURE__ */ jsx("p", { style: mutedStyle(theme), children: labels.pickerIntro }),
910
+ groups.map((group, index) => /* @__PURE__ */ jsx(
911
+ PickerGroup,
912
+ {
913
+ group,
914
+ expanded: expanded.has(group.category),
915
+ onToggle: () => setExpanded(toggled(expanded, group.category)),
916
+ firstButtonRef: index === 0 ? firstRef : void 0
917
+ },
918
+ group.category
919
+ )),
920
+ /* @__PURE__ */ jsx("div", { style: { display: "flex", justifyContent: "flex-end", marginTop: 12 }, children: /* @__PURE__ */ jsx(TourButton, { label: labels.close, onPress: closePicker, theme, testID: "tour-picker-close" }) })
921
+ ] })
922
+ }
923
+ ),
924
+ document.body
925
+ );
926
+ }
927
+ function FirstRunOffer({ tourId, mode = "guide" /* Guide */ }) {
928
+ const { user, active, start, openPicker, theme, labels } = useTour();
929
+ const [dismissed, setDismissed] = useState(false);
930
+ if (typeof document === "undefined" || user === null || active !== null || dismissed || hasSeenOffer(user.id)) return null;
931
+ const close = () => {
932
+ markOfferSeen(user.id);
933
+ setDismissed(true);
934
+ };
935
+ const take = () => {
936
+ close();
937
+ if (tourId !== void 0) start(tourId, mode);
938
+ else openPicker();
939
+ };
940
+ return /* @__PURE__ */ jsxs("div", { role: "region", "aria-label": labels.offerTitle, "data-tour-overlay": "", "data-testid": "tour-offer", style: offerStyle(theme), children: [
941
+ /* @__PURE__ */ jsx("strong", { children: labels.offerTitle }),
942
+ /* @__PURE__ */ jsx("p", { style: { margin: "6px 0 12px", color: theme.muted }, children: labels.offerBody }),
943
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexWrap: "wrap", gap: 8 }, children: [
944
+ /* @__PURE__ */ jsx(TourButton, { label: labels.offerStart, onPress: take, theme, testID: "tour-offer-start", primary: true }),
945
+ /* @__PURE__ */ jsx(TourButton, { label: labels.offerDismiss, onPress: close, theme, testID: "tour-offer-dismiss" })
946
+ ] })
947
+ ] });
948
+ }
949
+
950
+ // src/validateTours.ts
951
+ function hasTarget(target) {
952
+ if (typeof target === "string") return target.trim() !== "";
953
+ if (target === void 0 || target === null) return false;
954
+ return typeof target.name === "string" ? target.name.trim() !== "" : target.name instanceof RegExp;
955
+ }
956
+ function stepErrors(tourId, index, step) {
957
+ const where = `tour ${tourId} step ${index + 1}`;
958
+ const errors = [];
959
+ if (!hasTarget(step.target)) errors.push(`${where}: missing target`);
960
+ if (typeof step.text !== "string" || step.text.trim() === "") errors.push(`${where}: missing text`);
961
+ if (step.action === "type" /* Type */ && (step.value ?? "") === "") errors.push(`${where}: type step needs a value`);
962
+ return errors;
963
+ }
964
+ function validateTours(tours) {
965
+ const errors = [];
966
+ const seen = /* @__PURE__ */ new Set();
967
+ tours.forEach((tour, index) => {
968
+ const id = typeof tour.id === "string" && tour.id.trim() !== "" ? tour.id : `#${index + 1}`;
969
+ if (seen.has(id)) errors.push(`tour ${id}: duplicate id`);
970
+ seen.add(id);
971
+ const steps = Array.isArray(tour.steps) ? tour.steps : [];
972
+ if (steps.length === 0) errors.push(`tour ${id}: has no steps`);
973
+ steps.forEach((step, stepIndex) => errors.push(...stepErrors(id, stepIndex, step)));
974
+ });
975
+ return { valid: errors.length === 0, errors };
976
+ }
977
+
978
+ export { DEFAULT_TIMING, FirstRunOffer, StepAction, StepPhase, TargetRole, TourEventType, TourMode, TourPicker, TourProvider, defaultTourLabels, findTarget, formatLabel, isForbiddenClick, useTour, validateTours };
979
+ //# sourceMappingURL=index.mjs.map
980
+ //# sourceMappingURL=index.mjs.map