@nanobpm/urban 0.54.0 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/runtime/core/host.d.ts +31 -5
  2. package/dist/runtime/core/modules/pages.js +5 -1850
  3. package/dist/runtime/core/modules/runtime.gen.d.ts +1 -0
  4. package/dist/runtime/core/modules/runtime.gen.js +5 -0
  5. package/dist/runtime/engine/nanosdk.d.ts +6 -5
  6. package/dist/runtime/engine/nanosdk.js +6 -0
  7. package/dist/runtime/index.d.ts +1 -1
  8. package/package.json +5 -3
  9. package/src/runtime/browser/runtime.browser.js +2179 -0
  10. package/src/runtime/browser/runtime.browser.test.ts +118 -0
  11. package/src/runtime/core/host.ts +32 -5
  12. package/src/runtime/core/modules/actions.test.ts +1 -0
  13. package/src/runtime/core/modules/agent.test.ts +1 -0
  14. package/src/runtime/core/modules/api.test.ts +1 -0
  15. package/src/runtime/core/modules/cancel.test.ts +1 -0
  16. package/src/runtime/core/modules/connectors.test.ts +1 -0
  17. package/src/runtime/core/modules/datasource.migrations.test.ts +1 -0
  18. package/src/runtime/core/modules/instance-tracking.test.ts +1 -0
  19. package/src/runtime/core/modules/pages.test.ts +114 -7
  20. package/src/runtime/core/modules/pages.ts +5 -1850
  21. package/src/runtime/core/modules/runtime.gen.ts +6 -0
  22. package/src/runtime/core/modules/surfaces.test.ts +2 -0
  23. package/src/runtime/core/modules/triggers.test.ts +1 -0
  24. package/src/runtime/core/modules/workers.test.ts +1 -0
  25. package/src/runtime/core/runtime.extensions.test.ts +3 -0
  26. package/src/runtime/core/runtime.test.ts +3 -0
  27. package/src/runtime/engine/nanosdk.test.ts +18 -0
  28. package/src/runtime/engine/nanosdk.ts +9 -4
  29. package/src/runtime/index.ts +1 -0
@@ -26,6 +26,7 @@ import { html, json } from "../router.js";
26
26
  import { cancelInstanceReconciling } from "./cancel.js";
27
27
  import { apiDocsPath } from "./api.js";
28
28
  import { quoteIdent } from "./gateway.js";
29
+ import { RENDERER_JS } from "./runtime.gen.js";
29
30
  /** A JavaScript-body response (the renderer module served at the fingerprinted
30
31
  * `/app/runtime.<hash>.js`, and its `/app/runtime.js` back-compat route). */
31
32
  function javascript(body, status = 200, extraHeaders) {
@@ -708,1857 +709,11 @@ table.pc-grid th { font-weight:600; color:var(--nano-text-muted); }
708
709
  // /app/runtime.js — it does NOT ship Craft.js (authoring is console-side only). It
709
710
  // fetches the home page's page.json and renders text / actionForm / dataGrid / prose
710
711
  // nodes, wiring actionForm → /app/actions/start and dataGrid/prose → /app/data (with a refresh).
711
- const RENDERER_JS = String.raw `
712
- const root = document.getElementById("page");
713
- const HOME = root.dataset.home || "home";
714
-
715
- // Single mobile breakpoint, interpolated from the same MOBILE_MAX_WIDTH constant
716
- // as the shell CSS @media so the JS mode-switch and the pure-CSS card flip can
717
- // never drift on where "narrow" begins (#268). Only Tier-2 (an optional
718
- // page-level 'mobile' layout variant) needs this JS switch — the dataGrid card
719
- // flip, nav collapse and button/form stacking are all pure CSS + data-label.
720
- const MOBILE_MQ = window.matchMedia("(max-width:${MOBILE_MAX_WIDTH})");
721
- function isNarrow() { return MOBILE_MQ.matches; }
722
-
723
- // ── Multi-page routing (hash-based, reverse-proxy safe) ──────────────────
724
- // Pages are selected by the URL fragment (#/<page>) so navigation never hits
725
- // the server and works identically at the origin root and under the Nano
726
- // console's /console/app-view/<name>/ path-prefixed proxy (the hash is never
727
- // sent upstream). An empty/invalid hash falls back to the home page. Only a
728
- // safe id charset is accepted so the fragment can't smuggle a path/URL.
729
- const PAGE_ID = /^[A-Za-z0-9_-]+$/;
730
- function safePageId(value) {
731
- return typeof value === "string" && PAGE_ID.test(value);
732
- }
733
- // A route is #/<page> or #/<page>/<url-encoded-param>. We split on the FIRST
734
- // "/" *before* decoding, so a param that itself contains encoded slashes or
735
- // hashes (e.g. a plan_key "owner/repo#123" carried as "owner%2Frepo%23123")
736
- // survives intact instead of the inner "%2F" being decoded into a second
737
- // segment. The page segment is still restricted to the safe id charset; the
738
- // param is opaque free text (bound only as a whitelisted '?' SQL value, or
739
- // interpolated as DOM text — never as HTML/markup).
740
- function parseRoute() {
741
- const raw = (location.hash || "").replace(/^#\/?/, "");
742
- const slash = raw.indexOf("/");
743
- const pageRaw = slash >= 0 ? raw.slice(0, slash) : raw;
744
- const paramRaw = slash >= 0 ? raw.slice(slash + 1) : "";
745
- let page = HOME, param = "", pageOk = false;
746
- try { const p = decodeURIComponent(pageRaw); if (safePageId(p)) { page = p; pageOk = true; } } catch (e) { /* keep HOME */ }
747
- // Only carry the param when the page segment resolved to a real (safe-id) page.
748
- // A malformed/unknown page like #/not-a-page/x falls back to HOME and must NOT
749
- // inherit x, or that stray param would silently scope every eqParam grid and
750
- // {{param}} on the home page to an entity the user never selected.
751
- if (pageOk) { try { param = paramRaw ? decodeURIComponent(paramRaw) : ""; } catch (e) { param = ""; } }
752
- return { page, param };
753
- }
754
- function currentPage() { return parseRoute().page; }
755
- let CURRENT = currentPage();
756
- // The current route param (the "/<param>" tail, or "" when absent). Exposed to a
757
- // page's datasource filters (a filter with { eqParam: true } binds its value to
758
- // this) and to {{param}} text interpolation, so one page template can scope
759
- // every section to a selected entity (e.g. an epic's plan_key).
760
- let PARAM = parseRoute().param;
761
- // Monotonic render token. renderPage() is async and fires from both hashchange
762
- // and the matchMedia viewport-crossing handler, so two invocations can overlap
763
- // and their fetches resolve out of order. Each render captures the token it
764
- // bumped to; after its await it only touches the DOM if it is still the latest,
765
- // so a stale navigation/viewport render can't overwrite a newer one.
766
- let renderSeq = 0;
767
-
768
- // Per-render teardown. Each dataGrid registers its poll interval + pc:refresh
769
- // listener here; navigating to another page runs every disposer before the new
770
- // page renders, so a switched-away grid stops polling (otherwise every visited
771
- // page would leave a live setInterval fetching forever).
772
- const disposers = [];
773
- function teardown() {
774
- while (disposers.length) {
775
- try { disposers.pop()(); } catch (e) { /* best-effort cleanup */ }
776
- }
777
- }
778
-
779
- // Monotonic counter for per-modal element ids. aria-labelledby needs a unique
780
- // title id: a fixed id would clash if the page already contains that id, and
781
- // mis-associate the label for assistive tech.
782
- let modalSeq = 0;
783
- // At most one modal is open at a time. A double-click (or two rapid button
784
- // clicks) would otherwise stack multiple overlays + document-level keydown
785
- // listeners; this guard keeps a single dialog + handler live.
786
- let modalOpen = false;
787
-
788
- // Theme bridge for the Nano console embed. The app runs in a sandboxed,
789
- // same-origin iframe, so the console's --nano-* custom properties and its
790
- // data-appearance never cascade in. Instead the console postMessages its
791
- // resolved tokens; we lay them onto this document's :root and mirror the
792
- // appearance. Standalone (no console parent) nothing is posted, so the CSS
793
- // defaults stand. We announce readiness so the console can push the theme even
794
- // if its first message raced our listener install.
795
- function applyTheme(msg) {
796
- if (!msg || msg.type !== "nano-theme") return;
797
- const el = document.documentElement;
798
- if (msg.appearance === "light" || msg.appearance === "dark") el.dataset.appearance = msg.appearance;
799
- const vars = msg.vars;
800
- if (vars && typeof vars === "object") {
801
- for (const [k, v] of Object.entries(vars)) {
802
- // Only accept the shared token namespace; ignore anything else.
803
- if (typeof k === "string" && k.startsWith("--nano-") && typeof v === "string") {
804
- el.style.setProperty(k, v);
805
- }
806
- }
807
- }
808
- }
809
- // True when this app runs inside the Nano console's same-origin iframe (vs a
810
- // standalone CLI run). Gates the theme bridge below AND in-host link navigation:
811
- // embedded, a processExplorer link routes the console in place; standalone, the
812
- // link keeps its native new-window behavior. The same-origin probe matters: a
813
- // cross-origin framer is also window.parent, but postMessage to our own origin
814
- // would never reach it and hostNavigate would still preventDefault the link —
815
- // so a cross-origin embed must fall through to the native _blank anchor. Reading
816
- // parent.location.origin throws under the same-origin policy for a cross-origin
817
- // parent, so the try/catch is the origin gate.
818
- const NANO_EMBEDDED = (() => {
819
- if (!window.parent || window.parent === window) return false;
820
- try {
821
- return window.parent.location.origin === window.location.origin;
822
- } catch {
823
- return false;
824
- }
825
- })();
826
-
827
- // Ask the framing console to navigate in-host. Returns true when a message was
828
- // posted (embedded) so the caller can suppress the native anchor; false
829
- // standalone so it falls through to the new-window <a>. The payload is
830
- // structured (target + params), never a raw href — the console constructs its
831
- // own route, so app/row data can't smuggle a path or scheme across the boundary.
832
- function hostNavigate(target, params) {
833
- if (!NANO_EMBEDDED) return false;
834
- window.parent.postMessage({ type: "nano-navigate", target: target, params: params }, window.location.origin);
835
- return true;
836
- }
837
-
838
- if (NANO_EMBEDDED) {
839
- window.addEventListener("message", (ev) => {
840
- // Same-origin proxy (posture A): only trust a message from the framing
841
- // parent AND from our own origin. ev.source alone is insufficient — a
842
- // cross-origin page that frames a standalone run becomes window.parent, so
843
- // an origin check is what actually pins the trust boundary.
844
- if (ev.origin === window.location.origin && ev.source === window.parent) applyTheme(ev.data);
845
- });
846
- window.parent.postMessage({ type: "nano-app-ready" }, window.location.origin);
847
- }
848
-
849
- // Resolve every app endpoint against where THIS module was actually served from,
850
- // so absolute-looking "/app/…" paths work both at the origin root (direct run,
851
- // e.g. the CLI on :3000) and under a path-prefixed reverse proxy (the Nano
852
- // console embeds the app at /console/app-view/<name>/). "../" drops the trailing
853
- // "app/runtime.js" to land on the app's mount root (always ends in "/").
854
- const APP_BASE = new URL("../", import.meta.url);
855
- function apiUrl(u) {
856
- // Rebase root-absolute app paths ("/app/…") onto the mount root. Leave a
857
- // protocol-relative ("//host/…") or otherwise non-root-relative string alone —
858
- // only a single leading slash denotes an app path we own.
859
- return typeof u === "string" && u.startsWith("/") && !u.startsWith("//")
860
- ? new URL(u.slice(1), APP_BASE).toString()
861
- : u;
862
- }
863
-
864
- async function getJSON(url, opts) {
865
- const r = await fetch(apiUrl(url), opts);
866
- const body = await r.json().catch(() => ({}));
867
- if (!r.ok) throw new Error(body.error || ("HTTP " + r.status));
868
- return body;
869
- }
870
-
871
- // ── route-driven actions ────────────────────────────────────────────────
872
- // Every page action is a single primitive: POST (or any method) the resolved
873
- // body to an app route path. There are NO bespoke action kinds — a form/row
874
- // reaches process start, message publish, cancel, an OpenAPI operation, a
875
- // webhook, or any app route uniformly by naming its path. Path + body may
876
- // interpolate the current form fields and (for grid rows/detail forms) the row
877
- // via {{form.KEY}} / {{row.KEY}} tokens; the whole-string tokens {{form}} and
878
- // {{row}} splice the object itself (type-preserving), so a body of
879
- // "variables": "{{form}}" sends the form object as the variable map.
880
- function lookupToken(path, ctx) {
881
- const segs = String(path).split(".");
882
- const head = segs[0];
883
- let base = head === "form" ? (ctx.form || {}) : head === "row" ? (ctx.row || {}) : undefined;
884
- for (let i = 1; i < segs.length; i++) base = base == null ? undefined : base[segs[i]];
885
- return base;
886
- }
887
- function resolveTemplate(node, ctx) {
888
- if (typeof node === "string") {
889
- const whole = node.match(/^\{\{\s*([\w.]+)\s*\}\}$/);
890
- if (whole) return lookupToken(whole[1], ctx);
891
- return node.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, k) => {
892
- const v = lookupToken(k, ctx);
893
- return v == null ? "" : String(v);
894
- });
895
- }
896
- if (Array.isArray(node)) return node.map((n) => resolveTemplate(n, ctx));
897
- if (node && typeof node === "object") {
898
- // Null-proto target so a template key like "__proto__" can't trigger prototype
899
- // mutation (prototype-pollution class) when copied into the resolved object.
900
- const out = Object.create(null);
901
- for (const [k, v] of Object.entries(node)) out[k] = resolveTemplate(v, ctx);
902
- return out;
903
- }
904
- return node;
905
- }
906
- async function runRoute(action, ctx) {
907
- if (!action || typeof action.path !== "string" || action.path === "") {
908
- throw new Error("This action has no route configured (action.path is missing or blank)");
909
- }
910
- const path = action.path.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, k) => {
911
- const v = lookupToken(k, ctx);
912
- return v == null ? "" : encodeURIComponent(String(v));
913
- });
914
- const method = String(action.method || "POST").toUpperCase();
915
- let body;
916
- if (action.body !== undefined) body = resolveTemplate(action.body, ctx);
917
- else if (ctx.form) body = { variables: ctx.form };
918
- else body = {};
919
- const opts = { method, headers: { "content-type": "application/json" } };
920
- if (method !== "GET" && method !== "HEAD") opts.body = JSON.stringify(body);
921
- return getJSON(path, opts);
922
- }
923
-
924
- function el(tag, attrs = {}, ...kids) {
925
- const n = document.createElement(tag);
926
- for (const [k, v] of Object.entries(attrs)) {
927
- if (k === "class") n.className = v;
928
- else if (k.startsWith("on") && typeof v === "function") n.addEventListener(k.slice(2), v);
929
- else if (v != null) n.setAttribute(k, v);
930
- }
931
- for (const kid of kids) n.append(kid);
932
- return n;
933
- }
934
-
935
- // Interpolate the {{param}} token in a schema-supplied string with the current
936
- // route param. The result is only ever set as DOM text (textContent), so the
937
- // substituted value cannot inject markup. Other tokens are left untouched.
938
- // A function replacement inserts PARAM literally; a plain string replacement would
939
- // treat replacement patterns inside PARAM (an id like the dollar-one token) as
940
- // special and render the wrong text.
941
- function interpParam(s) {
942
- return typeof s === "string" ? s.replace(/\{\{param\}\}/g, () => PARAM) : s;
943
- }
944
-
945
- // Interpolate {{field}} tokens in a column's per-cell template with values from
946
- // the row, coercing each to a string (null/undefined → ""). Like interpParam the
947
- // result is only ever set as DOM text (textContent via el()), so a substituted
948
- // row value cannot inject markup or attributes. A function replacement inserts
949
- // each value literally, so a "$"-bearing value can't be reinterpreted as a
950
- // replacement pattern. Unknown tokens (no such field) render empty rather than
951
- // throwing, matching interpParam. This is a dumb text formatter: no expressions,
952
- // arithmetic, or conditionals — just field splicing. Only the row's own
953
- // fields resolve (own-property gate, enumerable or not): an inherited
954
- // Object.prototype key (toString, constructor, …) counts as unknown and
955
- // renders "", so a token can't pick up prototype cruft instead of blank.
956
- function interpTemplate(tpl, row) {
957
- return typeof tpl === "string"
958
- ? tpl.replace(/\{\{([^{}]+)\}\}/g, (_m, name) => {
959
- const key = name.trim();
960
- const v = Object.prototype.hasOwnProperty.call(row, key) ? row[key] : null;
961
- return v == null ? "" : String(v);
962
- })
963
- : tpl;
964
- }
965
- function renderText(node) {
966
- const v = node.props.variant;
967
- const cls = v === "heading" ? "pc-heading" : v === "sub" ? "pc-sub" : "pc-body";
968
- return el(v === "heading" ? "h1" : "p", { class: cls }, interpParam(node.props.text) || "");
969
- }
970
-
971
- // Copy text to the clipboard, resiliently. The async Clipboard API is tried
972
- // first, but it can reject inside a sandboxed console iframe (no clipboard-write
973
- // permission) — so fall back to a hidden <textarea> + execCommand("copy"), which
974
- // works under a user gesture with only allow-scripts. Returns whether a copy
975
- // succeeded so the caller can nudge the user to ⌘/Ctrl+C when both paths fail.
976
- async function copyToClipboard(text) {
977
- try {
978
- if (navigator.clipboard && navigator.clipboard.writeText) {
979
- await navigator.clipboard.writeText(text);
980
- return true;
981
- }
982
- } catch (_e) { /* fall through to the execCommand path */ }
983
- const ta = document.createElement("textarea");
984
- try {
985
- ta.value = text;
986
- ta.setAttribute("readonly", "");
987
- ta.style.position = "fixed";
988
- ta.style.top = "-1000px";
989
- ta.style.opacity = "0";
990
- document.body.append(ta);
991
- ta.select();
992
- return document.execCommand("copy");
993
- } catch (_e) { return false; }
994
- // Always remove the hidden textarea, even if select()/execCommand threw, so a
995
- // failed copy never leaves a detached node accreting in <body> on retry.
996
- finally { ta.remove(); }
997
- }
998
-
999
- // Rebase the sole {{appBase}} token in author-supplied copy text onto the app's
1000
- // absolute mount root (always ends in "/"), so a prompt like
1001
- // "read {{appBase}}app/api/agent" resolves to a URL an external agent can fetch —
1002
- // the console proxy path when embedded, the app origin when standalone. No other
1003
- // interpolation happens: copy text is otherwise emitted verbatim.
1004
- function resolveCopyText(text) {
1005
- return typeof text === "string" ? text.split("{{appBase}}").join(APP_BASE.toString()) : "";
1006
- }
1007
-
1008
- // Open a lightweight modal appended to <body>. Closes on the ✕/Close button, a
1009
- // backdrop click, Escape, or a page switch; the keydown listener is removed on
1010
- // close so it never leaks, and close() is registered with teardown() so
1011
- // navigating away (hashchange → renderPage → teardown) tears down any open modal
1012
- // instead of leaving a stale overlay + document-level listener alive. When it
1013
- // carries copyText it renders a scrollable code block plus a Copy button (see
1014
- // copyToClipboard for the sandbox-safe fallback).
1015
- function openModal(m) {
1016
- // Only one modal at a time — drop a second (e.g. double-click) open so we
1017
- // never stack overlays or register duplicate document-level keydown handlers.
1018
- if (modalOpen) return;
1019
- modalOpen = true;
1020
- const overlay = el("div", { class: "pc-modal-overlay" });
1021
- // role="dialog" + aria-modal need an accessible name: label by the visible
1022
- // title when present, else fall back to a generic aria-label so screen readers
1023
- // don't announce an unnamed dialog. The title id is unique per instance so it
1024
- // can't collide with a pre-existing page id.
1025
- const titleId = m.title ? "pc-modal-title-" + (++modalSeq) : null;
1026
- const dialog = el("div", titleId
1027
- ? { class: "pc-modal", role: "dialog", "aria-modal": "true", "aria-labelledby": titleId }
1028
- : { class: "pc-modal", role: "dialog", "aria-modal": "true", "aria-label": "Dialog" });
1029
- if (m.title) dialog.append(el("h2", { class: "pc-modal-title", id: titleId }, m.title));
1030
- if (m.description) dialog.append(el("p", { class: "pc-modal-desc" }, m.description));
1031
- const copyText = resolveCopyText(m.copyText);
1032
- if (copyText) dialog.append(el("pre", { class: "pc-modal-code" }, copyText));
1033
- const actions = el("div", { class: "pc-modal-actions" });
1034
- // Remember what had focus so we can restore it on close — a keyboard/screen
1035
- // reader user returns to where they were instead of being dumped at <body>.
1036
- const prevFocus = document.activeElement;
1037
- let closed = false;
1038
- function close() {
1039
- if (closed) return;
1040
- closed = true;
1041
- modalOpen = false;
1042
- document.removeEventListener("keydown", onKey);
1043
- overlay.remove();
1044
- // A manual close (button / Escape / backdrop) never pops the disposers
1045
- // stack, so drop our own entry here — otherwise repeated open/close cycles
1046
- // accrete dead close() closures until the next page navigation runs teardown.
1047
- const i = disposers.indexOf(close);
1048
- if (i !== -1) disposers.splice(i, 1);
1049
- if (prevFocus && typeof prevFocus.focus === "function") prevFocus.focus();
1050
- }
1051
- // Focusable descendants of the dialog, in DOM order, for the Tab focus trap.
1052
- function focusables() {
1053
- return Array.prototype.slice.call(dialog.querySelectorAll(
1054
- 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
1055
- )).filter((n) => !n.disabled);
1056
- }
1057
- function onKey(ev) {
1058
- if (ev.key === "Escape") { close(); return; }
1059
- if (ev.key !== "Tab") return;
1060
- // Trap Tab within the dialog so focus can't slip behind the overlay onto the
1061
- // inert page underneath — that would break aria-modal semantics.
1062
- const f = focusables();
1063
- if (!f.length) return;
1064
- const first = f[0];
1065
- const last = f[f.length - 1];
1066
- if (ev.shiftKey && document.activeElement === first) { ev.preventDefault(); last.focus(); }
1067
- else if (!ev.shiftKey && document.activeElement === last) { ev.preventDefault(); first.focus(); }
1068
- }
1069
- if (copyText) {
1070
- const label = m.copyLabel || "Copy";
1071
- const copyBtn = el("button", { class: "pc-btn pc-btn-sm", type: "button" }, label);
1072
- copyBtn.addEventListener("click", async () => {
1073
- const ok = await copyToClipboard(copyText);
1074
- copyBtn.textContent = ok ? "Copied ✓" : "Press ⌘/Ctrl+C";
1075
- setTimeout(() => { copyBtn.textContent = label; }, 2200);
1076
- });
1077
- actions.append(copyBtn);
1078
- }
1079
- const closeBtn = el("button", { class: "pc-btn pc-btn-sm pc-btn-ghost", type: "button" }, m.closeLabel || "Close");
1080
- closeBtn.addEventListener("click", close);
1081
- actions.append(closeBtn);
1082
- dialog.append(actions);
1083
- overlay.append(dialog);
1084
- // A click on the backdrop (never the dialog itself) dismisses.
1085
- overlay.addEventListener("click", (ev) => { if (ev.target === overlay) close(); });
1086
- document.addEventListener("keydown", onKey);
1087
- document.body.append(overlay);
1088
- // A page switch runs teardown() before the next render — dispose the modal
1089
- // there too so navigating away never leaves a stale overlay + keydown listener.
1090
- disposers.push(close);
1091
- closeBtn.focus();
1092
- }
1093
-
1094
- // A standalone button node. Clicking it opens props.modal — used e.g. to surface
1095
- // a copy-pasteable "point your agent here" prompt. props.variant === "ghost"
1096
- // renders the muted outline style. A button without a modal is inert.
1097
- function renderButton(node) {
1098
- const p = node.props || {};
1099
- const btn = el(
1100
- "button",
1101
- { class: "pc-btn" + (p.variant === "ghost" ? " pc-btn-ghost" : ""), type: "button" },
1102
- p.label || "Open",
1103
- );
1104
- const m = p.modal && typeof p.modal === "object" ? p.modal : null;
1105
- if (m) btn.addEventListener("click", () => openModal(m));
1106
- return el("div", { class: "pc-buttonrow" }, btn);
1107
- }
1108
-
1109
- // A grid td cell with three column-declared rendering modes, checked in order:
1110
- // 1. badge — a compact status indicator, gated on a non-empty field value
1111
- // (see the detailed note at the check below).
1112
- // 2. linkField — the cell text becomes a link to the URL held in that other
1113
- // field. Only http(s) hrefs are linked (a javascript:/other-scheme URL
1114
- // smuggled through row data falls back to plain text).
1115
- // 3. link: { kind: "processExplorer", keyField } — a structured, engine-aware
1116
- // link: the cell text links to the Nano console's explorer view for the
1117
- // process instance whose key is held in the row's keyField. The console
1118
- // path is constructed HERE (never taken from row data) and the key is
1119
- // URL-encoded, so row data can't smuggle a path or scheme; only a
1120
- // non-empty key (after trimming surrounding whitespace) produces a link.
1121
- // Unknown link kinds fall back to plain text so an unrecognised schema
1122
- // can't render a broken anchor.
1123
- // The external linkField anchor always opens in a new tab (rel=noopener
1124
- // noreferrer). The processExplorer anchor does too when the app runs
1125
- // standalone, but when embedded in the console a plain click instead routes the
1126
- // host's own explorer view in place via the nano-navigate postMessage bridge
1127
- // (a modified/middle click keeps the new-tab behavior). Shared by the top-level
1128
- // grid and child grids.
1129
712
  //
1130
- // Cell TEXT (the 'text' local below): the visible string a cell renders. By
1131
- // default it is the column's single 'field' value, but an optional
1132
- // 'col.template' string wins: its {{field}} tokens are spliced from the row
1133
- // (interpTemplate) into DOM text. A template lets one cell combine several
1134
- // fields / add surrounding text (e.g. "{{current_wave}}/{{wave_count}}")
1135
- // without denormalising a display column into the datasource. The template
1136
- // drives the rendered text for the plain, linkField and link
1137
- // (page/processExplorer) paths — a link's href still comes from its own
1138
- // keyField/linkField, never the template. The 'badge' presence gate and its
1139
- // tooltip stay keyed to the raw 'field' value (a badge shows a fixed glyph, not
1140
- // the field text), so a template does not change badge behaviour. Sorting,
1141
- // groupBy and orderBy also key off real fields, never the rendered template.
1142
- //
1143
- // Two-line identity + one-line clamp (additive, opt-in, backward-compatible):
1144
- // a column may also declare 'subtitleField'/'subtitleTemplate' to render a muted
1145
- // second line under the primary text (the identity key beneath a title, GitHub/
1146
- // Linear style) and 'truncate: true' to clamp each line to one row with an
1147
- // ellipsis and a full-text title/aria-label tooltip (pairs with a per-column
1148
- // width/weight — see buildColgroup — to give the clip a bounded column). The
1149
- // subtitle is ALWAYS plain DOM text, never an href source. With none of these
1150
- // set the cell is a single inline node exactly as before (see cellTd).
1151
- // Build an in-app hash route to another page, scoped to a row key: #/<page>/<key>.
1152
- // The page id is validated against the safe-id charset and the key must be
1153
- // non-empty (after trimming); either failing yields "" (no link). The key is
1154
- // URL-encoded into the route's param tail, which parseRoute() decodes back
1155
- // verbatim, so row data can't smuggle a path or scheme. SINGLE source of truth
1156
- // for the page-link href so the grid's link cell and the pipeline locus link
1157
- // (issue #265) can't drift on how the route is built.
1158
- function pageHashHref(page, key) {
1159
- const keyStr = key == null ? "" : String(key).trim();
1160
- if (!safePageId(page) || keyStr === "") return "";
1161
- return "#/" + encodeURIComponent(page) + "/" + encodeURIComponent(keyStr);
1162
- }
1163
-
1164
- // Coerce a not-in-path value (issue #265) into a Set of stage keys. Accepts an
1165
- // array of keys or a comma/whitespace-separated string; null/undefined → empty
1166
- // set. Used to mark the stages a given row skips (dashed/omitted).
1167
- function toStageSet(v) {
1168
- // Trim + drop-empties on BOTH inputs so array entries with stray whitespace
1169
- // (e.g. from CSV/JSON munging) match stages[].key just like the string path.
1170
- if (Array.isArray(v)) return new Set(v.map((s) => String(s).trim()).filter((s) => s !== ""));
1171
- if (v == null) return new Set();
1172
- return new Set(String(v).split(/[\s,]+/).filter((s) => s !== ""));
1173
- }
1174
-
1175
- function gridCell(col, row, role) {
1176
- // Mobile card attributes stamped on every td so a dataGrid can flip to a
1177
- // stacked card list below the breakpoint with no JS branching (#268):
1178
- // 'data-label' drives the pure-CSS label:value line (the column header, or a
1179
- // mobile:{label} override), and the role class picks the card region (title /
1180
- // status chip / secondary field / hidden). The role is derived by convention
1181
- // (classifyColumns) and refinable per-column via col.mobile.priority.
1182
- const mrole = role || "secondary";
1183
- const mlabel =
1184
- col.mobile && typeof col.mobile.label === "string"
1185
- ? col.mobile.label
1186
- : col.header != null
1187
- ? String(col.header)
1188
- : String(col.field == null ? "" : col.field);
1189
- const mob = { class: "pc-mcell pc-mcell-" + mrole, "data-label": mlabel };
1190
- // Raw single-field value: drives the badge presence gate + tooltip and any
1191
- // field-derived defaults. Kept separate from the (possibly templated) display
1192
- // text so a template never re-lights or blanks a badge.
1193
- const rawText = row[col.field] == null ? "" : String(row[col.field]);
1194
- // Visible text: a col.template (interpolated from the row) wins over the
1195
- // raw field value, else the field value is shown verbatim.
1196
- const text = typeof col.template === "string" ? interpTemplate(col.template, row) : rawText;
1197
- // 1. badge — a compact status indicator. When the row's field value is
1198
- // non-empty (truthy after trimming) render a small circular badge (e.g. a
1199
- // red "1" dot flagging an incident) whose tooltip is the full field text;
1200
- // when empty the cell stays blank so the column is unobtrusive until it
1201
- // matters. tone (danger|warn|ok|info, default danger) picks the color and
1202
- // label the glyph inside (default "1"). Label/tone come from the app
1203
- // schema (trusted); the tooltip is row data set via title/textContent
1204
- // (DOM-escaped by the platform, so no HTML/attribute injection). The full
1205
- // field text is also mirrored into aria-label so assistive tech announces
1206
- // the incident/status text (the visible "1" glyph alone is not meaningful).
1207
- if (col.badge) {
1208
- // Even when blank, stamp data-label (the "every td carries data-label"
1209
- // invariant): the cell still collapses on mobile via the pc-mcell-chip:empty
1210
- // rule (attributes don't defeat :empty), so this keeps empty and non-empty
1211
- // badge cells consistent without re-lighting the label.
1212
- if (rawText.trim() === "") return el("td", { class: "pc-mcell pc-mcell-chip", "data-label": mlabel });
1213
- const t = col.badge.tone;
1214
- const tone = t === "warn" || t === "ok" || t === "info" ? t : "danger";
1215
- const label = col.badge.label == null ? "1" : String(col.badge.label);
1216
- return el(
1217
- "td",
1218
- mob,
1219
- el("span", { class: "pc-badge pc-badge-" + tone, title: rawText, "aria-label": rawText }, label),
1220
- );
1221
- }
1222
- // Optional second line (col.subtitleField / subtitleTemplate): a muted key
1223
- // under the primary title. subtitleTemplate wins (interpolated from the row);
1224
- // else the raw subtitleField value. Absent/null → "" → no extra line. It is
1225
- // ALWAYS plain DOM text (see cellTd), never a link/href source — a subtitle
1226
- // cannot smuggle a scheme or path, only linkField/keyField drive hrefs.
1227
- const subRaw =
1228
- col.subtitleField != null && row[col.subtitleField] != null ? String(row[col.subtitleField]) : "";
1229
- const subText = typeof col.subtitleTemplate === "string" ? interpTemplate(col.subtitleTemplate, row) : subRaw;
1230
- const truncate = col.truncate === true;
1231
- // pipeline (issue #265): a dataGrid column declaring kind:"pipeline" renders
1232
- // the ordered stages as a per-row horizontal progress track (upstream-filled
1233
- // → active-lit → downstream-ghosted, not-in-path dashed). It owns the whole
1234
- // cell, so it returns here before the link chain below. Gated purely on the
1235
- // discriminator so every existing column mode is untouched when it is absent;
1236
- // unknown/missing pipeline config degrades to plain cell text (never throws),
1237
- // exactly as an unrecognised link.kind falls back today.
1238
- if (col.kind === "pipeline") return pipelineCell(col, row, text, subText, truncate, mob);
1239
- // Primary inline content: an anchor for a valid link mode (checked in the same
1240
- // badge < linkField < link(page) < link(processExplorer) precedence as before),
1241
- // else the plain display text. Each link mode only claims the cell while
1242
- // 'primary' is still the bare text — an invalid href falls through to the next
1243
- // mode and ultimately to plain text, exactly as the early-return chain did.
1244
- let primary = text;
1245
- if (col.linkField) {
1246
- const href = row[col.linkField] == null ? "" : String(row[col.linkField]);
1247
- if (text !== "" && /^https?:\/\//i.test(href)) {
1248
- primary = el("a", { class: "pc-link", href, target: "_blank", rel: "noopener noreferrer" }, text);
1249
- }
1250
- }
1251
- if (primary === text && col.link && col.link.kind === "page" && col.link.page && col.link.keyField) {
1252
- // An in-app link to another page, scoped to this row: #/<page>/<key>. Built
1253
- // via pageHashHref (the single source of truth for the route): the page id is
1254
- // validated against the safe-id charset and the key must be non-empty, so a
1255
- // blank/keyless cell stays plain text. Navigation is a pure hash change
1256
- // (no new tab, no server hit) — the SPA router re-renders in place.
1257
- const href = pageHashHref(col.link.page, row[col.link.keyField]);
1258
- if (text !== "" && href !== "") {
1259
- primary = el("a", { class: "pc-link", href }, text);
1260
- }
1261
- }
1262
- if (primary === text && col.link && col.link.kind === "processExplorer" && col.link.keyField) {
1263
- const key = row[col.link.keyField];
1264
- const keyStr = key == null ? "" : String(key).trim();
1265
- if (text !== "" && keyStr !== "") {
1266
- const href = "/console/explorer?instance=" + encodeURIComponent(keyStr);
1267
- primary = el("a", {
1268
- class: "pc-link",
1269
- href,
1270
- target: "_blank",
1271
- rel: "noopener noreferrer",
1272
- // Embedded in the console a plain primary click routes the host's
1273
- // explorer in place (via the nano-navigate bridge) instead of opening
1274
- // a new window. A non-primary button (middle/right = new-tab/context
1275
- // intent), a modified click (⌘/ctrl/shift/alt = new-tab intent) and
1276
- // any standalone run fall through to the native anchor above.
1277
- onclick: (ev) => {
1278
- if (ev.button !== 0) return;
1279
- if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
1280
- if (hostNavigate("processExplorer", { instance: keyStr })) ev.preventDefault();
1281
- },
1282
- }, text);
1283
- }
1284
- }
1285
- return cellTd(primary, text, subText, truncate, mob);
1286
- }
1287
-
1288
- // Compose a grid <td> from its primary inline content (a string or an anchor),
1289
- // an optional muted subtitle line, and optional one-line truncation. With
1290
- // NEITHER a subtitle nor truncation the cell is exactly the single inline node
1291
- // as before, so existing grids render byte-for-byte unchanged (backward
1292
- // compatible). When either is set the content is wrapped in a .pc-cell-main
1293
- // line and, if a subtitle is present, a .pc-cell-sub line beneath it. truncate
1294
- // adds .pc-truncate (nowrap + ellipsis) to each line and mirrors the full text
1295
- // into title=/aria-label so the clipped value is still recoverable on hover and
1296
- // to assistive tech. When the primary is an element (a link cell's <a>), title=/
1297
- // aria-label= are ALSO mirrored onto it: HTML does not inherit those to
1298
- // descendants, so hovering the link text or naming the anchor for assistive tech
1299
- // would otherwise miss the full value the wrapper carries. The subtitle is set as
1300
- // DOM text only — never an href. 'tdAttrs' (the mobile card attrs: data-label +
1301
- // role class, see gridCell) is applied to whichever <td> shape is returned so
1302
- // the CSS-only card flip labels every cell identically (#268).
1303
- function cellTd(primary, primaryText, subText, truncate, tdAttrs) {
1304
- const td = tdAttrs || {};
1305
- if (subText === "" && !truncate) return el("td", td, primary);
1306
- const mainAttrs = { class: "pc-cell-main" + (truncate ? " pc-truncate" : "") };
1307
- if (truncate && primaryText !== "") {
1308
- mainAttrs.title = primaryText; mainAttrs["aria-label"] = primaryText;
1309
- if (primary && typeof primary.setAttribute === "function") {
1310
- primary.setAttribute("title", primaryText); primary.setAttribute("aria-label", primaryText);
1311
- }
1312
- }
1313
- const main = el("div", mainAttrs, primary);
1314
- if (subText === "") return el("td", td, main);
1315
- const subAttrs = { class: "pc-cell-sub" + (truncate ? " pc-truncate" : "") };
1316
- if (truncate) { subAttrs.title = subText; subAttrs["aria-label"] = subText; }
1317
- return el("td", td, main, el("div", subAttrs, subText));
1318
- }
1319
-
1320
- // Classify each grid column into a mobile-card region so a dataGrid flips to a
1321
- // stacked card list below the breakpoint with ZERO page-schema change (#268).
1322
- // Convention (Tier 0): the first non-badge column is the card title (primary), a
1323
- // badge column is a status chip, and everything else is a secondary label:value
1324
- // row. Tier 1 refines it — a column may carry mobile:{priority:"primary" |
1325
- // "secondary" | "hidden"}: an explicit "primary" suppresses the auto title pick
1326
- // so a later column can lead the card, "hidden" drops the column off the card
1327
- // (behind the row's "More" toggle), and "secondary" forces a plain field row.
1328
- function classifyColumns(cols) {
1329
- const list = cols || [];
1330
- const explicitPrimary = list.some((c) => c && c.mobile && c.mobile.priority === "primary");
1331
- let titleTaken = explicitPrimary;
1332
- return list.map((col) => {
1333
- const pr = col && col.mobile ? col.mobile.priority : null;
1334
- if (pr === "primary") return "primary";
1335
- if (pr === "secondary") return "secondary";
1336
- if (pr === "hidden") return "hidden";
1337
- if (col && col.badge) return "chip";
1338
- if (!titleTaken) { titleTaken = true; return "primary"; }
1339
- return "secondary";
1340
- });
1341
- }
1342
-
1343
- // Per-row mobile "More" toggle cell: reveals the mobile:{priority:"hidden"} columns
1344
- // a narrow viewport drops off the card. The cell is base-hidden (display:none) so
1345
- // the desktop table is byte-for-byte unchanged; clicking flips .pc-open on the row,
1346
- // swaps the label, and updates aria-expanded so the reveal state is exposed to
1347
- // assistive tech (#268). One implementation shared by the top-level grid and child
1348
- // grids so the affordance — and its accessibility — can't drift between them.
1349
- function mobileMoreCell(tr) {
1350
- const moreBtn = el("button",
1351
- { class: "pc-btn pc-btn-sm pc-btn-ghost pc-more", type: "button", "aria-expanded": "false" }, "More");
1352
- moreBtn.addEventListener("click", () => {
1353
- const open = tr.classList.toggle("pc-open");
1354
- moreBtn.textContent = open ? "Less" : "More";
1355
- moreBtn.setAttribute("aria-expanded", String(open));
1356
- });
1357
- return el("td", { class: "pc-mcard-toggle" }, moreBtn);
1358
- }
1359
-
1360
- // Pipeline / stepper cell (issue #265) — a dataGrid column with kind:"pipeline"
1361
- // renders a per-row, multi-stage horizontal progress track. It is RENDER-ONLY:
1362
- // stage state is read straight from the row fields the app supplies; no
1363
- // app-specific stage derivation lives here. Column config (all fields are the
1364
- // NAMES of row fields, mirroring the issue sketch):
1365
- // { kind:"pipeline",
1366
- // stages:[{key,label},...], // ordered stage definitions (required)
1367
- // activeField:"stage", // row field → the current stage's key
1368
- // stateField:"stage_state", // row field → ok | active | failed | blocked
1369
- // badgeField:"attention", // optional row field → badge text shown on the active stage
1370
- // notInPathField:"skipped", // optional row field → stages this row skips
1371
- // notInPath:["converging"], // static fallback used only when no field given
1372
- // locus:{ field:"pr_key", stage?:"<key>",
1373
- // link:{ kind:"page", page:"home" } } } // optional out-link
1374
- // Rendering: stages BEFORE the active one are filled/completed, the active stage
1375
- // is lit (its treatment driven by stateField — success ✓ vs failure ✕ vs blocked
1376
- // ⊘ are made unmistakably distinct), in-path stages AFTER it are ghosted, and any
1377
- // stage in the row's not-in-path set is dashed. Reuses the .pc-badge and .pc-link
1378
- // classes and the shared pageHashHref route builder — no parallel implementations. Unknown or
1379
- // missing config (no stages array) degrades gracefully to plain cell text.
1380
- function pipelineCell(col, row, text, subText, truncate, tdAttrs) {
1381
- // Drop null/undefined entries defensively: a schema with a hole must still
1382
- // render (never throws on s.key) — same graceful-degradation goal as below.
1383
- const stages = Array.isArray(col.stages) ? col.stages.filter((s) => s != null) : [];
1384
- // Graceful fallback: an unrecognised/empty pipeline config renders plain text,
1385
- // exactly like an unknown link.kind — never throws.
1386
- if (stages.length === 0) return cellTd(text, text, subText, truncate, tdAttrs);
1387
- // The current stage's key, matched against stages[].key to find the active index.
1388
- // The row value is trimmed for consistency with the other row-derived keys
1389
- // (pageHashHref, toStageSet), so a whitespace-padded value still matches its stage
1390
- // instead of leaving the whole track rendered as upcoming.
1391
- // Stage keys identify a single stage, so stop at the first match: the result is
1392
- // deterministic even if a config accidentally repeats a key, and we avoid scanning
1393
- // the remaining stages on every row.
1394
- const activeKey = col.activeField != null && row[col.activeField] != null ? String(row[col.activeField]).trim() : "";
1395
- let activeIdx = -1;
1396
- for (let i = 0; i < stages.length; i++) {
1397
- if (String(stages[i].key) === activeKey) {
1398
- activeIdx = i;
1399
- break;
1400
- }
1401
- }
1402
- // The active stage's state drives its lit/failed/blocked treatment. Anything
1403
- // outside the allow-list (or absent) is treated as an in-progress "active".
1404
- const stRaw = col.stateField != null && row[col.stateField] != null ? String(row[col.stateField]) : "";
1405
- const state = stRaw === "ok" || stRaw === "failed" || stRaw === "blocked" ? stRaw : "active";
1406
- // Not-in-path (skipped) stages: driven per-row from notInPathField when given,
1407
- // else the static notInPath config (per the issue: "per row, from a field").
1408
- const skip =
1409
- col.notInPathField != null && row[col.notInPathField] != null
1410
- ? toStageSet(row[col.notInPathField])
1411
- : toStageSet(col.notInPath);
1412
- // Optional active-stage badge (escalation/attention → warn, blocked/failure →
1413
- // danger), reusing .pc-badge tone classes — no new badge styles. The badge text
1414
- // is a single row-level value (row[badgeField]) shown only on the active stage.
1415
- const badgeText = col.badgeField != null && row[col.badgeField] != null ? String(row[col.badgeField]) : "";
1416
- const badgeTone = state === "failed" || state === "blocked" ? "danger" : "warn";
1417
- // Optional locus out-link: the relevant stage (default the active one, or
1418
- // locus.stage by key) becomes an in-app page link when the row's locus key is
1419
- // non-empty. Href comes from the shared pageHashHref builder (safePageId guard,
1420
- // encodeURIComponent) — a blank key yields "" so the stage stays plain.
1421
- const locus = col.locus;
1422
- const locusKey = locus && locus.field != null && row[locus.field] != null ? String(row[locus.field]) : "";
1423
- const locusHref =
1424
- locus && locus.link && locus.link.kind === "page" && locus.link.page ? pageHashHref(locus.link.page, locusKey) : "";
1425
- const track = el("div", {
1426
- class: "pc-pipe",
1427
- role: "list",
1428
- "aria-label": "Progress" + (activeIdx >= 0 ? ": " + labelOf(stages[activeIdx]) : ""),
1429
- });
1430
- for (let i = 0; i < stages.length; i++) {
1431
- const s = stages[i];
1432
- // Active wins over skip: if the active stage's key is also in the not-in-path
1433
- // set, it must still render as the current step (active styling + aria-current),
1434
- // never as skipped. Excluding activeIdx here keeps that precedence consistent
1435
- // across the stage class, the aria-current mark, and the connector fill below.
1436
- const skipped = i !== activeIdx && skip.has(String(s.key));
1437
- // Connector between adjacent stages; filled up to and including the active
1438
- // stage, but never across a not-in-path stage — a skipped predecessor breaks
1439
- // the fill so we don't visually imply it was on the path.
1440
- if (i > 0) {
1441
- const filled =
1442
- activeIdx >= 0 && i <= activeIdx && !skipped && !skip.has(String(stages[i - 1].key)) ? " filled" : "";
1443
- track.append(el("span", { class: "pc-pipe-conn" + filled, "aria-hidden": "true" }));
1444
- }
1445
- let cls;
1446
- let word;
1447
- let glyph = "";
1448
- let current = false;
1449
- if (skipped) {
1450
- cls = "pc-pipe-skip"; word = "skipped";
1451
- } else if (activeIdx >= 0 && i < activeIdx) {
1452
- cls = "pc-pipe-done"; word = "completed";
1453
- } else if (i === activeIdx) {
1454
- current = true;
1455
- if (state === "failed") { cls = "pc-pipe-active pc-pipe-failed"; word = "failed"; glyph = "\u2715"; }
1456
- else if (state === "blocked") { cls = "pc-pipe-active pc-pipe-blocked"; word = "blocked"; glyph = "\u2298"; }
1457
- else if (state === "ok") { cls = "pc-pipe-active pc-pipe-ok"; word = "done"; glyph = "\u2713"; }
1458
- else { cls = "pc-pipe-active"; word = "current"; }
1459
- } else {
1460
- cls = "pc-pipe-upcoming"; word = "upcoming";
1461
- }
1462
- const isLocus = locusHref !== "" && (locus.stage != null ? String(s.key) === String(locus.stage) : i === activeIdx);
1463
- const label = labelOf(s);
1464
- const labelNode = isLocus
1465
- ? el("a", { class: "pc-link pc-pipe-label", href: locusHref }, label)
1466
- : el("span", { class: "pc-pipe-label" }, label);
1467
- const attrs = { class: "pc-pipe-stage " + cls, role: "listitem", "aria-label": label + " \u2014 " + word };
1468
- if (current) attrs["aria-current"] = "step";
1469
- const stage = el("span", attrs, labelNode);
1470
- if (glyph !== "") stage.append(el("span", { class: "pc-pipe-mark", "aria-hidden": "true" }, glyph));
1471
- if (current && badgeText.trim() !== "") {
1472
- stage.append(el("span", { class: "pc-badge pc-badge-" + badgeTone, title: badgeText, "aria-label": badgeText }, badgeText));
1473
- }
1474
- track.append(stage);
1475
- }
1476
- // The mobile card attrs (data-label + role class, #268) stamped by gridCell are
1477
- // merged onto the pipeline <td> too, alongside its own pc-pipe-cell class, so a
1478
- // pipeline column labels and classifies identically under the CSS-only card flip.
1479
- const cellAttrs = { ...(tdAttrs || {}), class: (tdAttrs && tdAttrs.class ? tdAttrs.class + " " : "") + "pc-pipe-cell" };
1480
- return el("td", cellAttrs, track);
1481
- }
1482
-
1483
- // A stage's visible label: its declared label, else its key as a fallback.
1484
- function labelOf(stage) {
1485
- return stage.label == null ? String(stage.key) : String(stage.label);
1486
- }
1487
-
1488
- // Parse a "<number>%" width into its numeric percentage, or null if the string
1489
- // is not a bare percentage (e.g. "22rem", "120px") — used to decide whether the
1490
- // remainder left for weighted columns can be computed.
1491
- function colWidthPct(width) {
1492
- const m = /^\s*([0-9]*\.?[0-9]+)%\s*$/.exec(width);
1493
- return m ? parseFloat(m[1]) : null;
1494
- }
1495
-
1496
- // A column carries an explicit width only when it is a non-empty string. Single
1497
- // source of truth so colWidthStyle/buildColgroup can't drift on what "explicit"
1498
- // means (which columns win verbatim, consume the remainder, or use their weight).
1499
- function hasExplicitWidth(col) {
1500
- return typeof col.width === "string" && col.width !== "";
1501
- }
1502
-
1503
- // A column's <col> width for the grid's <colgroup>: an explicit col.width string
1504
- // ("40%", "22rem") wins verbatim; else a positive numeric col.weight is
1505
- // normalised across the weighted columns into a percentage share of the width
1506
- // left over by explicit columns (remainderPct); else null (no width — the column
1507
- // shares the remainder equally under table-layout:fixed).
1508
- function colWidthStyle(col, weightTotal, remainderPct) {
1509
- if (hasExplicitWidth(col)) return col.width;
1510
- if (typeof col.weight === "number" && col.weight > 0 && weightTotal > 0) {
1511
- return Math.round((col.weight / weightTotal) * remainderPct * 100) / 100 + "%";
1512
- }
1513
- return null;
1514
- }
1515
-
1516
- // Build a <colgroup> that sizes the grid's columns so table-layout:fixed stops
1517
- // splitting width equally. Returns null when no column declares width/weight, so
1518
- // an unsized grid emits no colgroup and lays out exactly as today. 'extraCount'
1519
- // adds trailing unsized <col>s for the row-actions/detail column so the sized
1520
- // data columns stay aligned with their headers.
1521
- function buildColgroup(cols, extraCount) {
1522
- const hasSizing = cols.some(
1523
- (c) => hasExplicitWidth(c) || (typeof c.weight === "number" && c.weight > 0),
1524
- );
1525
- if (!hasSizing) return null;
1526
- // Only columns that will actually use their weight (no explicit width — an
1527
- // explicit width wins verbatim in colWidthStyle and never consumes weight)
1528
- // contribute to weightTotal; counting a width-bearing column's weight here
1529
- // would inflate the divisor and shrink the truly-weighted columns' share.
1530
- let weightTotal = 0;
1531
- for (const c of cols)
1532
- if (!hasExplicitWidth(c) && typeof c.weight === "number" && c.weight > 0) weightTotal += c.weight;
1533
- // Weighted columns share only the width the explicit columns leave behind, so
1534
- // mixing e.g. width:"40%" with weighted columns can't oversubscribe past 100%.
1535
- // The remainder is only computable when every explicit width is a percentage;
1536
- // if any uses an absolute/relative unit (rem/px) we can't subtract it from
1537
- // 100%, so weighted columns fall back to a share of the full width.
1538
- let explicitPctTotal = 0;
1539
- let allExplicitArePct = true;
1540
- for (const c of cols) {
1541
- if (hasExplicitWidth(c)) {
1542
- const pct = colWidthPct(c.width);
1543
- if (pct === null) allExplicitArePct = false;
1544
- else explicitPctTotal += pct;
1545
- }
1546
- }
1547
- const remainderPct = allExplicitArePct ? Math.max(0, 100 - explicitPctTotal) : 100;
1548
- const colEls = cols.map((c) => {
1549
- const w = colWidthStyle(c, weightTotal, remainderPct);
1550
- return el("col", w ? { style: "width:" + w } : {});
1551
- });
1552
- for (let i = 0; i < extraCount; i++) colEls.push(el("col", {}));
1553
- return el("colgroup", {}, ...colEls);
1554
- }
1555
-
1556
- function renderActionForm(node) {
1557
- const p = node.props;
1558
- const card = el("section", { class: "pc-card" });
1559
- if (p.title) card.append(el("h2", {}, p.title));
1560
- // Map/null-proto stores so a schema field keyed __proto__/constructor can't
1561
- // pollute Object.prototype or shadow inherited props (prototype-pollution class).
1562
- const inputs = new Map();
1563
- const fieldTypes = new Map();
1564
- // Client-side required-field validation state: the set of required keys, each
1565
- // field's custom message, and its inline error node (populated on a blocked
1566
- // submit, cleared as soon as the user edits the field).
1567
- const required = new Set();
1568
- const reqMsg = new Map();
1569
- const errs = new Map();
1570
- // A required field's label carries a danger-toned "*" so the requirement is
1571
- // visible BEFORE submit; spread into el(...) — an empty array adds no child.
1572
- const reqMark = (f) => (f.required === true ? [el("span", { class: "pc-req", title: "Required" }, " *")] : []);
1573
- // Register a field's inline error node and, when required, mark the input
1574
- // (aria-required) and wire a clear-on-edit handler so a hint disappears the
1575
- // moment the user starts fixing it. Editing a required field also clears the
1576
- // blocked-submit summary ("Please fill in the required fields.") so it never
1577
- // lingers as a stale/misleading banner while the user is correcting input.
1578
- const wireField = (f, input, ferr, evt) => {
1579
- errs.set(f.key, ferr);
1580
- if (f.required !== true) return;
1581
- required.add(f.key);
1582
- if (typeof f.requiredMessage === "string" && f.requiredMessage !== "") reqMsg.set(f.key, f.requiredMessage);
1583
- input.setAttribute("aria-required", "true");
1584
- input.addEventListener(evt, () => {
1585
- input.classList.remove("pc-invalid");
1586
- input.removeAttribute("aria-invalid");
1587
- ferr.textContent = "";
1588
- msg.textContent = "";
1589
- msg.className = "pc-msg";
1590
- });
1591
- };
1592
- for (const f of p.fields || []) {
1593
- const kind = f.type === "checkbox" ? "checkbox" : (f.type === "number" ? "number" : "text");
1594
- fieldTypes.set(f.key, kind);
1595
- const ferr = el("p", { class: "pc-field-err" });
1596
- if (kind === "checkbox") {
1597
- // A boolean field renders a real checkbox; its default checked state comes
1598
- // from default/checked on the field (unset -> unchecked). We record that on
1599
- // the input's defaultChecked so a post-submit reset can restore it without a
1600
- // side map that could drift from the actual input.
1601
- const checked = f.default === true || f.checked === true;
1602
- const input = el("input", { type: "checkbox" });
1603
- input.defaultChecked = checked;
1604
- input.checked = checked;
1605
- inputs.set(f.key, input);
1606
- wireField(f, input, ferr, "change");
1607
- // Input-first, wrapped in the label so the whole row is a click target.
1608
- card.append(
1609
- el("div", { class: "pc-field pc-field-check" }, el("label", {}, input, " " + (f.label || f.key), ...reqMark(f)), ferr),
1610
- );
1611
- continue;
1612
- }
1613
- const attrs = { type: kind, placeholder: f.label || f.key };
1614
- if (kind === "number") {
1615
- attrs.inputmode = "numeric";
1616
- if (f.min != null) attrs.min = String(f.min);
1617
- if (f.max != null) attrs.max = String(f.max);
1618
- attrs.step = f.step != null ? String(f.step) : "1";
1619
- }
1620
- const input = el("input", attrs);
1621
- inputs.set(f.key, input);
1622
- wireField(f, input, ferr, "input");
1623
- card.append(el("div", { class: "pc-field" }, el("label", {}, f.label || f.key, ...reqMark(f)), input, ferr));
1624
- }
1625
- const msg = el("p", { class: "pc-msg" });
1626
- const btn = el("button", { class: "pc-btn" }, p.submitLabel || "Submit");
1627
- btn.addEventListener("click", async () => {
1628
- // Required-field gate: block the submit and surface an inline hint on each
1629
- // empty required field (a text/number left blank, a required checkbox left
1630
- // unchecked), focusing the first offender — so a missing value never
1631
- // round-trips to the server only to bounce back as a generic error.
1632
- let firstInvalid = null;
1633
- for (const [k, input] of inputs) {
1634
- const ferr = errs.get(k);
1635
- if (ferr) ferr.textContent = "";
1636
- input.classList.remove("pc-invalid");
1637
- input.removeAttribute("aria-invalid");
1638
- if (!required.has(k)) continue;
1639
- const type = fieldTypes.get(k);
1640
- const val = String(input.value).trim();
1641
- const missing = type === "checkbox"
1642
- ? input.checked !== true
1643
- : type === "number"
1644
- ? (val === "" || !Number.isFinite(Number(val)))
1645
- : val === "";
1646
- if (missing) {
1647
- if (ferr) ferr.textContent = reqMsg.get(k) || "Required";
1648
- input.classList.add("pc-invalid");
1649
- input.setAttribute("aria-invalid", "true");
1650
- if (!firstInvalid) firstInvalid = input;
1651
- }
1652
- }
1653
- if (firstInvalid) {
1654
- msg.className = "pc-msg err";
1655
- msg.textContent = "Please fill in the required fields.";
1656
- firstInvalid.focus();
1657
- return;
1658
- }
1659
- const variables = Object.create(null);
1660
- for (const [k, input] of inputs) {
1661
- if (fieldTypes.get(k) === "checkbox") {
1662
- // Always emit a real boolean (checked -> true / false), never a string,
1663
- // so a strict equality check on the action side sees the intended value.
1664
- variables[k] = input.checked === true;
1665
- } else if (fieldTypes.get(k) === "number") {
1666
- const t = String(input.value).trim();
1667
- // Blank → omit so the action-side default applies; a non-finite parse
1668
- // (NaN/Infinity) is also omitted rather than smuggling a raw string
1669
- // process variable through, which would defeat the numeric coercion.
1670
- if (t === "") continue;
1671
- const num = Number(t);
1672
- if (!Number.isFinite(num)) continue;
1673
- variables[k] = num;
1674
- } else {
1675
- variables[k] = input.value;
1676
- }
1677
- }
1678
- btn.disabled = true; msg.className = "pc-msg"; msg.textContent = "Submitting…";
1679
- try {
1680
- // Route-driven: POST the form (as { variables } by default, or the action's
1681
- // own body template) to the action's route path. correlationKey / process /
1682
- // message are expressed by the path + body template the page author supplies,
1683
- // e.g. { path: "/app/actions/message", body: { name, correlationKey, variables: "{{form}}" } }.
1684
- const res = await runRoute(p.action, { form: variables });
1685
- msg.className = "pc-msg ok";
1686
- msg.textContent = (p.action && p.action.successLabel) ||
1687
- (res && res.processInstanceKey != null ? "Started (instance " + res.processInstanceKey + ")" : "Done");
1688
- for (const [k, input] of inputs) {
1689
- // Text/number inputs clear; a checkbox resets to its declared default,
1690
- // read straight off the input's defaultChecked (no side map to drift).
1691
- if (fieldTypes.get(k) === "checkbox") input.checked = input.defaultChecked;
1692
- else input.value = "";
1693
- }
1694
- document.dispatchEvent(new CustomEvent("pc:refresh"));
1695
- } catch (e) {
1696
- msg.className = "pc-msg err"; msg.textContent = String(e.message || e);
1697
- } finally { btn.disabled = false; }
1698
- });
1699
- card.append(btn, msg);
1700
- return card;
1701
- }
1702
-
1703
- // Accessible name for the row-count badge. The visible text is just a number, so an
1704
- // aria-label would override it with a bare "row count" (the count — the important part —
1705
- // is dropped). Instead name it "N row(s)" and keep it in sync with the text on refresh.
1706
- // Single source of truth for both the initial render and every refresh below.
1707
- function rowCountLabel(n) { return n + (n === 1 ? " row" : " rows"); }
1708
-
1709
- // Build the /app/data/<source>/<table> URL a data-bound list renderer fetches,
1710
- // threading the whitelisted where/order query params. Shared by dataGrid and the
1711
- // prose renderer so the two can't drift on how a filter/orderBy is encoded. A
1712
- // filter is { field, in:[…] } (IN set), { field, eqParam:true } (bound to the
1713
- // current route PARAM — "show the selected entity's rows"), or { field, eq } (a
1714
- // literal equals); orderBy is { field, dir }. The source/table/field names are
1715
- // server-side whitelisted (the /app/data route rejects unknown columns).
1716
- function dataUrl(source, tbl, filters, order) {
1717
- let u = "/app/data/" + encodeURIComponent(source) + "/" + encodeURIComponent(tbl);
1718
- const qs = [];
1719
- for (const f of filters || []) {
1720
- if (Array.isArray(f.in)) qs.push("where=" + encodeURIComponent(f.field + ":in:" + f.in.join(",")));
1721
- else if (f.eqParam) qs.push("where=" + encodeURIComponent(f.field + ":" + PARAM));
1722
- else qs.push("where=" + encodeURIComponent(f.field + ":" + f.eq));
1723
- }
1724
- if (order && order.field) qs.push("order=" + encodeURIComponent(order.field + ":" + (order.dir || "asc")));
1725
- return qs.length ? u + "?" + qs.join("&") : u;
1726
- }
1727
-
1728
- // ── Minimal, safe Markdown → DOM (no innerHTML) — used by the prose renderer ──
1729
- // A dependency-free CommonMark subset. It NEVER sets innerHTML: every block and
1730
- // inline token is materialised as a known element via el(), with text set through
1731
- // textContent / createTextNode — so a record's body field may carry markdown
1732
- // WITHOUT ever becoming an HTML/script injection vector (the same text-only
1733
- // guarantee interpTemplate gives a grid cell). Supported: ATX headings
1734
- // (#..######), fenced + inline code, bold (**/__), italic (*/_), links
1735
- // [text](url) (http/https/mailto only — every other scheme degrades to its plain
1736
- // label), unordered (-,*,+) and ordered (1. / 1)) lists, blockquotes (>),
1737
- // thematic breaks (---), and blank-line-separated paragraphs. The backtick used
1738
- // for code spans/fences is built from a char code so this source stays inside the
1739
- // String.raw template literal (which is itself delimited by a backtick).
1740
- const MD_BACKTICK = String.fromCharCode(96);
1741
- function mdIsWordChar(c) { return typeof c === "string" && /[0-9A-Za-z]/.test(c); }
1742
- // Only http(s)/mailto hrefs become anchors; anything else (javascript:, data:,
1743
- // vbscript:, a bare relative path, …) returns "" so the caller renders the label
1744
- // as plain text rather than a clickable, potentially-hostile link.
1745
- function mdSafeHref(href) {
1746
- const h = String(href == null ? "" : href).trim();
1747
- return /^(?:https?:|mailto:)/i.test(h) ? h : "";
1748
- }
1749
- // Find the closing run of 'marker' at or after 'from'. For underscore emphasis the
1750
- // close must not be intra-word (a following alphanumeric means snake_case, not a
1751
- // delimiter), so keep scanning past such runs; -1 when there is no valid close.
1752
- function mdFindClose(s, marker, from, underscore) {
1753
- let j = from;
1754
- while (true) {
1755
- const k = s.indexOf(marker, j);
1756
- if (k < 0) return -1;
1757
- if (!underscore || !mdIsWordChar(s[k + marker.length])) return k;
1758
- j = k + marker.length;
1759
- }
1760
- }
1761
- function mdInline(text) {
1762
- const s = String(text == null ? "" : text);
1763
- const nodes = [];
1764
- let buf = "";
1765
- const flush = () => { if (buf) { nodes.push(document.createTextNode(buf)); buf = ""; } };
1766
- let i = 0;
1767
- while (i < s.length) {
1768
- const ch = s[i];
1769
- // Backslash escape: the next char is emitted literally, never as a delimiter.
1770
- if (ch === "\\" && i + 1 < s.length) { buf += s[i + 1]; i += 2; continue; }
1771
- // Inline code span — verbatim, no nested inline parsing.
1772
- if (ch === MD_BACKTICK) {
1773
- const end = s.indexOf(MD_BACKTICK, i + 1);
1774
- if (end > i) { flush(); nodes.push(el("code", { class: "pc-md-code" }, s.slice(i + 1, end))); i = end + 1; continue; }
1775
- }
1776
- // Strong (** or __). Underscore only when it opens on a word boundary so an
1777
- // identifier like a__b doesn't get mangled into emphasis.
1778
- if ((ch === "*" || ch === "_") && s[i + 1] === ch) {
1779
- const underscore = ch === "_";
1780
- if (!underscore || !mdIsWordChar(s[i - 1])) {
1781
- const marker = ch + ch;
1782
- const end = mdFindClose(s, marker, i + 2, underscore);
1783
- if (end > i + 1) { flush(); nodes.push(el("strong", {}, ...mdInline(s.slice(i + 2, end)))); i = end + 2; continue; }
1784
- }
1785
- }
1786
- // Emphasis (* or _), same word-boundary guard for underscore.
1787
- if (ch === "*" || ch === "_") {
1788
- const underscore = ch === "_";
1789
- if (!underscore || !mdIsWordChar(s[i - 1])) {
1790
- const end = mdFindClose(s, ch, i + 1, underscore);
1791
- if (end > i + 1) { flush(); nodes.push(el("em", {}, ...mdInline(s.slice(i + 1, end)))); i = end + 1; continue; }
1792
- }
1793
- }
1794
- // Link [label](href): href sanitised; an unsafe scheme drops to the label text.
1795
- if (ch === "[") {
1796
- const close = s.indexOf("]", i + 1);
1797
- if (close > i && s[close + 1] === "(") {
1798
- const paren = s.indexOf(")", close + 2);
1799
- if (paren > close) {
1800
- const href = mdSafeHref(s.slice(close + 2, paren));
1801
- const label = mdInline(s.slice(i + 1, close));
1802
- flush();
1803
- if (href) nodes.push(el("a", { href: href, target: "_blank", rel: "noopener noreferrer" }, ...label));
1804
- else for (const l of label) nodes.push(l);
1805
- i = paren + 1; continue;
1806
- }
1807
- }
1808
- }
1809
- buf += ch; i++;
1810
- }
1811
- flush();
1812
- return nodes;
1813
- }
1814
- // Regexes that classify a block-opening line; shared by the block loop and the
1815
- // paragraph terminator so the two can't disagree on where a paragraph ends.
1816
- const MD_HEADING = /^(#{1,6})\s+(.*)$/;
1817
- const MD_QUOTE = /^>\s?/;
1818
- const MD_UL = /^[-*+]\s+/;
1819
- const MD_OL = /^\d+[.)]\s+/;
1820
- const MD_HR = /^([-*_])(?:\s*\1){2,}\s*$/;
1821
- function mdBlockStart(t) {
1822
- return t.slice(0, 3) === MD_BACKTICK + MD_BACKTICK + MD_BACKTICK
1823
- || MD_HEADING.test(t) || MD_QUOTE.test(t) || MD_UL.test(t) || MD_OL.test(t) || MD_HR.test(t);
1824
- }
1825
- // Parse a markdown string into an array of block-level DOM nodes.
1826
- function mdToNodes(src) {
1827
- const out = [];
1828
- const fence = MD_BACKTICK + MD_BACKTICK + MD_BACKTICK;
1829
- const lines = String(src == null ? "" : src).replace(/\r\n?/g, "\n").split("\n");
1830
- let i = 0;
1831
- while (i < lines.length) {
1832
- const t = lines[i].trim();
1833
- if (t === "") { i++; continue; }
1834
- // Fenced code block — content is verbatim (no inline parsing).
1835
- if (t.slice(0, 3) === fence) {
1836
- const body = [];
1837
- i++;
1838
- while (i < lines.length && lines[i].trim().slice(0, 3) !== fence) { body.push(lines[i]); i++; }
1839
- if (i < lines.length) i++; // consume the closing fence
1840
- out.push(el("pre", { class: "pc-md-pre" }, el("code", {}, body.join("\n"))));
1841
- continue;
1842
- }
1843
- // Thematic break (checked before lists so "***"/"---" isn't read as a bullet).
1844
- if (MD_HR.test(t)) { out.push(el("hr", { class: "pc-md-hr" })); i++; continue; }
1845
- // ATX heading.
1846
- const h = MD_HEADING.exec(t);
1847
- if (h) { out.push(el("h" + h[1].length, { class: "pc-md-h" }, ...mdInline(h[2].trim()))); i++; continue; }
1848
- // Blockquote — strip one '>' per line and re-parse the inner block(s).
1849
- if (MD_QUOTE.test(t)) {
1850
- const inner = [];
1851
- while (i < lines.length && MD_QUOTE.test(lines[i].trim())) { inner.push(lines[i].trim().replace(MD_QUOTE, "")); i++; }
1852
- const bq = el("blockquote", { class: "pc-md-quote" });
1853
- for (const b of mdToNodes(inner.join("\n"))) bq.append(b);
1854
- out.push(bq); continue;
1855
- }
1856
- // Unordered list.
1857
- if (MD_UL.test(t)) {
1858
- const ul = el("ul", { class: "pc-md-list" });
1859
- while (i < lines.length && MD_UL.test(lines[i].trim())) {
1860
- ul.append(el("li", {}, ...mdInline(lines[i].trim().replace(MD_UL, ""))));
1861
- i++;
1862
- }
1863
- out.push(ul); continue;
1864
- }
1865
- // Ordered list.
1866
- if (MD_OL.test(t)) {
1867
- const ol = el("ol", { class: "pc-md-list" });
1868
- while (i < lines.length && MD_OL.test(lines[i].trim())) {
1869
- ol.append(el("li", {}, ...mdInline(lines[i].trim().replace(MD_OL, ""))));
1870
- i++;
1871
- }
1872
- out.push(ol); continue;
1873
- }
1874
- // Paragraph — soft-wrapped lines joined with a space until a blank line or the
1875
- // next block opener.
1876
- const para = [];
1877
- while (i < lines.length) {
1878
- const lt = lines[i].trim();
1879
- if (lt === "" || mdBlockStart(lt)) break;
1880
- para.push(lt); i++;
1881
- }
1882
- out.push(el("p", { class: "pc-md-p" }, ...mdInline(para.join(" "))));
1883
- }
1884
- return out;
1885
- }
1886
-
1887
- // A data-bound prose/markdown list (#274). Binds a datasource like dataGrid
1888
- // (props.data = { source, table, orderBy, filter }) but renders each row as a
1889
- // stacked prose block — a small header template (props.header, e.g.
1890
- // "Round {{round}} · {{approved}}") over one body field (props.body) rendered as
1891
- // sanitised markdown at a comfortable measure (props.measure ch, ~66 default).
1892
- // This is the primitive for narrative records (plan-review findings, coordination
1893
- // notes, escalation bodies) that read as a document, not a squeezed table cell.
1894
- // It inherits collapsible/defaultCollapsed for free via makeCollapsible (which
1895
- // unwraps the <h2> title), and refreshMs polling + pc:refresh like dataGrid.
1896
- function renderProse(node) {
1897
- const p = node.props || {};
1898
- const data = p.data || {};
1899
- const card = el("section", { class: "pc-card" });
1900
- if (p.title) card.append(el("h2", {}, p.title));
1901
- const listEl = el("div", { class: "pc-prose-list" });
1902
- card.append(listEl);
1903
- const headerTpl = typeof p.header === "string" ? p.header : null;
1904
- const bodyField = p.body;
1905
- // Clamp the reading measure to a sane range so a malformed schema can't set a
1906
- // 5000ch (full-bleed) or 2ch (one-word-per-line) body. ~66ch is the default.
1907
- let measure = Number(p.measure);
1908
- if (!Number.isFinite(measure)) measure = 66;
1909
- measure = Math.max(40, Math.min(100, Math.round(measure)));
1910
- const activeFilter = Array.isArray(data.filter) ? data.filter : [];
1911
-
1912
- function itemFor(row) {
1913
- const item = el("article", { class: "pc-prose-item" });
1914
- if (headerTpl) item.append(el("div", { class: "pc-prose-head" }, interpTemplate(headerTpl, row)));
1915
- const bodyEl = el("div", { class: "pc-prose-body", style: "max-width:" + measure + "ch" });
1916
- // Own-property gate (matching interpTemplate) so a body field name that
1917
- // collides with a prototype key can't pick up prototype cruft.
1918
- const raw = bodyField != null && Object.prototype.hasOwnProperty.call(row, bodyField) && row[bodyField] != null
1919
- ? String(row[bodyField])
1920
- : "";
1921
- for (const b of mdToNodes(raw)) bodyEl.append(b);
1922
- item.append(bodyEl);
1923
- return item;
1924
- }
1925
-
1926
- async function refresh() {
1927
- try {
1928
- // A param-scoped list ("show the selected entity's records") with no route
1929
- // param present renders nothing rather than a field=empty-string query.
1930
- const paramScoped = (activeFilter || []).some((f) => f && f.eqParam);
1931
- const { rows } = paramScoped && PARAM === ""
1932
- ? { rows: [] }
1933
- : await getJSON(dataUrl(data.source, data.table, activeFilter, data.orderBy));
1934
- listEl.replaceChildren();
1935
- if (!rows.length) { listEl.append(el("p", { class: "pc-prose-empty" }, p.empty || "No records")); return; }
1936
- for (const row of rows) listEl.append(itemFor(row));
1937
- } catch (e) {
1938
- listEl.replaceChildren(el("p", { class: "pc-msg err" }, String((e && e.message) || e)));
1939
- }
1940
- }
1941
- document.addEventListener("pc:refresh", refresh);
1942
- disposers.push(() => document.removeEventListener("pc:refresh", refresh));
1943
- if (p.refreshMs && p.refreshMs > 0) {
1944
- const timer = setInterval(refresh, p.refreshMs);
1945
- disposers.push(() => clearInterval(timer));
1946
- }
1947
- refresh();
1948
- return card;
1949
- }
1950
-
1951
- function renderDataGrid(node) {
1952
- const p = node.props;
1953
- const card = el("section", { class: "pc-card" });
1954
- // Opt-in live row-count badge ("showCount"). Rendered inside the <h2> so a plain
1955
- // (non-collapsible) grid surfaces it beside the title; makeCollapsible re-homes it
1956
- // into the collapse header so it stays visible — and refresh-updated — while the
1957
- // section is collapsed. refresh() below rewrites its text on every poll/pc:refresh.
1958
- const countBadge = p.showCount ? el("span", { class: "pc-badge pc-count-badge", "aria-label": rowCountLabel(0) }, "0") : null;
1959
- if (p.title || countBadge) {
1960
- const h2 = el("h2", {}, p.title || "");
1961
- if (countBadge) { if (p.title) h2.append(" "); h2.append(countBadge); }
1962
- card.append(h2);
1963
- }
1964
- const cols = p.columns || [];
1965
- // Mobile card roles per column (derived by convention, refined by
1966
- // col.mobile.priority) so the grid can flip to a stacked card list on a phone
1967
- // (#268). 'hasHidden' gates the per-row "More" toggle that reveals the columns
1968
- // a mobile:{priority:"hidden"} hint drops off the card.
1969
- const roles = classifyColumns(cols);
1970
- const hasHidden = roles.indexOf("hidden") >= 0;
1971
- const tabs = p.tabs || [];
1972
- const rowActions = p.rowActions || [];
1973
- const detail = p.detail || null;
1974
- const hasExtra = rowActions.length > 0 || detail != null;
1975
- let activeFilter = p.data.filter || [];
1976
-
1977
- if (tabs.length) {
1978
- const bar = el("div", { class: "pc-tabs" });
1979
- activeFilter = tabs[0].filter || [];
1980
- tabs.forEach((t, i) => {
1981
- const b = el("button", { class: "pc-tab" + (i === 0 ? " active" : "") }, t.label);
1982
- b.addEventListener("click", () => {
1983
- activeFilter = t.filter || [];
1984
- for (const c of bar.children) c.classList.remove("active");
1985
- b.classList.add("active");
1986
- refresh();
1987
- });
1988
- bar.append(b);
1989
- });
1990
- card.append(bar);
1991
- }
1992
-
1993
- const headCells = cols.map((c) => el("th", {}, c.header || c.field));
1994
- if (hasExtra) headCells.push(el("th", {}, ""));
1995
- const thead = el("thead", {}, el("tr", {}, ...headCells));
1996
- const tbody = el("tbody", {});
1997
- // A <colgroup> (present only when a column declares width/weight) sizes the
1998
- // columns so table-layout:fixed stops splitting width equally; it must precede
1999
- // <thead> in the table.
2000
- const colgroup = buildColgroup(cols, hasExtra ? 1 : 0);
2001
- const table = colgroup
2002
- ? el("table", { class: "pc-grid" }, colgroup, thead, tbody)
2003
- : el("table", { class: "pc-grid" }, thead, tbody);
2004
- card.append(table);
2005
- const span = String((cols.length || 1) + (hasExtra ? 1 : 0));
2006
-
2007
- // Expansion state has to outlive the poll: refresh() rebuilds the whole tbody
2008
- // every refreshMs, so without this an open detail row (where you answer an
2009
- // escalation) would collapse on the next tick. We remember which rowKeys are
2010
- // open, and reuse the already-built detail <tr> for them across refreshes so a
2011
- // half-typed answer survives too. Keyed by p.rowKey; grids without one keep the
2012
- // old (collapse-on-refresh) behavior.
2013
- const expanded = new Set();
2014
- const detailNodes = new Map();
2015
- // A row only participates in expansion/detail-node caching if it has a real
2016
- // (non-null) rowKey. Coercing a missing key through String() would yield the
2017
- // literal "undefined"/"null" and collide unrelated rows, so treat it as keyless.
2018
- const rowKeyOf = (row) => {
2019
- if (!p.rowKey) return null;
2020
- const v = row[p.rowKey];
2021
- return v == null ? null : String(v);
2022
- };
2023
-
2024
- async function fireAction(action, row) {
2025
- // Route-driven row action: POST the action's body template (default {})
2026
- // to its route path, with {{row.KEY}} tokens resolved from this row.
2027
- return runRoute(action, { row });
2028
- }
2029
-
2030
- function rowActionButton(row, ra) {
2031
- if (ra.showWhenField && !row[ra.showWhenField]) return null;
2032
- const b = el("button", { class: "pc-btn pc-btn-sm" }, ra.label);
2033
- b.addEventListener("click", async (ev) => {
2034
- ev.stopPropagation();
2035
- if (ra.confirm && !confirm(ra.confirm)) return;
2036
- b.disabled = true;
2037
- try {
2038
- await fireAction(ra.action, row);
2039
- document.dispatchEvent(new CustomEvent("pc:refresh"));
2040
- } catch (e) {
2041
- b.disabled = false;
2042
- alert(String(e.message || e));
2043
- }
2044
- });
2045
- return b;
2046
- }
2047
-
2048
- function detailForm(row) {
2049
- const f = detail.form;
2050
- if (!f || !row[f.showWhenField]) return null;
2051
- const box = el("div", { class: "pc-subform" });
2052
- if (f.title) box.append(el("div", { class: "pc-subform-title" }, f.title));
2053
- if (f.promptField && row[f.promptField] != null) {
2054
- box.append(el("div", { class: "pc-prompt" }, String(row[f.promptField])));
2055
- }
2056
- const input = el("textarea", { class: "pc-textarea", placeholder: f.inputLabel || f.inputKey });
2057
- const msg = el("p", { class: "pc-msg" });
2058
- const btn = el("button", { class: "pc-btn pc-btn-sm" }, f.submitLabel || "Submit");
2059
- btn.addEventListener("click", async () => {
2060
- btn.disabled = true; msg.className = "pc-msg"; msg.textContent = "Sending…";
2061
- try {
2062
- // The textarea value is the form's single field (f.inputKey); route + body
2063
- // template come from f.action, e.g. { path: "/app/actions/message",
2064
- // body: { name, correlationKey: "{{row.pr_key}}", variables: "{{form}}" } }.
2065
- // Null-proto so an f.inputKey of "__proto__"/"constructor" can't mutate a prototype.
2066
- const form = Object.create(null); form[f.inputKey] = input.value;
2067
- await runRoute(f.action, { form, row });
2068
- msg.className = "pc-msg ok"; msg.textContent = (f.action && f.action.successLabel) || "Sent";
2069
- document.dispatchEvent(new CustomEvent("pc:refresh"));
2070
- } catch (e) {
2071
- btn.disabled = false; msg.className = "pc-msg err"; msg.textContent = String(e.message || e);
2072
- }
2073
- });
2074
- box.append(el("div", { class: "pc-field" }, input), btn, msg);
2075
- return box;
2076
- }
2077
-
2078
- async function childGrid(cg, row) {
2079
- const wrap = el("div", { class: "pc-child" });
2080
- if (cg.title) wrap.append(el("div", { class: "pc-child-title" }, cg.title));
2081
- const ccols = cg.columns || [];
2082
- const croles = classifyColumns(ccols);
2083
- const chasHidden = croles.indexOf("hidden") >= 0;
2084
- const cbody = el("tbody", {});
2085
- const ccolgroup = buildColgroup(ccols, cg.lazyField ? 1 : 0);
2086
- const cthead = el("thead", {}, el("tr", {}, ...ccols.map((c) => el("th", {}, c.header || c.field)),
2087
- ...(cg.lazyField ? [el("th", {}, "")] : [])));
2088
- const ctable = ccolgroup
2089
- ? el("table", { class: "pc-grid" }, ccolgroup, cthead, cbody)
2090
- : el("table", { class: "pc-grid" }, cthead, cbody);
2091
- wrap.append(ctable);
2092
- try {
2093
- const { rows } = await getJSON(dataUrl(cg.source || "app", cg.table,
2094
- [{ field: cg.childField, eq: row[cg.parentField] }], cg.orderBy));
2095
- const cspan = String((ccols.length || 1) + (cg.lazyField ? 1 : 0));
2096
- if (!rows.length) {
2097
- cbody.append(el("tr", {}, el("td", { colspan: cspan }, "None")));
2098
- }
2099
- for (const cr of rows) {
2100
- const cells = ccols.map((c, i) => gridCell(c, cr, croles[i]));
2101
- if (cg.lazyField) {
2102
- const lf = cg.lazyField;
2103
- const has = cr[lf.field] != null && String(cr[lf.field]).trim() !== "";
2104
- const cell = el("td", {});
2105
- if (has) {
2106
- const toggle = el("button", { class: "pc-btn pc-btn-sm" }, lf.label || "Show");
2107
- const pre = el("pre", { class: "pc-transcript", hidden: "" });
2108
- pre.textContent = String(cr[lf.field]);
2109
- toggle.addEventListener("click", () => {
2110
- pre.hidden = !pre.hidden;
2111
- toggle.textContent = pre.hidden ? (lf.label || "Show") : "Hide";
2112
- });
2113
- cell.append(toggle, pre);
2114
- }
2115
- cells.push(cell);
2116
- }
2117
- // Child grids classify columns into the same mobile roles (including
2118
- // "hidden") as the top-level grid, so they need the same per-row "More"
2119
- // toggle — without it a mobile:{priority:"hidden"} child column would be
2120
- // permanently unreachable on a narrow viewport (#268).
2121
- const ctr = el("tr", {}, ...cells);
2122
- if (chasHidden) ctr.append(mobileMoreCell(ctr));
2123
- cbody.append(ctr);
2124
- }
2125
- } catch (e) {
2126
- cbody.append(el("tr", {}, el("td", { colspan: cspan }, String(e.message || e))));
2127
- }
2128
- return wrap;
2129
- }
2130
-
2131
- function detailPanel(row) {
2132
- const box = el("div", { class: "pc-detail" });
2133
- if (detail.linkField && row[detail.linkField]) {
2134
- const href = String(row[detail.linkField]);
2135
- // Render as a link only for http(s); anything else (e.g. a javascript: URL
2136
- // smuggled through row data) is shown as inert text. External links get
2137
- // rel="noopener noreferrer" so the opened page can't reach window.opener.
2138
- if (/^https?:\/\//i.test(href)) {
2139
- box.append(el("a", { class: "pc-link", href, target: "_blank", rel: "noopener noreferrer" }, href));
2140
- } else {
2141
- box.append(el("span", { class: "pc-link" }, href));
2142
- }
2143
- }
2144
- for (const df of detail.fields || []) {
2145
- box.append(el("div", { class: "pc-detail-field" },
2146
- el("span", { class: "pc-detail-label" }, df.label || df.field),
2147
- el("span", {}, row[df.field] == null ? "" : String(row[df.field]))));
2148
- }
2149
- for (const cg of detail.children || []) {
2150
- const holder = el("div", {});
2151
- box.append(holder);
2152
- childGrid(cg, row).then((w) => holder.replaceChildren(w));
2153
- }
2154
- const form = detailForm(row);
2155
- if (form) box.append(form);
2156
- return box;
2157
- }
2158
-
2159
- function renderRow(row, sink) {
2160
- const cells = cols.map((c, i) => gridCell(c, row, roles[i]));
2161
- const key = rowKeyOf(row);
2162
- let toggle = null;
2163
- if (hasExtra) {
2164
- const actionCell = el("td", { class: "pc-row-actions" });
2165
- if (detail) {
2166
- toggle = el("button", { class: "pc-btn pc-btn-sm pc-chevron" }, "▸");
2167
- actionCell.append(toggle);
2168
- }
2169
- for (const ra of rowActions) {
2170
- const b = rowActionButton(row, ra);
2171
- if (b) actionCell.append(b);
2172
- }
2173
- cells.push(actionCell);
2174
- }
2175
- // Per-row "More" toggle: only when a mobile:{priority:"hidden"} hint drops
2176
- // columns off the card. Appended after the <tr> is built (the toggle wires a
2177
- // click against its own row) and shared with child grids via mobileMoreCell so
2178
- // the reveal affordance and its aria state can't drift (#268).
2179
- const tr = el("tr", {}, ...cells);
2180
- if (hasHidden) tr.append(mobileMoreCell(tr));
2181
- tbody.append(tr);
2182
- // When grouping, the caller collects every <tr> this row produced (the data
2183
- // row plus any detail row) so a group header can hide/show them as one unit.
2184
- if (sink) sink.push({ tr, isDetail: false, key });
2185
- if (detail && toggle) {
2186
- const isOpen = key != null && expanded.has(key);
2187
- // Reuse an already-built detail row for an open PR across refreshes so its
2188
- // expanded state — and any half-typed escalation answer in the form — survives
2189
- // the poll. A closed (or keyless) row always gets a fresh, lazily-built panel.
2190
- let entry = key != null ? detailNodes.get(key) : null;
2191
- if (!(isOpen && entry && entry.built)) {
2192
- const dtr = el("tr", { hidden: isOpen ? null : "" }, el("td", { colspan: span }));
2193
- entry = { dtr, built: false };
2194
- if (key != null) detailNodes.set(key, entry);
2195
- if (isOpen) { entry.built = true; dtr.firstChild.append(detailPanel(row)); }
2196
- }
2197
- const dtr = entry.dtr;
2198
- toggle.textContent = dtr.hidden ? "▸" : "▾";
2199
- toggle.addEventListener("click", (ev) => {
2200
- ev.stopPropagation();
2201
- const open = dtr.hidden;
2202
- dtr.hidden = !open;
2203
- toggle.textContent = open ? "▾" : "▸";
2204
- if (open) {
2205
- if (key != null) expanded.add(key);
2206
- if (!entry.built) { entry.built = true; dtr.firstChild.append(detailPanel(row)); }
2207
- } else if (key != null) {
2208
- expanded.delete(key);
2209
- }
2210
- });
2211
- tbody.append(dtr);
2212
- if (sink) sink.push({ tr: dtr, isDetail: true, key });
2213
- }
2214
- }
2215
-
2216
- // Append the fetched rows into the tbody, either flat (default) or partitioned
2217
- // into collapsible groups when the grid declares 'groupBy: "<field>"'. Each
2218
- // group renders a clickable header row ("<Label> <value> (<count>)") that
2219
- // collapses/expands its member rows as one unit; the collapsed state is
2220
- // persisted (localStorage, keyed by page + node + group value) so it survives
2221
- // both the refresh poll and a full reload — the same durability the top-level
2222
- // 'collapsible' node wrapper gives. Group order is numeric-aware ascending
2223
- // (so waves 1,2,10 sort naturally), falling back to lexical for non-numeric
2224
- // keys. 'groupDefaultCollapsed' seeds each group collapsed until toggled.
2225
- function appendRows(rows) {
2226
- const groupBy = p.groupBy;
2227
- // Treat a non-string groupBy as "no grouping": labelBase calls groupBy.charAt()
2228
- // below, so a truthy non-string (number/object from a malformed page schema)
2229
- // would throw at render time and break the whole page instead of one grid.
2230
- if (!groupBy || typeof groupBy !== "string") { for (const row of rows) renderRow(row, null); return; }
2231
- const order = [];
2232
- const groups = new Map();
2233
- for (const row of rows) {
2234
- const gvRaw = row[groupBy];
2235
- const gv = gvRaw == null ? "" : String(gvRaw);
2236
- if (!groups.has(gv)) { groups.set(gv, []); order.push(gv); }
2237
- groups.get(gv).push(row);
2238
- }
2239
- order.sort((a, b) => {
2240
- const na = Number(a), nb = Number(b);
2241
- if (a !== "" && b !== "" && !Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
2242
- return a < b ? -1 : a > b ? 1 : 0;
2243
- });
2244
- const labelBase = p.groupLabel != null
2245
- ? String(p.groupLabel)
2246
- : groupBy.charAt(0).toUpperCase() + groupBy.slice(1);
2247
- for (const gv of order) {
2248
- const groupRows = groups.get(gv);
2249
- const gkey = "pc:collapsed:" + CURRENT + ":" + (node.id || p.title || "grid") + ":g:" + gv;
2250
- let gcollapsed = readCollapsed(gkey, !!p.groupDefaultCollapsed);
2251
- const chevron = el("span", { class: "pc-chevron-inline" }, gcollapsed ? "▸" : "▾");
2252
- const label = (gv === "" ? labelBase + " —" : labelBase + " " + gv) + " (" + groupRows.length + ")";
2253
- const btn = el("button", { class: "pc-group-toggle", type: "button" },
2254
- chevron, el("span", { class: "pc-group-title" }, label));
2255
- tbody.append(el("tr", { class: "pc-group-header" }, el("td", { colspan: span }, btn)));
2256
- const members = [];
2257
- for (const row of groupRows) renderRow(row, members);
2258
- const applyGroup = () => {
2259
- chevron.textContent = gcollapsed ? "▸" : "▾";
2260
- btn.setAttribute("aria-expanded", String(!gcollapsed));
2261
- for (const m of members) {
2262
- m.tr.hidden = gcollapsed
2263
- ? true
2264
- : (m.isDetail ? !(m.key != null && expanded.has(m.key)) : false);
2265
- }
2266
- };
2267
- btn.addEventListener("click", () => {
2268
- gcollapsed = !gcollapsed;
2269
- writeCollapsed(gkey, gcollapsed);
2270
- applyGroup();
2271
- });
2272
- applyGroup();
2273
- }
2274
- }
2275
-
2276
- // Is the user actively typing inside this grid? tbody.replaceChildren() in refresh()
2277
- // detaches the subtree, and detaching the node that holds document.activeElement blurs
2278
- // it — so an open detail form (where you answer an escalation) loses focus every
2279
- // refreshMs even though #103 preserves its half-typed value. Used to skip the poll.
2280
- const editingInGrid = () => {
2281
- const a = document.activeElement;
2282
- if (!a || !tbody.contains(a)) return false;
2283
- return a.tagName === "INPUT" || a.tagName === "TEXTAREA" || a.tagName === "SELECT" || a.isContentEditable;
2284
- };
2285
-
2286
- async function refresh() {
2287
- try {
2288
- // A grid scoped to a route param (any eqParam filter) means "show the rows
2289
- // for the selected entity". With no param present, PARAM is empty and emitting
2290
- // a where clause of field-colon-empty would read server-side as field equals
2291
- // empty string and surface empty-valued rows. That is not the selected entity's
2292
- // rows (there is no selection), so short-circuit to zero rows without a request.
2293
- const paramScoped = (activeFilter || []).some((f) => f && f.eqParam);
2294
- const { rows } = paramScoped && PARAM === ""
2295
- ? { rows: [] }
2296
- : await getJSON(dataUrl(p.data.source, p.data.table, activeFilter, p.data.orderBy));
2297
- // Live row-count badge: reflect the currently-fetched, filtered (active-tab)
2298
- // set — exactly what the body renders — on every refresh (poll + pc:refresh),
2299
- // whether the section is expanded or collapsed.
2300
- if (countBadge) { countBadge.textContent = String(rows.length); countBadge.setAttribute("aria-label", rowCountLabel(rows.length)); }
2301
- // Forget expansion / cached detail nodes for rows no longer present so the maps
2302
- // don't grow without bound and a stale answer can't resurface on a key reuse.
2303
- if (p.rowKey) {
2304
- const live = new Set();
2305
- for (const r of rows) { const k = rowKeyOf(r); if (k != null) live.add(k); }
2306
- for (const k of [...detailNodes.keys()]) if (!live.has(k)) detailNodes.delete(k);
2307
- for (const k of [...expanded]) if (!live.has(k)) expanded.delete(k);
2308
- }
2309
- // Capture focus + caret before the DOM swap. replaceChildren() detaches (and so blurs)
2310
- // the reused detail node; re-appending it restores its value but not its focus. If the
2311
- // very same node is re-attached (an open, still-present row), put the caret back.
2312
- const active = document.activeElement;
2313
- const keepFocus = !!active && tbody.contains(active);
2314
- let selStart = null, selEnd = null, savedRange = null;
2315
- if (keepFocus) {
2316
- if (active.isContentEditable) {
2317
- // contenteditable has no selectionStart — its caret lives in the document
2318
- // selection. The reused node is re-attached, so the cloned range still points
2319
- // at live containers and can be restored after focus.
2320
- try { const s = document.getSelection(); if (s && s.rangeCount) savedRange = s.getRangeAt(0).cloneRange(); } catch (e) { /* selection unavailable */ }
2321
- } else {
2322
- try { selStart = active.selectionStart; selEnd = active.selectionEnd; } catch (e) { /* non-text field */ }
2323
- }
2324
- }
2325
- // Capture scroll offsets of scrolled descendants before the swap. An open detail node is
2326
- // reused (same element instance), but replaceChildren() detaches it, which resets the
2327
- // scrollTop/scrollLeft of any inner scroll container (e.g. a scrolled-into .pc-transcript,
2328
- // max-height + overflow:auto) back to 0. Only built (open) detail subtrees are re-attached
2329
- // by the rebuild, so walk just those — not the whole grid — to keep this O(open panels)
2330
- // rather than O(grid size). Restoration below skips any node that isn't re-attached.
2331
- const scrollSaved = [];
2332
- for (const entry of detailNodes.values()) {
2333
- if (!entry.built) continue;
2334
- for (const sc of entry.dtr.querySelectorAll("*")) {
2335
- if (sc.scrollTop || sc.scrollLeft) scrollSaved.push([sc, sc.scrollTop, sc.scrollLeft]);
2336
- }
2337
- }
2338
- tbody.replaceChildren();
2339
- appendRows(rows);
2340
- if (!rows.length) tbody.append(el("tr", {}, el("td", { colspan: span }, "No rows")));
2341
- if (keepFocus && active.isConnected) {
2342
- active.focus();
2343
- if (savedRange) {
2344
- try { const s = document.getSelection(); s.removeAllRanges(); s.addRange(savedRange); } catch (e) { /* selection unavailable */ }
2345
- } else if (selStart != null && typeof active.setSelectionRange === "function") {
2346
- try { active.setSelectionRange(selStart, selEnd); } catch (e) { /* non-text field */ }
2347
- }
2348
- }
2349
- // Restore scroll depth on the reused nodes that survived the swap (still connected).
2350
- for (const [sc, top, left] of scrollSaved) {
2351
- if (sc.isConnected) { sc.scrollTop = top; sc.scrollLeft = left; }
2352
- }
2353
- } catch (e) {
2354
- tbody.replaceChildren(el("tr", {}, el("td", { colspan: span }, String(e.message || e))));
2355
- }
2356
- }
2357
- document.addEventListener("pc:refresh", refresh);
2358
- disposers.push(() => document.removeEventListener("pc:refresh", refresh));
2359
- // Skip the automatic poll while the user is typing in the grid — an explicit pc:refresh
2360
- // (e.g. after submitting an answer) still runs — so rows never shift under an in-progress
2361
- // answer and the detail input keeps focus across ticks. The interval is registered as a
2362
- // disposer so a page switch (hashchange → renderPage → teardown) stops it.
2363
- if (p.refreshMs && p.refreshMs > 0) {
2364
- const timer = setInterval(() => { if (!editingInGrid()) refresh(); }, p.refreshMs);
2365
- disposers.push(() => clearInterval(timer));
2366
- }
2367
- refresh();
2368
- return card;
2369
- }
2370
-
2371
- // A navigation node — a horizontal menu bar (variant "bar", default) or a
2372
- // vertical side rail (variant "rail"). Each item links either to another page
2373
- // ({ label, page } -> an in-app #/<page> hash link, highlighted when it's the
2374
- // current page) or to an external URL ({ label, href } -> a hardened new-tab
2375
- // link; only http(s) is honoured). With items:"auto" (or omitted) the nav
2376
- // lists every page from the /app/pages index, using each page's title.
2377
- function navLink(item) {
2378
- const isPage = safePageId(item.page);
2379
- const isExt = !isPage && typeof item.href === "string" && /^https?:\/\//i.test(item.href);
2380
- if (!isPage && !isExt) return null;
2381
- const attrs = { class: "pc-nav-link" };
2382
- if (isPage) {
2383
- attrs.href = "#/" + encodeURIComponent(item.page);
2384
- if (item.page === CURRENT) { attrs.class += " active"; attrs["aria-current"] = "page"; }
2385
- } else {
2386
- attrs.href = item.href; attrs.target = "_blank"; attrs.rel = "noopener noreferrer";
2387
- }
2388
- const kids = [];
2389
- if (item.icon != null) kids.push(el("span", { class: "pc-nav-icon" }, String(item.icon)));
2390
- kids.push(el("span", { class: "pc-nav-label" }, String(item.label != null ? item.label : (item.page || item.href))));
2391
- return el("a", attrs, ...kids);
2392
- }
2393
- function fillNav(list, items) {
2394
- list.replaceChildren();
2395
- let n = 0;
2396
- for (const item of items || []) {
2397
- if (!item || typeof item !== "object") continue;
2398
- const a = navLink(item);
2399
- if (a) { list.append(a); n++; }
2400
- }
2401
- if (!n) list.append(el("span", { class: "pc-nav-empty" }, "No pages"));
2402
- }
2403
- function renderNav(node) {
2404
- const p = node.props || {};
2405
- const rail = p.variant === "rail";
2406
- // A bar nav can opt into staying pinned to the top of the viewport while the
2407
- // page scrolls (sticky) — useful on the long, multi-section operator pages so
2408
- // the page switcher is always reachable. Rails are already full-height, so the
2409
- // flag only applies to the bar variant.
2410
- const barSticky = !rail && p.sticky === true;
2411
- const nav = el("nav", {
2412
- class: (rail ? "pc-nav pc-rail" : "pc-nav pc-bar") + (barSticky ? " pc-sticky" : ""),
2413
- });
2414
- if (p.title != null) nav.append(el("div", { class: "pc-nav-title" }, String(p.title)));
2415
- const list = el("div", { class: "pc-nav-items" });
2416
- nav.append(list);
2417
- const items = p.items;
2418
- if (Array.isArray(items)) {
2419
- fillNav(list, items);
2420
- } else {
2421
- // "auto" (or unspecified): enumerate every page and link to each.
2422
- getJSON("/app/pages")
2423
- .then((res) => fillNav(list, (res.pages || []).map((pg) => ({ label: pg.title || pg.id, page: pg.id }))))
2424
- .catch(() => list.append(el("span", { class: "pc-nav-empty" }, "No pages")));
2425
- }
2426
- return nav;
2427
- }
2428
-
2429
- const RENDERERS = { text: renderText, actionForm: renderActionForm, dataGrid: renderDataGrid, prose: renderProse, nav: renderNav, button: renderButton };
2430
-
2431
- // Durable per-node UI state. localStorage is keyed by the home page id + node
2432
- // id so two grids on the same page (or the same grid across pages) don't clash,
2433
- // and the collapsed state survives a full reload / new session — not just the
2434
- // refresh poll. Every access is guarded: private-mode or storage-disabled
2435
- // browsers throw on localStorage, and a UI preference must never break render.
2436
- function readCollapsed(key, dflt) {
2437
- try {
2438
- const v = localStorage.getItem(key);
2439
- return v === null ? dflt : v === "1";
2440
- } catch (e) {
2441
- return dflt;
2442
- }
2443
- }
2444
- function writeCollapsed(key, val) {
2445
- try {
2446
- localStorage.setItem(key, val ? "1" : "0");
2447
- } catch (e) {
2448
- // Preference is best-effort; ignore storage failures.
2449
- }
2450
- }
2451
-
2452
- // Wrap a rendered node so its card can be collapsed from a clickable header.
2453
- // Opt-in via the node's "collapsible" prop; "defaultCollapsed" seeds the state
2454
- // the first time (before the user has toggled it). Generic across node types —
2455
- // the body (everything the renderer produced, minus its own <h2> title, which
2456
- // becomes the header label) is hidden as one unit.
2457
- function makeCollapsible(node, card) {
2458
- const props = node.props || {};
2459
- if (!props.collapsible) return card;
2460
- // Normalize to a card container. Card renderers already return
2461
- // <section class="pc-card"> — we unwrap those in place (lift out the <h2>
2462
- // title, reparent the rest into the body). A non-card renderer (e.g. text
2463
- // returning <p>/<h1>) is nested whole inside a fresh section instead:
2464
- // appending a <button>/<div> directly into a <p> is invalid markup the
2465
- // browser silently re-parents, breaking layout and click handling.
2466
- const isCard = card.tagName === "SECTION";
2467
- const container = isCard ? card : el("section", { class: "pc-card" });
2468
- const h2 = isCard && card.querySelector ? card.querySelector("h2") : null;
2469
- // A dataGrid with "showCount" renders a live count badge inside its <h2>. Lift it
2470
- // out before deriving the title (so the count doesn't leak into the label text),
2471
- // then re-home it in the header alongside the title so it stays visible — and
2472
- // refresh-updated by the grid's own refresh() — while the section is collapsed.
2473
- const countBadge = h2 && h2.querySelector ? h2.querySelector(".pc-count-badge") : null;
2474
- if (countBadge) countBadge.remove();
2475
- // Trim the derived label: after the badge is lifted out, the leftover " " whitespace
2476
- // node from h2.append(" ", countBadge) would otherwise make a title-less section's
2477
- // header a lone space (and leak whitespace into the storage key). Fall back to "Section".
2478
- const titleText = props.title || (h2 ? h2.textContent.trim() : "") || "Section";
2479
- if (h2) h2.remove();
2480
- const body = el("div", { class: "pc-card-body" });
2481
- if (isCard) {
2482
- while (card.firstChild) body.append(card.firstChild);
2483
- } else {
2484
- body.append(card);
2485
- }
2486
- const chevron = el("span", { class: "pc-chevron-inline" }, "▾");
2487
- const header = el(
2488
- "button",
2489
- { class: "pc-collapse-header", type: "button" },
2490
- chevron,
2491
- el("span", { class: "pc-collapse-title" }, titleText),
2492
- );
2493
- if (countBadge) header.append(countBadge);
2494
- const storageKey = "pc:collapsed:" + CURRENT + ":" + (node.id || titleText);
2495
- let collapsed = readCollapsed(storageKey, !!props.defaultCollapsed);
2496
- function apply() {
2497
- body.hidden = collapsed;
2498
- chevron.textContent = collapsed ? "▸" : "▾";
2499
- header.setAttribute("aria-expanded", String(!collapsed));
2500
- }
2501
- header.addEventListener("click", () => {
2502
- collapsed = !collapsed;
2503
- writeCollapsed(storageKey, collapsed);
2504
- apply();
2505
- });
2506
- apply();
2507
- container.append(header, body);
2508
- return container;
2509
- }
2510
-
2511
- // Tier-2 escape hatch (#268): a page may declare a distinct 'mobile' layout
2512
- // variant — its own node list — for the rare case the derived card flip isn't
2513
- // enough (reorder/omit sections, swap a dense grid for a summary card). It is
2514
- // used ONLY on a narrow viewport; the default 'nodes' render everywhere else,
2515
- // and anything malformed falls back to them, so the variant is purely additive.
2516
- function pickNodes(doc) {
2517
- if (isNarrow() && doc && doc.mobile && Array.isArray(doc.mobile.nodes)) return doc.mobile.nodes;
2518
- return (doc && doc.nodes) || [];
2519
- }
2520
-
2521
- // Render the page named by the current hash route. A rail nav is lifted into a
2522
- // left <aside> and the rest of the nodes flow into a content column; otherwise
2523
- // (bar nav or none) nodes render in document order. Re-runs on every hashchange,
2524
- // tearing down the previous page's grid polls first.
2525
- async function renderPage() {
2526
- teardown();
2527
- const mySeq = ++renderSeq;
2528
- const route = parseRoute();
2529
- CURRENT = route.page;
2530
- PARAM = route.param;
2531
- try {
2532
- const doc = await getJSON("/app/pages/" + encodeURIComponent(CURRENT));
2533
- if (mySeq !== renderSeq) return;
2534
- document.title = (doc && doc.title) || "Urban App";
2535
- const nodes = pickNodes(doc);
2536
- const built = nodes.map((n) => ({ n, node: makeCollapsible(n, (RENDERERS[n.type] || (() => el("div")))(n)) }));
2537
- const rail = built.find((b) => b.n.type === "nav" && b.n.props && b.n.props.variant === "rail");
2538
- if (rail) {
2539
- const col = el("div", { class: "pc-main-col" });
2540
- for (const b of built) if (b !== rail) col.append(b.node);
2541
- root.replaceChildren(el("div", { class: "pc-layout" }, el("aside", { class: "pc-rail-wrap" }, rail.node), col));
2542
- } else {
2543
- root.replaceChildren(...built.map((b) => b.node));
2544
- }
2545
- } catch (e) {
2546
- if (mySeq !== renderSeq) return;
2547
- root.replaceChildren(el("p", { class: "pc-msg err" }, "Failed to load page: " + String((e && e.message) || e)));
2548
- }
2549
- }
2550
- window.addEventListener("hashchange", renderPage);
2551
- // Re-render when the viewport crosses the mobile breakpoint so a Tier-2 'mobile'
2552
- // variant swaps in/out on rotation or a window resize (the grid card flip, nav
2553
- // collapse and button stacking are pure CSS and need no re-render). teardown()
2554
- // inside renderPage stops the outgoing page's grid polls first. Prefer the modern
2555
- // addEventListener but fall back to the deprecated addListener so older Safari/iOS
2556
- // (< 14), where MediaQueryList.addEventListener is unimplemented, still swaps the
2557
- // Tier-2 variant on rotation/resize instead of silently failing to register.
2558
- if (typeof MOBILE_MQ.addEventListener === "function") MOBILE_MQ.addEventListener("change", renderPage);
2559
- else if (typeof MOBILE_MQ.addListener === "function") MOBILE_MQ.addListener(renderPage);
2560
- renderPage();
2561
- `;
713
+ // `RENDERER_JS` is a generated, checked-in artifact (runtime.gen.ts) derived from the
714
+ // real, type-checked/linted/unit-tested source at ../../browser/runtime.browser.js by
715
+ // scripts/gen-runtime.mjs (#291). Do not edit runtime.gen.ts by hand — edit the source
716
+ // and run `npm run gen:runtime`; CI enforces the two stay in sync (npm run check:runtime).
2562
717
  /** A tiny, dependency-free FNV-1a hash → 8 hex chars. Used to fingerprint the renderer
2563
718
  * module's URL so a content change busts the browser cache. Environment-agnostic (no
2564
719
  * `crypto` import) so the runtime stays loadable under Node, Deno, and the embedded host. */