@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.
package/dist/index.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use client';
2
2
  import * as React from 'react';
3
- import React__default, { useRef, useEffect, useMemo, useState, useCallback, createContext, useContext, Fragment, useSyncExternalStore, useTransition, useLayoutEffect, Suspense } from 'react';
3
+ import React__default, { useRef, useEffect, useMemo, useState, useCallback, createContext, useContext, Fragment, useSyncExternalStore, useTransition, Suspense } from 'react';
4
4
  import { useSession, signOut } from 'next-auth/react';
5
- import { useQueryClient, useQuery, QueryClientContext, QueryClient, useIsFetching, hashKey, MutationCache, QueryCache, QueryClientProvider } from '@tanstack/react-query';
5
+ import { useQueryClient, useQuery, QueryClientContext, QueryClient, hashKey, MutationCache, QueryCache, QueryClientProvider } from '@tanstack/react-query';
6
6
  import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
7
7
  import { cn, Button, Tooltip, TooltipTrigger, TooltipContent, Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbSeparator, BreadcrumbPage, Avatar, AvatarImage, AvatarFallback, Collapsible, CollapsibleTrigger, CollapsibleContent, Badge, DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuLabel, DropdownMenuItem, DropdownMenuSeparator, Skeleton, Dialog, DialogContent, DialogHeader, DialogTitle, Label, Textarea, DialogFooter, Card, CardHeader, CardContent } from '@eintrek/erp-theme';
8
8
  import { PanelLeftClose, Menu, ChevronRight, Building2, Palette, ChevronUp, Sun, Moon, Monitor, Globe, UserCog, LayoutGrid, ExternalLink, CircleHelp, Loader2, LogOut, Calculator, Warehouse, FolderKanban, Users, Store, Headset, ChevronDown, Plus, ChevronsUpDown, Flag, MessageCircle, ImagePlus, X, CircleCheck, ArrowLeft, Ban, Home, ContactRound, UserPlus, ArrowRight, Compass, ArrowUpRight } from 'lucide-react';
@@ -14,8 +14,10 @@ import { createPortal } from 'react-dom';
14
14
  import { useTheme, ThemeProvider as ThemeProvider$1 } from 'next-themes';
15
15
  import axios, { isAxiosError, AxiosHeaders } from 'axios';
16
16
  export { isAxiosError } from 'axios';
17
- import { computePosition, offset, shift, arrow } from '@floating-ui/dom';
17
+ import { j as reportApiEvent, h as guideAnchor, u as useGuideEntry, o as openGuidePanel, b as GuideErrorBoundary, d as GuideRuntime } from './chunks/guide-runtime-CBLovNNu.esm.js';
18
+ export { A as GUIDE_API_EVENT, G as GUIDE_EVENT_PREFIX, a as GUIDE_LAYER_ATTRIBUTE, c as GuideProgressConflict, f as emitGuideEvent, r as reportApiCall } from './chunks/guide-runtime-CBLovNNu.esm.js';
18
19
  import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
20
+ import '@floating-ui/dom';
19
21
 
20
22
  /**
21
23
  * Interval (ms) between session updates to trigger JWT callback and refresh
@@ -1259,35 +1261,35 @@ let declaredApp = null;
1259
1261
  // The message the dialog should open on (the ตอบกลับ link's ?help=H1004),
1260
1262
  // until it is closed or left.
1261
1263
  let pendingRef = null;
1262
- const listeners$1 = new Set();
1263
- function emit$1() {
1264
- listeners$1.forEach(l => l());
1264
+ const listeners = new Set();
1265
+ function emit() {
1266
+ listeners.forEach(l => l());
1265
1267
  }
1266
- function subscribe$1(l) {
1267
- listeners$1.add(l);
1268
+ function subscribe(l) {
1269
+ listeners.add(l);
1268
1270
  return () => {
1269
- listeners$1.delete(l);
1271
+ listeners.delete(l);
1270
1272
  };
1271
1273
  }
1272
1274
  /** Opens the dialog — a no-op when no layout has mounted one. */
1273
1275
  function openHelp() {
1274
1276
  if (!open) {
1275
1277
  open = true;
1276
- emit$1();
1278
+ emit();
1277
1279
  }
1278
1280
  }
1279
1281
  function closeHelp() {
1280
1282
  pendingRef = null;
1281
1283
  if (open) {
1282
1284
  open = false;
1283
- emit$1();
1285
+ emit();
1284
1286
  }
1285
1287
  }
1286
1288
  /** Opens the dialog on one of the person's messages, by id or "H1004". */
1287
1289
  function openHelpOn(ref) {
1288
1290
  pendingRef = ref;
1289
1291
  open = true;
1290
- emit$1();
1292
+ emit();
1291
1293
  }
1292
1294
  /** The message the dialog was asked to open on, if it has not been left. */
1293
1295
  function pendingHelpRef() {
@@ -1306,22 +1308,22 @@ function registerHelpHost() {
1306
1308
  hosts += 1;
1307
1309
  if (pendingRef)
1308
1310
  open = true;
1309
- emit$1();
1311
+ emit();
1310
1312
  return () => {
1311
1313
  hosts -= 1;
1312
1314
  if (hosts <= 0) {
1313
1315
  hosts = 0;
1314
1316
  open = false;
1315
1317
  }
1316
- emit$1();
1318
+ emit();
1317
1319
  };
1318
1320
  }
1319
1321
  function useHelpOpen() {
1320
- return useSyncExternalStore(subscribe$1, () => open, () => false);
1322
+ return useSyncExternalStore(subscribe, () => open, () => false);
1321
1323
  }
1322
1324
  /** True while a dialog host is mounted, i.e. the ช่วยเหลือ entry works. */
1323
1325
  function useHelpAvailable() {
1324
- return useSyncExternalStore(subscribe$1, () => hosts > 0, () => false);
1326
+ return useSyncExternalStore(subscribe, () => hosts > 0, () => false);
1325
1327
  }
1326
1328
  /**
1327
1329
  * Every app names itself when it builds its app-switcher links
@@ -1345,17 +1347,17 @@ function declaredHelpApp() {
1345
1347
  const OWNER_CHIP = "เจ้าของ";
1346
1348
  /** How many role names the card spells out before counting the rest. */
1347
1349
  const CARD_ROLE_LIMIT = 2;
1348
- const isRecord$2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1350
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1349
1351
  /**
1350
1352
  * The answer, checked. Anything that is not the shape the card needs — an
1351
1353
  * older API, a proxy's error page, another organisation's answer — is null,
1352
1354
  * and the card shows no role line.
1353
1355
  */
1354
1356
  function parseMyRoles(payload, organizationId) {
1355
- if (!isRecord$2(payload))
1357
+ if (!isRecord(payload))
1356
1358
  return null;
1357
1359
  // Envelope { success, data } or the bare data.
1358
- const data = isRecord$2(payload.data) ? payload.data : payload;
1360
+ const data = isRecord(payload.data) ? payload.data : payload;
1359
1361
  if (!Array.isArray(data.roles))
1360
1362
  return null;
1361
1363
  if (typeof data.organization_id === "string" && data.organization_id !== organizationId) {
@@ -1364,7 +1366,7 @@ function parseMyRoles(payload, organizationId) {
1364
1366
  const roles = [];
1365
1367
  const seen = new Set();
1366
1368
  for (const r of data.roles) {
1367
- if (!isRecord$2(r))
1369
+ if (!isRecord(r))
1368
1370
  continue;
1369
1371
  const name = typeof r.name_th === "string" ? r.name_th.trim() : "";
1370
1372
  const key = typeof r.key === "string" ? r.key : "";
@@ -1585,242 +1587,6 @@ async function retryWithStoredOrganizations(config, status, send) {
1585
1587
  return undefined;
1586
1588
  }
1587
1589
 
1588
- /**
1589
- * Route and API-path patterns for tour steps.
1590
- *
1591
- * No runtime imports: the tests run this file in Node as it is.
1592
- */
1593
- const trimSlash = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p);
1594
- function splitPattern(pattern) {
1595
- const q = pattern.indexOf("?");
1596
- if (q < 0)
1597
- return { path: pattern, query: new URLSearchParams() };
1598
- return { path: pattern.slice(0, q), query: new URLSearchParams(pattern.slice(q + 1)) };
1599
- }
1600
- function paramName(segment) {
1601
- const bracket = /^\[([A-Za-z0-9_]+)\]$/.exec(segment);
1602
- if (bracket)
1603
- return bracket[1];
1604
- const colon = /^:([A-Za-z0-9_]+)$/.exec(segment);
1605
- return colon ? colon[1] : null;
1606
- }
1607
- function safeDecode(s) {
1608
- try {
1609
- return decodeURIComponent(s);
1610
- }
1611
- catch {
1612
- return s;
1613
- }
1614
- }
1615
- /**
1616
- * Matches a Next-style page pattern ("/[code]/employee/[id]", optionally
1617
- * "?tab=job") against a path and query. `[code]`, when given, must be the
1618
- * organisation code. Returns the params, or null.
1619
- */
1620
- function matchRoute(pattern, pathname, search, code) {
1621
- const { path, query } = splitPattern(pattern);
1622
- const want = trimSlash(path).split("/");
1623
- const have = trimSlash(pathname || "/").split("/");
1624
- if (want.length !== have.length)
1625
- return null;
1626
- const params = {};
1627
- for (let i = 0; i < want.length; i++) {
1628
- const name = paramName(want[i]);
1629
- if (name) {
1630
- if (!have[i])
1631
- return null;
1632
- params[name] = safeDecode(have[i]);
1633
- continue;
1634
- }
1635
- if (want[i] !== have[i])
1636
- return null;
1637
- }
1638
- if (code !== undefined && params.code !== undefined && params.code !== code) {
1639
- return null;
1640
- }
1641
- if ([...query.keys()].length > 0) {
1642
- const s = search instanceof URLSearchParams ? search : new URLSearchParams(search ?? "");
1643
- for (const [k, v] of query.entries()) {
1644
- if (s.get(k) !== v)
1645
- return null;
1646
- }
1647
- }
1648
- return params;
1649
- }
1650
- /** Fills a page pattern's params ("/[code]/x/[id]" → "/O1/x/42"); null if one is missing. */
1651
- function fillRoute(pattern, params) {
1652
- const { path, query } = splitPattern(pattern);
1653
- const out = [];
1654
- for (const seg of path.split("/")) {
1655
- const name = paramName(seg);
1656
- if (!name) {
1657
- out.push(seg);
1658
- continue;
1659
- }
1660
- const v = params[name];
1661
- if (!v)
1662
- return null;
1663
- out.push(encodeURIComponent(v));
1664
- }
1665
- const qs = query.toString();
1666
- return out.join("/") + (qs ? `?${qs}` : "");
1667
- }
1668
- /**
1669
- * The path of a request, without origin, base URL query or hash:
1670
- * ("/shifts/4", "https://hr-api/api/v1") → "/api/v1/shifts/4".
1671
- */
1672
- function requestPath(url, baseURL) {
1673
- const raw = url ?? "";
1674
- let full = raw;
1675
- if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) && baseURL) {
1676
- full = baseURL.replace(/\/+$/, "") + "/" + raw.replace(/^\/+/, "");
1677
- }
1678
- try {
1679
- return trimSlash(new URL(full, "http://local.invalid").pathname);
1680
- }
1681
- catch {
1682
- return trimSlash(full.split(/[?#]/)[0] || "/");
1683
- }
1684
- }
1685
- /**
1686
- * Whether a request path matches a step's API path: the pattern's segments
1687
- * must be the END of the path ("/shifts/[id]" matches "/api/v1/shifts/42");
1688
- * `[x]`/`:x` is one segment, `*` any number (including none). A RegExp is
1689
- * tested against the whole path.
1690
- */
1691
- function matchApiPath(pattern, path) {
1692
- if (pattern instanceof RegExp)
1693
- return pattern.test(path);
1694
- const want = trimSlash(pattern).split("/").filter(Boolean);
1695
- const have = trimSlash(path).split("/").filter(Boolean);
1696
- // Try every suffix of the path as the place the pattern starts.
1697
- for (let start = 0; start <= have.length; start++) {
1698
- if (matchSegments(want, 0, have, start))
1699
- return true;
1700
- }
1701
- return false;
1702
- }
1703
- function matchSegments(want, wi, have, hi) {
1704
- if (wi === want.length)
1705
- return hi === have.length;
1706
- const seg = want[wi];
1707
- if (seg === "*") {
1708
- for (let k = hi; k <= have.length; k++) {
1709
- if (matchSegments(want, wi + 1, have, k))
1710
- return true;
1711
- }
1712
- return false;
1713
- }
1714
- if (hi >= have.length)
1715
- return false;
1716
- if (paramName(seg) || seg === have[hi])
1717
- return matchSegments(want, wi + 1, have, hi + 1);
1718
- return false;
1719
- }
1720
- /** "2xx" or an exact status. */
1721
- function matchStatus(want, status) {
1722
- if (want === undefined || want === "2xx")
1723
- return status >= 200 && status < 300;
1724
- return status === want;
1725
- }
1726
-
1727
- /**
1728
- * The tour's event bus and anchor helper — the parts an app calls.
1729
- *
1730
- * - `guideAnchor(key, id?)` → `{ "data-guide": key, "data-guide-id"?: id }`
1731
- * - `emitGuideEvent(name, detail?)` → window CustomEvent `erp:guide:<name>`
1732
- * - `reportApiEvent(responseOrError)` → window CustomEvent `erp:api`, which
1733
- * the shell's own axios instance already sends for every answer. An app
1734
- * with a second axios instance calls it from that instance's interceptor.
1735
- *
1736
- * Only method, path, status, the saved record's id and (on a refusal) the
1737
- * server's message go on the bus — never a request or response body.
1738
- *
1739
- * No runtime imports beyond sibling pure modules.
1740
- */
1741
- const GUIDE_ATTRIBUTE = "data-guide";
1742
- const GUIDE_ID_ATTRIBUTE = "data-guide-id";
1743
- const GUIDE_LAYER_ATTRIBUTE = "data-erp-guide-layer";
1744
- const API_EVENT = "erp:api";
1745
- const GUIDE_EVENT_PREFIX = "erp:guide:";
1746
- /** Spread onto the element a tour step points at. */
1747
- function guideAnchor(key, id) {
1748
- return id === undefined || id === null || id === ""
1749
- ? { [GUIDE_ATTRIBUTE]: key }
1750
- : { [GUIDE_ATTRIBUTE]: key, [GUIDE_ID_ATTRIBUTE]: String(id) };
1751
- }
1752
- /** Announces an app event a step can wait for (`advanceOn: { event: name }`). */
1753
- function emitGuideEvent(name, detail) {
1754
- if (typeof window === "undefined" || !name)
1755
- return;
1756
- const clean = {};
1757
- for (const [k, v] of Object.entries(detail ?? {})) {
1758
- if (typeof v === "string" || typeof v === "number")
1759
- clean[k] = String(v);
1760
- }
1761
- try {
1762
- window.dispatchEvent(new CustomEvent(GUIDE_EVENT_PREFIX + name, { detail: clean }));
1763
- }
1764
- catch {
1765
- /* never let the tour break the app */
1766
- }
1767
- }
1768
- const isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1769
- function idOf(data) {
1770
- const pick = (v) => typeof v === "string" && v ? v : typeof v === "number" ? String(v) : undefined;
1771
- if (!isRecord$1(data))
1772
- return undefined;
1773
- return pick(data.id) ?? (isRecord$1(data.data) ? pick(data.data.id) : undefined);
1774
- }
1775
- function messageOf(data) {
1776
- if (!isRecord$1(data))
1777
- return undefined;
1778
- const m = data.message ?? (isRecord$1(data.error) ? data.error.message : data.error);
1779
- return typeof m === "string" && m.trim() ? m.trim().slice(0, 200) : undefined;
1780
- }
1781
- /** The bus detail for an axios answer or error; null when it is neither. */
1782
- function apiEventDetail(responseOrError) {
1783
- if (!isRecord$1(responseOrError))
1784
- return null;
1785
- const err = responseOrError;
1786
- // An AxiosError has .response (or none: network failure) and .config.
1787
- const isError = "isAxiosError" in responseOrError || ("response" in responseOrError && !("data" in responseOrError));
1788
- const res = isError ? err.response : responseOrError;
1789
- const config = (res?.config ?? err.config);
1790
- if (!config)
1791
- return null;
1792
- const status = typeof res?.status === "number" ? res.status : 0;
1793
- const detail = {
1794
- method: (config.method ?? "get").toUpperCase(),
1795
- path: requestPath(config.url, config.baseURL),
1796
- status,
1797
- };
1798
- if (status >= 200 && status < 300) {
1799
- const id = idOf(res?.data);
1800
- if (id)
1801
- detail.id = id;
1802
- }
1803
- else {
1804
- const msg = messageOf(res?.data);
1805
- if (msg)
1806
- detail.message = msg;
1807
- }
1808
- return detail;
1809
- }
1810
- /** Puts an axios answer (or error) on the bus. Safe to call with anything. */
1811
- function reportApiEvent(responseOrError) {
1812
- if (typeof window === "undefined")
1813
- return;
1814
- try {
1815
- const detail = apiEventDetail(responseOrError);
1816
- if (detail)
1817
- window.dispatchEvent(new CustomEvent(API_EVENT, { detail }));
1818
- }
1819
- catch {
1820
- /* never let the tour break the app */
1821
- }
1822
- }
1823
-
1824
1590
  const isBrowser = () => typeof window !== "undefined";
1825
1591
  const isAuthEndpoint = (url) => !!url && url.includes("/api/auth/");
1826
1592
  const isAuthPage = () => isBrowser() && window.location.pathname.startsWith("/auth/");
@@ -1956,7 +1722,7 @@ function platformApiBase(app) {
1956
1722
  * This package's version, attached to help messages so the back office can
1957
1723
  * tell which shell a report came from. Keep in step with package.json.
1958
1724
  */
1959
- const SHELL_VERSION = "0.1.67";
1725
+ const SHELL_VERSION = "0.1.69";
1960
1726
 
1961
1727
  const HELP_APP_LABEL = {
1962
1728
  platform: "แพลตฟอร์ม",
@@ -2783,37 +2549,6 @@ const WORKSPACE_LIGHT_HEADER_VARS = {
2783
2549
  "--header-title-py": "0px",
2784
2550
  };
2785
2551
 
2786
- let entry = null;
2787
- let openPanelImpl = null;
2788
- const listeners = new Set();
2789
- function emit() {
2790
- listeners.forEach(l => l());
2791
- }
2792
- function subscribe(l) {
2793
- listeners.add(l);
2794
- return () => {
2795
- listeners.delete(l);
2796
- };
2797
- }
2798
- /** Called by the host: the entry to show (null: none), and how to open the panel. */
2799
- function publishGuideEntry(next, openPanel) {
2800
- const same = (next === null && entry === null) ||
2801
- (next !== null && entry !== null && next.done === entry.done && next.total === entry.total);
2802
- openPanelImpl = openPanel;
2803
- if (!same) {
2804
- entry = next;
2805
- emit();
2806
- }
2807
- }
2808
- /** Opens the tour's quest panel, when this user has a tour here. */
2809
- function openGuidePanel() {
2810
- openPanelImpl?.();
2811
- }
2812
- /** The "?" menu's entry, or null when there is no tour for this user. */
2813
- function useGuideEntry() {
2814
- return useSyncExternalStore(subscribe, () => entry, () => null);
2815
- }
2816
-
2817
2552
  const BUTTON_CLASS = "grid size-[34px] shrink-0 place-items-center rounded-lg text-[var(--header-fg-muted,#ffffffc7)] transition-colors hover:bg-[var(--header-hover,#ffffff1f)] hover:text-[var(--header-fg,#ffffff)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--header-fg-muted,#ffffffc7)]";
2818
2553
  /**
2819
2554
  * The ช่วยเหลือ button in the top bar. Drawn in the header's ink (the
@@ -3784,2446 +3519,84 @@ function resolveStaleOrganization({ code, organizations, organizationsStatus, or
3784
3519
  return { action: "forget" };
3785
3520
  }
3786
3521
 
3787
- /* ------------------------------------------------------------------ */
3788
- /* Copy */
3789
- /* ------------------------------------------------------------------ */
3790
- const COPY = {
3791
- fieldFix: "แก้ในช่องที่ไฮไลต์ แล้วกด ถัดไป",
3792
- saveFailed: "บันทึกไม่สำเร็จ",
3793
- blank: "ยังไม่ได้พิมพ์",
3794
- exitToast: "ออกจากไกด์แล้ว",
3795
- replayDone: "ทบทวนภารกิจเสร็จแล้ว",
3796
- replayEnded: "จบการทบทวนแล้ว",
3797
- hiddenToast: "ซ่อนแล้ว",
3798
- aborted: "ไกด์ไปต่อไม่ได้ ลองอีกครั้งภายหลัง",
3799
- bridgeTitle: "กดปุ่มเมนู",
3800
- bridgeWhy: (app) => `เมนูทั้งหมดของ ${app} อยู่ในนี้`,
3801
- };
3802
- /* ------------------------------------------------------------------ */
3803
- /* Helpers */
3804
- /* ------------------------------------------------------------------ */
3805
- const BRIDGE_TARGET = "shell.menu-toggle";
3806
- function initialGuideState(audience, progress) {
3807
- return {
3808
- audience,
3809
- progress,
3810
- screen: { name: "idle" },
3811
- panelOpen: false,
3812
- justDone: null,
3813
- chipPulse: 0,
3814
- nudge: 0,
3815
- gateDismissed: false,
3816
- replayPage: null,
3817
- };
3818
- }
3819
- function findMission(suite, key) {
3820
- return key ? suite.missions.find(m => m.key === key) : undefined;
3821
- }
3822
- function guideContext(env, data, params = {}) {
3823
- return {
3824
- code: env.code,
3825
- pathname: env.pathname,
3826
- search: env.search,
3827
- params: { code: env.code, ...params },
3828
- data,
3829
- facts: env.facts,
3830
- can: env.can,
3831
- visible: (anchor) => env.isVisible(anchor),
3832
- };
3833
- }
3834
- function resolveText(t, ctx) {
3835
- if (t === undefined)
3836
- return "";
3837
- try {
3838
- return typeof t === "function" ? t(ctx) : t;
3839
- }
3840
- catch {
3841
- return "";
3842
- }
3843
- }
3844
- /** Runs an app predicate; a throw counts as `fallback`. */
3845
- function safe(fn, fallback) {
3846
- try {
3847
- return fn();
3848
- }
3849
- catch {
3850
- return fallback;
3851
- }
3852
- }
3853
- function triggersOf(step) {
3854
- if (!step.advanceOn)
3855
- return [];
3856
- return Array.isArray(step.advanceOn) ? step.advanceOn : [step.advanceOn];
3857
- }
3858
- function stepKind(step) {
3859
- return step.kind ?? "click";
3860
- }
3861
- /** The last checkpoint at or before `index` (a mission's first step always is one). */
3862
- function checkpointAtOrBefore(steps, index) {
3863
- for (let i = Math.min(index, steps.length - 1); i > 0; i--) {
3864
- if (steps[i].checkpoint)
3865
- return i;
3866
- }
3867
- return 0;
3868
- }
3869
- function targetIdOf(step, ctx) {
3870
- if (typeof step.targetId === "function")
3871
- return safe(() => step.targetId(ctx), undefined);
3872
- return step.targetId;
3873
- }
3874
- /**
3875
- * A commit step with nothing to save: its button is not on the page, and what
3876
- * is saved is (GuideStep.nothingToSave).
3877
- */
3878
- function nothingToSaveHolds(step, env, ctx) {
3879
- const n = step.nothingToSave;
3880
- if (!n || !step.target)
3881
- return false;
3882
- return !env.isVisible(step.target, targetIdOf(step, ctx)) && env.isVisible(n.target);
3883
- }
3522
+ const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
3523
+ const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
3524
+ const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
3884
3525
  /**
3885
- * The step as it is shown: a commit step with nothing to save is a read step
3886
- * on what is saved, with its own title (ถัดไป moves on).
3526
+ * Shown when the API refuses every request because the signed-in account has
3527
+ * no employee record in this organisation.
3528
+ *
3529
+ * A gate rather than a banner. Leave, attendance, approvals and payslips all
3530
+ * identify a person by that record, so once the server started enforcing it
3531
+ * every call fails — and without something that says so, the app becomes a
3532
+ * screen of error toasts with no explanation and no way forward.
3887
3533
  */
3888
- function shownStep(step, nothingToSave) {
3889
- const n = step.nothingToSave;
3890
- if (!nothingToSave || !n)
3891
- return step;
3892
- return {
3893
- key: step.key,
3894
- kind: "view",
3895
- target: n.target,
3896
- title: n.title,
3897
- why: n.why,
3898
- allow: n.allow,
3899
- route: step.route,
3900
- resumeUrl: step.resumeUrl,
3901
- checkpoint: step.checkpoint,
3902
- timeoutMs: step.timeoutMs,
3903
- abort: step.abort,
3904
- };
3905
- }
3906
- /** Whether the step's target (or the bridge's) is on screen. */
3907
- function stepTargetVisible(step, env, ctx, bridge) {
3908
- if (bridge)
3909
- return env.isVisible(BRIDGE_TARGET);
3910
- if (!step.target)
3911
- return true;
3912
- return env.isVisible(step.target, targetIdOf(step, ctx));
3913
- }
3914
- /** The anchor the spotlight is on for the current step. */
3915
- function spotlightTarget(step, ctx, bridge) {
3916
- if (bridge)
3917
- return { anchor: BRIDGE_TARGET };
3918
- if (!step.target)
3534
+ function EmployeeRequiredGate({ platformBaseUrl, }) {
3535
+ const [blocked, setBlocked] = useState(false);
3536
+ const params = useParams();
3537
+ const code = params?.code ?? "";
3538
+ useEffect(() => {
3539
+ const onBlocked = () => setBlocked(true);
3540
+ const onOk = () => setBlocked(false);
3541
+ window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3542
+ window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3543
+ return () => {
3544
+ window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
3545
+ window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
3546
+ };
3547
+ }, []);
3548
+ if (!blocked)
3919
3549
  return null;
3920
- return { anchor: step.target, id: targetIdOf(step, ctx) };
3921
- }
3922
- function needsBridge(step, env, ctx) {
3923
- return (!!step.target &&
3924
- step.target.startsWith("nav.") &&
3925
- !env.sidebarOpen &&
3926
- !env.isVisible(step.target, targetIdOf(step, ctx)));
3927
- }
3928
- /**
3929
- * The page a step happens on: its own `route`, or else where the steps before
3930
- * it left the user (an earlier step's route trigger or route). Undefined when
3931
- * nothing says (a mission's first steps, which work from any page).
3932
- */
3933
- function stepHomeRoute(steps, index) {
3934
- for (let j = Math.min(index, steps.length - 1); j >= 0; j--) {
3935
- const s = steps[j];
3936
- if (j < index) {
3937
- // What this earlier step moved the user to comes after where it happened.
3938
- const t = triggersOf(s).find((x) => "route" in x);
3939
- if (t)
3940
- return t.route;
3941
- }
3942
- if (s.route)
3943
- return s.route;
3944
- }
3945
- return undefined;
3946
- }
3947
- /**
3948
- * The page a step is shown on, or the "ทำต่อ" card when the user is elsewhere:
3949
- * its route; for a checkpoint without one, the page the steps before it lead
3950
- * to (so going back to it from another page cannot loop).
3951
- */
3952
- function placeRoute(steps, index) {
3953
- const step = steps[index];
3954
- if (step.route)
3955
- return step.route;
3956
- return step.checkpoint ? stepHomeRoute(steps, index) : undefined;
3957
- }
3958
- /** The user is not on the page the step happens on. */
3959
- function offRoute(steps, index, env) {
3960
- const home = stepHomeRoute(steps, index);
3961
- return !!home && !matchRoute(home, env.pathname, env.search, env.code);
3962
- }
3963
- /** What puts the page back when a replay ends at this step (see GuideStep.abort). */
3964
- function abortActionsFor(mission, index) {
3965
- const step = mission.steps[index];
3966
- const own = step?.abort ?? mission.abort;
3967
- if (own)
3968
- return Array.isArray(own) ? own : [own];
3969
- // Default: Escape to the dialog the tour opened; nothing on a stable page.
3970
- if (!step || index === 0 || step.checkpoint)
3971
- return [];
3972
- return [{ escape: true }];
3973
- }
3974
- /** Every anchor the mission's abort actions press. */
3975
- function abortAnchorsOf(mission) {
3976
- const out = new Set();
3977
- const add = (a) => {
3978
- for (const x of a ? (Array.isArray(a) ? a : [a]) : [])
3979
- if ("click" in x)
3980
- out.add(x.click);
3981
- };
3982
- add(mission.abort);
3983
- for (const st of mission.steps)
3984
- add(st.abort);
3985
- return Array.from(out);
3550
+ const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
3551
+ const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
3552
+ return (jsx("div", { className: "fixed inset-0 z-[100] flex items-center justify-center bg-background/95 p-6 backdrop-blur-sm", children: jsxs("div", { className: "w-full max-w-md space-y-5 text-center", children: [jsx(ContactRound, { className: "mx-auto h-12 w-12 text-muted-foreground" }), jsxs("div", { className: "space-y-2", children: [jsx("h1", { className: "text-lg font-semibold tracking-tight", children: "\u0E1A\u0E31\u0E0D\u0E0A\u0E35\u0E19\u0E35\u0E49\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E1C\u0E39\u0E01\u0E01\u0E31\u0E1A\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E25\u0E32 \u0E25\u0E07\u0E40\u0E27\u0E25\u0E32 \u0E40\u0E1A\u0E34\u0E01\u0E40\u0E07\u0E34\u0E19 \u0E41\u0E25\u0E30\u0E01\u0E32\u0E23\u0E2D\u0E19\u0E38\u0E21\u0E31\u0E15\u0E34 \u0E23\u0E30\u0E1A\u0E38\u0E15\u0E31\u0E27\u0E04\u0E19\u0E08\u0E32\u0E01\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19 \u0E08\u0E36\u0E07\u0E22\u0E31\u0E07\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19\u0E43\u0E19\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49" })] }), jsxs("div", { className: "flex flex-wrap justify-center gap-2", children: [jsx(Button, { onClick: () => window.location.reload(), children: "\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48" }), jsx(Button, { variant: "outline", asChild: true, children: jsxs("a", { href: createHref, children: [jsx(UserPlus, { className: "mr-1 h-4 w-4" }), "\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19"] }) })] }), jsx("p", { className: "text-xs text-muted-foreground", children: "\u0E16\u0E49\u0E32\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E41\u0E01\u0E49\u0E44\u0E02 \u0E43\u0E2B\u0E49\u0E41\u0E08\u0E49\u0E07\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" })] }) }));
3986
3553
  }
3554
+
3987
3555
  /**
3988
- * What the replay may do to put the page back: not press what the user had
3989
- * open before it started, not Escape out of a dialog that was already open,
3990
- * and no app event while anything of theirs was open.
3556
+ * Talking to platform-api about tour progress (API.md): the GET that says
3557
+ * who sees what, and the PUT that saves, with its rev check. This is the
3558
+ * shell's progress adapter (GuideHost); the rules live in progress-sync.ts.
3991
3559
  */
3992
- function abortActionsLeft(actions, before) {
3993
- if (!before)
3994
- return actions;
3995
- const busy = before.anchors.length > 0 || before.dialog;
3996
- return actions.filter(a => "click" in a ? !before.anchors.includes(a.click) : "escape" in a ? !before.dialog : !busy);
3997
- }
3998
- function routeParamsFor(step, env) {
3999
- if (!step.route)
4000
- return {};
4001
- return matchRoute(step.route, env.pathname, env.search, env.code) ?? {};
4002
- }
4003
- /** A state trigger (route, visible) that holds now; the capture event for it. */
4004
- function stateTriggerHolds(step, env) {
4005
- for (const t of triggersOf(step)) {
4006
- if ("route" in t) {
4007
- const params = matchRoute(t.route, env.pathname, env.search, env.code);
4008
- if (params)
4009
- return { route: { pathname: env.pathname, params } };
4010
- }
4011
- else if ("visible" in t) {
4012
- if (env.isVisible(t.visible))
4013
- return {};
4014
- }
4015
- }
4016
- return null;
4017
- }
4018
- /** Any trigger that holds on a sync (route, visible, and — once armed — hidden). */
4019
- function syncTriggerHolds(step, env, armed) {
4020
- const held = stateTriggerHolds(step, env);
4021
- if (held)
4022
- return held;
4023
- if (!armed)
4024
- return null;
4025
- for (const t of triggersOf(step)) {
4026
- if ("hidden" in t && !env.isVisible(t.hidden))
4027
- return {};
4028
- }
4029
- return null;
4030
- }
4031
- /** Whether any of the step's `hidden` anchors is on screen now. */
4032
- function hiddenAnchorShown(step, env) {
4033
- return triggersOf(step).some(t => "hidden" in t && env.isVisible(t.hidden));
4034
- }
4035
- function missionCount(suite) {
4036
- return suite.missions.length;
4037
- }
4038
- function missionSettled(m, entry, ctx) {
4039
- if (entry?.status === "done")
4040
- return true;
4041
- if (m.optional && entry?.status === "skipped")
4042
- return true;
4043
- return safe(() => m.alreadyDone?.(ctx) === true, false);
4044
- }
4045
- function settledCount(suite, progress, ctx) {
4046
- return suite.missions.filter(m => missionSettled(m, progress.missions[m.key], ctx)).length;
4047
- }
4048
- function gateState(suite, ctx) {
4049
- if (!suite.gate)
4050
- return true;
4051
- return safe(() => suite.gate.ready(ctx), undefined);
3560
+ function base(app) {
3561
+ // LIFF's progress is on peoplx-api, never here; the help channel's default.
3562
+ return platformApiBase(app === "liff" ? "other" : app);
4052
3563
  }
4053
- function missionViews(suite, progress, ctx) {
4054
- const gate = gateState(suite, ctx);
4055
- const settled = (key) => {
4056
- const m = findMission(suite, key);
4057
- return !!m && missionSettled(m, progress.missions[key], ctx);
3564
+ /** platform-api's `…/organizations/:id/guides/me` as a progress adapter. */
3565
+ function platformGuideProgress(organizationId) {
3566
+ const org = encodeURIComponent(organizationId);
3567
+ return {
3568
+ async fetchProgress({ app, signal }) {
3569
+ const res = await instance.get(`${base(app)}/organizations/${org}/guides/me`, {
3570
+ params: { app },
3571
+ signal,
3572
+ erpOrganizationId: organizationId,
3573
+ });
3574
+ return res.data;
3575
+ },
3576
+ async saveProgress({ app, guideKey, body }) {
3577
+ const res = await instance.put(`${base(app)}/organizations/${org}/guides/me/${encodeURIComponent(guideKey)}`, body, {
3578
+ validateStatus: s => (s >= 200 && s < 300) || s === 409,
3579
+ erpOrganizationId: organizationId,
3580
+ });
3581
+ return { status: res.status, data: res.data };
3582
+ },
4058
3583
  };
4059
- let nextMarked = false;
4060
- return suite.missions.map(mission => {
4061
- const entry = progress.missions[mission.key];
4062
- let view;
4063
- if (entry?.status === "done")
4064
- view = "done";
4065
- else if (safe(() => mission.alreadyDone?.(ctx) === true, false))
4066
- view = "already";
4067
- else if (entry?.status === "skipped")
4068
- view = "skipped";
4069
- else if (entry?.status === "active")
4070
- view = "active";
4071
- else if (gate === false)
4072
- view = "waiting";
4073
- else if ((mission.after ?? []).some(k => !settled(k)))
4074
- view = "locked";
4075
- else
4076
- view = "todo";
4077
- if (!nextMarked && (view === "todo" || view === "active" || view === "skipped")) {
4078
- nextMarked = true;
4079
- if (view === "todo")
4080
- view = "next";
4081
- }
4082
- return { mission, view, entry };
4083
- });
4084
- }
4085
- /** The mission the celebration offers next: the first one not settled and not locked. */
4086
- function nextMissionKey(suite, progress, ctx) {
4087
- for (const v of missionViews(suite, progress, ctx)) {
4088
- if (v.view === "next" || v.view === "todo" || v.view === "active" || v.view === "skipped") {
4089
- return v.mission.key;
4090
- }
4091
- }
4092
- return null;
4093
- }
4094
- /** Whether the welcome should open by itself. */
4095
- function welcomeDue(state, suite) {
4096
- return (state.audience === "forced" &&
4097
- state.progress.welcome === "not_seen" &&
4098
- state.progress.status === "in_progress" &&
4099
- !state.progress.mission_key &&
4100
- state.screen.name === "idle" &&
4101
- suite.missions.length > 0);
4102
- }
4103
- /** Whether the floating "ภารกิจ n/N" chip shows. */
4104
- function chipVisible(state, suite, ctx) {
4105
- return (state.audience !== "none" &&
4106
- state.progress.welcome !== "not_seen" &&
4107
- state.progress.status !== "completed" &&
4108
- !state.progress.chip_hidden &&
4109
- state.screen.name === "idle" &&
4110
- !state.panelOpen &&
4111
- settledCount(suite, state.progress, ctx) < missionCount(suite));
4112
- }
4113
- function withProgress(d, patch) {
4114
- d.state = { ...d.state, progress: { ...d.state.progress, ...patch } };
4115
- }
4116
- function setMission(d, key, entry) {
4117
- withProgress(d, { missions: { ...d.state.progress.missions, [key]: entry } });
4118
- }
4119
- function setScreen(d, screen) {
4120
- d.state = { ...d.state, screen };
4121
- }
4122
- function save(d, immediate = false) {
4123
- const existing = d.effects.find(e => e.type === "save");
4124
- if (existing)
4125
- existing.immediate = existing.immediate || immediate;
4126
- else
4127
- d.effects.push({ type: "save", immediate });
4128
- }
4129
- function announceStep(d, suite, env) {
4130
- const s = d.state.screen;
4131
- if (s.name !== "step")
4132
- return;
4133
- const mission = findMission(suite, s.mission);
4134
- if (!mission)
4135
- return;
4136
- const step = shownStep(mission.steps[s.index], s.nothingToSave);
4137
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4138
- const title = s.bridge ? COPY.bridgeTitle : plainTitle(resolveText(step.title, ctx));
4139
- const why = s.bridge ? COPY.bridgeWhy(suite.appName) : plainTitle(resolveText(step.why, ctx));
4140
- d.effects.push({
4141
- type: "announce",
4142
- text: `ขั้นที่ ${s.index + 1} จาก ${mission.steps.length}. ${title}${why ? `. ${why}` : ""}`,
4143
- });
4144
3584
  }
4145
- /** "กด [บันทึก]" → "กด บันทึก" (for screen readers). */
4146
- function plainTitle(t) {
4147
- return t.replace(/\[([^\]]+)\]/g, "$1");
3585
+
3586
+ function GuideHost(props) {
3587
+ // The boundary covers the adapters too (useSidebar throws without its provider).
3588
+ return (jsx(GuideErrorBoundary, { children: jsx(Suspense, { fallback: null, children: jsx(GuideHostInner, { ...props }) }) }));
4148
3589
  }
4149
- /**
4150
- * Enter step `index` of the mission (or the first one after it that is not
4151
- * skipped, forbidden or already passed). Past the end, the mission is over.
4152
- */
4153
- function enterStep(d, suite, env, mission, index, opts) {
4154
- const steps = mission.steps;
4155
- let i = Math.max(0, index);
4156
- let firstPass = true;
4157
- while (i < steps.length) {
4158
- const step = steps[i];
4159
- const params = routeParamsFor(step, env);
4160
- const ctx = guideContext(env, d.state.progress.context, params);
4161
- if (step.requires && !safe(() => env.can(step.requires), true)) {
4162
- // A replay writes nothing, not even what went wrong.
4163
- if (!opts.replay)
4164
- withProgress(d, { last_error: `forbidden:${step.requires}`.slice(0, 128) });
4165
- i++;
4166
- continue;
4167
- }
4168
- if (step.skipIf && safe(() => step.skipIf(ctx), false)) {
4169
- i++;
4170
- continue;
4171
- }
4172
- const autoPass = step.autoPass !== false && !(firstPass && opts.noAutoPass);
4173
- firstPass = false;
4174
- if (autoPass && stepKind(step) !== "input" && stepKind(step) !== "view") {
4175
- const held = stateTriggerHolds(step, env);
4176
- if (held) {
4177
- captureInto(d, step, held, ctx);
4178
- i++;
4179
- continue;
4180
- }
4181
- }
4182
- break;
4183
- }
4184
- if (i >= steps.length) {
4185
- finishMission(d, suite, env, mission, opts.replay);
4186
- return;
4187
- }
4188
- const step = steps[i];
4189
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4190
- const where = placeRoute(steps, i);
4191
- const away = !!where && !matchRoute(where, env.pathname, env.search, env.code);
4192
- const bridge = !away && needsBridge(step, env, ctx);
4193
- setScreen(d, {
4194
- name: "step",
4195
- mission: mission.key,
4196
- index: i,
4197
- replay: opts.replay,
4198
- bridge,
4199
- phase: away ? "away" : "waiting",
4200
- error: opts.error ?? null,
4201
- confirmExit: false,
4202
- misses: 0,
4203
- armed: hiddenAnchorShown(step, env),
4204
- nothingToSave: !away && !bridge && nothingToSaveHolds(step, env, ctx),
4205
- });
4206
- if (!opts.replay) {
4207
- const cp = checkpointAtOrBefore(steps, i);
4208
- setMission(d, mission.key, { status: "active", step_key: step.key });
4209
- withProgress(d, {
4210
- mission_key: mission.key,
4211
- step_key: step.key,
4212
- step_index: i,
4213
- checkpoint_key: steps[cp].key,
4214
- });
4215
- save(d);
4216
- }
4217
- if (!away) {
4218
- // The target may already be there.
4219
- markReadyIfVisible(d, suite, env);
4220
- }
3590
+ let fallbackClient = null;
3591
+ function useShellQueryClient() {
3592
+ const provided = useContext(QueryClientContext);
3593
+ if (provided)
3594
+ return provided;
3595
+ fallbackClient ?? (fallbackClient = new QueryClient());
3596
+ return fallbackClient;
4221
3597
  }
4222
- /**
4223
- * The save button came (a change) or went (nothing left to save): show the
4224
- * commit step's other form. A ready step whose new target is not there is
4225
- * left to the target-lost path (back to the checkpoint).
4226
- */
4227
- function setNothingToSave(d, suite, env, on) {
4228
- const s = d.state.screen;
4229
- if (s.name !== "step" || s.nothingToSave === on)
4230
- return;
4231
- setScreen(d, { ...s, nothingToSave: on, error: null });
4232
- if (s.phase !== "ready") {
4233
- markReadyIfVisible(d, suite, env);
4234
- return;
4235
- }
4236
- const mission = findMission(suite, s.mission);
4237
- if (!mission)
4238
- return;
4239
- const step = shownStep(mission.steps[s.index], on);
4240
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4241
- if (stepTargetVisible(step, env, ctx, s.bridge))
4242
- announceStep(d, suite, env);
4243
- }
4244
- function markReadyIfVisible(d, suite, env) {
4245
- const s = d.state.screen;
4246
- if (s.name !== "step" || s.phase !== "waiting")
4247
- return;
4248
- const mission = findMission(suite, s.mission);
4249
- if (!mission)
4250
- return;
4251
- const step = shownStep(mission.steps[s.index], s.nothingToSave);
4252
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4253
- if (stepTargetVisible(step, env, ctx, s.bridge)) {
4254
- setScreen(d, { ...s, phase: "ready" });
4255
- announceStep(d, suite, env);
4256
- if (s.error)
4257
- d.effects.push({ type: "announce", text: s.error.title });
4258
- }
4259
- }
4260
- /** Where to send the user to resume at a step: its resumeUrl, or its page filled in. */
4261
- function resumeHref(mission, index, d, env) {
4262
- const step = mission.steps[index];
4263
- const ctx = guideContext(env, d.state.progress.context);
4264
- const where = placeRoute(mission.steps, index);
4265
- return (safe(() => step.resumeUrl?.(ctx), undefined) ??
4266
- (where ? fillRoute(where, { ...d.state.progress.context, code: env.code }) : null));
4267
- }
4268
- /**
4269
- * The user left the page the step happens on (a link, the browser's back):
4270
- * back to the last checkpoint. On another page that is the "ทำต่อ" card;
4271
- * `navigate` (ลองอีกครั้ง) goes there at once.
4272
- */
4273
- function recoverOffRoute(d, suite, env, navigate) {
4274
- const s = d.state.screen;
4275
- if (s.name !== "step")
4276
- return;
4277
- const mission = findMission(suite, s.mission);
4278
- if (!mission)
4279
- return;
4280
- const cp = checkpointAtOrBefore(mission.steps, s.index);
4281
- enterStep(d, suite, env, mission, cp, { replay: s.replay });
4282
- const now = d.state.screen;
4283
- if (navigate && now.name === "step" && now.phase === "away") {
4284
- const href = resumeHref(mission, now.index, d, env);
4285
- if (href)
4286
- d.effects.push({ type: "navigate", href });
4287
- }
4288
- }
4289
- function captureInto(d, step, e, ctx) {
4290
- if (!step.capture)
4291
- return;
4292
- const got = safe(() => step.capture(e, ctx), undefined);
4293
- if (!got)
4294
- return;
4295
- const clean = {};
4296
- for (const [k, v] of Object.entries(got)) {
4297
- if (typeof v === "string" && v)
4298
- clean[k] = v;
4299
- }
4300
- if (Object.keys(clean).length) {
4301
- withProgress(d, { context: { ...d.state.progress.context, ...clean } });
4302
- }
4303
- }
4304
- function advance(d, suite, env, capture) {
4305
- const s = d.state.screen;
4306
- if (s.name !== "step")
4307
- return;
4308
- const mission = findMission(suite, s.mission);
4309
- if (!mission)
4310
- return;
4311
- const step = mission.steps[s.index];
4312
- if (capture) {
4313
- captureInto(d, step, capture, guideContext(env, d.state.progress.context, routeParamsFor(step, env)));
4314
- }
4315
- enterStep(d, suite, env, mission, s.index + 1, { replay: s.replay });
4316
- }
4317
- function finishMission(d, suite, env, mission, replay) {
4318
- if (replay) {
4319
- setScreen(d, { name: "idle" });
4320
- d.effects.push({ type: "toast", text: COPY.replayDone });
4321
- return;
4322
- }
4323
- setMission(d, mission.key, { status: "done", step_key: null, skipped_step: null });
4324
- withProgress(d, {
4325
- mission_key: null,
4326
- step_key: null,
4327
- step_index: 0,
4328
- checkpoint_key: null,
4329
- context: {},
4330
- last_error: null,
4331
- });
4332
- const ctx = guideContext(env, {});
4333
- const all = settledCount(suite, d.state.progress, ctx) >= missionCount(suite);
4334
- if (all)
4335
- withProgress(d, { status: "completed" });
4336
- setScreen(d, all ? { name: "complete" } : { name: "celebrate", mission: mission.key });
4337
- d.state = { ...d.state, justDone: mission.key };
4338
- save(d, true);
4339
- const n = settledCount(suite, d.state.progress, ctx);
4340
- const N = missionCount(suite);
4341
- const title = resolveText(mission.done?.title, ctx) || `${mission.title}แล้ว`;
4342
- d.effects.push({
4343
- type: "announce",
4344
- text: all
4345
- ? `ครบ ${N} ภารกิจ ${resolveText(suite.complete.title, ctx) || "บริษัทพร้อมใช้งานแล้ว"}`
4346
- : `ภารกิจสำเร็จ ${title} เสร็จ ${n} จาก ${N} ภารกิจ`,
4347
- });
4348
- }
4349
- function startMission(d, suite, env, key, replay) {
4350
- const mission = findMission(suite, key);
4351
- if (!mission || mission.steps.length === 0)
4352
- return;
4353
- const entry = d.state.progress.missions[key];
4354
- // A mission already done is only ever replayed; its done status stays.
4355
- const isReplay = replay || entry?.status === "done";
4356
- const before = d.state.progress;
4357
- d.state = { ...d.state, panelOpen: false, justDone: null };
4358
- if (d.state.progress.welcome === "not_seen")
4359
- withProgress(d, { welcome: "started" });
4360
- if (!isReplay && d.state.progress.mission_key !== key)
4361
- withProgress(d, { context: {} });
4362
- if (!isReplay && d.state.progress.status !== "in_progress") {
4363
- // Picking up an optional mission after the tour completed.
4364
- withProgress(d, { status: "in_progress" });
4365
- }
4366
- // Resume where it was left: back to the checkpoint at or before it.
4367
- let index = 0;
4368
- if (!isReplay && entry && (entry.status === "active" || entry.status === "skipped")) {
4369
- const at = mission.steps.findIndex(s => s.key === (entry.step_key ?? entry.skipped_step));
4370
- if (at > 0)
4371
- index = checkpointAtOrBefore(mission.steps, at);
4372
- }
4373
- if (isReplay) {
4374
- // What is open now is the user's: ending the replay leaves it alone.
4375
- d.state = {
4376
- ...d.state,
4377
- replayPage: {
4378
- mission: key,
4379
- anchors: abortAnchorsOf(mission).filter(a => safe(() => env.isVisible(a), false)),
4380
- dialog: safe(() => env.dialogOpen?.() === true, false),
4381
- },
4382
- };
4383
- }
4384
- enterStep(d, suite, env, mission, index, { replay: isReplay });
4385
- // A replay never writes progress; only what starting it changed (the
4386
- // welcome, first seen through a replay) is saved.
4387
- if (isReplay && d.state.progress !== before)
4388
- save(d);
4389
- }
4390
- function exitMission(d) {
4391
- const s = d.state.screen;
4392
- if (s.name !== "step")
4393
- return;
4394
- if (!s.replay) {
4395
- const prev = d.state.progress.missions[s.mission];
4396
- if (prev?.status !== "done") {
4397
- setMission(d, s.mission, {
4398
- status: "skipped",
4399
- step_key: d.state.progress.step_key,
4400
- skipped_step: d.state.progress.step_key,
4401
- });
4402
- }
4403
- withProgress(d, { mission_key: null });
4404
- save(d, true);
4405
- }
4406
- d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
4407
- setScreen(d, { name: "idle" });
4408
- }
4409
- function triggerMatchesSignal(t, sig, env, ctx) {
4410
- if ("api" in t && sig.kind === "api") {
4411
- if (t.api.method && t.api.method.toUpperCase() !== sig.method.toUpperCase())
4412
- return null;
4413
- if (!matchApiPath(t.api.path, sig.path))
4414
- return null;
4415
- if (!matchStatus(t.api.status, sig.status))
4416
- return null;
4417
- return { api: { method: sig.method.toUpperCase(), path: sig.path, status: sig.status, id: sig.id } };
4418
- }
4419
- if ("event" in t && sig.kind === "event") {
4420
- return t.event === sig.name ? { event: { name: sig.name, detail: sig.detail } } : null;
4421
- }
4422
- if ("activate" in t && sig.kind === "activate")
4423
- return {};
4424
- if ("value" in t && sig.kind === "value") {
4425
- return safe(() => t.value(sig.value, ctx), false) ? {} : null;
4426
- }
4427
- return null;
4428
- }
4429
- /** A refused save that a commit step listens for. */
4430
- function apiFailureFor(step, sig) {
4431
- if (sig.kind !== "api" || sig.status < 400)
4432
- return false;
4433
- return triggersOf(step).some(t => "api" in t &&
4434
- (!t.api.method || t.api.method.toUpperCase() === sig.method.toUpperCase()) &&
4435
- matchApiPath(t.api.path, sig.path));
4436
- }
4437
- /** A replay ends early: what puts the page back (nothing on another page). */
4438
- function pushAbort(d, suite, s) {
4439
- if (s.phase === "away")
4440
- return;
4441
- const mission = findMission(suite, s.mission);
4442
- if (!mission)
4443
- return;
4444
- const before = d.state.replayPage?.mission === s.mission ? d.state.replayPage : null;
4445
- const actions = abortActionsLeft(abortActionsFor(mission, s.index), before);
4446
- if (actions.length)
4447
- d.effects.push({ type: "abort", actions });
4448
- }
4449
- function reduceGuide(state, action, suite, env) {
4450
- const d = { state, effects: [] };
4451
- const s = state.screen;
4452
- const ctxNow = () => guideContext(env, d.state.progress.context);
4453
- switch (action.type) {
4454
- case "welcome": {
4455
- if (!welcomeDue(state, suite))
4456
- break;
4457
- const gate = gateState(suite, ctxNow());
4458
- if (gate === undefined)
4459
- break;
4460
- if (gate === false) {
4461
- if (!state.gateDismissed)
4462
- setScreen(d, { name: "gate" });
4463
- break;
4464
- }
4465
- setScreen(d, { name: "welcome", confirm: false });
4466
- break;
4467
- }
4468
- case "welcomeSkip":
4469
- if (s.name === "welcome")
4470
- setScreen(d, { name: "welcome", confirm: true });
4471
- break;
4472
- case "welcomeStart":
4473
- case "welcomeSkipCancel": {
4474
- if (s.name !== "welcome")
4475
- break;
4476
- const first = nextMissionKey(suite, d.state.progress, ctxNow());
4477
- if (first)
4478
- startMission(d, suite, env, first, false);
4479
- else
4480
- setScreen(d, { name: "idle" });
4481
- break;
4482
- }
4483
- case "welcomeSkipConfirm":
4484
- if (s.name !== "welcome")
4485
- break;
4486
- withProgress(d, { welcome: "skipped" });
4487
- d.state = { ...d.state, chipPulse: d.state.chipPulse + 1 };
4488
- setScreen(d, { name: "idle" });
4489
- save(d, true);
4490
- break;
4491
- case "gateLater":
4492
- if (s.name === "gate") {
4493
- d.state = { ...d.state, gateDismissed: true };
4494
- setScreen(d, { name: "idle" });
4495
- }
4496
- break;
4497
- case "start":
4498
- if (state.audience === "none")
4499
- break;
4500
- if (s.name === "step" && !s.replay && s.mission !== action.mission) {
4501
- // Leaving one mission for another: the first is set aside.
4502
- exitMission(d);
4503
- }
4504
- startMission(d, suite, env, action.mission, !!action.replay);
4505
- break;
4506
- case "resume": {
4507
- if (state.audience === "none" || s.name !== "idle")
4508
- break;
4509
- const mission = findMission(suite, d.state.progress.mission_key);
4510
- if (!mission || d.state.progress.missions[mission.key]?.status !== "active")
4511
- break;
4512
- // Back to the last checkpoint at or before the step reached; the saved
4513
- // checkpoint when the step is no longer in the tour.
4514
- const stepAt = mission.steps.findIndex(st => st.key === d.state.progress.step_key);
4515
- const cpAt = mission.steps.findIndex(st => st.key === d.state.progress.checkpoint_key);
4516
- const index = stepAt >= 0 ? checkpointAtOrBefore(mission.steps, stepAt) : Math.max(cpAt, 0);
4517
- enterStep(d, suite, env, mission, index, { replay: false });
4518
- break;
4519
- }
4520
- case "sync": {
4521
- if (s.name !== "step")
4522
- break;
4523
- const mission = findMission(suite, s.mission);
4524
- if (!mission)
4525
- break;
4526
- const step = mission.steps[s.index];
4527
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4528
- if (s.phase === "away") {
4529
- const where = placeRoute(mission.steps, s.index);
4530
- if (!where || matchRoute(where, env.pathname, env.search, env.code)) {
4531
- // Arrived: run the step again from here (it may already be passed).
4532
- enterStep(d, suite, env, mission, s.index, { replay: s.replay, error: s.error });
4533
- }
4534
- break;
4535
- }
4536
- if (s.confirmExit)
4537
- break;
4538
- const nts = !s.bridge && nothingToSaveHolds(step, env, ctx);
4539
- if (nts !== s.nothingToSave) {
4540
- setNothingToSave(d, suite, env, nts);
4541
- break;
4542
- }
4543
- const kind = stepKind(shownStep(step, s.nothingToSave));
4544
- const armed = s.armed || hiddenAnchorShown(step, env);
4545
- if (kind !== "input" && kind !== "view") {
4546
- const held = syncTriggerHolds(step, env, armed);
4547
- if (held) {
4548
- advance(d, suite, env, held);
4549
- break;
4550
- }
4551
- }
4552
- if (!s.bridge && !stepTargetVisible(shownStep(step, s.nothingToSave), env, ctx, false) && offRoute(mission.steps, s.index, env)) {
4553
- // The target is missing because the page is another one.
4554
- recoverOffRoute(d, suite, env, false);
4555
- break;
4556
- }
4557
- if (armed !== s.armed)
4558
- setScreen(d, { ...s, armed });
4559
- const cur = d.state.screen;
4560
- // The menu step: done once the sidebar is open; needed again if shut.
4561
- if (cur.bridge && (env.sidebarOpen || stepTargetVisible(step, env, ctx, false))) {
4562
- setScreen(d, { ...cur, bridge: false, phase: "waiting" });
4563
- }
4564
- else if (!cur.bridge && needsBridge(step, env, ctx)) {
4565
- setScreen(d, { ...cur, bridge: true, phase: "waiting" });
4566
- }
4567
- markReadyIfVisible(d, suite, env);
4568
- break;
4569
- }
4570
- case "signal": {
4571
- if (s.name !== "step" || s.phase === "away" || s.confirmExit)
4572
- break;
4573
- const mission = findMission(suite, s.mission);
4574
- if (!mission)
4575
- break;
4576
- const step = mission.steps[s.index];
4577
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4578
- const sig = action.signal;
4579
- if (sig.kind === "typing") {
4580
- if (s.error)
4581
- setScreen(d, { ...s, error: null });
4582
- break;
4583
- }
4584
- if (s.bridge)
4585
- break;
4586
- for (const t of triggersOf(step)) {
4587
- const hit = triggerMatchesSignal(t, sig, env, ctx);
4588
- if (hit) {
4589
- advance(d, suite, env, hit);
4590
- return { state: d.state, effects: d.effects };
4591
- }
4592
- }
4593
- if (sig.kind === "api" && stepKind(step) === "commit" && apiFailureFor(step, sig)) {
4594
- const mapped = safe(() => step.onApiError?.({ status: sig.status, message: sig.message }, ctx), undefined);
4595
- if (mapped && mapped.step) {
4596
- const to = mission.steps.findIndex(st => st.key === mapped.step);
4597
- if (to >= 0) {
4598
- enterStep(d, suite, env, mission, to, {
4599
- replay: s.replay,
4600
- noAutoPass: true,
4601
- error: { title: mapped.message ?? sig.message ?? COPY.saveFailed, detail: COPY.fieldFix },
4602
- });
4603
- break;
4604
- }
4605
- }
4606
- const error = mapped?.message
4607
- ? { title: mapped.message, detail: undefined }
4608
- : { title: COPY.saveFailed, detail: sig.message };
4609
- setScreen(d, { ...s, error });
4610
- d.effects.push({ type: "announce", text: [error.title, error.detail].filter(Boolean).join(". ") });
4611
- if (!s.replay)
4612
- withProgress(d, { last_error: `api_${sig.status}:${step.key}`.slice(0, 128) });
4613
- }
4614
- break;
4615
- }
4616
- case "next": {
4617
- if (s.name !== "step" || s.phase !== "ready" || s.confirmExit || s.bridge)
4618
- break;
4619
- const mission = findMission(suite, s.mission);
4620
- if (!mission)
4621
- break;
4622
- const step = mission.steps[s.index];
4623
- const kind = stepKind(shownStep(step, s.nothingToSave));
4624
- if (kind === "view") {
4625
- // A read step, or a commit step with nothing to save.
4626
- advance(d, suite, env);
4627
- break;
4628
- }
4629
- if (kind !== "input")
4630
- break;
4631
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(step, env));
4632
- const value = safe(() => env.targetValue(), "");
4633
- const problem = step.validate
4634
- ? safe(() => step.validate(value, ctx), null)
4635
- : value.trim()
4636
- ? null
4637
- : COPY.blank;
4638
- if (problem) {
4639
- setScreen(d, { ...s, error: { title: problem, detail: COPY.fieldFix } });
4640
- d.state = { ...d.state, nudge: d.state.nudge + 1 };
4641
- d.effects.push({ type: "announce", text: problem });
4642
- }
4643
- else {
4644
- advance(d, suite, env);
4645
- }
4646
- break;
4647
- }
4648
- case "targetLost": {
4649
- if (s.name !== "step" || s.phase !== "ready" || s.confirmExit)
4650
- break;
4651
- const mission = findMission(suite, s.mission);
4652
- if (!mission)
4653
- break;
4654
- const raw = mission.steps[s.index];
4655
- const ctx = guideContext(env, d.state.progress.context, routeParamsFor(raw, env));
4656
- // The save went with nothing left to save, or came back: the other form.
4657
- setNothingToSave(d, suite, env, !s.bridge && nothingToSaveHolds(raw, env, ctx));
4658
- const cur = d.state.screen;
4659
- if (stepTargetVisible(shownStep(raw, cur.nothingToSave), env, ctx, cur.bridge))
4660
- break;
4661
- if (!cur.bridge && offRoute(mission.steps, cur.index, env)) {
4662
- recoverOffRoute(d, suite, env, false);
4663
- break;
4664
- }
4665
- const cp = checkpointAtOrBefore(mission.steps, cur.index);
4666
- if (cp < cur.index && !cur.bridge) {
4667
- // A dialog or a menu closed under the step: back to what opens it.
4668
- enterStep(d, suite, env, mission, cp, { replay: cur.replay, noAutoPass: false });
4669
- }
4670
- else {
4671
- setScreen(d, { ...cur, phase: "waiting" });
4672
- }
4673
- break;
4674
- }
4675
- case "timeout": {
4676
- if (s.name !== "step" || s.phase !== "waiting")
4677
- break;
4678
- const mission = findMission(suite, s.mission);
4679
- if (!mission)
4680
- break;
4681
- const step = mission.steps[s.index];
4682
- if (!s.bridge && offRoute(mission.steps, s.index, env)) {
4683
- recoverOffRoute(d, suite, env, false);
4684
- break;
4685
- }
4686
- const anchor = s.bridge ? BRIDGE_TARGET : (step.target ?? step.key);
4687
- // Diagnostic only: kept with the progress, sent with its next save (a
4688
- // replay keeps nothing). The same error again changes nothing, so it
4689
- // never sends a PUT on its own.
4690
- if (!s.replay)
4691
- withProgress(d, { last_error: `target_missing:${anchor}`.slice(0, 128) });
4692
- const misses = s.misses + 1;
4693
- const policy = step.onMissing ?? "retry";
4694
- const cp = checkpointAtOrBefore(mission.steps, s.index);
4695
- if (policy === "skip") {
4696
- advance(d, suite, env);
4697
- }
4698
- else if (policy === "abort") {
4699
- exitMission(d);
4700
- d.effects.push({ type: "toast", text: COPY.aborted });
4701
- }
4702
- else if ((policy === "rewind" || (policy === "retry" && misses >= 2)) && cp < s.index) {
4703
- enterStep(d, suite, env, mission, cp, { replay: s.replay });
4704
- const now = d.state.screen;
4705
- if (now.name === "step" && now.index === s.index) {
4706
- // The checkpoint passed straight back to this step (its dialog is
4707
- // still open): going back cannot help, so say so.
4708
- setScreen(d, { ...now, phase: "missing", misses });
4709
- d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
4710
- }
4711
- }
4712
- else {
4713
- setScreen(d, { ...s, phase: "missing", misses });
4714
- d.effects.push({ type: "announce", text: "ไม่พบส่วนนี้บนหน้า" });
4715
- }
4716
- break;
4717
- }
4718
- case "retry": {
4719
- if (s.name !== "step" || s.phase !== "missing")
4720
- break;
4721
- const mission = findMission(suite, s.mission);
4722
- if (mission && !s.bridge && offRoute(mission.steps, s.index, env)) {
4723
- // Polling again cannot help on another page: go back to the step's.
4724
- recoverOffRoute(d, suite, env, true);
4725
- break;
4726
- }
4727
- setScreen(d, { ...s, phase: "waiting" });
4728
- markReadyIfVisible(d, suite, env);
4729
- break;
4730
- }
4731
- case "blocked":
4732
- if (s.name === "step")
4733
- d.state = { ...d.state, nudge: d.state.nudge + 1 };
4734
- break;
4735
- case "exit":
4736
- if (s.name !== "step")
4737
- break;
4738
- if (s.replay) {
4739
- pushAbort(d, suite, s);
4740
- setScreen(d, { name: "idle" });
4741
- d.effects.push({ type: "toast", text: COPY.replayEnded });
4742
- }
4743
- else {
4744
- setScreen(d, { ...s, confirmExit: true });
4745
- }
4746
- break;
4747
- case "exitCancel":
4748
- if (s.name === "step" && s.confirmExit)
4749
- setScreen(d, { ...s, confirmExit: false });
4750
- break;
4751
- case "exitConfirm":
4752
- if (s.name !== "step")
4753
- break;
4754
- exitMission(d);
4755
- d.effects.push({ type: "toast", text: COPY.exitToast });
4756
- break;
4757
- case "endWithoutSave":
4758
- if (s.name !== "step" || !s.replay)
4759
- break;
4760
- pushAbort(d, suite, s);
4761
- setScreen(d, { name: "idle" });
4762
- d.effects.push({ type: "toast", text: COPY.replayEnded });
4763
- break;
4764
- case "goResume": {
4765
- if (s.name !== "step" || s.phase !== "away")
4766
- break;
4767
- const mission = findMission(suite, s.mission);
4768
- if (!mission)
4769
- break;
4770
- const href = resumeHref(mission, s.index, d, env);
4771
- if (href)
4772
- d.effects.push({ type: "navigate", href });
4773
- break;
4774
- }
4775
- case "celebrateNext": {
4776
- if (s.name !== "celebrate")
4777
- break;
4778
- const next = nextMissionKey(suite, d.state.progress, ctxNow());
4779
- if (next)
4780
- startMission(d, suite, env, next, false);
4781
- else
4782
- setScreen(d, { name: "idle" });
4783
- break;
4784
- }
4785
- case "rest":
4786
- if (s.name !== "celebrate")
4787
- break;
4788
- setScreen(d, { name: "idle" });
4789
- d.state = { ...d.state, panelOpen: true, justDone: s.mission };
4790
- break;
4791
- case "finish": {
4792
- if (s.name !== "complete")
4793
- break;
4794
- setScreen(d, { name: "idle" });
4795
- const href = resolveText(suite.complete.action.href, ctxNow());
4796
- const filled = href ? (fillRoute(href, { code: env.code }) ?? href) : "";
4797
- if (filled)
4798
- d.effects.push({ type: "navigate", href: filled });
4799
- break;
4800
- }
4801
- case "openPanel":
4802
- if (state.audience !== "none" && s.name === "idle") {
4803
- d.state = { ...d.state, panelOpen: true };
4804
- }
4805
- break;
4806
- case "closePanel":
4807
- d.state = { ...d.state, panelOpen: false, justDone: null };
4808
- break;
4809
- case "hideChip":
4810
- withProgress(d, { chip_hidden: true });
4811
- d.state = { ...d.state, panelOpen: false };
4812
- d.effects.push({ type: "toast", text: COPY.hiddenToast });
4813
- save(d, true);
4814
- break;
4815
- case "dismissMission": {
4816
- const m = findMission(suite, action.mission);
4817
- if (!m?.optional)
4818
- break;
4819
- setMission(d, m.key, { status: "skipped", step_key: null, skipped_step: null });
4820
- const all = settledCount(suite, d.state.progress, ctxNow()) >= missionCount(suite);
4821
- if (all) {
4822
- withProgress(d, { status: "completed" });
4823
- d.state = { ...d.state, panelOpen: false };
4824
- setScreen(d, { name: "complete" });
4825
- }
4826
- save(d, true);
4827
- break;
4828
- }
4829
- case "serverRow": {
4830
- // A saved row came back: its rev, the server's status, and the dates
4831
- // the server stamps on missions ("เสร็จ 26 ต.ค. 2569 13:04").
4832
- const missions = { ...d.state.progress.missions };
4833
- for (const [k, m] of Object.entries(missions)) {
4834
- const r = action.progress.missions[k];
4835
- if (r && r.status === m.status) {
4836
- missions[k] = { ...m, completed_at: r.completed_at ?? m.completed_at, skipped_at: r.skipped_at ?? m.skipped_at };
4837
- }
4838
- }
4839
- withProgress(d, { rev: action.progress.rev, server_status: action.progress.server_status, missions });
4840
- break;
4841
- }
4842
- }
4843
- return { state: d.state, effects: d.effects };
4844
- }
4845
-
4846
- /**
4847
- * A tour's progress as platform-api stores it (one row per user, org and
4848
- * suite: GET/PUT /organizations/:id/guides/me), and the rules for reading,
4849
- * writing and merging it. See _claude-work/peoplx-guide/API.md.
4850
- *
4851
- * No runtime imports: the tests run this file in Node as it is.
4852
- */
4853
- const KEY_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4854
- const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4855
- const str = (v) => (typeof v === "string" && v !== "" ? v : null);
4856
- function freshProgress(version, rev = 0) {
4857
- return {
4858
- guide_version: version,
4859
- rev,
4860
- status: "in_progress",
4861
- mission_key: null,
4862
- step_key: null,
4863
- step_index: 0,
4864
- checkpoint_key: null,
4865
- missions: {},
4866
- context: {},
4867
- welcome: "not_seen",
4868
- chip_hidden: false,
4869
- last_error: null,
4870
- skipped_step: null,
4871
- server_status: null,
4872
- };
4873
- }
4874
- const ROW_STATUSES = ["in_progress", "completed", "skipped", "aborted"];
4875
- const MISSION_STATUSES = ["todo", "active", "done", "skipped"];
4876
- const WELCOMES = ["not_seen", "started", "skipped"];
4877
- /** One row (a GET `guides[]` entry, a PUT answer, a 409's `current`). Null when off-shape. */
4878
- function parseRow(raw) {
4879
- if (!isRecord(raw))
4880
- return null;
4881
- const version = Number(raw.guide_version);
4882
- const rev = Number(raw.rev);
4883
- if (!Number.isInteger(version) || version < 1 || !Number.isInteger(rev) || rev < 0)
4884
- return null;
4885
- const status = ROW_STATUSES.includes(raw.status)
4886
- ? raw.status
4887
- : "in_progress";
4888
- const missions = {};
4889
- if (isRecord(raw.missions)) {
4890
- for (const [k, v] of Object.entries(raw.missions)) {
4891
- if (!isRecord(v) || !MISSION_STATUSES.includes(v.status))
4892
- continue;
4893
- missions[k] = {
4894
- status: v.status,
4895
- step_key: str(v.step_key),
4896
- skipped_step: str(v.skipped_step),
4897
- completed_at: str(v.completed_at),
4898
- skipped_at: str(v.skipped_at),
4899
- };
4900
- }
4901
- }
4902
- const context = {};
4903
- if (isRecord(raw.context)) {
4904
- for (const [k, v] of Object.entries(raw.context)) {
4905
- if (typeof v === "string")
4906
- context[k] = v;
4907
- else if (typeof v === "number")
4908
- context[k] = String(v);
4909
- }
4910
- }
4911
- return {
4912
- guide_version: version,
4913
- rev,
4914
- status,
4915
- mission_key: str(raw.mission_key),
4916
- step_key: str(raw.step_key),
4917
- step_index: Number.isInteger(raw.step_index) ? raw.step_index : 0,
4918
- checkpoint_key: str(raw.checkpoint_key),
4919
- missions,
4920
- context,
4921
- welcome: WELCOMES.includes(raw.welcome) ? raw.welcome : "not_seen",
4922
- chip_hidden: raw.chip_hidden === true,
4923
- last_error: str(raw.last_error),
4924
- skipped_step: str(raw.skipped_step),
4925
- server_status: status,
4926
- };
4927
- }
4928
- /**
4929
- * The GET answer for one suite. Null — show nothing — for anything that is
4930
- * not the expected shape (an older API, a proxy's page, another app's answer).
4931
- */
4932
- function parseGuidesAnswer(payload, suite) {
4933
- if (!isRecord(payload))
4934
- return null;
4935
- const data = isRecord(payload.data) ? payload.data : payload;
4936
- const mode = data.mode;
4937
- const audience = data.audience;
4938
- if (mode !== "off" && mode !== "invite" && mode !== "forced")
4939
- return null;
4940
- if (audience !== "forced" && audience !== "optional" && audience !== "none")
4941
- return null;
4942
- if (typeof data.app === "string" && data.app !== suite.app)
4943
- return null;
4944
- const rows = Array.isArray(data.guides) ? data.guides : [];
4945
- let row = null;
4946
- for (const r of rows) {
4947
- if (isRecord(r) && r.guide_key === suite.key) {
4948
- row = parseRow(r);
4949
- break;
4950
- }
4951
- }
4952
- let progress;
4953
- let newerOnServer = false;
4954
- if (!row)
4955
- progress = freshProgress(suite.version);
4956
- else if (row.guide_version < suite.version) {
4957
- // A new version of the tour: start over (the server resets the row on the
4958
- // PUT); keep the rev the server will check.
4959
- progress = { ...freshProgress(suite.version, row.rev), server_status: row.server_status };
4960
- }
4961
- else {
4962
- progress = row;
4963
- newerOnServer = row.guide_version > suite.version;
4964
- }
4965
- return { mode, audience: mode === "off" ? "none" : audience, progress, newerOnServer };
4966
- }
4967
- const TERMINAL = ["completed", "skipped", "aborted"];
4968
- /** The PUT body for the client's state. Drops keys the server would refuse. */
4969
- function putBody(p, app) {
4970
- const key = (k) => (k && KEY_RE.test(k) ? k : null);
4971
- const missions = {};
4972
- for (const [k, m] of Object.entries(p.missions)) {
4973
- if (!KEY_RE.test(k))
4974
- continue;
4975
- missions[k] = {
4976
- status: m.status,
4977
- step_key: key(m.step_key ?? null),
4978
- skipped_step: key(m.skipped_step ?? null),
4979
- };
4980
- }
4981
- const context = {};
4982
- for (const [k, v] of Object.entries(p.context)) {
4983
- if (typeof v === "string" && v.length <= 200)
4984
- context[k] = v;
4985
- }
4986
- return {
4987
- app,
4988
- guide_version: p.guide_version,
4989
- rev: p.rev,
4990
- status: p.status,
4991
- mission_key: key(p.mission_key),
4992
- step_key: key(p.step_key),
4993
- step_index: Math.max(0, Math.min(1000, Math.floor(p.step_index || 0))),
4994
- checkpoint_key: key(p.checkpoint_key),
4995
- missions,
4996
- context,
4997
- welcome: p.welcome,
4998
- chip_hidden: p.chip_hidden,
4999
- last_error: p.last_error ? p.last_error.slice(0, 128) : null,
5000
- skipped_step: key(p.skipped_step),
5001
- restart: p.status === "in_progress" &&
5002
- p.server_status !== null &&
5003
- TERMINAL.includes(p.server_status),
5004
- };
5005
- }
5006
- function stable(v) {
5007
- if (Array.isArray(v))
5008
- return `[${v.map(stable).join(",")}]`;
5009
- if (isRecord(v)) {
5010
- return `{${Object.keys(v)
5011
- .sort()
5012
- .map(k => `${JSON.stringify(k)}:${stable(v[k])}`)
5013
- .join(",")}}`;
5014
- }
5015
- return JSON.stringify(v) ?? "null";
5016
- }
5017
- /**
5018
- * What a PUT would store, without the rev it is checked against: two equal
5019
- * keys mean the save would change nothing, and it is not sent (a replay
5020
- * starting, a step entered again, never bump the row's rev). Key order does
5021
- * not matter.
5022
- */
5023
- function payloadKey(p, app) {
5024
- const { rev: _rev, restart: _restart, ...rest } = putBody(p, app);
5025
- return stable(rest);
5026
- }
5027
- const MISSION_RANK = { todo: 0, skipped: 1, active: 1, done: 3 };
5028
- const WELCOME_RANK = { not_seen: 0, skipped: 1, started: 1 };
5029
- /**
5030
- * After a 409: this tab's state laid over the server's, keeping whatever is
5031
- * further along — a mission done anywhere stays done, the welcome once seen
5032
- * stays seen, a hidden chip stays hidden. Otherwise this tab's own choice
5033
- * wins. The rev is the server's.
5034
- */
5035
- function mergeProgress(local, remote) {
5036
- const missions = { ...remote.missions };
5037
- for (const [k, m] of Object.entries(local.missions)) {
5038
- const r = remote.missions[k];
5039
- missions[k] = !r || MISSION_RANK[m.status] >= MISSION_RANK[r.status] ? { ...r, ...m } : r;
5040
- }
5041
- const welcome = WELCOME_RANK[local.welcome] >= WELCOME_RANK[remote.welcome] ? local.welcome : remote.welcome;
5042
- const completed = local.status === "completed" || remote.status === "completed";
5043
- const mission_key = local.mission_key && missions[local.mission_key]?.status === "active"
5044
- ? local.mission_key
5045
- : remote.mission_key && missions[remote.mission_key]?.status === "active"
5046
- ? remote.mission_key
5047
- : null;
5048
- const fromLocal = mission_key !== null && mission_key === local.mission_key;
5049
- return {
5050
- ...local,
5051
- rev: remote.rev,
5052
- server_status: remote.server_status,
5053
- status: completed ? "completed" : local.status,
5054
- missions,
5055
- welcome,
5056
- chip_hidden: local.chip_hidden || remote.chip_hidden,
5057
- mission_key,
5058
- step_key: fromLocal ? local.step_key : mission_key ? remote.step_key : null,
5059
- step_index: fromLocal ? local.step_index : mission_key ? remote.step_index : 0,
5060
- checkpoint_key: fromLocal ? local.checkpoint_key : mission_key ? remote.checkpoint_key : null,
5061
- context: fromLocal ? local.context : mission_key ? remote.context : {},
5062
- };
5063
- }
5064
- /**
5065
- * Which of two copies (sessionStorage after F5, the server) to resume from:
5066
- * the one further along for the same version; the server's on a tie.
5067
- */
5068
- function furtherProgress(a, b) {
5069
- const score = (p) => Object.values(p.missions).reduce((s, m) => s + MISSION_RANK[m.status] * 1000, 0) +
5070
- (p.mission_key ? 100 + p.step_index : 0) +
5071
- WELCOME_RANK[p.welcome];
5072
- return score(a) > score(b) ? a : b;
5073
- }
5074
-
5075
- /**
5076
- * Talking to platform-api about tour progress (API.md): the GET that says
5077
- * who sees what, and the PUT that saves, with its rev check.
5078
- */
5079
- function base(app) {
5080
- return platformApiBase(app);
5081
- }
5082
- /** GET …/guides/me?app=…; null (show nothing) on any failure or odd answer. */
5083
- async function fetchGuides(organizationId, suite, signal) {
5084
- try {
5085
- const res = await instance.get(`${base(suite.app)}/organizations/${encodeURIComponent(organizationId)}/guides/me`, { params: { app: suite.app }, signal, erpOrganizationId: organizationId });
5086
- return parseGuidesAnswer(res.data, suite);
5087
- }
5088
- catch {
5089
- return null;
5090
- }
5091
- }
5092
- /**
5093
- * PUT the whole state. On 409 the server's row comes back: merge (keeping
5094
- * whatever is further along) and try once more with its rev. Returns the
5095
- * stored row, or null when it could not be saved (the tour goes on; the
5096
- * session copy keeps the place).
5097
- */
5098
- async function saveGuides(organizationId, suite, progress) {
5099
- const url = `${base(suite.app)}/organizations/${encodeURIComponent(organizationId)}/guides/me/${encodeURIComponent(suite.key)}`;
5100
- let body = progress;
5101
- for (let attempt = 0; attempt < 2; attempt++) {
5102
- let res;
5103
- try {
5104
- res = await instance.put(url, putBody(body, suite.app), {
5105
- validateStatus: s => (s >= 200 && s < 300) || s === 409,
5106
- erpOrganizationId: organizationId,
5107
- });
5108
- }
5109
- catch {
5110
- return null;
5111
- }
5112
- const payload = res.data;
5113
- if (res.status !== 409) {
5114
- return parseRow(payload?.data ?? payload);
5115
- }
5116
- const current = parseRow(payload?.current);
5117
- if (current && current.guide_version > body.guide_version) {
5118
- // Another app build is ahead of this one: stop writing.
5119
- return null;
5120
- }
5121
- if (!current)
5122
- body = { ...body, rev: 0, server_status: null };
5123
- else if (current.guide_version < body.guide_version) {
5124
- // The server's row is the previous version: this one replaces it.
5125
- body = { ...body, rev: current.rev, server_status: current.server_status };
5126
- }
5127
- else
5128
- body = mergeProgress(body, current);
5129
- }
5130
- return null;
5131
- }
5132
-
5133
- /**
5134
- * The tour's DOM side: finding anchors, deciding whether one is really on
5135
- * screen, and the rectangles the spotlight cuts out. Browser only; every
5136
- * function tolerates a missing document.
5137
- */
5138
- const hasDocument = () => typeof document !== "undefined";
5139
- function cssString(value) {
5140
- return `"${value.replace(/["\\]/g, "\\$&")}"`;
5141
- }
5142
- function anchorSelector(anchor, id) {
5143
- return (`[${GUIDE_ATTRIBUTE}=${cssString(anchor)}]` +
5144
- (id ? `[${GUIDE_ID_ATTRIBUTE}=${cssString(id)}]` : ""));
5145
- }
5146
- /**
5147
- * On screen: connected, with a size, not hidden by style, not inside
5148
- * aria-hidden or inert (other than the guide's own), not a closed Radix part.
5149
- *
5150
- * aria-hidden that Radix put there (data-aria-hidden: everything outside an
5151
- * open dialog, select or menu is hidden from screen readers) does not count:
5152
- * a dialog's field is still on screen while its select's list is open.
5153
- */
5154
- function isPresent(el) {
5155
- if (!el || !el.isConnected)
5156
- return false;
5157
- const r = el.getBoundingClientRect();
5158
- if (r.width <= 0 || r.height <= 0)
5159
- return false;
5160
- // Slid off the side (a closed drawer); off the top or bottom is only
5161
- // scrolled away, and the tour scrolls it back. So is a tab scrolled out of
5162
- // a row of tabs that scrolls sideways, as long as the row is on screen.
5163
- if ((r.right <= 0 || r.left >= window.innerWidth) && !inSidewaysScroller(el))
5164
- return false;
5165
- if (el.getAttribute("data-state") === "closed")
5166
- return false;
5167
- const style = getComputedStyle(el);
5168
- if (style.visibility === "hidden" || style.display === "none")
5169
- return false;
5170
- for (let n = el; n; n = n.parentElement) {
5171
- if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
5172
- break;
5173
- if (n.hasAttribute("inert"))
5174
- return false;
5175
- if (n.getAttribute("aria-hidden") === "true" && !n.hasAttribute("data-aria-hidden"))
5176
- return false;
5177
- }
5178
- return true;
5179
- }
5180
- /** The first matching anchor that is on screen. */
5181
- function findAnchor(anchor, id) {
5182
- if (!hasDocument() || !anchor)
5183
- return null;
5184
- let list;
5185
- try {
5186
- list = document.querySelectorAll(anchorSelector(anchor, id));
5187
- }
5188
- catch {
5189
- return null;
5190
- }
5191
- for (const el of Array.from(list)) {
5192
- if (isPresent(el))
5193
- return el;
5194
- }
5195
- return null;
5196
- }
5197
- function anchorVisible(anchor, id) {
5198
- return findAnchor(anchor, id) !== null;
5199
- }
5200
- const FIELD = "input:not([type=hidden]),textarea,select,[contenteditable=''],[contenteditable=true]";
5201
- /** The field to type into: the anchor itself, or the first field inside it. */
5202
- function fieldOf(el) {
5203
- if (!el)
5204
- return null;
5205
- if (el.matches(FIELD))
5206
- return el;
5207
- return el.querySelector(FIELD);
5208
- }
5209
- function fieldValue(el) {
5210
- const f = fieldOf(el);
5211
- if (!f)
5212
- return "";
5213
- if ("value" in f && typeof f.value === "string")
5214
- return f.value;
5215
- return f.textContent ?? "";
5216
- }
5217
- 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]";
5218
- function focusablesIn(root) {
5219
- if (!root)
5220
- return [];
5221
- const own = root.matches(FOCUSABLE) ? [root] : [];
5222
- return own.concat(Array.from(root.querySelectorAll(FOCUSABLE)).filter(isPresent));
5223
- }
5224
- function rectOf(el) {
5225
- const r = el.getBoundingClientRect();
5226
- return { x: r.left, y: r.top, width: r.width, height: r.height };
5227
- }
5228
- function padRect(r, pad) {
5229
- return { x: r.x - pad, y: r.y - pad, width: r.width + pad * 2, height: r.height + pad * 2 };
5230
- }
5231
- function sameRect(a, b) {
5232
- if (!a || !b)
5233
- return a === b;
5234
- return (Math.abs(a.x - b.x) < 0.5 &&
5235
- Math.abs(a.y - b.y) < 0.5 &&
5236
- Math.abs(a.width - b.width) < 0.5 &&
5237
- Math.abs(a.height - b.height) < 0.5);
5238
- }
5239
- /** Open Radix poppers (a select's list, a menu): usable while a step runs. */
5240
- const POPPER_SELECTOR = "[data-radix-popper-content-wrapper]";
5241
- /** Toasts stay usable above the tour. */
5242
- const TOASTER_SELECTOR = "[data-sonner-toaster]";
5243
- /** Open dialogs (Radix dialog, alert dialog, sheet, popover content). */
5244
- const OPEN_DIALOG_SELECTOR = '[role="dialog"][data-state="open"],[role="alertdialog"][data-state="open"]';
5245
- /**
5246
- * Whether an open dialog of the app's covers the target: the target is
5247
- * neither in it nor around it (a confirm opened by the step's own button).
5248
- * The ring and the hand would be drawn over the dialog, pointing at a button
5249
- * behind it.
5250
- */
5251
- function coveredByDialog(el) {
5252
- if (!hasDocument() || !el)
5253
- return false;
5254
- for (const d of Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR))) {
5255
- if (inGuideLayer(d) || !isPresent(d))
5256
- continue;
5257
- if (d.contains(el) || el.contains(d))
5258
- continue;
5259
- return true;
5260
- }
5261
- return false;
5262
- }
5263
- /** An app dialog (not the tour's) is open on the page. */
5264
- function appDialogOpen() {
5265
- if (!hasDocument())
5266
- return false;
5267
- return Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR)).some(d => !inGuideLayer(d) && isPresent(d));
5268
- }
5269
- function openPoppers() {
5270
- if (!hasDocument())
5271
- return [];
5272
- return Array.from(document.querySelectorAll(POPPER_SELECTOR)).filter(isPresent);
5273
- }
5274
- function inGuideLayer(node) {
5275
- if (!node || typeof Node === "undefined" || !(node instanceof Node))
5276
- return false;
5277
- const el = node instanceof Element ? node : node.parentElement;
5278
- return !!el?.closest(`[${GUIDE_LAYER_ATTRIBUTE}]`);
5279
- }
5280
- function prefersReducedMotion() {
5281
- return typeof window !== "undefined" && !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
5282
- }
5283
- function isPhoneWidth() {
5284
- return typeof window !== "undefined" && window.innerWidth < 768;
5285
- }
5286
- /* ---------------- what is really on screen ---------------- */
5287
- const INFINITE = 1e7;
5288
- /** The overlap of two rectangles, or null when they do not meet. */
5289
- function intersectRect(a, b) {
5290
- const x = Math.max(a.x, b.x);
5291
- const y = Math.max(a.y, b.y);
5292
- const right = Math.min(a.x + a.width, b.x + b.width);
5293
- const bottom = Math.min(a.y + a.height, b.y + b.height);
5294
- if (right - x <= 0 || bottom - y <= 0)
5295
- return null;
5296
- return { x, y, width: right - x, height: bottom - y };
5297
- }
5298
- /** The part of `rect` inside every clip (scroll boxes, the viewport); null when none is. */
5299
- function visibleRect(rect, clips) {
5300
- let r = rect;
5301
- for (const c of clips) {
5302
- if (!r)
5303
- return null;
5304
- r = intersectRect(r, c);
5305
- }
5306
- return r;
5307
- }
5308
- const clipsX = (v) => v !== "visible";
5309
- const scrollsX = (v) => v === "auto" || v === "scroll";
5310
- /**
5311
- * The ancestors that cut the element off: anything with overflow other than
5312
- * visible on an axis. The body and the root scroll the page and are covered by
5313
- * the viewport. Read once per target; their rectangles are read every frame.
5314
- */
5315
- function clipAncestors(el) {
5316
- const out = [];
5317
- if (typeof getComputedStyle !== "function")
5318
- return out;
5319
- for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
5320
- if (n.hasAttribute(GUIDE_LAYER_ATTRIBUTE))
5321
- break;
5322
- const s = getComputedStyle(n);
5323
- const x = clipsX(s.overflowX);
5324
- const y = clipsX(s.overflowY);
5325
- if (x || y)
5326
- out.push({ el: n, x, y });
5327
- if (s.position === "fixed")
5328
- break;
5329
- }
5330
- return out;
5331
- }
5332
- /** An ancestor's clip as a rectangle: unbounded on an axis it does not clip. */
5333
- function clipRectOf(c) {
5334
- const r = c.el.getBoundingClientRect();
5335
- return {
5336
- x: c.x ? r.left : -INFINITE,
5337
- y: c.y ? r.top : -INFINITE,
5338
- width: c.x ? r.width : INFINITE * 2,
5339
- height: c.y ? r.height : INFINITE * 2,
5340
- };
5341
- }
5342
- function viewportRect() {
5343
- const vv = typeof window !== "undefined" ? window.visualViewport : undefined;
5344
- return {
5345
- x: 0,
5346
- y: vv ? vv.offsetTop : 0,
5347
- width: window.innerWidth,
5348
- height: vv ? vv.height : window.innerHeight,
5349
- };
5350
- }
5351
- /**
5352
- * The part of the element a person can see: its box cut by every scroll box
5353
- * around it and by the viewport. The spotlight, its hole, the ring and the
5354
- * hand use this, so a tab half out of a sideways-scrolling row of tabs is not
5355
- * spotlit where it cannot be pressed. Null when none of it is on screen.
5356
- */
5357
- function visibleRectOf(el, ancestors = clipAncestors(el)) {
5358
- return visibleRect(rectOf(el), [...ancestors.map(clipRectOf), viewportRect()]);
5359
- }
5360
- /** Inside a box that scrolls sideways (with somewhere to scroll) that is itself on screen. */
5361
- function inSidewaysScroller(el) {
5362
- if (typeof getComputedStyle !== "function")
5363
- return false;
5364
- for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
5365
- const s = getComputedStyle(n);
5366
- if (scrollsX(s.overflowX) && n.scrollWidth > n.clientWidth + 1) {
5367
- const r = n.getBoundingClientRect();
5368
- return r.width > 0 && r.right > 0 && r.left < window.innerWidth;
5369
- }
5370
- }
5371
- return false;
5372
- }
5373
- /**
5374
- * How to bring a target into view, or null when it already is: to the middle
5375
- * when it is above or below the comfortable band (under the header, at the
5376
- * bottom edge), the nearest edge when only a side is cut off (a tab out of a
5377
- * sideways-scrolling row, on a phone).
5378
- */
5379
- function revealPlan(rect, visible, viewportHeight) {
5380
- const offVertically = rect.y < 70 || rect.y + rect.height > viewportHeight - 20;
5381
- const cutSideways = !visible || visible.width < rect.width - 1;
5382
- if (!offVertically && !cutSideways)
5383
- return null;
5384
- return { block: offVertically ? "center" : "nearest", inline: "nearest" };
5385
- }
5386
- /** Room left beside a target scrolled into a sideways scroll box. */
5387
- const SIDEWAYS_MARGIN = 12;
5388
- /**
5389
- * How far to scroll a sideways scroll box so the target sits inside its
5390
- * visible part (`box`: the box cut by the viewport) with `margin` to spare on
5391
- * both sides; 0 when it already does. Clamped to what the box can scroll.
5392
- * A target wider than the room is aligned to its start.
5393
- */
5394
- function sidewaysDelta(target, box, scrollLeft, maxScrollLeft, margin = SIDEWAYS_MARGIN) {
5395
- const left = box.x + margin;
5396
- const right = box.x + box.width - margin;
5397
- let delta = 0;
5398
- if (target.x < left || target.width > right - left)
5399
- delta = target.x - left;
5400
- else if (target.x + target.width > right)
5401
- delta = target.x + target.width - right;
5402
- const next = Math.min(Math.max(scrollLeft + delta, 0), Math.max(maxScrollLeft, 0));
5403
- return next - scrollLeft;
5404
- }
5405
- /** The nearest ancestor that scrolls sideways and has somewhere to scroll. */
5406
- function sidewaysScroller(el) {
5407
- if (typeof getComputedStyle !== "function")
5408
- return null;
5409
- for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
5410
- if (scrollsX(getComputedStyle(n).overflowX) && n.scrollWidth > n.clientWidth + 1)
5411
- return n;
5412
- }
5413
- return null;
5414
- }
5415
- /**
5416
- * Scrolls the target into view (instant under reduced motion). In a box that
5417
- * scrolls sideways (a row of tabs on a phone) the box is scrolled first,
5418
- * leaving SIDEWAYS_MARGIN beside the target so its whole label shows; then
5419
- * the page, up or down only.
5420
- */
5421
- function revealTarget(el) {
5422
- const behavior = prefersReducedMotion() ? "auto" : "smooth";
5423
- const scroller = sidewaysScroller(el);
5424
- if (scroller) {
5425
- const box = intersectRect(rectOf(scroller), viewportRect()) ?? rectOf(scroller);
5426
- const dx = sidewaysDelta(rectOf(el), box, scroller.scrollLeft, scroller.scrollWidth - scroller.clientWidth);
5427
- // Instant: the page's own scroll below must not cancel it.
5428
- if (Math.abs(dx) >= 1)
5429
- scroller.scrollLeft += dx;
5430
- }
5431
- const vh = window.visualViewport?.height ?? window.innerHeight;
5432
- const plan = revealPlan(rectOf(el), visibleRectOf(el), vh);
5433
- if (!plan)
5434
- return;
5435
- try {
5436
- el.scrollIntoView({ ...plan, behavior });
5437
- }
5438
- catch {
5439
- el.scrollIntoView();
5440
- }
5441
- }
5442
- /* ---------------- the scrim's holes, as one union ---------------- */
5443
- /**
5444
- * The scrim's blocking area: the screen (with a 10 px margin) minus the union
5445
- * of the holes, as rectangles that do not overlap. Cutting each hole out with
5446
- * an even-odd fill made the place where two holes overlap (a field and the
5447
- * select list open over it) solid again, and the option there could not be
5448
- * pressed.
5449
- *
5450
- * Every hole edge splits the screen into a grid; a cell is blocked when no
5451
- * hole covers it. Cells in a row are joined, and identical rows stacked.
5452
- */
5453
- function blockedRects(holes, width, height) {
5454
- const x0 = -10;
5455
- const y0 = -10;
5456
- const x1 = width + 10;
5457
- const y1 = height + 10;
5458
- const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
5459
- const hs = holes
5460
- .filter(h => h.width > 0 && h.height > 0)
5461
- .map(h => ({
5462
- l: clamp(h.x, x0, x1),
5463
- t: clamp(h.y, y0, y1),
5464
- r: clamp(h.x + h.width, x0, x1),
5465
- b: clamp(h.y + h.height, y0, y1),
5466
- }))
5467
- .filter(h => h.r > h.l && h.b > h.t);
5468
- if (!hs.length)
5469
- return [{ x: x0, y: y0, width: x1 - x0, height: y1 - y0 }];
5470
- const uniq = (v) => Array.from(new Set(v)).sort((a, b) => a - b);
5471
- const xs = uniq([x0, x1, ...hs.flatMap(h => [h.l, h.r])]);
5472
- const ys = uniq([y0, y1, ...hs.flatMap(h => [h.t, h.b])]);
5473
- const out = [];
5474
- let prev = null;
5475
- for (let j = 0; j < ys.length - 1; j++) {
5476
- const top = ys[j];
5477
- const bottom = ys[j + 1];
5478
- const cy = (top + bottom) / 2;
5479
- const row = [];
5480
- for (let i = 0; i < xs.length - 1; i++) {
5481
- const left = xs[i];
5482
- const right = xs[i + 1];
5483
- const cx = (left + right) / 2;
5484
- const covered = hs.some(h => cx > h.l && cx < h.r && cy > h.t && cy < h.b);
5485
- if (covered)
5486
- continue;
5487
- const last = row[row.length - 1];
5488
- if (last && last.x + last.width === left)
5489
- last.width = right - last.x;
5490
- else
5491
- row.push({ x: left, y: top, width: right - left, height: bottom - top });
5492
- }
5493
- const key = row.map(r => `${r.x},${r.width}`).join("|");
5494
- if (prev && prev.key === key) {
5495
- for (const r of prev.rects)
5496
- r.height += bottom - top;
5497
- }
5498
- else {
5499
- out.push(...row);
5500
- prev = { key, rects: row };
5501
- }
5502
- }
5503
- return out;
5504
- }
5505
-
5506
- /**
5507
- * The tour's stylesheet. The shell has no CSS pipeline and the apps only scan
5508
- * its dist for Tailwind classes, which cannot carry keyframes; so the layer
5509
- * brings its own sheet, namespaced `eg-`, drawn from the theme's tokens
5510
- * (--primary carries each app's brand accent; light and dark follow).
5511
- */
5512
- const GUIDE_CSS = `
5513
- [data-erp-guide-layer]{position:fixed;inset:0;z-index:1000;pointer-events:none;font-family:inherit;color:var(--popover-foreground,#1c2634);
5514
- --eg-scrim:rgba(12,20,34,.64);--eg-card:var(--popover,#fff);--eg-fg:var(--popover-foreground,#1c2634);
5515
- --eg-muted:var(--muted-foreground,#6d7886);--eg-soft:var(--muted,#eef3f9);--eg-line:var(--border,#e8ecf1);
5516
- --eg-primary:var(--primary,#3280dd);--eg-on-primary:var(--primary-foreground,#fff);
5517
- --eg-tint:color-mix(in oklab,var(--eg-primary) 13%,var(--eg-card));--eg-strong:color-mix(in oklab,var(--eg-primary) 82%,#000);
5518
- --eg-danger:var(--destructive,#d23b4b);--eg-ok:#1d9a5f;--eg-gold:#e6a417;
5519
- --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}
5520
- [data-erp-guide-layer] *{box-sizing:border-box}
5521
- [data-erp-guide-layer] button{font:inherit;color:inherit;cursor:pointer}
5522
- .eg-i{pointer-events:auto}
5523
- .eg-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
5524
- .eg-scrim-svg{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}
5525
- .eg-scrim-svg .eg-scrim-fill{fill:var(--eg-scrim);pointer-events:none}
5526
- .eg-scrim-svg .eg-scrim-hit{fill:transparent;pointer-events:all}
5527
- .eg-scrim{position:fixed;inset:0;background:var(--eg-scrim);pointer-events:auto}
5528
- .eg-scrim.eg-light{background:rgba(12,20,34,.45)}
5529
- .eg-scrim.eg-faint{background:rgba(12,20,34,.35)}
5530
- .eg-ring{position:fixed;border-radius:12px;pointer-events:none;box-shadow:0 0 0 3px #fff,0 0 0 6px var(--eg-primary)}
5531
- .eg-ring.eg-move{transition:left .26s ease,top .26s ease,width .26s ease,height .26s ease}
5532
- .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}
5533
- .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1}
5534
- @keyframes eg-pulse{0%{opacity:.9;transform:scale(1)}100%{opacity:0;transform:scale(1.12)}}
5535
- @keyframes eg-flash{0%,100%{opacity:1;transform:none}50%{opacity:.2}}
5536
- .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}
5537
- .eg-hand svg{width:46px;height:46px;fill:#fff;stroke:#1c2634;stroke-width:1.4;stroke-linejoin:round;stroke-linecap:round}
5538
- .eg-hand.eg-flip svg{transform:scaleY(-1)}
5539
- @keyframes eg-tap{0%,100%{transform:translate(6px,8px)}50%{transform:translate(0,0)}}
5540
- .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}
5541
- .eg-bubble.eg-err{border-top-color:var(--eg-danger)}
5542
- .eg-bubble.eg-nudge{animation:eg-nudge .38s ease}
5543
- @keyframes eg-nudge{0%,100%{translate:0}20%{translate:-7px}40%{translate:6px}60%{translate:-4px}80%{translate:2px}}
5544
- .eg-b-top{display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:12px;color:var(--eg-muted)}
5545
- .eg-b-top .eg-mis{font-weight:600;color:var(--eg-strong);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
5546
- .eg-b-top .eg-cnt{white-space:nowrap;font-weight:600}
5547
- .eg-pips{display:flex;gap:4px;margin:8px 0 10px}
5548
- .eg-pips i{flex:1;height:4px;border-radius:2px;background:var(--eg-soft)}
5549
- .eg-pips i.eg-d{background:var(--eg-primary)}
5550
- .eg-pips i.eg-c{background:color-mix(in oklab,var(--eg-primary) 45%,var(--eg-card))}
5551
- .eg-b-t{margin:0;font-size:16px;font-weight:600;line-height:1.45}
5552
- .eg-b-w{margin:2px 0 0;font-size:13.5px;color:var(--eg-muted)}
5553
- .eg-bubble.eg-err .eg-b-t{color:var(--eg-danger)}
5554
- .eg-k{display:inline-block;background:var(--eg-tint);color:var(--eg-strong);border-radius:7px;padding:0 7px;font-weight:600}
5555
- .eg-b-f{display:flex;align-items:center;justify-content:space-between;margin-top:12px;gap:8px}
5556
- .eg-b-f .eg-btn{height:34px;padding:0 14px;font-size:13.5px}
5557
- .eg-exit{border:0;background:none;color:var(--eg-muted);font-size:12.5px;padding:4px 0;text-decoration:underline;text-underline-offset:3px}
5558
- .eg-exit:hover{color:var(--eg-fg)}
5559
- .eg-arrow{position:absolute;width:14px;height:14px;background:var(--eg-card);transform:rotate(45deg);border-radius:2px}
5560
- .eg-arrow.eg-top{background:var(--eg-primary)}
5561
- .eg-bubble.eg-err .eg-arrow.eg-top{background:var(--eg-danger)}
5562
- .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}
5563
- .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}
5564
- .eg-primary{background:var(--eg-primary);color:var(--eg-on-primary)!important}
5565
- .eg-primary:hover{background:var(--eg-strong)}
5566
- .eg-primary[disabled]{opacity:.55;cursor:default}
5567
- .eg-ghost{background:var(--eg-card);border-color:var(--eg-line)}
5568
- .eg-ghost:hover{background:var(--eg-soft)}
5569
- .eg-ghost[disabled]{opacity:.55;cursor:default}
5570
- .eg-link{background:none;border:0;color:var(--eg-muted);font-weight:500;padding:0 6px;height:32px}
5571
- .eg-link:hover{color:var(--eg-fg);text-decoration:underline}
5572
- .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}
5573
- .eg-modal.eg-pop{animation:eg-pop .32s cubic-bezier(.2,.9,.3,1.3)}
5574
- @keyframes eg-pop{from{opacity:0;transform:translate(-50%,-46%) scale(.94)}}
5575
- .eg-modal h2{margin:6px 0 4px;font-size:22px;font-weight:700;letter-spacing:-.2px;line-height:1.3}
5576
- .eg-modal .eg-sub{margin:0;color:var(--eg-muted);font-size:14.5px}
5577
- .eg-eyebrow{margin:0;font-size:12.5px;font-weight:600;letter-spacing:.3px;color:var(--eg-strong)}
5578
- .eg-actions{display:grid;gap:6px;margin-top:20px}
5579
- .eg-actions .eg-btn{height:44px}
5580
- .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)}
5581
- .eg-badge svg.eg-ic{width:30px;height:30px}
5582
- .eg-quests{list-style:none;padding:0;margin:18px 0 0;text-align:left;display:grid;gap:6px}
5583
- .eg-quests li{display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:11px;background:var(--eg-soft);font-size:14px}
5584
- .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}
5585
- .eg-quests li.eg-first{background:var(--eg-tint)}
5586
- .eg-quests li.eg-first .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
5587
- .eg-quests li.eg-ok .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
5588
- .eg-quests li .eg-n svg.eg-ic{width:15px;height:15px;stroke-width:3}
5589
- .eg-quests li .eg-t{flex:1}
5590
- .eg-quests li small{color:var(--eg-muted);font-size:12px;white-space:nowrap}
5591
- .eg-modal.eg-confirm{text-align:left;width:min(380px,calc(100vw - 32px));padding:22px}
5592
- .eg-modal.eg-confirm h2{font-size:18px;margin-top:0}
5593
- .eg-modal.eg-confirm .eg-actions{grid-template-columns:1fr 1fr}
5594
- .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}
5595
- .eg-medal svg.eg-ic{width:42px;height:42px;stroke-width:2.6}
5596
- @keyframes eg-stamp{from{transform:scale(.3) rotate(-25deg);opacity:0}}
5597
- .eg-prog{display:flex;align-items:center;gap:10px;margin-top:16px;font-size:13px;color:var(--eg-muted);font-weight:600}
5598
- .eg-prog .eg-bar{flex:1;height:8px;border-radius:4px;background:var(--eg-soft);overflow:hidden}
5599
- .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}
5600
- .eg-burst{position:absolute;left:50%;top:70px;width:0;height:0;pointer-events:none}
5601
- .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}
5602
- @keyframes eg-conf{0%{opacity:1;transform:translate(0,0) rotate(0)}100%{opacity:0;transform:translate(var(--x),var(--y)) rotate(var(--r))}}
5603
- .eg-card{position:fixed;left:50%;bottom:28px;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}
5604
- .eg-card .eg-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px}
5605
- .eg-loading{display:flex;align-items:center;gap:10px;font-weight:600}
5606
- .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}
5607
- @keyframes eg-spin{to{transform:rotate(360deg)}}
5608
- .eg-chip{position:fixed;right:22px;bottom: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}
5609
- .eg-chip svg{width:34px;height:34px}
5610
- .eg-chip.eg-hi{animation:eg-hi 1.2s ease 2}
5611
- @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)}}
5612
- .eg-panel{position:fixed;right:22px;bottom:82px;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}
5613
- .eg-panel-bd{display:none}
5614
- .eg-q-h{display:flex;align-items:center;gap:10px;padding:16px 12px 4px 18px}
5615
- .eg-q-h h2{margin:0;font-size:16px;font-weight:700;flex:1}
5616
- .eg-q-h .eg-n{font-size:13px;color:var(--eg-muted);font-weight:600}
5617
- .eg-x{width:34px;height:34px;border-radius:10px;border:0;background:none;display:grid;place-items:center;color:var(--eg-muted)}
5618
- .eg-x:hover{background:var(--eg-soft)}
5619
- .eg-x svg.eg-ic{width:18px;height:18px}
5620
- .eg-panel .eg-prog{margin:6px 18px 8px}
5621
- .eg-q-list{list-style:none;margin:0;padding:4px 10px 6px;display:grid;gap:2px}
5622
- .eg-q-item{display:flex;align-items:center;gap:12px;padding:10px 8px;border-radius:11px}
5623
- .eg-q-item.eg-next{background:var(--eg-tint)}
5624
- .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)}
5625
- .eg-q-item.eg-next .eg-n{border-color:var(--eg-primary);color:var(--eg-strong)}
5626
- .eg-q-item.eg-done .eg-n{background:var(--eg-ok);border-color:var(--eg-ok);color:#fff}
5627
- .eg-q-item.eg-done .eg-n svg.eg-ic{width:16px;height:16px;stroke-width:3}
5628
- .eg-q-item.eg-dim .eg-n{opacity:.55}
5629
- .eg-q-item.eg-just .eg-n{animation:eg-stamp .55s cubic-bezier(.2,.9,.3,1.4) .2s both}
5630
- .eg-q-item .eg-t{flex:1;min-width:0}
5631
- .eg-q-item .eg-t b{display:block;font-size:14px;font-weight:600}
5632
- .eg-q-item.eg-done .eg-t b{color:var(--eg-muted)}
5633
- .eg-q-item .eg-t small{display:block;font-size:12px;color:var(--eg-muted)}
5634
- .eg-q-item .eg-t small.eg-sk{color:#b06a00}
5635
- .eg-q-item .eg-t small.eg-lock{color:var(--eg-fg);font-weight:500}
5636
- .eg-q-item .eg-btn{height:32px;padding:0 12px;font-size:13px}
5637
- .eg-q-acts{display:flex;flex-direction:column;align-items:flex-end;gap:2px}
5638
- .eg-q-acts .eg-link{height:22px;font-size:12px;padding:0 2px}
5639
- .eg-q-f{border-top:1px solid var(--eg-line);padding:8px 12px;display:flex;justify-content:flex-end}
5640
- .eg-toast{position:fixed;left:50%;bottom:84px;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}
5641
- svg.eg-ic{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex:none}
5642
- @media (max-width:767px){
5643
- .eg-bubble{width:auto}
5644
- .eg-arrow{display:none}
5645
- .eg-modal{top:auto;bottom:12px;transform:translateX(-50%);width:calc(100vw - 24px);padding:24px 20px 18px}
5646
- .eg-modal.eg-pop{animation:eg-up .3s cubic-bezier(.2,.9,.3,1.1)}
5647
- .eg-modal .eg-actions .eg-btn{height:46px}
5648
- .eg-chip{right:16px;bottom:calc(16px + env(safe-area-inset-bottom))}
5649
- .eg-panel-bd{display:block;position:fixed;inset:0;background:rgba(15,23,42,.38);pointer-events:auto}
5650
- .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)}
5651
- .eg-q-item{padding:12px 8px}
5652
- .eg-card{bottom:calc(12px + env(safe-area-inset-bottom))}
5653
- .eg-toast{bottom:calc(76px + env(safe-area-inset-bottom))}
5654
- }
5655
- @keyframes eg-up{from{opacity:0;transform:translate(-50%,30px)}}
5656
- @media (prefers-reduced-motion:reduce){
5657
- [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}
5658
- .eg-ring::after{animation:none!important;opacity:1;transform:none}
5659
- .eg-ring.eg-flash::after{animation:eg-flash .5s ease 1!important;animation-duration:.5s!important}
5660
- .eg-hand{animation:none!important;transform:translate(4px,6px)}
5661
- .eg-burst{display:none}
5662
- .eg-bubble.eg-nudge{animation:none!important;border-top-color:var(--eg-danger)}
5663
- }
5664
- `;
5665
-
5666
- /* ------------------------------------------------------------------ */
5667
- /* Bits */
5668
- /* ------------------------------------------------------------------ */
5669
- const TH_MONTHS = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
5670
- const pad2 = (n) => String(n).padStart(2, "0");
5671
- /** "26 ต.ค. 2569 13:04" — day, month, Buddhist year, 24 h. */
5672
- function formatThaiDateTime(iso) {
5673
- if (!iso)
5674
- return "";
5675
- const d = new Date(iso);
5676
- if (Number.isNaN(d.getTime()))
5677
- return "";
5678
- return `${d.getDate()} ${TH_MONTHS[d.getMonth()]} ${d.getFullYear() + 543} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
5679
- }
5680
- /** "กด [บันทึก]": the bracketed word is a chip in the brand colour. */
5681
- function GuideTitle({ text }) {
5682
- const parts = text.split(/(\[[^\]]+\])/g).filter(Boolean);
5683
- return (jsx(Fragment$1, { children: parts.map((p, i) => p.startsWith("[") && p.endsWith("]") ? (jsx("span", { className: "eg-k", children: p.slice(1, -1) }, i)) : (jsx(React.Fragment, { children: p }, i))) }));
5684
- }
5685
- const Svg = ({ children, className = "eg-ic" }) => (jsx("svg", { className: className, viewBox: "0 0 24 24", "aria-hidden": "true", children: children }));
5686
- const IconCheck = () => (jsx(Svg, { children: jsx("path", { d: "M20 6 9 17l-5-5" }) }));
5687
- const IconX = () => (jsx(Svg, { children: jsx("path", { d: "M18 6 6 18M6 6l12 12" }) }));
5688
- const IconFlag = () => (jsxs(Svg, { children: [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" }), jsx("path", { d: "M4 22v-7" })] }));
5689
- const IconTrophy = () => (jsx(Svg, { children: 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" }) }));
5690
- 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";
5691
- /** Rounded-rectangle subpath for the scrim's holes. */
5692
- function roundRect(r, radius) {
5693
- const rad = Math.max(0, Math.min(radius, r.width / 2, r.height / 2));
5694
- const { x, y, width: w, height: h } = r;
5695
- return (`M${x + rad} ${y}H${x + w - rad}A${rad} ${rad} 0 0 1 ${x + w} ${y + rad}` +
5696
- `V${y + h - rad}A${rad} ${rad} 0 0 1 ${x + w - rad} ${y + h}` +
5697
- `H${x + rad}A${rad} ${rad} 0 0 1 ${x} ${y + h - rad}` +
5698
- `V${y + rad}A${rad} ${rad} 0 0 1 ${x + rad} ${y}Z`);
5699
- }
5700
- const rectPath = (r) => `M${r.x} ${r.y}H${r.x + r.width}V${r.y + r.height}H${r.x}Z`;
5701
- /**
5702
- * The dim layer that eats every press outside the holes. The holes are a
5703
- * union: where two overlap (a field and the select list open over it) the
5704
- * page stays open.
5705
- *
5706
- * - The look: one rectangle masked by the rounded holes (a mask adds holes
5707
- * up, so an overlap is not filled back in).
5708
- * - The presses: a transparent path made of the screen minus the holes, as
5709
- * rectangles that do not overlap (blockedRects). A press inside a hole
5710
- * reaches the page underneath; any other lands on the path (marked
5711
- * data-eg-block) and is cancelled.
5712
- * - `open`: the holes a press may go through, when not all of them (a "view"
5713
- * step's target is shown but not pressable). Default: every hole.
5714
- */
5715
- function Scrim({ holes, open, width, height }) {
5716
- const maskId = "eg-scrim-mask-" + React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
5717
- const block = blockedRects(open ?? holes, width, height).map(rectPath).join("");
5718
- return (jsxs("svg", { className: "eg-scrim-svg", width: width, height: height, "aria-hidden": "true", children: [holes.length ? (jsx("defs", { children: jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: -10, y: -10, width: width + 20, height: height + 20, children: [jsx("rect", { x: -10, y: -10, width: width + 20, height: height + 20, fill: "#fff" }), holes.map((h, i) => (jsx("path", { d: roundRect(h, 12), fill: "#000" }, i)))] }) })) : null, jsx("rect", { className: "eg-scrim-fill", x: -10, y: -10, width: width + 20, height: height + 20, mask: holes.length ? `url(#${maskId})` : undefined }), jsx("path", { className: "eg-scrim-hit", d: block, "data-eg-block": "" })] }));
5719
- }
5720
- /** Whether two rectangles overlap. */
5721
- const meets = (a, b) => !!intersectRect(a, b);
5722
- /** The smallest rectangle around all of them. */
5723
- function boundingRect(rs) {
5724
- const x = Math.min(...rs.map(r => r.x));
5725
- const y = Math.min(...rs.map(r => r.y));
5726
- const right = Math.max(...rs.map(r => r.x + r.width));
5727
- const bottom = Math.max(...rs.map(r => r.y + r.height));
5728
- return { x, y, width: right - x, height: bottom - y };
5729
- }
5730
- /** Where the bubble may go, in order of preference. */
5731
- const BUBBLE_PLACEMENTS = ["right", "bottom", "top", "left"];
5732
- /**
5733
- * The first placement (in BUBBLE_PLACEMENTS order) whose bubble is on screen,
5734
- * off the target (with its open list), and off everything to keep clear;
5735
- * failing that, the first that is only on screen and off the target; -1 when
5736
- * none is.
5737
- */
5738
- function pickPlacement(results, bw, bh, anchor, clear, bounds) {
5739
- const box = (r) => ({ x: r.x, y: r.y, width: bw, height: bh });
5740
- 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;
5741
- const ok = results.map(r => {
5742
- const b = box(r);
5743
- return fits(b) && !meets(b, anchor);
5744
- });
5745
- const best = results.findIndex((r, i) => ok[i] && !clear.some(c => meets(box(r), c)));
5746
- return best >= 0 ? best : ok.indexOf(true);
5747
- }
5748
- const BUBBLE_TITLE_ID = "eg-bubble-title";
5749
- const BUBBLE_WHY_ID = "eg-bubble-why";
5750
- function useNudge(nudge, ref) {
5751
- const first = useRef(nudge);
5752
- useEffect(() => {
5753
- if (nudge === first.current)
5754
- return;
5755
- const el = ref.current;
5756
- if (!el)
5757
- return;
5758
- el.classList.remove("eg-nudge");
5759
- void el.offsetWidth;
5760
- el.classList.add("eg-nudge");
5761
- }, [nudge, ref]);
5762
- }
5763
- function StepLayer(p) {
5764
- const { spot, phone, viewport } = p;
5765
- const bubbleRef = useRef(null);
5766
- const arrowRef = useRef(null);
5767
- const ringRef = useRef(null);
5768
- const [pos, setPos] = useState(null);
5769
- useNudge(p.nudge, bubbleRef);
5770
- // Flash the ring with each nudge too (a press outside the hole).
5771
- const firstNudge = useRef(p.nudge);
5772
- useEffect(() => {
5773
- if (p.nudge === firstNudge.current)
5774
- return;
5775
- const el = ringRef.current;
5776
- if (!el)
5777
- return;
5778
- el.classList.remove("eg-flash");
5779
- void el.offsetWidth;
5780
- el.classList.add("eg-flash");
5781
- }, [p.nudge]);
5782
- const showBubble = p.phase === "ready" && (!!spot || !p.hasTarget);
5783
- const gap = p.showHand ? 34 : 14;
5784
- const spotKey = spot ? `${spot.x}|${spot.y}|${spot.width}|${spot.height}` : "";
5785
- const contentKey = `${p.bubble.title}|${p.bubble.why}|${p.bubble.error?.title ?? ""}|${p.bubble.showNext}`;
5786
- // What the bubble sits beside: the target, with an open list over it (the
5787
- // list is what the person is choosing from now). What it must not cover:
5788
- // open lists, and the other anchors the step allows (a map step's
5789
- // coordinate fields).
5790
- const popoverList = p.popovers ?? [];
5791
- const anchor = spot ? boundingRect([spot, ...popoverList.filter(o => meets(o, spot))]) : null;
5792
- const clear = [...popoverList, ...p.holes];
5793
- const anchorKey = anchor ? `${anchor.x}|${anchor.y}|${anchor.width}|${anchor.height}` : "";
5794
- const clearKey = clear.map(r => `${r.x},${r.y},${r.width},${r.height}`).join(";");
5795
- useLayoutEffect(() => {
5796
- const el = bubbleRef.current;
5797
- if (!el || !showBubble)
5798
- return;
5799
- const m = 16;
5800
- if (!spot || !anchor) {
5801
- // Nothing to point at: the middle of the screen (the bottom on a phone).
5802
- const bw = el.offsetWidth;
5803
- const bh = el.offsetHeight;
5804
- setPos(phone
5805
- ? { left: m, top: viewport.offsetTop + viewport.height - bh - m, side: "dock" }
5806
- : { left: (window.innerWidth - bw) / 2, top: viewport.offsetTop + (viewport.height - bh) / 2, side: "dock" });
5807
- return;
5808
- }
5809
- if (phone) {
5810
- // Docked to the top or the bottom of the screen, whichever covers less
5811
- // of the target and its open list (target in the lower half: top).
5812
- const vh = viewport.height;
5813
- const oy = viewport.offsetTop;
5814
- const bh = el.offsetHeight;
5815
- const topT = oy + m + 4;
5816
- const botT = oy + vh - bh - m;
5817
- const { y, height: h } = anchor;
5818
- const overlapTop = Math.max(0, topT + bh + 8 - y);
5819
- const overlapBot = Math.max(0, y + h + gap - botT);
5820
- const top = y + h / 2 > vh / 2
5821
- ? overlapTop <= overlapBot
5822
- ? topT
5823
- : botT
5824
- : overlapBot <= overlapTop
5825
- ? botT
5826
- : topT;
5827
- setPos({ left: m, top, side: "dock" });
5828
- return;
5829
- }
5830
- let cancelled = false;
5831
- const a = anchor;
5832
- const ref = {
5833
- getBoundingClientRect: () => ({
5834
- x: a.x,
5835
- y: a.y,
5836
- left: a.x,
5837
- top: a.y,
5838
- width: a.width,
5839
- height: a.height,
5840
- right: a.x + a.width,
5841
- bottom: a.y + a.height,
5842
- }),
5843
- };
5844
- const at = (placement) => computePosition(ref, el, {
5845
- strategy: "fixed",
5846
- placement,
5847
- middleware: [
5848
- offset(placement.startsWith("bottom") ? gap : 14),
5849
- shift({ padding: m }),
5850
- ...(arrowRef.current ? [arrow({ element: arrowRef.current, padding: 14 })] : []),
5851
- ],
5852
- });
5853
- Promise.all(BUBBLE_PLACEMENTS.map(at))
5854
- .then(results => {
5855
- if (cancelled)
5856
- return;
5857
- const bw = el.offsetWidth;
5858
- const bh = el.offsetHeight;
5859
- const bounds = { x: m, y: viewport.offsetTop + m, width: window.innerWidth - 2 * m, height: viewport.height - 2 * m };
5860
- const i = pickPlacement(results, bw, bh, a, clear, bounds);
5861
- if (i < 0) {
5862
- // Nowhere beside it: the bottom-right corner.
5863
- setPos({ left: window.innerWidth - bw - m, top: viewport.height + viewport.offsetTop - bh - m, side: "dock" });
5864
- return;
5865
- }
5866
- const { x, y, placement, middlewareData } = results[i];
5867
- const side = placement.split("-")[0];
5868
- setPos({ left: x, top: y, side, ax: middlewareData.arrow?.x, ay: middlewareData.arrow?.y });
5869
- })
5870
- .catch(() => {
5871
- if (!cancelled)
5872
- setPos({ left: m, top: m, side: "dock" });
5873
- });
5874
- return () => {
5875
- cancelled = true;
5876
- };
5877
- // The keys stand for spot, the lists, the holes and the bubble's size.
5878
- // eslint-disable-next-line react-hooks/exhaustive-deps
5879
- }, [spotKey, anchorKey, clearKey, contentKey, phone, showBubble, gap, viewport.height, viewport.offsetTop]);
5880
- const popovers = p.popovers ?? [];
5881
- const covered = !!p.covered;
5882
- const holes = [...(spot && !covered ? [spot] : []), ...popovers, ...p.holes];
5883
- const openHoles = p.targetPressable === false ? [...popovers, ...p.holes] : holes;
5884
- const ringShown = !!spot && p.phase === "ready" && !covered && !popovers.some(o => meets(o, spot));
5885
- const hand = spot && p.showHand && p.phase === "ready" && !covered && !popovers.length ? handPosition(spot, viewport.height) : null;
5886
- let arrowStyle;
5887
- if (pos && pos.side !== "dock") {
5888
- if (pos.side === "right")
5889
- arrowStyle = { left: -7, top: pos.ay };
5890
- else if (pos.side === "left")
5891
- arrowStyle = { right: -7, top: pos.ay };
5892
- else if (pos.side === "bottom")
5893
- arrowStyle = { top: -9, left: pos.ax };
5894
- else
5895
- arrowStyle = { bottom: -7, left: pos.ax };
5896
- }
5897
- return (jsxs(Fragment$1, { children: [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 ? (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 ? (jsx("div", { className: "eg-hand" + (hand.flip ? " eg-flip" : ""), style: { left: hand.left, top: hand.top }, "aria-hidden": "true", children: jsx("svg", { viewBox: "0 0 24 24", children: jsx("path", { d: HAND_PATH }) }) })) : null, showBubble ? (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: {
5898
- left: pos?.left ?? 0,
5899
- top: pos?.top ?? 0,
5900
- width: phone ? viewport.width - 32 : undefined,
5901
- visibility: pos ? "visible" : "hidden",
5902
- }, children: [jsx(BubbleBody, { ...p }), jsx("span", { ref: arrowRef, className: "eg-arrow" + (pos?.side === "bottom" ? " eg-top" : ""), style: arrowStyle ?? { display: "none" }, "aria-hidden": "true" })] })) : null, p.phase === "waiting" ? (jsxs("div", { className: "eg-card", role: "status", "data-eg-card": "", children: [jsxs("div", { className: "eg-loading", children: [jsx("span", { className: "eg-spin", "aria-hidden": "true" }), "\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14\u2026"] }), jsx("div", { className: "eg-row", children: jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }) })] })) : null, p.phase === "missing" ? (jsxs("div", { className: "eg-card eg-err", role: "alertdialog", "aria-labelledby": "eg-missing-t", "data-eg-card": "", tabIndex: -1, children: [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" }), jsxs("div", { className: "eg-row", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), 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" ? (jsxs("div", { className: "eg-card", role: "dialog", "aria-modal": "false", "aria-labelledby": "eg-away-t", "data-eg-card": "", tabIndex: -1, children: [jsxs("div", { className: "eg-b-top", children: [jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.bubble.missionNo, " \u00B7 ", p.bubble.missionTitle, p.bubble.replay ? " (ทบทวน)" : ""] }), jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", p.bubble.index + 1, "/", p.bubble.total] })] }), jsx("p", { className: "eg-b-t", id: "eg-away-t", style: { marginTop: 8 }, children: jsx(GuideTitle, { text: p.bubble.title }) }), jsxs("div", { className: "eg-row", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: p.bubble.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onGoResume, children: "\u0E17\u0E33\u0E15\u0E48\u0E2D" })] })] })) : null, p.confirmExit ? (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] }));
5903
- }
5904
- function BubbleBody(p) {
5905
- const b = p.bubble;
5906
- const title = b.error ? b.error.title : b.title;
5907
- const why = b.error ? (b.error.detail ?? "") : b.why;
5908
- return (jsxs(Fragment$1, { children: [jsxs("div", { className: "eg-b-top", children: [jsxs("span", { className: "eg-mis", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", b.missionNo, " \u00B7 ", b.missionTitle, b.replay ? " (ทบทวน)" : ""] }), jsxs("span", { className: "eg-cnt", children: ["\u0E02\u0E31\u0E49\u0E19\u0E17\u0E35\u0E48 ", b.index + 1, "/", b.total] })] }), jsx("div", { className: "eg-pips", "aria-hidden": "true", children: Array.from({ length: b.total }, (_, i) => (jsx("i", { className: i < b.index ? "eg-d" : i === b.index ? "eg-c" : undefined }, i))) }), jsx("p", { className: "eg-b-t", id: BUBBLE_TITLE_ID, children: jsx(GuideTitle, { text: title }) }), jsx("p", { className: "eg-b-w", id: BUBBLE_WHY_ID, hidden: !why, children: jsx(GuideTitle, { text: why }) }), jsxs("div", { className: "eg-b-f", children: [jsx("button", { type: "button", className: "eg-exit", onClick: p.onExit, children: b.replay ? "จบการทบทวน" : "ออกจากไกด์" }), jsxs("span", { style: { display: "flex", gap: 6 }, children: [b.showEndWithoutSave ? (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 ? (jsx("button", { type: "button", className: "eg-btn eg-primary", onClick: p.onNext, children: "\u0E16\u0E31\u0E14\u0E44\u0E1B" })) : null] })] })] }));
5909
- }
5910
- /** The fingertip at ≈62% across and down the target; upside down near the bottom. */
5911
- function handPosition(spot, viewportHeight) {
5912
- const { x, y, width: w, height: h } = spot;
5913
- const px = x + Math.min(w * 0.62, w - 14);
5914
- const py = y + h * 0.62;
5915
- const flip = py + 50 > viewportHeight;
5916
- return { left: px - 11.5, top: flip ? py - h * 0.3 - 42 : py - 4, flip };
5917
- }
5918
- /* ------------------------------------------------------------------ */
5919
- /* Modals */
5920
- /* ------------------------------------------------------------------ */
5921
- function useAutoFocus() {
5922
- const ref = useRef(null);
5923
- useEffect(() => {
5924
- ref.current?.focus({ preventScroll: true });
5925
- }, []);
5926
- return ref;
5927
- }
5928
- function ConfirmModal(p) {
5929
- const stay = useAutoFocus();
5930
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim eg-faint", "data-eg-block": "", onClick: p.onStay }), 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: [jsx("h2", { id: "eg-c-t", children: p.title }), jsx("p", { className: "eg-sub", id: "eg-c-d", style: { fontSize: 14 }, children: p.line }), jsxs("div", { className: "eg-actions", children: [jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: p.onLeave, children: p.leaveLabel }), jsx("button", { type: "button", ref: stay, className: "eg-btn eg-primary", onClick: p.onStay, children: p.stayLabel })] })] })] }));
5931
- }
5932
- function WelcomeModal(p) {
5933
- const start = useAutoFocus();
5934
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-w-t", "data-eg-modal": "", tabIndex: -1, children: [jsx("div", { className: "eg-badge", children: jsx(IconFlag, {}) }), jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsx("h2", { id: "eg-w-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxs("li", { className: i === 0 ? "eg-first" : undefined, children: [jsx("span", { className: "eg-n", children: i + 1 }), jsx("span", { className: "eg-t", children: m.title }), jsxs("small", { children: [m.minutes, " \u0E19\u0E32\u0E17\u0E35"] })] }, i))) }), jsxs("div", { className: "eg-actions", children: [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" }), 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 ? (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] }));
5935
- }
5936
- function GateModal(p) {
5937
- const go = useAutoFocus();
5938
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-g-t", "data-eg-modal": "", tabIndex: -1, children: [jsx("div", { className: "eg-badge", children: jsx(IconFlag, {}) }), jsx("p", { className: "eg-eyebrow", children: "\u0E44\u0E01\u0E14\u0E4C\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsx("h2", { id: "eg-g-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsxs("div", { className: "eg-actions", children: [jsx("a", { ref: go, className: "eg-btn eg-primary", href: p.href, style: { textDecoration: "none" }, children: p.actionLabel }), jsx("button", { type: "button", className: "eg-btn eg-link", onClick: p.onLater, children: "\u0E44\u0E27\u0E49\u0E17\u0E35\u0E2B\u0E25\u0E31\u0E07" })] })] })] }));
5939
- }
5940
- const CONFETTI_COLOURS = ["#3b82f6", "#7db7ff", "#e6a417", "#ff7a6b", "#1d9a5f", "#b0d2ff"];
5941
- function Confetti({ reduced }) {
5942
- // Fixed per mount, so a re-render does not throw new pieces.
5943
- const [pieces] = useState(() => Array.from({ length: 26 }, (_, i) => {
5944
- const a = (Math.PI * 2 * i) / 26 + Math.random() * 0.3;
5945
- const dist = 90 + Math.random() * 90;
5946
- return {
5947
- background: CONFETTI_COLOURS[i % CONFETTI_COLOURS.length],
5948
- "--x": `${Math.cos(a) * dist}px`,
5949
- "--y": `${Math.sin(a) * dist + 40}px`,
5950
- "--r": `${Math.random() * 540 - 270}deg`,
5951
- animationDelay: `${Math.random() * 0.12}s`,
5952
- };
5953
- }));
5954
- if (reduced)
5955
- return null;
5956
- return (jsx("div", { className: "eg-burst", "aria-hidden": "true", children: pieces.map((s, i) => (jsx("span", { style: s }, i))) }));
5957
- }
5958
- function ProgressBar({ from, to, total, label }) {
5959
- const [width, setWidth] = useState(total ? (from / total) * 100 : 0);
5960
- useEffect(() => {
5961
- // Two frames so the bar is drawn at `from` before it runs to `to`.
5962
- let raf2 = 0;
5963
- const raf1 = requestAnimationFrame(() => {
5964
- raf2 = requestAnimationFrame(() => setWidth(total ? (to / total) * 100 : 0));
5965
- });
5966
- return () => {
5967
- cancelAnimationFrame(raf1);
5968
- cancelAnimationFrame(raf2);
5969
- };
5970
- }, [to, total]);
5971
- return (jsxs("div", { className: "eg-prog", children: [jsx("div", { className: "eg-bar", children: jsx("i", { style: { width: `${width}%` } }) }), jsx("span", { children: label })] }));
5972
- }
5973
- function CelebrateModal(p) {
5974
- const primary = useAutoFocus();
5975
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim eg-light", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-cel-t", "data-eg-modal": "", tabIndex: -1, children: [jsx(Confetti, { reduced: p.reduced }), jsx("div", { className: "eg-medal", children: jsx(IconCheck, {}) }), jsxs("p", { className: "eg-eyebrow", children: ["\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08 ", p.missionNo, " \u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08"] }), jsx("h2", { id: "eg-cel-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx(ProgressBar, { from: p.reduced ? p.done : Math.max(0, p.done - 1), to: p.done, total: p.total, label: `${p.done}/${p.total} ภารกิจ` }), jsxs("div", { className: "eg-actions", children: [p.nextTitle ? (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, 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" })] })] })] }));
5976
- }
5977
- function CompleteModal(p) {
5978
- const primary = useAutoFocus();
5979
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-scrim", "data-eg-block": "" }), jsxs("div", { className: "eg-modal eg-pop", role: "dialog", "aria-modal": "true", "aria-labelledby": "eg-f-t", "data-eg-modal": "", tabIndex: -1, children: [jsx(Confetti, { reduced: p.reduced }), jsx("div", { className: "eg-medal", children: jsx(IconTrophy, {}) }), jsxs("p", { className: "eg-eyebrow", children: ["\u0E04\u0E23\u0E1A ", p.total, " \u0E20\u0E32\u0E23\u0E01\u0E34\u0E08"] }), jsx("h2", { id: "eg-f-t", children: p.title }), p.subtitle ? jsx("p", { className: "eg-sub", children: p.subtitle }) : null, jsx("ol", { className: "eg-quests", children: p.missions.map((m, i) => (jsxs("li", { className: "eg-ok", children: [jsx("span", { className: "eg-n", children: jsx(IconCheck, {}) }), jsx("span", { className: "eg-t", children: m })] }, i))) }), jsxs("div", { className: "eg-actions", children: [jsx("button", { type: "button", ref: primary, className: "eg-btn eg-primary", onClick: p.onFinish, children: p.actionLabel }), p.secondary ? (jsx("a", { className: "eg-btn eg-ghost", href: p.secondary.href, style: { textDecoration: "none" }, children: p.secondary.label })) : null] })] })] }));
5980
- }
5981
- /* ------------------------------------------------------------------ */
5982
- /* Quest chip and panel */
5983
- /* ------------------------------------------------------------------ */
5984
- function QuestChip({ done, total, pulse, onOpen }) {
5985
- const ref = useRef(null);
5986
- const first = useRef(pulse);
5987
- useEffect(() => {
5988
- if (pulse === first.current)
5989
- return;
5990
- const el = ref.current;
5991
- if (!el)
5992
- return;
5993
- el.classList.remove("eg-hi");
5994
- void el.offsetWidth;
5995
- el.classList.add("eg-hi");
5996
- }, [pulse]);
5997
- const C = 2 * Math.PI * 14;
5998
- const pct = total ? done / total : 0;
5999
- return (jsxs("button", { ref: ref, type: "button", className: "eg-chip", onClick: onOpen, "aria-label": `ภารกิจเริ่มต้น เสร็จ ${done} จาก ${total}`, children: [jsxs("svg", { viewBox: "0 0 34 34", "aria-hidden": "true", children: [jsx("circle", { cx: "17", cy: "17", r: "14", fill: "none", stroke: "var(--eg-soft)", strokeWidth: "4" }), done ? (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] }));
6000
- }
6001
- function QuestPanel(p) {
6002
- const ref = useAutoFocus();
6003
- return (jsxs(Fragment$1, { children: [jsx("div", { className: "eg-panel-bd", onClick: p.onClose }), jsxs("section", { ref: ref, className: "eg-panel", role: "dialog", "aria-labelledby": "eg-q-t", tabIndex: -1, "data-eg-panel": "", children: [jsxs("div", { className: "eg-q-h", children: [jsx("h2", { id: "eg-q-t", children: "\u0E20\u0E32\u0E23\u0E01\u0E34\u0E08\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19" }), jsxs("span", { className: "eg-n", children: [p.done, "/", p.total] }), jsx("button", { type: "button", className: "eg-x", onClick: p.onClose, "aria-label": "\u0E1B\u0E34\u0E14", children: jsx(IconX, {}) })] }), jsx("div", { className: "eg-prog", children: jsx("div", { className: "eg-bar", children: jsx("i", { style: { width: `${p.total ? (p.done / p.total) * 100 : 0}%` } }) }) }), jsx("ol", { className: "eg-q-list", children: p.items.map((it, i) => (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 ? (jsx("div", { className: "eg-q-f", children: 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] })] }));
6004
- }
6005
- function QuestRow({ item, n, just, gate, onStart, onDismiss, }) {
6006
- const v = item.view;
6007
- const ticked = v === "done" || v === "already";
6008
- const cls = "eg-q-item" +
6009
- (ticked ? " eg-done" : v === "next" ? " eg-next" : "") +
6010
- (v === "locked" || v === "waiting" ? " eg-dim" : "") +
6011
- (just ? " eg-just" : "");
6012
- let meta = `ประมาณ ${item.minutes} นาที`;
6013
- if (v === "done")
6014
- meta = item.completedAt ? `เสร็จ ${formatThaiDateTime(item.completedAt)}` : "เสร็จแล้ว";
6015
- else if (v === "already")
6016
- meta = "ทำไว้แล้ว";
6017
- else if (v === "skipped")
6018
- meta = jsx("span", { children: "\u0E02\u0E49\u0E32\u0E21\u0E44\u0E27\u0E49" });
6019
- else if (v === "waiting" && gate)
6020
- meta = gate.pending;
6021
- // Locked: what to do first gets its own line under the title, so the title
6022
- // keeps the row's width and the button stays short.
6023
- const lockHint = v === "locked" && item.lockedBy ? `ทำ ${item.lockedBy} ก่อน` : null;
6024
- let button;
6025
- if (v === "done")
6026
- button = jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E17\u0E33\u0E0B\u0E49\u0E33" });
6027
- else if (v === "already")
6028
- button = jsx("button", { type: "button", className: "eg-btn eg-ghost", onClick: () => onStart(item.key, true), children: "\u0E14\u0E39\u0E27\u0E34\u0E18\u0E35\u0E17\u0E33" });
6029
- else if (v === "waiting" && gate)
6030
- button = (jsx("a", { className: "eg-btn eg-ghost", href: gate.href, style: { textDecoration: "none" }, children: gate.label }));
6031
- else if (v === "locked")
6032
- button = (jsx("button", { type: "button", className: "eg-btn eg-ghost", disabled: true, "aria-label": lockHint ? `เริ่ม (${lockHint})` : undefined, children: "\u0E40\u0E23\u0E34\u0E48\u0E21" }));
6033
- else
6034
- button = (jsx("button", { type: "button", className: "eg-btn " + (v === "next" ? "eg-primary" : "eg-ghost"), onClick: () => onStart(item.key, false), children: v === "skipped" || v === "active" ? "ทำต่อ" : "เริ่ม" }));
6035
- const dismissable = item.optional && (v === "todo" || v === "next");
6036
- return (jsxs("li", { className: cls, children: [jsx("span", { className: "eg-n", children: ticked ? jsx(IconCheck, {}) : n }), jsxs("div", { className: "eg-t", children: [jsx("b", { children: item.title }), lockHint ? jsx("small", { className: "eg-lock", children: lockHint }) : null, jsx("small", { className: v === "skipped" ? "eg-sk" : undefined, children: meta })] }), dismissable ? (jsxs("span", { className: "eg-q-acts", children: [button, 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)] }));
6037
- }
6038
- function GuideToast({ text }) {
6039
- return (jsx("div", { className: "eg-toast", role: "status", children: text }));
6040
- }
6041
-
6042
- const EMPLOYEE_RECORD_REQUIRED = "EMPLOYEE_RECORD_REQUIRED";
6043
- const EMPLOYEE_RECORD_REQUIRED_EVENT = "erp:employee-record-required";
6044
- const EMPLOYEE_RECORD_OK_EVENT = "erp:employee-record-ok";
6045
- /**
6046
- * Shown when the API refuses every request because the signed-in account has
6047
- * no employee record in this organisation.
6048
- *
6049
- * A gate rather than a banner. Leave, attendance, approvals and payslips all
6050
- * identify a person by that record, so once the server started enforcing it
6051
- * every call fails — and without something that says so, the app becomes a
6052
- * screen of error toasts with no explanation and no way forward.
6053
- */
6054
- function EmployeeRequiredGate({ platformBaseUrl, }) {
6055
- const [blocked, setBlocked] = useState(false);
6056
- const params = useParams();
6057
- const code = params?.code ?? "";
6058
- useEffect(() => {
6059
- const onBlocked = () => setBlocked(true);
6060
- const onOk = () => setBlocked(false);
6061
- window.addEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
6062
- window.addEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
6063
- return () => {
6064
- window.removeEventListener(EMPLOYEE_RECORD_REQUIRED_EVENT, onBlocked);
6065
- window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, onOk);
6066
- };
6067
- }, []);
6068
- if (!blocked)
6069
- return null;
6070
- const base = platformBaseUrl?.replace(/\/$/, "") ?? "";
6071
- const createHref = code ? `${base}/${code}/employee/create` : `${base}/`;
6072
- return (jsx("div", { className: "fixed inset-0 z-[100] flex items-center justify-center bg-background/95 p-6 backdrop-blur-sm", children: jsxs("div", { className: "w-full max-w-md space-y-5 text-center", children: [jsx(ContactRound, { className: "mx-auto h-12 w-12 text-muted-foreground" }), jsxs("div", { className: "space-y-2", children: [jsx("h1", { className: "text-lg font-semibold tracking-tight", children: "\u0E1A\u0E31\u0E0D\u0E0A\u0E35\u0E19\u0E35\u0E49\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E1C\u0E39\u0E01\u0E01\u0E31\u0E1A\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19" }), jsx("p", { className: "text-sm text-muted-foreground", children: "\u0E25\u0E32 \u0E25\u0E07\u0E40\u0E27\u0E25\u0E32 \u0E40\u0E1A\u0E34\u0E01\u0E40\u0E07\u0E34\u0E19 \u0E41\u0E25\u0E30\u0E01\u0E32\u0E23\u0E2D\u0E19\u0E38\u0E21\u0E31\u0E15\u0E34 \u0E23\u0E30\u0E1A\u0E38\u0E15\u0E31\u0E27\u0E04\u0E19\u0E08\u0E32\u0E01\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19 \u0E08\u0E36\u0E07\u0E22\u0E31\u0E07\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19\u0E43\u0E19\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49" })] }), jsxs("div", { className: "flex flex-wrap justify-center gap-2", children: [jsx(Button, { onClick: () => window.location.reload(), children: "\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48" }), jsx(Button, { variant: "outline", asChild: true, children: jsxs("a", { href: createHref, children: [jsx(UserPlus, { className: "mr-1 h-4 w-4" }), "\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E1E\u0E19\u0E31\u0E01\u0E07\u0E32\u0E19"] }) })] }), jsx("p", { className: "text-xs text-muted-foreground", children: "\u0E16\u0E49\u0E32\u0E04\u0E38\u0E13\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E41\u0E01\u0E49\u0E44\u0E02 \u0E43\u0E2B\u0E49\u0E41\u0E08\u0E49\u0E07\u0E1C\u0E39\u0E49\u0E14\u0E39\u0E41\u0E25\u0E2D\u0E07\u0E04\u0E4C\u0E01\u0E23" })] }) }));
6073
- }
6074
-
6075
- /* ------------------------------------------------------------------ */
6076
- /* Fail-open wrappers */
6077
- /* ------------------------------------------------------------------ */
6078
- class GuideErrorBoundary extends React.Component {
6079
- constructor() {
6080
- super(...arguments);
6081
- Object.defineProperty(this, "state", {
6082
- enumerable: true,
6083
- configurable: true,
6084
- writable: true,
6085
- value: { failed: false }
6086
- });
6087
- }
6088
- static getDerivedStateFromError() {
6089
- return { failed: true };
6090
- }
6091
- componentDidCatch(error) {
6092
- if (typeof console !== "undefined")
6093
- console.warn("[erp-shell guide] hidden after an error", error);
6094
- try {
6095
- publishGuideEntry(null, null);
6096
- }
6097
- catch {
6098
- /* ignore */
6099
- }
6100
- }
6101
- render() {
6102
- return this.state.failed ? null : this.props.children;
6103
- }
6104
- }
6105
- function GuideHost(props) {
6106
- return (jsx(GuideErrorBoundary, { children: jsx(Suspense, { fallback: null, children: jsx(GuideHostInner, { ...props }) }) }));
6107
- }
6108
- let fallbackClient = null;
6109
- function useShellQueryClient() {
6110
- const provided = useContext(QueryClientContext);
6111
- if (provided)
6112
- return provided;
6113
- fallbackClient ?? (fallbackClient = new QueryClient());
6114
- return fallbackClient;
6115
- }
6116
- /* ------------------------------------------------------------------ */
6117
- /* Session mirror (instant resume after F5) */
6118
- /* ------------------------------------------------------------------ */
6119
- const mirrorKey = (orgId, suite) => `erp-guide:${orgId}:${suite.key}`;
6120
- function readMirror(orgId, suite) {
6121
- try {
6122
- const raw = sessionStorage.getItem(mirrorKey(orgId, suite));
6123
- if (!raw)
6124
- return null;
6125
- const parsed = JSON.parse(raw);
6126
- const row = parseRow(parsed);
6127
- if (!row || row.guide_version !== suite.version)
6128
- return null;
6129
- return { ...row, server_status: parsed.server_status ?? null };
6130
- }
6131
- catch {
6132
- return null;
6133
- }
6134
- }
6135
- function writeMirror(orgId, suite, p) {
6136
- try {
6137
- sessionStorage.setItem(mirrorKey(orgId, suite), JSON.stringify(p));
6138
- }
6139
- catch {
6140
- /* private mode: the server copy is enough */
6141
- }
6142
- }
6143
- /* ------------------------------------------------------------------ */
6144
- /* One tab at a time */
6145
- /* ------------------------------------------------------------------ */
6146
- /**
6147
- * Whether this tab runs the tour. With two tabs open, the first holds a Web
6148
- * Lock and the second shows nothing until the first goes away.
6149
- */
6150
- function usePrimaryTab(name) {
6151
- const [primary, setPrimary] = useState(false);
6152
- useEffect(() => {
6153
- const locks = (typeof navigator !== "undefined" ? navigator.locks : undefined);
6154
- if (!locks?.request) {
6155
- setPrimary(true);
6156
- return;
6157
- }
6158
- const abort = new AbortController();
6159
- let release = null;
6160
- locks
6161
- .request(name, { signal: abort.signal }, () => {
6162
- setPrimary(true);
6163
- return new Promise(resolve => {
6164
- release = resolve;
6165
- });
6166
- })
6167
- .catch(() => {
6168
- /* aborted on unmount */
6169
- });
6170
- return () => {
6171
- abort.abort();
6172
- release?.();
6173
- setPrimary(false);
6174
- };
6175
- }, [name]);
6176
- return primary;
6177
- }
6178
- /* ------------------------------------------------------------------ */
6179
- /* Putting the page back after a replay */
6180
- /* ------------------------------------------------------------------ */
6181
- const ABORT_DELAY_MS = 60;
6182
- const ABORT_GAP_MS = 150;
6183
- /**
6184
- * Runs a replay's abort actions in order, once the tour has let go of the
6185
- * page: press an anchor (passed over when it is not there), emit an app
6186
- * event, or Escape to the open dialog (Radix listens on the document).
6187
- */
6188
- function runAbort(actions) {
6189
- actions.forEach((a, i) => {
6190
- setTimeout(() => {
6191
- try {
6192
- if ("click" in a) {
6193
- findAnchor(a.click)?.click();
6194
- }
6195
- else if ("event" in a) {
6196
- emitGuideEvent(a.event);
6197
- }
6198
- else if ("escape" in a) {
6199
- const t = document.activeElement ?? document.body;
6200
- t.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true }));
6201
- }
6202
- }
6203
- catch {
6204
- /* never breaks the app */
6205
- }
6206
- }, ABORT_DELAY_MS + i * ABORT_GAP_MS);
6207
- });
6208
- }
6209
- /** A step's own target takes presses: not on a "view" step, unless the step allows it. */
6210
- function targetPressable(step, bridge) {
6211
- if (!step || bridge)
6212
- return true;
6213
- if (stepKind(step) !== "view")
6214
- return true;
6215
- return !!step.target && (step.allow ?? []).includes(step.target);
6216
- }
6217
- /* ------------------------------------------------------------------ */
6218
- /* Host */
6219
- /* ------------------------------------------------------------------ */
6220
- const TARGET_PAD = 6;
6221
- const LOST_GRACE_MS = 350;
6222
- const WAIT_MS = 8000;
6223
- const WAIT_CAP_MS = 30000;
6224
- const WELCOME_DELAY_MS = 500;
6225
- const CELEBRATE_DELAY_MS = 450;
6226
- const SAVE_DEBOUNCE_MS = 600;
3598
+ /** The shell's own queries (the tour's progress, the roles card) are not "the page loading". */
3599
+ const pageQuery = (q) => q.queryKey[0] !== "erp-shell";
6227
3600
  function GuideHostInner({ config, organizationId, code }) {
6228
3601
  const suite = config.suite;
6229
3602
  const client = useShellQueryClient();
@@ -6232,8 +3605,6 @@ function GuideHostInner({ config, organizationId, code }) {
6232
3605
  const search = searchParams?.toString() ?? "";
6233
3606
  const router = useRouter();
6234
3607
  const { open: sidebarOpen } = useSidebar();
6235
- const fetching = useIsFetching({ predicate: q => q.queryKey[0] !== "erp-shell" }, client);
6236
- const primary = usePrimaryTab(`erp-guide:${organizationId}:${suite.key}`);
6237
3608
  // The shell's EmployeeRequiredGate is up: no tour over it.
6238
3609
  const [employeeBlocked, setEmployeeBlocked] = useState(false);
6239
3610
  useEffect(() => {
@@ -6246,811 +3617,26 @@ function GuideHostInner({ config, organizationId, code }) {
6246
3617
  window.removeEventListener(EMPLOYEE_RECORD_OK_EVENT, off);
6247
3618
  };
6248
3619
  }, []);
6249
- const query = useQuery({
6250
- queryKey: ["erp-shell", "guides", organizationId, suite.app, suite.key, suite.version],
6251
- queryFn: ({ signal }) => fetchGuides(organizationId, suite, signal),
6252
- enabled: primary && config.ready !== false,
6253
- staleTime: 5 * 60000,
6254
- gcTime: 30 * 60000,
6255
- retry: false,
6256
- refetchOnWindowFocus: false,
6257
- }, client);
6258
- const answer = query.data ?? null;
6259
- const live = !!answer && answer.audience !== "none" && !answer.newerOnServer && primary && config.ready !== false && !employeeBlocked;
6260
- /* ---------------- machine ---------------- */
6261
- const [state, setState] = useState(null);
6262
- const stateRef = useRef(null);
6263
- // What the server holds (payloadKey), so a save that would change nothing
6264
- // is not sent and does not bump its rev.
6265
- const savedKey = useRef(null);
6266
- useEffect(() => {
6267
- if (!answer || answer.audience === "none" || answer.newerOnServer) {
6268
- stateRef.current = null;
6269
- setState(null);
6270
- return;
6271
- }
6272
- if (stateRef.current)
6273
- return;
6274
- savedKey.current = answer.progress && answer.progress.rev > 0 ? payloadKey(answer.progress, suite.app) : null;
6275
- // Resume from whichever copy is further along: the server's, or this
6276
- // tab's session copy from before a refresh (its rev is the server's).
6277
- const mirror = readMirror(organizationId, suite);
6278
- let progress = answer.progress;
6279
- if (mirror && furtherProgress(mirror, progress) === mirror)
6280
- progress = mergeProgress(mirror, progress);
6281
- const s = initialGuideState(answer.audience, progress);
6282
- stateRef.current = s;
6283
- setState(s);
6284
- }, [answer, organizationId, suite]);
6285
- // The latest page facts, read by the machine through env.
6286
- const pageRef = useRef({ pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can });
6287
- pageRef.current = { pathname, search, sidebarOpen, facts: config.facts ?? {}, can: config.can };
6288
- const targetElRef = useRef(null);
6289
- const env = useCallback(() => {
6290
- const pg = pageRef.current;
3620
+ const isBusy = useCallback(() => client.isFetching({ predicate: pageQuery }) > 0, [client]);
3621
+ // platform-api, with the GET answer kept in React Query as before 0.1.68
3622
+ // (fresh for 5 minutes, so a remount does not ask again; a failure is
3623
+ // kept too, and shows nothing).
3624
+ const progress = useMemo(() => {
3625
+ const platform = platformGuideProgress(organizationId);
6291
3626
  return {
6292
- code,
6293
- pathname: pg.pathname,
6294
- search: new URLSearchParams(pg.search),
6295
- facts: pg.facts,
6296
- can: (key) => {
6297
- try {
6298
- return pg.can ? pg.can(key) : true;
6299
- }
6300
- catch {
6301
- return true;
6302
- }
6303
- },
6304
- isVisible: (anchor, id) => anchorVisible(anchor, id),
6305
- sidebarOpen: pg.sidebarOpen,
6306
- targetValue: () => fieldValue(targetElRef.current),
6307
- dialogOpen: () => appDialogOpen(),
6308
- };
6309
- }, [code]);
6310
- /* ---------------- effects: save, announce, toast, navigate ---------------- */
6311
- const [liveText, setLiveText] = useState("");
6312
- const [toast, setToast] = useState(null);
6313
- const toastTimer = useRef(null);
6314
- const saveTimer = useRef(null);
6315
- const saving = useRef(null);
6316
- const savePending = useRef(false);
6317
- const flushSave = useCallback(async () => {
6318
- if (saveTimer.current) {
6319
- clearTimeout(saveTimer.current);
6320
- saveTimer.current = null;
6321
- }
6322
- if (saving.current) {
6323
- savePending.current = true;
6324
- return;
6325
- }
6326
- const run = async () => {
6327
- do {
6328
- savePending.current = false;
6329
- const cur = stateRef.current;
6330
- if (!cur)
6331
- return;
6332
- if (payloadKey(cur.progress, suite.app) === savedKey.current)
6333
- continue;
6334
- const row = await saveGuides(organizationId, suite, cur.progress);
6335
- if (row)
6336
- savedKey.current = payloadKey(row, suite.app);
6337
- if (row && stateRef.current) {
6338
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
6339
- dispatchRef.current({ type: "serverRow", progress: row });
6340
- }
6341
- } while (savePending.current);
6342
- };
6343
- saving.current = run().finally(() => {
6344
- saving.current = null;
6345
- });
6346
- }, [organizationId, suite]);
6347
- const runEffects = useCallback((effects) => {
6348
- for (const e of effects) {
6349
- try {
6350
- if (e.type === "save") {
6351
- if (stateRef.current)
6352
- writeMirror(organizationId, suite, stateRef.current.progress);
6353
- if (e.immediate)
6354
- void flushSave();
6355
- else {
6356
- if (saveTimer.current)
6357
- clearTimeout(saveTimer.current);
6358
- saveTimer.current = setTimeout(() => void flushSave(), SAVE_DEBOUNCE_MS);
6359
- }
6360
- }
6361
- else if (e.type === "announce") {
6362
- setLiveText("");
6363
- setTimeout(() => setLiveText(e.text), 60);
6364
- }
6365
- else if (e.type === "toast") {
6366
- setToast(e.text);
6367
- if (toastTimer.current)
6368
- clearTimeout(toastTimer.current);
6369
- toastTimer.current = setTimeout(() => setToast(null), 3200);
6370
- }
6371
- else if (e.type === "navigate") {
6372
- if (/^https?:\/\//i.test(e.href))
6373
- window.location.assign(e.href);
6374
- else
6375
- router.push(e.href);
6376
- }
6377
- else if (e.type === "abort") {
6378
- // After this render takes the guard away, put the page back.
6379
- runAbort(e.actions);
6380
- }
6381
- }
6382
- catch {
6383
- /* an effect never breaks the app */
6384
- }
6385
- }
6386
- }, [flushSave, organizationId, router, suite]);
6387
- const dispatch = useCallback((action) => {
6388
- const cur = stateRef.current;
6389
- if (!cur)
6390
- return;
6391
- let r;
6392
- try {
6393
- r = reduceGuide(cur, action, suite, env());
6394
- }
6395
- catch (err) {
6396
- if (typeof console !== "undefined")
6397
- console.warn("[erp-shell guide] stopped", err);
6398
- stateRef.current = null;
6399
- setState(null);
6400
- return;
6401
- }
6402
- if (r.state !== cur) {
6403
- stateRef.current = r.state;
6404
- setState(r.state);
6405
- }
6406
- if (r.effects.length)
6407
- runEffects(r.effects);
6408
- }, [env, runEffects, suite]);
6409
- const dispatchRef = useRef(dispatch);
6410
- dispatchRef.current = dispatch;
6411
- // Save what is pending when the page goes away.
6412
- useEffect(() => {
6413
- const flush = () => {
6414
- if (saveTimer.current)
6415
- void flushSave();
6416
- };
6417
- window.addEventListener("pagehide", flush);
6418
- return () => {
6419
- window.removeEventListener("pagehide", flush);
6420
- flush();
6421
- if (toastTimer.current)
6422
- clearTimeout(toastTimer.current);
6423
- };
6424
- }, [flushSave]);
6425
- /* ---------------- boot: resume, welcome ---------------- */
6426
- const screen = state?.screen ?? { name: "idle" };
6427
- const resumed = useRef(false);
6428
- useEffect(() => {
6429
- if (!live || !state || resumed.current)
6430
- return;
6431
- resumed.current = true;
6432
- dispatch({ type: "resume" });
6433
- }, [live, state, dispatch]);
6434
- const welcomeRoutes = suite.welcomeRoutes ?? ["/[code]"];
6435
- const onWelcomeRoute = welcomeRoutes.some(r => !!matchRoute(r, pathname, search, code));
6436
- const due = !!state && live && welcomeDue(state, suite) && onWelcomeRoute && fetching === 0;
6437
- const factsKey = useFactsKey(config.facts);
6438
- useEffect(() => {
6439
- if (!due)
6440
- return;
6441
- const t = setTimeout(() => dispatchRef.current({ type: "welcome" }), WELCOME_DELAY_MS);
6442
- return () => clearTimeout(t);
6443
- }, [due, factsKey]);
6444
- /* ---------------- sync on route, sidebar, facts, DOM ---------------- */
6445
- const inStep = live && screen.name === "step";
6446
- useEffect(() => {
6447
- if (inStep)
6448
- dispatch({ type: "sync" });
6449
- }, [inStep, pathname, search, sidebarOpen, factsKey, dispatch]);
6450
- useEffect(() => {
6451
- if (!inStep || typeof MutationObserver === "undefined")
6452
- return;
6453
- let raf = 0;
6454
- const obs = new MutationObserver(records => {
6455
- // Our own layer's changes are not the page's.
6456
- if (records.every(r => inGuideLayer(r.target)))
6457
- return;
6458
- if (raf)
6459
- return;
6460
- raf = requestAnimationFrame(() => {
6461
- raf = 0;
6462
- dispatchRef.current({ type: "sync" });
6463
- });
6464
- });
6465
- obs.observe(document.body, {
6466
- childList: true,
6467
- subtree: true,
6468
- attributes: true,
6469
- attributeFilter: ["data-state", "hidden", "aria-hidden", "class", "style", "open"],
6470
- });
6471
- return () => {
6472
- obs.disconnect();
6473
- if (raf)
6474
- cancelAnimationFrame(raf);
6475
- };
6476
- }, [inStep]);
6477
- /* ---------------- the current step ---------------- */
6478
- const stepInfo = useMemo(() => {
6479
- if (!state || screen.name !== "step")
6480
- return null;
6481
- const mission = findMission(suite, screen.mission);
6482
- if (!mission)
6483
- return null;
6484
- const raw = mission.steps[screen.index];
6485
- if (!raw)
6486
- return null;
6487
- // A commit step with nothing to save is shown as its read form.
6488
- const step = shownStep(raw, screen.nothingToSave);
6489
- const missionNo = suite.missions.indexOf(mission) + 1;
6490
- return { mission, step, raw, missionNo };
6491
- }, [state, screen, suite]);
6492
- const stepCtx = useMemo(() => {
6493
- if (!state)
6494
- return null;
6495
- const e = env();
6496
- const params = stepInfo?.step.route ? (matchRoute(stepInfo.step.route, e.pathname, e.search, code) ?? {}) : {};
6497
- return guideContext(e, state.progress.context, params);
6498
- // pathname/search/factsKey make it current.
6499
- // eslint-disable-next-line react-hooks/exhaustive-deps
6500
- }, [state, stepInfo, env, code, pathname, search, factsKey]);
6501
- const target = stepInfo && stepCtx && screen.name === "step"
6502
- ? spotlightTarget(stepInfo.step, stepCtx, screen.bridge)
6503
- : null;
6504
- const targetKey = target ? `${target.anchor}|${target.id ?? ""}` : "";
6505
- const phase = screen.name === "step" ? screen.phase : null;
6506
- const stepId = screen.name === "step" ? `${screen.mission}:${screen.index}:${screen.bridge ? "b" : ""}${screen.nothingToSave ? "n" : ""}` : "";
6507
- /* Measure every frame while a step is shown: the spotlight follows
6508
- scrolling, dialogs animating in, the drawer sliding, the keyboard. */
6509
- const [layout, setLayout] = useState({
6510
- spot: null,
6511
- covered: false,
6512
- holes: [],
6513
- popovers: [],
6514
- vw: 0,
6515
- vh: 0,
6516
- oy: 0,
6517
- });
6518
- useEffect(() => {
6519
- if (!inStep) {
6520
- targetElRef.current = null;
6521
- return;
6522
- }
6523
- let raf = 0;
6524
- let lostSince = null;
6525
- let last = { spot: null, covered: false, holes: [], popovers: [], vw: 0, vh: 0, oy: 0 };
6526
- targetElRef.current = target ? findAnchor(target.anchor, target.id) : null;
6527
- const allow = stepInfo?.step.allow ?? [];
6528
- // The spotlight is the part of the target a person can see: cut by the
6529
- // scroll boxes around it (a row of tabs that scrolls sideways) and the
6530
- // viewport. Wholly out of view (scrolled away up or down), its own box,
6531
- // and the tour scrolls it back.
6532
- let clipFor = null;
6533
- let clips = [];
6534
- const spotOf = (el) => {
6535
- if (el !== clipFor) {
6536
- clipFor = el;
6537
- clips = clipAncestors(el);
6538
- }
6539
- return padRect(visibleRectOf(el, clips) ?? rectOf(el), TARGET_PAD);
6540
- };
6541
- const tick = () => {
6542
- raf = requestAnimationFrame(tick);
6543
- const vv = window.visualViewport;
6544
- const vw = window.innerWidth;
6545
- const vh = vv ? vv.height : window.innerHeight;
6546
- const oy = vv ? vv.offsetTop : 0;
6547
- let el = targetElRef.current;
6548
- if (target && (!el || !el.isConnected)) {
6549
- el = findAnchor(target.anchor, target.id);
6550
- targetElRef.current = el;
6551
- }
6552
- let spot = null;
6553
- if (target && el && isPresent(el)) {
6554
- lostSince = null;
6555
- spot = spotOf(el);
6556
- }
6557
- else if (target) {
6558
- // Maybe re-rendered under another node.
6559
- const again = findAnchor(target.anchor, target.id);
6560
- if (again) {
6561
- targetElRef.current = again;
6562
- spot = spotOf(again);
6563
- lostSince = null;
6564
- }
6565
- else if (phase === "ready") {
6566
- lostSince ?? (lostSince = performance.now());
6567
- if (performance.now() - lostSince > LOST_GRACE_MS) {
6568
- lostSince = null;
6569
- dispatchRef.current({ type: "targetLost" });
6570
- }
6571
- }
6572
- }
6573
- if (phase === "waiting" && spot)
6574
- dispatchRef.current({ type: "sync" });
6575
- const popovers = [];
6576
- for (const p of openPoppers())
6577
- popovers.push(padRect(rectOf(p), 2));
6578
- const holes = [];
6579
- for (const a of allow) {
6580
- const ael = findAnchor(a);
6581
- if (ael)
6582
- holes.push(padRect(rectOf(ael), TARGET_PAD));
6583
- }
6584
- const covered = !!spot && coveredByDialog(targetElRef.current);
6585
- const next = { spot, covered, holes, popovers, vw, vh, oy };
6586
- const sameList = (a, b) => a.length === b.length && a.every((h, i) => sameRect(h, b[i]));
6587
- if (!sameRect(next.spot, last.spot) ||
6588
- next.covered !== last.covered ||
6589
- next.vw !== last.vw ||
6590
- next.vh !== last.vh ||
6591
- next.oy !== last.oy ||
6592
- !sameList(next.holes, last.holes) ||
6593
- !sameList(next.popovers, last.popovers)) {
6594
- last = next;
6595
- setLayout(next);
6596
- }
6597
- };
6598
- raf = requestAnimationFrame(tick);
6599
- return () => cancelAnimationFrame(raf);
6600
- // stepId/targetKey/phase restart the loop for a new step.
6601
- // eslint-disable-next-line react-hooks/exhaustive-deps
6602
- }, [inStep, stepId, targetKey, phase]);
6603
- /* Waiting for the target: 8 s of not-loading time (30 s at most). */
6604
- const fetchingRef = useRef(fetching);
6605
- fetchingRef.current = fetching;
6606
- useEffect(() => {
6607
- if (!inStep || phase !== "waiting")
6608
- return;
6609
- let idle = 0;
6610
- const started = Date.now();
6611
- const timeout = stepInfo?.step.timeoutMs ?? WAIT_MS;
6612
- const iv = setInterval(() => {
6613
- if (fetchingRef.current === 0 && document.visibilityState !== "hidden")
6614
- idle += 250;
6615
- if (idle >= timeout || Date.now() - started >= WAIT_CAP_MS) {
6616
- clearInterval(iv);
6617
- dispatchRef.current({ type: "timeout" });
6618
- }
6619
- }, 250);
6620
- return () => clearInterval(iv);
6621
- // eslint-disable-next-line react-hooks/exhaustive-deps
6622
- }, [inStep, stepId, phase, screen.name === "step" ? screen.misses : 0]);
6623
- /* On a step becoming ready: bring the target into view, focus, describe. */
6624
- const readyKey = inStep && phase === "ready" ? stepId : "";
6625
- useEffect(() => {
6626
- if (!readyKey || !stepInfo || screen.name !== "step")
6627
- return;
6628
- const el = targetElRef.current ?? (target ? findAnchor(target.anchor, target.id) : null);
6629
- if (el)
6630
- revealTarget(el);
6631
- const isInput = !screen.bridge && stepKind(stepInfo.step) === "input";
6632
- const t = setTimeout(() => {
6633
- if (isInput && el) {
6634
- const f = fieldOf(el);
6635
- f?.focus({ preventScroll: true });
6636
- }
6637
- else {
6638
- const b = document.querySelector(`[${GUIDE_LAYER_ATTRIBUTE}] [data-eg-bubble]`);
6639
- b?.focus({ preventScroll: true });
6640
- }
6641
- }, 30);
6642
- // The target is described by the bubble while the step lasts.
6643
- const described = el ? (isInput ? fieldOf(el) : el) : null;
6644
- const prev = described?.getAttribute("aria-describedby") ?? null;
6645
- if (described)
6646
- described.setAttribute("aria-describedby", [BUBBLE_TITLE_ID, BUBBLE_WHY_ID, prev].filter(Boolean).join(" "));
6647
- return () => {
6648
- clearTimeout(t);
6649
- if (!described)
6650
- return;
6651
- if (prev)
6652
- described.setAttribute("aria-describedby", prev);
6653
- else
6654
- described.removeAttribute("aria-describedby");
6655
- };
6656
- // eslint-disable-next-line react-hooks/exhaustive-deps
6657
- }, [readyKey]);
6658
- /* Signals from the page: API answers, app events, presses, typing. */
6659
- useEffect(() => {
6660
- if (!inStep || !stepInfo)
6661
- return;
6662
- const onApi = (e) => {
6663
- const d = e.detail;
6664
- if (!d || typeof d.status !== "number")
6665
- return;
6666
- dispatchRef.current({ type: "signal", signal: { kind: "api", method: d.method, path: d.path, status: d.status, id: d.id, message: d.message } });
6667
- };
6668
- window.addEventListener(API_EVENT, onApi);
6669
- const names = triggersOf(stepInfo.raw).flatMap(t => ("event" in t ? [t.event] : []));
6670
- const onApp = (name) => (e) => dispatchRef.current({ type: "signal", signal: { kind: "event", name, detail: e.detail ?? undefined } });
6671
- const appHandlers = names.map(n => [GUIDE_EVENT_PREFIX + n, onApp(n)]);
6672
- appHandlers.forEach(([n, h]) => window.addEventListener(n, h));
6673
- const inTarget = (node) => {
6674
- const el = targetElRef.current;
6675
- return !!el && node instanceof Node && el.contains(node);
6676
- };
6677
- // After the app has handled it, so what it does comes first.
6678
- const later = (a) => setTimeout(() => dispatchRef.current(a), 0);
6679
- const onPress = (e) => {
6680
- if (inTarget(e.target))
6681
- later({ type: "signal", signal: { kind: "activate" } });
6682
- };
6683
- const onKey = (e) => {
6684
- if ((e.key === "Enter" || e.key === " ") && inTarget(e.target) && stepKind(stepInfo.step) !== "input") {
6685
- later({ type: "signal", signal: { kind: "activate" } });
6686
- }
6687
- };
6688
- const onInput = (e) => {
6689
- if (!inTarget(e.target))
6690
- return;
6691
- dispatchRef.current({ type: "signal", signal: { kind: "typing" } });
6692
- later({ type: "signal", signal: { kind: "value", value: fieldValue(targetElRef.current) } });
6693
- };
6694
- document.addEventListener("pointerup", onPress, true);
6695
- document.addEventListener("keydown", onKey, true);
6696
- document.addEventListener("input", onInput, true);
6697
- document.addEventListener("change", onInput, true);
6698
- return () => {
6699
- window.removeEventListener(API_EVENT, onApi);
6700
- appHandlers.forEach(([n, h]) => window.removeEventListener(n, h));
6701
- document.removeEventListener("pointerup", onPress, true);
6702
- document.removeEventListener("keydown", onKey, true);
6703
- document.removeEventListener("input", onInput, true);
6704
- document.removeEventListener("change", onInput, true);
6705
- };
6706
- }, [inStep, stepInfo]);
6707
- /* ---------------- the guard ---------------- */
6708
- const modalScreen = live && (screen.name === "welcome" || screen.name === "gate" || screen.name === "celebrate" || screen.name === "complete");
6709
- const panelOpen = live && !!state?.panelOpen;
6710
- const guarding = inStep || modalScreen;
6711
- const guardingRef = useRef(guarding);
6712
- guardingRef.current = guarding;
6713
- const modalRef = useRef(false);
6714
- modalRef.current = modalScreen || (screen.name === "step" && (screen.confirmExit || screen.phase !== "ready"));
6715
- const stepInfoRef = useRef(stepInfo);
6716
- stepInfoRef.current = stepInfo;
6717
- useEffect(() => {
6718
- if (!live)
6719
- return;
6720
- const allowedTarget = (node) => {
6721
- if (!(node instanceof Node))
6722
- return false;
6723
- const el = targetElRef.current;
6724
- // A "view" step's target is there to be read: ถัดไป is the way on.
6725
- const sc = stateRef.current?.screen;
6726
- const pressable = targetPressable(stepInfoRef.current?.step, sc?.name === "step" && sc.bridge);
6727
- if (el && pressable && el.contains(node))
6728
- return true;
6729
- const elNode = node instanceof Element ? node : node.parentElement;
6730
- if (!elNode)
6731
- return false;
6732
- if (elNode.closest(POPPER_SELECTOR) || elNode.closest(TOASTER_SELECTOR))
6733
- return true;
6734
- for (const a of stepInfoRef.current?.step.allow ?? []) {
6735
- const ael = findAnchor(a);
6736
- if (ael && ael.contains(node))
6737
- return true;
6738
- }
6739
- return false;
6740
- };
6741
- const onPointer = (e) => {
6742
- const t = e.target;
6743
- if (inGuideLayer(t)) {
6744
- // Our dim layer eats the press (and keeps focus where it is).
6745
- if (t instanceof Element && t.closest("[data-eg-block]")) {
6746
- e.preventDefault();
6747
- if (e.type === "pointerdown")
6748
- dispatchRef.current({ type: "blocked" });
6749
- }
6750
- // The app's open dialog or menu never hears the press (the click
6751
- // itself goes on to our buttons).
6752
- if (e.type !== "click")
6753
- e.stopPropagation();
6754
- return;
6755
- }
6756
- if (!guardingRef.current)
6757
- return;
6758
- if (modalRef.current || !allowedTarget(t)) {
6759
- e.preventDefault();
6760
- e.stopPropagation();
6761
- if (e.type === "pointerdown")
6762
- dispatchRef.current({ type: "blocked" });
6763
- }
6764
- };
6765
- // Radix FocusScope pulls focus back into an open dialog; DismissableLayer
6766
- // closes on focus outside. Neither may see focus moving to the tour.
6767
- const onFocusIn = (e) => {
6768
- if (inGuideLayer(e.target))
6769
- e.stopPropagation();
6770
- };
6771
- const onFocusOut = (e) => {
6772
- if (inGuideLayer(e.relatedTarget))
6773
- e.stopPropagation();
6774
- };
6775
- const onKey = (e) => {
6776
- const s = stateRef.current;
6777
- if (!s)
6778
- return;
6779
- const sc = s.screen;
6780
- const stop = () => {
6781
- e.preventDefault();
6782
- e.stopImmediatePropagation();
6783
- };
6784
- if (e.key === "Escape") {
6785
- if (sc.name === "step") {
6786
- stop();
6787
- if (sc.confirmExit)
6788
- dispatchRef.current({ type: "exitCancel" });
6789
- else
6790
- dispatchRef.current({ type: "exit" });
6791
- }
6792
- else if (sc.name === "welcome") {
6793
- stop();
6794
- dispatchRef.current({ type: sc.confirm ? "welcomeSkipCancel" : "welcomeSkip" });
6795
- }
6796
- else if (sc.name === "gate") {
6797
- stop();
6798
- dispatchRef.current({ type: "gateLater" });
6799
- }
6800
- else if (sc.name === "celebrate") {
6801
- stop();
6802
- dispatchRef.current({ type: "rest" });
6803
- }
6804
- else if (sc.name === "complete") {
6805
- stop();
6806
- dispatchRef.current({ type: "finish" });
6807
- }
6808
- else if (s.panelOpen) {
6809
- stop();
6810
- dispatchRef.current({ type: "closePanel" });
6811
- }
6812
- return;
6813
- }
6814
- if (!guardingRef.current)
6815
- return;
6816
- const layer = layerRef.current;
6817
- if (e.key === "Tab") {
6818
- // Tab stays on what the step is about: the target and the bubble, or
6819
- // the open card.
6820
- const modals = layer ? Array.from(layer.querySelectorAll("[data-eg-modal],[data-eg-card]")) : [];
6821
- let list;
6822
- if (sc.name === "step" && !sc.confirmExit && sc.phase === "ready") {
6823
- const el = targetElRef.current;
6824
- const step = stepInfoRef.current?.step;
6825
- const isInput = !!step && !sc.bridge && stepKind(step) === "input";
6826
- const inTargetList = el && targetPressable(step, sc.bridge) ? focusablesIn(isInput ? (fieldOf(el) ?? el) : el) : [];
6827
- const bubble = layer?.querySelector("[data-eg-bubble]") ?? null;
6828
- list = [...inTargetList, ...(bubble ? Array.from(bubble.querySelectorAll(FOCUSABLE)) : [])];
6829
- for (const p of openPoppers())
6830
- list.push(...focusablesIn(p));
6831
- }
6832
- else {
6833
- const last = modals[modals.length - 1] ?? null;
6834
- list = last ? Array.from(last.querySelectorAll(FOCUSABLE)) : [];
6835
- }
6836
- if (!list.length)
6837
- return;
6838
- stop();
6839
- const i = list.indexOf(document.activeElement);
6840
- const n = e.shiftKey ? (i <= 0 ? list.length - 1 : i - 1) : i === -1 || i === list.length - 1 ? 0 : i + 1;
6841
- list[n].focus();
6842
- return;
6843
- }
6844
- if (e.key === "Enter" || e.key === " ") {
6845
- const active = document.activeElement;
6846
- if (inGuideLayer(active))
6847
- return;
6848
- if (sc.name === "step" && sc.phase === "ready" && !sc.confirmExit && e.key === "Enter") {
6849
- const step = stepInfoRef.current?.step;
6850
- const el = targetElRef.current;
6851
- if (step && stepKind(step) === "input" && el && active instanceof Node && el.contains(active) && !(active instanceof HTMLTextAreaElement)) {
6852
- // During the tour Enter is ถัดไป, not "submit the form".
6853
- stop();
6854
- dispatchRef.current({ type: "next" });
6855
- return;
6856
- }
6857
- }
6858
- if (modalRef.current || !allowedTarget(active))
6859
- stop();
6860
- }
6861
- };
6862
- window.addEventListener("pointerdown", onPointer, true);
6863
- window.addEventListener("mousedown", onPointer, true);
6864
- window.addEventListener("touchstart", onPointer, { capture: true, passive: false });
6865
- window.addEventListener("click", onPointer, true);
6866
- window.addEventListener("focusin", onFocusIn, true);
6867
- window.addEventListener("focusout", onFocusOut, true);
6868
- window.addEventListener("keydown", onKey, true);
6869
- return () => {
6870
- window.removeEventListener("pointerdown", onPointer, true);
6871
- window.removeEventListener("mousedown", onPointer, true);
6872
- window.removeEventListener("touchstart", onPointer, true);
6873
- window.removeEventListener("click", onPointer, true);
6874
- window.removeEventListener("focusin", onFocusIn, true);
6875
- window.removeEventListener("focusout", onFocusOut, true);
6876
- window.removeEventListener("keydown", onKey, true);
6877
- };
6878
- }, [live]);
6879
- /* Focus comes back to where it was when the tour lets go. */
6880
- const lastFocus = useRef(null);
6881
- const engaged = guarding || panelOpen;
6882
- useLayoutEffect(() => {
6883
- if (engaged) {
6884
- if (!lastFocus.current) {
6885
- const a = document.activeElement;
6886
- lastFocus.current = a instanceof HTMLElement && !inGuideLayer(a) ? a : null;
6887
- }
6888
- return;
6889
- }
6890
- const back = lastFocus.current;
6891
- lastFocus.current = null;
6892
- if (back && back.isConnected)
6893
- back.focus({ preventScroll: true });
6894
- }, [engaged]);
6895
- /* ---------------- the layer ---------------- */
6896
- const [layer, setLayer] = useState(null);
6897
- const layerRef = useRef(null);
6898
- useEffect(() => {
6899
- const el = document.createElement("div");
6900
- el.setAttribute(GUIDE_LAYER_ATTRIBUTE, "");
6901
- document.body.appendChild(el);
6902
- layerRef.current = el;
6903
- setLayer(el);
6904
- // A Radix modal (dialog, select, menu) hides everything outside it from
6905
- // screen readers with aria-hidden's hideOthers. It keeps [aria-live]
6906
- // elements but walks into their ancestors and hides the other children:
6907
- // with the status line live, the bubble and its buttons were hidden.
6908
- // Take off what it adds, at once. hideOthers marks what it hides with
6909
- // data-aria-hidden (the layer never sets that, or inert); aria-hidden goes
6910
- // only where it was just added, so the layer's own decorative aria-hidden
6911
- // stays. (aria-live="off" on the layer would make hideOthers skip it, but
6912
- // it changed what test tools match by text.)
6913
- const obs = new MutationObserver(records => {
6914
- for (const r of records) {
6915
- const n = r.target;
6916
- if (!(n instanceof Element))
6917
- continue;
6918
- if (r.attributeName === "inert" && n.hasAttribute("inert"))
6919
- n.removeAttribute("inert");
6920
- else if (r.attributeName === "data-aria-hidden" && n.hasAttribute("data-aria-hidden"))
6921
- n.removeAttribute("data-aria-hidden");
6922
- else if (r.attributeName === "aria-hidden" &&
6923
- n.getAttribute("aria-hidden") === "true" &&
6924
- (n === el || r.oldValue === null)) {
6925
- n.removeAttribute("aria-hidden");
6926
- }
6927
- }
6928
- });
6929
- obs.observe(el, { attributes: true, attributeOldValue: true, subtree: true, attributeFilter: ["aria-hidden", "data-aria-hidden", "inert"] });
6930
- return () => {
6931
- obs.disconnect();
6932
- el.remove();
6933
- layerRef.current = null;
6934
- };
6935
- }, []);
6936
- const [phone, setPhone] = useState(false);
6937
- const [reduced, setReduced] = useState(false);
6938
- useEffect(() => {
6939
- const sync = () => {
6940
- setPhone(isPhoneWidth());
6941
- setReduced(prefersReducedMotion());
3627
+ fetchProgress: req => client.fetchQuery({
3628
+ queryKey: ["erp-shell", "guides", organizationId, suite.app, suite.key, suite.version],
3629
+ queryFn: ({ signal }) => platform.fetchProgress({ ...req, signal }).catch(() => null),
3630
+ staleTime: 5 * 60000,
3631
+ gcTime: 30 * 60000,
3632
+ retry: false,
3633
+ }),
3634
+ saveProgress: req => platform.saveProgress(req),
6942
3635
  };
6943
- sync();
6944
- window.addEventListener("resize", sync);
6945
- return () => window.removeEventListener("resize", sync);
6946
- }, []);
6947
- // The celebration waits a beat, so the new row can be seen first.
6948
- const [celebrateShown, setCelebrateShown] = useState(false);
6949
- const celebrateKey = screen.name === "celebrate" || screen.name === "complete" ? screen.name + (screen.name === "celebrate" ? screen.mission : "") : "";
6950
- useEffect(() => {
6951
- setCelebrateShown(false);
6952
- if (!celebrateKey)
6953
- return;
6954
- const t = setTimeout(() => setCelebrateShown(true), CELEBRATE_DELAY_MS);
6955
- return () => clearTimeout(t);
6956
- }, [celebrateKey]);
6957
- // Ring moves smoothly only right after a step change.
6958
- const [moving, setMoving] = useState(false);
6959
- useEffect(() => {
6960
- if (!stepId)
6961
- return;
6962
- setMoving(true);
6963
- const t = setTimeout(() => setMoving(false), 320);
6964
- return () => clearTimeout(t);
6965
- }, [stepId]);
6966
- /* ---------------- the "?" menu entry ---------------- */
6967
- const ctxIdle = useMemo(() => (state ? guideContext(env(), state.progress.context) : null), [state, env, factsKey, pathname]); // eslint-disable-line react-hooks/exhaustive-deps
6968
- const done = state && ctxIdle ? settledCount(suite, state.progress, ctxIdle) : 0;
6969
- const total = suite.missions.length;
6970
- useEffect(() => {
6971
- if (!live || !state) {
6972
- publishGuideEntry(null, null);
6973
- return;
6974
- }
6975
- publishGuideEntry({ done, total }, () => dispatchRef.current({ type: "openPanel" }));
6976
- }, [live, state, done, total]);
6977
- useEffect(() => () => publishGuideEntry(null, null), []);
6978
- if (!live || !state || !layer || !ctxIdle)
6979
- return null;
6980
- /* ---------------- render ---------------- */
6981
- const views = missionViews(suite, state.progress, ctxIdle);
6982
- const gate = suite.gate;
6983
- const gateHref = gate ? resolveText(gate.action.href, ctxIdle) : "";
6984
- const gateFailing = gate ? gateState(suite, ctxIdle) === false : false;
6985
- let content = null;
6986
- if (screen.name === "welcome") {
6987
- content = (jsx(WelcomeModal, { title: resolveText(suite.welcome.title, ctxIdle), subtitle: resolveText(suite.welcome.subtitle, ctxIdle) || `มาตั้งค่าบริษัทให้พร้อมใน ${total} ภารกิจ`, missions: suite.missions.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" }) }));
6988
- }
6989
- else if (screen.name === "gate" && gate) {
6990
- content = (jsx(GateModal, { title: gate.title, subtitle: gate.subtitle, actionLabel: gate.action.label, href: gateHref, onLater: () => dispatch({ type: "gateLater" }) }));
6991
- }
6992
- else if (screen.name === "step" && stepInfo && stepCtx) {
6993
- const { mission, step, missionNo } = stepInfo;
6994
- const kind = stepKind(step);
6995
- const bridge = screen.bridge;
6996
- content = (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: {
6997
- missionNo,
6998
- missionTitle: mission.title,
6999
- replay: screen.replay,
7000
- index: screen.index,
7001
- total: mission.steps.length,
7002
- title: bridge ? "กดปุ่มเมนู" : resolveText(step.title, stepCtx),
7003
- why: bridge ? `เมนูทั้งหมดของ ${suite.appName} อยู่ในนี้` : resolveText(step.why, stepCtx),
7004
- error: screen.error,
7005
- showNext: !bridge && (kind === "input" || kind === "view"),
7006
- showEndWithoutSave: !bridge && screen.replay && kind === "commit",
7007
- }, 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" }) }));
7008
- }
7009
- else if (screen.name === "celebrate" && celebrateShown) {
7010
- const mission = findMission(suite, screen.mission);
7011
- const next = findMission(suite, nextMissionKey(suite, state.progress, ctxIdle));
7012
- if (mission) {
7013
- content = (jsx(CelebrateModal, { missionNo: suite.missions.indexOf(mission) + 1, 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" }) }));
7014
- }
7015
- }
7016
- else if (screen.name === "complete" && celebrateShown) {
7017
- const secondary = suite.complete.secondary;
7018
- let secondaryHref;
7019
- try {
7020
- secondaryHref = secondary ? (typeof secondary.href === "function" ? secondary.href(ctxIdle) : secondary.href) : undefined;
7021
- }
7022
- catch {
7023
- secondaryHref = undefined;
7024
- }
7025
- content = (jsx(CompleteModal, { total: total, title: resolveText(suite.complete.title, ctxIdle) || "บริษัทพร้อมใช้งานแล้ว", subtitle: resolveText(suite.complete.subtitle, ctxIdle), missions: suite.missions.map(m => m.title), actionLabel: suite.complete.action.label, secondary: secondary && secondaryHref ? { label: secondary.label, href: secondaryHref } : null, reduced: reduced, onFinish: () => dispatch({ type: "finish" }) }));
7026
- }
7027
- const items = views.map(v => ({
7028
- key: v.mission.key,
7029
- title: v.mission.title,
7030
- minutes: v.mission.minutes,
7031
- view: v.view,
7032
- optional: !!v.mission.optional,
7033
- completedAt: v.entry?.completed_at ?? null,
7034
- lockedBy: v.view === "locked"
7035
- ? (v.mission.after ?? [])
7036
- .map(k => findMission(suite, k)?.title)
7037
- .filter(Boolean)
7038
- .join(", ")
7039
- : undefined,
7040
- }));
7041
- const showChip = chipVisible(state, suite, ctxIdle);
7042
- return createPortal(jsxs(Fragment$1, { children: [jsx("style", { children: GUIDE_CSS }), jsx("div", { className: "eg-sr", "aria-live": "polite", role: "status", children: liveText }), content, showChip ? jsx(QuestChip, { done: done, total: total, pulse: state.chipPulse, onOpen: () => dispatch({ type: "openPanel" }) }) : null, state.panelOpen && screen.name === "idle" ? (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 ? jsx(GuideToast, { text: toast }) : null] }), layer);
7043
- }
7044
- /** A stable key for the facts object, so effects re-run when they change. */
7045
- function useFactsKey(facts) {
7046
- return useMemo(() => {
7047
- try {
7048
- return JSON.stringify(facts ?? {});
7049
- }
7050
- catch {
7051
- return String(Math.random());
7052
- }
7053
- }, [facts]);
3636
+ }, [client, organizationId, suite.app, suite.key, suite.version]);
3637
+ const routing = useMemo(() => ({ pathname, search, navigate: (href) => router.push(href) }), [pathname, search, router]);
3638
+ const menu = useMemo(() => ({ open: sidebarOpen }), [sidebarOpen]);
3639
+ return (jsx(GuideRuntime, { config: config, organizationId: organizationId, code: code, routing: routing, progress: progress, isBusy: isBusy, menu: menu, hidden: employeeBlocked }));
7054
3640
  }
7055
3641
 
7056
3642
  /**
@@ -7828,5 +4414,5 @@ const getAxiosErrorMessage = (error) => {
7828
4414
  return String(error);
7829
4415
  };
7830
4416
 
7831
- export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, FOR_ORGANIZATION_FIELD, FeatureFlagsProvider, API_EVENT as GUIDE_API_EVENT, GUIDE_EVENT_PREFIX, GUIDE_LAYER_ATTRIBUTE, GuideHost, HeaderBackground, HelpButton, HelpDialogHost, NavMain, NavTools, NavUser, OWNER_CHIP, OrganizationSwitcher, PLAN_FEATURES, PermissionGateShell, PermissionProvider, PermissionRulesProvider, ReactQueryProvider, SHELL_VERSION, SessionBackedProfileCacheSeeder, SessionRefreshTrigger, SidebarContent, SidebarFooter, SidebarHeader, SidebarHelpCard, SidebarHelpLink, SidebarProvider, SidebarTrigger, TapMenu, ThemeProvider, WITHOUT_ORGANIZATION_FLAG, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, accountSettingsHref, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, clearStoredOrganization, closeHelp, decodeJWT, describeAttached, describeBrowser, detectHelpApp, emitGuideEvent, filterNavigationModulesByPermission, filterNavigationToolsByPermission, findOrganizationForCode, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequestOrganizationId, getRequiredChildGroups, getStoredOrganizationIds, getTabOrganizationId, guideAnchor, hasPlanFeature, isKnownStaleOrganizationId, isLikelyTransientNetworkError, isPathActive, myRolesQueryKey, normalizePathnameForPermissionRules, openGuidePanel, openHelp, organizationScopedQueryHash, parseMyRoles, platformBaseUrl, reportApiEvent, resolveActiveNav, resolveSidebarNav, resolveStaleOrganization, resolveUiRoutePermission, resolveUrlOrgGate, retryWithStoredOrganizations, roleSummary, runGlobalRequestPrecheck, runWithTransientRetry, setKnownOrganizationIds, setOrganizationId, setTabOrganizationId, shouldRetryQuery, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useGuideEntry, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useMyRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle, withoutOrganization };
4417
+ export { AccessDenied, ApiError, AppBreadcrumb, AppLayoutShell, AppSidebar, EMPLOYEE_RECORD_OK_EVENT, EMPLOYEE_RECORD_REQUIRED, EMPLOYEE_RECORD_REQUIRED_EVENT, EmployeeRequiredGate, FOR_ORGANIZATION_FIELD, FeatureFlagsProvider, GuideHost, GuideRuntime, HeaderBackground, HelpButton, HelpDialogHost, NavMain, NavTools, NavUser, OWNER_CHIP, OrganizationSwitcher, PLAN_FEATURES, PermissionGateShell, PermissionProvider, PermissionRulesProvider, ReactQueryProvider, SHELL_VERSION, SessionBackedProfileCacheSeeder, SessionRefreshTrigger, SidebarContent, SidebarFooter, SidebarHeader, SidebarHelpCard, SidebarHelpLink, SidebarProvider, SidebarTrigger, TapMenu, ThemeProvider, WITHOUT_ORGANIZATION_FLAG, WORKSPACE_HEADER_VARS, WORKSPACE_LIGHT_HEADER_VARS, WorkspaceBrand, accountSettingsHref, instance as axiosInstance, buildSystemLinks, buildUrlWithCode, canAccessNavPermissionRoute, clearAccessTokenCache, clearOrganizationId, clearStoredOrganization, closeHelp, decodeJWT, describeAttached, describeBrowser, detectHelpApp, filterNavigationModulesByPermission, filterNavigationToolsByPermission, findOrganizationForCode, getAccessToken, getActiveModule, getActiveSubModule, getAxiosErrorMessage, getOrganizationId, getQueryClientConfig, getRequestOrganizationId, getRequiredChildGroups, getStoredOrganizationIds, getTabOrganizationId, guideAnchor, hasPlanFeature, isKnownStaleOrganizationId, isLikelyTransientNetworkError, isPathActive, myRolesQueryKey, normalizePathnameForPermissionRules, openGuidePanel, openHelp, organizationScopedQueryHash, parseMyRoles, platformBaseUrl, reportApiEvent, resolveActiveNav, resolveSidebarNav, resolveStaleOrganization, resolveUiRoutePermission, resolveUrlOrgGate, retryWithStoredOrganizations, roleSummary, runGlobalRequestPrecheck, runWithTransientRetry, setKnownOrganizationIds, setOrganizationId, setTabOrganizationId, shouldRetryQuery, toApiError, unwrapApiResponse, updateOrganizationId, useClearOrgOnUserChange, useFeatureFlag, useFeatureFlags, useGuideEntry, useInvalidateQueriesOnOrgChange, useKeycloakRoles, useMyRoles, useOrganizationIdState, usePermissionRules, useSessionRefresh, useSidebar, useSidebarToggle, withoutOrganization };
7832
4418
  //# sourceMappingURL=index.esm.js.map