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