@eintrek/erp-shell 0.1.66 → 0.1.68

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