@eintrek/erp-shell 0.1.67 → 0.1.69

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.
@@ -0,0 +1,3878 @@
1
+ 'use client';
2
+ 'use strict';
3
+
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+ var React = require('react');
6
+ var reactDom = require('react-dom');
7
+ var dom = require('@floating-ui/dom');
8
+
9
+ function _interopNamespaceDefault(e) {
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
27
+
28
+ /**
29
+ * Route and API-path patterns for tour steps.
30
+ *
31
+ * No runtime imports: the tests run this file in Node as it is.
32
+ */
33
+ const trimSlash = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p);
34
+ function splitPattern(pattern) {
35
+ const q = pattern.indexOf("?");
36
+ if (q < 0)
37
+ return { path: pattern, query: new URLSearchParams() };
38
+ return { path: pattern.slice(0, q), query: new URLSearchParams(pattern.slice(q + 1)) };
39
+ }
40
+ function paramName(segment) {
41
+ const bracket = /^\[([A-Za-z0-9_]+)\]$/.exec(segment);
42
+ if (bracket)
43
+ return bracket[1];
44
+ const colon = /^:([A-Za-z0-9_]+)$/.exec(segment);
45
+ return colon ? colon[1] : null;
46
+ }
47
+ function safeDecode(s) {
48
+ try {
49
+ return decodeURIComponent(s);
50
+ }
51
+ catch {
52
+ return s;
53
+ }
54
+ }
55
+ /** `[[name]]`: a segment that may be absent (`/me/[[org]]/attendance`). */
56
+ function optionalName(segment) {
57
+ const m = /^\[\[([A-Za-z0-9_]+)\]\]$/.exec(segment);
58
+ return m ? m[1] : null;
59
+ }
60
+ /**
61
+ * Page segments against pattern segments; `[[x]]` may match nothing. A
62
+ * `code` param, when `code` is given, must be that code.
63
+ */
64
+ function matchPage(want, wi, have, hi, params, code) {
65
+ if (wi === want.length)
66
+ return hi === have.length;
67
+ const bind = (name, raw) => {
68
+ const v = safeDecode(raw);
69
+ if (name === "code" && code !== undefined && v !== code)
70
+ return false;
71
+ params[name] = v;
72
+ if (matchPage(want, wi + 1, have, hi + 1, params, code))
73
+ return true;
74
+ delete params[name];
75
+ return false;
76
+ };
77
+ const opt = optionalName(want[wi]);
78
+ if (opt) {
79
+ // Present first (`/me/O1/attendance`), then absent (`/me/attendance`).
80
+ if (hi < have.length && have[hi] && bind(opt, have[hi]))
81
+ return true;
82
+ return matchPage(want, wi + 1, have, hi, params, code);
83
+ }
84
+ if (hi >= have.length)
85
+ return false;
86
+ const name = paramName(want[wi]);
87
+ if (name)
88
+ return !!have[hi] && bind(name, have[hi]);
89
+ return want[wi] === have[hi] && matchPage(want, wi + 1, have, hi + 1, params, code);
90
+ }
91
+ /**
92
+ * Matches a Next-style page pattern ("/[code]/employee/[id]", optionally
93
+ * "?tab=job") against a path and query. `[code]`, when given, must be the
94
+ * organisation code. `[[x]]` is a segment that may be absent. Returns the
95
+ * params, or null.
96
+ */
97
+ function matchRoute(pattern, pathname, search, code) {
98
+ const { path, query } = splitPattern(pattern);
99
+ const want = trimSlash(path).split("/");
100
+ const have = trimSlash(pathname || "/").split("/");
101
+ const params = {};
102
+ if (!matchPage(want, 0, have, 0, params, code))
103
+ return null;
104
+ if ([...query.keys()].length > 0) {
105
+ const s = search instanceof URLSearchParams ? search : new URLSearchParams(search ?? "");
106
+ for (const [k, v] of query.entries()) {
107
+ if (s.get(k) !== v)
108
+ return null;
109
+ }
110
+ }
111
+ return params;
112
+ }
113
+ /**
114
+ * Fills a page pattern's params ("/[code]/x/[id]" → "/O1/x/42"); null if one
115
+ * is missing. A `[[x]]` segment without a value is left out.
116
+ */
117
+ function fillRoute(pattern, params) {
118
+ const { path, query } = splitPattern(pattern);
119
+ const out = [];
120
+ for (const seg of path.split("/")) {
121
+ const opt = optionalName(seg);
122
+ if (opt) {
123
+ const v = params[opt];
124
+ if (v)
125
+ out.push(encodeURIComponent(v));
126
+ continue;
127
+ }
128
+ const name = paramName(seg);
129
+ if (!name) {
130
+ out.push(seg);
131
+ continue;
132
+ }
133
+ const v = params[name];
134
+ if (!v)
135
+ return null;
136
+ out.push(encodeURIComponent(v));
137
+ }
138
+ const qs = query.toString();
139
+ return out.join("/") + (qs ? `?${qs}` : "");
140
+ }
141
+ /**
142
+ * The path of a request, without origin, base URL query or hash:
143
+ * ("/shifts/4", "https://hr-api/api/v1") → "/api/v1/shifts/4".
144
+ */
145
+ function requestPath(url, baseURL) {
146
+ const raw = url ?? "";
147
+ let full = raw;
148
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) && baseURL) {
149
+ full = baseURL.replace(/\/+$/, "") + "/" + raw.replace(/^\/+/, "");
150
+ }
151
+ try {
152
+ return trimSlash(new URL(full, "http://local.invalid").pathname);
153
+ }
154
+ catch {
155
+ return trimSlash(full.split(/[?#]/)[0] || "/");
156
+ }
157
+ }
158
+ /**
159
+ * Whether a request path matches a step's API path: the pattern's segments
160
+ * must be the END of the path ("/shifts/[id]" matches "/api/v1/shifts/42");
161
+ * `[x]`/`:x` is one segment, `*` any number (including none). A RegExp is
162
+ * tested against the whole path.
163
+ */
164
+ function matchApiPath(pattern, path) {
165
+ if (pattern instanceof RegExp)
166
+ return pattern.test(path);
167
+ const want = trimSlash(pattern).split("/").filter(Boolean);
168
+ const have = trimSlash(path).split("/").filter(Boolean);
169
+ // Try every suffix of the path as the place the pattern starts.
170
+ for (let start = 0; start <= have.length; start++) {
171
+ if (matchSegments(want, 0, have, start))
172
+ return true;
173
+ }
174
+ return false;
175
+ }
176
+ function matchSegments(want, wi, have, hi) {
177
+ if (wi === want.length)
178
+ return hi === have.length;
179
+ const seg = want[wi];
180
+ if (seg === "*") {
181
+ for (let k = hi; k <= have.length; k++) {
182
+ if (matchSegments(want, wi + 1, have, k))
183
+ return true;
184
+ }
185
+ return false;
186
+ }
187
+ if (hi >= have.length)
188
+ return false;
189
+ if (paramName(seg) || seg === have[hi])
190
+ return matchSegments(want, wi + 1, have, hi + 1);
191
+ return false;
192
+ }
193
+ /** "2xx" or an exact status. */
194
+ function matchStatus(want, status) {
195
+ if (want === undefined || want === "2xx")
196
+ return status >= 200 && status < 300;
197
+ return status === want;
198
+ }
199
+
200
+ /**
201
+ * The tour's event bus and anchor helper — the parts an app calls.
202
+ *
203
+ * - `guideAnchor(key, id?)` → `{ "data-guide": key, "data-guide-id"?: id }`
204
+ * - `emitGuideEvent(name, detail?)` → window CustomEvent `erp:guide:<name>`
205
+ * - `reportApiEvent(responseOrError)` → window CustomEvent `erp:api`, which
206
+ * the shell's own axios instance already sends for every answer. An app
207
+ * with a second axios instance calls it from that instance's interceptor.
208
+ * - `reportApiCall({ method, url, status, data })` → the same event, for a
209
+ * client built on plain `fetch` (erp-liff's hrPost).
210
+ *
211
+ * Only method, path, status, the saved record's id and (on a refusal) the
212
+ * server's message go on the bus — never a request or response body.
213
+ *
214
+ * No runtime imports beyond sibling pure modules.
215
+ */
216
+ const GUIDE_ATTRIBUTE = "data-guide";
217
+ const GUIDE_ID_ATTRIBUTE = "data-guide-id";
218
+ const GUIDE_LAYER_ATTRIBUTE = "data-erp-guide-layer";
219
+ const API_EVENT = "erp:api";
220
+ const GUIDE_EVENT_PREFIX = "erp:guide:";
221
+ /** Spread onto the element a tour step points at. */
222
+ function guideAnchor(key, id) {
223
+ return id === undefined || id === null || id === ""
224
+ ? { [GUIDE_ATTRIBUTE]: key }
225
+ : { [GUIDE_ATTRIBUTE]: key, [GUIDE_ID_ATTRIBUTE]: String(id) };
226
+ }
227
+ /** Announces an app event a step can wait for (`advanceOn: { event: name }`). */
228
+ function emitGuideEvent(name, detail) {
229
+ if (typeof window === "undefined" || !name)
230
+ return;
231
+ const clean = {};
232
+ for (const [k, v] of Object.entries(detail ?? {})) {
233
+ if (typeof v === "string" || typeof v === "number")
234
+ clean[k] = String(v);
235
+ }
236
+ try {
237
+ window.dispatchEvent(new CustomEvent(GUIDE_EVENT_PREFIX + name, { detail: clean }));
238
+ }
239
+ catch {
240
+ /* never let the tour break the app */
241
+ }
242
+ }
243
+ const isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
244
+ function idOf(data) {
245
+ const pick = (v) => typeof v === "string" && v ? v : typeof v === "number" ? String(v) : undefined;
246
+ if (!isRecord$1(data))
247
+ return undefined;
248
+ return pick(data.id) ?? (isRecord$1(data.data) ? pick(data.data.id) : undefined);
249
+ }
250
+ function messageOf(data) {
251
+ if (!isRecord$1(data))
252
+ return undefined;
253
+ const m = data.message ?? (isRecord$1(data.error) ? data.error.message : data.error);
254
+ return typeof m === "string" && m.trim() ? m.trim().slice(0, 200) : undefined;
255
+ }
256
+ /** The bus detail for an axios answer or error; null when it is neither. */
257
+ function apiEventDetail(responseOrError) {
258
+ if (!isRecord$1(responseOrError))
259
+ return null;
260
+ const err = responseOrError;
261
+ // An AxiosError has .response (or none: network failure) and .config.
262
+ const isError = "isAxiosError" in responseOrError || ("response" in responseOrError && !("data" in responseOrError));
263
+ const res = isError ? err.response : responseOrError;
264
+ const config = (res?.config ?? err.config);
265
+ if (!config)
266
+ return null;
267
+ const status = typeof res?.status === "number" ? res.status : 0;
268
+ const detail = {
269
+ method: (config.method ?? "get").toUpperCase(),
270
+ path: requestPath(config.url, config.baseURL),
271
+ status,
272
+ };
273
+ if (status >= 200 && status < 300) {
274
+ const id = idOf(res?.data);
275
+ if (id)
276
+ detail.id = id;
277
+ }
278
+ else {
279
+ const msg = messageOf(res?.data);
280
+ if (msg)
281
+ detail.message = msg;
282
+ }
283
+ return detail;
284
+ }
285
+ /** Puts an axios answer (or error) on the bus. Safe to call with anything. */
286
+ function reportApiEvent(responseOrError) {
287
+ if (typeof window === "undefined")
288
+ return;
289
+ try {
290
+ const detail = apiEventDetail(responseOrError);
291
+ if (detail)
292
+ window.dispatchEvent(new CustomEvent(API_EVENT, { detail }));
293
+ }
294
+ catch {
295
+ /* never let the tour break the app */
296
+ }
297
+ }
298
+ /** The bus detail for a fetch-style report; null when it has no URL. */
299
+ function apiCallDetail(call) {
300
+ if (!call || typeof call.url !== "string" || !call.url)
301
+ return null;
302
+ const status = typeof call.status === "number" && Number.isFinite(call.status) ? call.status : 0;
303
+ const detail = {
304
+ method: (call.method || "GET").toUpperCase(),
305
+ path: requestPath(call.url, call.baseURL),
306
+ status,
307
+ };
308
+ if (status >= 200 && status < 300) {
309
+ const id = idOf(call.data);
310
+ if (id)
311
+ detail.id = id;
312
+ }
313
+ else {
314
+ const msg = messageOf(call.data);
315
+ if (msg)
316
+ detail.message = msg;
317
+ }
318
+ return detail;
319
+ }
320
+ /**
321
+ * Puts a request answered through plain `fetch` on the bus (`{ api }`
322
+ * triggers and `completeOn`). Call it once per answer, refusals and network
323
+ * failures (status 0) included. Safe to call with anything.
324
+ */
325
+ function reportApiCall(call) {
326
+ if (typeof window === "undefined")
327
+ return;
328
+ try {
329
+ const detail = apiCallDetail(call);
330
+ if (detail)
331
+ window.dispatchEvent(new CustomEvent(API_EVENT, { detail }));
332
+ }
333
+ catch {
334
+ /* never let the tour break the app */
335
+ }
336
+ }
337
+
338
+ let entry = null;
339
+ let openPanelImpl = null;
340
+ const listeners = new Set();
341
+ function emit() {
342
+ listeners.forEach(l => l());
343
+ }
344
+ function subscribe(l) {
345
+ listeners.add(l);
346
+ return () => {
347
+ listeners.delete(l);
348
+ };
349
+ }
350
+ /** Called by the host: the entry to show (null: none), and how to open the panel. */
351
+ function publishGuideEntry(next, openPanel) {
352
+ const same = (next === null && entry === null) ||
353
+ (next !== null && entry !== null && next.done === entry.done && next.total === entry.total);
354
+ openPanelImpl = openPanel;
355
+ if (!same) {
356
+ entry = next;
357
+ emit();
358
+ }
359
+ }
360
+ /** Opens the tour's quest panel, when this user has a tour here. */
361
+ function openGuidePanel() {
362
+ openPanelImpl?.();
363
+ }
364
+ /** The "?" menu's entry, or null when there is no tour for this user. */
365
+ function useGuideEntry() {
366
+ return React.useSyncExternalStore(subscribe, () => entry, () => null);
367
+ }
368
+
369
+ /* ------------------------------------------------------------------ */
370
+ /* Copy */
371
+ /* ------------------------------------------------------------------ */
372
+ const COPY = {
373
+ fieldFix: "แก้ในช่องที่ไฮไลต์ แล้วกด ถัดไป",
374
+ saveFailed: "บันทึกไม่สำเร็จ",
375
+ blank: "ยังไม่ได้พิมพ์",
376
+ exitToast: "ออกจากไกด์แล้ว",
377
+ replayDone: "ทบทวนภารกิจเสร็จแล้ว",
378
+ replayEnded: "จบการทบทวนแล้ว",
379
+ hiddenToast: "ซ่อนแล้ว",
380
+ aborted: "ไกด์ไปต่อไม่ได้ ลองอีกครั้งภายหลัง",
381
+ bridgeTitle: "กดปุ่มเมนู",
382
+ bridgeWhy: (app) => `เมนูทั้งหมดของ ${app} อยู่ในนี้`,
383
+ };
384
+ /* ------------------------------------------------------------------ */
385
+ /* Helpers */
386
+ /* ------------------------------------------------------------------ */
387
+ const BRIDGE_TARGET = "shell.menu-toggle";
388
+ function initialGuideState(audience, progress) {
389
+ return {
390
+ audience,
391
+ progress,
392
+ screen: { name: "idle" },
393
+ panelOpen: false,
394
+ justDone: null,
395
+ chipPulse: 0,
396
+ nudge: 0,
397
+ gateDismissed: false,
398
+ replayPage: null,
399
+ pendingCelebrate: [],
400
+ };
401
+ }
402
+ function findMission(suite, key) {
403
+ return key ? suite.missions.find(m => m.key === key) : undefined;
404
+ }
405
+ /**
406
+ * Whether the user has this mission (GuideMission.visible). Without the
407
+ * predicate, yes; with it, only `true` (undefined — not known yet — and a
408
+ * throw hide it).
409
+ */
410
+ function missionShown(m, ctx) {
411
+ if (!m.visible)
412
+ return true;
413
+ try {
414
+ return m.visible(ctx) === true;
415
+ }
416
+ catch {
417
+ return false;
418
+ }
419
+ }
420
+ /** The missions this user has, in order: what the panel draws and n/N counts. */
421
+ function shownMissions(suite, ctx) {
422
+ return suite.missions.filter(m => missionShown(m, ctx));
423
+ }
424
+ /** The mission's number among the shown ones (1-based); its place in the suite when hidden. */
425
+ function missionNumber(suite, key, ctx) {
426
+ const shown = shownMissions(suite, ctx);
427
+ const i = shown.findIndex(m => m.key === key);
428
+ return i >= 0 ? i + 1 : suite.missions.findIndex(m => m.key === key) + 1;
429
+ }
430
+ function guideContext(env, data, params = {}) {
431
+ return {
432
+ code: env.code,
433
+ pathname: env.pathname,
434
+ search: env.search,
435
+ params: { code: env.code, ...params },
436
+ data,
437
+ facts: env.facts,
438
+ can: env.can,
439
+ visible: (anchor) => env.isVisible(anchor),
440
+ };
441
+ }
442
+ function resolveText(t, ctx) {
443
+ if (t === undefined)
444
+ return "";
445
+ try {
446
+ return typeof t === "function" ? t(ctx) : t;
447
+ }
448
+ catch {
449
+ return "";
450
+ }
451
+ }
452
+ /** Runs an app predicate; a throw counts as `fallback`. */
453
+ function safe(fn, fallback) {
454
+ try {
455
+ return fn();
456
+ }
457
+ catch {
458
+ return fallback;
459
+ }
460
+ }
461
+ function triggersOf(step) {
462
+ if (!step.advanceOn)
463
+ return [];
464
+ return Array.isArray(step.advanceOn) ? step.advanceOn : [step.advanceOn];
465
+ }
466
+ function stepKind(step) {
467
+ return step.kind ?? "click";
468
+ }
469
+ /** The last checkpoint at or before `index` (a mission's first step always is one). */
470
+ function checkpointAtOrBefore(steps, index) {
471
+ for (let i = Math.min(index, steps.length - 1); i > 0; i--) {
472
+ if (steps[i].checkpoint)
473
+ return i;
474
+ }
475
+ return 0;
476
+ }
477
+ function targetIdOf(step, ctx) {
478
+ if (typeof step.targetId === "function")
479
+ return safe(() => step.targetId(ctx), undefined);
480
+ return step.targetId;
481
+ }
482
+ /**
483
+ * A commit step with nothing to save: its button is not on the page, and what
484
+ * is saved is (GuideStep.nothingToSave).
485
+ */
486
+ function nothingToSaveHolds(step, env, ctx) {
487
+ const n = step.nothingToSave;
488
+ if (!n || !step.target)
489
+ return false;
490
+ return !env.isVisible(step.target, targetIdOf(step, ctx)) && env.isVisible(n.target);
491
+ }
492
+ /**
493
+ * The step as it is shown: a commit step with nothing to save is a read step
494
+ * on what is saved, with its own title (ถัดไป moves on).
495
+ */
496
+ function shownStep(step, nothingToSave) {
497
+ const n = step.nothingToSave;
498
+ if (!nothingToSave || !n)
499
+ return step;
500
+ return {
501
+ key: step.key,
502
+ kind: "view",
503
+ target: n.target,
504
+ title: n.title,
505
+ why: n.why,
506
+ allow: n.allow,
507
+ route: step.route,
508
+ resumeUrl: step.resumeUrl,
509
+ checkpoint: step.checkpoint,
510
+ timeoutMs: step.timeoutMs,
511
+ abort: step.abort,
512
+ };
513
+ }
514
+ /** Whether the step's target (or the bridge's) is on screen. */
515
+ function stepTargetVisible(step, env, ctx, bridge) {
516
+ if (bridge)
517
+ return env.isVisible(BRIDGE_TARGET);
518
+ if (!step.target)
519
+ return true;
520
+ return env.isVisible(step.target, targetIdOf(step, ctx));
521
+ }
522
+ /** The anchor the spotlight is on for the current step. */
523
+ function spotlightTarget(step, ctx, bridge) {
524
+ if (bridge)
525
+ return { anchor: BRIDGE_TARGET };
526
+ if (!step.target)
527
+ return null;
528
+ return { anchor: step.target, id: targetIdOf(step, ctx) };
529
+ }
530
+ function needsBridge(step, env, ctx) {
531
+ return (!!step.target &&
532
+ step.target.startsWith("nav.") &&
533
+ !env.sidebarOpen &&
534
+ !env.isVisible(step.target, targetIdOf(step, ctx)));
535
+ }
536
+ /**
537
+ * The page a step happens on: its own `route`, or else where the steps before
538
+ * it left the user (an earlier step's route trigger or route). Undefined when
539
+ * nothing says (a mission's first steps, which work from any page).
540
+ */
541
+ function stepHomeRoute(steps, index) {
542
+ for (let j = Math.min(index, steps.length - 1); j >= 0; j--) {
543
+ const s = steps[j];
544
+ if (j < index) {
545
+ // What this earlier step moved the user to comes after where it happened.
546
+ const t = triggersOf(s).find((x) => "route" in x);
547
+ if (t)
548
+ return t.route;
549
+ }
550
+ if (s.route)
551
+ return s.route;
552
+ }
553
+ return undefined;
554
+ }
555
+ /**
556
+ * The page a step is shown on, or the "ทำต่อ" card when the user is elsewhere:
557
+ * its route; for a checkpoint without one, the page the steps before it lead
558
+ * to (so going back to it from another page cannot loop).
559
+ */
560
+ function placeRoute(steps, index) {
561
+ const step = steps[index];
562
+ if (step.route)
563
+ return step.route;
564
+ return step.checkpoint ? stepHomeRoute(steps, index) : undefined;
565
+ }
566
+ /** The user is not on the page the step happens on. */
567
+ function offRoute(steps, index, env) {
568
+ const home = stepHomeRoute(steps, index);
569
+ return !!home && !matchRoute(home, env.pathname, env.search, env.code);
570
+ }
571
+ /** What puts the page back when a replay ends at this step (see GuideStep.abort). */
572
+ function abortActionsFor(mission, index) {
573
+ const step = mission.steps[index];
574
+ const own = step?.abort ?? mission.abort;
575
+ if (own)
576
+ return Array.isArray(own) ? own : [own];
577
+ // Default: Escape to the dialog the tour opened; nothing on a stable page.
578
+ if (!step || index === 0 || step.checkpoint)
579
+ return [];
580
+ return [{ escape: true }];
581
+ }
582
+ /** Every anchor the mission's abort actions press. */
583
+ function abortAnchorsOf(mission) {
584
+ const out = new Set();
585
+ const add = (a) => {
586
+ for (const x of a ? (Array.isArray(a) ? a : [a]) : [])
587
+ if ("click" in x)
588
+ out.add(x.click);
589
+ };
590
+ add(mission.abort);
591
+ for (const st of mission.steps)
592
+ add(st.abort);
593
+ return Array.from(out);
594
+ }
595
+ /**
596
+ * What the replay may do to put the page back: not press what the user had
597
+ * open before it started, not Escape out of a dialog that was already open,
598
+ * and no app event while anything of theirs was open.
599
+ */
600
+ function abortActionsLeft(actions, before) {
601
+ if (!before)
602
+ return actions;
603
+ const busy = before.anchors.length > 0 || before.dialog;
604
+ return actions.filter(a => "click" in a ? !before.anchors.includes(a.click) : "escape" in a ? !before.dialog : !busy);
605
+ }
606
+ function routeParamsFor(step, env) {
607
+ if (!step.route)
608
+ return {};
609
+ return matchRoute(step.route, env.pathname, env.search, env.code) ?? {};
610
+ }
611
+ /** A state trigger (route, visible) that holds now; the capture event for it. */
612
+ function stateTriggerHolds(step, env) {
613
+ for (const t of triggersOf(step)) {
614
+ if ("route" in t) {
615
+ const params = matchRoute(t.route, env.pathname, env.search, env.code);
616
+ if (params)
617
+ return { route: { pathname: env.pathname, params } };
618
+ }
619
+ else if ("visible" in t) {
620
+ if (env.isVisible(t.visible))
621
+ return {};
622
+ }
623
+ }
624
+ return null;
625
+ }
626
+ /** Any trigger that holds on a sync (route, visible, and — once armed — hidden). */
627
+ function syncTriggerHolds(step, env, armed) {
628
+ const held = stateTriggerHolds(step, env);
629
+ if (held)
630
+ return held;
631
+ if (!armed)
632
+ return null;
633
+ for (const t of triggersOf(step)) {
634
+ if ("hidden" in t && !env.isVisible(t.hidden))
635
+ return {};
636
+ }
637
+ return null;
638
+ }
639
+ /** Whether any of the step's `hidden` anchors is on screen now. */
640
+ function hiddenAnchorShown(step, env) {
641
+ return triggersOf(step).some(t => "hidden" in t && env.isVisible(t.hidden));
642
+ }
643
+ function missionCount(suite, ctx) {
644
+ return shownMissions(suite, ctx).length;
645
+ }
646
+ function missionSettled(m, entry, ctx) {
647
+ if (entry?.status === "done")
648
+ return true;
649
+ if (m.optional && entry?.status === "skipped")
650
+ return true;
651
+ return safe(() => m.alreadyDone?.(ctx) === true, false);
652
+ }
653
+ /** Settled missions among the shown ones (the n of n/N). */
654
+ function settledCount(suite, progress, ctx) {
655
+ return shownMissions(suite, ctx).filter(m => missionSettled(m, progress.missions[m.key], ctx)).length;
656
+ }
657
+ function gateState(suite, ctx) {
658
+ if (!suite.gate)
659
+ return true;
660
+ return safe(() => suite.gate.ready(ctx), undefined);
661
+ }
662
+ function missionViews(suite, progress, ctx) {
663
+ const gate = gateState(suite, ctx);
664
+ const settled = (key) => {
665
+ const m = findMission(suite, key);
666
+ // A prerequisite this user does not have never locks anything.
667
+ return !!m && (missionSettled(m, progress.missions[key], ctx) || !missionShown(m, ctx));
668
+ };
669
+ let nextMarked = false;
670
+ return shownMissions(suite, ctx).map(mission => {
671
+ const entry = progress.missions[mission.key];
672
+ let view;
673
+ if (entry?.status === "done")
674
+ view = "done";
675
+ else if (safe(() => mission.alreadyDone?.(ctx) === true, false))
676
+ view = "already";
677
+ else if (entry?.status === "skipped")
678
+ view = "skipped";
679
+ else if (entry?.status === "active")
680
+ view = "active";
681
+ else if (gate === false)
682
+ view = "waiting";
683
+ else if ((mission.after ?? []).some(k => !settled(k)))
684
+ view = "locked";
685
+ else
686
+ view = "todo";
687
+ if (!nextMarked && (view === "todo" || view === "active" || view === "skipped")) {
688
+ nextMarked = true;
689
+ if (view === "todo")
690
+ view = "next";
691
+ }
692
+ return { mission, view, entry };
693
+ });
694
+ }
695
+ /** The mission the celebration offers next: the first one not settled and not locked. */
696
+ function nextMissionKey(suite, progress, ctx) {
697
+ for (const v of missionViews(suite, progress, ctx)) {
698
+ if (v.view === "next" || v.view === "todo" || v.view === "active" || v.view === "skipped") {
699
+ return v.mission.key;
700
+ }
701
+ }
702
+ return null;
703
+ }
704
+ /** Whether the welcome should open by itself (with `ctx`: only when a mission is shown). */
705
+ function welcomeDue(state, suite, ctx) {
706
+ return (state.audience === "forced" &&
707
+ state.progress.welcome === "not_seen" &&
708
+ state.progress.status === "in_progress" &&
709
+ !state.progress.mission_key &&
710
+ state.screen.name === "idle" &&
711
+ (ctx ? shownMissions(suite, ctx).length : suite.missions.length) > 0);
712
+ }
713
+ /** Whether the floating "ภารกิจ n/N" chip shows. */
714
+ function chipVisible(state, suite, ctx) {
715
+ return (state.audience !== "none" &&
716
+ state.progress.welcome !== "not_seen" &&
717
+ state.progress.status !== "completed" &&
718
+ !state.progress.chip_hidden &&
719
+ state.screen.name === "idle" &&
720
+ !state.panelOpen &&
721
+ settledCount(suite, state.progress, ctx) < missionCount(suite, ctx));
722
+ }
723
+ function withProgress(d, patch) {
724
+ d.state = { ...d.state, progress: { ...d.state.progress, ...patch } };
725
+ }
726
+ function setMission(d, key, entry) {
727
+ withProgress(d, { missions: { ...d.state.progress.missions, [key]: entry } });
728
+ }
729
+ function setScreen(d, screen) {
730
+ d.state = { ...d.state, screen };
731
+ }
732
+ function save(d, immediate = false) {
733
+ const existing = d.effects.find(e => e.type === "save");
734
+ if (existing)
735
+ existing.immediate = existing.immediate || immediate;
736
+ else
737
+ d.effects.push({ type: "save", immediate });
738
+ }
739
+ function announceStep(d, suite, env) {
740
+ const s = d.state.screen;
741
+ if (s.name !== "step")
742
+ return;
743
+ const mission = findMission(suite, s.mission);
744
+ if (!mission)
745
+ return;
746
+ const step = shownStep(mission.steps[s.index], s.nothingToSave);
747
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
748
+ const title = s.bridge ? COPY.bridgeTitle : plainTitle(resolveText(step.title, ctx));
749
+ const why = s.bridge ? COPY.bridgeWhy(suite.appName) : plainTitle(resolveText(step.why, ctx));
750
+ d.effects.push({
751
+ type: "announce",
752
+ text: `ขั้นที่ ${s.index + 1} จาก ${mission.steps.length}. ${title}${why ? `. ${why}` : ""}`,
753
+ });
754
+ }
755
+ /** "กด [บันทึก]" → "กด บันทึก" (for screen readers). */
756
+ function plainTitle(t) {
757
+ return t.replace(/\[([^\]]+)\]/g, "$1");
758
+ }
759
+ /**
760
+ * Enter step `index` of the mission (or the first one after it that is not
761
+ * skipped, forbidden or already passed). Past the end, the mission is over.
762
+ */
763
+ function enterStep(d, suite, env, mission, index, opts) {
764
+ const steps = mission.steps;
765
+ let i = Math.max(0, index);
766
+ let firstPass = true;
767
+ while (i < steps.length) {
768
+ const step = steps[i];
769
+ const params = routeParamsFor(step, env);
770
+ const ctx = guideContext(env, d.state.progress.context, params);
771
+ if (step.requires && !safe(() => env.can(step.requires), true)) {
772
+ // A replay writes nothing, not even what went wrong.
773
+ if (!opts.replay)
774
+ withProgress(d, { last_error: `forbidden:${step.requires}`.slice(0, 128) });
775
+ i++;
776
+ continue;
777
+ }
778
+ if (step.skipIf && safe(() => step.skipIf(ctx), false)) {
779
+ i++;
780
+ continue;
781
+ }
782
+ const autoPass = step.autoPass !== false && !(firstPass && opts.noAutoPass);
783
+ firstPass = false;
784
+ if (autoPass && stepKind(step) !== "input" && stepKind(step) !== "view") {
785
+ const held = stateTriggerHolds(step, env);
786
+ if (held) {
787
+ captureInto(d, step, held, ctx);
788
+ i++;
789
+ continue;
790
+ }
791
+ }
792
+ break;
793
+ }
794
+ if (i >= steps.length) {
795
+ finishMission(d, suite, env, mission, opts.replay);
796
+ return;
797
+ }
798
+ const step = steps[i];
799
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
800
+ const where = placeRoute(steps, i);
801
+ const away = !!where && !matchRoute(where, env.pathname, env.search, env.code);
802
+ const bridge = !away && needsBridge(step, env, ctx);
803
+ setScreen(d, {
804
+ name: "step",
805
+ mission: mission.key,
806
+ index: i,
807
+ replay: opts.replay,
808
+ bridge,
809
+ phase: away ? "away" : "waiting",
810
+ error: opts.error ?? null,
811
+ confirmExit: false,
812
+ misses: 0,
813
+ armed: hiddenAnchorShown(step, env),
814
+ nothingToSave: !away && !bridge && nothingToSaveHolds(step, env, ctx),
815
+ });
816
+ if (!opts.replay) {
817
+ const cp = checkpointAtOrBefore(steps, i);
818
+ // Done outside the tour meanwhile (completeOn): it stays done.
819
+ if (d.state.progress.missions[mission.key]?.status !== "done") {
820
+ setMission(d, mission.key, { status: "active", step_key: step.key });
821
+ }
822
+ withProgress(d, {
823
+ mission_key: mission.key,
824
+ step_key: step.key,
825
+ step_index: i,
826
+ checkpoint_key: steps[cp].key,
827
+ });
828
+ save(d);
829
+ }
830
+ if (!away) {
831
+ // The target may already be there.
832
+ markReadyIfVisible(d, suite, env);
833
+ }
834
+ }
835
+ /**
836
+ * The save button came (a change) or went (nothing left to save): show the
837
+ * commit step's other form. A ready step whose new target is not there is
838
+ * left to the target-lost path (back to the checkpoint).
839
+ */
840
+ function setNothingToSave(d, suite, env, on) {
841
+ const s = d.state.screen;
842
+ if (s.name !== "step" || s.nothingToSave === on)
843
+ return;
844
+ setScreen(d, { ...s, nothingToSave: on, error: null });
845
+ if (s.phase !== "ready") {
846
+ markReadyIfVisible(d, suite, env);
847
+ return;
848
+ }
849
+ const mission = findMission(suite, s.mission);
850
+ if (!mission)
851
+ return;
852
+ const step = shownStep(mission.steps[s.index], on);
853
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
854
+ if (stepTargetVisible(step, env, ctx, s.bridge))
855
+ announceStep(d, suite, env);
856
+ }
857
+ function markReadyIfVisible(d, suite, env) {
858
+ const s = d.state.screen;
859
+ if (s.name !== "step" || s.phase !== "waiting")
860
+ return;
861
+ const mission = findMission(suite, s.mission);
862
+ if (!mission)
863
+ return;
864
+ const step = shownStep(mission.steps[s.index], s.nothingToSave);
865
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
866
+ if (stepTargetVisible(step, env, ctx, s.bridge)) {
867
+ setScreen(d, { ...s, phase: "ready" });
868
+ announceStep(d, suite, env);
869
+ if (s.error)
870
+ d.effects.push({ type: "announce", text: s.error.title });
871
+ }
872
+ }
873
+ /** Where to send the user to resume at a step: its resumeUrl, or its page filled in. */
874
+ function resumeHref(mission, index, d, env) {
875
+ const step = mission.steps[index];
876
+ const ctx = guideContext(env, d.state.progress.context);
877
+ const where = placeRoute(mission.steps, index);
878
+ return (safe(() => step.resumeUrl?.(ctx), undefined) ??
879
+ (where ? fillRoute(where, { ...d.state.progress.context, code: env.code }) : null));
880
+ }
881
+ /**
882
+ * The user left the page the step happens on (a link, the browser's back):
883
+ * back to the last checkpoint. On another page that is the "ทำต่อ" card;
884
+ * `navigate` (ลองอีกครั้ง) goes there at once.
885
+ */
886
+ function recoverOffRoute(d, suite, env, navigate) {
887
+ const s = d.state.screen;
888
+ if (s.name !== "step")
889
+ return;
890
+ const mission = findMission(suite, s.mission);
891
+ if (!mission)
892
+ return;
893
+ const cp = checkpointAtOrBefore(mission.steps, s.index);
894
+ enterStep(d, suite, env, mission, cp, { replay: s.replay });
895
+ const now = d.state.screen;
896
+ if (navigate && now.name === "step" && now.phase === "away") {
897
+ const href = resumeHref(mission, now.index, d, env);
898
+ if (href)
899
+ d.effects.push({ type: "navigate", href });
900
+ }
901
+ }
902
+ function captureInto(d, step, e, ctx) {
903
+ if (!step.capture)
904
+ return;
905
+ const got = safe(() => step.capture(e, ctx), undefined);
906
+ if (!got)
907
+ return;
908
+ const clean = {};
909
+ for (const [k, v] of Object.entries(got)) {
910
+ if (typeof v === "string" && v)
911
+ clean[k] = v;
912
+ }
913
+ if (Object.keys(clean).length) {
914
+ withProgress(d, { context: { ...d.state.progress.context, ...clean } });
915
+ }
916
+ }
917
+ function advance(d, suite, env, capture) {
918
+ const s = d.state.screen;
919
+ if (s.name !== "step")
920
+ return;
921
+ const mission = findMission(suite, s.mission);
922
+ if (!mission)
923
+ return;
924
+ const step = mission.steps[s.index];
925
+ if (capture) {
926
+ captureInto(d, step, capture, guideContext(env, d.state.progress.context, routeParamsFor(step, env)));
927
+ }
928
+ enterStep(d, suite, env, mission, s.index + 1, { replay: s.replay });
929
+ }
930
+ function finishMission(d, suite, env, mission, replay) {
931
+ if (replay) {
932
+ setScreen(d, { name: "idle" });
933
+ d.effects.push({ type: "toast", text: COPY.replayDone });
934
+ return;
935
+ }
936
+ setMission(d, mission.key, { status: "done", step_key: null, skipped_step: null });
937
+ withProgress(d, {
938
+ mission_key: null,
939
+ step_key: null,
940
+ step_index: 0,
941
+ checkpoint_key: null,
942
+ context: {},
943
+ last_error: null,
944
+ });
945
+ const ctx = guideContext(env, {});
946
+ const all = settledCount(suite, d.state.progress, ctx) >= missionCount(suite, ctx);
947
+ if (all)
948
+ withProgress(d, { status: "completed" });
949
+ // This celebration (or the finish) covers a passive one for the same mission.
950
+ const pending = all ? [] : (d.state.pendingCelebrate ?? []).filter(k => k !== mission.key);
951
+ d.state = { ...d.state, pendingCelebrate: pending };
952
+ showCelebration(d, suite, mission, all, ctx);
953
+ save(d, true);
954
+ }
955
+ /** The celebration (or the finish) for a mission just done, and what it announces. */
956
+ function showCelebration(d, suite, mission, all, ctx) {
957
+ setScreen(d, all ? { name: "complete" } : { name: "celebrate", mission: mission.key });
958
+ d.state = { ...d.state, justDone: mission.key };
959
+ const n = settledCount(suite, d.state.progress, ctx);
960
+ const N = missionCount(suite, ctx);
961
+ const title = resolveText(mission.done?.title, ctx) || `${mission.title}แล้ว`;
962
+ d.effects.push({
963
+ type: "announce",
964
+ text: all
965
+ ? `ครบ ${N} ภารกิจ ${resolveText(suite.complete.title, ctx) || "บริษัทพร้อมใช้งานแล้ว"}`
966
+ : `ภารกิจสำเร็จ ${title} เสร็จ ${n} จาก ${N} ภารกิจ`,
967
+ });
968
+ }
969
+ /** A mission's `completeOn` triggers, as a list. */
970
+ function completeTriggersOf(mission) {
971
+ if (!mission.completeOn)
972
+ return [];
973
+ return Array.isArray(mission.completeOn) ? mission.completeOn : [mission.completeOn];
974
+ }
975
+ /** Every app event name a suite's `completeOn` listens for. */
976
+ function passiveEventNames(suite) {
977
+ const out = new Set();
978
+ for (const m of suite.missions) {
979
+ for (const t of completeTriggersOf(m))
980
+ if ("event" in t && t.event)
981
+ out.add(t.event);
982
+ }
983
+ return Array.from(out);
984
+ }
985
+ /** Missions whose `completeOn` this signal meets ({ api } and { event } only). */
986
+ function passiveMatches(suite, sig) {
987
+ if (sig.kind !== "api" && sig.kind !== "event")
988
+ return [];
989
+ return suite.missions.filter(m => completeTriggersOf(m).some(t => {
990
+ if ("api" in t && sig.kind === "api") {
991
+ if (t.api.method && t.api.method.toUpperCase() !== sig.method.toUpperCase())
992
+ return false;
993
+ return matchApiPath(t.api.path, sig.path) && matchStatus(t.api.status, sig.status);
994
+ }
995
+ return "event" in t && sig.kind === "event" && t.event === sig.name;
996
+ }));
997
+ }
998
+ /**
999
+ * A mission done outside the tour: done with the ordinary save; its
1000
+ * celebration waits for the next idle moment (idleCelebrate). A mission being
1001
+ * played right now is left to its own end (which celebrates it); one already
1002
+ * done changes nothing.
1003
+ */
1004
+ function passiveDone(d, suite, env, mission) {
1005
+ if (d.state.progress.missions[mission.key]?.status === "done")
1006
+ return;
1007
+ const s = d.state.screen;
1008
+ const playing = s.name === "step" && !s.replay && s.mission === mission.key;
1009
+ setMission(d, mission.key, { status: "done", step_key: null, skipped_step: null });
1010
+ if (!playing && d.state.progress.mission_key === mission.key) {
1011
+ // Saved as the one in progress (not running now): nothing to resume.
1012
+ withProgress(d, { mission_key: null, step_key: null, step_index: 0, checkpoint_key: null, context: {} });
1013
+ }
1014
+ const ctx = guideContext(env, {});
1015
+ if (!playing && settledCount(suite, d.state.progress, ctx) >= missionCount(suite, ctx)) {
1016
+ withProgress(d, { status: "completed" });
1017
+ }
1018
+ const pending = d.state.pendingCelebrate ?? [];
1019
+ if (missionShown(mission, ctx) && !pending.includes(mission.key)) {
1020
+ d.state = { ...d.state, pendingCelebrate: [...pending, mission.key] };
1021
+ }
1022
+ save(d, true);
1023
+ }
1024
+ function startMission(d, suite, env, key, replay) {
1025
+ const mission = findMission(suite, key);
1026
+ if (!mission || mission.steps.length === 0)
1027
+ return;
1028
+ const entry = d.state.progress.missions[key];
1029
+ // A mission already done is only ever replayed; its done status stays.
1030
+ const isReplay = replay || entry?.status === "done";
1031
+ const before = d.state.progress;
1032
+ d.state = { ...d.state, panelOpen: false, justDone: null };
1033
+ if (d.state.progress.welcome === "not_seen")
1034
+ withProgress(d, { welcome: "started" });
1035
+ if (!isReplay && d.state.progress.mission_key !== key)
1036
+ withProgress(d, { context: {} });
1037
+ if (!isReplay && d.state.progress.status !== "in_progress") {
1038
+ // Picking up an optional mission after the tour completed.
1039
+ withProgress(d, { status: "in_progress" });
1040
+ }
1041
+ // Resume where it was left: back to the checkpoint at or before it.
1042
+ let index = 0;
1043
+ if (!isReplay && entry && (entry.status === "active" || entry.status === "skipped")) {
1044
+ const at = mission.steps.findIndex(s => s.key === (entry.step_key ?? entry.skipped_step));
1045
+ if (at > 0)
1046
+ index = checkpointAtOrBefore(mission.steps, at);
1047
+ }
1048
+ if (isReplay) {
1049
+ // What is open now is the user's: ending the replay leaves it alone.
1050
+ d.state = {
1051
+ ...d.state,
1052
+ replayPage: {
1053
+ mission: key,
1054
+ anchors: abortAnchorsOf(mission).filter(a => safe(() => env.isVisible(a), false)),
1055
+ dialog: safe(() => env.dialogOpen?.() === true, false),
1056
+ },
1057
+ };
1058
+ }
1059
+ enterStep(d, suite, env, mission, index, { replay: isReplay });
1060
+ // A replay never writes progress; only what starting it changed (the
1061
+ // welcome, first seen through a replay) is saved.
1062
+ if (isReplay && d.state.progress !== before)
1063
+ save(d);
1064
+ }
1065
+ function exitMission(d) {
1066
+ const s = d.state.screen;
1067
+ if (s.name !== "step")
1068
+ return;
1069
+ if (!s.replay) {
1070
+ const prev = d.state.progress.missions[s.mission];
1071
+ if (prev?.status !== "done") {
1072
+ setMission(d, s.mission, {
1073
+ status: "skipped",
1074
+ step_key: d.state.progress.step_key,
1075
+ skipped_step: d.state.progress.step_key,
1076
+ });
1077
+ }
1078
+ withProgress(d, { mission_key: null });
1079
+ save(d, true);
1080
+ }
1081
+ d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
1082
+ setScreen(d, { name: "idle" });
1083
+ }
1084
+ function triggerMatchesSignal(t, sig, env, ctx) {
1085
+ if ("api" in t && sig.kind === "api") {
1086
+ if (t.api.method && t.api.method.toUpperCase() !== sig.method.toUpperCase())
1087
+ return null;
1088
+ if (!matchApiPath(t.api.path, sig.path))
1089
+ return null;
1090
+ if (!matchStatus(t.api.status, sig.status))
1091
+ return null;
1092
+ return { api: { method: sig.method.toUpperCase(), path: sig.path, status: sig.status, id: sig.id } };
1093
+ }
1094
+ if ("event" in t && sig.kind === "event") {
1095
+ return t.event === sig.name ? { event: { name: sig.name, detail: sig.detail } } : null;
1096
+ }
1097
+ if ("activate" in t && sig.kind === "activate")
1098
+ return {};
1099
+ if ("value" in t && sig.kind === "value") {
1100
+ return safe(() => t.value(sig.value, ctx), false) ? {} : null;
1101
+ }
1102
+ return null;
1103
+ }
1104
+ /** A refused save that a commit step listens for. */
1105
+ function apiFailureFor(step, sig) {
1106
+ if (sig.kind !== "api" || sig.status < 400)
1107
+ return false;
1108
+ return triggersOf(step).some(t => "api" in t &&
1109
+ (!t.api.method || t.api.method.toUpperCase() === sig.method.toUpperCase()) &&
1110
+ matchApiPath(t.api.path, sig.path));
1111
+ }
1112
+ /** A replay ends early: what puts the page back (nothing on another page). */
1113
+ function pushAbort(d, suite, s) {
1114
+ if (s.phase === "away")
1115
+ return;
1116
+ const mission = findMission(suite, s.mission);
1117
+ if (!mission)
1118
+ return;
1119
+ const before = d.state.replayPage?.mission === s.mission ? d.state.replayPage : null;
1120
+ const actions = abortActionsLeft(abortActionsFor(mission, s.index), before);
1121
+ if (actions.length)
1122
+ d.effects.push({ type: "abort", actions });
1123
+ }
1124
+ function reduceGuide(state, action, suite, env) {
1125
+ const d = { state, effects: [] };
1126
+ const s = state.screen;
1127
+ const ctxNow = () => guideContext(env, d.state.progress.context);
1128
+ switch (action.type) {
1129
+ case "welcome": {
1130
+ if (!welcomeDue(state, suite))
1131
+ break;
1132
+ const gate = gateState(suite, ctxNow());
1133
+ if (gate === undefined)
1134
+ break;
1135
+ if (gate === false) {
1136
+ if (!state.gateDismissed)
1137
+ setScreen(d, { name: "gate" });
1138
+ break;
1139
+ }
1140
+ setScreen(d, { name: "welcome", confirm: false });
1141
+ break;
1142
+ }
1143
+ case "welcomeSkip":
1144
+ if (s.name === "welcome")
1145
+ setScreen(d, { name: "welcome", confirm: true });
1146
+ break;
1147
+ case "welcomeStart":
1148
+ case "welcomeSkipCancel": {
1149
+ if (s.name !== "welcome")
1150
+ break;
1151
+ const first = nextMissionKey(suite, d.state.progress, ctxNow());
1152
+ if (first)
1153
+ startMission(d, suite, env, first, false);
1154
+ else
1155
+ setScreen(d, { name: "idle" });
1156
+ break;
1157
+ }
1158
+ case "welcomeSkipConfirm":
1159
+ if (s.name !== "welcome")
1160
+ break;
1161
+ withProgress(d, { welcome: "skipped" });
1162
+ d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
1163
+ setScreen(d, { name: "idle" });
1164
+ save(d, true);
1165
+ break;
1166
+ case "gateLater":
1167
+ if (s.name === "gate") {
1168
+ d.state = { ...d.state, gateDismissed: true };
1169
+ setScreen(d, { name: "idle" });
1170
+ }
1171
+ break;
1172
+ case "start":
1173
+ if (state.audience === "none")
1174
+ break;
1175
+ if (s.name === "step" && !s.replay && s.mission !== action.mission) {
1176
+ // Leaving one mission for another: the first is set aside.
1177
+ exitMission(d);
1178
+ }
1179
+ startMission(d, suite, env, action.mission, !!action.replay);
1180
+ break;
1181
+ case "resume": {
1182
+ if (state.audience === "none" || s.name !== "idle")
1183
+ break;
1184
+ const mission = findMission(suite, d.state.progress.mission_key);
1185
+ if (!mission || d.state.progress.missions[mission.key]?.status !== "active")
1186
+ break;
1187
+ // Back to the last checkpoint at or before the step reached; the saved
1188
+ // checkpoint when the step is no longer in the tour.
1189
+ const stepAt = mission.steps.findIndex(st => st.key === d.state.progress.step_key);
1190
+ const cpAt = mission.steps.findIndex(st => st.key === d.state.progress.checkpoint_key);
1191
+ const index = stepAt >= 0 ? checkpointAtOrBefore(mission.steps, stepAt) : Math.max(cpAt, 0);
1192
+ enterStep(d, suite, env, mission, index, { replay: false });
1193
+ break;
1194
+ }
1195
+ case "sync": {
1196
+ if (s.name !== "step")
1197
+ break;
1198
+ const mission = findMission(suite, s.mission);
1199
+ if (!mission)
1200
+ break;
1201
+ const step = mission.steps[s.index];
1202
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
1203
+ if (s.phase === "away") {
1204
+ const where = placeRoute(mission.steps, s.index);
1205
+ if (!where || matchRoute(where, env.pathname, env.search, env.code)) {
1206
+ // Arrived: run the step again from here (it may already be passed).
1207
+ enterStep(d, suite, env, mission, s.index, { replay: s.replay, error: s.error });
1208
+ }
1209
+ break;
1210
+ }
1211
+ if (s.confirmExit)
1212
+ break;
1213
+ const nts = !s.bridge && nothingToSaveHolds(step, env, ctx);
1214
+ if (nts !== s.nothingToSave) {
1215
+ setNothingToSave(d, suite, env, nts);
1216
+ break;
1217
+ }
1218
+ const kind = stepKind(shownStep(step, s.nothingToSave));
1219
+ const armed = s.armed || hiddenAnchorShown(step, env);
1220
+ if (kind !== "input" && kind !== "view") {
1221
+ const held = syncTriggerHolds(step, env, armed);
1222
+ if (held) {
1223
+ advance(d, suite, env, held);
1224
+ break;
1225
+ }
1226
+ }
1227
+ if (!s.bridge && !stepTargetVisible(shownStep(step, s.nothingToSave), env, ctx, false) && offRoute(mission.steps, s.index, env)) {
1228
+ // The target is missing because the page is another one.
1229
+ recoverOffRoute(d, suite, env, false);
1230
+ break;
1231
+ }
1232
+ if (armed !== s.armed)
1233
+ setScreen(d, { ...s, armed });
1234
+ const cur = d.state.screen;
1235
+ // The menu step: done once the sidebar is open; needed again if shut.
1236
+ if (cur.bridge && (env.sidebarOpen || stepTargetVisible(step, env, ctx, false))) {
1237
+ setScreen(d, { ...cur, bridge: false, phase: "waiting" });
1238
+ }
1239
+ else if (!cur.bridge && needsBridge(step, env, ctx)) {
1240
+ setScreen(d, { ...cur, bridge: true, phase: "waiting" });
1241
+ }
1242
+ markReadyIfVisible(d, suite, env);
1243
+ break;
1244
+ }
1245
+ case "signal": {
1246
+ if (s.name !== "step" || s.phase === "away" || s.confirmExit)
1247
+ break;
1248
+ const mission = findMission(suite, s.mission);
1249
+ if (!mission)
1250
+ break;
1251
+ const step = mission.steps[s.index];
1252
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
1253
+ const sig = action.signal;
1254
+ if (sig.kind === "typing") {
1255
+ if (s.error)
1256
+ setScreen(d, { ...s, error: null });
1257
+ break;
1258
+ }
1259
+ if (s.bridge)
1260
+ break;
1261
+ for (const t of triggersOf(step)) {
1262
+ const hit = triggerMatchesSignal(t, sig, env, ctx);
1263
+ if (hit) {
1264
+ advance(d, suite, env, hit);
1265
+ return { state: d.state, effects: d.effects };
1266
+ }
1267
+ }
1268
+ if (sig.kind === "api" && stepKind(step) === "commit" && apiFailureFor(step, sig)) {
1269
+ const mapped = safe(() => step.onApiError?.({ status: sig.status, message: sig.message }, ctx), undefined);
1270
+ if (mapped && mapped.step) {
1271
+ const to = mission.steps.findIndex(st => st.key === mapped.step);
1272
+ if (to >= 0) {
1273
+ enterStep(d, suite, env, mission, to, {
1274
+ replay: s.replay,
1275
+ noAutoPass: true,
1276
+ error: { title: mapped.message ?? sig.message ?? COPY.saveFailed, detail: COPY.fieldFix },
1277
+ });
1278
+ break;
1279
+ }
1280
+ }
1281
+ const error = mapped?.message
1282
+ ? { title: mapped.message, detail: undefined }
1283
+ : { title: COPY.saveFailed, detail: sig.message };
1284
+ setScreen(d, { ...s, error });
1285
+ d.effects.push({ type: "announce", text: [error.title, error.detail].filter(Boolean).join(". ") });
1286
+ if (!s.replay)
1287
+ withProgress(d, { last_error: `api_${sig.status}:${step.key}`.slice(0, 128) });
1288
+ }
1289
+ break;
1290
+ }
1291
+ case "next": {
1292
+ if (s.name !== "step" || s.phase !== "ready" || s.confirmExit || s.bridge)
1293
+ break;
1294
+ const mission = findMission(suite, s.mission);
1295
+ if (!mission)
1296
+ break;
1297
+ const step = mission.steps[s.index];
1298
+ const kind = stepKind(shownStep(step, s.nothingToSave));
1299
+ if (kind === "view") {
1300
+ // A read step, or a commit step with nothing to save.
1301
+ advance(d, suite, env);
1302
+ break;
1303
+ }
1304
+ if (kind !== "input")
1305
+ break;
1306
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
1307
+ const value = safe(() => env.targetValue(), "");
1308
+ const problem = step.validate
1309
+ ? safe(() => step.validate(value, ctx), null)
1310
+ : value.trim()
1311
+ ? null
1312
+ : COPY.blank;
1313
+ if (problem) {
1314
+ setScreen(d, { ...s, error: { title: problem, detail: COPY.fieldFix } });
1315
+ d.state = { ...d.state, nudge: d.state.nudge + 1 };
1316
+ d.effects.push({ type: "announce", text: problem });
1317
+ }
1318
+ else {
1319
+ advance(d, suite, env);
1320
+ }
1321
+ break;
1322
+ }
1323
+ case "targetLost": {
1324
+ if (s.name !== "step" || s.phase !== "ready" || s.confirmExit)
1325
+ break;
1326
+ const mission = findMission(suite, s.mission);
1327
+ if (!mission)
1328
+ break;
1329
+ const raw = mission.steps[s.index];
1330
+ const ctx = guideContext(env, d.state.progress.context, routeParamsFor(raw, env));
1331
+ // The save went with nothing left to save, or came back: the other form.
1332
+ setNothingToSave(d, suite, env, !s.bridge && nothingToSaveHolds(raw, env, ctx));
1333
+ const cur = d.state.screen;
1334
+ if (stepTargetVisible(shownStep(raw, cur.nothingToSave), env, ctx, cur.bridge))
1335
+ break;
1336
+ if (!cur.bridge && offRoute(mission.steps, cur.index, env)) {
1337
+ recoverOffRoute(d, suite, env, false);
1338
+ break;
1339
+ }
1340
+ const cp = checkpointAtOrBefore(mission.steps, cur.index);
1341
+ if (cp < cur.index && !cur.bridge) {
1342
+ // A dialog or a menu closed under the step: back to what opens it.
1343
+ enterStep(d, suite, env, mission, cp, { replay: cur.replay, noAutoPass: false });
1344
+ }
1345
+ else {
1346
+ setScreen(d, { ...cur, phase: "waiting" });
1347
+ }
1348
+ break;
1349
+ }
1350
+ case "timeout": {
1351
+ if (s.name !== "step" || s.phase !== "waiting")
1352
+ break;
1353
+ const mission = findMission(suite, s.mission);
1354
+ if (!mission)
1355
+ break;
1356
+ const step = mission.steps[s.index];
1357
+ if (!s.bridge && offRoute(mission.steps, s.index, env)) {
1358
+ recoverOffRoute(d, suite, env, false);
1359
+ break;
1360
+ }
1361
+ const anchor = s.bridge ? BRIDGE_TARGET : (step.target ?? step.key);
1362
+ // Diagnostic only: kept with the progress, sent with its next save (a
1363
+ // replay keeps nothing). The same error again changes nothing, so it
1364
+ // never sends a PUT on its own.
1365
+ if (!s.replay)
1366
+ withProgress(d, { last_error: `target_missing:${anchor}`.slice(0, 128) });
1367
+ const misses = s.misses + 1;
1368
+ const policy = step.onMissing ?? "retry";
1369
+ const cp = checkpointAtOrBefore(mission.steps, s.index);
1370
+ if (policy === "skip") {
1371
+ advance(d, suite, env);
1372
+ }
1373
+ else if (policy === "abort") {
1374
+ exitMission(d);
1375
+ d.effects.push({ type: "toast", text: COPY.aborted });
1376
+ }
1377
+ else if ((policy === "rewind" || (policy === "retry" && misses >= 2)) && cp < s.index) {
1378
+ enterStep(d, suite, env, mission, cp, { replay: s.replay });
1379
+ const now = d.state.screen;
1380
+ if (now.name === "step" && now.index === s.index) {
1381
+ // The checkpoint passed straight back to this step (its dialog is
1382
+ // still open): going back cannot help, so say so.
1383
+ setScreen(d, { ...now, phase: "missing", misses });
1384
+ d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
1385
+ }
1386
+ }
1387
+ else {
1388
+ setScreen(d, { ...s, phase: "missing", misses });
1389
+ d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
1390
+ }
1391
+ break;
1392
+ }
1393
+ case "retry": {
1394
+ if (s.name !== "step" || s.phase !== "missing")
1395
+ break;
1396
+ const mission = findMission(suite, s.mission);
1397
+ if (mission && !s.bridge && offRoute(mission.steps, s.index, env)) {
1398
+ // Polling again cannot help on another page: go back to the step's.
1399
+ recoverOffRoute(d, suite, env, true);
1400
+ break;
1401
+ }
1402
+ setScreen(d, { ...s, phase: "waiting" });
1403
+ markReadyIfVisible(d, suite, env);
1404
+ break;
1405
+ }
1406
+ case "blocked":
1407
+ if (s.name === "step")
1408
+ d.state = { ...d.state, nudge: d.state.nudge + 1 };
1409
+ break;
1410
+ case "exit":
1411
+ if (s.name !== "step")
1412
+ break;
1413
+ if (s.replay) {
1414
+ pushAbort(d, suite, s);
1415
+ setScreen(d, { name: "idle" });
1416
+ d.effects.push({ type: "toast", text: COPY.replayEnded });
1417
+ }
1418
+ else {
1419
+ setScreen(d, { ...s, confirmExit: true });
1420
+ }
1421
+ break;
1422
+ case "exitCancel":
1423
+ if (s.name === "step" && s.confirmExit)
1424
+ setScreen(d, { ...s, confirmExit: false });
1425
+ break;
1426
+ case "exitConfirm":
1427
+ if (s.name !== "step")
1428
+ break;
1429
+ exitMission(d);
1430
+ d.effects.push({ type: "toast", text: COPY.exitToast });
1431
+ break;
1432
+ case "endWithoutSave":
1433
+ if (s.name !== "step" || !s.replay)
1434
+ break;
1435
+ pushAbort(d, suite, s);
1436
+ setScreen(d, { name: "idle" });
1437
+ d.effects.push({ type: "toast", text: COPY.replayEnded });
1438
+ break;
1439
+ case "goResume": {
1440
+ if (s.name !== "step" || s.phase !== "away")
1441
+ break;
1442
+ const mission = findMission(suite, s.mission);
1443
+ if (!mission)
1444
+ break;
1445
+ const href = resumeHref(mission, s.index, d, env);
1446
+ if (href)
1447
+ d.effects.push({ type: "navigate", href });
1448
+ break;
1449
+ }
1450
+ case "celebrateNext": {
1451
+ if (s.name !== "celebrate")
1452
+ break;
1453
+ const next = nextMissionKey(suite, d.state.progress, ctxNow());
1454
+ if (next)
1455
+ startMission(d, suite, env, next, false);
1456
+ else
1457
+ setScreen(d, { name: "idle" });
1458
+ break;
1459
+ }
1460
+ case "rest":
1461
+ if (s.name !== "celebrate")
1462
+ break;
1463
+ setScreen(d, { name: "idle" });
1464
+ d.state = { ...d.state, panelOpen: true, justDone: s.mission };
1465
+ break;
1466
+ case "finish": {
1467
+ if (s.name !== "complete")
1468
+ break;
1469
+ setScreen(d, { name: "idle" });
1470
+ const href = resolveText(suite.complete.action.href, ctxNow());
1471
+ const filled = href ? (fillRoute(href, { code: env.code }) ?? href) : "";
1472
+ if (filled)
1473
+ d.effects.push({ type: "navigate", href: filled });
1474
+ break;
1475
+ }
1476
+ case "openPanel":
1477
+ if (state.audience !== "none" && s.name === "idle") {
1478
+ d.state = { ...d.state, panelOpen: true };
1479
+ }
1480
+ break;
1481
+ case "closePanel":
1482
+ d.state = { ...d.state, panelOpen: false, justDone: null };
1483
+ break;
1484
+ case "hideChip":
1485
+ withProgress(d, { chip_hidden: true });
1486
+ d.state = { ...d.state, panelOpen: false };
1487
+ d.effects.push({ type: "toast", text: COPY.hiddenToast });
1488
+ save(d, true);
1489
+ break;
1490
+ case "dismissMission": {
1491
+ const m = findMission(suite, action.mission);
1492
+ if (!m?.optional)
1493
+ break;
1494
+ setMission(d, m.key, { status: "skipped", step_key: null, skipped_step: null });
1495
+ const all = settledCount(suite, d.state.progress, ctxNow()) >= missionCount(suite, ctxNow());
1496
+ if (all) {
1497
+ withProgress(d, { status: "completed" });
1498
+ d.state = { ...d.state, panelOpen: false };
1499
+ setScreen(d, { name: "complete" });
1500
+ }
1501
+ save(d, true);
1502
+ break;
1503
+ }
1504
+ case "serverRow": {
1505
+ // A saved row came back: its rev, the server's status, and the dates
1506
+ // the server stamps on missions ("เสร็จ 26 ต.ค. 2569 13:04").
1507
+ const missions = { ...d.state.progress.missions };
1508
+ for (const [k, m] of Object.entries(missions)) {
1509
+ const r = action.progress.missions[k];
1510
+ if (r && r.status === m.status) {
1511
+ missions[k] = { ...m, completed_at: r.completed_at ?? m.completed_at, skipped_at: r.skipped_at ?? m.skipped_at };
1512
+ }
1513
+ }
1514
+ withProgress(d, { rev: action.progress.rev, server_status: action.progress.server_status, missions });
1515
+ break;
1516
+ }
1517
+ case "passive": {
1518
+ if (state.audience === "none")
1519
+ break;
1520
+ for (const m of passiveMatches(suite, action.signal))
1521
+ passiveDone(d, suite, env, m);
1522
+ break;
1523
+ }
1524
+ case "idleCelebrate": {
1525
+ if (s.name !== "idle" || state.panelOpen)
1526
+ break;
1527
+ const ctx = ctxNow();
1528
+ // Only what is still done and still shown.
1529
+ const pending = (state.pendingCelebrate ?? []).filter(k => {
1530
+ const m = findMission(suite, k);
1531
+ return !!m && d.state.progress.missions[k]?.status === "done" && missionShown(m, ctx);
1532
+ });
1533
+ const key = pending.shift();
1534
+ d.state = { ...d.state, pendingCelebrate: pending };
1535
+ const mission = findMission(suite, key);
1536
+ if (!mission)
1537
+ break;
1538
+ const all = d.state.progress.status === "completed" && settledCount(suite, d.state.progress, ctx) >= missionCount(suite, ctx);
1539
+ if (all)
1540
+ d.state = { ...d.state, pendingCelebrate: [] };
1541
+ showCelebration(d, suite, mission, all, ctx);
1542
+ break;
1543
+ }
1544
+ }
1545
+ return { state: d.state, effects: d.effects };
1546
+ }
1547
+
1548
+ /**
1549
+ * A tour's progress as platform-api stores it (one row per user, org and
1550
+ * suite: GET/PUT /organizations/:id/guides/me), and the rules for reading,
1551
+ * writing and merging it. See _claude-work/peoplx-guide/API.md.
1552
+ *
1553
+ * No runtime imports: the tests run this file in Node as it is.
1554
+ */
1555
+ const KEY_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1556
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1557
+ const str = (v) => (typeof v === "string" && v !== "" ? v : null);
1558
+ function freshProgress(version, rev = 0) {
1559
+ return {
1560
+ guide_version: version,
1561
+ rev,
1562
+ status: "in_progress",
1563
+ mission_key: null,
1564
+ step_key: null,
1565
+ step_index: 0,
1566
+ checkpoint_key: null,
1567
+ missions: {},
1568
+ context: {},
1569
+ welcome: "not_seen",
1570
+ chip_hidden: false,
1571
+ last_error: null,
1572
+ skipped_step: null,
1573
+ server_status: null,
1574
+ };
1575
+ }
1576
+ const ROW_STATUSES = ["in_progress", "completed", "skipped", "aborted"];
1577
+ const MISSION_STATUSES = ["todo", "active", "done", "skipped"];
1578
+ const WELCOMES = ["not_seen", "started", "skipped"];
1579
+ /** One row (a GET `guides[]` entry, a PUT answer, a 409's `current`). Null when off-shape. */
1580
+ function parseRow(raw) {
1581
+ if (!isRecord(raw))
1582
+ return null;
1583
+ const version = Number(raw.guide_version);
1584
+ const rev = Number(raw.rev);
1585
+ if (!Number.isInteger(version) || version < 1 || !Number.isInteger(rev) || rev < 0)
1586
+ return null;
1587
+ const status = ROW_STATUSES.includes(raw.status)
1588
+ ? raw.status
1589
+ : "in_progress";
1590
+ const missions = {};
1591
+ if (isRecord(raw.missions)) {
1592
+ for (const [k, v] of Object.entries(raw.missions)) {
1593
+ if (!isRecord(v) || !MISSION_STATUSES.includes(v.status))
1594
+ continue;
1595
+ missions[k] = {
1596
+ status: v.status,
1597
+ step_key: str(v.step_key),
1598
+ skipped_step: str(v.skipped_step),
1599
+ completed_at: str(v.completed_at),
1600
+ skipped_at: str(v.skipped_at),
1601
+ };
1602
+ }
1603
+ }
1604
+ const context = {};
1605
+ if (isRecord(raw.context)) {
1606
+ for (const [k, v] of Object.entries(raw.context)) {
1607
+ if (typeof v === "string")
1608
+ context[k] = v;
1609
+ else if (typeof v === "number")
1610
+ context[k] = String(v);
1611
+ }
1612
+ }
1613
+ return {
1614
+ guide_version: version,
1615
+ rev,
1616
+ status,
1617
+ mission_key: str(raw.mission_key),
1618
+ step_key: str(raw.step_key),
1619
+ step_index: Number.isInteger(raw.step_index) ? raw.step_index : 0,
1620
+ checkpoint_key: str(raw.checkpoint_key),
1621
+ missions,
1622
+ context,
1623
+ welcome: WELCOMES.includes(raw.welcome) ? raw.welcome : "not_seen",
1624
+ chip_hidden: raw.chip_hidden === true,
1625
+ last_error: str(raw.last_error),
1626
+ skipped_step: str(raw.skipped_step),
1627
+ server_status: status,
1628
+ };
1629
+ }
1630
+ /**
1631
+ * The GET answer for one suite. Null — show nothing — for anything that is
1632
+ * not the expected shape (an older API, a proxy's page, another app's answer).
1633
+ */
1634
+ function parseGuidesAnswer(payload, suite) {
1635
+ if (!isRecord(payload))
1636
+ return null;
1637
+ const data = isRecord(payload.data) ? payload.data : payload;
1638
+ const mode = data.mode;
1639
+ const audience = data.audience;
1640
+ if (mode !== "off" && mode !== "invite" && mode !== "forced")
1641
+ return null;
1642
+ if (audience !== "forced" && audience !== "optional" && audience !== "none")
1643
+ return null;
1644
+ if (typeof data.app === "string" && data.app !== suite.app)
1645
+ return null;
1646
+ const rows = Array.isArray(data.guides) ? data.guides : [];
1647
+ let row = null;
1648
+ for (const r of rows) {
1649
+ if (isRecord(r) && r.guide_key === suite.key) {
1650
+ row = parseRow(r);
1651
+ break;
1652
+ }
1653
+ }
1654
+ let progress;
1655
+ let newerOnServer = false;
1656
+ if (!row)
1657
+ progress = freshProgress(suite.version);
1658
+ else if (row.guide_version < suite.version) {
1659
+ // A new version of the tour: start over (the server resets the row on the
1660
+ // PUT); keep the rev the server will check.
1661
+ progress = { ...freshProgress(suite.version, row.rev), server_status: row.server_status };
1662
+ }
1663
+ else {
1664
+ progress = row;
1665
+ newerOnServer = row.guide_version > suite.version;
1666
+ }
1667
+ return { mode, audience: mode === "off" ? "none" : audience, progress, newerOnServer };
1668
+ }
1669
+ const TERMINAL = ["completed", "skipped", "aborted"];
1670
+ /** The PUT body for the client's state. Drops keys the server would refuse. */
1671
+ function putBody(p, app) {
1672
+ const key = (k) => (k && KEY_RE.test(k) ? k : null);
1673
+ const missions = {};
1674
+ for (const [k, m] of Object.entries(p.missions)) {
1675
+ if (!KEY_RE.test(k))
1676
+ continue;
1677
+ missions[k] = {
1678
+ status: m.status,
1679
+ step_key: key(m.step_key ?? null),
1680
+ skipped_step: key(m.skipped_step ?? null),
1681
+ };
1682
+ }
1683
+ const context = {};
1684
+ for (const [k, v] of Object.entries(p.context)) {
1685
+ if (typeof v === "string" && v.length <= 200)
1686
+ context[k] = v;
1687
+ }
1688
+ return {
1689
+ app,
1690
+ guide_version: p.guide_version,
1691
+ rev: p.rev,
1692
+ status: p.status,
1693
+ mission_key: key(p.mission_key),
1694
+ step_key: key(p.step_key),
1695
+ step_index: Math.max(0, Math.min(1000, Math.floor(p.step_index || 0))),
1696
+ checkpoint_key: key(p.checkpoint_key),
1697
+ missions,
1698
+ context,
1699
+ welcome: p.welcome,
1700
+ chip_hidden: p.chip_hidden,
1701
+ last_error: p.last_error ? p.last_error.slice(0, 128) : null,
1702
+ skipped_step: key(p.skipped_step),
1703
+ restart: p.status === "in_progress" &&
1704
+ p.server_status !== null &&
1705
+ TERMINAL.includes(p.server_status),
1706
+ };
1707
+ }
1708
+ function stable(v) {
1709
+ if (Array.isArray(v))
1710
+ return `[${v.map(stable).join(",")}]`;
1711
+ if (isRecord(v)) {
1712
+ return `{${Object.keys(v)
1713
+ .sort()
1714
+ .map(k => `${JSON.stringify(k)}:${stable(v[k])}`)
1715
+ .join(",")}}`;
1716
+ }
1717
+ return JSON.stringify(v) ?? "null";
1718
+ }
1719
+ /**
1720
+ * What a PUT would store, without the rev it is checked against: two equal
1721
+ * keys mean the save would change nothing, and it is not sent (a replay
1722
+ * starting, a step entered again, never bump the row's rev). Key order does
1723
+ * not matter.
1724
+ */
1725
+ function payloadKey(p, app) {
1726
+ const { rev: _rev, restart: _restart, ...rest } = putBody(p, app);
1727
+ return stable(rest);
1728
+ }
1729
+ const MISSION_RANK = { todo: 0, skipped: 1, active: 1, done: 3 };
1730
+ const WELCOME_RANK = { not_seen: 0, skipped: 1, started: 1 };
1731
+ /**
1732
+ * After a 409: this tab's state laid over the server's, keeping whatever is
1733
+ * further along — a mission done anywhere stays done, the welcome once seen
1734
+ * stays seen, a hidden chip stays hidden. Otherwise this tab's own choice
1735
+ * wins. The rev is the server's.
1736
+ */
1737
+ function mergeProgress(local, remote) {
1738
+ const missions = { ...remote.missions };
1739
+ for (const [k, m] of Object.entries(local.missions)) {
1740
+ const r = remote.missions[k];
1741
+ missions[k] = !r || MISSION_RANK[m.status] >= MISSION_RANK[r.status] ? { ...r, ...m } : r;
1742
+ }
1743
+ const welcome = WELCOME_RANK[local.welcome] >= WELCOME_RANK[remote.welcome] ? local.welcome : remote.welcome;
1744
+ const completed = local.status === "completed" || remote.status === "completed";
1745
+ const mission_key = local.mission_key && missions[local.mission_key]?.status === "active"
1746
+ ? local.mission_key
1747
+ : remote.mission_key && missions[remote.mission_key]?.status === "active"
1748
+ ? remote.mission_key
1749
+ : null;
1750
+ const fromLocal = mission_key !== null && mission_key === local.mission_key;
1751
+ return {
1752
+ ...local,
1753
+ rev: remote.rev,
1754
+ server_status: remote.server_status,
1755
+ status: completed ? "completed" : local.status,
1756
+ missions,
1757
+ welcome,
1758
+ chip_hidden: local.chip_hidden || remote.chip_hidden,
1759
+ mission_key,
1760
+ step_key: fromLocal ? local.step_key : mission_key ? remote.step_key : null,
1761
+ step_index: fromLocal ? local.step_index : mission_key ? remote.step_index : 0,
1762
+ checkpoint_key: fromLocal ? local.checkpoint_key : mission_key ? remote.checkpoint_key : null,
1763
+ context: fromLocal ? local.context : mission_key ? remote.context : {},
1764
+ };
1765
+ }
1766
+ /**
1767
+ * Which of two copies (sessionStorage after F5, the server) to resume from:
1768
+ * the one further along for the same version; the server's on a tie.
1769
+ */
1770
+ function furtherProgress(a, b) {
1771
+ const score = (p) => Object.values(p.missions).reduce((s, m) => s + MISSION_RANK[m.status] * 1000, 0) +
1772
+ (p.mission_key ? 100 + p.step_index : 0) +
1773
+ WELCOME_RANK[p.welcome];
1774
+ return score(a) > score(b) ? a : b;
1775
+ }
1776
+
1777
+ /**
1778
+ * A 409 from the progress API, for a client that throws on non-2xx: throw
1779
+ * it from `saveProgress` with the answer's `current` (the stored row, or
1780
+ * null) and the engine merges as if `{ status: 409, data: { current } }` had
1781
+ * been returned.
1782
+ */
1783
+ class GuideProgressConflict extends Error {
1784
+ constructor(current, code = "guides.stale") {
1785
+ super(code);
1786
+ Object.defineProperty(this, "current", {
1787
+ enumerable: true,
1788
+ configurable: true,
1789
+ writable: true,
1790
+ value: current
1791
+ });
1792
+ Object.defineProperty(this, "code", {
1793
+ enumerable: true,
1794
+ configurable: true,
1795
+ writable: true,
1796
+ value: code
1797
+ });
1798
+ Object.defineProperty(this, "status", {
1799
+ enumerable: true,
1800
+ configurable: true,
1801
+ writable: true,
1802
+ value: 409
1803
+ });
1804
+ this.name = "GuideProgressConflict";
1805
+ }
1806
+ }
1807
+ /** A thrown 409 that carries the stored row: what the engine merges with. */
1808
+ function conflictOf(err) {
1809
+ if (typeof err !== "object" || err === null)
1810
+ return null;
1811
+ const e = err;
1812
+ if (e.status !== 409)
1813
+ return null;
1814
+ if ("current" in e)
1815
+ return { status: 409, data: { current: e.current } };
1816
+ const data = e.data;
1817
+ if (data && typeof data === "object" && "current" in data)
1818
+ return { status: 409, data };
1819
+ return null;
1820
+ }
1821
+ /** The GET, parsed for this suite; null (show nothing) on any failure or odd answer. */
1822
+ async function loadGuides(adapter, suite, signal) {
1823
+ try {
1824
+ const raw = await adapter.fetchProgress({ app: suite.app, guideKey: suite.key, signal });
1825
+ return parseGuidesAnswer(raw, suite);
1826
+ }
1827
+ catch {
1828
+ return null;
1829
+ }
1830
+ }
1831
+ /**
1832
+ * PUT the whole state. On 409 the server's row comes back: merge (keeping
1833
+ * whatever is further along) and try once more with its rev. Returns the
1834
+ * stored row, or null when it could not be saved.
1835
+ */
1836
+ async function storeGuides(adapter, suite, progress) {
1837
+ let body = progress;
1838
+ for (let attempt = 0; attempt < 2; attempt++) {
1839
+ let res;
1840
+ try {
1841
+ res = await adapter.saveProgress({ app: suite.app, guideKey: suite.key, body: putBody(body, suite.app) });
1842
+ }
1843
+ catch (err) {
1844
+ const conflict = conflictOf(err);
1845
+ if (!conflict)
1846
+ return null;
1847
+ res = conflict;
1848
+ }
1849
+ if (!res || typeof res.status !== "number")
1850
+ return null;
1851
+ const payload = res.data;
1852
+ if (res.status >= 200 && res.status < 300) {
1853
+ return parseRow(payload?.data ?? payload);
1854
+ }
1855
+ if (res.status !== 409)
1856
+ return null;
1857
+ const current = parseRow(payload?.current);
1858
+ if (current && current.guide_version > body.guide_version) {
1859
+ // Another app build is ahead of this one: stop writing.
1860
+ return null;
1861
+ }
1862
+ if (!current)
1863
+ body = { ...body, rev: 0, server_status: null };
1864
+ else if (current.guide_version < body.guide_version) {
1865
+ // The server's row is the previous version: this one replaces it.
1866
+ body = { ...body, rev: current.rev, server_status: current.server_status };
1867
+ }
1868
+ else
1869
+ body = mergeProgress(body, current);
1870
+ }
1871
+ return null;
1872
+ }
1873
+
1874
+ /**
1875
+ * The tour's DOM side: finding anchors, deciding whether one is really on
1876
+ * screen, and the rectangles the spotlight cuts out. Browser only; every
1877
+ * function tolerates a missing document.
1878
+ */
1879
+ const hasDocument = () => typeof document !== "undefined";
1880
+ function cssString(value) {
1881
+ return `"${value.replace(/["\\]/g, "\\$&")}"`;
1882
+ }
1883
+ function anchorSelector(anchor, id) {
1884
+ return (`[${GUIDE_ATTRIBUTE}=${cssString(anchor)}]` +
1885
+ (id ? `[${GUIDE_ID_ATTRIBUTE}=${cssString(id)}]` : ""));
1886
+ }
1887
+ /**
1888
+ * On screen: connected, with a size, not hidden by style, not inside
1889
+ * aria-hidden or inert (other than the guide's own), not a closed Radix part.
1890
+ *
1891
+ * aria-hidden that Radix put there (data-aria-hidden: everything outside an
1892
+ * open dialog, select or menu is hidden from screen readers) does not count:
1893
+ * a dialog's field is still on screen while its select's list is open.
1894
+ */
1895
+ function isPresent(el) {
1896
+ if (!el || !el.isConnected)
1897
+ return false;
1898
+ const r = el.getBoundingClientRect();
1899
+ if (r.width <= 0 || r.height <= 0)
1900
+ return false;
1901
+ // Slid off the side (a closed drawer); off the top or bottom is only
1902
+ // scrolled away, and the tour scrolls it back. So is a tab scrolled out of
1903
+ // a row of tabs that scrolls sideways, as long as the row is on screen.
1904
+ if ((r.right <= 0 || r.left >= window.innerWidth) && !inSidewaysScroller(el))
1905
+ return false;
1906
+ // Closed Radix content (a shut dialog, popover or collapsible body) is
1907
+ // absent. Its trigger also says data-state="closed" while shut, but it is
1908
+ // on screen and is what a step points at (a sidebar group header, a
1909
+ // dialog's open button), so a trigger (aria-expanded) stays present.
1910
+ if (el.getAttribute("data-state") === "closed" && !el.hasAttribute("aria-expanded"))
1911
+ return false;
1912
+ const style = getComputedStyle(el);
1913
+ if (style.visibility === "hidden" || style.display === "none")
1914
+ return false;
1915
+ for (let n = el; n; n = n.parentElement) {
1916
+ if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
1917
+ break;
1918
+ if (n.hasAttribute("inert"))
1919
+ return false;
1920
+ if (n.getAttribute("aria-hidden") === "true" && !n.hasAttribute("data-aria-hidden"))
1921
+ return false;
1922
+ }
1923
+ return true;
1924
+ }
1925
+ /** The first matching anchor that is on screen. */
1926
+ function findAnchor(anchor, id) {
1927
+ if (!hasDocument() || !anchor)
1928
+ return null;
1929
+ let list;
1930
+ try {
1931
+ list = document.querySelectorAll(anchorSelector(anchor, id));
1932
+ }
1933
+ catch {
1934
+ return null;
1935
+ }
1936
+ for (const el of Array.from(list)) {
1937
+ if (isPresent(el))
1938
+ return el;
1939
+ }
1940
+ return null;
1941
+ }
1942
+ function anchorVisible(anchor, id) {
1943
+ return findAnchor(anchor, id) !== null;
1944
+ }
1945
+ const FIELD = "input:not([type=hidden]),textarea,select,[contenteditable=''],[contenteditable=true]";
1946
+ /** The field to type into: the anchor itself, or the first field inside it. */
1947
+ function fieldOf(el) {
1948
+ if (!el)
1949
+ return null;
1950
+ if (el.matches(FIELD))
1951
+ return el;
1952
+ return el.querySelector(FIELD);
1953
+ }
1954
+ function fieldValue(el) {
1955
+ const f = fieldOf(el);
1956
+ if (!f)
1957
+ return "";
1958
+ if ("value" in f && typeof f.value === "string")
1959
+ return f.value;
1960
+ return f.textContent ?? "";
1961
+ }
1962
+ const FOCUSABLE = "a[href],button:not([disabled]),input:not([disabled]):not([type=hidden]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1']),[contenteditable=''],[contenteditable=true]";
1963
+ function focusablesIn(root) {
1964
+ if (!root)
1965
+ return [];
1966
+ const own = root.matches(FOCUSABLE) ? [root] : [];
1967
+ return own.concat(Array.from(root.querySelectorAll(FOCUSABLE)).filter(isPresent));
1968
+ }
1969
+ function rectOf(el) {
1970
+ const r = el.getBoundingClientRect();
1971
+ return { x: r.left, y: r.top, width: r.width, height: r.height };
1972
+ }
1973
+ function padRect(r, pad) {
1974
+ return { x: r.x - pad, y: r.y - pad, width: r.width + pad * 2, height: r.height + pad * 2 };
1975
+ }
1976
+ function sameRect(a, b) {
1977
+ if (!a || !b)
1978
+ return a === b;
1979
+ return (Math.abs(a.x - b.x) < 0.5 &&
1980
+ Math.abs(a.y - b.y) < 0.5 &&
1981
+ Math.abs(a.width - b.width) < 0.5 &&
1982
+ Math.abs(a.height - b.height) < 0.5);
1983
+ }
1984
+ /** Open Radix poppers (a select's list, a menu): usable while a step runs. */
1985
+ const POPPER_SELECTOR = "[data-radix-popper-content-wrapper]";
1986
+ /** Toasts stay usable above the tour. */
1987
+ const TOASTER_SELECTOR = "[data-sonner-toaster]";
1988
+ /** Open dialogs (Radix dialog, alert dialog, sheet, popover content). */
1989
+ const OPEN_DIALOG_SELECTOR = '[role="dialog"][data-state="open"],[role="alertdialog"][data-state="open"]';
1990
+ /**
1991
+ * Whether an open dialog of the app's covers the target: the target is
1992
+ * neither in it nor around it (a confirm opened by the step's own button).
1993
+ * The ring and the hand would be drawn over the dialog, pointing at a button
1994
+ * behind it.
1995
+ */
1996
+ function coveredByDialog(el) {
1997
+ if (!hasDocument() || !el)
1998
+ return false;
1999
+ for (const d of Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR))) {
2000
+ if (inGuideLayer(d) || !isPresent(d))
2001
+ continue;
2002
+ if (d.contains(el) || el.contains(d))
2003
+ continue;
2004
+ return true;
2005
+ }
2006
+ return false;
2007
+ }
2008
+ /** An app dialog (not the tour's) is open on the page. */
2009
+ function appDialogOpen() {
2010
+ if (!hasDocument())
2011
+ return false;
2012
+ return Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR)).some(d => !inGuideLayer(d) && isPresent(d));
2013
+ }
2014
+ function openPoppers() {
2015
+ if (!hasDocument())
2016
+ return [];
2017
+ return Array.from(document.querySelectorAll(POPPER_SELECTOR)).filter(isPresent);
2018
+ }
2019
+ function inGuideLayer(node) {
2020
+ if (!node || typeof Node === "undefined" || !(node instanceof Node))
2021
+ return false;
2022
+ const el = node instanceof Element ? node : node.parentElement;
2023
+ return !!el?.closest(`[${GUIDE_LAYER_ATTRIBUTE}]`);
2024
+ }
2025
+ function prefersReducedMotion() {
2026
+ return typeof window !== "undefined" && !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
2027
+ }
2028
+ function isPhoneWidth() {
2029
+ return typeof window !== "undefined" && window.innerWidth < 768;
2030
+ }
2031
+ /* ---------------- what is really on screen ---------------- */
2032
+ const INFINITE = 1e7;
2033
+ /** The overlap of two rectangles, or null when they do not meet. */
2034
+ function intersectRect(a, b) {
2035
+ const x = Math.max(a.x, b.x);
2036
+ const y = Math.max(a.y, b.y);
2037
+ const right = Math.min(a.x + a.width, b.x + b.width);
2038
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
2039
+ if (right - x <= 0 || bottom - y <= 0)
2040
+ return null;
2041
+ return { x, y, width: right - x, height: bottom - y };
2042
+ }
2043
+ /** The part of `rect` inside every clip (scroll boxes, the viewport); null when none is. */
2044
+ function visibleRect(rect, clips) {
2045
+ let r = rect;
2046
+ for (const c of clips) {
2047
+ if (!r)
2048
+ return null;
2049
+ r = intersectRect(r, c);
2050
+ }
2051
+ return r;
2052
+ }
2053
+ const clipsX = (v) => v !== "visible";
2054
+ const scrollsX = (v) => v === "auto" || v === "scroll";
2055
+ /**
2056
+ * The ancestors that cut the element off: anything with overflow other than
2057
+ * visible on an axis. The body and the root scroll the page and are covered by
2058
+ * the viewport. Read once per target; their rectangles are read every frame.
2059
+ */
2060
+ function clipAncestors(el) {
2061
+ const out = [];
2062
+ if (typeof getComputedStyle !== "function")
2063
+ return out;
2064
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
2065
+ if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
2066
+ break;
2067
+ const s = getComputedStyle(n);
2068
+ const x = clipsX(s.overflowX);
2069
+ const y = clipsX(s.overflowY);
2070
+ if (x || y)
2071
+ out.push({ el: n, x, y });
2072
+ if (s.position === "fixed")
2073
+ break;
2074
+ }
2075
+ return out;
2076
+ }
2077
+ /** An ancestor's clip as a rectangle: unbounded on an axis it does not clip. */
2078
+ function clipRectOf(c) {
2079
+ const r = c.el.getBoundingClientRect();
2080
+ return {
2081
+ x: c.x ? r.left : -INFINITE,
2082
+ y: c.y ? r.top : -INFINITE,
2083
+ width: c.x ? r.width : INFINITE * 2,
2084
+ height: c.y ? r.height : INFINITE * 2,
2085
+ };
2086
+ }
2087
+ function viewportRect() {
2088
+ const vv = typeof window !== "undefined" ? window.visualViewport : undefined;
2089
+ return {
2090
+ x: 0,
2091
+ y: vv ? vv.offsetTop : 0,
2092
+ width: window.innerWidth,
2093
+ height: vv ? vv.height : window.innerHeight,
2094
+ };
2095
+ }
2096
+ /**
2097
+ * The part of the element a person can see: its box cut by every scroll box
2098
+ * around it and by the viewport. The spotlight, its hole, the ring and the
2099
+ * hand use this, so a tab half out of a sideways-scrolling row of tabs is not
2100
+ * spotlit where it cannot be pressed. Null when none of it is on screen.
2101
+ */
2102
+ function visibleRectOf(el, ancestors = clipAncestors(el)) {
2103
+ return visibleRect(rectOf(el), [...ancestors.map(clipRectOf), viewportRect()]);
2104
+ }
2105
+ /** Inside a box that scrolls sideways (with somewhere to scroll) that is itself on screen. */
2106
+ function inSidewaysScroller(el) {
2107
+ if (typeof getComputedStyle !== "function")
2108
+ return false;
2109
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
2110
+ const s = getComputedStyle(n);
2111
+ if (scrollsX(s.overflowX) && n.scrollWidth > n.clientWidth + 1) {
2112
+ const r = n.getBoundingClientRect();
2113
+ return r.width > 0 && r.right > 0 && r.left < window.innerWidth;
2114
+ }
2115
+ }
2116
+ return false;
2117
+ }
2118
+ /**
2119
+ * How to bring a target into view, or null when it already is: to the middle
2120
+ * when it is above or below the comfortable band (under the header, at the
2121
+ * bottom edge), the nearest edge when only a side is cut off (a tab out of a
2122
+ * sideways-scrolling row, on a phone).
2123
+ */
2124
+ function revealPlan(rect, visible, viewportHeight) {
2125
+ const offVertically = rect.y < 70 || rect.y + rect.height > viewportHeight - 20;
2126
+ const cutSideways = !visible || visible.width < rect.width - 1;
2127
+ if (!offVertically && !cutSideways)
2128
+ return null;
2129
+ return { block: offVertically ? "center" : "nearest", inline: "nearest" };
2130
+ }
2131
+ /** Room left beside a target scrolled into a sideways scroll box. */
2132
+ const SIDEWAYS_MARGIN = 12;
2133
+ /**
2134
+ * How far to scroll a sideways scroll box so the target sits inside its
2135
+ * visible part (`box`: the box cut by the viewport) with `margin` to spare on
2136
+ * both sides; 0 when it already does. Clamped to what the box can scroll.
2137
+ * A target wider than the room is aligned to its start.
2138
+ */
2139
+ function sidewaysDelta(target, box, scrollLeft, maxScrollLeft, margin = SIDEWAYS_MARGIN) {
2140
+ const left = box.x + margin;
2141
+ const right = box.x + box.width - margin;
2142
+ let delta = 0;
2143
+ if (target.x < left || target.width > right - left)
2144
+ delta = target.x - left;
2145
+ else if (target.x + target.width > right)
2146
+ delta = target.x + target.width - right;
2147
+ const next = Math.min(Math.max(scrollLeft + delta, 0), Math.max(maxScrollLeft, 0));
2148
+ return next - scrollLeft;
2149
+ }
2150
+ /** The nearest ancestor that scrolls sideways and has somewhere to scroll. */
2151
+ function sidewaysScroller(el) {
2152
+ if (typeof getComputedStyle !== "function")
2153
+ return null;
2154
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
2155
+ if (scrollsX(getComputedStyle(n).overflowX) && n.scrollWidth > n.clientWidth + 1)
2156
+ return n;
2157
+ }
2158
+ return null;
2159
+ }
2160
+ /**
2161
+ * Scrolls the target into view (instant under reduced motion). In a box that
2162
+ * scrolls sideways (a row of tabs on a phone) the box is scrolled first,
2163
+ * leaving SIDEWAYS_MARGIN beside the target so its whole label shows; then
2164
+ * the page, up or down only.
2165
+ */
2166
+ function revealTarget(el) {
2167
+ const behavior = prefersReducedMotion() ? "auto" : "smooth";
2168
+ const scroller = sidewaysScroller(el);
2169
+ if (scroller) {
2170
+ const box = intersectRect(rectOf(scroller), viewportRect()) ?? rectOf(scroller);
2171
+ const dx = sidewaysDelta(rectOf(el), box, scroller.scrollLeft, scroller.scrollWidth - scroller.clientWidth);
2172
+ // Instant: the page's own scroll below must not cancel it.
2173
+ if (Math.abs(dx) >= 1)
2174
+ scroller.scrollLeft += dx;
2175
+ }
2176
+ const vh = window.visualViewport?.height ?? window.innerHeight;
2177
+ const plan = revealPlan(rectOf(el), visibleRectOf(el), vh);
2178
+ if (!plan)
2179
+ return;
2180
+ try {
2181
+ el.scrollIntoView({ ...plan, behavior });
2182
+ }
2183
+ catch {
2184
+ el.scrollIntoView();
2185
+ }
2186
+ }
2187
+ /* ---------------- the scrim's holes, as one union ---------------- */
2188
+ /**
2189
+ * The scrim's blocking area: the screen (with a 10 px margin) minus the union
2190
+ * of the holes, as rectangles that do not overlap. Cutting each hole out with
2191
+ * an even-odd fill made the place where two holes overlap (a field and the
2192
+ * select list open over it) solid again, and the option there could not be
2193
+ * pressed.
2194
+ *
2195
+ * Every hole edge splits the screen into a grid; a cell is blocked when no
2196
+ * hole covers it. Cells in a row are joined, and identical rows stacked.
2197
+ */
2198
+ function blockedRects(holes, width, height) {
2199
+ const x0 = -10;
2200
+ const y0 = -10;
2201
+ const x1 = width + 10;
2202
+ const y1 = height + 10;
2203
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
2204
+ const hs = holes
2205
+ .filter(h => h.width > 0 && h.height > 0)
2206
+ .map(h => ({
2207
+ l: clamp(h.x, x0, x1),
2208
+ t: clamp(h.y, y0, y1),
2209
+ r: clamp(h.x + h.width, x0, x1),
2210
+ b: clamp(h.y + h.height, y0, y1),
2211
+ }))
2212
+ .filter(h => h.r > h.l && h.b > h.t);
2213
+ if (!hs.length)
2214
+ return [{ x: x0, y: y0, width: x1 - x0, height: y1 - y0 }];
2215
+ const uniq = (v) => Array.from(new Set(v)).sort((a, b) => a - b);
2216
+ const xs = uniq([x0, x1, ...hs.flatMap(h => [h.l, h.r])]);
2217
+ const ys = uniq([y0, y1, ...hs.flatMap(h => [h.t, h.b])]);
2218
+ const out = [];
2219
+ let prev = null;
2220
+ for (let j = 0; j < ys.length - 1; j++) {
2221
+ const top = ys[j];
2222
+ const bottom = ys[j + 1];
2223
+ const cy = (top + bottom) / 2;
2224
+ const row = [];
2225
+ for (let i = 0; i < xs.length - 1; i++) {
2226
+ const left = xs[i];
2227
+ const right = xs[i + 1];
2228
+ const cx = (left + right) / 2;
2229
+ const covered = hs.some(h => cx > h.l && cx < h.r && cy > h.t && cy < h.b);
2230
+ if (covered)
2231
+ continue;
2232
+ const last = row[row.length - 1];
2233
+ if (last && last.x + last.width === left)
2234
+ last.width = right - last.x;
2235
+ else
2236
+ row.push({ x: left, y: top, width: right - left, height: bottom - top });
2237
+ }
2238
+ const key = row.map(r => `${r.x},${r.width}`).join("|");
2239
+ if (prev && prev.key === key) {
2240
+ for (const r of prev.rects)
2241
+ r.height += bottom - top;
2242
+ }
2243
+ else {
2244
+ out.push(...row);
2245
+ prev = { key, rects: row };
2246
+ }
2247
+ }
2248
+ return out;
2249
+ }
2250
+
2251
+ /**
2252
+ * The tour's stylesheet. The shell has no CSS pipeline and the apps only scan
2253
+ * its dist for Tailwind classes, which cannot carry keyframes; so the layer
2254
+ * brings its own sheet, namespaced `eg-`, drawn from the theme's tokens
2255
+ * (--primary carries each app's brand accent; light and dark follow).
2256
+ *
2257
+ * `--erp-guide-bottom-offset` (set by the app on :root/body, or through
2258
+ * GuideRuntime's `bottomOffset`) lifts the chip, the bottom card, the toast
2259
+ * and the desktop panel above a bottom nav. Unset, they sit where they did
2260
+ * before 0.1.68: 16px from the bottom (+ the safe area) on a phone, 22px on
2261
+ * desktop.
2262
+ */
2263
+ const GUIDE_CSS = `
2264
+ [data-erp-guide-layer]{position:fixed;inset:0;z-index:1000;pointer-events:none;font-family:inherit;color:var(--popover-foreground,#1c2634);
2265
+ --eg-scrim:rgba(12,20,34,.64);--eg-card:var(--popover,#fff);--eg-fg:var(--popover-foreground,#1c2634);
2266
+ --eg-muted:var(--muted-foreground,#6d7886);--eg-soft:var(--muted,#eef3f9);--eg-line:var(--border,#e8ecf1);
2267
+ --eg-primary:var(--primary,#3280dd);--eg-on-primary:var(--primary-foreground,#fff);
2268
+ --eg-tint:color-mix(in oklab,var(--eg-primary) 13%,var(--eg-card));--eg-strong:color-mix(in oklab,var(--eg-primary) 82%,#000);
2269
+ --eg-danger:var(--destructive,#d23b4b);--eg-ok:#1d9a5f;--eg-gold:#e6a417;
2270
+ --eg-shadow:0 18px 50px -12px rgba(16,32,64,.35),0 4px 12px rgba(16,32,64,.08);line-height:1.5;font-size:14px}
2271
+ [data-erp-guide-layer] *{box-sizing:border-box}
2272
+ [data-erp-guide-layer] button{font:inherit;color:inherit;cursor:pointer}
2273
+ .eg-i{pointer-events:auto}
2274
+ .eg-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
2275
+ .eg-scrim-svg{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}
2276
+ .eg-scrim-svg .eg-scrim-fill{fill:var(--eg-scrim);pointer-events:none}
2277
+ .eg-scrim-svg .eg-scrim-hit{fill:transparent;pointer-events:all}
2278
+ .eg-scrim{position:fixed;inset:0;background:var(--eg-scrim);pointer-events:auto}
2279
+ .eg-scrim.eg-light{background:rgba(12,20,34,.45)}
2280
+ .eg-scrim.eg-faint{background:rgba(12,20,34,.35)}
2281
+ .eg-ring{position:fixed;border-radius:12px;pointer-events:none;box-shadow:0 0 0 3px #fff,0 0 0 6px var(--eg-primary)}
2282
+ .eg-ring.eg-move{transition:left .26s ease,top .26s ease,width .26s ease,height .26s ease}
2283
+ .eg-ring::after{content:"";position:absolute;inset:-6px;border-radius:15px;border:3px solid var(--eg-primary);animation:eg-pulse 1.6s ease-out infinite}
2284
+ .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1}
2285
+ @keyframes eg-pulse{0%{opacity:.9;transform:scale(1)}100%{opacity:0;transform:scale(1.12)}}
2286
+ @keyframes eg-flash{0%,100%{opacity:1;transform:none}50%{opacity:.2}}
2287
+ .eg-hand{position:fixed;width:46px;height:46px;pointer-events:none;filter:drop-shadow(0 4px 6px rgba(0,0,0,.35));animation:eg-tap 1.1s ease-in-out infinite}
2288
+ .eg-hand svg{width:46px;height:46px;fill:#fff;stroke:#1c2634;stroke-width:1.4;stroke-linejoin:round;stroke-linecap:round}
2289
+ .eg-hand.eg-flip svg{transform:scaleY(-1)}
2290
+ @keyframes eg-tap{0%,100%{transform:translate(6px,8px)}50%{transform:translate(0,0)}}
2291
+ .eg-bubble{position:fixed;left:0;top:0;width:320px;background:var(--eg-card);color:var(--eg-fg);border-radius:14px;box-shadow:var(--eg-shadow);padding:14px 16px 12px;border-top:4px solid var(--eg-primary);outline:none;pointer-events:auto}
2292
+ .eg-bubble.eg-err{border-top-color:var(--eg-danger)}
2293
+ .eg-bubble.eg-nudge{animation:eg-nudge .38s ease}
2294
+ @keyframes eg-nudge{0%,100%{translate:0}20%{translate:-7px}40%{translate:6px}60%{translate:-4px}80%{translate:2px}}
2295
+ .eg-b-top{display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:12px;color:var(--eg-muted)}
2296
+ .eg-b-top .eg-mis{font-weight:600;color:var(--eg-strong);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2297
+ .eg-b-top .eg-cnt{white-space:nowrap;font-weight:600}
2298
+ .eg-pips{display:flex;gap:4px;margin:8px 0 10px}
2299
+ .eg-pips i{flex:1;height:4px;border-radius:2px;background:var(--eg-soft)}
2300
+ .eg-pips i.eg-d{background:var(--eg-primary)}
2301
+ .eg-pips i.eg-c{background:color-mix(in oklab,var(--eg-primary) 45%,var(--eg-card))}
2302
+ .eg-b-t{margin:0;font-size:16px;font-weight:600;line-height:1.45}
2303
+ .eg-b-w{margin:2px 0 0;font-size:13.5px;color:var(--eg-muted)}
2304
+ .eg-bubble.eg-err .eg-b-t{color:var(--eg-danger)}
2305
+ .eg-k{display:inline-block;background:var(--eg-tint);color:var(--eg-strong);border-radius:7px;padding:0 7px;font-weight:600}
2306
+ .eg-b-f{display:flex;align-items:center;justify-content:space-between;margin-top:12px;gap:8px}
2307
+ .eg-b-f .eg-btn{height:34px;padding:0 14px;font-size:13.5px}
2308
+ .eg-exit{border:0;background:none;color:var(--eg-muted);font-size:12.5px;padding:4px 0;text-decoration:underline;text-underline-offset:3px}
2309
+ .eg-exit:hover{color:var(--eg-fg)}
2310
+ .eg-arrow{position:absolute;width:14px;height:14px;background:var(--eg-card);transform:rotate(45deg);border-radius:2px}
2311
+ .eg-arrow.eg-top{background:var(--eg-primary)}
2312
+ .eg-bubble.eg-err .eg-arrow.eg-top{background:var(--eg-danger)}
2313
+ .eg-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:40px;padding:0 16px;border-radius:10px;border:1px solid transparent;font-size:14px;font-weight:600;white-space:nowrap}
2314
+ .eg-btn:focus-visible,.eg-exit:focus-visible,.eg-chip:focus-visible,.eg-x:focus-visible{outline:2px solid var(--eg-primary);outline-offset:2px}
2315
+ .eg-primary{background:var(--eg-primary);color:var(--eg-on-primary)!important}
2316
+ .eg-primary:hover{background:var(--eg-strong)}
2317
+ .eg-primary[disabled]{opacity:.55;cursor:default}
2318
+ .eg-ghost{background:var(--eg-card);border-color:var(--eg-line)}
2319
+ .eg-ghost:hover{background:var(--eg-soft)}
2320
+ .eg-ghost[disabled]{opacity:.55;cursor:default}
2321
+ .eg-link{background:none;border:0;color:var(--eg-muted);font-weight:500;padding:0 6px;height:32px}
2322
+ .eg-link:hover{color:var(--eg-fg);text-decoration:underline}
2323
+ .eg-modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(440px,calc(100vw - 32px));max-height:calc(100vh - 32px);overflow:auto;background:var(--eg-card);color:var(--eg-fg);border-radius:20px;box-shadow:var(--eg-shadow);padding:28px 28px 22px;text-align:center;outline:none;pointer-events:auto}
2324
+ .eg-modal.eg-pop{animation:eg-pop .32s cubic-bezier(.2,.9,.3,1.3)}
2325
+ @keyframes eg-pop{from{opacity:0;transform:translate(-50%,-46%) scale(.94)}}
2326
+ .eg-modal h2{margin:6px 0 4px;font-size:22px;font-weight:700;letter-spacing:-.2px;line-height:1.3}
2327
+ .eg-modal .eg-sub{margin:0;color:var(--eg-muted);font-size:14.5px}
2328
+ .eg-eyebrow{margin:0;font-size:12.5px;font-weight:600;letter-spacing:.3px;color:var(--eg-strong)}
2329
+ .eg-actions{display:grid;gap:6px;margin-top:20px}
2330
+ .eg-actions .eg-btn{height:44px}
2331
+ .eg-badge{width:64px;height:64px;border-radius:18px;margin:0 auto 12px;display:grid;place-items:center;background:var(--eg-tint);color:var(--eg-strong)}
2332
+ .eg-badge svg.eg-ic{width:30px;height:30px}
2333
+ .eg-quests{list-style:none;padding:0;margin:18px 0 0;text-align:left;display:grid;gap:6px}
2334
+ .eg-quests li{display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:11px;background:var(--eg-soft);font-size:14px}
2335
+ .eg-quests li .eg-n{width:26px;height:26px;border-radius:50%;background:var(--eg-card);border:1.5px solid var(--eg-line);display:grid;place-items:center;font-size:12px;font-weight:700;color:var(--eg-muted);flex:none}
2336
+ .eg-quests li.eg-first{background:var(--eg-tint)}
2337
+ .eg-quests li.eg-first .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
2338
+ .eg-quests li.eg-ok .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
2339
+ .eg-quests li .eg-n svg.eg-ic{width:15px;height:15px;stroke-width:3}
2340
+ .eg-quests li .eg-t{flex:1}
2341
+ .eg-quests li small{color:var(--eg-muted);font-size:12px;white-space:nowrap}
2342
+ .eg-modal.eg-confirm{text-align:left;width:min(380px,calc(100vw - 32px));padding:22px}
2343
+ .eg-modal.eg-confirm h2{font-size:18px;margin-top:0}
2344
+ .eg-modal.eg-confirm .eg-actions{grid-template-columns:1fr 1fr}
2345
+ .eg-medal{width:84px;height:84px;border-radius:50%;margin:4px auto 10px;display:grid;place-items:center;color:#fff;background:radial-gradient(circle at 35% 30%,#ffd666,var(--eg-gold));box-shadow:0 0 0 8px #fff4d6;animation:eg-stamp .5s cubic-bezier(.2,.9,.3,1.4) .1s both}
2346
+ .eg-medal svg.eg-ic{width:42px;height:42px;stroke-width:2.6}
2347
+ @keyframes eg-stamp{from{transform:scale(.3) rotate(-25deg);opacity:0}}
2348
+ .eg-prog{display:flex;align-items:center;gap:10px;margin-top:16px;font-size:13px;color:var(--eg-muted);font-weight:600}
2349
+ .eg-prog .eg-bar{flex:1;height:8px;border-radius:4px;background:var(--eg-soft);overflow:hidden}
2350
+ .eg-prog .eg-bar i{display:block;height:100%;background:var(--eg-primary);border-radius:4px;transition:width .9s cubic-bezier(.2,.8,.2,1) .35s}
2351
+ .eg-burst{position:absolute;left:50%;top:70px;width:0;height:0;pointer-events:none}
2352
+ .eg-burst span{position:absolute;width:8px;height:12px;border-radius:2px;opacity:0;animation:eg-conf 1.1s cubic-bezier(.15,.7,.3,1) forwards}
2353
+ @keyframes eg-conf{0%{opacity:1;transform:translate(0,0) rotate(0)}100%{opacity:0;transform:translate(var(--x),var(--y)) rotate(var(--r))}}
2354
+ .eg-card{position:fixed;left:50%;bottom:calc(var(--erp-guide-bottom-offset,16px) + 12px);transform:translateX(-50%);width:min(360px,calc(100vw - 32px));background:var(--eg-card);color:var(--eg-fg);border-radius:14px;box-shadow:var(--eg-shadow);padding:14px 16px;border-top:4px solid var(--eg-primary);pointer-events:auto;outline:none}
2355
+ .eg-card .eg-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px}
2356
+ .eg-loading{display:flex;align-items:center;gap:10px;font-weight:600}
2357
+ .eg-spin{width:18px;height:18px;border-radius:50%;border:2.5px solid var(--eg-soft);border-top-color:var(--eg-primary);animation:eg-spin .8s linear infinite;flex:none}
2358
+ @keyframes eg-spin{to{transform:rotate(360deg)}}
2359
+ .eg-chip{position:fixed;right:22px;bottom:var(--erp-guide-bottom-offset,22px);display:flex;align-items:center;gap:10px;height:48px;padding:0 18px 0 8px;border-radius:24px;border:1px solid var(--eg-line);background:var(--eg-card);color:var(--eg-fg);box-shadow:0 8px 24px -8px rgba(16,32,64,.3);font-weight:600;font-size:14px;pointer-events:auto}
2360
+ .eg-chip svg{width:34px;height:34px}
2361
+ .eg-chip.eg-hi{animation:eg-hi 1.2s ease 2}
2362
+ @keyframes eg-hi{50%{box-shadow:0 0 0 6px color-mix(in oklab,var(--eg-primary) 35%,transparent),0 8px 24px -8px rgba(16,32,64,.3)}}
2363
+ .eg-panel{position:fixed;right:22px;bottom:calc(var(--erp-guide-bottom-offset,22px) + 60px);width:360px;max-height:calc(100vh - 110px);overflow:auto;background:var(--eg-card);color:var(--eg-fg);border:1px solid var(--eg-line);border-radius:16px;box-shadow:var(--eg-shadow);outline:none;pointer-events:auto}
2364
+ .eg-panel-bd{display:none}
2365
+ .eg-q-h{display:flex;align-items:center;gap:10px;padding:16px 12px 4px 18px}
2366
+ .eg-q-h h2{margin:0;font-size:16px;font-weight:700;flex:1}
2367
+ .eg-q-h .eg-n{font-size:13px;color:var(--eg-muted);font-weight:600}
2368
+ .eg-x{width:34px;height:34px;border-radius:10px;border:0;background:none;display:grid;place-items:center;color:var(--eg-muted)}
2369
+ .eg-x:hover{background:var(--eg-soft)}
2370
+ .eg-x svg.eg-ic{width:18px;height:18px}
2371
+ .eg-panel .eg-prog{margin:6px 18px 8px}
2372
+ .eg-q-list{list-style:none;margin:0;padding:4px 10px 6px;display:grid;gap:2px}
2373
+ .eg-q-item{display:flex;align-items:center;gap:12px;padding:10px 8px;border-radius:11px}
2374
+ .eg-q-item.eg-next{background:var(--eg-tint)}
2375
+ .eg-q-item .eg-n{width:30px;height:30px;border-radius:50%;border:1.5px solid var(--eg-line);display:grid;place-items:center;font-size:12.5px;font-weight:700;color:var(--eg-muted);flex:none;background:var(--eg-card)}
2376
+ .eg-q-item.eg-next .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
2377
+ .eg-q-item.eg-done .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
2378
+ .eg-q-item.eg-done .eg-n svg.eg-ic{width:16px;height:16px;stroke-width:3}
2379
+ .eg-q-item.eg-dim .eg-n{opacity:.55}
2380
+ .eg-q-item.eg-just .eg-n{animation:eg-stamp .55s cubic-bezier(.2,.9,.3,1.4) .2s both}
2381
+ .eg-q-item .eg-t{flex:1;min-width:0}
2382
+ .eg-q-item .eg-t b{display:block;font-size:14px;font-weight:600}
2383
+ .eg-q-item.eg-done .eg-t b{color:var(--eg-muted)}
2384
+ .eg-q-item .eg-t small{display:block;font-size:12px;color:var(--eg-muted)}
2385
+ .eg-q-item .eg-t small.eg-sk{color:#b06a00}
2386
+ .eg-q-item .eg-t small.eg-lock{color:var(--eg-fg);font-weight:500}
2387
+ .eg-q-item .eg-btn{height:32px;padding:0 12px;font-size:13px}
2388
+ .eg-q-acts{display:flex;flex-direction:column;align-items:flex-end;gap:2px}
2389
+ .eg-q-acts .eg-link{height:22px;font-size:12px;padding:0 2px}
2390
+ .eg-q-f{border-top:1px solid var(--eg-line);padding:8px 12px;display:flex;justify-content:flex-end}
2391
+ .eg-toast{position:fixed;left:50%;bottom:calc(var(--erp-guide-bottom-offset,22px) + 62px);transform:translateX(-50%);background:#1c2634;color:#fff;padding:10px 16px;border-radius:10px;font-size:13.5px;box-shadow:var(--eg-shadow);max-width:calc(100vw - 32px);pointer-events:none}
2392
+ svg.eg-ic{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex:none}
2393
+ @media (max-width:767px){
2394
+ .eg-bubble{width:auto}
2395
+ .eg-arrow{display:none}
2396
+ .eg-modal{top:auto;bottom:12px;transform:translateX(-50%);width:calc(100vw - 24px);padding:24px 20px 18px}
2397
+ .eg-modal.eg-pop{animation:eg-up .3s cubic-bezier(.2,.9,.3,1.1)}
2398
+ .eg-modal .eg-actions .eg-btn{height:46px}
2399
+ .eg-chip{right:16px;bottom:var(--erp-guide-bottom-offset,calc(16px + env(safe-area-inset-bottom)))}
2400
+ .eg-panel-bd{display:block;position:fixed;inset:0;background:rgba(15,23,42,.38);pointer-events:auto}
2401
+ .eg-panel{left:0;right:0;bottom:0;width:100%;max-height:85vh;border-radius:18px 18px 0 0;padding-bottom:env(safe-area-inset-bottom)}
2402
+ .eg-q-item{padding:12px 8px}
2403
+ .eg-card{bottom:calc(var(--erp-guide-bottom-offset,calc(16px + env(safe-area-inset-bottom))) - 4px)}
2404
+ .eg-toast{bottom:calc(var(--erp-guide-bottom-offset,calc(16px + env(safe-area-inset-bottom))) + 60px)}
2405
+ }
2406
+ @keyframes eg-up{from{opacity:0;transform:translate(-50%,30px)}}
2407
+ @media (prefers-reduced-motion:reduce){
2408
+ [data-erp-guide-layer] *,[data-erp-guide-layer] *::before,[data-erp-guide-layer] *::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important}
2409
+ .eg-ring::after{animation:none!important;opacity:1;transform:none}
2410
+ .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1!important;animation-duration:.5s!important}
2411
+ .eg-hand{animation:none!important;transform:translate(4px,6px)}
2412
+ .eg-burst{display:none}
2413
+ .eg-bubble.eg-nudge{animation:none!important;border-top-color:var(--eg-danger)}
2414
+ }
2415
+ `;
2416
+
2417
+ /* ------------------------------------------------------------------ */
2418
+ /* Bits */
2419
+ /* ------------------------------------------------------------------ */
2420
+ const TH_MONTHS = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
2421
+ const pad2 = (n) => String(n).padStart(2, "0");
2422
+ /** "26 ต.ค. 2569 13:04" — day, month, Buddhist year, 24 h. */
2423
+ function formatThaiDateTime(iso) {
2424
+ if (!iso)
2425
+ return "";
2426
+ const d = new Date(iso);
2427
+ if (Number.isNaN(d.getTime()))
2428
+ return "";
2429
+ return `${d.getDate()} ${TH_MONTHS[d.getMonth()]} ${d.getFullYear() + 543} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
2430
+ }
2431
+ /** "กด [บันทึก]": the bracketed word is a chip in the brand colour. */
2432
+ function GuideTitle({ text }) {
2433
+ const parts = text.split(/(\[[^\]]+\])/g).filter(Boolean);
2434
+ return (jsxRuntime.jsx(jsxRuntime.Fragment, { children: parts.map((p, i) => p.startsWith("[") && p.endsWith("]") ? (jsxRuntime.jsx("span", { className: "eg-k", children: p.slice(1, -1) }, i)) : (jsxRuntime.jsx(React__namespace.Fragment, { children: p }, i))) }));
2435
+ }
2436
+ const Svg = ({ children, className = "eg-ic" }) => (jsxRuntime.jsx("svg", { className: className, viewBox: "0 0 24 24", "aria-hidden": "true", children: children }));
2437
+ const IconCheck = () => (jsxRuntime.jsx(Svg, { children: jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" }) }));
2438
+ const IconX = () => (jsxRuntime.jsx(Svg, { children: jsxRuntime.jsx("path", { d: "M18 6 6 18M6 6l12 12" }) }));
2439
+ const IconFlag = () => (jsxRuntime.jsxs(Svg, { children: [jsxRuntime.jsx("path", { d: "M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" }), jsxRuntime.jsx("path", { d: "M4 22v-7" })] }));
2440
+ const IconTrophy = () => (jsxRuntime.jsx(Svg, { children: jsxRuntime.jsx("path", { d: "M6 9H4.5a2.5 2.5 0 0 1 0-5H6M18 9h1.5a2.5 2.5 0 0 0 0-5H18M4 22h16M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22M18 2H6v7a6 6 0 0 0 12 0V2Z" }) }));
2441
+ const HAND_PATH = "M18 11V9.5a2 2 0 0 0-4 0V9a2 2 0 0 0-4 0v.5V4a2 2 0 0 0-4 0v10l-1.6-1.6a2 2 0 0 0-2.83 2.83l3.6 3.6C6.66 20.3 8.6 22 11.5 22H14a8 8 0 0 0 8-8v-3a2 2 0 0 0-4 0z";
2442
+ /** Rounded-rectangle subpath for the scrim's holes. */
2443
+ function roundRect(r, radius) {
2444
+ const rad = Math.max(0, Math.min(radius, r.width / 2, r.height / 2));
2445
+ const { x, y, width: w, height: h } = r;
2446
+ return (`M${x + rad} ${y}H${x + w - rad}A${rad} ${rad} 0 0 1 ${x + w} ${y + rad}` +
2447
+ `V${y + h - rad}A${rad} ${rad} 0 0 1 ${x + w - rad} ${y + h}` +
2448
+ `H${x + rad}A${rad} ${rad} 0 0 1 ${x} ${y + h - rad}` +
2449
+ `V${y + rad}A${rad} ${rad} 0 0 1 ${x + rad} ${y}Z`);
2450
+ }
2451
+ const rectPath = (r) => `M${r.x} ${r.y}H${r.x + r.width}V${r.y + r.height}H${r.x}Z`;
2452
+ /**
2453
+ * The dim layer that eats every press outside the holes. The holes are a
2454
+ * union: where two overlap (a field and the select list open over it) the
2455
+ * page stays open.
2456
+ *
2457
+ * - The look: one rectangle masked by the rounded holes (a mask adds holes
2458
+ * up, so an overlap is not filled back in).
2459
+ * - The presses: a transparent path made of the screen minus the holes, as
2460
+ * rectangles that do not overlap (blockedRects). A press inside a hole
2461
+ * reaches the page underneath; any other lands on the path (marked
2462
+ * data-eg-block) and is cancelled.
2463
+ * - `open`: the holes a press may go through, when not all of them (a "view"
2464
+ * step's target is shown but not pressable). Default: every hole.
2465
+ */
2466
+ function Scrim({ holes, open, width, height }) {
2467
+ const maskId = "eg-scrim-mask-" + React__namespace.useId().replace(/[^a-zA-Z0-9_-]/g, "");
2468
+ const block = blockedRects(open ?? holes, width, height).map(rectPath).join("");
2469
+ return (jsxRuntime.jsxs("svg", { className: "eg-scrim-svg", width: width, height: height, "aria-hidden": "true", children: [holes.length ? (jsxRuntime.jsx("defs", { children: jsxRuntime.jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: -10, y: -10, width: width + 20, height: height + 20, children: [jsxRuntime.jsx("rect", { x: -10, y: -10, width: width + 20, height: height + 20, fill: "#fff" }), holes.map((h, i) => (jsxRuntime.jsx("path", { d: roundRect(h, 12), fill: "#000" }, i)))] }) })) : null, jsxRuntime.jsx("rect", { className: "eg-scrim-fill", x: -10, y: -10, width: width + 20, height: height + 20, mask: holes.length ? `url(#${maskId})` : undefined }), jsxRuntime.jsx("path", { className: "eg-scrim-hit", d: block, "data-eg-block": "" })] }));
2470
+ }
2471
+ /** Whether two rectangles overlap. */
2472
+ const meets = (a, b) => !!intersectRect(a, b);
2473
+ /** The smallest rectangle around all of them. */
2474
+ function boundingRect(rs) {
2475
+ const x = Math.min(...rs.map(r => r.x));
2476
+ const y = Math.min(...rs.map(r => r.y));
2477
+ const right = Math.max(...rs.map(r => r.x + r.width));
2478
+ const bottom = Math.max(...rs.map(r => r.y + r.height));
2479
+ return { x, y, width: right - x, height: bottom - y };
2480
+ }
2481
+ /** Where the bubble may go, in order of preference. */
2482
+ const BUBBLE_PLACEMENTS = ["right", "bottom", "top", "left"];
2483
+ /**
2484
+ * The first placement (in BUBBLE_PLACEMENTS order) whose bubble is on screen,
2485
+ * off the target (with its open list), and off everything to keep clear;
2486
+ * failing that, the first that is only on screen and off the target; -1 when
2487
+ * none is.
2488
+ */
2489
+ function pickPlacement(results, bw, bh, anchor, clear, bounds) {
2490
+ const box = (r) => ({ x: r.x, y: r.y, width: bw, height: bh });
2491
+ const fits = (b) => b.x >= bounds.x - 1 && b.y >= bounds.y - 1 && b.x + b.width <= bounds.x + bounds.width + 1 && b.y + b.height <= bounds.y + bounds.height + 1;
2492
+ const ok = results.map(r => {
2493
+ const b = box(r);
2494
+ return fits(b) && !meets(b, anchor);
2495
+ });
2496
+ const best = results.findIndex((r, i) => ok[i] && !clear.some(c => meets(box(r), c)));
2497
+ return best >= 0 ? best : ok.indexOf(true);
2498
+ }
2499
+ const BUBBLE_TITLE_ID = "eg-bubble-title";
2500
+ const BUBBLE_WHY_ID = "eg-bubble-why";
2501
+ function useNudge(nudge, ref) {
2502
+ const first = React.useRef(nudge);
2503
+ React.useEffect(() => {
2504
+ if (nudge === first.current)
2505
+ return;
2506
+ const el = ref.current;
2507
+ if (!el)
2508
+ return;
2509
+ el.classList.remove("eg-nudge");
2510
+ void el.offsetWidth;
2511
+ el.classList.add("eg-nudge");
2512
+ }, [nudge, ref]);
2513
+ }
2514
+ function StepLayer(p) {
2515
+ const { spot, phone, viewport } = p;
2516
+ const bubbleRef = React.useRef(null);
2517
+ const arrowRef = React.useRef(null);
2518
+ const ringRef = React.useRef(null);
2519
+ const [pos, setPos] = React.useState(null);
2520
+ useNudge(p.nudge, bubbleRef);
2521
+ // Flash the ring with each nudge too (a press outside the hole).
2522
+ const firstNudge = React.useRef(p.nudge);
2523
+ React.useEffect(() => {
2524
+ if (p.nudge === firstNudge.current)
2525
+ return;
2526
+ const el = ringRef.current;
2527
+ if (!el)
2528
+ return;
2529
+ el.classList.remove("eg-flash");
2530
+ void el.offsetWidth;
2531
+ el.classList.add("eg-flash");
2532
+ }, [p.nudge]);
2533
+ const showBubble = p.phase === "ready" && (!!spot || !p.hasTarget);
2534
+ const gap = p.showHand ? 34 : 14;
2535
+ const spotKey = spot ? `${spot.x}|${spot.y}|${spot.width}|${spot.height}` : "";
2536
+ const contentKey = `${p.bubble.title}|${p.bubble.why}|${p.bubble.error?.title ?? ""}|${p.bubble.showNext}`;
2537
+ // What the bubble sits beside: the target, with an open list over it (the
2538
+ // list is what the person is choosing from now). What it must not cover:
2539
+ // open lists, and the other anchors the step allows (a map step's
2540
+ // coordinate fields).
2541
+ const popoverList = p.popovers ?? [];
2542
+ const anchor = spot ? boundingRect([spot, ...popoverList.filter(o => meets(o, spot))]) : null;
2543
+ const clear = [...popoverList, ...p.holes];
2544
+ const anchorKey = anchor ? `${anchor.x}|${anchor.y}|${anchor.width}|${anchor.height}` : "";
2545
+ const clearKey = clear.map(r => `${r.x},${r.y},${r.width},${r.height}`).join(";");
2546
+ React.useLayoutEffect(() => {
2547
+ const el = bubbleRef.current;
2548
+ if (!el || !showBubble)
2549
+ return;
2550
+ const m = 16;
2551
+ if (!spot || !anchor) {
2552
+ // Nothing to point at: the middle of the screen (the bottom on a phone).
2553
+ const bw = el.offsetWidth;
2554
+ const bh = el.offsetHeight;
2555
+ setPos(phone
2556
+ ? { left: m, top: viewport.offsetTop + viewport.height - bh - m, side: "dock" }
2557
+ : { left: (window.innerWidth - bw) / 2, top: viewport.offsetTop + (viewport.height - bh) / 2, side: "dock" });
2558
+ return;
2559
+ }
2560
+ if (phone) {
2561
+ // Docked to the top or the bottom of the screen, whichever covers less
2562
+ // of the target and its open list (target in the lower half: top).
2563
+ const vh = viewport.height;
2564
+ const oy = viewport.offsetTop;
2565
+ const bh = el.offsetHeight;
2566
+ const topT = oy + m + 4;
2567
+ const botT = oy + vh - bh - m;
2568
+ const { y, height: h } = anchor;
2569
+ const overlapTop = Math.max(0, topT + bh + 8 - y);
2570
+ const overlapBot = Math.max(0, y + h + gap - botT);
2571
+ const top = y + h / 2 > vh / 2
2572
+ ? overlapTop <= overlapBot
2573
+ ? topT
2574
+ : botT
2575
+ : overlapBot <= overlapTop
2576
+ ? botT
2577
+ : topT;
2578
+ setPos({ left: m, top, side: "dock" });
2579
+ return;
2580
+ }
2581
+ let cancelled = false;
2582
+ const a = anchor;
2583
+ const ref = {
2584
+ getBoundingClientRect: () => ({
2585
+ x: a.x,
2586
+ y: a.y,
2587
+ left: a.x,
2588
+ top: a.y,
2589
+ width: a.width,
2590
+ height: a.height,
2591
+ right: a.x + a.width,
2592
+ bottom: a.y + a.height,
2593
+ }),
2594
+ };
2595
+ const at = (placement) => dom.computePosition(ref, el, {
2596
+ strategy: "fixed",
2597
+ placement,
2598
+ middleware: [
2599
+ dom.offset(placement.startsWith("bottom") ? gap : 14),
2600
+ dom.shift({ padding: m }),
2601
+ ...(arrowRef.current ? [dom.arrow({ element: arrowRef.current, padding: 14 })] : []),
2602
+ ],
2603
+ });
2604
+ Promise.all(BUBBLE_PLACEMENTS.map(at))
2605
+ .then(results => {
2606
+ if (cancelled)
2607
+ return;
2608
+ const bw = el.offsetWidth;
2609
+ const bh = el.offsetHeight;
2610
+ const bounds = { x: m, y: viewport.offsetTop + m, width: window.innerWidth - 2 * m, height: viewport.height - 2 * m };
2611
+ const i = pickPlacement(results, bw, bh, a, clear, bounds);
2612
+ if (i < 0) {
2613
+ // Nowhere beside it: the bottom-right corner.
2614
+ setPos({ left: window.innerWidth - bw - m, top: viewport.height + viewport.offsetTop - bh - m, side: "dock" });
2615
+ return;
2616
+ }
2617
+ const { x, y, placement, middlewareData } = results[i];
2618
+ const side = placement.split("-")[0];
2619
+ setPos({ left: x, top: y, side, ax: middlewareData.arrow?.x, ay: middlewareData.arrow?.y });
2620
+ })
2621
+ .catch(() => {
2622
+ if (!cancelled)
2623
+ setPos({ left: m, top: m, side: "dock" });
2624
+ });
2625
+ return () => {
2626
+ cancelled = true;
2627
+ };
2628
+ // The keys stand for spot, the lists, the holes and the bubble's size.
2629
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2630
+ }, [spotKey, anchorKey, clearKey, contentKey, phone, showBubble, gap, viewport.height, viewport.offsetTop]);
2631
+ const popovers = p.popovers ?? [];
2632
+ const covered = !!p.covered;
2633
+ const holes = [...(spot && !covered ? [spot] : []), ...popovers, ...p.holes];
2634
+ const openHoles = p.targetPressable === false ? [...popovers, ...p.holes] : holes;
2635
+ const ringShown = !!spot && p.phase === "ready" && !covered && !popovers.some(o => meets(o, spot));
2636
+ const hand = spot && p.showHand && p.phase === "ready" && !covered && !popovers.length ? handPosition(spot, viewport.height) : null;
2637
+ let arrowStyle;
2638
+ if (pos && pos.side !== "dock") {
2639
+ if (pos.side === "right")
2640
+ arrowStyle = { left: -7, top: pos.ay };
2641
+ else if (pos.side === "left")
2642
+ arrowStyle = { right: -7, top: pos.ay };
2643
+ else if (pos.side === "bottom")
2644
+ arrowStyle = { top: -9, left: pos.ax };
2645
+ else
2646
+ arrowStyle = { bottom: -7, left: pos.ax };
2647
+ }
2648
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(Scrim, { holes: p.phase === "ready" ? holes : [], open: p.phase === "ready" ? openHoles : [], width: viewport.width, height: Math.max(viewport.height + viewport.offsetTop, 0) }), spot && ringShown ? (jsxRuntime.jsx("div", { ref: ringRef, className: "eg-ring" + (p.moving ? " eg-move" : ""), style: { left: spot.x, top: spot.y, width: spot.width, height: spot.height }, "aria-hidden": "true" })) : null, hand ? (jsxRuntime.jsx("div", { className: "eg-hand" + (hand.flip ? " eg-flip" : ""), style: { left: hand.left, top: hand.top }, "aria-hidden": "true", children: jsxRuntime.jsx("svg", { viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { d: HAND_PATH }) }) })) : null, showBubble ? (jsxRuntime.jsxs("div", { ref: bubbleRef, className: "eg-bubble" + (p.bubble.error ? " eg-err" : ""), role: "dialog", "aria-modal": "false", "aria-labelledby": BUBBLE_TITLE_ID, "aria-describedby": BUBBLE_WHY_ID, tabIndex: -1, "data-eg-bubble": "", style: {
2649
+ left: pos?.left ?? 0,
2650
+ top: pos?.top ?? 0,
2651
+ width: phone ? viewport.width - 32 : undefined,
2652
+ visibility: pos ? "visible" : "hidden",
2653
+ }, children: [jsxRuntime.jsx(BubbleBody, { ...p }), jsxRuntime.jsx("span", { ref: arrowRef, className: "eg-arrow" + (pos?.side === "bottom" ? " eg-top" : ""), style: arrowStyle ?? { display: "none" }, "aria-hidden": "true" })] })) : null, p.phase === "waiting" ? (jsxRuntime.jsxs("div", { className: "eg-card", role: "status", "data-eg-card": "", children: [jsxRuntime.jsxs("div", { className: "eg-loading", children: [jsxRuntime.jsx("span", { className: "eg-spin", "aria-hidden": "true" }), "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14\u2026"] }), jsxRuntime.jsx("div", { className: "eg-row", children: jsxRuntime.jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }) })] })) : null, p.phase === "missing" ? (jsxRuntime.jsxs("div", { className: "eg-card eg-err", role: "alertdialog", "aria-labelledby": "eg-missing-t", "data-eg-card": "", tabIndex: -1, children: [jsxRuntime.jsx("p", { className: "eg-b-t", id: "eg-missing-t", children: "\u0E44\u0E21\u0E48\u0E1E\u0E1A\u0E2A\u0E48\u0E27\u0E19\u0E19\u0E35\u0E49\u0E1A\u0E19\u0E2B\u0E19\u0E49\u0E32" }), jsxRuntime.jsxs("div", { className: "eg-row", children: [jsxRuntime.jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onRetry, children: "\u0E25\u0E2D\u0E07\u0E2D\u0E35\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07" })] })] })) : null, p.phase === "away" ? (jsxRuntime.jsxs("div", { className: "eg-card", role: "dialog", "aria-modal": "false", "aria-labelledby": "eg-away-t", "data-eg-card": "", tabIndex: -1, children: [jsxRuntime.jsxs("div", { className: "eg-b-top", children: [jsxRuntime.jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.bubble.missionNo, " \u00B7 ", p.bubble.missionTitle, p.bubble.replay ? " (ทบทวน)" : ""] }), jsxRuntime.jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", p.bubble.index + 1, "/", p.bubble.total] })] }), jsxRuntime.jsx("p", { className: "eg-b-t", id: "eg-away-t", style: { marginTop: 8 }, children: jsxRuntime.jsx(GuideTitle, { text: p.bubble.title }) }), jsxRuntime.jsxs("div", { className: "eg-row", children: [jsxRuntime.jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onGoResume, children: "\u0E17\u0E33\u0E15\u0E48\u0E2D" })] })] })) : null, p.confirmExit ? (jsxRuntime.jsx(ConfirmModal, { title: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E44\u0E01\u0E14\u0E4C\u0E15\u0E2D\u0E19\u0E19\u0E35\u0E49?", line: "\u0E40\u0E1B\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E44\u0E14\u0E49\u0E17\u0E35\u0E48\u0E1B\u0E38\u0E48\u0E21 ? \u0E21\u0E38\u0E21\u0E02\u0E27\u0E32\u0E1A\u0E19", leaveLabel: "\u0E2D\u0E2D\u0E01\u0E08\u0E32\u0E01\u0E44\u0E01\u0E14\u0E4C", stayLabel: "\u0E17\u0E33\u0E15\u0E48\u0E2D", onLeave: p.onExitConfirm, onStay: p.onExitCancel })) : null] }));
2654
+ }
2655
+ function BubbleBody(p) {
2656
+ const b = p.bubble;
2657
+ const title = b.error ? b.error.title : b.title;
2658
+ const why = b.error ? (b.error.detail ?? "") : b.why;
2659
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: "eg-b-top", children: [jsxRuntime.jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", b.missionNo, " \u00B7 ", b.missionTitle, b.replay ? " (ทบทวน)" : ""] }), jsxRuntime.jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", b.index + 1, "/", b.total] })] }), jsxRuntime.jsx("div", { className: "eg-pips", "aria-hidden": "true", children: Array.from({ length: b.total }, (_, i) => (jsxRuntime.jsx("i", { className: i < b.index ? "eg-d" : i === b.index ? "eg-c" : undefined }, i))) }), jsxRuntime.jsx("p", { className: "eg-b-t", id: BUBBLE_TITLE_ID, children: jsxRuntime.jsx(GuideTitle, { text: title }) }), jsxRuntime.jsx("p", { className: "eg-b-w", id: BUBBLE_WHY_ID, hidden: !why, children: jsxRuntime.jsx(GuideTitle, { text: why }) }), jsxRuntime.jsxs("div", { className: "eg-b-f", children: [jsxRuntime.jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: b.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsxRuntime.jsxs("span", { style: { display: "flex", gap: 6 }, children: [b.showEndWithoutSave ? (jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: p.onEndWithoutSave, children: "\u0E08\u0E1A\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01" })) : null, b.showNext ? (jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onNext, children: "\u0E16\u0E31\u0E14\u0E44\u0E1B" })) : null] })] })] }));
2660
+ }
2661
+ /** The fingertip at ≈62% across and down the target; upside down near the bottom. */
2662
+ function handPosition(spot, viewportHeight) {
2663
+ const { x, y, width: w, height: h } = spot;
2664
+ const px = x + Math.min(w * 0.62, w - 14);
2665
+ const py = y + h * 0.62;
2666
+ const flip = py + 50 > viewportHeight;
2667
+ return { left: px - 11.5, top: flip ? py - h * 0.3 - 42 : py - 4, flip };
2668
+ }
2669
+ /* ------------------------------------------------------------------ */
2670
+ /* Modals */
2671
+ /* ------------------------------------------------------------------ */
2672
+ function useAutoFocus() {
2673
+ const ref = React.useRef(null);
2674
+ React.useEffect(() => {
2675
+ ref.current?.focus({ preventScroll: true });
2676
+ }, []);
2677
+ return ref;
2678
+ }
2679
+ function ConfirmModal(p) {
2680
+ const stay = useAutoFocus();
2681
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-scrim eg-faint", "data-eg-block": "", onClick: p.onStay }), jsxRuntime.jsxs("div", { className: "eg-modal eg-confirm eg-pop", role: "alertdialog", "aria-modal": "true", "aria-labelledby": "eg-c-t", "aria-describedby": "eg-c-d", "data-eg-modal": "", children: [jsxRuntime.jsx("h2", { id: "eg-c-t", children: p.title }), jsxRuntime.jsx("p", { className: "eg-sub", id: "eg-c-d", style: { fontSize: 14 }, children: p.line }), jsxRuntime.jsxs("div", { className: "eg-actions", children: [jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: p.onLeave, children: p.leaveLabel }), jsxRuntime.jsx("button", { type: "button", ref: stay, className: "eg-btn eg-primary", onClick: p.onStay, children: p.stayLabel })] })] })] }));
2682
+ }
2683
+ function WelcomeModal(p) {
2684
+ const start = useAutoFocus();
2685
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxRuntime.jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-w-t", "data-eg-modal": "", tabIndex: -1, children: [jsxRuntime.jsx("div", { className: "eg-badge", children: jsxRuntime.jsx(IconFlag, {}) }), jsxRuntime.jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxRuntime.jsx("h2", { id: "eg-w-t", children: p.title }), p.subtitle ? jsxRuntime.jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxRuntime.jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxRuntime.jsxs("li", { className: i === 0 ? "eg-first" : undefined, children: [jsxRuntime.jsx("span", { className: "eg-n", children: i + 1 }), jsxRuntime.jsx("span", { className: "eg-t", children: m.title }), jsxRuntime.jsxs("small", { children: [m.minutes, " \u0E19\u0E32\u0E17\u0E35"] })] }, i))) }), jsxRuntime.jsxs("div", { className: "eg-actions", children: [jsxRuntime.jsx("button", { type: "button", ref: start, className: "eg-btn eg-primary", onClick: p.onStart, children: "\u0E40\u0E23\u0E34\u0E48\u0E21\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E41\u0E23\u0E01" }), jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onSkip, children: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19" })] })] }), p.confirm ? (jsxRuntime.jsx(ConfirmModal, { title: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E01\u0E14\u0E4C\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19?", line: "\u0E40\u0E1B\u0E34\u0E14\u0E15\u0E48\u0E2D\u0E44\u0E14\u0E49\u0E17\u0E35\u0E48\u0E1B\u0E38\u0E48\u0E21 ? \u0E21\u0E38\u0E21\u0E02\u0E27\u0E32\u0E1A\u0E19", leaveLabel: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E1B\u0E01\u0E48\u0E2D\u0E19", stayLabel: "\u0E40\u0E23\u0E34\u0E48\u0E21\u0E40\u0E25\u0E22", onLeave: p.onSkipConfirm, onStay: p.onSkipCancel })) : null] }));
2686
+ }
2687
+ function GateModal(p) {
2688
+ const go = useAutoFocus();
2689
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxRuntime.jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-g-t", "data-eg-modal": "", tabIndex: -1, children: [jsxRuntime.jsx("div", { className: "eg-badge", children: jsxRuntime.jsx(IconFlag, {}) }), jsxRuntime.jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxRuntime.jsx("h2", { id: "eg-g-t", children: p.title }), p.subtitle ? jsxRuntime.jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxRuntime.jsxs("div", { className: "eg-actions", children: [jsxRuntime.jsx("a", { ref: go, className: "eg-btn eg-primary", href: p.href, style: { textDecoration: "none" }, children: p.actionLabel }), jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onLater, children: "\u0E44\u0E27\u0E49\u0E17\u0E35\u0E2B\u0E25\u0E31\u0E07" })] })] })] }));
2690
+ }
2691
+ const CONFETTI_COLOURS = ["#3b82f6", "#7db7ff", "#e6a417", "#ff7a6b", "#1d9a5f", "#b0d2ff"];
2692
+ function Confetti({ reduced }) {
2693
+ // Fixed per mount, so a re-render does not throw new pieces.
2694
+ const [pieces] = React.useState(() => Array.from({ length: 26 }, (_, i) => {
2695
+ const a = (Math.PI * 2 * i) / 26 + Math.random() * 0.3;
2696
+ const dist = 90 + Math.random() * 90;
2697
+ return {
2698
+ background: CONFETTI_COLOURS[i % CONFETTI_COLOURS.length],
2699
+ "--x": `${Math.cos(a) * dist}px`,
2700
+ "--y": `${Math.sin(a) * dist + 40}px`,
2701
+ "--r": `${Math.random() * 540 - 270}deg`,
2702
+ animationDelay: `${Math.random() * 0.12}s`,
2703
+ };
2704
+ }));
2705
+ if (reduced)
2706
+ return null;
2707
+ return (jsxRuntime.jsx("div", { className: "eg-burst", "aria-hidden": "true", children: pieces.map((s, i) => (jsxRuntime.jsx("span", { style: s }, i))) }));
2708
+ }
2709
+ function ProgressBar({ from, to, total, label }) {
2710
+ const [width, setWidth] = React.useState(total ? (from / total) * 100 : 0);
2711
+ React.useEffect(() => {
2712
+ // Two frames so the bar is drawn at `from` before it runs to `to`.
2713
+ let raf2 = 0;
2714
+ const raf1 = requestAnimationFrame(() => {
2715
+ raf2 = requestAnimationFrame(() => setWidth(total ? (to / total) * 100 : 0));
2716
+ });
2717
+ return () => {
2718
+ cancelAnimationFrame(raf1);
2719
+ cancelAnimationFrame(raf2);
2720
+ };
2721
+ }, [to, total]);
2722
+ return (jsxRuntime.jsxs("div", { className: "eg-prog", children: [jsxRuntime.jsx("div", { className: "eg-bar", children: jsxRuntime.jsx("i", { style: { width: `${width}%` } }) }), jsxRuntime.jsx("span", { children: label })] }));
2723
+ }
2724
+ function CelebrateModal(p) {
2725
+ const primary = useAutoFocus();
2726
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-scrim eg-light", "data-eg-block": "" }), jsxRuntime.jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-cel-t", "data-eg-modal": "", tabIndex: -1, children: [jsxRuntime.jsx(Confetti, { reduced: p.reduced }), jsxRuntime.jsx("div", { className: "eg-medal", children: jsxRuntime.jsx(IconCheck, {}) }), jsxRuntime.jsxs("p", { className: "eg-eyebrow", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.missionNo, " \u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08"] }), jsxRuntime.jsx("h2", { id: "eg-cel-t", children: p.title }), p.subtitle ? jsxRuntime.jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxRuntime.jsx(ProgressBar, { from: p.reduced ? p.done : Math.max(0, p.done - 1), to: p.done, total: p.total, label: `${p.done}/${p.total} ภารกิจ` }), jsxRuntime.jsxs("div", { className: "eg-actions", children: [p.nextTitle ? (jsxRuntime.jsxs("button", { type: "button", ref: primary, className: "eg-btn eg-primary", onClick: p.onNext, children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E16\u0E31\u0E14\u0E44\u0E1B: ", p.nextTitle] })) : null, jsxRuntime.jsx("button", { type: "button", ref: p.nextTitle ? undefined : primary, className: "eg-btn eg-link", onClick: p.onRest, children: "\u0E1E\u0E31\u0E01\u0E01\u0E48\u0E2D\u0E19" })] })] })] }));
2727
+ }
2728
+ function CompleteModal(p) {
2729
+ const primary = useAutoFocus();
2730
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxRuntime.jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-f-t", "data-eg-modal": "", tabIndex: -1, children: [jsxRuntime.jsx(Confetti, { reduced: p.reduced }), jsxRuntime.jsx("div", { className: "eg-medal", children: jsxRuntime.jsx(IconTrophy, {}) }), jsxRuntime.jsxs("p", { className: "eg-eyebrow", children: ["\u0E04\u0E23\u0E1A ", p.total, " \u0E20\u0E32\u0E23\u0E01\u0E34\u0E08"] }), jsxRuntime.jsx("h2", { id: "eg-f-t", children: p.title }), p.subtitle ? jsxRuntime.jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxRuntime.jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxRuntime.jsxs("li", { className: "eg-ok", children: [jsxRuntime.jsx("span", { className: "eg-n", children: jsxRuntime.jsx(IconCheck, {}) }), jsxRuntime.jsx("span", { className: "eg-t", children: m })] }, i))) }), jsxRuntime.jsxs("div", { className: "eg-actions", children: [jsxRuntime.jsx("button", { type: "button", ref: primary, className: "eg-btn eg-primary", onClick: p.onFinish, children: p.actionLabel }), p.secondary ? (jsxRuntime.jsx("a", { className: "eg-btn eg-ghost", href: p.secondary.href, style: { textDecoration: "none" }, children: p.secondary.label })) : null] })] })] }));
2731
+ }
2732
+ /* ------------------------------------------------------------------ */
2733
+ /* Quest chip and panel */
2734
+ /* ------------------------------------------------------------------ */
2735
+ function QuestChip({ done, total, pulse, onOpen }) {
2736
+ const ref = React.useRef(null);
2737
+ const first = React.useRef(pulse);
2738
+ React.useEffect(() => {
2739
+ if (pulse === first.current)
2740
+ return;
2741
+ const el = ref.current;
2742
+ if (!el)
2743
+ return;
2744
+ el.classList.remove("eg-hi");
2745
+ void el.offsetWidth;
2746
+ el.classList.add("eg-hi");
2747
+ }, [pulse]);
2748
+ const C = 2 * Math.PI * 14;
2749
+ const pct = total ? done / total : 0;
2750
+ return (jsxRuntime.jsxs("button", { ref: ref, type: "button", className: "eg-chip", onClick: onOpen, "aria-label": `ภารกิจเริ่มต้น เสร็จ ${done} จาก ${total}`, children: [jsxRuntime.jsxs("svg", { viewBox: "0 0 34 34", "aria-hidden": "true", children: [jsxRuntime.jsx("circle", { cx: "17", cy: "17", r: "14", fill: "none", stroke: "var(--eg-soft)", strokeWidth: "4" }), done ? (jsxRuntime.jsx("circle", { cx: "17", cy: "17", r: "14", fill: "none", stroke: "var(--eg-primary)", strokeWidth: "4", strokeLinecap: "round", strokeDasharray: `${C * pct} ${C}`, transform: "rotate(-90 17 17)" })) : null] }), "\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", done, "/", total] }));
2751
+ }
2752
+ function QuestPanel(p) {
2753
+ const ref = useAutoFocus();
2754
+ return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: "eg-panel-bd", onClick: p.onClose }), jsxRuntime.jsxs("section", { ref: ref, className: "eg-panel", role: "dialog", "aria-labelledby": "eg-q-t", tabIndex: -1, "data-eg-panel": "", children: [jsxRuntime.jsxs("div", { className: "eg-q-h", children: [jsxRuntime.jsx("h2", { id: "eg-q-t", children: "\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxRuntime.jsxs("span", { className: "eg-n", children: [p.done, "/", p.total] }), jsxRuntime.jsx("button", { type: "button", className: "eg-x", onClick: p.onClose, "aria-label": "\u0E1B\u0E34\u0E14", children: jsxRuntime.jsx(IconX, {}) })] }), jsxRuntime.jsx("div", { className: "eg-prog", children: jsxRuntime.jsx("div", { className: "eg-bar", children: jsxRuntime.jsx("i", { style: { width: `${p.total ? (p.done / p.total) * 100 : 0}%` } }) }) }), jsxRuntime.jsx("ol", { className: "eg-q-list", children: p.items.map((it, i) => (jsxRuntime.jsx(QuestRow, { item: it, n: i + 1, just: p.justDone === it.key, gate: p.gate, onStart: p.onStart, onDismiss: p.onDismiss }, it.key))) }), p.canHideChip ? (jsxRuntime.jsx("div", { className: "eg-q-f", children: jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onHideChip, children: "\u0E0B\u0E48\u0E2D\u0E19\u0E1B\u0E38\u0E48\u0E21\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08" }) })) : null] })] }));
2755
+ }
2756
+ function QuestRow({ item, n, just, gate, onStart, onDismiss, }) {
2757
+ const v = item.view;
2758
+ const ticked = v === "done" || v === "already";
2759
+ const cls = "eg-q-item" +
2760
+ (ticked ? " eg-done" : v === "next" ? " eg-next" : "") +
2761
+ (v === "locked" || v === "waiting" ? " eg-dim" : "") +
2762
+ (just ? " eg-just" : "");
2763
+ let meta = `ประมาณ ${item.minutes} นาที`;
2764
+ if (v === "done")
2765
+ meta = item.completedAt ? `เสร็จ ${formatThaiDateTime(item.completedAt)}` : "เสร็จแล้ว";
2766
+ else if (v === "already")
2767
+ meta = "ทำไว้แล้ว";
2768
+ else if (v === "skipped")
2769
+ meta = jsxRuntime.jsx("span", { children: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E27\u0E49" });
2770
+ else if (v === "waiting" && gate)
2771
+ meta = gate.pending;
2772
+ // Locked: what to do first gets its own line under the title, so the title
2773
+ // keeps the row's width and the button stays short.
2774
+ const lockHint = v === "locked" && item.lockedBy ? `ทำ ${item.lockedBy} ก่อน` : null;
2775
+ let button;
2776
+ if (v === "done")
2777
+ button = jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E17\u0E33\u0E0B\u0E49\u0E33" });
2778
+ else if (v === "already")
2779
+ button = jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E14\u0E39\u0E27\u0E34\u0E18\u0E35\u0E17\u0E33" });
2780
+ else if (v === "waiting" && gate)
2781
+ button = (jsxRuntime.jsx("a", { className: "eg-btn eg-ghost", href: gate.href, style: { textDecoration: "none" }, children: gate.label }));
2782
+ else if (v === "locked")
2783
+ button = (jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-ghost", disabled: true, "aria-label": lockHint ? `เริ่ม (${lockHint})` : undefined, children: "\u0E40\u0E23\u0E34\u0E48\u0E21" }));
2784
+ else
2785
+ button = (jsxRuntime.jsx("button", { type: "button", className: "eg-btn " + (v === "next" ? "eg-primary" : "eg-ghost"), onClick: () => onStart(item.key, false), children: v === "skipped" || v === "active" ? "ทำต่อ" : "เริ่ม" }));
2786
+ const dismissable = item.optional && (v === "todo" || v === "next");
2787
+ return (jsxRuntime.jsxs("li", { className: cls, children: [jsxRuntime.jsx("span", { className: "eg-n", children: ticked ? jsxRuntime.jsx(IconCheck, {}) : n }), jsxRuntime.jsxs("div", { className: "eg-t", children: [jsxRuntime.jsx("b", { children: item.title }), lockHint ? jsxRuntime.jsx("small", { className: "eg-lock", children: lockHint }) : null, jsxRuntime.jsx("small", { className: v === "skipped" ? "eg-sk" : undefined, children: meta })] }), dismissable ? (jsxRuntime.jsxs("span", { className: "eg-q-acts", children: [button, jsxRuntime.jsx("button", { type: "button", className: "eg-btn eg-link", onClick: () => onDismiss(item.key), children: "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E49\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E19\u0E35\u0E49" })] })) : (button)] }));
2788
+ }
2789
+ function GuideToast({ text }) {
2790
+ return (jsxRuntime.jsx("div", { className: "eg-toast", role: "status", children: text }));
2791
+ }
2792
+
2793
+ /* ------------------------------------------------------------------ */
2794
+ /* Fail-open wrappers */
2795
+ /* ------------------------------------------------------------------ */
2796
+ /** Hides the tour (and only the tour) after any error under it. */
2797
+ class GuideErrorBoundary extends React__namespace.Component {
2798
+ constructor() {
2799
+ super(...arguments);
2800
+ Object.defineProperty(this, "state", {
2801
+ enumerable: true,
2802
+ configurable: true,
2803
+ writable: true,
2804
+ value: { failed: false }
2805
+ });
2806
+ }
2807
+ static getDerivedStateFromError() {
2808
+ return { failed: true };
2809
+ }
2810
+ componentDidCatch(error) {
2811
+ if (typeof console !== "undefined")
2812
+ console.warn("[erp-shell guide] hidden after an error", error);
2813
+ try {
2814
+ publishGuideEntry(null, null);
2815
+ }
2816
+ catch {
2817
+ /* ignore */
2818
+ }
2819
+ }
2820
+ render() {
2821
+ return this.state.failed ? null : this.props.children;
2822
+ }
2823
+ }
2824
+ /**
2825
+ * Runs a tour with the app's adapters. Mount it once, above the pages (so a
2826
+ * route change does not unmount it), only where the tour may run.
2827
+ */
2828
+ function GuideRuntime(props) {
2829
+ return (jsxRuntime.jsx(GuideErrorBoundary, { children: jsxRuntime.jsx(GuideRuntimeInner, { ...props }) }, `${props.organizationId}|${props.config.suite.key}`));
2830
+ }
2831
+ /** Waits for `ms` of the page not loading (isBusy false), then calls `fn`; null `isBusy` waits `ms`. */
2832
+ function useAfterIdle(active, ms, isBusy, fn, deps) {
2833
+ const fnRef = React.useRef(fn);
2834
+ fnRef.current = fn;
2835
+ const busyRef = React.useRef(isBusy);
2836
+ busyRef.current = isBusy;
2837
+ React.useEffect(() => {
2838
+ if (!active)
2839
+ return;
2840
+ let idleSince = null;
2841
+ const iv = setInterval(() => {
2842
+ let busy = false;
2843
+ try {
2844
+ busy = busyRef.current();
2845
+ }
2846
+ catch {
2847
+ busy = false;
2848
+ }
2849
+ if (busy) {
2850
+ idleSince = null;
2851
+ return;
2852
+ }
2853
+ idleSince ?? (idleSince = Date.now());
2854
+ if (Date.now() - idleSince >= ms) {
2855
+ clearInterval(iv);
2856
+ fnRef.current();
2857
+ }
2858
+ }, IDLE_POLL_MS);
2859
+ return () => clearInterval(iv);
2860
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2861
+ }, [active, ms, ...deps]);
2862
+ }
2863
+ const notBusy = () => false;
2864
+ /* ------------------------------------------------------------------ */
2865
+ /* Session mirror (instant resume after F5) */
2866
+ /* ------------------------------------------------------------------ */
2867
+ const mirrorKey = (orgId, suite) => `erp-guide:${orgId}:${suite.key}`;
2868
+ function readMirror(orgId, suite) {
2869
+ try {
2870
+ const raw = sessionStorage.getItem(mirrorKey(orgId, suite));
2871
+ if (!raw)
2872
+ return null;
2873
+ const parsed = JSON.parse(raw);
2874
+ const row = parseRow(parsed);
2875
+ if (!row || row.guide_version !== suite.version)
2876
+ return null;
2877
+ return { ...row, server_status: parsed.server_status ?? null };
2878
+ }
2879
+ catch {
2880
+ return null;
2881
+ }
2882
+ }
2883
+ function writeMirror(orgId, suite, p) {
2884
+ try {
2885
+ sessionStorage.setItem(mirrorKey(orgId, suite), JSON.stringify(p));
2886
+ }
2887
+ catch {
2888
+ /* private mode: the server copy is enough */
2889
+ }
2890
+ }
2891
+ /* ------------------------------------------------------------------ */
2892
+ /* One tab at a time */
2893
+ /* ------------------------------------------------------------------ */
2894
+ /**
2895
+ * Whether this tab runs the tour. With two tabs open, the first holds a Web
2896
+ * Lock and the second shows nothing until the first goes away.
2897
+ */
2898
+ function usePrimaryTab(name) {
2899
+ const [primary, setPrimary] = React.useState(false);
2900
+ React.useEffect(() => {
2901
+ const locks = (typeof navigator !== "undefined" ? navigator.locks : undefined);
2902
+ if (!locks?.request) {
2903
+ setPrimary(true);
2904
+ return;
2905
+ }
2906
+ const abort = new AbortController();
2907
+ let release = null;
2908
+ locks
2909
+ .request(name, { signal: abort.signal }, () => {
2910
+ setPrimary(true);
2911
+ return new Promise(resolve => {
2912
+ release = resolve;
2913
+ });
2914
+ })
2915
+ .catch(() => {
2916
+ /* aborted on unmount */
2917
+ });
2918
+ return () => {
2919
+ abort.abort();
2920
+ release?.();
2921
+ setPrimary(false);
2922
+ };
2923
+ }, [name]);
2924
+ return primary;
2925
+ }
2926
+ /* ------------------------------------------------------------------ */
2927
+ /* Putting the page back after a replay */
2928
+ /* ------------------------------------------------------------------ */
2929
+ const ABORT_DELAY_MS = 60;
2930
+ const ABORT_GAP_MS = 150;
2931
+ /**
2932
+ * Runs a replay's abort actions in order, once the tour has let go of the
2933
+ * page: press an anchor (passed over when it is not there), emit an app
2934
+ * event, or Escape to the open dialog (Radix listens on the document).
2935
+ */
2936
+ function runAbort(actions) {
2937
+ actions.forEach((a, i) => {
2938
+ setTimeout(() => {
2939
+ try {
2940
+ if ("click" in a) {
2941
+ findAnchor(a.click)?.click();
2942
+ }
2943
+ else if ("event" in a) {
2944
+ emitGuideEvent(a.event);
2945
+ }
2946
+ else if ("escape" in a) {
2947
+ const t = document.activeElement ?? document.body;
2948
+ t.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true }));
2949
+ }
2950
+ }
2951
+ catch {
2952
+ /* never breaks the app */
2953
+ }
2954
+ }, ABORT_DELAY_MS + i * ABORT_GAP_MS);
2955
+ });
2956
+ }
2957
+ /** A step's own target takes presses: not on a "view" step, unless the step allows it. */
2958
+ function targetPressable(step, bridge) {
2959
+ if (!step || bridge)
2960
+ return true;
2961
+ if (stepKind(step) !== "view")
2962
+ return true;
2963
+ return !!step.target && (step.allow ?? []).includes(step.target);
2964
+ }
2965
+ /* ------------------------------------------------------------------ */
2966
+ /* Host */
2967
+ /* ------------------------------------------------------------------ */
2968
+ const TARGET_PAD = 6;
2969
+ const LOST_GRACE_MS = 350;
2970
+ const WAIT_MS = 8000;
2971
+ const WAIT_CAP_MS = 30000;
2972
+ const WELCOME_DELAY_MS = 500;
2973
+ const CELEBRATE_DELAY_MS = 450;
2974
+ const SAVE_DEBOUNCE_MS = 600;
2975
+ const IDLE_POLL_MS = 100;
2976
+ /** A celebration earned outside the tour waits this long of nothing loading. */
2977
+ const PASSIVE_IDLE_MS = 600;
2978
+ function GuideRuntimeInner({ config, organizationId, code, routing, progress: progressAdapter, isBusy, menu, hidden, bottomOffset }) {
2979
+ const suite = config.suite;
2980
+ const pathname = routing.pathname || "/";
2981
+ const search = routing.search ?? "";
2982
+ const navigateRef = React.useRef(routing.navigate);
2983
+ navigateRef.current = routing.navigate;
2984
+ const adapterRef = React.useRef(progressAdapter);
2985
+ adapterRef.current = progressAdapter;
2986
+ const busy = isBusy ?? notBusy;
2987
+ const busyRef = React.useRef(busy);
2988
+ busyRef.current = busy;
2989
+ // No menu: never a menu step (the machine sees it as always open).
2990
+ const sidebarOpen = menu ? !!menu.open : true;
2991
+ const primary = usePrimaryTab(`erp-guide:${organizationId}:${suite.key}`);
2992
+ // Progress: read once this tab runs the tour and the app is ready.
2993
+ const [answer, setAnswer] = React.useState(null);
2994
+ const enabled = primary && config.ready !== false;
2995
+ const loaded = React.useRef(false);
2996
+ React.useEffect(() => {
2997
+ if (!enabled || loaded.current)
2998
+ return;
2999
+ loaded.current = true;
3000
+ const ac = new AbortController();
3001
+ let alive = true;
3002
+ let settled = false;
3003
+ void loadGuides(adapterRef.current, suite, ac.signal).then(a => {
3004
+ settled = true;
3005
+ if (alive)
3006
+ setAnswer(a);
3007
+ });
3008
+ return () => {
3009
+ alive = false;
3010
+ ac.abort();
3011
+ // Unmounted before the answer (StrictMode's second pass): ask again.
3012
+ if (!settled)
3013
+ loaded.current = false;
3014
+ };
3015
+ }, [enabled, suite]);
3016
+ const live = !!answer && answer.audience !== "none" && !answer.newerOnServer && primary && config.ready !== false && !hidden;
3017
+ /* ---------------- machine ---------------- */
3018
+ const [state, setState] = React.useState(null);
3019
+ const stateRef = React.useRef(null);
3020
+ // What the server holds (payloadKey), so a save that would change nothing
3021
+ // is not sent and does not bump its rev.
3022
+ const savedKey = React.useRef(null);
3023
+ React.useEffect(() => {
3024
+ if (!answer || answer.audience === "none" || answer.newerOnServer) {
3025
+ stateRef.current = null;
3026
+ setState(null);
3027
+ return;
3028
+ }
3029
+ if (stateRef.current)
3030
+ return;
3031
+ savedKey.current = answer.progress && answer.progress.rev > 0 ? payloadKey(answer.progress, suite.app) : null;
3032
+ // Resume from whichever copy is further along: the server's, or this
3033
+ // tab's session copy from before a refresh (its rev is the server's).
3034
+ const mirror = readMirror(organizationId, suite);
3035
+ let progress = answer.progress;
3036
+ if (mirror && furtherProgress(mirror, progress) === mirror)
3037
+ progress = mergeProgress(mirror, progress);
3038
+ const s = initialGuideState(answer.audience, progress);
3039
+ stateRef.current = s;
3040
+ setState(s);
3041
+ }, [answer, organizationId, suite]);
3042
+ // The latest page facts, read by the machine through env.
3043
+ const pageRef = React.useRef({ pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can });
3044
+ pageRef.current = { pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can };
3045
+ const targetElRef = React.useRef(null);
3046
+ const env = React.useCallback(() => {
3047
+ const pg = pageRef.current;
3048
+ return {
3049
+ code,
3050
+ pathname: pg.pathname,
3051
+ search: new URLSearchParams(pg.search),
3052
+ facts: pg.facts,
3053
+ can: (key) => {
3054
+ try {
3055
+ return pg.can ? pg.can(key) : true;
3056
+ }
3057
+ catch {
3058
+ return true;
3059
+ }
3060
+ },
3061
+ isVisible: (anchor, id) => anchorVisible(anchor, id),
3062
+ sidebarOpen: pg.sidebarOpen,
3063
+ targetValue: () => fieldValue(targetElRef.current),
3064
+ dialogOpen: () => appDialogOpen(),
3065
+ };
3066
+ }, [code]);
3067
+ /* ---------------- effects: save, announce, toast, navigate ---------------- */
3068
+ const [liveText, setLiveText] = React.useState("");
3069
+ const [toast, setToast] = React.useState(null);
3070
+ const toastTimer = React.useRef(null);
3071
+ const saveTimer = React.useRef(null);
3072
+ const saving = React.useRef(null);
3073
+ const savePending = React.useRef(false);
3074
+ const flushSave = React.useCallback(async () => {
3075
+ if (saveTimer.current) {
3076
+ clearTimeout(saveTimer.current);
3077
+ saveTimer.current = null;
3078
+ }
3079
+ if (saving.current) {
3080
+ savePending.current = true;
3081
+ return;
3082
+ }
3083
+ const run = async () => {
3084
+ do {
3085
+ savePending.current = false;
3086
+ const cur = stateRef.current;
3087
+ if (!cur)
3088
+ return;
3089
+ if (payloadKey(cur.progress, suite.app) === savedKey.current)
3090
+ continue;
3091
+ const row = await storeGuides(adapterRef.current, suite, cur.progress);
3092
+ if (row)
3093
+ savedKey.current = payloadKey(row, suite.app);
3094
+ if (row && stateRef.current) {
3095
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
3096
+ dispatchRef.current({ type: "serverRow", progress: row });
3097
+ }
3098
+ } while (savePending.current);
3099
+ };
3100
+ saving.current = run().finally(() => {
3101
+ saving.current = null;
3102
+ });
3103
+ }, [organizationId, suite]);
3104
+ const runEffects = React.useCallback((effects) => {
3105
+ for (const e of effects) {
3106
+ try {
3107
+ if (e.type === "save") {
3108
+ if (stateRef.current)
3109
+ writeMirror(organizationId, suite, stateRef.current.progress);
3110
+ if (e.immediate)
3111
+ void flushSave();
3112
+ else {
3113
+ if (saveTimer.current)
3114
+ clearTimeout(saveTimer.current);
3115
+ saveTimer.current = setTimeout(() => void flushSave(), SAVE_DEBOUNCE_MS);
3116
+ }
3117
+ }
3118
+ else if (e.type === "announce") {
3119
+ setLiveText("");
3120
+ setTimeout(() => setLiveText(e.text), 60);
3121
+ }
3122
+ else if (e.type === "toast") {
3123
+ setToast(e.text);
3124
+ if (toastTimer.current)
3125
+ clearTimeout(toastTimer.current);
3126
+ toastTimer.current = setTimeout(() => setToast(null), 3200);
3127
+ }
3128
+ else if (e.type === "navigate") {
3129
+ if (/^https?:\/\//i.test(e.href))
3130
+ window.location.assign(e.href);
3131
+ else
3132
+ navigateRef.current(e.href);
3133
+ }
3134
+ else if (e.type === "abort") {
3135
+ // After this render takes the guard away, put the page back.
3136
+ runAbort(e.actions);
3137
+ }
3138
+ }
3139
+ catch {
3140
+ /* an effect never breaks the app */
3141
+ }
3142
+ }
3143
+ }, [flushSave, organizationId, suite]);
3144
+ const dispatch = React.useCallback((action) => {
3145
+ const cur = stateRef.current;
3146
+ if (!cur)
3147
+ return;
3148
+ let r;
3149
+ try {
3150
+ r = reduceGuide(cur, action, suite, env());
3151
+ }
3152
+ catch (err) {
3153
+ if (typeof console !== "undefined")
3154
+ console.warn("[erp-shell guide] stopped", err);
3155
+ stateRef.current = null;
3156
+ setState(null);
3157
+ return;
3158
+ }
3159
+ if (r.state !== cur) {
3160
+ stateRef.current = r.state;
3161
+ setState(r.state);
3162
+ }
3163
+ if (r.effects.length)
3164
+ runEffects(r.effects);
3165
+ }, [env, runEffects, suite]);
3166
+ const dispatchRef = React.useRef(dispatch);
3167
+ dispatchRef.current = dispatch;
3168
+ // Save what is pending when the page goes away.
3169
+ React.useEffect(() => {
3170
+ const flush = () => {
3171
+ if (saveTimer.current)
3172
+ void flushSave();
3173
+ };
3174
+ window.addEventListener("pagehide", flush);
3175
+ return () => {
3176
+ window.removeEventListener("pagehide", flush);
3177
+ flush();
3178
+ if (toastTimer.current)
3179
+ clearTimeout(toastTimer.current);
3180
+ };
3181
+ }, [flushSave]);
3182
+ /* ---------------- boot: resume, welcome ---------------- */
3183
+ const screen = state?.screen ?? { name: "idle" };
3184
+ const resumed = React.useRef(false);
3185
+ React.useEffect(() => {
3186
+ if (!live || !state || resumed.current)
3187
+ return;
3188
+ resumed.current = true;
3189
+ dispatch({ type: "resume" });
3190
+ }, [live, state, dispatch]);
3191
+ const welcomeRoutes = suite.welcomeRoutes ?? ["/[code]"];
3192
+ const onWelcomeRoute = welcomeRoutes.some(r => !!matchRoute(r, pathname, search, code));
3193
+ const factsKey = useFactsKey(config.facts);
3194
+ const welcomeCtx = state ? guideContext(env(), state.progress.context) : null;
3195
+ const welcomeIsDue = !!state && !!welcomeCtx && live && welcomeDue(state, suite, welcomeCtx);
3196
+ const due = welcomeIsDue && onWelcomeRoute;
3197
+ // After a moment of nothing loading (the page has settled).
3198
+ useAfterIdle(due, WELCOME_DELAY_MS, busy, () => dispatchRef.current({ type: "welcome" }), [factsKey]);
3199
+ /* ---------------- done outside the tour (completeOn) ---------------- */
3200
+ const passiveNames = React.useMemo(() => passiveEventNames(suite), [suite]);
3201
+ const hasPassive = React.useMemo(() => suite.missions.some(m => !!m.completeOn), [suite]);
3202
+ React.useEffect(() => {
3203
+ if (!live || !hasPassive)
3204
+ return;
3205
+ const onApi = (e) => {
3206
+ const d = e.detail;
3207
+ if (!d || typeof d.status !== "number" || typeof d.path !== "string")
3208
+ return;
3209
+ dispatchRef.current({ type: "passive", signal: { kind: "api", method: String(d.method ?? "GET"), path: d.path, status: d.status, id: d.id, message: d.message } });
3210
+ };
3211
+ window.addEventListener(API_EVENT, onApi);
3212
+ const handlers = passiveNames.map(n => [
3213
+ GUIDE_EVENT_PREFIX + n,
3214
+ (e) => dispatchRef.current({ type: "passive", signal: { kind: "event", name: n, detail: e.detail ?? undefined } }),
3215
+ ]);
3216
+ handlers.forEach(([n, h]) => window.addEventListener(n, h));
3217
+ return () => {
3218
+ window.removeEventListener(API_EVENT, onApi);
3219
+ handlers.forEach(([n, h]) => window.removeEventListener(n, h));
3220
+ };
3221
+ }, [live, hasPassive, passiveNames]);
3222
+ /* ---------------- sync on route, sidebar, facts, DOM ---------------- */
3223
+ const inStep = live && screen.name === "step";
3224
+ React.useEffect(() => {
3225
+ if (inStep)
3226
+ dispatch({ type: "sync" });
3227
+ }, [inStep, pathname, search, sidebarOpen, factsKey, dispatch]);
3228
+ React.useEffect(() => {
3229
+ if (!inStep || typeof MutationObserver === "undefined")
3230
+ return;
3231
+ let raf = 0;
3232
+ const obs = new MutationObserver(records => {
3233
+ // Our own layer's changes are not the page's.
3234
+ if (records.every(r => inGuideLayer(r.target)))
3235
+ return;
3236
+ if (raf)
3237
+ return;
3238
+ raf = requestAnimationFrame(() => {
3239
+ raf = 0;
3240
+ dispatchRef.current({ type: "sync" });
3241
+ });
3242
+ });
3243
+ obs.observe(document.body, {
3244
+ childList: true,
3245
+ subtree: true,
3246
+ attributes: true,
3247
+ attributeFilter: ["data-state", "hidden", "aria-hidden", "class", "style", "open"],
3248
+ });
3249
+ return () => {
3250
+ obs.disconnect();
3251
+ if (raf)
3252
+ cancelAnimationFrame(raf);
3253
+ };
3254
+ }, [inStep]);
3255
+ /* ---------------- the current step ---------------- */
3256
+ const stepInfo = React.useMemo(() => {
3257
+ if (!state || screen.name !== "step")
3258
+ return null;
3259
+ const mission = findMission(suite, screen.mission);
3260
+ if (!mission)
3261
+ return null;
3262
+ const raw = mission.steps[screen.index];
3263
+ if (!raw)
3264
+ return null;
3265
+ // A commit step with nothing to save is shown as its read form.
3266
+ const step = shownStep(raw, screen.nothingToSave);
3267
+ return { mission, step, raw };
3268
+ }, [state, screen, suite]);
3269
+ const stepCtx = React.useMemo(() => {
3270
+ if (!state)
3271
+ return null;
3272
+ const e = env();
3273
+ const params = stepInfo?.step.route ? (matchRoute(stepInfo.step.route, e.pathname, e.search, code) ?? {}) : {};
3274
+ return guideContext(e, state.progress.context, params);
3275
+ // pathname/search/factsKey make it current.
3276
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3277
+ }, [state, stepInfo, env, code, pathname, search, factsKey]);
3278
+ const target = stepInfo && stepCtx && screen.name === "step"
3279
+ ? spotlightTarget(stepInfo.step, stepCtx, screen.bridge)
3280
+ : null;
3281
+ const targetKey = target ? `${target.anchor}|${target.id ?? ""}` : "";
3282
+ const phase = screen.name === "step" ? screen.phase : null;
3283
+ const stepId = screen.name === "step" ? `${screen.mission}:${screen.index}:${screen.bridge ? "b" : ""}${screen.nothingToSave ? "n" : ""}` : "";
3284
+ /* Measure every frame while a step is shown: the spotlight follows
3285
+ scrolling, dialogs animating in, the drawer sliding, the keyboard. */
3286
+ const [layout, setLayout] = React.useState({
3287
+ spot: null,
3288
+ covered: false,
3289
+ holes: [],
3290
+ popovers: [],
3291
+ vw: 0,
3292
+ vh: 0,
3293
+ oy: 0,
3294
+ });
3295
+ React.useEffect(() => {
3296
+ if (!inStep) {
3297
+ targetElRef.current = null;
3298
+ return;
3299
+ }
3300
+ let raf = 0;
3301
+ let lostSince = null;
3302
+ let last = { spot: null, covered: false, holes: [], popovers: [], vw: 0, vh: 0, oy: 0 };
3303
+ targetElRef.current = target ? findAnchor(target.anchor, target.id) : null;
3304
+ const allow = stepInfo?.step.allow ?? [];
3305
+ // The spotlight is the part of the target a person can see: cut by the
3306
+ // scroll boxes around it (a row of tabs that scrolls sideways) and the
3307
+ // viewport. Wholly out of view (scrolled away up or down), its own box,
3308
+ // and the tour scrolls it back.
3309
+ let clipFor = null;
3310
+ let clips = [];
3311
+ const spotOf = (el) => {
3312
+ if (el !== clipFor) {
3313
+ clipFor = el;
3314
+ clips = clipAncestors(el);
3315
+ }
3316
+ return padRect(visibleRectOf(el, clips) ?? rectOf(el), TARGET_PAD);
3317
+ };
3318
+ const tick = () => {
3319
+ raf = requestAnimationFrame(tick);
3320
+ const vv = window.visualViewport;
3321
+ const vw = window.innerWidth;
3322
+ const vh = vv ? vv.height : window.innerHeight;
3323
+ const oy = vv ? vv.offsetTop : 0;
3324
+ let el = targetElRef.current;
3325
+ if (target && (!el || !el.isConnected)) {
3326
+ el = findAnchor(target.anchor, target.id);
3327
+ targetElRef.current = el;
3328
+ }
3329
+ let spot = null;
3330
+ if (target && el && isPresent(el)) {
3331
+ lostSince = null;
3332
+ spot = spotOf(el);
3333
+ }
3334
+ else if (target) {
3335
+ // Maybe re-rendered under another node.
3336
+ const again = findAnchor(target.anchor, target.id);
3337
+ if (again) {
3338
+ targetElRef.current = again;
3339
+ spot = spotOf(again);
3340
+ lostSince = null;
3341
+ }
3342
+ else if (phase === "ready") {
3343
+ lostSince ?? (lostSince = performance.now());
3344
+ if (performance.now() - lostSince > LOST_GRACE_MS) {
3345
+ lostSince = null;
3346
+ dispatchRef.current({ type: "targetLost" });
3347
+ }
3348
+ }
3349
+ }
3350
+ if (phase === "waiting" && spot)
3351
+ dispatchRef.current({ type: "sync" });
3352
+ const popovers = [];
3353
+ for (const p of openPoppers())
3354
+ popovers.push(padRect(rectOf(p), 2));
3355
+ const holes = [];
3356
+ for (const a of allow) {
3357
+ const ael = findAnchor(a);
3358
+ if (ael)
3359
+ holes.push(padRect(rectOf(ael), TARGET_PAD));
3360
+ }
3361
+ const covered = !!spot && coveredByDialog(targetElRef.current);
3362
+ const next = { spot, covered, holes, popovers, vw, vh, oy };
3363
+ const sameList = (a, b) => a.length === b.length && a.every((h, i) => sameRect(h, b[i]));
3364
+ if (!sameRect(next.spot, last.spot) ||
3365
+ next.covered !== last.covered ||
3366
+ next.vw !== last.vw ||
3367
+ next.vh !== last.vh ||
3368
+ next.oy !== last.oy ||
3369
+ !sameList(next.holes, last.holes) ||
3370
+ !sameList(next.popovers, last.popovers)) {
3371
+ last = next;
3372
+ setLayout(next);
3373
+ }
3374
+ };
3375
+ raf = requestAnimationFrame(tick);
3376
+ return () => cancelAnimationFrame(raf);
3377
+ // stepId/targetKey/phase restart the loop for a new step.
3378
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3379
+ }, [inStep, stepId, targetKey, phase]);
3380
+ /* Waiting for the target: 8 s of not-loading time (30 s at most). */
3381
+ React.useEffect(() => {
3382
+ if (!inStep || phase !== "waiting")
3383
+ return;
3384
+ let idle = 0;
3385
+ const started = Date.now();
3386
+ const timeout = stepInfo?.step.timeoutMs ?? WAIT_MS;
3387
+ const iv = setInterval(() => {
3388
+ let loading = false;
3389
+ try {
3390
+ loading = busyRef.current();
3391
+ }
3392
+ catch {
3393
+ loading = false;
3394
+ }
3395
+ if (!loading && document.visibilityState !== "hidden")
3396
+ idle += 250;
3397
+ if (idle >= timeout || Date.now() - started >= WAIT_CAP_MS) {
3398
+ clearInterval(iv);
3399
+ dispatchRef.current({ type: "timeout" });
3400
+ }
3401
+ }, 250);
3402
+ return () => clearInterval(iv);
3403
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3404
+ }, [inStep, stepId, phase, screen.name === "step" ? screen.misses : 0]);
3405
+ /* On a step becoming ready: bring the target into view, focus, describe. */
3406
+ const readyKey = inStep && phase === "ready" ? stepId : "";
3407
+ React.useEffect(() => {
3408
+ if (!readyKey || !stepInfo || screen.name !== "step")
3409
+ return;
3410
+ const el = targetElRef.current ?? (target ? findAnchor(target.anchor, target.id) : null);
3411
+ if (el)
3412
+ revealTarget(el);
3413
+ const isInput = !screen.bridge && stepKind(stepInfo.step) === "input";
3414
+ const t = setTimeout(() => {
3415
+ if (isInput && el) {
3416
+ const f = fieldOf(el);
3417
+ f?.focus({ preventScroll: true });
3418
+ }
3419
+ else {
3420
+ const b = document.querySelector(`[${GUIDE_LAYER_ATTRIBUTE}] [data-eg-bubble]`);
3421
+ b?.focus({ preventScroll: true });
3422
+ }
3423
+ }, 30);
3424
+ // The target is described by the bubble while the step lasts.
3425
+ const described = el ? (isInput ? fieldOf(el) : el) : null;
3426
+ const prev = described?.getAttribute("aria-describedby") ?? null;
3427
+ if (described)
3428
+ described.setAttribute("aria-describedby", [BUBBLE_TITLE_ID, BUBBLE_WHY_ID, prev].filter(Boolean).join(" "));
3429
+ return () => {
3430
+ clearTimeout(t);
3431
+ if (!described)
3432
+ return;
3433
+ if (prev)
3434
+ described.setAttribute("aria-describedby", prev);
3435
+ else
3436
+ described.removeAttribute("aria-describedby");
3437
+ };
3438
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3439
+ }, [readyKey]);
3440
+ /* Signals from the page: API answers, app events, presses, typing. */
3441
+ React.useEffect(() => {
3442
+ if (!inStep || !stepInfo)
3443
+ return;
3444
+ const onApi = (e) => {
3445
+ const d = e.detail;
3446
+ if (!d || typeof d.status !== "number")
3447
+ return;
3448
+ dispatchRef.current({ type: "signal", signal: { kind: "api", method: d.method, path: d.path, status: d.status, id: d.id, message: d.message } });
3449
+ };
3450
+ window.addEventListener(API_EVENT, onApi);
3451
+ const names = triggersOf(stepInfo.raw).flatMap(t => ("event" in t ? [t.event] : []));
3452
+ const onApp = (name) => (e) => dispatchRef.current({ type: "signal", signal: { kind: "event", name, detail: e.detail ?? undefined } });
3453
+ const appHandlers = names.map(n => [GUIDE_EVENT_PREFIX + n, onApp(n)]);
3454
+ appHandlers.forEach(([n, h]) => window.addEventListener(n, h));
3455
+ const inTarget = (node) => {
3456
+ const el = targetElRef.current;
3457
+ return !!el && node instanceof Node && el.contains(node);
3458
+ };
3459
+ // After the app has handled it, so what it does comes first.
3460
+ const later = (a) => setTimeout(() => dispatchRef.current(a), 0);
3461
+ const onPress = (e) => {
3462
+ if (inTarget(e.target))
3463
+ later({ type: "signal", signal: { kind: "activate" } });
3464
+ };
3465
+ const onKey = (e) => {
3466
+ if ((e.key === "Enter" || e.key === " ") && inTarget(e.target) && stepKind(stepInfo.step) !== "input") {
3467
+ later({ type: "signal", signal: { kind: "activate" } });
3468
+ }
3469
+ };
3470
+ const onInput = (e) => {
3471
+ if (!inTarget(e.target))
3472
+ return;
3473
+ dispatchRef.current({ type: "signal", signal: { kind: "typing" } });
3474
+ later({ type: "signal", signal: { kind: "value", value: fieldValue(targetElRef.current) } });
3475
+ };
3476
+ document.addEventListener("pointerup", onPress, true);
3477
+ document.addEventListener("keydown", onKey, true);
3478
+ document.addEventListener("input", onInput, true);
3479
+ document.addEventListener("change", onInput, true);
3480
+ return () => {
3481
+ window.removeEventListener(API_EVENT, onApi);
3482
+ appHandlers.forEach(([n, h]) => window.removeEventListener(n, h));
3483
+ document.removeEventListener("pointerup", onPress, true);
3484
+ document.removeEventListener("keydown", onKey, true);
3485
+ document.removeEventListener("input", onInput, true);
3486
+ document.removeEventListener("change", onInput, true);
3487
+ };
3488
+ }, [inStep, stepInfo]);
3489
+ /* ---------------- the guard ---------------- */
3490
+ const modalScreen = live && (screen.name === "welcome" || screen.name === "gate" || screen.name === "celebrate" || screen.name === "complete");
3491
+ const panelOpen = live && !!state?.panelOpen;
3492
+ const guarding = inStep || modalScreen;
3493
+ const guardingRef = React.useRef(guarding);
3494
+ guardingRef.current = guarding;
3495
+ const modalRef = React.useRef(false);
3496
+ modalRef.current = modalScreen || (screen.name === "step" && (screen.confirmExit || screen.phase !== "ready"));
3497
+ const stepInfoRef = React.useRef(stepInfo);
3498
+ stepInfoRef.current = stepInfo;
3499
+ React.useEffect(() => {
3500
+ if (!live)
3501
+ return;
3502
+ const allowedTarget = (node) => {
3503
+ if (!(node instanceof Node))
3504
+ return false;
3505
+ const el = targetElRef.current;
3506
+ // A "view" step's target is there to be read: ถัดไป is the way on.
3507
+ const sc = stateRef.current?.screen;
3508
+ const pressable = targetPressable(stepInfoRef.current?.step, sc?.name === "step" && sc.bridge);
3509
+ if (el && pressable && el.contains(node))
3510
+ return true;
3511
+ const elNode = node instanceof Element ? node : node.parentElement;
3512
+ if (!elNode)
3513
+ return false;
3514
+ if (elNode.closest(POPPER_SELECTOR) || elNode.closest(TOASTER_SELECTOR))
3515
+ return true;
3516
+ for (const a of stepInfoRef.current?.step.allow ?? []) {
3517
+ const ael = findAnchor(a);
3518
+ if (ael && ael.contains(node))
3519
+ return true;
3520
+ }
3521
+ return false;
3522
+ };
3523
+ const onPointer = (e) => {
3524
+ const t = e.target;
3525
+ if (inGuideLayer(t)) {
3526
+ // Our dim layer eats the press (and keeps focus where it is).
3527
+ if (t instanceof Element && t.closest("[data-eg-block]")) {
3528
+ e.preventDefault();
3529
+ if (e.type === "pointerdown")
3530
+ dispatchRef.current({ type: "blocked" });
3531
+ }
3532
+ // The app's open dialog or menu never hears the press (the click
3533
+ // itself goes on to our buttons).
3534
+ if (e.type !== "click")
3535
+ e.stopPropagation();
3536
+ return;
3537
+ }
3538
+ if (!guardingRef.current)
3539
+ return;
3540
+ if (modalRef.current || !allowedTarget(t)) {
3541
+ e.preventDefault();
3542
+ e.stopPropagation();
3543
+ if (e.type === "pointerdown")
3544
+ dispatchRef.current({ type: "blocked" });
3545
+ }
3546
+ };
3547
+ // Radix FocusScope pulls focus back into an open dialog; DismissableLayer
3548
+ // closes on focus outside. Neither may see focus moving to the tour.
3549
+ const onFocusIn = (e) => {
3550
+ if (inGuideLayer(e.target))
3551
+ e.stopPropagation();
3552
+ };
3553
+ const onFocusOut = (e) => {
3554
+ if (inGuideLayer(e.relatedTarget))
3555
+ e.stopPropagation();
3556
+ };
3557
+ const onKey = (e) => {
3558
+ const s = stateRef.current;
3559
+ if (!s)
3560
+ return;
3561
+ const sc = s.screen;
3562
+ const stop = () => {
3563
+ e.preventDefault();
3564
+ e.stopImmediatePropagation();
3565
+ };
3566
+ if (e.key === "Escape") {
3567
+ if (sc.name === "step") {
3568
+ stop();
3569
+ if (sc.confirmExit)
3570
+ dispatchRef.current({ type: "exitCancel" });
3571
+ else
3572
+ dispatchRef.current({ type: "exit" });
3573
+ }
3574
+ else if (sc.name === "welcome") {
3575
+ stop();
3576
+ dispatchRef.current({ type: sc.confirm ? "welcomeSkipCancel" : "welcomeSkip" });
3577
+ }
3578
+ else if (sc.name === "gate") {
3579
+ stop();
3580
+ dispatchRef.current({ type: "gateLater" });
3581
+ }
3582
+ else if (sc.name === "celebrate") {
3583
+ stop();
3584
+ dispatchRef.current({ type: "rest" });
3585
+ }
3586
+ else if (sc.name === "complete") {
3587
+ stop();
3588
+ dispatchRef.current({ type: "finish" });
3589
+ }
3590
+ else if (s.panelOpen) {
3591
+ stop();
3592
+ dispatchRef.current({ type: "closePanel" });
3593
+ }
3594
+ return;
3595
+ }
3596
+ if (!guardingRef.current)
3597
+ return;
3598
+ const layer = layerRef.current;
3599
+ if (e.key === "Tab") {
3600
+ // Tab stays on what the step is about: the target and the bubble, or
3601
+ // the open card.
3602
+ const modals = layer ? Array.from(layer.querySelectorAll("[data-eg-modal],[data-eg-card]")) : [];
3603
+ let list;
3604
+ if (sc.name === "step" && !sc.confirmExit && sc.phase === "ready") {
3605
+ const el = targetElRef.current;
3606
+ const step = stepInfoRef.current?.step;
3607
+ const isInput = !!step && !sc.bridge && stepKind(step) === "input";
3608
+ const inTargetList = el && targetPressable(step, sc.bridge) ? focusablesIn(isInput ? (fieldOf(el) ?? el) : el) : [];
3609
+ const bubble = layer?.querySelector("[data-eg-bubble]") ?? null;
3610
+ list = [...inTargetList, ...(bubble ? Array.from(bubble.querySelectorAll(FOCUSABLE)) : [])];
3611
+ for (const p of openPoppers())
3612
+ list.push(...focusablesIn(p));
3613
+ }
3614
+ else {
3615
+ const last = modals[modals.length - 1] ?? null;
3616
+ list = last ? Array.from(last.querySelectorAll(FOCUSABLE)) : [];
3617
+ }
3618
+ if (!list.length)
3619
+ return;
3620
+ stop();
3621
+ const i = list.indexOf(document.activeElement);
3622
+ const n = e.shiftKey ? (i <= 0 ? list.length - 1 : i - 1) : i === -1 || i === list.length - 1 ? 0 : i + 1;
3623
+ list[n].focus();
3624
+ return;
3625
+ }
3626
+ if (e.key === "Enter" || e.key === " ") {
3627
+ const active = document.activeElement;
3628
+ if (inGuideLayer(active))
3629
+ return;
3630
+ if (sc.name === "step" && sc.phase === "ready" && !sc.confirmExit && e.key === "Enter") {
3631
+ const step = stepInfoRef.current?.step;
3632
+ const el = targetElRef.current;
3633
+ if (step && stepKind(step) === "input" && el && active instanceof Node && el.contains(active) && !(active instanceof HTMLTextAreaElement)) {
3634
+ // During the tour Enter is ถัดไป, not "submit the form".
3635
+ stop();
3636
+ dispatchRef.current({ type: "next" });
3637
+ return;
3638
+ }
3639
+ }
3640
+ if (modalRef.current || !allowedTarget(active))
3641
+ stop();
3642
+ }
3643
+ };
3644
+ window.addEventListener("pointerdown", onPointer, true);
3645
+ window.addEventListener("mousedown", onPointer, true);
3646
+ window.addEventListener("touchstart", onPointer, { capture: true, passive: false });
3647
+ window.addEventListener("click", onPointer, true);
3648
+ window.addEventListener("focusin", onFocusIn, true);
3649
+ window.addEventListener("focusout", onFocusOut, true);
3650
+ window.addEventListener("keydown", onKey, true);
3651
+ return () => {
3652
+ window.removeEventListener("pointerdown", onPointer, true);
3653
+ window.removeEventListener("mousedown", onPointer, true);
3654
+ window.removeEventListener("touchstart", onPointer, true);
3655
+ window.removeEventListener("click", onPointer, true);
3656
+ window.removeEventListener("focusin", onFocusIn, true);
3657
+ window.removeEventListener("focusout", onFocusOut, true);
3658
+ window.removeEventListener("keydown", onKey, true);
3659
+ };
3660
+ }, [live]);
3661
+ /* Focus comes back to where it was when the tour lets go. */
3662
+ const lastFocus = React.useRef(null);
3663
+ const engaged = guarding || panelOpen;
3664
+ React.useLayoutEffect(() => {
3665
+ if (engaged) {
3666
+ if (!lastFocus.current) {
3667
+ const a = document.activeElement;
3668
+ lastFocus.current = a instanceof HTMLElement && !inGuideLayer(a) ? a : null;
3669
+ }
3670
+ return;
3671
+ }
3672
+ const back = lastFocus.current;
3673
+ lastFocus.current = null;
3674
+ if (back && back.isConnected)
3675
+ back.focus({ preventScroll: true });
3676
+ }, [engaged]);
3677
+ /* ---------------- the layer ---------------- */
3678
+ const [layer, setLayer] = React.useState(null);
3679
+ const layerRef = React.useRef(null);
3680
+ React.useEffect(() => {
3681
+ const el = layerRef.current;
3682
+ if (!el)
3683
+ return;
3684
+ if (bottomOffset)
3685
+ el.style.setProperty("--erp-guide-bottom-offset", bottomOffset);
3686
+ else
3687
+ el.style.removeProperty("--erp-guide-bottom-offset");
3688
+ }, [bottomOffset, layer]);
3689
+ React.useEffect(() => {
3690
+ const el = document.createElement("div");
3691
+ el.setAttribute(GUIDE_LAYER_ATTRIBUTE, "");
3692
+ document.body.appendChild(el);
3693
+ layerRef.current = el;
3694
+ setLayer(el);
3695
+ // A Radix modal (dialog, select, menu) hides everything outside it from
3696
+ // screen readers with aria-hidden's hideOthers. It keeps [aria-live]
3697
+ // elements but walks into their ancestors and hides the other children:
3698
+ // with the status line live, the bubble and its buttons were hidden.
3699
+ // Take off what it adds, at once. hideOthers marks what it hides with
3700
+ // data-aria-hidden (the layer never sets that, or inert); aria-hidden goes
3701
+ // only where it was just added, so the layer's own decorative aria-hidden
3702
+ // stays. (aria-live="off" on the layer would make hideOthers skip it, but
3703
+ // it changed what test tools match by text.)
3704
+ const obs = new MutationObserver(records => {
3705
+ for (const r of records) {
3706
+ const n = r.target;
3707
+ if (!(n instanceof Element))
3708
+ continue;
3709
+ if (r.attributeName === "inert" && n.hasAttribute("inert"))
3710
+ n.removeAttribute("inert");
3711
+ else if (r.attributeName === "data-aria-hidden" && n.hasAttribute("data-aria-hidden"))
3712
+ n.removeAttribute("data-aria-hidden");
3713
+ else if (r.attributeName === "aria-hidden" &&
3714
+ n.getAttribute("aria-hidden") === "true" &&
3715
+ (n === el || r.oldValue === null)) {
3716
+ n.removeAttribute("aria-hidden");
3717
+ }
3718
+ }
3719
+ });
3720
+ obs.observe(el, { attributes: true, attributeOldValue: true, subtree: true, attributeFilter: ["aria-hidden", "data-aria-hidden", "inert"] });
3721
+ return () => {
3722
+ obs.disconnect();
3723
+ el.remove();
3724
+ layerRef.current = null;
3725
+ };
3726
+ }, []);
3727
+ const [phone, setPhone] = React.useState(false);
3728
+ const [reduced, setReduced] = React.useState(false);
3729
+ React.useEffect(() => {
3730
+ const sync = () => {
3731
+ setPhone(isPhoneWidth());
3732
+ setReduced(prefersReducedMotion());
3733
+ };
3734
+ sync();
3735
+ window.addEventListener("resize", sync);
3736
+ return () => window.removeEventListener("resize", sync);
3737
+ }, []);
3738
+ // The celebration waits a beat, so the new row can be seen first.
3739
+ const [celebrateShown, setCelebrateShown] = React.useState(false);
3740
+ const celebrateKey = screen.name === "celebrate" || screen.name === "complete" ? screen.name + (screen.name === "celebrate" ? screen.mission : "") : "";
3741
+ React.useEffect(() => {
3742
+ setCelebrateShown(false);
3743
+ if (!celebrateKey)
3744
+ return;
3745
+ const t = setTimeout(() => setCelebrateShown(true), CELEBRATE_DELAY_MS);
3746
+ return () => clearTimeout(t);
3747
+ }, [celebrateKey]);
3748
+ // Ring moves smoothly only right after a step change.
3749
+ const [moving, setMoving] = React.useState(false);
3750
+ React.useEffect(() => {
3751
+ if (!stepId)
3752
+ return;
3753
+ setMoving(true);
3754
+ const t = setTimeout(() => setMoving(false), 320);
3755
+ return () => clearTimeout(t);
3756
+ }, [stepId]);
3757
+ /* ---------------- the "?" menu entry ---------------- */
3758
+ const ctxIdle = React.useMemo(() => (state ? guideContext(env(), state.progress.context) : null), [state, env, factsKey, pathname]); // eslint-disable-line react-hooks/exhaustive-deps
3759
+ const done = state && ctxIdle ? settledCount(suite, state.progress, ctxIdle) : 0;
3760
+ // Only the missions this user has (GuideMission.visible).
3761
+ const shown = React.useMemo(() => (ctxIdle ? shownMissions(suite, ctxIdle) : suite.missions), [suite, ctxIdle]);
3762
+ const total = shown.length;
3763
+ // A celebration earned outside the tour: at the next idle moment — no
3764
+ // step, card or panel up, the welcome not waiting, nothing loading.
3765
+ const passiveDue = live &&
3766
+ !!state &&
3767
+ (state.pendingCelebrate?.length ?? 0) > 0 &&
3768
+ screen.name === "idle" &&
3769
+ !state.panelOpen &&
3770
+ !due;
3771
+ useAfterIdle(passiveDue, PASSIVE_IDLE_MS, busy, () => dispatchRef.current({ type: "idleCelebrate" }), [state?.pendingCelebrate?.join(",")]);
3772
+ React.useEffect(() => {
3773
+ if (!live || !state) {
3774
+ publishGuideEntry(null, null);
3775
+ return;
3776
+ }
3777
+ publishGuideEntry({ done, total }, () => dispatchRef.current({ type: "openPanel" }));
3778
+ }, [live, state, done, total]);
3779
+ React.useEffect(() => () => publishGuideEntry(null, null), []);
3780
+ if (!live || !state || !layer || !ctxIdle)
3781
+ return null;
3782
+ /* ---------------- render ---------------- */
3783
+ const views = missionViews(suite, state.progress, ctxIdle);
3784
+ const gate = suite.gate;
3785
+ const gateHref = gate ? resolveText(gate.action.href, ctxIdle) : "";
3786
+ const gateFailing = gate ? gateState(suite, ctxIdle) === false : false;
3787
+ let content = null;
3788
+ if (screen.name === "welcome") {
3789
+ content = (jsxRuntime.jsx(WelcomeModal, { title: resolveText(suite.welcome.title, ctxIdle), subtitle: resolveText(suite.welcome.subtitle, ctxIdle) || `มาตั้งค่าบริษัทให้พร้อมใน ${total} ภารกิจ`, missions: shown.map(m => ({ title: m.title, minutes: m.minutes })), confirm: screen.confirm, onStart: () => dispatch({ type: "welcomeStart" }), onSkip: () => dispatch({ type: "welcomeSkip" }), onSkipConfirm: () => dispatch({ type: "welcomeSkipConfirm" }), onSkipCancel: () => dispatch({ type: "welcomeSkipCancel" }) }));
3790
+ }
3791
+ else if (screen.name === "gate" && gate) {
3792
+ content = (jsxRuntime.jsx(GateModal, { title: gate.title, subtitle: gate.subtitle, actionLabel: gate.action.label, href: gateHref, onLater: () => dispatch({ type: "gateLater" }) }));
3793
+ }
3794
+ else if (screen.name === "step" && stepInfo && stepCtx) {
3795
+ const { mission, step } = stepInfo;
3796
+ const missionNo = missionNumber(suite, mission.key, ctxIdle);
3797
+ const kind = stepKind(step);
3798
+ const bridge = screen.bridge;
3799
+ content = (jsxRuntime.jsx(StepLayer, { spot: layout.spot, holes: layout.holes, popovers: layout.popovers, covered: layout.covered, viewport: { width: layout.vw || window.innerWidth, height: layout.vh || window.innerHeight, offsetTop: layout.oy }, phone: phone, showHand: bridge || (kind !== "input" && kind !== "view"), bubble: {
3800
+ missionNo,
3801
+ missionTitle: mission.title,
3802
+ replay: screen.replay,
3803
+ index: screen.index,
3804
+ total: mission.steps.length,
3805
+ title: bridge ? "กดปุ่มเมนู" : resolveText(step.title, stepCtx),
3806
+ why: bridge ? `เมนูทั้งหมดของ ${suite.appName} อยู่ในนี้` : resolveText(step.why, stepCtx),
3807
+ error: screen.error,
3808
+ showNext: !bridge && (kind === "input" || kind === "view"),
3809
+ showEndWithoutSave: !bridge && screen.replay && kind === "commit",
3810
+ }, hasTarget: bridge || !!step.target, targetPressable: targetPressable(step, bridge), phase: screen.phase, confirmExit: screen.confirmExit, nudge: state.nudge, moving: moving, onExit: () => dispatch({ type: "exit" }), onNext: () => dispatch({ type: "next" }), onEndWithoutSave: () => dispatch({ type: "endWithoutSave" }), onRetry: () => dispatch({ type: "retry" }), onGoResume: () => dispatch({ type: "goResume" }), onExitConfirm: () => dispatch({ type: "exitConfirm" }), onExitCancel: () => dispatch({ type: "exitCancel" }) }));
3811
+ }
3812
+ else if (screen.name === "celebrate" && celebrateShown) {
3813
+ const mission = findMission(suite, screen.mission);
3814
+ const next = findMission(suite, nextMissionKey(suite, state.progress, ctxIdle));
3815
+ if (mission) {
3816
+ content = (jsxRuntime.jsx(CelebrateModal, { missionNo: missionNumber(suite, mission.key, ctxIdle), title: resolveText(mission.done?.title, ctxIdle) || `${mission.title}แล้ว`, subtitle: resolveText(mission.done?.subtitle, ctxIdle), done: done, total: total, nextTitle: next?.title ?? null, reduced: reduced, onNext: () => dispatch({ type: "celebrateNext" }), onRest: () => dispatch({ type: "rest" }) }));
3817
+ }
3818
+ }
3819
+ else if (screen.name === "complete" && celebrateShown) {
3820
+ const secondary = suite.complete.secondary;
3821
+ let secondaryHref;
3822
+ try {
3823
+ secondaryHref = secondary ? (typeof secondary.href === "function" ? secondary.href(ctxIdle) : secondary.href) : undefined;
3824
+ }
3825
+ catch {
3826
+ secondaryHref = undefined;
3827
+ }
3828
+ content = (jsxRuntime.jsx(CompleteModal, { total: total, title: resolveText(suite.complete.title, ctxIdle) || "บริษัทพร้อมใช้งานแล้ว", subtitle: resolveText(suite.complete.subtitle, ctxIdle), missions: shown.map(m => m.title), actionLabel: suite.complete.action.label, secondary: secondary && secondaryHref ? { label: secondary.label, href: secondaryHref } : null, reduced: reduced, onFinish: () => dispatch({ type: "finish" }) }));
3829
+ }
3830
+ const items = views.map(v => ({
3831
+ key: v.mission.key,
3832
+ title: v.mission.title,
3833
+ minutes: v.mission.minutes,
3834
+ view: v.view,
3835
+ optional: !!v.mission.optional,
3836
+ completedAt: v.entry?.completed_at ?? null,
3837
+ lockedBy: v.view === "locked"
3838
+ ? (v.mission.after ?? [])
3839
+ .filter(k => shown.some(m => m.key === k))
3840
+ .map(k => findMission(suite, k)?.title)
3841
+ .filter(Boolean)
3842
+ .join(", ")
3843
+ : undefined,
3844
+ }));
3845
+ const showChip = chipVisible(state, suite, ctxIdle);
3846
+ return reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("style", { children: GUIDE_CSS }), jsxRuntime.jsx("div", { className: "eg-sr", "aria-live": "polite", role: "status", children: liveText }), content, showChip ? jsxRuntime.jsx(QuestChip, { done: done, total: total, pulse: state.chipPulse, onOpen: () => dispatch({ type: "openPanel" }) }) : null, state.panelOpen && screen.name === "idle" ? (jsxRuntime.jsx(QuestPanel, { items: items, done: done, total: total, justDone: state.justDone, gate: gate && gateFailing ? { label: gate.action.label, pending: gate.pending, href: gateHref } : null, canHideChip: !state.progress.chip_hidden && state.progress.status !== "completed", onClose: () => dispatch({ type: "closePanel" }), onStart: (key, replayIt) => dispatch({ type: "start", mission: key, replay: replayIt }), onDismiss: key => dispatch({ type: "dismissMission", mission: key }), onHideChip: () => dispatch({ type: "hideChip" }) })) : null, toast ? jsxRuntime.jsx(GuideToast, { text: toast }) : null] }), layer);
3847
+ }
3848
+ /** A stable key for the facts object, so effects re-run when they change. */
3849
+ function useFactsKey(facts) {
3850
+ return React.useMemo(() => {
3851
+ try {
3852
+ return JSON.stringify(facts ?? {});
3853
+ }
3854
+ catch {
3855
+ return String(Math.random());
3856
+ }
3857
+ }, [facts]);
3858
+ }
3859
+
3860
+ exports.API_EVENT = API_EVENT;
3861
+ exports.GUIDE_EVENT_PREFIX = GUIDE_EVENT_PREFIX;
3862
+ exports.GUIDE_LAYER_ATTRIBUTE = GUIDE_LAYER_ATTRIBUTE;
3863
+ exports.GuideErrorBoundary = GuideErrorBoundary;
3864
+ exports.GuideProgressConflict = GuideProgressConflict;
3865
+ exports.GuideRuntime = GuideRuntime;
3866
+ exports.apiCallDetail = apiCallDetail;
3867
+ exports.emitGuideEvent = emitGuideEvent;
3868
+ exports.fillRoute = fillRoute;
3869
+ exports.guideAnchor = guideAnchor;
3870
+ exports.loadGuides = loadGuides;
3871
+ exports.matchApiPath = matchApiPath;
3872
+ exports.matchRoute = matchRoute;
3873
+ exports.openGuidePanel = openGuidePanel;
3874
+ exports.reportApiCall = reportApiCall;
3875
+ exports.reportApiEvent = reportApiEvent;
3876
+ exports.storeGuides = storeGuides;
3877
+ exports.useGuideEntry = useGuideEntry;
3878
+ //# sourceMappingURL=guide-runtime-CFVYM8Xi.cjs.map