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