From c5ca143d90229787f2ac257973320c6fd78fb490 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:56:41 -0600 Subject: [PATCH 1/4] Diagrams: architecture, flowchart, data flow, sequence and schema (DECISIONS 269 and 270) Five React components on one engine (diagram-core.ts, no React inside it), the HTML skill's diagram module, the diagram tokens, foundations' Diagrams section and the AGENTS.md rules, and review round 56. Built by Opus from Fable's decision. Tests written, not run (DECISIONS 271). Co-Authored-By: Claude Opus 5.5 --- .agent/skills/basalt-html/SKILL.md | 1 + .agent/skills/basalt-html/compose.mjs | 41 +- .agent/skills/basalt-html/parts/diagram.css | 1 + .agent/skills/basalt-html/parts/diagram.js | 1 + .agent/skills/basalt-html/parts/manifest.json | 86 +- .../skills/basalt-html/parts/usage/diagram.md | 23 + AGENTS.md | 6 +- Sources/BasaltTokens/Tokens.swift | 60 + docs/foundations.md | 133 +- packages/react/README.md | 1 + packages/react/src/architecture-diagram.tsx | 23 + packages/react/src/data-flow-diagram.tsx | 23 + packages/react/src/diagram-core.ts | 1740 +++++++++++++++++ packages/react/src/diagram-figure.tsx | 196 ++ packages/react/src/flowchart-diagram.tsx | 22 + packages/react/src/index.ts | 10 + packages/react/src/schema-diagram.tsx | 21 + packages/react/src/sequence-diagram.tsx | 20 + packages/react/src/styles/components.css | 431 ++++ packages/react/test/diagram-geometry.mjs | 143 ++ packages/react/test/diagrams.test.mjs | 671 +++++++ packages/react/test/export-sizes.json | 17 +- .../react/test/fixtures/cimip-diagrams.json | 186 ++ packages/tokens/build.mjs | 2 + packages/tokens/test/contrast.test.mjs | 44 +- .../tokens/test/repeated-numbers.test.mjs | 44 +- packages/tokens/tokens/primitives.tokens.json | 48 + packages/tokens/tokens/theme.dark.tokens.json | 34 + .../tokens/tokens/theme.light.tokens.json | 34 + tools/html-skill/build.mjs | 33 +- tools/html-skill/src/compose.mjs | 41 +- tools/html-skill/src/modules.json | 86 +- tools/html-skill/src/modules/diagram.js | 161 ++ tools/html-skill/src/usage/diagram.md | 23 + tools/html-skill/test/compose.test.mjs | 3 +- tools/html-skill/test/diagrams.test.mjs | 166 ++ tools/review/round56.tsx | 150 ++ tools/review/rounds.tsx | 2 + 38 files changed, 4704 insertions(+), 23 deletions(-) create mode 100644 .agent/skills/basalt-html/parts/diagram.css create mode 100644 .agent/skills/basalt-html/parts/diagram.js create mode 100644 .agent/skills/basalt-html/parts/usage/diagram.md create mode 100644 packages/react/src/architecture-diagram.tsx create mode 100644 packages/react/src/data-flow-diagram.tsx create mode 100644 packages/react/src/diagram-core.ts create mode 100644 packages/react/src/diagram-figure.tsx create mode 100644 packages/react/src/flowchart-diagram.tsx create mode 100644 packages/react/src/schema-diagram.tsx create mode 100644 packages/react/src/sequence-diagram.tsx create mode 100644 packages/react/test/diagram-geometry.mjs create mode 100644 packages/react/test/diagrams.test.mjs create mode 100644 packages/react/test/fixtures/cimip-diagrams.json create mode 100644 tools/html-skill/src/modules/diagram.js create mode 100644 tools/html-skill/src/usage/diagram.md create mode 100644 tools/html-skill/test/diagrams.test.mjs create mode 100644 tools/review/round56.tsx diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index bb34f77a..dd9b6b80 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -62,6 +62,7 @@ Markup built only at run time (a `.row` your script writes) won't be seen: add ` - **period** `.period`: two ghost icon buttons round `.period-label`; at an end `aria-disabled`, never `disabled`. - **terminal** `.terminal`: with `.code`; lines are `span[data-kind]`; the script draws the gutter. - **chart** `.chart`: JSON in `script[data-chart]`; `null` is a day not observed, never zero; needs a `summary`. +- **diagram** `.diagram`: JSON in `script[data-diagram]`; sides only to change the default; needs a `summary`. - **sparkline** `.sparkline`: JSON in `script[data-sparkline]`; one line, no axes or series (that is a `chart`). - **palette** `data-open-palette`, `Basalt.init({ palette })`: `keys` is an array, `['⌘', 'S']`: ⌘, ⌃ or ⌥ plus one key. - **command-list** `.command-list`: the script builds it; items are the palette's; ⌘K goes to the palette when the page has one. diff --git a/.agent/skills/basalt-html/compose.mjs b/.agent/skills/basalt-html/compose.mjs index 272b537a..f8d526b0 100644 --- a/.agent/skills/basalt-html/compose.mjs +++ b/.agent/skills/basalt-html/compose.mjs @@ -28,6 +28,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import vm from "node:vm"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -539,7 +540,8 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = }); for (const name of use) if (!(name in manifest.modules)) throw new Error(`basalt:use names "${name}", which is not a module (modules: ${Object.keys(manifest.modules).join(", ")})`); - const content = held.restore(markup).replace(/^\s+/, ""); + const diagramNotes = []; + const content = writeDiagrams(held.restore(markup).replace(/^\s+/, ""), parts, diagramNotes); title ||= held.h1 || "Untitled page"; // an empty names nothing: the heading does // Detection reads markup and code, never comments: a word written about in a comment (an HTML one, or one inside a script or a style) brings nothing in. @@ -587,7 +589,41 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = "</html>", "", ].join("\n"); - return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), bytes: Buffer.byteLength(html) }; + return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), diagrams: diagramNotes, bytes: Buffer.byteLength(html) }; +} + +/** + * A diagram's words, written into the page (DECISIONS 269, 1.19): each `<figure class="diagram">` that holds only its JSON gets the markup the diagram module's + * script would write for it, from that same script (parts/diagram.js, run here without a page), so the page reads before any script runs. The figure's own + * attributes stay (its class joins ours, its id stays); the JSON stays for the script. A figure whose JSON does not parse is left for the script, which says why. + */ +function writeDiagrams(content, parts, notes) { + if (!/\bdata-diagram\b/.test(content) || !exists(parts, "diagram.js")) return content; + let markup = null; + let serial = 0; + const figure = /<figure\b((?:"[^"]*"|'[^']*'|[^>"'])*)>(\s*<script\b(?:"[^"]*"|'[^']*'|[^>"'])*\bdata-diagram\b(?:"[^"]*"|'[^']*'|[^>"'])*>)([\s\S]*?)(<\/script\s*>)(\s*)<\/figure\s*>/gi; + return content.replace(figure, (whole, attrs, open, json, close) => { + if (!/\bclass\s*=\s*(?:"[^"]*\bdiagram\b[^"]*"|'[^']*\bdiagram\b[^']*')/.test(attrs) || /\bdata-diagram-drawn\b/.test(attrs)) return whole; + let spec; + try { spec = JSON.parse(json); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); return whole; } + if (!markup) { + const context = { window: { Basalt: { _: { step() {}, esc: (x) => x } } }, console: { warn() {}, error() {}, log() {} } }; + vm.runInNewContext(read(parts, "diagram.js"), context); + markup = context.window.Basalt._.diagramMarkup; + } + const made = markup(spec, `dg${++serial}`); + for (const w of made.warnings) notes.push(`${spec.title ?? "a diagram"}: ${w}`); + const ours = [...made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]); + const theirs = [...attrs.matchAll(/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g)].map((m) => [m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? ""]); + const merged = new Map(theirs); + for (const [k, v] of ours) { + if (k === "class") merged.set("class", [...new Set(`${merged.get("class") ?? ""} ${v}`.split(/\s+/).filter(Boolean))].join(" ")); + else if (k === "style") merged.set("style", merged.has("style") ? `${v};${merged.get("style")}` : v); + else merged.set(k, v); + } + const tag = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; + return `${tag}${open}${json}${close}${made.inner}</figure>`; + }); } /** The module lines of SKILL.md's "## Modules" index: [{ name, trigger, warning }]. A line is `- **name** \`trigger\`: warning`. */ @@ -707,6 +743,7 @@ if (isMain) { const say = (l) => (l.name in result.built ? ` ${l.name}: built by the ${result.built[l.name]}; nothing to check.` : ` ${l.name}: ${l.warning}`); if (warnings.length) console.log(`Check before you hand it over (the full text of one: --usage NAME):\n${warnings.map(say).join("\n")}`); } + for (const note of result.diagrams) console.log(`Diagram: ${note}`); // After the page and the modules' lines: what the body references that is not in the file. The page is written; the warning is for the one who handed it over. if (result.external.length) console.log(`Warning: ${result.external.length} reference${result.external.length === 1 ? "" : "s"} leave${result.external.length === 1 ? "s" : ""} the file, and a page is one file with no network (nothing loads offline; a link is the reader's to follow):\n${result.external.map((line) => ` ${line}`).join("\n")}`); } catch (e) { diff --git a/.agent/skills/basalt-html/parts/diagram.css b/.agent/skills/basalt-html/parts/diagram.css new file mode 100644 index 00000000..6c04c128 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram.css @@ -0,0 +1 @@ +:root{--basalt-size-diagram-node: 144px;--basalt-size-diagram-table: 224px;--basalt-size-diagram-lane: 120px;--basalt-size-diagram-step: 56px;--basalt-size-diagram-head: 8px;--basalt-size-diagram-guide-dash: 4px}:root,[data-theme=light],.light{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-white-6);--basalt-diagram-focal-rule-contrast: var(--basalt-white-38)}[data-theme=dark],.dark{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}}@media(prefers-contrast:more){:root,[data-theme=light],[data-theme=dark],.light,.dark,:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-diagram-focal-rule-contrast)}}@layer basalt{.diagram{--_ground: var(--panel-bg, var(--basalt-surface-page));container-type:inline-size;display:flex;flex-direction:column;gap:var(--basalt-space-4);width:100%;min-width:0;margin:0;font-family:var(--basalt-font-family-sans)}.diagram-head{display:flex;flex-direction:column;gap:var(--basalt-space-0-5);min-width:0}.diagram-title{margin:0;color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans);letter-spacing:var(--basalt-text-md-tracking)}.diagram-source{margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-drawing{--_drawn: initial;--_d-display: var(--_drawn) grid;--_d-max: var(--_drawn) none;--_d-cols: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-gap: var(--_drawn) var(--_row-gap) var(--_col-gap);--_d-pad: var(--_drawn) var(--_gpad, 0);--_row-gap: var(--basalt-space-12);--_col-gap: var(--basalt-space-16);position:relative;box-sizing:border-box;display:var(--_d-display, flex);flex-direction:column;grid-template-columns:var(--_d-cols, none);gap:var(--_d-gap, 0);width:100%;max-width:var(--_d-max, var(--basalt-size-breakpoint-container));min-width:0;padding:var(--_d-pad, 0 var(--_gutter, 0) 0 0)}.diagram[data-layout=drawn]>.diagram-drawing{--_drawn: }.diagram[data-layout=stacked]>.diagram-drawing{--_drawn: initial}.diagram[data-gutter]>.diagram-drawing{--_gutter: var(--basalt-space-10)}.diagram[data-type=data-flow]>.diagram-drawing{--_d-cols: var(--_drawn) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr));--_row-gap: var(--basalt-space-10);--_col-gap: var(--basalt-space-12)}.diagram[data-type=schema]>.diagram-drawing{--_row-gap: var(--basalt-space-8);--_col-gap: var(--basalt-space-12);display:grid;grid-template-columns:var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));gap:var(--_d-gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram-node{--_d-gc: var(--_drawn) var(--_c);--_d-gr: var(--_drawn) var(--_r) / var(--_r2);--_d-mt: var(--_drawn) 0;--_d-align: var(--_drawn) center;position:relative;z-index:1;box-sizing:border-box;display:flex;flex-direction:column;min-width:0;grid-column:var(--_d-gc, auto);grid-row:var(--_d-gr, auto);align-self:var(--_d-align, stretch);margin-block-start:var(--_d-mt, var(--_gap, 0));padding:var(--basalt-space-2-5) var(--basalt-space-3);background:var(--panel-next, var(--basalt-surface-1));border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);color:var(--basalt-text-primary);overflow-wrap:break-word;outline:none;transition:border-color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-type=data-flow] .diagram-node{--_d-gc: var(--_drawn) var(--_lc)}.diagram-node[data-branch]{--_d-mi: var(--_drawn) 0;margin-inline:var(--_d-mi, var(--basalt-space-12) var(--basalt-space-6))}.diagram-node:focus-visible{z-index:2;outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:var(--basalt-size-focus-offset)}.diagram-node[data-near]{border-color:var(--basalt-border-hover)}.diagram-kind{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-lane-word{--_d-lw: var(--_drawn) none;display:var(--_d-lw, inline)}.diagram-name{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-detail{margin-block-start:var(--basalt-space-0-5);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-detail[data-mono]{font-family:var(--basalt-font-family-mono)}.diagram-node[data-focal]{background:var(--basalt-diagram-focal);border-color:var(--basalt-diagram-focal)}.diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:var(--basalt-diagram-focal-ink)}.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:var(--basalt-opacity-amount)}.diagram[data-type=flowchart] .diagram-node:not([data-focal]){border-color:var(--basalt-diagram-structure)}.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:var(--basalt-text-secondary)}.diagram-node[data-shape=terminal]{align-items:center;padding-inline:var(--basalt-space-5);border-radius:var(--basalt-radius-full);text-align:center}.diagram-node[data-shape=decision]{justify-content:center;align-items:center;height:var(--_h, auto);min-height:var(--basalt-space-16);padding:var(--basalt-space-2) var(--basalt-space-2-5);text-align:center}.diagram-words{position:relative;max-width:62%}.diagram-node[data-shape=decision] .diagram-name{font-weight:var(--basalt-font-weight-medium);text-wrap:balance}.diagram-diamond{display:none;position:absolute;inset:0;width:100%;height:100%;overflow:visible}.diagram-diamond path{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);vector-effect:non-scaling-stroke;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-measured] .diagram-node[data-shape=decision]{background:none;border-color:transparent}.diagram[data-measured] .diagram-node[data-shape=decision] .diagram-diamond{display:block}.diagram-node[data-shape=decision][data-near] .diagram-diamond path{stroke:var(--basalt-text-secondary)}.diagram-node[data-shape=decision][data-focal] .diagram-diamond path{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-group{--_d-gd: var(--_drawn) contents;position:relative;box-sizing:border-box;display:var(--_d-gd, flex);flex-direction:column;margin-block-start:var(--basalt-space-12);padding:var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5);border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg)}.diagram-group:first-child{margin-block-start:0}.diagram-group>.diagram-glabel+.diagram-node{--_d-mt: 0}.diagram-glabel{position:absolute;top:var(--basalt-space-2);inset-inline-start:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);white-space:nowrap}.diagram-group>.diagram-glabel{--_d-gl: var(--_drawn) none;display:var(--_d-gl, block)}.diagram-gbox{--_d-gb: var(--_drawn) block;position:relative;display:var(--_d-gb, none);grid-column:var(--_c) / var(--_c2);grid-row:var(--_r) / var(--_r2);margin:calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4));border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-lane{--_d-ln: var(--_drawn) flex;position:relative;display:var(--_d-ln, none);grid-column:1 / -1;grid-row:var(--_r);align-items:center;pointer-events:none}.diagram-lane+.diagram-lane:before{content:"";position:absolute;inset-inline:0;top:calc(-1 * var(--basalt-space-5));border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-lane-name{box-sizing:border-box;width:var(--basalt-size-diagram-lane);padding-inline-end:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-ink{position:absolute;inset:0;z-index:0;pointer-events:none}.diagram-svg{position:absolute;top:0;left:0;overflow:visible}.diagram-ruler{position:absolute;visibility:hidden;white-space:pre;pointer-events:none}.diagram-ruler[data-f=name]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=name-500]{font:var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=table]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-ruler:is([data-f=mono],[data-f=label]){font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-ruler[data-f=sans]{font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-line{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main);stroke-width:var(--basalt-size-chart-line)}.diagram-line[data-kind=dashed]{stroke-dasharray:var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap);stroke-linecap:butt}.diagram-tip{fill:var(--basalt-diagram-edge);transition:fill var(--basalt-duration-fast) var(--basalt-ease-out),stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-tip[data-kind=main]{fill:var(--basalt-diagram-edge-main)}.diagram-tip[data-open]{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:round;stroke-linejoin:round}.diagram-dot{fill:var(--basalt-diagram-edge)}.diagram-life{fill:none;stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);stroke-dasharray:var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash)}.diagram-edge[data-lit] .diagram-line{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip:not([data-open]),.diagram-edge[data-lit] .diagram-dot{fill:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip:not([data-open]),.diagram-edge[data-dim] .diagram-dot{fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-label{position:absolute;box-sizing:border-box;height:var(--basalt-text-xs-line-height);color:var(--basalt-diagram-edge);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);text-align:center;white-space:nowrap;transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-label[data-on]{background:var(--_ground)}.diagram-label[data-lit]{color:var(--basalt-diagram-edge-main)}.diagram-cast{--_d-cd: var(--_drawn) grid;display:var(--_d-cd, flex);flex-wrap:wrap;grid-template-columns:repeat(var(--_cols, 1),minmax(0,1fr));gap:var(--_d-cast-gap, var(--basalt-space-1-5));--_d-cast-gap: var(--_drawn) var(--basalt-space-5);margin:0;padding:0;list-style:none}.diagram-actor{display:flex;min-width:0}.diagram-node[data-shape=participant]{--_d-pd: var(--_drawn) var(--basalt-space-2-5) var(--basalt-space-3);--_d-pr: var(--_drawn) var(--basalt-radius-md);--_d-pa: var(--_drawn) center;flex:var(--_d-pflex, none);--_d-pflex: var(--_drawn) 1;align-items:center;justify-content:var(--_d-pa, center);min-height:var(--_d-ph, var(--basalt-size-badge));--_d-ph: var(--_drawn) 0;padding:var(--_d-pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline)));border-radius:var(--_d-pr, var(--basalt-radius-xs));text-align:center}.diagram-node[data-shape=participant]:not([data-focal]){--_d-pbg: var(--_drawn) var(--panel-next, var(--basalt-surface-1));--_d-pbc: var(--_drawn) var(--basalt-border-rim);--_d-pbt: var(--_drawn) var(--basalt-border-rim-top);background:var(--_d-pbg, none);border-color:var(--_d-pbc, var(--basalt-border-hairline));border-top-color:var(--_d-pbt, var(--basalt-border-hairline))}.diagram-node[data-shape=participant] .diagram-kind{--_d-pk: var(--_drawn) block;display:var(--_d-pk, none)}.diagram-node[data-shape=participant] .diagram-name{font-size:var(--_d-pn, var(--basalt-text-xs-size));line-height:var(--_d-pnl, var(--basalt-text-xs-line-height));font-weight:var(--_d-pw, var(--basalt-font-weight-medium));--_d-pn: var(--_drawn) var(--basalt-text-sm-size);--_d-pnl: var(--_drawn) var(--basalt-text-sm-line-height);--_d-pw: var(--_drawn) var(--basalt-font-weight-semibold)}.diagram-steps{--_d-sp: var(--_drawn) var(--basalt-space-4);position:relative;z-index:1;padding-block-start:var(--_d-sp, var(--basalt-space-4))}.diagram-msgs{margin:0;padding:0;list-style:none}.diagram-msg{--_d-md: var(--_drawn) grid;--_d-mc: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-mr: var(--_drawn) 1fr 1fr;--_d-mh: var(--_drawn) var(--basalt-size-diagram-step);--_d-mg: var(--_drawn) 0 var(--basalt-space-5);display:grid;grid-template-columns:var(--_d-mc, var(--basalt-space-8) minmax(0, 1fr));grid-template-rows:var(--_d-mr, auto);column-gap:var(--basalt-space-5);gap:var(--_d-mg, 0);height:var(--_d-mh, auto);padding-block:var(--_d-mpb, var(--basalt-space-2-5));--_d-mpb: var(--_drawn) 0;border-top:var(--_d-mb, var(--basalt-size-hairline) solid var(--basalt-border-divider));--_d-mb: var(--_drawn) 0;font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-said{--_d-sd: var(--_drawn) block;display:var(--_d-sd, contents);grid-column:var(--_a) / var(--_b);grid-row:1;align-self:end;justify-self:center;margin-block-end:calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--basalt-space-1-5);background:var(--_ground);white-space:nowrap}.diagram-num{grid-column:1;color:var(--basalt-text-tertiary);font-variant-numeric:tabular-nums}.diagram-said .diagram-num{margin-inline-end:var(--_d-nm, 0);--_d-nm: var(--_drawn) var(--basalt-space-1-5)}.diagram-mlabel{grid-column:2;color:var(--basalt-text-primary);font-family:var(--basalt-font-family-mono)}.diagram-route{--_d-rd: var(--_drawn) none;display:var(--_d-rd, inline-flex);grid-column:2;align-items:center;gap:var(--basalt-space-1);flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-note{--_d-nd: var(--_drawn) 2;grid-column:var(--_d-nc, 2);--_d-nc: var(--_drawn) var(--_a) / var(--_b);grid-row:var(--_d-nd, auto);align-self:start;justify-self:var(--_d-nj, stretch);--_d-nj: var(--_drawn) center;margin-block-start:var(--_d-nmt, 0);--_d-nmt: var(--_drawn) calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--_d-npi, 0);--_d-npi: var(--_drawn) var(--basalt-space-1-5);background:var(--_d-nbg, none);--_d-nbg: var(--_drawn) var(--_ground);color:var(--basalt-text-tertiary);white-space:var(--_d-nws, normal);--_d-nws: var(--_drawn) nowrap}.diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) start;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-start:var(--_d-sm, 0)}.diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) end;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-end:var(--_d-sm, 0)}.diagram-arrow{flex:none;overflow:visible}.diagram-band{--_d-bh: var(--_drawn) var(--basalt-size-control-lg);--_d-bj: var(--_drawn) center;position:relative;display:flex;align-items:center;justify-content:var(--_d-bj, flex-start);height:var(--_d-bh, auto);margin:var(--_d-bm, var(--basalt-space-5) 0 var(--basalt-space-2));--_d-bm: var(--_drawn) 0;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-band:before{--_d-br: var(--_drawn) "";content:var(--_d-br, none);position:absolute;inset-inline:0;top:50%;border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-band>span{position:relative;padding-inline:var(--_d-bp, 0);--_d-bp: var(--_drawn) var(--basalt-space-1-5);background:var(--_ground)}.diagram-node[data-shape=table]{align-self:start;padding:0;overflow-wrap:normal}.diagram-th{padding:var(--basalt-space-2) var(--basalt-space-3);border-bottom:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-node[data-focal] .diagram-th{border-bottom-color:var(--basalt-diagram-focal-rule)}.diagram-tname{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-rows{display:flex;flex-direction:column;padding-block:var(--basalt-space-1)}.diagram-row{display:flex;flex-wrap:wrap;align-items:center;column-gap:var(--basalt-space-3);min-height:var(--basalt-size-control-sm);padding-inline:var(--basalt-space-3);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-keyseat{flex:none;width:var(--basalt-space-6);margin-inline-end:calc(-1 * var(--basalt-space-3));color:var(--basalt-text-tertiary)}.diagram-cname{flex:1 0 auto;color:var(--basalt-text-primary)}.diagram-ctype{margin-inline-start:auto;color:var(--basalt-text-tertiary)}.diagram-ctype[data-ref]{color:var(--basalt-text-secondary)}.diagram-more{padding:0 var(--basalt-space-3) var(--basalt-space-2);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-key{padding-block-start:var(--basalt-space-3);border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-legend{display:flex;flex-wrap:wrap;gap:var(--basalt-space-2) var(--basalt-space-5);margin:0;padding:0;list-style:none;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-entry{display:inline-flex;align-items:center;gap:var(--basalt-space-1-5)}.diagram[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram:not([data-layout]) .diagram-entry[data-when=drawn]{display:none}.diagram-swatch{flex:none;overflow:visible}.diagram-swatch-shape{fill:var(--_ground);stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline)}.diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke-dasharray:var(--basalt-space-1) var(--basalt-space-0-5)}.diagram-fk-mark{color:var(--basalt-text-secondary);font-family:var(--basalt-font-family-mono)}.diagram-hint{display:flex;flex-wrap:wrap;gap:var(--basalt-space-1) var(--basalt-space-4);margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-hint>span{display:inline-flex;align-items:center;gap:var(--basalt-space-1)}.diagram[data-layout=stacked]:is([data-type=sequence],[data-type=schema]) .diagram-hint{display:none}.diagram-summary{order:1;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans);text-wrap:pretty}.diagram-foot{order:2;display:flex}.diagram-list{order:3;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list[hidden]{display:none}.diagram-list strong{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-code{color:var(--basalt-text-primary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-list-head{margin:var(--basalt-space-4) 0 var(--basalt-space-2);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list-head:first-child{margin-block-start:0}.diagram-list-group{margin:var(--basalt-space-3) 0 var(--basalt-space-1);color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-medium)}.diagram-list-items{display:flex;flex-direction:column;gap:var(--basalt-space-1);margin:0;padding-inline-start:var(--basalt-space-5)}.diagram-list-exits{margin:var(--basalt-space-1) 0 0;padding-inline-start:var(--basalt-space-5)}@media(pointer:coarse){.diagram-toggle{min-height:var(--basalt-size-tap-min)}}@media(prefers-reduced-motion:reduce){.diagram-node,.diagram-line,.diagram-tip,.diagram-label,.diagram-diamond path{transition:none}}@media(prefers-contrast:more){.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:1}}@container (width >= 640px){.diagram:not([data-layout])[data-type=architecture][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 696px){.diagram:not([data-layout])[data-type=data-flow][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 768px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="4"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 784px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 800px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 888px){.diagram:not([data-layout])[data-type=data-flow][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 964px){.diagram:not([data-layout])[data-type=sequence][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 976px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 992px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1008px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 1080px){.diagram:not([data-layout])[data-type=data-flow][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1184px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1200px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1216px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1272px){.diagram:not([data-layout])[data-type=data-flow][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1312px){.diagram:not([data-layout])[data-type=schema][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]>.diagram-drawing{--_drawn: }}@media(scripting:none){.diagram:not(#basalt-diagram-no-id)>.diagram-drawing{--_drawn: initial}.diagram-list[hidden]{display:block}.diagram-foot,.diagram-entry[data-line],.diagram-hint{display:none}}@media(forced-colors:active){.diagram-svg,.diagram-swatch,.diagram-arrow{forced-color-adjust:none}.diagram .diagram-line,.diagram .diagram-line[data-kind]{stroke:CanvasText}.diagram .diagram-tip,.diagram .diagram-tip[data-kind],.diagram .diagram-dot{fill:CanvasText}.diagram .diagram-tip[data-open],.diagram .diagram-tip[data-kind][data-open]{fill:none;stroke:CanvasText}.diagram .diagram-edge[data-dim] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-dim] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:GrayText}.diagram .diagram-edge[data-dim] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-edge[data-lit] .diagram-line{stroke:Highlight}.diagram .diagram-edge[data-lit] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:Highlight}.diagram .diagram-edge[data-lit] .diagram-tip[data-open]{stroke:Highlight}.diagram .diagram-life{stroke:GrayText}.diagram .diagram-label{color:CanvasText;forced-color-adjust:none}.diagram .diagram-label[data-on]{background:Canvas}.diagram .diagram-label[data-lit]{color:Highlight}.diagram .diagram-swatch-shape{fill:Canvas;stroke:CanvasText}.diagram .diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke:GrayText}.diagram .diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:CanvasText;stroke:CanvasText}.diagram[data-type=flowchart] .diagram-node:not([data-focal]),.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:CanvasText}.diagram .diagram-diamond{forced-color-adjust:none}.diagram .diagram-diamond path,.diagram .diagram-node[data-near] .diagram-diamond path{fill:Canvas;stroke:CanvasText}.diagram .diagram-group,.diagram .diagram-gbox{border-color:GrayText}.diagram .diagram-lane+.diagram-lane:before,.diagram .diagram-band:before{border-color:GrayText}.diagram .diagram-hint{color:GrayText}.diagram :is(.diagram-kind,.diagram-name,.diagram-detail,.diagram-glabel,.diagram-lane-name,.diagram-title,.diagram-source,.diagram-num,.diagram-mlabel,.diagram-route,.diagram-note,.diagram-band,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more,.diagram-legend,.diagram-fk-mark){color:CanvasText}.diagram .diagram-node:focus-visible{outline-color:Highlight}.diagram .diagram-node[data-focal],.diagram .diagram-node[data-focal][data-near]{forced-color-adjust:none;background:CanvasText;border-color:CanvasText}.diagram .diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:Canvas;opacity:1}.diagram .diagram-node[data-focal] .diagram-th{border-bottom-color:Canvas}.diagram .diagram-node[data-focal]:focus-visible{outline:var(--basalt-size-focus-width) solid Highlight}.diagram .diagram-node[data-focal][data-shape=decision] .diagram-diamond path{fill:CanvasText;stroke:CanvasText}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow{print-color-adjust:exact}.diagram-hint{display:none}}} diff --git a/.agent/skills/basalt-html/parts/diagram.js b/.agent/skills/basalt-html/parts/diagram.js new file mode 100644 index 00000000..10ce884f --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram.js @@ -0,0 +1 @@ +(()=>{var Nt=["top","right","bottom","left"];function $t(t){const e=[],n=i=>{e.push(i)},a={...t.legend??{}},o=typeof t.stepLabel=="function"?t.stepLabel:typeof t.stepLabel=="string"?(i=>t.stepLabel.replace("{n}",String(i))):i=>`Step ${i}`,s={terminal:"Start or end",step:"Step",decision:"Decision",...t.shapeLabels??{}},r=[],d=[];let h=[];const l=[],c=[],u=t.type;if(u==="architecture"||u==="flowchart"){for(const i of t.nodes??[]){const g=u==="flowchart"&&i.shape==="decision"?"decision":u==="flowchart"&&i.shape==="terminal"?"terminal":"box";r.push({id:i.id,i:r.length,name:i.name,kind:g==="decision"?void 0:i.kind,detail:g==="decision"?void 0:i.detail,mono:!!i.detailMono,focal:!!i.focal,col:i.col,row:i.row,row2:i.row,branch:!!i.branch,shape:g,group:u==="architecture"?i.group:void 0})}if(u==="architecture")for(const i of t.groups??[])l.push({...i,members:r.filter(g=>g.group===i.id).map(g=>g.id)})}else if(u==="data-flow"){h=t.lanes??[];const i=new Map(h.map((g,b)=>[g.id,b+1]));for(const g of t.nodes??[]){const b=i.get(g.lane);b===void 0&&n(`a node (${g.id}) names the lane "${g.lane}", which is not in lanes`);const m=r.length+1;r.push({id:g.id,i:r.length,name:g.name,kind:o(m),detail:g.detail,mono:!!g.detailMono,focal:!!g.focal,col:g.col,row:b??1,row2:b??1,branch:!1,shape:"box",lane:b??1,laneLabel:h[(b??1)-1]?.label??g.lane,step:m})}}else if(u==="sequence"){(t.participants??[]).forEach((g,b)=>r.push({id:g.id,i:b,name:g.name,kind:g.kind,mono:!1,focal:!!g.focal,col:b+1,row:1,row2:1,branch:!1,shape:"participant",short:g.short??g.name}));let i=0;for(const g of t.steps??[])"band"in g?c.push({band:g.band}):c.push({n:++i,from:g.from,to:g.to,label:g.label,note:g.note,kind:g.kind??"plain"})}else if(u==="schema")for(const i of t.tables??[]){const[g,b]=Array.isArray(i.row)?i.row:[i.row,i.row];r.push({id:i.name,i:r.length,name:i.name,mono:!0,focal:!!i.focal,col:i.col,row:g,row2:b,branch:!1,shape:"table",more:i.more,columns:i.columns.map(m=>({name:m.name,type:m.type,key:m.key}))})}const p=new Map;for(const i of r)i.id?p.has(i.id)&&n(`the id "${i.id}" is used twice`):n("a node has no id"),p.set(i.id,i);if(u==="schema")(t.tables??[]).forEach(i=>i.columns.forEach((g,b)=>{if(!g.references)return;const[m,x]=g.references.split("."),B=p.get(m??""),v=B?.columns?.findIndex(I=>I.name===x)??-1;if(!B||v<0){n(`${i.name}.${g.name} references ${g.references}, which is not a shown column`);return}const _=p.get(i.name);_.columns[b].ref={table:m,column:x,row:v},d.push({i:d.length,from:i.name,to:m,kind:"plain",fromRow:b,toRow:v,fk:!0})}));else if(u!=="sequence")for(const i of t.edges??[]){if(!p.has(i.from)||!p.has(i.to)){n(`a line names ${p.has(i.from)?i.to:i.from}, which is not a node`);continue}i.label&&i.label.length>wt&&n(`the label "${i.label}" is over ${wt} characters: longer words belong in the node or the summary`);for(const g of[i.fromSide,i.toSide])g&&!Nt.includes(g)&&n(`"${g}" is not a side (top, right, bottom or left)`);d.push({i:d.length,from:i.from,to:i.to,kind:i.kind??"plain",label:i.label||void 0,fromSide:i.fromSide,toSide:i.toSide})}else for(const i of c)"n"in i&&(!p.has(i.from)||!p.has(i.to))&&n(`message ${i.n} names ${p.has(i.from)?i.to:i.from}, which is not a participant`);if(u!=="sequence"){const i=new Map;for(const g of r)for(let b=g.row;b<=g.row2;b++){const m=`${g.col}:${b}`;i.has(m)&&n(`${g.id} and ${i.get(m)} share the cell at column ${g.col}, row ${b}`),i.set(m,g.id)}}for(const i of l){const g=i.members.map(x=>p.get(x));if(!g.length)continue;const b={c1:Math.min(...g.map(x=>x.col)),c2:Math.max(...g.map(x=>x.col)),r1:Math.min(...g.map(x=>x.row)),r2:Math.max(...g.map(x=>x.row2))};for(const x of r)x.group!==i.id&&x.col>=b.c1&&x.col<=b.c2&&x.row>=b.r1&&x.row<=b.r2&&n(`${x.id} is inside the box of the group "${i.label}" but not a member`);const m=g.map(x=>x.i);Math.max(...m)-Math.min(...m)+1!==m.length&&n(`the members of the group "${i.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const i of r)i.group&&!l.some(g=>g.id===i.group)&&n(`${i.id} names the group "${i.group}", which is not in groups`);r.filter(i=>i.focal).length>1&&n("more than one node is focal: a diagram has one at most");const M=new Set(u==="sequence"?c.flatMap(i=>"n"in i?[i.kind]:[]):d.map(i=>i.kind));M.has("main")&&!a.main&&n("main lines are drawn but the legend has no words for them (legend.main)"),M.has("dashed")&&!a.dashed&&n("dashed lines are drawn but the legend has no words for them (legend.dashed)"),r.some(i=>i.focal)&&!a.focal&&n("a focal node is drawn but the legend has no words for what it marks (legend.focal)");const f=Math.max(1,...r.map(i=>i.col)),y=u==="data-flow"?Math.max(1,h.length):Math.max(1,...r.map(i=>i.row2));return{type:u,title:t.title,heading:t.heading??3,legend:a,nodes:r,byId:p,edges:d,groups:l,lanes:h,steps:c,cols:f,rows:y,shapeLabels:s,stepWord:o,warnings:e}}var wt=28,at=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""},Gt=t=>t.charAt(0).toUpperCase()+t.slice(1);function xt(t,e){return t.legend[e]}function Dt(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function Vt(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const a=(e.columns??[]).filter(s=>s.ref).map(s=>`${s.ref.table} (${s.name})`),o=t.edges.filter(s=>s.to===e.id).map(s=>`${s.from} (${t.byId.get(s.from).columns[s.fromRow].name})`);a.length&&n.push(`References ${a.join(", ")}.`),o.length&&n.push(`Referenced by ${o.join(", ")}.`)}else if(t.type==="sequence"){const a=t.steps.filter(s=>"n"in s&&s.from===e.id).length,o=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(at(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${a} ${a===1?"message":"messages"} and receives ${o}.`)}else{const a=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?Dt(t,e):e.kind;if(n.push(at(a?`${e.name}, ${a}`:e.name)),e.detail&&n.push(at(e.detail)),e.group){const r=t.groups.find(d=>d.id===e.group);r&&n.push(`In ${r.label}.`)}const o=t.edges.filter(r=>r.to===e.id).map(r=>`${t.byId.get(r.from).name}${r.label?` (${r.label})`:""}`),s=t.edges.filter(r=>r.from===e.id).map(r=>`${t.byId.get(r.to).name}${r.label?` (${r.label})`:""}`);o.length&&n.push(`From: ${o.join(", ")}.`),s.length&&n.push(`To: ${s.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(at(t.legend.focal)),n.join(" ")}function Zt(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function $(t,e,...n){const a=[];for(const o of n.flat(1/0))o!=null&&o!==!1&&!Array.isArray(o)&&a.push(o);return{t,a:e??{},c:a}}var Kt={"&":"&","<":"<",">":">",'"':""","'":"'"},tt=t=>t.replace(/[&<>"']/g,e=>Kt[e]),Ut=" br img input meta link hr path polygon polyline circle rect line ";function Mt(t,e={}){if(typeof t=="string")return tt(t);if("slot"in t)return e[t.slot]??"";let n="";for(const[a,o]of Object.entries(t.a))o==null||o===!1||(n+=o===!0?` ${a}`:` ${a}="${tt(String(o))}"`);return Ut.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(a=>Mt(a,e)).join("")}</${t.t}>`}var Xt=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function rt(t,e){return e.layout?e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema":!1}function Yt(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function vt(t){let e=0;for(const n of t.groups){const a=n.members.map(o=>t.byId.get(o).col);a.length&&(Math.min(...a)===1&&(e|=1),Math.max(...a)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function ht(t){return t.type==="sequence"?t.nodes.length:t.cols}function kt(t){const e=t.nodes,n=f=>t.type==="data-flow"||!e[f].branch,a=t.edges.map(f=>{const y=t.byId.get(f.from).i,i=t.byId.get(f.to).i,b=e.slice(Math.min(y,i)+1,Math.max(y,i)).every(m=>!n(m.i));return i===y+1&&!(n(y)&&!n(i))?"down":i===y-1?"up":i>y&&n(y)&&!n(i)&&b?"trunk":i>y&&n(y)&&n(i)&&b?"rail":i>y?"end-down":"end-up"}),o=t.edges.map((f,y)=>({e:f,k:y})).filter(({k:f})=>a[f]==="end-down"||a[f]==="end-up"),s=f=>{const y=t.byId.get(f.from).i,i=t.byId.get(f.to).i;return[Math.min(y,i),Math.max(y,i)]},r=(f,y)=>{const[i,g]=s(f),[b,m]=s(y);return i<m&&b<g},d=o.every(({e:f})=>{const y=t.byId.get(f.from).i,[i,g]=s(f);return!n(y)&&e.slice(i+1,g).every(b=>!n(b.i))&&o.every(b=>b.e===f||!r(b.e,f))}),h=o.length>0&&(t.type==="data-flow"||!d),l=f=>{const[y,i]=s(f);return i-y},c=t.edges.map(()=>0);let u=!1;for(const{e:f,k:y}of o){const i=o.filter(g=>g.e!==f&&r(g.e,f)&&(l(g.e)<l(f)||l(g.e)===l(f)&&g.k<y));if(c[y]=i.length?1:0,i.length>1||o.filter(g=>g.e!==f&&r(g.e,f)).length>1){const g=o.filter(b=>b.e!==f&&r(b.e,f));g.some(b=>g.some(m=>m!==b&&r(b.e,m.e)))&&(u=!0)}}const p=t.edges.map(()=>.5);for(const f of e){const y=o.filter(({e:b})=>b.from===f.id);if(y.length<2)continue;const i=y.filter(({k:b})=>a[b]==="end-down").sort((b,m)=>l(m.e)-l(b.e)||b.k-m.k),g=y.filter(({k:b})=>a[b]==="end-up").sort((b,m)=>l(b.e)-l(m.e)||m.k-b.k);[...i,...g].forEach(({k:b},m,x)=>{p[b]=x.length===2?m===0?1/3:2/3:(m+1)/(x.length+1)})}const M={};for(let f=1;f<e.length;f++){const y=e[f],i=e[f-1];let g=0,b=t.type==="data-flow"?48:32,m=!1,x=!1;t.edges.forEach((B,v)=>{const _=a[v],I=t.byId.get(B.from).i,j=t.byId.get(B.to).i,F=j===f&&(_==="down"||_==="trunk"||_==="rail"||_==="end-down"),G=I===f&&j===f-1&&_==="up",A=j===f-1&&_==="end-up";F&&(_==="trunk"||_==="end-down")&&(m=!0),A&&(x=!0),(F||G||A)&&B.label&&(g++,b=Math.max(b,_==="trunk"?40:48))}),(g>1||m&&x)&&(b=64),M[y.id]=b}return{routes:a,gutter:h,lanes:c,exits:p,gaps:M,third:u}}var ct=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function St(t,e){const n=e==="fk"?"plain":e,a=n==="main"?8:8.5,o=24,s=n==="dashed"?o-1:o-7;return $("svg",{class:`${t}-swatch`,"data-kind":n,...ct(24,16)},e==="fk"?$("circle",{class:`${t}-dot`,cx:3,cy:a,r:3}):null,$("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${a}H${s}`}),n==="dashed"?$("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${o-8} ${a-4}L${o} ${a}L${o-8} ${a+4}`}):$("path",{class:`${t}-tip`,"data-kind":n,d:`M${o} ${a}L${o-8} ${a-4}L${o-8} ${a+4}Z`}))}function dt(t,e){return e==="decision"?$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function Jt(t,e){const n=[],a=(s,r,d={})=>n.push($("li",{class:`${t}-entry`,...d},s,$("span",null,r)));if(e.type==="flowchart"){const s=new Set(e.nodes.map(r=>r.shape));s.has("terminal")&&a(dt(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&a(dt(t,"box"),e.shapeLabels.step),s.has("decision")&&a(dt(t,"decision"),e.shapeLabels.decision)}const o=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind));for(const s of["main","plain","dashed"]){const r=e.legend[s];o.has(s)&&r&&a(St(t,s),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(a(St(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"}),n.push($("li",{class:`${t}-entry`,"data-when":"stacked"},$("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},"→"),$("span",null,"A foreign key, written in the row")))),e.nodes.some(s=>s.focal)&&e.legend.focal&&a(dt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&a(dt(t,"group"),e.legend.group),n.length?$("div",{class:`${t}-key`},$("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function Qt(t,e){const n=e==="main"?6:6.5;return $("svg",{class:`${t}-arrow`,"data-kind":e,...ct(20,12)},$("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?$("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):$("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function Pt(t,e,n){if(n.shape==="decision")return[$("span",{class:`${t}-words`},$("span",{class:`${t}-name`},n.name))];const a=[];return e.type==="data-flow"?a.push($("span",{class:`${t}-kind`},n.kind,$("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&a.push($("span",{class:`${t}-kind`},n.kind)),a.push($("span",{class:`${t}-name`},n.name)),n.detail&&a.push($("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.detail)),a}function te(t,e){return[$("span",{class:`${t}-th`},$("span",{class:`${t}-tname`},e.name)),$("span",{class:`${t}-rows`},(e.columns??[]).map((n,a)=>$("span",{class:`${t}-row`,"data-row":a,"data-key":n.key},$("span",{class:`${t}-keyseat`},n.key??""),$("span",{class:`${t}-cname`},n.name),n.ref?$("span",{class:`${t}-ctype`,"data-ref":""},`→ ${n.ref.table}`):n.type?$("span",{class:`${t}-ctype`},n.type):null))),e.more?$("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Et=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function pt(t,e,n,a){const{P:o}=t,s=Yt(e,a)||a.keep===n.id,r=rt(e,a),d=[`--_c:${n.col}`,`--_r:${n.row}`,`--_r2:${n.row2+1}`];e.type==="data-flow"&&d.push(`--_lc:${n.col+1}`),e.type==="sequence"&&d.push(`--_c2:${n.col+1}`);const h=t.plan;if(h&&n.i>0){const c=h.gaps[n.id]??32,u=a.grow?.[n.id]??0;d.push(`--_gap:${u?`calc(${Et(c)} + var(--basalt-space-4) * ${u})`:Et(c)}`)}a.heights?.[n.id]&&d.push(`--_h:${a.heights[n.id]}px`);const l=r?a.stop===n.id?0:-1:a.keep===n.id?-1:void 0;return $("div",{class:`${o}-node`,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-level":t.level,style:d.join(";"),role:s?"img":void 0,"aria-label":s?Vt(e,n):void 0,tabindex:l},n.shape==="decision"?$("svg",{class:`${o}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},$("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.shape==="table"?te(o,n):Pt(o,e,n))}function ee(t,e,n){const{P:a}=t,o=[];if(e.type==="data-flow"&&o.push(...e.lanes.map((r,d)=>$("div",{class:`${a}-lane`,style:`--_r:${d+1}`,"aria-hidden":"true"},$("span",{class:`${a}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const d=r.members.map(p=>e.byId.get(p));if(!d.length)continue;const h=Math.min(...d.map(p=>p.col)),l=Math.max(...d.map(p=>p.col)),c=Math.min(...d.map(p=>p.row)),u=Math.max(...d.map(p=>p.row2));o.push($("div",{class:`${a}-gbox`,"data-group":r.id,style:`--_c:${h};--_c2:${l+1};--_r:${c};--_r2:${u+1}`,"aria-hidden":"true"},$("span",{class:`${a}-glabel`},r.label)))}if(e.type==="sequence")return o.push($("ul",{class:`${a}-cast`},e.nodes.map(r=>$("li",{class:`${a}-actor`},pt(t,e,r,n))))),o.push(ne(t,e)),o;let s=0;for(;s<e.nodes.length;){const r=e.nodes[s],d=r.group?e.groups.find(l=>l.id===r.group):void 0;if(!d){o.push(pt(t,e,r,n)),s++;continue}const h=[];for(;s<e.nodes.length&&e.nodes[s].group===d.id;)h.push(e.nodes[s++]);o.push($("div",{class:`${a}-group`,"data-group":d.id},$("span",{class:`${a}-glabel`,"aria-hidden":"true"},d.label),h.map(l=>pt(t,e,l,n))))}return o}function ne(t,e){const{P:n}=t,a=[];let o=null;for(const s of e.steps){if("band"in s){o=null,a.push($("p",{class:`${n}-band`},$("span",null,s.band)));continue}o||(o=$("ol",{class:`${n}-msgs`,start:s.n}),a.push(o));const r=e.byId.get(s.from),d=e.byId.get(s.to),h=r?.col??1,l=d?.col??1,c=h===l,u=c&&h===e.nodes.length,p=xt(e,s.kind);o.c.push($("li",{class:`${n}-msg`,"data-kind":s.kind,"data-from":s.from,"data-to":s.to,"data-self":c?u?"start":"end":void 0,style:`--_a:${Math.min(h,l)};--_b:${Math.max(h,l)+1}`},$("span",{class:`${n}-said`},$("span",{class:`${n}-num`},String(s.n)),$("span",{class:`${n}-mlabel`},s.label)),$("span",{class:`${n}-route`},r?.short??s.from," ",Qt(n,s.kind),$("span",{class:t.hidden}," to ")," ",d?.short??s.to,p?` · ${p}`:""),s.note?$("span",{class:`${n}-note`},s.note):null))}return $("div",{class:`${n}-steps`},a)}function se(t,e){const n=Math.min(6,e.heading+1),a=c=>$(`h${n}`,{class:`${t}-list-head`},c),o=c=>$("strong",null,c),s=c=>$("code",{class:`${t}-code`},c),r=c=>e.byId.get(c)?.name??c,d=c=>{const u=xt(e,c);return u?` (${u})`:""},h=c=>c.focal&&e.legend.focal?` ${at(e.legend.focal)}`:"";if(e.type==="architecture"){const c=M=>$("li",null,o(M.name),M.kind?`, ${M.kind}`:"",M.detail?[". ",M.mono?s(M.detail):M.detail,/[.!?]$/.test(M.detail)?"":"."]:/[.!?]$/.test(M.kind??M.name)?"":".",h(M)),u=[a("Parts")],p=e.nodes.filter(M=>!M.group);p.length&&u.push($("ul",{class:`${t}-list-items`},p.map(c)));for(const M of e.groups)u.push($("p",{class:`${t}-list-group`},M.label)),u.push($("ul",{class:`${t}-list-items`},M.members.map(f=>c(e.byId.get(f)))));return u.push(a("Connections")),u.push($("ol",{class:`${t}-list-items`},e.edges.map(M=>$("li",null,o(r(M.from))," to ",o(r(M.to)),M.label?[": ",s(M.label)]:"",`${d(M.kind)}.`)))),u}if(e.type==="flowchart"){const c=u=>(e.byId.get(u)?.i??0)+1;return[$("ol",{class:`${t}-list-items`},e.nodes.map(u=>{const p=e.edges.filter(y=>y.from===u.id),M=u.shape==="decision"?"Decision":u.shape==="terminal"?p.length?"Start":"End":"Step",f=!u.detail&&/[.!?]$/.test(u.name)?" ":". ";return $("li",null,o(u.name),u.detail?[", ",u.mono?s(u.detail):u.detail]:"",`${f}${M}.`,h(u),p.length?$("ul",{class:`${t}-list-exits`},p.map(y=>$("li",null,y.label?`If ${y.label}: go to ${c(y.to)}, `:`Then: go to ${c(y.to)}, `,o(r(y.to)),y.kind==="main"&&e.legend.main?` (${e.legend.main})`:""))):null)}))]}if(e.type==="data-flow")return[$("ol",{class:`${t}-list-items`},e.nodes.map(c=>{const u=e.edges.filter(p=>p.from===c.id);return $("li",null,`${c.laneLabel}: `,o(c.name),c.detail?[", ",c.mono?s(c.detail):c.detail]:"",".",h(c),u.length?[" Then ",...u.flatMap((p,M)=>[M?"; ":"",`to step ${e.byId.get(p.to).step}, `,o(r(p.to)),p.label?[": ",s(p.label)]:"",d(p.kind)]),"."]:"")}))];if(e.type==="sequence"){const c=[a("Participants"),$("ul",{class:`${t}-list-items`},e.nodes.map(p=>$("li",null,o(p.name),p.kind?`, ${p.kind}`:"",".",h(p))))];c.push(a("Messages"));let u=null;for(const p of e.steps){if("band"in p){u=null,c.push($("p",{class:`${t}-list-group`},p.band));continue}u||(u=$("ol",{class:`${t}-list-items`,start:p.n}),c.push(u)),u.c.push($("li",null,s(p.label),": ",o(r(p.from))," to ",o(r(p.to)),`${d(p.kind)}.`,p.note?` ${at(Gt(p.note))}`:""))}return c}const l=[];for(const c of e.nodes)l.push($("p",{class:`${t}-list-group`},s(c.name),h(c))),l.push($("ul",{class:`${t}-list-items`},[...(c.columns??[]).map(u=>$("li",null,s(u.name),u.key==="PK"?", primary key":u.key==="FK"?", foreign key":"",u.ref?[", references ",s(`${u.ref.table}.${u.ref.column}`)]:u.type?`, ${u.type}`:"")),...c.more?[$("li",null,`and ${c.more} more ${c.more===1?"column":"columns"}`)]:[]]));return l}function oe(t){return`Arrow keys move to the next or the previous ${t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step"}, in the author's order; Home and End go to the ends; Escape clears the trace.`}function ae(t){return[{keys:["←","→"],words:Zt(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}function Lt(t,e,n){const a=n.prefix,o=Xt(n.base),s=t.type==="sequence"||t.type==="schema"?null:kt(t),r={P:a,ids:o,level:n.level,plan:s,hidden:n.hiddenClass},d=e.layout==="drawn",h=rt(t,e),l=t.type==="sequence"||t.type==="schema"?d:!0,c=`h${t.heading}`,u=[`--_cols:${ht(t)}`];if(t.type==="architecture"&&t.groups.length){const p=t.groups.flatMap(f=>f.members.map(y=>t.byId.get(y))),M=(f,y)=>f?`var(--basalt-space-${y})`:"0px";u.push(`--_gpad:${M(p.some(f=>f.row===1),"8")} ${M(p.some(f=>f.col===t.cols),"4")} ${M(p.some(f=>f.row2===t.rows),"4")} ${M(p.some(f=>f.col===1),"4")}`)}return t.type==="schema"&&e.track&&u.push(`--_track:${e.track}px`),$("figure",{class:n.className?`${a} ${n.className}`:a,"aria-labelledby":o.title,"data-type":t.type,"data-cols":ht(t),"data-reach":t.type==="architecture"?vt(t):void 0,"data-gutter":s?.gutter?"":void 0,"data-layout":e.layout,"data-measured":e.layout?"":void 0,style:u.join(";")},$("div",{class:`${a}-head`},$(c,{id:o.title,class:`${a}-title`},t.title),n.hasSource?$("p",{class:`${a}-source`},{slot:"source"}):null),$("div",{class:`${a}-drawing`,role:l?"group":void 0,"aria-roledescription":l?"diagram":void 0,"aria-labelledby":l?o.title:void 0,"aria-describedby":l?`${o.summary} ${o.keys}`:void 0,"data-stops":h?"":void 0},ee(r,t,e),$("div",{class:`${a}-ink`,"aria-hidden":"true"}),$("span",{class:`${a}-ruler`,"aria-hidden":"true"})),Jt(a,t),$("p",{class:`${a}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),$("div",{class:`${a}-foot`},{slot:"toggle"}),$("div",{id:o.list,class:`${a}-list`,hidden:!e.open},se(a,t)),$("span",{id:o.keys,class:n.hiddenClass},oe(t)),$("figcaption",{id:o.summary,class:`${a}-summary`},{slot:"summary"}))}function re(t){const e=getComputedStyle(t),n=(o,s)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${o}`));return Number.isFinite(r)?r:s},a=new Map;return{space:o=>(a.has(o)||a.set(o,n(`space-${o}`,parseFloat(o.replace("-","."))*4)),a.get(o)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4)}}var ft=(t,e)=>t==="main"?e.line:e.hair,Q=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},P=(t,e,n=.01)=>t.l<e.r-n&&t.r>e.l+n&&t.t<e.b-n&&t.b>e.t+n,At=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function Y(t,e,n){const{l:a,t:o,r:s,b:r}=t.rect,d=(a+s)/2,h=(o+r)/2,l=(s-a)/2,c=(r-o)/2,u=e==="top"||e==="bottom";if(t.shape==="decision"){if(u){const f=n,y=c*Math.max(0,1-Math.abs(f-d)/l);return{x:f,y:e==="top"?h-y:h+y}}const p=n,M=l*Math.max(0,1-Math.abs(p-h)/c);return{x:e==="left"?d-M:d+M,y:p}}if(t.shape==="terminal"){const p=Math.min(l,c);if(u){const i=n,g=Math.min(Math.max(i,a+p),s-p),b=i-g,m=Math.abs(b)>=p?0:Math.sqrt(p*p-b*b);return{x:i,y:Math.abs(b)<1e-6?e==="top"?o:r:e==="top"?h-m:h+m}}const M=n,f=M-h,y=Math.abs(f)>=p?0:Math.sqrt(p*p-f*f);return{x:e==="left"?a+p-y:s-p+y,y:M}}return u?{x:n,y:e==="top"?o:r}:{x:e==="left"?a:s,y:n}}function ie(t,e,n){const{l:a,t:o,r:s,b:r}=e.rect,d=(a+s)/2,h=(o+r)/2,l=(s-a)/2,c=(r-o)/2;if(e.shape==="decision")return Math.abs(t.x-d)/l+Math.abs(t.y-h)/c<1-n/Math.min(l,c);if(e.shape==="terminal"){const u=Math.min(l,c),p=Math.min(Math.max(t.x,a+u),s-u);return Math.hypot(t.x-p,t.y-h)<u-n}return t.x>a+n&&t.x<s-n&&t.y>o+n&&t.y<r-n}function qt(t,e){if(!P(t,e.rect))return!1;if(e.shape!=="decision"&&e.shape!=="terminal")return!0;const{l:n,t:a,r:o,b:s}=e.rect,r=(n+o)/2,d=(a+s)/2,h=(o-n)/2,l=(s-a)/2;if(e.shape==="decision"){const u=Math.max(t.l,Math.min(r,t.r)),p=Math.max(t.t,Math.min(d,t.b));return Math.abs(u-r)/h+Math.abs(p-d)/l<1-1e-6}const c=Math.min(l,h);if(P(t,{l:n+c,r:o-c,t:a,b:s}))return!0;for(const u of[n+c,o-c]){const p=Math.max(t.l,Math.min(u,t.r)),M=Math.max(t.t,Math.min(d,t.b));if(Math.hypot(p-u,M-d)<c-.01)return!0}return!1}function le(t,e,n){const a=Math.hypot(e.x-t.x,e.y-t.y),o=Math.max(2,Math.ceil(a/2));for(let s=1;s<o;s++){const r=s/o;if(!(r*a<1.5||(1-r)*a<1.5)&&ie({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r},n,1))return!0}return!1}function ce(t,e){const n=t.querySelector(`.${e}-ruler`),a=new Map;return(o,s)=>{const r=`${s}|${o}`;return a.has(r)||(n.setAttribute("data-f",s),n.textContent=o,a.set(r,n.getBoundingClientRect().width),n.textContent=""),a.get(r)}}var gt=t=>t?t.split(/\s+/).filter(Boolean):[];function de(t,e,n){const a=e.space;let o=e.node,s=e.table;for(const h of t.nodes){if(h.shape==="table"){for(const p of h.columns??[]){const M=p.ref?`→ ${p.ref.table}`:p.type??"",f=a("6")+n(p.name,"mono")+(M?a("3")+n(M,"mono"):0)+2*a("3")+2*e.hair;s=Math.max(s,Math.ceil(f))}s=Math.max(s,Math.ceil(n(h.name,"table")+2*a("3")+2*e.hair));continue}const l=h.shape==="terminal"?2*a("5"):2*a("3");let c=0;for(const p of gt(h.name))c=Math.max(c,n(p,h.shape==="decision"?"name-500":"name"));if(t.type!=="data-flow")for(const p of gt(h.kind))c=Math.max(c,n(p,"mono"));for(const p of gt(h.detail))c=Math.max(c,n(p,h.mono?"mono":"sans"));const u=h.shape==="decision"?c/.62:c+l+2*e.hair;o=Math.max(o,Math.ceil(u))}const r=ht(t);let d;return t.type==="data-flow"?d=e.lane+r*(o+a("12")):t.type==="schema"?d=r*s+(r-1)*a("12"):t.type==="sequence"?d=r*e.node+(r-1)*a("5"):d=r*o+(r-1)*a("16")+vt(t)*a("4"),{track:o,table:s,least:Math.max(e.wide,d)}}function It(t,e){return{x:(n,a)=>a%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,a)=>a%2===1?Math.round(n+e-.5)+.5-e:Math.round(n+e)-e}}function yt(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ct(t,e,n){const a=t.map(s=>({...s}));for(let s=1;s<a.length;s++){const r=a[s-1],d=a[s];if(Math.abs(r.x-d.x)<.75){const h=n.x(r.x,e);r.x=h,d.x=h}else if(Math.abs(r.y-d.y)<.75){const h=n.y(r.y,e);r.y=h,d.y=h}}const o=[a[0]];for(let s=1;s<a.length;s++){const r=a[s],d=o[o.length-1];if(!(Math.abs(r.x-d.x)<.01&&Math.abs(r.y-d.y)<.01)){if(o.length>=2){const h=o[o.length-2];if(Math.abs(h.x-d.x)<.01&&Math.abs(d.x-r.x)<.01||Math.abs(h.y-d.y)<.01&&Math.abs(d.y-r.y)<.01){o[o.length-1]=r;continue}}o.push(r)}}return o}var it=t=>t.slice(1).map((e,n)=>[t[n],e]);function ut(t,e){const n=[];for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){const r=t[o],d=t[s];for(const[h,l]of it(r.pts))for(const[c,u]of it(d.pts)){const p=Math.abs(h.y-l.y)<.01,M=Math.abs(c.y-u.y)<.01;if(p===M)continue;const[f,y,i,g]=p?[h,l,c,u]:[c,u,h,l],b=i.x,m=f.y;if(b>Math.min(f.x,y.x)+.75&&b<Math.max(f.x,y.x)-.75&&m>Math.min(i.y,g.y)+.75&&m<Math.max(i.y,g.y)-.75){const x=p?o:s,B=p?s:o;let v=x,_=B;if(e){const I=e(t[x]);e(t[B])&&!I&&(v=B,_=x)}n.push({top:v,under:_,at:{x:b,y:m},underVertical:_===B})}}}return n}function fe(t){const e=getComputedStyle(t),n=o=>o.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),a=(o,s,r)=>{const d=[];let h=s;for(const l of o)d.push([h,h+l]),h+=l+r;return d};return{cols:a(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:a(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var D=t=>t==="left"||t==="right",Bt={top:"bottom",bottom:"top",left:"right",right:"left"};function ue(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function he(t,e,n){const a=[];t.edges.forEach((s,r)=>{const d=t.byId.get(s.from),h=t.byId.get(s.to),[l,c]=e[r],u=d.row===h.row&&D(l)&&D(c)&&l===Bt[c]||d.col===h.col&&!D(l)&&!D(c)&&l===Bt[c];a.push({edge:r,end:"from",node:d,side:l,far:h,straight:u,f:.5},{edge:r,end:"to",node:h,side:c,far:d,straight:u,f:.5})});const o=new Map;for(const s of a){const r=`${s.node.id}.${s.side}`;o.has(r)||o.set(r,[]),o.get(r).push(s)}for(const[s,r]of o){if(r[0].node.shape==="decision")continue;const d=c=>D(c.side)?c.far.row-c.node.row:c.far.col-c.node.col,h=r.filter(c=>c.straight),l=r.filter(c=>!c.straight);l.sort((c,u)=>d(c)-d(u)||(D(c.side)?c.far.col-u.far.col:c.far.row-u.far.row)*(d(c)<0?1:-1)),r.length>3&&n(`${s.replace("."," has ")} has ${r.length} lines on one side; more than three is an error: use another side`),h.length?l.forEach(c=>{c.f=d(c)<0?.25:.75}):l.length===2?(l[0].f=.25,l[1].f=.75):l.length===3?(l[0].f=.25,l[1].f=.5,l[2].f=.75):l.length>3&&l.forEach((c,u)=>{c.f=(u+1)/(l.length+1)})}return a}function _t(t,e,n){const{l:a,t:o,r:s,b:r}=t.rect;return D(e)?Y(t,e,o+(r-o)*n):Y(t,e,a+(s-a)*n)}function Ot(t,e,n,a){const o=new Map;return e.querySelectorAll(`.${a}-node`).forEach(s=>{const r=t.byId.get(s.dataset.node);r&&o.set(r.id,{id:r.id,rect:Q(s,n),shape:r.shape,i:r.i})}),o}function mt(t,e){const n=e.head,a=e.head/2,{x:o,y:s}=t.tip;return t.dir==="down"?{l:o-a,r:o+a,t:s-n,b:s}:t.dir==="up"?{l:o-a,r:o+a,t:s,b:s+n}:t.dir==="right"?{l:o-n,r:o,t:s-a,b:s+a}:{l:o,r:o+n,t:s-a,b:s+a}}var jt=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function pe(t,e,n,a,o,s,r,d){const h=r.space,l=[],c=[],u=[],p=h("1"),M=e.filter(f=>t.edges[f.i]?.label).sort((f,y)=>+(t.edges[y.i].kind==="main")-+(t.edges[f.i].kind==="main")||f.i-y.i);for(const f of M){const y=t.edges[f.i].label,i=d(y,"label"),g=16,b=f.pts.length-2,m=[];it(f.pts).forEach(([v,_],I)=>{const j=Math.abs(v.y-_.y)<.01,F=j?v.x:v.y;let G=j?_.x:_.y;const A=Math.sign(G-F)||1;I===b&&(G-=A*r.head);let z=[[F,G]];for(const O of o)for(const R of j?[O.l,O.r]:[O.t,O.b]){const w=j?v.y:v.x;(j?w>O.t&&w<O.b:w>O.l&&w<O.r)&&(z=z.flatMap(([E,k])=>R>Math.min(E,k)+1&&R<Math.max(E,k)-1?[[E,R],[R,k]]:[[E,k]]))}const W=(O,R)=>{const w=(O+R)/2,C=j?{x:w,y:v.y}:{x:v.x,y:w};return!o.some(E=>C.x>E.l&&C.x<E.r&&C.y>E.t&&C.y<E.b)};for(const[O,R]of z)m.push({horiz:j,c:j?v.y:v.x,p:O,q:R,len:Math.abs(R-O),pri:z.length>1&&W(O,R)?1:0})}),m.sort((v,_)=>_.pri-v.pri||_.len-v.len);let x=null;const B=v=>{const _=At(v,p);return v.l<s.l||v.r>s.r||v.t<s.t||v.b>s.b||n.some(I=>qt(_,I))||l.some(I=>P(_,I))||a.heads.some(I=>P(_,I))||a.rects.some(I=>P(_,I))?!1:!e.some(I=>I.i!==f.i&&it(I.pts).some(([j,F])=>P(_,jt(j,F,I.width))))};for(const v of m){for(const _ of[1/2,1/3,2/3]){const I=v.p+(v.q-v.p)*_,j=[],F=h("2")+f.width/2;if(v.horiz?(v.len>=i+2*h("1")+h("3-5")&&j.push({box:{l:I-i/2-h("1"),r:I+i/2+h("1"),t:v.c-g/2,b:v.c+g/2},on:!0}),j.push({box:{l:I-i/2,r:I+i/2,t:v.c-F-g,b:v.c-F},on:!1}),j.push({box:{l:I-i/2,r:I+i/2,t:v.c+F,b:v.c+F+g},on:!1})):(v.len>=g+h("3")&&j.push({box:{l:v.c-i/2-h("1"),r:v.c+i/2+h("1"),t:I-g/2,b:I+g/2},on:!0}),j.push({box:{l:v.c+F,r:v.c+F+i,t:I-g/2,b:I+g/2},on:!1}),j.push({box:{l:v.c-F-i,r:v.c-F,t:I-g/2,b:I+g/2},on:!1})),x=j.find(G=>B(G.box))??null,x)break}if(x)break}if(!x){u.push(f.i);continue}l.push(x.box),c.push({i:f.i,text:y,box:x.box,on:x.on})}return{labels:c,unseated:u}}function Rt(t,e,n,a){const o=[],s=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const d=Q(r,e);s.push(d),o.push({l:d.l,r:d.r,t:d.t,b:d.t+1},{l:d.l,r:d.r,t:d.b-1,b:d.b},{l:d.l,r:d.l+1,t:d.t,b:d.b},{l:d.r-1,r:d.r,t:d.t,b:d.b});const h=r.querySelector(`:scope > .${n}-glabel`);h&&h.getClientRects().length&&o.push(Q(h,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,d)=>{if(!r.getClientRects().length)return;const h=Q(r,e);d>0&&o.push({l:h.l,r:h.r,t:h.t-a/2-.5,b:h.t-a/2+.5});const l=r.querySelector(`.${n}-lane-name`);l&&o.push(Q(l,e))}),{obstacles:{rects:o,heads:[]},groups:s}}function ge(t,e){const{m:n,tk:a,P:o,drawing:s,origin:r,warn:d}=t,h=a.space,l=Ot(n,s,r,o),c=[...l.values()],u=fe(s),p=r.left-Math.floor(r.left),M=r.top-Math.floor(r.top),f=It(p,M),y=s.clientWidth,i=s.clientHeight,g=w=>n.type==="data-flow"?w.col+1:w.col,b=parseFloat(getComputedStyle(s).rowGap)||0,m={w:y,h:i,nodes:c,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],ox:p,oy:M};if(n.type==="sequence")return ye(t,m,f);let x,B=[];n.type==="schema"?x=n.edges.map(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to);if(C.col===E.col){const k=C.col===n.cols?"left":"right";return[k,k]}return E.col>C.col?["right","left"]:["left","right"]}):(x=n.edges.map(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to),[k,L]=ue(C,E);return[w.fromSide??k,w.toSide??L]}),B=he(n,x,d));const v=(w,C)=>{const E=s.querySelector(`.${o}-node[data-node="${CSS.escape(w)}"] .${o}-row[data-row="${C}"]`);if(!E)return 0;const k=Q(E,r);return(k.t+k.b)/2},_=n.edges.map((w,C)=>{const[E,k]=x[C],L=l.get(w.from),H=l.get(w.to),N=ft(w.kind,a);if(w.fk){const T=f.y(v(w.from,w.fromRow),N),U=f.y(v(w.to,w.toRow),N);return{p1:{x:E==="right"?L.rect.r:L.rect.l,y:T},p2:{x:k==="right"?H.rect.r:H.rect.l,y:U}}}const V=B.find(T=>T.edge===C&&T.end==="from").f,Z=B.find(T=>T.edge===C&&T.end==="to").f;let S=_t(L,E,V),q=_t(H,k,Z);return D(E)?S={...S,y:f.y(S.y,N)}:S={...S,x:f.x(S.x,N)},D(k)?q={...q,y:f.y(q.y,N)}:q={...q,x:f.x(q.x,N)},D(E)&&D(k)&&Math.abs(S.y-q.y)<1.01&&(q={...q,y:S.y}),!D(E)&&!D(k)&&Math.abs(S.x-q.x)<1.01&&(q={...q,x:S.x}),S=D(E)?Y(L,E,S.y):Y(L,E,S.x),q=D(k)?Y(H,k,q.y):Y(H,k,q.x),{p1:S,p2:q}}),I=new Map;n.edges.forEach((w,C)=>{const[E,k]=x[C],{p1:L,p2:H}=_[C],N=n.byId.get(w.from),V=n.byId.get(w.to);let Z=null,S=null,q=!1;if(D(E)&&D(k)&&E!==k&&Math.abs(L.y-H.y)>.5){const K=g(V),et=k==="left",st=u.cols[(et?K-1:K)-1],X=u.cols[(et?K:K+1)-1];st&&X&&(Z=`c${et?K-1:K}`,S=[st[1],X[0]],q=!0)}else if(!D(E)&&!D(k)&&E!==k&&Math.abs(L.x-H.x)>.5){const et=k==="top"?V.row-1:V.row2,st=u.rows[et-1],X=u.rows[et];st&&X&&(Z=`r${et}`,S=[st[1],X[0]],q=!1)}if(!Z||!S)return;I.has(Z)||I.set(Z,{span:S,vertical:q,members:new Map});const T=`${w.to}.${k}.${Math.round(q?H.y:H.x)}`,U=I.get(Z);U.members.has(T)||U.members.set(T,[]),U.members.get(T).push(C)});const j=new Map,F=w=>{const[C,E]=x[w],{p1:k,p2:L}=_[w];if(D(C)&&D(E)){if(C===E){const N=C==="right"?Math.max(k.x,L.x)+h("4"):Math.min(k.x,L.x)-h("4");return[k,{x:N,y:k.y},{x:N,y:L.y},L]}if(Math.abs(k.y-L.y)<=.5)return[k,{x:L.x,y:k.y}];const H=j.get(w)??(k.x+L.x)/2;return[k,{x:H,y:k.y},{x:H,y:L.y},L]}if(!D(C)&&!D(E)){if(C===E){const N=C==="bottom"?Math.max(k.y,L.y)+h("4"):Math.min(k.y,L.y)-h("4");return[k,{x:k.x,y:N},{x:L.x,y:N},L]}if(Math.abs(k.x-L.x)<=.5)return[k,{x:k.x,y:L.y}];const H=j.get(w)??(k.y+L.y)/2;return[k,{x:k.x,y:H},{x:L.x,y:H},L]}return D(C)?[k,{x:L.x,y:k.y},L]:[k,{x:k.x,y:L.y},L]},G=()=>n.edges.map((w,C)=>{const E=ft(w.kind,a),k=Ct(F(C),E,f);return{i:C,from:w.from,to:w.to,kind:w.kind,pts:k,tip:k[k.length-1],dir:yt(k),dot:w.fk?k[0]:void 0,width:E}}),A=w=>ut(w).length*1e3+bt(w,c,n).length,z=(w,C)=>{const E=w.flatMap(k=>{const{p1:L,p2:H}=_[k];return C?[L.y,H.y]:[L.x,H.x]});return[Math.min(...E),Math.max(...E)]};for(const[,w]of I){const C=[...w.members.values()].map(k=>({members:k,run:z(k,w.vertical)})).sort((k,L)=>k.run[0]-L.run[0]),E=[];for(const k of C){const L=E[E.length-1];L&&L.some(H=>H.run[0]<k.run[1]+h("8")&&k.run[0]<H.run[1]+h("8"))?L.push(k):E.push([k])}for(const k of E){const L=k.map(S=>S.members),H=L.length,N=(w.span[1]-w.span[0])/(H+1);N<h("3")&&d(`a gutter holds ${H} lanes side by side, closer than space-3`);let V=L,Z=1/0;for(const S of Tt(L)){S.forEach((T,U)=>T.forEach(K=>j.set(K,w.span[0]+N*(U+1))));const q=A(G());q<Z&&(Z=q,V=S)}V.forEach((S,q)=>S.forEach(T=>j.set(T,w.span[0]+N*(q+1))))}}m.lines=G(),n.type==="schema"&&(m.lines=m.lines.filter(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to);return Math.abs(C.col-E.col)>1?(d(`${w.from} to ${w.to} is two columns apart, so its line is not drawn; its row still writes the target`),!1):!0})),m.crossings=ut(m.lines),m.through=bt(m.lines,c,n);const{obstacles:W,groups:O}=Rt(s,r,o,b);W.heads=m.lines.map(w=>mt(w,a));const R=pe(n,m.lines,c,W,O,{l:0,t:0,r:y,b:i},a,e);return m.labels=R.labels,m.unseated=R.unseated,m}function*Tt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e<t.length;e++){const n=t.slice(0,e).concat(t.slice(e+1));for(const a of Tt(n))yield[t[e],...a]}}function bt(t,e,n){const a=[];for(const o of t){const s=it(o.pts);e.some(r=>s.some(([d,h])=>le(d,h,r)))&&a.push(o.i)}return a}function ye(t,e,n){const{m:a,tk:o,P:s,drawing:r,origin:d}=t,h=o.space,l=new Map;r.querySelectorAll(`.${s}-node`).forEach(f=>l.set(f.dataset.node,Q(f,d)));const c=r.querySelector(`.${s}-steps`),u=c?Q(c,d).b:e.h,p=f=>{const y=l.get(f);return y?n.x((y.l+y.r)/2,o.hair):0};for(const f of a.nodes){const y=l.get(f.id);y&&e.lifelines.push({x:p(f.id),y1:y.b,y2:u})}const M=f=>l.get(f.id);return r.querySelectorAll(`.${s}-msg`).forEach(f=>{const y=f.dataset.from,i=f.dataset.to,g=f.dataset.kind??"plain",b=ft(g,o),m=Q(f,d),x=n.y((m.t+m.b)/2,b),B=Number(f.querySelector(`.${s}-num`)?.textContent??0),v=p(y),_=p(i);let I;if(y===i){const O=f.dataset.self==="start"?-h("6"):h("6"),R=n.y(x-h("2"),b),w=n.y(x+h("2"),b);I=[{x:v,y:R},{x:n.x(v+O,b),y:R},{x:n.x(v+O,b),y:w},{x:v,y:w}]}else I=[{x:v,y:x},{x:_,y:x}];e.lines.push({i:B,from:y,to:i,kind:g,pts:I,tip:I[I.length-1],dir:yt(I),width:b});const j=f.querySelector(`.${s}-said`),F=f.querySelector(`.${s}-note`),G=a.byId.get(y),A=a.byId.get(i);if(!G||!A)return;const z=y===i?(()=>{const O=a.nodes[G.i+(f.dataset.self==="start"?-1:1)],R=O?p(O.id):f.dataset.self==="start"?0:e.w;return Math.abs(R-v)-h("6")-h("2-5")-h("2")})():Math.abs(_-v)-2*h("2");Math.max(j?j.getBoundingClientRect().width:0,F?F.getBoundingClientRect().width:0)>z+.5&&e.unseated.push(B)}),e}function Ht(t,e,n){const{m:a,tk:o,P:s,drawing:r,origin:d,warn:h}=t,l=o.space,c=Ot(a,r,d,s),u=[...c.values()],p=d.left-Math.floor(d.left),M=d.top-Math.floor(d.top),f=It(p,M),y=r.clientWidth,i=r.clientHeight,g={w:y,h:i,nodes:u,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],ox:p,oy:M},b={};if(a.type==="sequence"||a.type==="schema")return{geo:g,grow:b};const m=new Map;r.querySelectorAll(`.${s}-node`).forEach(A=>{const z=A.parentElement,W=Q(z,d),O=getComputedStyle(z);m.set(A.dataset.node,W.r-(parseFloat(O.paddingRight)||0)-(parseFloat(O.borderRightWidth)||0))});const x=a.nodes,B=A=>c.get(x[A].id),v=[],_=A=>ft(a.edges[A].kind,o);a.edges.forEach((A,z)=>{const W=n.routes[z],O=c.get(A.from),R=c.get(A.to),w=_(z);let C=[];const E=A.label,k=E?e(E,"label"):0,L=16,H=l("4");if(W==="down"||W==="up"){const V=Math.max(O.rect.l,R.rect.l),Z=Math.min(O.rect.r,R.rect.r),S=f.x((V+Z)/2,w);if(C=W==="down"?[Y(O,"bottom",S),Y(R,"top",S)]:[Y(O,"top",S),Y(R,"bottom",S)],E){let q=Math.min(C[0].y,C[1].y),T=Math.max(C[0].y,C[1].y);W==="down"?T-=o.head:q+=o.head;const U=[...r.querySelectorAll(`.${s}-group`)].map(X=>Q(X,d));let K=[[q,T]];for(const X of U)for(const ot of[X.t,X.b])K=K.flatMap(([J,nt])=>ot>J+1&&ot<nt-1?[[J,ot],[ot,nt]]:[[J,nt]]);const et=(X,ot)=>U.some(J=>(X+ot)/2>J.t&&(X+ot)/2<J.b&&S>J.l&&S<J.r);if(K.length>1){const X=K.filter(([J,nt])=>!et(J,nt));[q,T]=(X.length?X:K).reduce((J,nt)=>nt[1]-nt[0]>J[1]-J[0]?nt:J)}const st=(q+T)/2;v.push({k:z,box:{l:S-k/2-l("1"),r:S+k/2+l("1"),t:st-L/2,b:st+L/2},on:!0,card:W==="down"?A.to:A.from})}}else if(W==="trunk"||W==="rail"){const V=f.x(Math.max(O.rect.l,W==="rail"?R.rect.l:O.rect.l)+l(W==="trunk"?"8":"3"),w),Z=Y(O,"bottom",V);if(W==="rail"){if(C=[Z,Y(R,"top",V)],E){const S=R.rect.t-l("6");v.push({k:z,box:{l:V+l("2-5"),r:V+l("2-5")+k,t:S-L/2,b:S+L/2},on:!1,card:A.to})}}else{const S=f.x(R.rect.l+l("6"),w),q=f.y(R.rect.t-H,w);C=[Z,{x:V,y:q},{x:S,y:q},Y(R,"top",S)],E&&v.push({k:z,box:{l:S+l("2-5"),r:S+l("2-5")+k,t:q-L/2,b:q+L/2},on:!1,card:A.to})}}else{const V=Math.min(m.get(A.from)??y,m.get(A.to)??y),Z=f.x(n.gutter?V+(n.lanes[z]?2*l("3-5"):l("3-5")):V-l("2-5"),w),S=f.y(O.rect.t+(O.rect.b-O.rect.t)*n.exits[z],w),q=Y(O,"right",S),T=f.x(R.rect.r-l("6"),w),U=W==="end-down",K=f.y(U?R.rect.t-H:R.rect.b+H,w);C=[q,{x:Z,y:q.y},{x:Z,y:K},{x:T,y:K},Y(R,U?"top":"bottom",T)],E&&v.push({k:z,box:{l:T-l("2-5")-k,r:T-l("2-5"),t:K-L/2,b:K+L/2},on:!1,card:U?A.to:x[R.i+1]?.id??A.to})}const N=Ct(C,w,f);g.lines.push({i:z,from:A.from,to:A.to,kind:A.kind,pts:N,tip:N[N.length-1],dir:yt(N),width:w})}),g.crossings=ut(g.lines),g.through=bt(g.lines,u,a);const{obstacles:I,groups:j}=Rt(r,d,s,0);I.heads=g.lines.map(A=>mt(A,o));const F=[],G={l:0,t:0,r:y,b:i};for(const A of v){const z=g.lines.find(w=>w.i===A.k),W=At(A.box,l("1")),O=mt(z,o);(A.box.l<G.l-.5||A.box.r>G.r+.5||u.some(w=>qt(W,w))||F.some(w=>P(W,w))||I.heads.some(w=>w!==O&&P(W,w))||I.rects.some(w=>P(W,w))||g.lines.some(w=>w.i!==A.k&&it(w.pts).some(([C,E])=>P(W,jt(C,E,w.width)))))&&(b[A.card]=(b[A.card]??0)+1,g.unseated.push(A.k)),F.push(A.box),g.labels.push({i:A.k,text:a.edges[A.k].label,box:A.box,on:A.on})}return n.third&&h("three end lines overlap in the stacked drawing; two lanes is the most (use the drawn layout or reorder)"),{geo:g,grow:b}}function me(t,e){const n=s=>String(Math.round(s*100)/100);let a=`M${n(t[0].x)} ${n(t[0].y)}`;for(let s=1;s<t.length-1;s++){const r=t[s-1],d=t[s],h=t[s+1],l=Math.hypot(d.x-r.x,d.y-r.y),c=Math.hypot(h.x-d.x,h.y-d.y),u=Math.min(e,l/2,c/2);if(u<.5){a+=`L${n(d.x)} ${n(d.y)}`;continue}const p={x:d.x+(r.x-d.x)/l*u,y:d.y+(r.y-d.y)/l*u},M={x:d.x+(h.x-d.x)/c*u,y:d.y+(h.y-d.y)/c*u};a+=`L${n(p.x)} ${n(p.y)}Q${n(d.x)} ${n(d.y)} ${n(M.x)} ${n(M.y)}`}const o=t[t.length-1];return`${a}L${n(o.x)} ${n(o.y)}`}var be={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function $e(t,e,n,a,o){const s=be[e.dir],r=e.kind==="dashed",d=n.head,h=n.head/2,l=r?1:d-1,c=e.pts.map(m=>({...m})),u=c[c.length-1];u.x-=s.x*l,u.y-=s.y*l;const p=e.tip.x-s.x*d,M=e.tip.y-s.y*d,f=-s.y*h,y=s.x*h,i=m=>Math.round(m*100)/100,g=r?`<path class="${t}-tip" data-kind="${e.kind}" data-open="" d="M${i(p+f)} ${i(M+y)}L${i(e.tip.x)} ${i(e.tip.y)}L${i(p-f)} ${i(M-y)}"/>`:`<path class="${t}-tip" data-kind="${e.kind}" d="M${i(e.tip.x)} ${i(e.tip.y)}L${i(p+f)} ${i(M+y)}L${i(p-f)} ${i(M-y)}Z"/>`,b=e.dot?`<circle class="${t}-dot" cx="${i(e.dot.x)}" cy="${i(e.dot.y)}" r="${n.dot/2}"/>`:"";return`<g class="${t}-edge" data-edge="${e.i}" data-from="${tt(e.from)}" data-to="${tt(e.to)}"><path class="${t}-line" data-kind="${e.kind}" d="${me(c,o)}"${a?` mask="url(#${a})"`:""}/>${g}${b}</g>`}function Ft(t,e,n,a){const o=new Map,s=new Map;for(const d of e.crossings)s.has(d.under)||s.set(d.under,[]),s.get(d.under).push(d);let r="";for(const[d,h]of s){const l=`${a}-cut-${d}`;o.set(d,l);const c=h.map(u=>{const p=e.lines[u.top],M=e.lines[u.under],f=p.width/2+n.cut,y=M.width/2+1;return u.underVertical?`<rect x="${u.at.x-y}" y="${u.at.y-f}" width="${2*y}" height="${2*f}" fill="black"/>`:`<rect x="${u.at.x-f}" y="${u.at.y-y}" width="${2*f}" height="${2*y}" fill="black"/>`}).join("");r+=`<mask id="${l}" maskUnits="userSpaceOnUse" x="0" y="0" width="${e.w}" height="${e.h}"><rect x="0" y="0" width="${e.w}" height="${e.h}" fill="white"/>${c}</mask>`}return{defs:r,ids:o}}function zt(t,e,n,a){const{defs:o,ids:s}=Ft(t,e,n,a),r=e.lifelines.map(c=>`<path class="${t}-life" d="M${c.x} ${c.y1}V${c.y2}"/>`).join(""),d=e.lines.map((c,u)=>$e(t,c,n,s.get(u)??null,c.from===c.to?n.radiusXs:n.radius)).join(""),h=`<svg class="${t}-svg" width="${e.w}" height="${e.h}" viewBox="0 0 ${e.w} ${e.h}" focusable="false">${o?`<defs>${o}</defs>`:""}${r}<g class="${t}-edges">${d}</g></svg>`,l=e.labels.map(c=>`<span class="${t}-label" data-edge="${c.i}"${c.on?' data-on=""':""} style="left:${Math.round(c.box.l*100)/100}px;top:${Math.round(c.box.t*100)/100}px;width:${Math.round((c.box.r-c.box.l)*100)/100}px">${tt(c.text)}</span>`).join("");return h+l}function we(t,e,n,a,o,s,r){const d=t.querySelector(`.${n}-drawing`);if(!d)return{dyn:o,geo:null,ink:"",tokens:null};const h=re(t),l=ce(d,n),c=de(e,h,l),u=t.clientWidth,p=(()=>{const x=document.activeElement;return x&&d.contains(x)&&x.dataset.node?x.dataset.node:void 0})(),M=x=>rt(e,x)?{...x,stop:x.stop&&e.byId.has(x.stop)?x.stop:e.nodes[0]?.id,keep:void 0}:{...x,stop:x.stop??e.nodes[0]?.id,keep:p&&x.layout!=="drawn"?p:void 0},f=x=>{if(e.type!=="flowchart")return x;s({...x,heights:void 0});const B={};return d.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(v=>{const _=v.querySelector(`.${n}-words`);if(!_)return;const I=v.getBoundingClientRect(),j=_.getBoundingClientRect(),F={w:j.width+2*h.space("2-5"),h:j.height+2*h.space("2")},G=I.width/2,A=1-F.w/2/G,z=A>.05?F.h/2/A:F.h*10;B[v.dataset.node]=Math.max(h.space("16"),Math.ceil(I.width/5),Math.ceil(2*z))}),{...x,heights:B}},y=()=>({m:e,tk:h,P:n,drawing:d,origin:d.getBoundingClientRect(),warn:r});if(u>=c.least){let x=M({...o,layout:"drawn",grow:void 0,track:void 0});x=f(x),s(x);const B=ge(y(),l);if(!B.through.length&&!B.unseated.length)return B.crossings.length&&r(`${B.crossings.length} crossing${B.crossings.length===1?"":"s"} in the drawn layout: ${B.crossings.map(v=>`${lt(e,B.lines[v.top])} over ${lt(e,B.lines[v.under])}`).join("; ")}`),{dyn:x,geo:B,ink:zt(n,B,h,a),tokens:h};B.through.length&&r(`the drawn layout does not fit at ${Math.round(u)}px: ${B.through.map(v=>lt(e,B.lines.find(_=>_.i===v))).join(", ")} would pass through a node`),B.unseated.length&&r(`the drawn layout does not fit at ${Math.round(u)}px: no clean seat for ${B.unseated.map(v=>e.type==="sequence"?`message ${v}`:`"${e.edges[v]?.label}"`).join(", ")}`)}let i=M({...o,layout:"stacked",heights:void 0,grow:{},track:e.type==="schema"?c.table:void 0});if(i=f(i),s(i),e.type==="sequence"||e.type==="schema")return{dyn:i,geo:null,ink:"",tokens:h};const g=kt(e);let b=Ht(y(),l,g);for(let x=0;x<6&&Object.keys(b.grow).length;x++){const B={...i.grow??{}};for(const[v,_]of Object.entries(b.grow))B[v]=(B[v]??0)+_;i={...i,grow:B},s(i),b=Ht(y(),l,g)}const m=b.geo;return m.crossings.length&&r(`${m.crossings.length} crossing${m.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${m.crossings.map(x=>`${lt(e,m.lines[x.top])} over ${lt(e,m.lines[x.under])}`).join("; ")}`),m.through.length&&r(`in the stacked drawing ${m.through.map(x=>lt(e,m.lines.find(B=>B.i===x))).join(", ")} passes through a node`),{dyn:i,geo:m,ink:zt(n,m,h,a),tokens:h}}function lt(t,e){const n=t.byId.get(e.from)?.name??e.from,a=t.byId.get(e.to)?.name??e.to;return`${n} to ${a}`}function xe(t,e,n,a,o,s){const r=new Set;if(s){r.add(s);for(const y of n?.lines??[])y.from===s&&r.add(y.to),y.to===s&&r.add(y.from)}if(t.toggleAttribute("data-tracing",!!s),t.querySelectorAll(`.${e}-node`).forEach(y=>y.toggleAttribute("data-near",r.has(y.dataset.node))),!n||!a)return;const d=y=>!!s&&(y.from===s||y.to===s),h=t.querySelector(`.${e}-edges`),l=new Map;t.querySelectorAll(`.${e}-edge`).forEach(y=>l.set(y.getAttribute("data-edge"),y));for(const y of n.lines){const i=l.get(String(y.i));i&&(i.toggleAttribute("data-lit",d(y)),i.toggleAttribute("data-dim",!!s&&!d(y)))}if(t.querySelectorAll(`.${e}-label`).forEach(y=>{const i=n.lines.find(g=>String(g.i)===y.dataset.edge);y.toggleAttribute("data-lit",!!(i&&d(i)))}),h){for(const y of n.lines)if(d(y)){const i=l.get(String(y.i));i&&h.appendChild(i)}}const c=ut(n.lines,d),{defs:u,ids:p}=Ft(e,{...n,crossings:c},a,o),M=t.querySelector(`.${e}-svg`);if(!M)return;let f=M.querySelector("defs");!f&&u&&(f=document.createElementNS("http://www.w3.org/2000/svg","defs"),M.insertBefore(f,M.firstChild)),f&&(f.innerHTML=u),n.lines.forEach((y,i)=>{const g=l.get(String(y.i))?.querySelector(`.${e}-line`);if(!g)return;const b=p.get(i);b?g.setAttribute("mask",`url(#${b})`):g.removeAttribute("mask")})}function Me(t,e,n){const a=t.byId.get(e)?.i??0,o=t.nodes.length;let s;if(n==="ArrowRight"||n==="ArrowDown")s=a+1;else if(n==="ArrowLeft"||n==="ArrowUp")s=a-1;else if(n==="Home")s=0;else if(n==="End")s=o-1;else return null;return t.nodes[Math.max(0,Math.min(o-1,s))].id}var ve=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],ke=["--_track","--_h","--_gap"];function Wt(t,e){if(typeof e=="string"||"slot"in e)return;for(const o of ve)(!(o in e.a)||e.a[o]===void 0||e.a[o]===null||e.a[o]===!1)&&t.removeAttribute(o);for(const[o,s]of Object.entries(e.a)){if(o==="class")continue;if(o==="style"){const d=t.style,h=new Map(String(s??"").split(";").map(l=>{const c=l.indexOf(":");return[l.slice(0,c).trim(),l.slice(c+1).trim()]}).filter(([l])=>l));for(const[l,c]of h)d.getPropertyValue(l).trim()!==c&&d.setProperty(l,c);for(const l of ke)h.has(l)||d.removeProperty(l);continue}if(s==null||s===!1){t.removeAttribute(o);continue}const r=s===!0?"":String(s);t.getAttribute(o)!==r&&t.setAttribute(o,r)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class))return;const n=e.c.filter(o=>typeof o!="string"&&!("slot"in o)),a=[...t.children];e.c.some(o=>typeof o!="string"&&"slot"in o)||n.forEach((o,s)=>{const r=a[s];r&&r.tagName.toLowerCase()===o.t&&Wt(r,o)})}(function(t){"use strict";var e=t._,n="diagram",a=0;function o(l,c){return{prefix:n,base:l,hasSource:c.source!==void 0&&c.source!==null&&c.source!=="",hiddenClass:"visually-hidden"}}function s(l,c,u,p){var M=function(f){return'<kbd class="kbd">'+tt(f)+"</kbd>"};return{source:tt(String(c.source||"")),summary:tt(String(c.summary||"")),hint:ae(l).map(function(f){return"<span>"+f.keys.map(M).join(" ")+" "+tt(f.words)+"</span>"}).join(""),toggle:'<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="'+(p?"true":"false")+'" aria-controls="'+u+'-list"><span>'+(p?"Hide the list":"View as list")+"</span></button>"}}function r(l,c){var u=$t(l),p=Lt(u,{},o(c,l)),M=Mt(p,s(u,l,c,!1)),f=M.indexOf(">");return{open:M.slice(0,f+1),inner:M.slice(f+1,M.length-9),warnings:u.warnings}}function d(l,c){l.__diagram&&l.__diagram.stop();var u=(l.getAttribute("aria-labelledby")||"").replace(/-title$/,""),p=$t(c);if(!l.querySelector(":scope > .diagram-drawing")){for(;document.getElementById("dg"+ ++a+"-title"););u="dg"+a;var M=r(c,u),f=document.createElement("div");f.innerHTML=M.open+"</figure>";for(var y=f.firstChild,i=0;i<y.attributes.length;i++){var g=y.attributes[i];g.name==="class"?l.classList.add.apply(l.classList,g.value.split(" ")):g.name==="style"?l.style.cssText=g.value+";"+l.style.cssText:l.setAttribute(g.name,g.value)}l.querySelectorAll(":scope > :not(script[data-diagram])").forEach(function(S){S.remove()}),l.insertAdjacentHTML("beforeend",M.inner)}p.warnings.forEach(function(S){console.warn("Basalt diagram: "+S)});var b=o(u,c),m={},x=null,B=null,v=null,_={},I=function(S){_[S]||(_[S]=1,console.warn("Basalt diagram: "+S))},j=function(S){Wt(l,Lt(p,S,b))},F=l.querySelector(".diagram-ink"),G=l.querySelector(".diagram-toggle");function A(){xe(l,n,x&&x.geo,x&&x.tokens,u,B||v)}function z(){x=we(l,p,n,u,m,j,I),m=x.dyn,j(m),F&&(F.innerHTML=x.ink),A()}function W(S){m=S,j(m)}var O=function(S){var q=S&&S.closest?S.closest(".diagram-node"):null;return q&&l.contains(q)?q:null};function R(S){var q=O(S.target);if(!(!q||S.defaultPrevented)){if(S.key==="Escape"){(B||v)&&(S.preventDefault(),B=v=null,A());return}if(rt(p,m)){var T=Me(p,q.getAttribute("data-node"),S.key);if(T){S.preventDefault(),W(Object.assign({},m,{stop:T}));var U=l.querySelector('.diagram-node[data-node="'+CSS.escape(T)+'"]');U&&U.focus()}}}}function w(S){var q=O(S.target);if(q){var T=q.getAttribute("data-node");B=q.matches(":focus-visible")?T:null,rt(p,m)&&m.stop!==T&&W(Object.assign({},m,{stop:T})),A()}}function C(S){var q=O(S.target);q&&(O(S.relatedTarget)||(B=null),m.keep===q.getAttribute("data-node")&&W(Object.assign({},m,{keep:void 0})),A())}function E(S){if(!(S.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var q=O(S.target),T=q&&rt(p,m)?q.getAttribute("data-node"):null;T!==v&&(v=T,A())}}function k(){v&&(v=null,A())}function L(){var S=!m.open;W(Object.assign({},m,{open:S})),G.setAttribute("aria-expanded",String(S)),G.firstElementChild.textContent=S?"Hide the list":"View as list"}l.addEventListener("keydown",R),l.addEventListener("focusin",w),l.addEventListener("focusout",C),l.addEventListener("pointerover",E),l.addEventListener("pointerleave",k),G&&G.addEventListener("click",L),z();var H=l.clientWidth,N=0,V=!0,Z=new ResizeObserver(function(){Math.abs(l.clientWidth-H)<.5||(H=l.clientWidth,cancelAnimationFrame(N),N=requestAnimationFrame(z))});Z.observe(l),document.fonts&&document.fonts.ready.then(function(){V&&z()}),l.__diagram={stop:function(){V=!1,Z.disconnect(),cancelAnimationFrame(N),l.removeEventListener("keydown",R),l.removeEventListener("focusin",w),l.removeEventListener("focusout",C),l.removeEventListener("pointerover",E),l.removeEventListener("pointerleave",k),G&&G.removeEventListener("click",L)},layout:z}}function h(){document.querySelectorAll("figure.diagram").forEach(function(l){if(!l.__diagram){var c=l.querySelector(":scope > script[data-diagram]");if(c)try{d(l,JSON.parse(c.textContent))}catch(u){console.error("Basalt diagram: this figure could not be drawn",u)}}})}e.diagramMarkup=r,t.diagram=function(l,c){d(l,c)},e.step(62,"wireDiagrams",h)})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/manifest.json b/.agent/skills/basalt-html/parts/manifest.json index 6f69410e..03ddece1 100644 --- a/.agent/skills/basalt-html/parts/manifest.json +++ b/.agent/skills/basalt-html/parts/manifest.json @@ -1,7 +1,7 @@ { "$comment": "Which parts of the skill's CSS and JS a page gets. The core is always in. A module is in when the page's body has one of its classes, attributes or tags, matches one of its text patterns, or is named in a <!-- basalt:use name --> comment, and when another module needs it (requires). Modules are added in the order listed here, which is the order of the source files' cascade. classes: every class the module's CSS styles (the test checks them against the CSS and against SKILL.md). budget: the most bytes its minified CSS and JS may reach together. budgets: skillMd (SKILL.md, the context an agent pays: never above what it was), core (the CSS and JS of every page). icons: Phosphor names the module's script draws itself. Raised in the first parity PR (the owner's \"bring up the parity\"): forms (the number-input, search-clear and file-input chrome), disclosure (the native details marker), status (the accent reader and the forced-colours badge border), spinner (a fixed 16px ring), and the new number, range and accent modules. skillMd rose 10555 to 10900 for the new rules (number field, native chrome, the braille rule, the accent). Raised in the second parity PR (popup rows, levels and the segment's pill): segment 1400 to 3700 (the shared sliding pill: its script, 1.5 KB, and its CSS with the pill's two fallbacks), rows 3600 to 4300 (#27's plate-in-a-row geometry, the plate per level, the glide's shared plate and the forced-colours lit row, net of the removed bar), palette 9400 to 11300 (the glide's script, 2.4 KB: it follows the lit row, travels on a pointer, snaps on a key, and fades in place on leaving). The art module (DECISIONS 101 and 104) is the token groups only some pages name, taken out of the core so the core stays under its cap: the chart roles and lengths, the art colours, the aspect ratios and the stage headroom, in both themes (2087 bytes at 2100; it grows only when a token of those groups is added). A page gets it when its body names one of them, a var() in its own style included. The every-module page has no cap of its own (owner, DECISIONS 79): each part is capped, and a page carries only the parts it uses. usage: the most bytes of a module's usage text (src/usage/NAME.md; core.usage for core.md), which compose.mjs --usage prints on demand. It is context an agent pays only for the modules its page uses, so it is capped per part as SKILL.md and the CSS and script are (DECISIONS 79 and 109). Each is set a little above what its text was when the usage moved out of SKILL.md (DECISIONS 109); raising one needs a reason in the PR, and a rise of 40 to 50% is the owner's. textWords: each text pattern said in words, which compose.mjs --usage prints instead of the regular expression (one for each entry of text, in order). builds: modules a module requires whose markup its script writes, so --usage prints a line saying so instead of their usage text (the palette builds its own rows and key chips). The council's clarity check of the usage texts (all three: not yet clear) raised eight caps because the texts gained what an agent had to guess: callout 200 to 700 (the icon and one wrapper div around the title and body as markup, the four status icons, the role React's Callout renders), palette 1100 to 1300 (an item shown whole, keys as an array, keywords), stats 450 to 800 (a snippet of the figures and of the dl), tabs 500 to 650 (the unselected panels), code 250 to 450 (the markup and what each token class means), segment 150 to 300 (a click does not switch it), progress 150 to 350 (the empty span that paints the fill), theme 250 to 400 (leave the button empty), and accent 250 to 300. Topbar went down, 700 to 500, as its build detail was cut. Raised in the usage PR (the council's clarity check): palette 11300 to 11450 (the module grew 11283 to 11448, +165, about 1.5%), for the guard that makes a string `keys` warn and draw no chip instead of throwing in `keys.filter`, which the palette's usage already promised. Round 2 of the clarity check: tabs 650 to 750 (the panel's top space shown in the snippet, and that the script selects a tab on click). Raised in the site-icons and status PR (skill-parity part A, DECISIONS 106 and 107): status 1650 to 1900 (the neutral, pending and running marks, the badge's real border, and the forced-colours disc, net of the red danger word it drops) and its usage 400 to 1000 (every status in words, the word alone, running, forced colours); rows 4300 to 4450 (the profile list's seat rule and the status parts on a lit row) and its usage 300 to 600 (the profile list, with the one mistake: never an empty element for the seat). New: the links module (2671 bytes: the social row, the new-tab arrow's CSS and the script that draws it; budget 2750) and its usage (1746 bytes; cap 1850), which carries the social link, the glyph set, icon only and the new tab. Dropping Regular halves icons.json. Added in the overlay PR (skill-parity-4, batch 7 step 2, DECISIONS 108): the shared plate leaves palette.js for a glide module (the palette, a menu and the notification centre all call it), so the palette's cap went down, 11450 to 9250, and rows 4450 to 3850 (the plate's CSS moved to glide); and the overlay layer comes in as seven modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: popover (the native popup shell), menu, dialog (the dialog and alert dialog), sheet (on every side, the top one the site header's narrow menu), tooltip, toast and notifications (the centre). skillMd is unchanged in its cap (the eight new index lines fit within it); the core is unchanged in bytes. Added in the figures and charts PR (skill-parity-5, batch 7 step 3, DECISIONS 108): four modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: meter (React's Meter, CSS only, 2581 bytes), dlist (the description list, CSS only, 1265), terminal (the code block's transcript: its CSS, 3242, and the script that draws the gutter, the copy button and the replay, 4824) and chart (React's TimeChart and ChartGroup: 7313 of CSS and 23262 of script, which port chart.tsx's scale, layout, lane, labels, sentences, keyboard and table; it needs the art tokens, the table and the kbd chips, and a page without a chart carries none of it). Stats grew for the source line (budget 700 to 850, 798 bytes; its usage 800 to 950, 675 to 899 bytes, +33%, under the owner's 40 to 50%). skillMd is unchanged in its cap (four index lines fit within it); the core is unchanged in bytes. Added in the forms and selection PR (skill-parity-6, batch 7 step 4, DECISIONS 108): six modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: select (React's Select: the native select's closed trigger in every browser and, where `appearance: base-select` is shipped, the styled list with its two-line rows; a small script that says which input lit a row, 7740 bytes before it, choice (Checkbox, Radio, RadioGroup and Switch as styled native inputs; CSS only, with the first-frame rule), choice-card (ChoiceCard; CSS only), toggle (the pressed toggle's plate and check seat on .btn; CSS only), selection (a table's checkbox column: its fixed width and the script that sets aria-selected, the mixed header box and the count) and loops (the page-level hold on every loop with its switch: the held look and the script that stores it). The select's styles left forms, whose budget fell 3650 to 3250. skillMd rose 8621 to the size of its six new index lines, within its cap; the core is unchanged in bytes; compose adds the stored-hold line to the head of a page that has the loops module. Revised in the same PR (the lead's review of the build): the select gains select.js (one row is lit at a time, by whichever of the pointer and the keys moved last), and choice, toggle, selection and loops carry the first-frame rule, so a state a script sets on load (a mixed header box, the stored hold) paints at once with no crossfade. Added in the navigation and layout PR (skill-parity-7, batch 7 step 5, DECISIONS 108): five modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: glyph (Basalt's core glyphs drawn by name, at rest and selected, from a table the build works out from the drawn set; a page carries only the glyphs it names, and the drawing of a core glyph from data-glyph left the sheet module, which draws none now), nav (React's Nav: the sidebar's, the narrow menu's and More's rows, with the shared hugging pill), topbar-nav (the site header's links, one action and narrow menu, built by script from the bar's markup), app-shell (the shell, its sidebar and rail, and the app header) and tab-bar (the phone tab bar). The topbar module became the site header's bar (React's SiteHeader, DECISIONS 108: 56px with its line inside, the 44 by 44 brand target, the narrow-screen buttons, the derived sticky offset), budget 1600 to 3200 because its rules gained the app header's shared smoke, and its usage 500 to 750 (+50%) for the lockup's markup (the links, action and menu are topbar-nav's usage). Glide 3700 to 3950: the navigation's pill is a shape inside the row that the plate follows (about 200 bytes). The core's usage 2000 to 2100 (+5%): h2 is the Section step, the prose column's measure, and a link already 44px tall needs no margin. skillMd rose 9317 to 9863 for five index lines, under its cap; the core CSS grew 38 bytes (the layout tokens replace raw lengths, the gutter is one derived property, h2, .prose and .lead follow foundations) and the core script is unchanged. A module's media query writes %bp-md%, %bp-lg% or %bp-container% and the build substitutes the breakpoint tokens. Added in the tables and filters PR (skill-parity-8, batch 7 step 6, DECISIONS 108): the existing table module gains React's table additions (DECISIONS 95: the row header, \"Not observed\", the row density and the scroll hint with its small script), budget 1400 to 3000 (it was 1134 bytes of CSS; it is 2168 of CSS and 693 of script) and its usage 700 to 950 (+36%); and two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: still-table (React's Table with `columns`: the fixed layout from a colgroup, the whole header cell as the sort button with its reserved seat, aria-sort, the pinned columns and their divider, the empty row; 4767 of CSS and 3264 of script, budget 8200) and filter (React's MultiSelect and FilterResult: the chips, the trigger and checklist with the search band from ten values, Clear held in place, the one debounced result line, and the narrowing of a table by `data-column`; 8240 of CSS and 7978 of script, budget 16400; it needs the popover, glide, glyph and choice modules). The core is unchanged in bytes. skillMd rose 9863 to 10128 for two index lines and the CaretUpDown icon's name, within its cap. Added in the commands PR (skill-parity-9, batch 7 step 7, DECISIONS 103 and 108): one new module a page carries only when it uses it, command-list (React's CommandList: the command panel set in the page, list plus preview, the push; it extends the palette and needs rows, kbd and glide; 5229 of CSS and 8734 of script, budget 14000, usage 2150). Two-line rows come to the existing modules: rows 3850 to 5350 (the described row's grid and description line, the push's chevron: 1481 bytes of CSS, the same rules React's menu rows carry), palette 9250 to 9900 (its rows are one function the list shares, with the description and the two-tier ranking of title matches over keyword and description matches; +636) and its usage 1300 to 1350, rows' usage 600 to 800, and glide 3950 to 4000 (a host that is idle counts as having no lit row, +54). skillMd rose 10128 to 10259 for one index line, within its cap; the core's CSS grew 24 bytes (.split.aside takes size-list-width in place of its raw 20rem: the same 320px, so no pixel moves) and the core script is unchanged. Added in the art PR (skill-parity-10, batch 7 step 8, DECISIONS 104 and 108): two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: stage (React's Stage and PairedArt: full-bleed art under the site header, the pull-up by the sticky offset, the headroom, the paired art that follows the page's theme, and the forced-colours and print rules; CSS only, 1179 bytes) and framed-art (React's FramedArt: the figure, its rim and radius, the reserved box, the placeholder and the failed alt, the caption and credit; 2208 bytes of CSS and the 733-byte script that sets the frame's phase); both need the art tokens. The bar stays smoked over a stage: React clears it only over a stage that passed the headroom test helper, and a page has no test run (DECISIONS 108's note), so the skill builds no clear state. skillMd rose 10259 to 10500 for two index lines, within its cap; the core is unchanged in bytes. The callout gained the status rim in the same PR (DECISIONS 82, D8's status callouts): success, warning and danger draw their border in the status colour at 45% mixed in sRGB over the callout's own level, one solid colour on every side, and CanvasText in forced colours with the icon; the status colour is now one property the icon and the rim read. Its budget rose 900 to 1150 (the module is 1089 bytes, from 792: +297, about 37%); its usage is unchanged. Added in the overlays-and-the-rest PR (skill-parity-11, batch 7 step 9, DECISIONS 90 and 108): the last two parts of D8's part 5, each a module a page carries only when it uses it, with its own cap and usage cap set a little above its size: combobox (React's Combobox: the input with its caret button inside, the popup of the menu's rows with the glide's shared plate and two-line options, the filtering, the keys, the hidden value, the empty message and the check; 4342 of CSS and 6423 of script, budget 10900, usage 2150; it needs forms, popover and glide, and builds the last two) and sparkline (React's Sparkline: the label and latest value, the line, the axis, the empty sentence and the loading line that breathes; 1609 of CSS and 1874 of script, budget 3600, usage 950). The combobox copies the menu's row rules, as the select's list does, because React's Combobox renders MenuItem rows (a 40px hit area, a 36px plate) and the skill's .row is the palette's 44px: it carries no menu script. popover.js gains the combobox popup in the list of popups that keep focus where it is (+21 bytes, within its cap). skillMd rose 10500 to 10724 for two index lines, within its cap; the core is unchanged in bytes. Added in the motion-rules PR (DECISIONS 136 and 139): one module, ambient (a page's one ambient loop: CSS 828 bytes, script 433, budget 1300, usage 800), taken out of loops so the hold's own module grows only by the icon toggle's glyph swap (loops 2000 to 2200, +10%; its usage 1300 to 1650 for the icon form and the new settings-row sentence, +27%); and the chart's entrance (`entrance: true`: the marks' animations, their conditions and the redraw that restarts them at the elapsed time, 23262 to 25299 bytes of script; budget 30700 to 32800, +7%, usage 2500 to 2950, +18%). The core grew by the three tokens (27704 to 27862 bytes of CSS, under its cap). its stage usage gained the ambient art's line (1650 to 1750, +6%). skillMd rose 10724 to the size of the ambient index line, within its cap. Raised again in the motion-rules amendment (DECISIONS 143): chart 32800 to 33800 (script 25299 to 26375 bytes, +4%; +10% over the 30700 it began with) for the glide a new data set makes mid-entrance, print settling it, and `Basalt.pageChange()`; its usage 2950 to 3150 (+26% over the 2500 it began with). Raised in the second motion-rules amendment (DECISIONS 148): chart 33800 to 34400 (script 26375 to 26970 bytes: a line and its markers glide from their drawn geometry, and `beforeprint` settles the entrance; +12% over the 30700 it began with); topbar-nav 6900 to 7500 (+8.7%: the narrow menu's pause row, its CSS and 275 bytes of script, DECISIONS 148 item 2); loops usage 1650 to 1800 (+38% over the 1300 it began with, for the icon form's `title` and the menu row). Raised in the audit-design-b PR (DECISIONS 138 and 139): still-table 8200 to 13400 (+63%: the module was 7927 bytes and is 13311; the cut cell's plate, its focus stops and its dismissal, ported from React's cell-peek.ts, are 4273 bytes of script and 1111 of CSS; a still table that truncates needs them). The same PR: core usage 2100 to 2250 (+7%: the skip link, one bullet), forms usage 350 to 480 (+37%: the required mark), still-table usage 1950 to 2150 (+10%: the cut cell and the width rule), notifications usage 1050 to 1100 (+5%: the 44px entry on touch). The skip link's rim and radius took the core 30457 to 30609 bytes, under its cap (the rules that hang it under the bar are the topbar module's: 3200 to 3600, +12.5%); core 30720 to 31050 (+1.1%, DECISIONS 147: also the bar's links left out of the rule: the pseudo-element that makes a short standalone link a 44 by 44 target), skip-link script in the topbar module (3200 to 4150 over this PR, +30%: the rules that hang the link under the bar, 3600, and the script that reads the bar's real edge, 4150), sparkline 3600 to 4050 (+12.5%: React's ticker structure, so the value copies once on its line, and in forced colours the strips go and the number is plain text), forms budget 3250 to 3500 (+7.7%: the necessity word), notifications 9050 to 9250 (+2.2%: the 44px entry). Raised in the audit-design-b PR's E2 port (DECISIONS 138 and 139: the core set draws check, close, the chevrons, copy, plus, minus and search wherever a component draws them): the modules that drew a Phosphor icon for one of those now carry the core glyph's whole SVG, written in at build time (`%glyph-svg:name%`, the markup the glyph module's `_.glyph(name)` returns, so no module needs the glyph module and a page pays for nothing it does not use), and the Phosphor path of the same icon leaves the page. Each module's own bytes rose by that markup, and a page's total moved by what the Phosphor path it no longer carries saves: menu 8600 to 8900 (+303), combobox 10900 to 11200 (+303), copy 1900 to 2400 (+640), terminal 8100 to 8850 (+761), toast 13850 to 14150 (+325), number 2900 to 3400 (+557), filter 16400 to 17050 (+785), palette 9900 to 10450 (+536); the command list shares the palette's search drawing and fell 20 bytes. Set in integration-nov15, where the type-layout, motion-rules and audit-design-b branches meet: the combined tree measured SKILL.md 10959 bytes (each side's cap was 10900: both added index lines), core 31192 bytes (caps 30720 and 31050: the page-row and display rules, the three motion tokens and the skip link and 44px target rules all land in the core CSS) and core usage 2348 bytes (caps 2300 and 2250: type-layout's line and the skip-link bullet), so each is set to the measured bytes rounded up to the next 50: skillMd 10900 to 11000, core 31050 to 31200, core usage 2300 to 2350. Raised in the audit-design PR (decisions 138 and 139, parts A, D and C11): core 30720 to 31600 (+2.9%: the more-contrast block and its three aliases, and the field boundary token, every page carries as React does; the shadow-pill token is gone; the script gained `reserve`, 240 bytes), segment 3700 to 4100 and tabs 2300 to 2700 (the chosen label is 600 against 400, its width reserved by a span that carries its own copy, drawn unseen at 600; the pill's drop shadow is gone), and the segment's usage 300 to 380 (the weight and the glyph-only button). Raised again in the audit-design-a amendment (decision 145): core 31600 to 32300 (reserve() also reserves a label that is not plain text), segment 4100 to 5100 and tabs 2700 to 3500 (the second copy of such a label, and an icon drawn in both its forms), glyph 1100 to 1300 (a glyph in a segment or tab is drawn in both forms). Raised in the second audit-design-a amendment (decision 149): core 32300 to 32800 (reserve() builds the second copy of a label without any id, name, reference or hidden control, and does not copy a frame or media), segment 5100 to 5400 and its usage 380 to 500 (the 600 is on the label, the one-line rule and the usage text); the still-table cap is back at 8200, as the wash is on every cell again. Return 3 of the audit-design-a build (decision 149): tabs 3500 to 3700 (a tab the script has not reserved is 600 itself when selected, and one it declined is marked; the same two lines are in segment, which stays under 5400). Raised in the audit-fix-c2 PR (engineering, no pixel changes): toast 13850 to 14350 (the module was 13789 bytes and is 14288, +499, 3.6%) for F6, which focuses the Notifications region and Shift+Tab or Escape from it (or from the first toast) leaves it for where focus came from (and keeps a dialog's focus trap from wrapping it), as Base UI's viewport does in React, and for placing the region from focus (in the modal that holds it, or in the body), so a toast is never under a backdrop or in an inert modal whatever order the modals opened in (A3-09); the palette module grew 9864 to 9897 of its 9900 so that a palette opened over a modal sits inside it; topbar 3200 to 3250 (3123 to 3233, +110) for the scroll margin on what the bar holds, so a Tab into the bar from a scrolled page does not scroll the page (React's rule from PR #66); stage usage 1650 to 1750 (1580 to 1713, +8%) for the art's new place in the markup, after the content (A1-09), the stage's own CSS rising 1179 to 1208 within its 1250. skillMd rose 10724 to 10876 for the sentence that says a body may carry head tags, within its 10900. compose.mjs, the tool an agent runs, has no cap here (it is never in a page): it grew 21673 to 38153 bytes for the tokenizer that reads a body as HTML does and the head tags. Raised in the site-parts PR (DECISIONS 146, round 39), which folds each new part into the module it belongs with, so SKILL.md gains no index line (it has 41 bytes under its cap and a new module needs about 100): topbar 4150 to 17600 (+13450: the site footer and its disclosures, the lockup by pixel density, and a bar that arrives or leaves and returns, with its observer; a page that has a .topbar and no footer carries them too: the alternative, a module for each, needs its own index line and so SKILL.md bytes) and its usage 950 to 2900 (the footer's markup, the lockup's and the phase's); theme 650 to 4550 (the three-word theme choice: its CSS 2230 bytes and its script, 2277, with arrows, storage and the system listener) and its usage 400 to 1150 (the choice's markup written in full, so the right word is chosen before any script); segment 3700 to 3800 (a radio group's checked state besides a pressed button); stage 1250 to 2150 (its first script, 768 bytes, for fit and anchor) and its usage 1750 to 2000; framed-art 3000 to 3900 (drawn art in the frame: fit, anchor, no scaling strokes) and its usage 1250 to 1400. SKILL.md rose 10959 to 10992 (the topbar and theme index lines name .site-footer and .theme-choice). The head's theme line also writes data-theme-choice. Raised in site-parts return 2 (DECISIONS 146 B1 and B4): theme 4550 to 5350 (+800: the icon form of the theme choice, [data-theme-menu], whose button shows the theme in use, is named for the choice and opens the page's own .menu of three radio rows, in the theme script's 3073 bytes; the menu and popover modules are the page's, brought by its markup, so no module line was added and SKILL.md is 10993 of 11000) and its usage 1150 to 2200 (+91%: the menu's markup is written in full, and the deprecated toggle is said once); app-shell usage 2000 to 2100 and topbar-nav usage 1900 to 1950 (the theme control leaves the bar's text; the tools and the end cluster come in). The two example bodies still carry the deprecated data-theme-toggle. Return 2, F3 (DECISIONS 146 F): stage 2150 to 2250 (script 842 bytes: slice is the stage's default, as a frame's, and a drawing's own preserveAspectRatio stands unless the stage names data-fit or data-anchor) and its usage 2000 to 2150. framed-art 3900 to 4000 (a drawing's own preserveAspectRatio stands unless the figure names data-fit or data-anchor, +101 bytes). Return 3: theme 5350 to 5900 (script +569 bytes: who wrote data-theme, so System follows the system's change live and a theme the page set by hand, or a .dark or .light root, survives it). Raised in the controls port (DECISIONS 154): skillMd 11000 to 11200 for two index lines (link-tabs and option-chips, 214 bytes together), and core 31200 to 31600 for the nine tokens the port adds to every page's token CSS (the control rungs 44 to 64, two container widths, the confirm hold and the amount's opacity, 311 bytes). New modules (DECISIONS 154): link-tabs 2700 (its sizes, the 640 container step, the forced-colours underline, and the select that replaces the row under 720 with its 590-byte script, A15; it requires the select module), option-chips 5700 (the chip's states each written for a native radio inside a label, which needs :has on every one, plus the 1 KB script that keeps an aria-disabled chip reachable and never chosen). Return 3 (DECISIONS 154 conformance): link-tabs 2700 to 3100 and its usage 1650 to 1850 (the select's height for each row size, and a script that reads aria-current when it is needed and watches it move: 3,048 bytes), option-chips 5700 to 6700 (each state written twice, as a state attribute and as :has(), so no browser needs :has(): 4,975 CSS and 1,623 script). Return 4 (DECISIONS 158, Q2): link-tabs 3100 to 4300 and its usage 1850 to 2400 (the \"Go to\" label drawn at the select's start with its measured clearance, the select's accessible name kept as the words and the chosen page's, and the key hold that keeps a letter or an arrow on the closed select from navigating: 4,174 bytes, CSS 2,951 and script 1,223). Raised in the links-and-rows port (DECISIONS 152; the owner's approval is the lead's to confirm): the new link-rows module (5050 bytes of CSS, 50 of them for Castle's big-row arrow stepping colour over duration-fast, return 1, 1500 of usage: the directory's and the big rows' CSS, whose arrow is a core glyph drawn as a mask, and their tokens, size-row taken out of the core like type-layout's), disclosure 1550 to 3500 (Show all: the track, the clip and the settle, 1.5 KB of script and 1.8 KB of CSS), copy 2400 to 3500 (the form with words: the one cell and its script). SKILL.md rose 10959 to 10997 for one line, within its 11000 cap. Raised in the charts port PR (DECISIONS 153, D7a): chart 34400 to 34650 (script 26970 to 27270 bytes, +1.1% on the 34283 it was: `Basalt.trailingMean`, the trend maths React exports as `trailingMean`, 300 bytes), its usage 3150 to 3350 (+6%: one line for it). The tokens the batch adds (chart-lit-top, -mid and -base in both themes, size-chart-plot-sm, size-chart-row, size-meter-marker and radius-2xs) took the art module 2087 to 2546 bytes (budget 2100 to 2600, +24%: the chart tokens are its group) and the core 31192 to 31250 (cap 31200 to 31300, +0.3%: radius-2xs). Only D7a names a skill module in the charts ballot; the lit marks, the headline frame, the phase chart, the share bar, the coverage strip, the marks row and the range meter are React-only in this batch. Added in the overlays-and-search PR (DECISIONS 155, D10b and D13a): the sheet gains React's head, body and foot (the 44px close, the 20/28 title over a 13px count, the divider and the safe areas; its CSS 3.6 to 5.2 KB, budget 4050 to 5250, +30%) and its usage 1050 to 1450 (+38%: the anatomy and the step's focus, two bullets); and one new module a page carries only when it uses it, search (React's SearchDialog: the form, the field's -2 outline, the count line, the fixed-height results area and the rows with their picture slots and full-bleed hover wash; CSS only, 4368 bytes, budget 4400, usage 2050; it requires the dialog). The dialog's title draws no ring when script focuses it. skillMd rose 10959 to 11079 for the search line (the sheet's line is unchanged: its usage carries the anatomy), so its cap rose 11000 to 11100 (+0.9%). The core's CSS grew 31192 to 31421 bytes for the six new size tokens (the wide dialog, the search trigger and the logo and picture slots of a search result): its cap rose 31200 to 31450 (+0.8%). The two 44px values (the sheet's close and the search field) are local to their modules, with a lint exception that says they join the controls batch's size token (DECISIONS 154). Set in integration-nov15b, where audit-design-a, audit-fix-c2, site-parts, port-controls, port-links-rows, port-charts and port-overlays-search meet: the combined tree measured SKILL.md 11560 bytes (the caps were 11000, 11100 and 11200: each side added index lines), core 34086 bytes (caps 31300 to 33550: every side's rules land in the core CSS and script), topbar 17660 (17600 from site-parts, plus audit-fix-c2's skip-link and focus work), number 3453 (3400), palette 11379 (11000, audit-fix-c2's hosted scrim plus the core search glyph), dialog 5120 (5100), toast 15692 (15400) and stage usage 2248 (2150), each over every side's cap, so each is set to the measured bytes rounded up to the next 50: skillMd 11200 to 11600, core 33550 to 34100, topbar 17600 to 17700, number 3400 to 3500, palette 11000 to 11400, dialog 5100 to 5150, toast 15400 to 15700, stage usage 2150 to 2250. The segment cap is the base's 5400 plus port-controls' 100 (5500), unchanged by the merge. Raised in integration-nov15b, join 2 (a link tab takes the selected state, DECISIONS 138 A, 145, 149 and 154's D12 row): link-tabs 4300 to 5750 (+34%: the module was 4174 bytes and is 5736; the 600 against 400, the reserved width and the second copy of a composed label, an icon drawn in both its forms, the same rules a tab carries, 1,530 bytes of CSS and script) and its usage 2400 to 2550 (+6%: one bullet). The cap is the measured bytes rounded up to the next 50; a module that needs the tab's rules carries them as the segment and tabs modules do, so a page without link tabs pays nothing. Raised in the panels, art and parts port (DECISIONS 162): table 3000 to 3150 and its usage 950 to 1450 (the flat form and the two-line cell), stage 2250 to 2600 and its usage 2250 to 3100 (the closing block: its held art, forced colours and print; its section gap is type-layout's --basalt-section-gap, which a page with data-closing brings), the new app-tile 4300 (a 120-point polygon clip and the hairline's mask of the same outline), captioned 2000 and period 1400; skillMd 11600 to 11950 for one index line each for captioned, app-tile and period (358 bytes; the file is 11918). Raised in the logs, status and forms port (DECISIONS 162): core 34100 to 34200 (the new size-field-label-inline token, 80px, is written into every page's tokens: 25 bytes); dlist 1300 to 1900 and its usage 950 to 1060 (the stacked form, R9 and R10: a title over its text, 20px between entries, no divider; one usage line). Raised in audit-fix-c6 (the owner's cap, raised by the builder and for the owner to confirm): glyph 1300 to 1900, for redrawing a glyph when its ancestor's aria-current or data-current moves (the lists that hold glyphs are watched). Raised in the colour-ink-ladder build (DECISIONS 166): core 34200 to 34350 (the four lifted dark inks are four new primitives, each written into every page's tokens: the core measured 34307). Raised in the audit-2-design build (DECISIONS 167, Q7a): disclosure 3500 to 3800 (the core chevron drawn as a mask in place of two borders: the module measured 3755). Joined in the integration of c7 (#86) and c10 (#91): option-chips 6750 to 6850 (c7's reset resync and c10's data-ready together measure 6839). Raised in table-sort-3 (DECISIONS 257 and 261, the owner's pick: three sort states, the arrow after the label, explainers on column titles): still-table 13400 to 14650 (+9.3%: the module was 13343 bytes and is 14602; the end-aligned label's move by a transform, its right-to-left sign and the indicator that waits for it on a fine pointer, 912 bytes of CSS; the third state, the sort from the table's own order and a .explainer kept out of the button, 347 bytes of script) and its usage 2150 to 2250 (2197: the third state and the own order); the new explainer module 5850 (5842: a manual native popover opened from the sort button on hover, keyboard focus and a long press, placed above the header or beside it, 1752 bytes of CSS and 4090 of script; a page without explainers pays nothing) and its usage 900; skillMd 12250 to 12400 for the explainer's index line (113 bytes; the file is 12352). Each cap is the measured bytes rounded up to the next 50. Raised in table-sort-3's fix pass (Astra's review): explainer 5850 to 6900 (+18%: 5842 to 6864 bytes; the gap between the header and the card kept while a pointer crosses it, the close when its header leaves the view whatever has focus, the dismissal held until pointer and focus have both left, and its page-wide listeners and timers scoped to an open card and stopped when the table leaves the page, 1,022 bytes of script).", "budgets": { - "skillMd": 12400, + "skillMd": 12500, "core": 34550 }, "core": { @@ -697,6 +697,90 @@ "kbd" ] }, + "diagram": { + "classes": [ + "diagram", + "diagram-actor", + "diagram-arrow", + "diagram-band", + "diagram-cast", + "diagram-cname", + "diagram-code", + "diagram-ctype", + "diagram-detail", + "diagram-diamond", + "diagram-dot", + "diagram-drawing", + "diagram-edge", + "diagram-entry", + "diagram-fk-mark", + "diagram-foot", + "diagram-gbox", + "diagram-glabel", + "diagram-group", + "diagram-head", + "diagram-hint", + "diagram-ink", + "diagram-key", + "diagram-keyseat", + "diagram-kind", + "diagram-label", + "diagram-lane", + "diagram-lane-name", + "diagram-lane-word", + "diagram-legend", + "diagram-life", + "diagram-line", + "diagram-list", + "diagram-list-exits", + "diagram-list-group", + "diagram-list-head", + "diagram-list-items", + "diagram-mlabel", + "diagram-more", + "diagram-msg", + "diagram-msgs", + "diagram-name", + "diagram-node", + "diagram-note", + "diagram-num", + "diagram-route", + "diagram-row", + "diagram-rows", + "diagram-ruler", + "diagram-said", + "diagram-source", + "diagram-steps", + "diagram-summary", + "diagram-svg", + "diagram-swatch", + "diagram-swatch-shape", + "diagram-th", + "diagram-tip", + "diagram-title", + "diagram-tname", + "diagram-toggle", + "diagram-words" + ], + "attrs": [ + "data-diagram" + ], + "text": [ + "Basalt\\s*\\.\\s*diagram\\b" + ], + "textWords": [ + "a call to Basalt.diagram" + ], + "requires": [ + "art", + "kbd" + ], + "budget": 82300, + "usage": 2600, + "builds": [ + "kbd" + ] + }, "sparkline": { "classes": [ "sparkline", diff --git a/.agent/skills/basalt-html/parts/usage/diagram.md b/.agent/skills/basalt-html/parts/usage/diagram.md new file mode 100644 index 00000000..c0089b27 --- /dev/null +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -0,0 +1,23 @@ +# diagram + +``` +<figure class="diagram"> + <script type="application/json" data-diagram> + { "type": "architecture", "title": "How a request reaches the agent", "source": "docs/architecture.md", + "summary": "…", "legend": { "main": "Request path", "plain": "Call", "dashed": "Async or one-way", "focal": "The service" }, + "groups": [{ "id": "aws", "label": "AWS · your account" }], + "nodes": [{ "id": "svc", "kind": "ECS service", "name": "cimip service", "detail": "N tasks", "detailMono": true, + "focal": true, "group": "aws", "col": 3, "row": 2 }], + "edges": [{ "from": "alb", "to": "svc", "kind": "main", "label": "HTTP" }] } + </script> +</figure> +``` + +Boxes and the lines between them. `compose.mjs` writes the figure's words into the page (it reads before script); the script draws the lines, the labels, the keys and "View as list". `Basalt.diagram(figure, spec)` draws one from script. + +- **Five shapes of data** (`type`): `architecture` (`nodes` with `group`, `groups`, `edges`); `flowchart` (`nodes` with `shape`: `step`, `decision` or `terminal`, the first node the start; `edges`, a branch's `label` its condition); `data-flow` (`lanes`, `nodes` with `lane` and `col`, its step columns; `edges`); `sequence` (`participants` with `short`; `steps`: `{ from, to, label, note, kind }` or `{ band }`); `schema` (`tables`: `name`, `col`, `row` or `[first, last]`, `columns` with `key` `PK`/`FK` and `references: "table.column"`, `more`). +- **Order is one thing:** the array's order is the stacked order, the focus order, the list's, a data flow's step numbers and a sequence's message numbers. +- **Place, don't route:** `col` and `row` are whole tracks from 1. Sides, slots, jogs, lanes, the group's box and a foreign key's line are derived. Write `fromSide` or `toSide` (`top`, `right`, `bottom`, `left`) only to change the default. `branch: true` indents a node in the stacked drawing. +- **Lines:** `kind` is `main` (2px), `plain` (default) or `dashed` (a reply, a stream). One `label` each, at most 28 characters. `legend` gives each kind its words; `main`, `dashed` and a `focal` node must have words. One node at most is `focal`. +- **Required:** `title`, `summary` (what it shows, in a sentence). `source`, `heading` (2 to 6, default 3). +- Monochrome: nothing takes a colour. The drawn layout is used only where it fits; otherwise the figure is stacked, one column at most 480 wide. diff --git a/AGENTS.md b/AGENTS.md index 86de8310..a4b4f976 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,7 +123,7 @@ Basalt has one owner (Bailey) and a design panel of two independent design revie tabs that scrolls, a sortable header cell (a header band that is itself a button), a phone tab bar cell, and a cut cell of a still table (a focus stop, which shows its own ring after Esc has closed its plate). These structural vertical lines are allowed, each named and never a selection, sort, active or status mark: the 1px divider at a pinned table column's edge while the table is scrolled, the app sidebar's 1px edge, a meter's labelled target tick, the vertical - `Separator` between groups of controls, and the edges between a `NumberField`'s value and its steppers. The active row in a menu, select, combobox or command menu is a rounded plate + `Separator` between groups of controls, the edges between a `NumberField`'s value and its steppers, a diagram's connector and a sequence diagram's lifeline. The active row in a menu, select, combobox or command menu is a rounded plate (radius 8, one solid fill per level) plus a lift from secondary ink to primary, with no weight change: it is the row the keyboard is on, and it changes with every arrow key (WCAG 1.4.1). A selected table row is the wash band, and its checked box carries the state. A wash over an opaque fill (a pinned cell) is one colour from `color-mix`, never a gradient, an image or a @@ -184,6 +184,10 @@ Basalt has one owner (Bailey) and a design panel of two independent design revie rest. Don't redraw a glyph in code: change `packages/react/glyphs/source.mjs` and run `node packages/react/glyphs/generate.mjs`. On Apple platforms, SF Symbols for system concepts (info, warning, error, success). Status icons pair with words. +- **Diagrams:** monochrome; one focal node, inverted. Three lines named by look (main 2px, plain 1px, dashed), and the key says what + each means. The drawn layout is used only when it fits (640, the track minimums, a clean seat for every label); otherwise stacked, in + the author's order, at most 480 wide. Nothing is cut and nothing overlaps at any width. Ports, routes, groups and foreign keys are derived from one + record each. A flowchart's shapes have a 3:1 contour. Tracing changes ink, never weight. The words are in the HTML before script. - **Type:** Geist and Geist Mono at 400, 500 and 600 only, and a `Geist Fallback` face (local Arial, one face per weight) that reduces the shift when Geist arrives; it does not promise the same wrap at every width. - **Display type:** two roles a page writes, hero (96/96; 72/76 from 720 to 1023; 44/48 under 720) and display (72/76; 56/60; 36/40), made of the fixed diff --git a/Sources/BasaltTokens/Tokens.swift b/Sources/BasaltTokens/Tokens.swift index ede137d1..5677d3ee 100644 --- a/Sources/BasaltTokens/Tokens.swift +++ b/Sources/BasaltTokens/Tokens.swift @@ -335,6 +335,54 @@ extension Basalt { dark: RGBA(red: 0.521561, green: 0.521561, blue: 0.521561, alpha: 1) ) + /// A diagram's main line and its head, and a traced line (DECISIONS 269). 3:1 or better on levels 0 to 3. + public static let diagramEdgeMain = ThemedColor( + light: RGBA(red: 0.090173, green: 0.090173, blue: 0.090173, alpha: 1), + dark: RGBA(red: 0.955355, green: 0.955355, blue: 0.955355, alpha: 1) + ) + + /// A diagram's plain and dashed lines and their heads, a foreign key's line and dot, and an edge label's ink. + public static let diagramEdge = ThemedColor( + light: RGBA(red: 0.301921, green: 0.301921, blue: 0.301921, alpha: 1), + dark: RGBA(red: 0.730753, green: 0.730753, blue: 0.730753, alpha: 1) + ) + + /// Every other line of a diagram while one node is traced: quieter, still 3:1. The input boundary; it does not step under more contrast. + public static let diagramEdgeDim = ThemedColor( + light: RGBA(red: 0, green: 0, blue: 0, alpha: 0.45), + dark: RGBA(red: 1, green: 1, blue: 1, alpha: 0.38) + ) + + /// A diagram's group boundary, a sequence's lifeline and a flowchart shape's contour: 3:1, because each carries meaning. It does not step under more contrast. + public static let diagramStructure = ThemedColor( + light: RGBA(red: 0, green: 0, blue: 0, alpha: 0.45), + dark: RGBA(red: 1, green: 1, blue: 1, alpha: 0.38) + ) + + /// A diagram's focal node: its fill and its edge, inverted ink. At most one a diagram, and never the accent. + public static let diagramFocal = ThemedColor( + light: RGBA(red: 0.090173, green: 0.090173, blue: 0.090173, alpha: 1), + dark: RGBA(red: 0.929405, green: 0.929405, blue: 0.929405, alpha: 1) + ) + + /// Ink on the focal node; its kind and detail are this ink at opacity-amount. + public static let diagramFocalInk = ThemedColor( + light: RGBA(red: 1, green: 1, blue: 1, alpha: 1), + dark: RGBA(red: 0, green: 0, blue: 0, alpha: 1) + ) + + /// The focal table's header rule. Decorative: the other theme's divider, because the focal fill is the other theme's ground. + public static let diagramFocalRule = ThemedColor( + light: RGBA(red: 1, green: 1, blue: 1, alpha: 0.06), + dark: RGBA(red: 0, green: 0, blue: 0, alpha: 0.08) + ) + + /// Under more contrast, the focal table's header rule: the other theme's input boundary (DECISIONS 269, 1.18). An alias, no new colour. + public static let diagramFocalRuleContrast = ThemedColor( + light: RGBA(red: 1, green: 1, blue: 1, alpha: 0.38), + dark: RGBA(red: 0, green: 0, blue: 0, alpha: 0.45) + ) + /// The ground of drawn art and of a stage. It is the page colour, so a stage meets the page with no seam, and it is the stage's placeholder while the art loads. public static let artField = ThemedColor( light: RGBA(red: 0.980387, green: 0.980387, blue: 0.980387, alpha: 1), @@ -608,6 +656,18 @@ extension Basalt { public static let chartPlotSm: Double = 96 /// A marks row's height, a default the app can set: one kind of reading across a run of days (DECISIONS 153, consent row 10). public static let chartRow: Double = 56 + /// The least width of a node's track in a diagram's drawn layout; a track is also as wide as its widest unbreakable word, measured (DECISIONS 269). + public static let diagramNode: Double = 144 + /// The least width of a schema diagram's table; a table is also as wide as its widest row on one line, measured (DECISIONS 269). + public static let diagramTable: Double = 224 + /// A data flow diagram's lane-name column, at the start of the drawn layout (DECISIONS 269). + public static let diagramLane: Double = 120 + /// A sequence diagram's message row: the line at its middle, the number and label above it, the note below (DECISIONS 269). + public static let diagramStep: Double = 56 + /// A diagram's arrowhead, its length and its width, for every kind of line (DECISIONS 269). + public static let diagramHead: Double = 8 + /// A sequence diagram's lifeline dash, on and off (4 on 4 off), unlike a message's 6 on 4 off (DECISIONS 269). + public static let diagramGuideDash: Double = 4 /// A range meter's marker: a dot, ringed size-cut in the colour of the surface (DECISIONS 153, consent row 14). public static let meterMarker: Double = 12 /// The top of a stage the art keeps quiet for the bar: size-header (56) plus space-6 (24). The top safe area is added by the layout CSS. No pixel of it passes art-quiet-limit, and a stage declares that the product's headroom check passed. diff --git a/docs/foundations.md b/docs/foundations.md index 7805f323..60b3338f 100644 --- a/docs/foundations.md +++ b/docs/foundations.md @@ -636,7 +636,8 @@ rest (a secondary Button, a chip, a pressed toggle). Surfaces, primary and secon selected washes and the smoked header do not change: the washes stay at their values so danger text keeps 4.5:1 on them (doubling the selected wash put it at 3.5:1). The aliases are declared on every selector that sets a theme, after all of them, so the mode works in both themes and under a theme chosen with `data-theme`; each alias reads the theme of the element it is on. The contrast tests -prove every text pair at 4.5:1 and every boundary at 3:1 in the mode too. Status: decided by the council and approved by the owner +prove every text pair at 4.5:1 and every boundary at 3:1 in the mode too. A diagram's focal node draws its quiet ink at full strength, and its structure lines (`diagram-structure`) stay on the input boundary +as a chart's baseline does (DECISIONS 269). Status: decided by the council and approved by the owner (DECISIONS 138, 139 and 145); the implementation hasn't been reviewed. ### Accent classes @@ -850,7 +851,8 @@ type. `Heading size` takes `"6xl"`, `"7xl"`, `"hero"` and `"display"`; the roles blocks and callouts), 12 (cards, menus, dialogs), 16 (bottom sheets, and the narrow menu's bottom corners; full-height side sheets are square), full (whatever is a circle or a capsule by meaning: avatars, dots, the navigation hover pill, the switch, the radio, the slider's track and thumb, progress, meter, and the tab bar's circle). A nested radius is the outer - radius minus the padding: a segmented control on touch is a track of 8 holding 44px segments of 6. **An app tile is a superellipse of exponent 5 at every size and takes no radius** (DECISIONS 162, vote 6; the shape is drawn by the tile's clip, and its hairline follows it). Status: decided by the council and approved by the owner (DECISIONS 138 and 139; the tile, DECISIONS 162); the implementation hasn't been reviewed. + radius minus the padding: a segmented control on touch is a track of 8 holding 44px segments of 6. 8 also takes a diagram's node and + table card; 12 a diagram's group; full a flowchart's start or end (DECISIONS 269). **An app tile is a superellipse of exponent 5 at every size and takes no radius** (DECISIONS 162, vote 6; the shape is drawn by the tile's clip, and its hairline follows it). Status: decided by the council and approved by the owner (DECISIONS 138 and 139; the tile, DECISIONS 162); the implementation hasn't been reviewed. ## Elevation @@ -1290,8 +1292,11 @@ is in). Basalt allows a short list of vertical lines. Each is structure, and none is a selection, sort, active or status mark (the owner's ruling against the vertical bar is about marks): the 1px divider at a pinned table column's edge while the table is scrolled, the app sidebar's 1px edge, a meter's labelled target tick, the vertical `Separator` between groups of controls (1px -`border-divider`, as tall as the controls), and the edges between a `NumberField`'s value and its steppers (part of the -field's own boundary). Status: decided by the council and approved by the owner (DECISIONS 138 and 139); the implementation hasn't been reviewed. +`border-divider`, as tall as the controls), the edges between a `NumberField`'s value and its steppers (part of the +field's own boundary), a diagram's connector (a line that joins two nodes and ends in a head, with its stems, rails and buses) and a +sequence diagram's lifeline. A connector is never drawn without both its nodes and its head, and neither is ever a mark of state. +Status: decided by the council and approved by the owner (DECISIONS 138 and 139); the diagram's connector and lifeline decided by the +council (DECISIONS 269, a handoff); the implementation hasn't been reviewed. ## Charts @@ -1502,6 +1507,126 @@ changes); the implementation hasn't been reviewed. The votes that had no majorit Widths the prototype set by hand are derived from tokens, with no new one: a marks column is `min(44%, 28px)` (`space-6` + `space-1`), a pill `min(26%, space-3)`, a block `min(64%, 44px)` (`space-10` + `space-1`), a missing seat `min(72%, 52px)`, a seven-day strip at most 240px. +## Diagrams + +Boxes and the lines between them, in five types: architecture, flowchart, data flow, sequence and database schema (DECISIONS 269; the +owner's prototype, one draft, a check and a decision, revised after the final positions by DECISIONS 270). The components are +`ArchitectureDiagram`, `FlowchartDiagram`, `DataFlowDiagram`, `SequenceDiagram` and `SchemaDiagram`, and the HTML skill's `diagram` module. + +**Status:** decided by the council (DECISIONS 269, a handoff); the implementation has not been reviewed. + +**The idea: the words are in the boxes, the lines say how they connect, and the key says what each line means.** A diagram is +monochrome. Nothing takes a colour, the accent or a status. One node may be focal, and it is inverted ink. + +### The figure + +- Its order is the chart's: the title and source, the drawing, the key, the key hint, the summary (a required `figcaption`), then + "View as list" and the list. +- Text is `text-xs` or `text-sm`. Nothing is under 12px. The drawing is laid out in real CSS pixels at its own measured width, never + scaled through a `viewBox`, and nothing scrolls sideways. +- A node is a panel one level above what the figure sits in: the rim, no shadow, radius 8, `space-2-5` by `space-3`. Its lines are a + kind (`text-xs` Mono, tertiary), a name (`text-sm` 600) and a detail (`text-xs` secondary, Mono only for an identifier). +- **The focal node** is inverted: `diagram-focal` under `diagram-focal-ink`, its quiet lines at `opacity-amount`. One at most. The key + says what it marks. + +### Lines + +- Three kinds, named by their look; the key gives each its meaning. **Main:** 2px, primary ink, a filled head. **Plain:** 1px, + secondary ink, a filled head. **Dashed:** 1px, secondary ink, 6 on 4 off, an open head. +- Lines are orthogonal, with elbows of 8 or half the shorter leg. One head, `size-diagram-head`, at the far end. A line ends on the + shape drawn, not on its box. A 1px line sits on half pixels, a 2px line on whole ones, and a head snaps with its line. +- **Ports are derived.** Nodes in a row or a column face each other; otherwise a line leaves sideways and enters from above or below. + A side's one line is at its middle; a straight line keeps the middle and others take the quarter points. An author names a side only + to change that. +- **Crossings:** place to avoid them; lines to one port share one lane and join; of two bypasses from one side, the farther-going + leaves higher and takes the outer lane. A crossing that is left is cut: the line underneath breaks `size-cut` each side of the one + on top. The horizontal run is on top, and a traced line is on top of an untraced one. +- **A label** is `text-xs` Mono in secondary ink, one line, never cut. On its own line it has a ground-colour plate; beside its line + it is `space-2` clear of the stroke. Seats are taken along the run's clear shaft (the run without its head). A seat is taken only if + the label, grown `space-1`, overlaps no node as drawn (the diamond or the capsule, not its box), label, head, boundary, rule or other + line. + +### Fit + +- **The drawn layout is used only when it fits:** the figure is at least 640 wide (`size-breakpoint-container-lg`), every track is at + least `size-diagram-node` (a table `size-diagram-table`) and as wide as its widest unbreakable content, every label has a clean seat + and no line passes through a node. Otherwise the figure is stacked. This is a measured fit, not a breakpoint. +- **Stacked** is one column in the author's order, at most 480 wide (`size-breakpoint-container`) on the start edge. Architecture and + flowchart are a spine with indented branches: a rail and a trunk at the start, one lane at the end, every route taken from the order. + A line that leaves or passes a spine card runs in an end gutter outside the cards (`space-10`, two lanes at most), down into a card's + top or up into its bottom. A data flow is its steps in order with bypasses in that gutter. A sequence is a strip of participants and a numbered list that names each message's sender, + receiver and kind. A schema is its cards in an auto-fit grid with no lines, because every foreign-key row writes its target. +- A name or a label is never cut at any width. + +### The types + +- **Architecture:** a group is a transparent box with a 1px dashed `diagram-structure` edge, radius 12, its label at the top start. Its + extent is its members'. One level of grouping. +- **Flowchart:** shape carries type: a step is the box, a start or end a capsule, a decision a diamond behind its words. **Every + flowchart shape has a 1px `diagram-structure` contour** in place of the rim, because the shape has to be seen at 3:1. A decision is + at least `space-16` tall and never flatter than 5:1. +- **Data flow:** lanes are bands ruled apart with the divider, named at the start. A node's kind line is its step number. +- **Sequence:** a head per participant; a lifeline is 1px `diagram-structure`, dashed 4 on 4 off; a message is a 56px row with its + number and label above the line and a note below, on plates that mask the lifelines; a self-call is a small loop; a reply is dashed; + a band is a ruled line of words, never a frame. +- **Schema:** a table is a card with a header band and 28px rows (a key seat, the name, the type or "→ table"). A foreign key is a + plain line from a dot on its row to a head on the referenced row. It comes from the column's own record. + +### The key, the summary and the list + +- The key is under the drawing and is built from the marks actually drawn, each swatch drawn like its mark. The author writes the + words. Main, dashed and the focal node must have them. +- The summary is required. "View as list" opens the same facts as real lists in the same figure: the parts and connections, a + flowchart's steps with each exit written once, a data flow's steps, a sequence's messages, a schema's tables. +- The figure's words are in the HTML before script runs, and where scripting is off the list is open. Before script the figure is + stacked unless it is at least its least width (the track minimums and gaps summed, never under 640); a figure of more than six + columns is stacked until script. + +### Keyboard, tracing and motion + +- Where lines are drawn the drawing is one tab stop: a `role="group"` with `aria-roledescription="diagram"`, named by the title and + described by the summary and a sentence about the keys. Each node is a focusable `role="img"` named by a sentence that says what it + is, where it sits, and what it connects from and to. → ↓ the next, ← ↑ the one before, Home and End the ends, Esc clears. No live + region. The SVG is `aria-hidden`. A layout change keeps focus on the same node, and never moves it, even into a stack with no stops. +- **Tracing** a node (hover, or keyboard focus) lifts its lines to primary ink and dims the rest to `diagram-edge-dim`. It changes ink + and never weight, dash or head, so the key stays true. There is no trace on touch, and a node is not a target. +- No motion in the drawing and no entrance. A trace's ink changes over `duration-fast`, at once under reduced motion. + +### Forced colours and more contrast + +- Forced colours: lines `CanvasText`, a dimmed line `GrayText`, a traced line `Highlight`; contours `CanvasText`; boundaries, lifelines + and rules `GrayText`; plates and cuts `Canvas`; the focal node `CanvasText` under `Canvas` ink, with `forced-color-adjust: none` on + it and every colour inside set by hand (Chromium otherwise paints a `Canvas` backplate under its words); the focus ring `Highlight`. +- More contrast: the aliases apply. The focal node's quiet ink goes to full strength. `diagram-structure` and `diagram-edge-dim` are + the input boundary and do not step. + +### Diagram tokens + +| Token | Value | Dark | Light | Use | +|---|---|---|---|---| +| `diagram-edge-main` | `text-primary` | `#f4f4f4` | `#171717` | The main line and its head; a traced line | +| `diagram-edge` | `text-secondary` | `#bababa` | `#4d4d4d` | Plain and dashed lines, their heads, a foreign key's line and dot | +| `diagram-edge-dim` | `border-input` | white 38% | black 45% | Every other line while one node is traced | +| `diagram-structure` | `border-input` | white 38% | black 45% | A group's boundary, a lifeline, a flowchart shape's contour | +| `diagram-focal` | `action-primary` | `#ededed` | `#171717` | The focal node's fill and edge | +| `diagram-focal-ink` | `action-primary-text` | `#000` | `#fff` | Ink on the focal node | +| `diagram-focal-rule` | `black-8` in dark, `white-6` in light | black 8% | white 6% | The focal table's header rule (decorative: it is the other theme's divider, because the focal fill is the other theme's ground) | + +| Token | Value | Use | +|---|---|---| +| `size-diagram-node` | 144px | The least width of a node's track in a drawn layout | +| `size-diagram-table` | 224px | The least width of a schema table | +| `size-diagram-lane` | 120px | A data flow's lane-name column | +| `size-diagram-step` | 56px | A sequence's message row | +| `size-diagram-head` | 8px | An arrowhead's length and its width | +| `size-diagram-guide-dash` | 4px | A lifeline's dash, on and off | + +Under more contrast `diagram-focal-rule` is drawn as `diagram-focal-rule-contrast` (`black-45` in dark, `white-38` in light: the other +theme's input boundary, 1.18), the way the other aliases of that mode are declared. + +**Not tokens, by choice:** the gaps, the rail (`space-3`), the trunk (`space-8`), the branch indent (`space-12`), the entry inset +(`space-6`), the end gutter (`space-10`, lanes at `space-3-5`) and the quarter-point slots are rules made of the space scale. + ## Layout The layout lengths and breakpoints (decision 101). Each is a token under `size`, emitted to CSS, JavaScript and Swift. diff --git a/packages/react/README.md b/packages/react/README.md index aa7c713c..31e38d83 100644 --- a/packages/react/README.md +++ b/packages/react/README.md @@ -208,6 +208,7 @@ None of these changes how anything looks: each is an existing look or rule, expo | `SkipLink` | The first thing on a page: a link past the bar and the navigation to the content. `<SkipLink target="main" />` renders `<a href="#main">Skip to content</a>`; the words are `children`, so an app in another language replaces them, and any anchor prop passes through (`target` may carry its `#`). It is unseen until it has focus. With a sticky bar (`SiteHeader`, `AppHeader` or your own `.basalt-sticky-bar`) it then hangs under the bar, space-2 below its line, on the brand's start edge at every width, so it covers nothing in the bar; without one it sits at the page's top start (space-2 in). **How it finds the bar:** when it takes focus it reads the real bottom edge of the first element matching `.basalt-site-header, .basalt-app-header, .basalt-sticky-bar` and sits space-2 below it, and reads it again on scroll and resize while it holds focus, so a bar that is not at the top of the viewport (a notice above it) is still cleared; with no script or no bar it is where the stylesheet puts it, under a bar at the top. It floats like a tooltip (level 3, the rim, `shadow-overlay`, radius 8) on the toast layer; 44px tall on a coarse pointer; not drawn in print. It is the HTML skill's `.skip-link`, drawn with the same tokens. **The app places it itself, as the first element of the page** (before the bar, so it is the first tab stop): `AppShell` and `SiteHeader` render none. Give the target `tabIndex={-1}` so following the link moves focus to it (`AppShell`: `mainProps={{ id: "main", tabIndex: -1 }}`); a target that cannot take focus starts the next Tab there instead. | | `TimeChart`'s `lit`, `headline`, `headlineFormat`, `trend`, `plotSize`, `compact`, `lane`, `onDayActivate`, `activateHint`; `trailingMean(values, { window, min })` | The lit figure (DECISIONS 153; the implementation hasn't been reviewed). `lit`: solid marks take one vertical gradient in three neutral stops, a line one stroke in the top stop. `headline`: the frame with the picked day's number as the headline (one series), the unit beside it, one context line, no live region; its number is written in the chart's `locale` unless `headlineFormat` writes it. `trend`: `true` (7 days) or a window: the readings as small dots and their trailing mean as one straight line that breaks at a gap, one head dot, the number the trend. `plotSize="sm"` is the 96px plot. `compact` (with `kind="bar"` and `plotSize="sm"`) is the short bar plot (DECISIONS 160, the owner's choice for vote 10): no gridlines, no y labels, no gutter, the plot the figure's width; the legend, keys, table and caption stay; ignored for a line, a 240px plot or a second series. `lane` and `onDayActivate` are what `PhaseChart` is built from. `trailingMean` returns `Array<number \| null>` (no NaN for no data). | | `PhaseChart` | A trend over weeks with a lane of one choice a week (seven days a choice; lanes of other lengths are in the backlog) and the open week's plate: `name`, `values`, `calls` (`{ word, changed?, text }`), `week`, `onWeekChange`, plus the words, all required and each a whole string, since the chart ships no word for the period: `laneLabel` ("Choose a check-in"), `previousLabel` and `nextLabel` ("Previous check-in", "Next check-in"), `callName(index)` ("Check-in 31", "Nov 3 check-in"), `statusLine(index, call)` (what the status line says of the open choice) and `activateHint` ("opens its check-in", Enter's hint in the legend), plus a `TimeChart`'s `title`, `days`, `format`, `summary`. A press on a day, or Enter, opens its week; on a phone the lane is marks with previous and next controls. | +| `ArchitectureDiagram`, `FlowchartDiagram`, `DataFlowDiagram`, `SequenceDiagram`, `SchemaDiagram` | Diagrams (DECISIONS 269 and 270; the implementation hasn't been reviewed): boxes and the lines between them, monochrome, one focal node inverted, three lines named by their look (`main`, `plain`, `dashed`) whose meaning the `legend` gives. Each takes the figure's `title`, `heading`, `source`, required `summary` and `legend`, and its own data: `nodes` placed by `col` and `row` (an architecture's `groups`, a flowchart's `shape`, a data flow's `lanes`), `edges` by node id (`fromSide`/`toSide` only to change the derived side), a sequence's `participants` and `steps`, a schema's `tables` with `references: "table.column"` on a foreign key. The array's order is the stacked order, the focus order and the list's. The drawn layout is used only where it fits; otherwise the figure is stacked, at most 480 wide. One tab stop, arrow keys between nodes, a trace on hover or keyboard focus, and "View as list". No layout engine, no dependency. | | `ChartGroup` | Charts stacked in one figure (`label` names it): the y gutter and the right margin are as wide as the widest chart's, so every plot starts and ends at the same x. Put the charts inside; each keeps its own title, legend, summary and table. | | `ShareBar`, `shareOf(values)` | Parts of a whole as one bar: `parts` (`{ name, value }`), `size="sm"` (8px) or `"md"` (12px), `format(share, part)`. One ink, a 4px gap, each part's share (whole percents that add to 100) and name under it; a part that is more than nothing and rounds to 0 reads "<1%" (spoken "less than 1%"), and a part of nothing is left out. | | `CoverageStrip`, `coverageWords(days)` | One cell a day (`{ date, recorded, why }`): `form="strip"` (slivers, 48px) or `"week"` (seven squares); the missing dates in words, built from the cells. | diff --git a/packages/react/src/architecture-diagram.tsx b/packages/react/src/architecture-diagram.tsx new file mode 100644 index 00000000..92cf40ef --- /dev/null +++ b/packages/react/src/architecture-diagram.tsx @@ -0,0 +1,23 @@ +import * as React from "react"; + +import { DiagramFigure } from "./diagram-figure"; +import type { DiagramFigureProps } from "./diagram-figure"; +import type { ArchitectureNode, DiagramEdge, DiagramGroup } from "./diagram-core"; + +export type { ArchitectureNode, DiagramEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramNode, DiagramSide } from "./diagram-core"; +export type { DiagramFigureProps } from "./diagram-figure"; + +export interface ArchitectureDiagramProps extends DiagramFigureProps { + /** The parts, in the author's order: the stacked order, the focus order and the list's. `col` and `row` place each in the drawn layout. */ + nodes: ArchitectureNode[]; + /** One level of grouping: `group: "aws"` on the members and `{ id, label }` here. The box is derived from its members. */ + groups?: DiagramGroup[]; + /** The lines, by node id. Sides are derived; name one only to change it. */ + edges: DiagramEdge[]; +} + +/** An architecture diagram (DECISIONS 269): nodes with a kind, a name and a detail, groups, and three kinds of line. */ +export function ArchitectureDiagram({ nodes, groups, edges, title, heading, legend, ...props }: ArchitectureDiagramProps) { + const spec = React.useMemo(() => ({ type: "architecture" as const, title, heading, legend, nodes, groups, edges }), [title, heading, legend, nodes, groups, edges]); + return <DiagramFigure {...props} title={title} heading={heading} legend={legend} spec={spec} component="ArchitectureDiagram" />; +} diff --git a/packages/react/src/data-flow-diagram.tsx b/packages/react/src/data-flow-diagram.tsx new file mode 100644 index 00000000..0301d508 --- /dev/null +++ b/packages/react/src/data-flow-diagram.tsx @@ -0,0 +1,23 @@ +import * as React from "react"; + +import { DiagramFigure } from "./diagram-figure"; +import type { DiagramFigureProps } from "./diagram-figure"; +import type { DataFlowLane, DataFlowNode, DiagramEdge } from "./diagram-core"; + +export type { DataFlowLane, DataFlowNode, DiagramEdge, DiagramLegend, DiagramLineKind, DiagramSide } from "./diagram-core"; + +export interface DataFlowDiagramProps extends DiagramFigureProps { + /** The lanes, top to bottom: a node's row is its lane's place here. */ + lanes: DataFlowLane[]; + /** The steps in order: a node's place here is its step number. `col` counts the step columns. */ + nodes: DataFlowNode[]; + edges: DiagramEdge[]; + /** How a step's number is written (default "Step 3"). */ + stepLabel?: (n: number) => string; +} + +/** A data flow (DECISIONS 269): lanes as bands, steps numbered in order; stacked, a step says its lane. */ +export function DataFlowDiagram({ lanes, nodes, edges, stepLabel, title, heading, legend, ...props }: DataFlowDiagramProps) { + const spec = React.useMemo(() => ({ type: "data-flow" as const, title, heading, legend, lanes, nodes, edges, stepLabel }), [title, heading, legend, lanes, nodes, edges, stepLabel]); + return <DiagramFigure {...props} title={title} heading={heading} legend={legend} spec={spec} component="DataFlowDiagram" />; +} diff --git a/packages/react/src/diagram-core.ts b/packages/react/src/diagram-core.ts new file mode 100644 index 00000000..b1dfeb29 --- /dev/null +++ b/packages/react/src/diagram-core.ts @@ -0,0 +1,1740 @@ +// Basalt's diagrams (DECISIONS 269, revised by 270): the one engine behind the five React components and the HTML skill's `diagram` module. +// It is not exported from the package. It holds no React and no state: the model is read from the author's data, the markup is a small tree +// (React renders it, the skill writes it as HTML at build time), and the drawing is measured from the DOM and returned as one string of +// SVG and labels, so the two implementations draw the same pixels. Nothing here runs when the module loads: every table, cache and +// measurer is built inside a function. +// +// What the author writes is placement on a grid and one record per part; everything else is derived: the sides and slots a line uses, its +// route and jogs, the lanes it shares, a group's box, a foreign key's line, the stacked drawing's routes and gaps, and every label's seat. + +// ============================================================================================================================================ +// Public shapes (the components re-export these types; no third-party type appears in them) +// ============================================================================================================================================ + +export type DiagramType = "architecture" | "flowchart" | "data-flow" | "sequence" | "schema"; +export type DiagramSide = "top" | "right" | "bottom" | "left"; +export type DiagramLineKind = "main" | "plain" | "dashed"; + +/** The words for the marks. The key is built from what is drawn; `main`, `dashed` and the focal node must have words when drawn. */ +export interface DiagramLegend { main?: string; plain?: string; dashed?: string; focal?: string; group?: string } + +export interface DiagramNode { + id: string; + name: string; + kind?: string; + detail?: string; + /** The detail is an identifier (a port, a type, a path): it is set in Geist Mono. Words stay in Geist. */ + detailMono?: boolean; + /** The one focal node, inverted. At most one a diagram. */ + focal?: boolean; + /** 1-based tracks of the drawn layout. */ + col: number; + row: number; + /** Indented in the stacked drawing; a node is on the spine unless it is a branch. */ + branch?: boolean; +} + +export interface DiagramEdge { + from: string; + to: string; + /** Default "plain". */ + kind?: DiagramLineKind; + /** One line, at most 28 characters. */ + label?: string; + /** Only to change the derived side. */ + fromSide?: DiagramSide; + toSide?: DiagramSide; +} + +export interface DiagramGroup { id: string; label: string } +export type ArchitectureNode = DiagramNode & { group?: string }; +export type FlowchartNode = DiagramNode & { shape?: "step" | "decision" | "terminal" }; +export interface DataFlowLane { id: string; label: string } +export type DataFlowNode = Omit<DiagramNode, "row" | "kind" | "branch"> & { lane: string }; +export interface SequenceParticipant { id: string; name: string; kind?: string; short?: string; focal?: boolean } +export type SequenceStep = { from: string; to: string; label: string; note?: string; kind?: DiagramLineKind } | { band: string }; +export interface SchemaColumn { name: string; type?: string; key?: "PK" | "FK"; references?: string } +export interface SchemaTable { name: string; col: number; row: number | [number, number]; focal?: boolean; more?: number; columns: SchemaColumn[] } +export interface DiagramShapeLabels { terminal?: string; step?: string; decision?: string } + +/** Everything a figure is drawn from: the React props, or the HTML skill's JSON, key for key. */ +export interface DiagramSpec { + type: DiagramType; + title: string; + heading?: 2 | 3 | 4 | 5 | 6; + legend?: DiagramLegend; + nodes?: Array<ArchitectureNode | FlowchartNode | DataFlowNode>; + edges?: DiagramEdge[]; + groups?: DiagramGroup[]; + lanes?: DataFlowLane[]; + participants?: SequenceParticipant[]; + steps?: SequenceStep[]; + tables?: SchemaTable[]; + shapeLabels?: DiagramShapeLabels; + stepLabel?: ((n: number) => string) | string; +} + +// ============================================================================================================================================ +// The model +// ============================================================================================================================================ + +type Shape = "box" | "terminal" | "decision" | "table" | "participant"; + +export interface MColumn { name: string; type?: string; key?: "PK" | "FK"; ref?: { table: string; column: string; row: number } } +export interface MNode { + id: string; + i: number; + name: string; + kind?: string; + detail?: string; + mono: boolean; + focal: boolean; + col: number; + row: number; + row2: number; + branch: boolean; + shape: Shape; + group?: string; + lane?: number; + laneLabel?: string; + step?: number; + columns?: MColumn[]; + more?: number; + short?: string; +} +export interface MEdge { + i: number; + from: string; + to: string; + kind: DiagramLineKind; + label?: string; + fromSide?: DiagramSide; + toSide?: DiagramSide; + /** A foreign key: the row it leaves and the row it points to. */ + fromRow?: number; + toRow?: number; + fk?: boolean; +} +export type MStep = { band: string } | { n: number; from: string; to: string; label: string; note?: string; kind: DiagramLineKind }; +export interface Model { + type: DiagramType; + title: string; + heading: 2 | 3 | 4 | 5 | 6; + legend: DiagramLegend; + nodes: MNode[]; + byId: Map<string, MNode>; + edges: MEdge[]; + groups: Array<DiagramGroup & { members: string[] }>; + lanes: DataFlowLane[]; + steps: MStep[]; + cols: number; + rows: number; + shapeLabels: Required<DiagramShapeLabels>; + stepWord: (n: number) => string; + warnings: string[]; +} + +const SIDES: DiagramSide[] = ["top", "right", "bottom", "left"]; + +/** Reads the author's data into the model. A problem the decision calls a development error is collected in `warnings`. */ +export function buildModel(spec: DiagramSpec): Model { + const warnings: string[] = []; + const warn = (message: string) => { warnings.push(message); }; + const legend = { ...(spec.legend ?? {}) }; + const stepWord = typeof spec.stepLabel === "function" ? spec.stepLabel : typeof spec.stepLabel === "string" ? ((n: number) => (spec.stepLabel as string).replace("{n}", String(n))) : (n: number) => `Step ${n}`; + const shapeLabels = { terminal: "Start or end", step: "Step", decision: "Decision", ...(spec.shapeLabels ?? {}) }; + const nodes: MNode[] = []; + const edges: MEdge[] = []; + let lanes: DataFlowLane[] = []; + const groups: Model["groups"] = []; + const steps: MStep[] = []; + const type = spec.type; + + if (type === "architecture" || type === "flowchart") { + for (const raw of (spec.nodes ?? []) as Array<ArchitectureNode & FlowchartNode>) { + const shape: Shape = type === "flowchart" && raw.shape === "decision" ? "decision" : type === "flowchart" && raw.shape === "terminal" ? "terminal" : "box"; + nodes.push({ + id: raw.id, i: nodes.length, name: raw.name, kind: shape === "decision" ? undefined : raw.kind, detail: shape === "decision" ? undefined : raw.detail, mono: Boolean(raw.detailMono), + focal: Boolean(raw.focal), col: raw.col, row: raw.row, row2: raw.row, branch: Boolean(raw.branch), shape, group: type === "architecture" ? raw.group : undefined, + }); + } + if (type === "architecture") for (const g of spec.groups ?? []) groups.push({ ...g, members: nodes.filter((n) => n.group === g.id).map((n) => n.id) }); + } else if (type === "data-flow") { + lanes = spec.lanes ?? []; + const laneIndex = new Map(lanes.map((l, k) => [l.id, k + 1])); + for (const raw of (spec.nodes ?? []) as DataFlowNode[]) { + const lane = laneIndex.get(raw.lane); + if (lane === undefined) warn(`a node (${raw.id}) names the lane "${raw.lane}", which is not in lanes`); + const n = nodes.length + 1; + nodes.push({ + id: raw.id, i: nodes.length, name: raw.name, kind: stepWord(n), detail: raw.detail, mono: Boolean(raw.detailMono), focal: Boolean(raw.focal), + col: raw.col, row: lane ?? 1, row2: lane ?? 1, branch: false, shape: "box", lane: lane ?? 1, laneLabel: lanes[(lane ?? 1) - 1]?.label ?? raw.lane, step: n, + }); + } + } else if (type === "sequence") { + (spec.participants ?? []).forEach((p, k) => nodes.push({ id: p.id, i: k, name: p.name, kind: p.kind, mono: false, focal: Boolean(p.focal), col: k + 1, row: 1, row2: 1, branch: false, shape: "participant", short: p.short ?? p.name })); + let n = 0; + for (const s of spec.steps ?? []) { + if ("band" in s) steps.push({ band: s.band }); + else steps.push({ n: ++n, from: s.from, to: s.to, label: s.label, note: s.note, kind: s.kind ?? "plain" }); + } + } else if (type === "schema") { + for (const t of spec.tables ?? []) { + const [r1, r2] = Array.isArray(t.row) ? t.row : [t.row, t.row]; + nodes.push({ + id: t.name, i: nodes.length, name: t.name, mono: true, focal: Boolean(t.focal), col: t.col, row: r1, row2: r2, branch: false, shape: "table", more: t.more, + columns: t.columns.map((c) => ({ name: c.name, type: c.type, key: c.key })), + }); + } + } + + const byId = new Map<string, MNode>(); + for (const n of nodes) { + if (!n.id) warn("a node has no id"); + else if (byId.has(n.id)) warn(`the id "${n.id}" is used twice`); + byId.set(n.id, n); + } + + // Schema: a foreign key is one record, `references` on the column; its line, its row's words, the sentence and the list all come from it. + if (type === "schema") { + (spec.tables ?? []).forEach((t) => t.columns.forEach((c, k) => { + if (!c.references) return; + const [table, column] = c.references.split("."); + const target = byId.get(table ?? ""); + const row = target?.columns?.findIndex((x) => x.name === column) ?? -1; + if (!target || row < 0) { warn(`${t.name}.${c.name} references ${c.references}, which is not a shown column`); return; } + const source = byId.get(t.name)!; + source.columns![k]!.ref = { table: table!, column: column!, row }; + edges.push({ i: edges.length, from: t.name, to: table!, kind: "plain", fromRow: k, toRow: row, fk: true }); + })); + } else if (type !== "sequence") { + for (const e of spec.edges ?? []) { + if (!byId.has(e.from) || !byId.has(e.to)) { warn(`a line names ${!byId.has(e.from) ? e.from : e.to}, which is not a node`); continue; } + if (e.label && e.label.length > MAX_LABEL) warn(`the label "${e.label}" is over ${MAX_LABEL} characters: longer words belong in the node or the summary`); + for (const side of [e.fromSide, e.toSide]) if (side && !SIDES.includes(side)) warn(`"${side}" is not a side (top, right, bottom or left)`); + edges.push({ i: edges.length, from: e.from, to: e.to, kind: e.kind ?? "plain", label: e.label || undefined, fromSide: e.fromSide, toSide: e.toSide }); + } + } else { + for (const s of steps) if ("n" in s) { + if (!byId.has(s.from) || !byId.has(s.to)) warn(`message ${s.n} names ${!byId.has(s.from) ? s.from : s.to}, which is not a participant`); + } + } + + // Placement checks: two nodes in one cell, a non-member inside a group's box, more than one focal node. + if (type !== "sequence") { + const cells = new Map<string, string>(); + for (const n of nodes) for (let r = n.row; r <= n.row2; r++) { + const key = `${n.col}:${r}`; + if (cells.has(key)) warn(`${n.id} and ${cells.get(key)} share the cell at column ${n.col}, row ${r}`); + cells.set(key, n.id); + } + } + for (const g of groups) { + const m = g.members.map((id) => byId.get(id)!); + if (!m.length) continue; + const box = { c1: Math.min(...m.map((n) => n.col)), c2: Math.max(...m.map((n) => n.col)), r1: Math.min(...m.map((n) => n.row)), r2: Math.max(...m.map((n) => n.row2)) }; + for (const n of nodes) if (n.group !== g.id && n.col >= box.c1 && n.col <= box.c2 && n.row >= box.r1 && n.row <= box.r2) warn(`${n.id} is inside the box of the group "${g.label}" but not a member`); + const idx = m.map((n) => n.i); + if (Math.max(...idx) - Math.min(...idx) + 1 !== idx.length) warn(`the members of the group "${g.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`); + } + for (const n of nodes) if (n.group && !groups.some((g) => g.id === n.group)) warn(`${n.id} names the group "${n.group}", which is not in groups`); + if (nodes.filter((n) => n.focal).length > 1) warn("more than one node is focal: a diagram has one at most"); + + // The key's words: main, dashed and the focal node must have them when drawn. + const kinds = new Set<DiagramLineKind>(type === "sequence" ? steps.flatMap((s) => ("n" in s ? [s.kind] : [])) : edges.map((e) => e.kind)); + if (kinds.has("main") && !legend.main) warn("main lines are drawn but the legend has no words for them (legend.main)"); + if (kinds.has("dashed") && !legend.dashed) warn("dashed lines are drawn but the legend has no words for them (legend.dashed)"); + if (nodes.some((n) => n.focal) && !legend.focal) warn("a focal node is drawn but the legend has no words for what it marks (legend.focal)"); + + const cols = Math.max(1, ...nodes.map((n) => n.col)); + const rows = type === "data-flow" ? Math.max(1, lanes.length) : Math.max(1, ...nodes.map((n) => n.row2)); + return { type, title: spec.title, heading: spec.heading ?? 3, legend, nodes, byId, edges, groups, lanes, steps, cols, rows, shapeLabels, stepWord, warnings }; +} + +const MAX_LABEL = 28; + +// ============================================================================================================================================ +// Words: sentences, the key, the list +// ============================================================================================================================================ + +const sentence = (s: string) => { const t = s.trim(); return !t ? "" : /[.!?]$/.test(t) ? t : `${t}.`; }; +const upperFirst = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + +/** A kind's word, from the key (none when the author gave none: an unkeyed plain line says "goes to"). */ +export function kindWord(m: Model, kind: DiagramLineKind): string | undefined { return m.legend[kind]; } + +/** What a flowchart node is called in words. */ +function shapeWord(m: Model, n: MNode): string { + if (n.shape === "decision") return "decision"; + if (n.shape === "terminal") return m.edges.some((e) => e.from === n.id) ? "start" : "end"; + return n.kind ?? "step"; +} + +/** The sentence a focusable node is named by: what it is, where it sits, what it connects from and to. */ +export function nodeSentence(m: Model, n: MNode): string { + const parts: string[] = []; + if (m.type === "schema") { + parts.push(`${n.name}, table.`); + const refs = (n.columns ?? []).filter((c) => c.ref).map((c) => `${c.ref!.table} (${c.name})`); + const by = m.edges.filter((e) => e.to === n.id).map((e) => `${e.from} (${m.byId.get(e.from)!.columns![e.fromRow!]!.name})`); + if (refs.length) parts.push(`References ${refs.join(", ")}.`); + if (by.length) parts.push(`Referenced by ${by.join(", ")}.`); + } else if (m.type === "sequence") { + const sends = m.steps.filter((s) => "n" in s && s.from === n.id).length; + const gets = m.steps.filter((s) => "n" in s && s.to === n.id).length; + parts.push(sentence(n.kind ? `${n.name}, ${n.kind}` : n.name)); + parts.push(`Sends ${sends} ${sends === 1 ? "message" : "messages"} and receives ${gets}.`); + } else { + const what = m.type === "data-flow" ? `${m.stepWord(n.step!)} of ${m.nodes.length}, ${n.laneLabel}` : m.type === "flowchart" ? shapeWord(m, n) : n.kind; + parts.push(sentence(what ? `${n.name}, ${what}` : n.name)); + if (n.detail) parts.push(sentence(n.detail)); + if (n.group) { const g = m.groups.find((x) => x.id === n.group); if (g) parts.push(`In ${g.label}.`); } + const from = m.edges.filter((e) => e.to === n.id).map((e) => `${m.byId.get(e.from)!.name}${e.label ? ` (${e.label})` : ""}`); + const to = m.edges.filter((e) => e.from === n.id).map((e) => `${m.byId.get(e.to)!.name}${e.label ? ` (${e.label})` : ""}`); + if (from.length) parts.push(`From: ${from.join(", ")}.`); + if (to.length) parts.push(`To: ${to.join(", ")}.`); + } + if (n.focal && m.legend.focal) parts.push(sentence(m.legend.focal)); + return parts.join(" "); +} + +/** The noun the key hint and the keys sentence use for one stop. */ +function stopNoun(m: Model): string { + return m.type === "architecture" ? "a part" : m.type === "sequence" ? "a participant" : m.type === "schema" ? "a table" : "a step"; +} + +// ============================================================================================================================================ +// The markup tree +// ============================================================================================================================================ + +export type VAttrs = Record<string, string | number | boolean | null | undefined>; +export interface VElement { t: string; a: VAttrs; c: VNode[] } +export interface VSlot { slot: "source" | "summary" | "hint" | "toggle" } +export type VNode = string | VElement | VSlot; + +type VChild = VNode | null | undefined | false | VChild[]; +function h(t: string, a: VAttrs | null, ...c: VChild[]): VElement { + const kids: VNode[] = []; + for (const k of c.flat(Infinity as 1) as VChild[]) if (k !== null && k !== undefined && k !== false && !Array.isArray(k)) kids.push(k); + return { t, a: a ?? {}, c: kids }; +} + +const ESC: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; +export const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ESC[c]!); +// Elements written with no closing tag (HTML's void elements, and SVG's shapes written self-closed). A string, so loading the module allocates nothing. +const VOID = " br img input meta link hr path polygon polyline circle rect line "; + +/** The tree as HTML. A slot is written by `slots`. */ +export function toHtml(v: VNode, slots: Partial<Record<VSlot["slot"], string>> = {}): string { + if (typeof v === "string") return escapeHtml(v); + if ("slot" in v) return slots[v.slot] ?? ""; + let attrs = ""; + for (const [k, value] of Object.entries(v.a)) { + if (value === undefined || value === null || value === false) continue; + attrs += value === true ? ` ${k}` : ` ${k}="${escapeHtml(String(value))}"`; + } + if (VOID.includes(` ${v.t} `) && !v.c.length) return v.t === "path" || v.t === "polygon" || v.t === "polyline" || v.t === "circle" || v.t === "rect" || v.t === "line" ? `<${v.t}${attrs}/>` : `<${v.t}${attrs}>`; + return `<${v.t}${attrs}>${v.c.map((c) => toHtml(c, slots)).join("")}</${v.t}>`; +} + +/** The parts of a figure's state that change its markup. Before script runs every field is unset. */ +export interface Dyn { + /** The layout script chose; unset before script, when the stylesheet decides by the figure's least width. */ + layout?: "drawn" | "stacked"; + /** The node that holds the roving tab stop. */ + stop?: string; + /** A node that keeps focus (and tabindex -1) in a stack with no stops, until focus leaves it. */ + keep?: string; + /** A decision's measured height, by node id, in px. */ + heights?: Record<string, number>; + /** Extra lines of 16 added to the gap above a stacked card, when a label did not fit its seat. */ + grow?: Record<string, number>; + /** The schema's stacked track: its widest row, measured. */ + track?: number; + open?: boolean; +} + +export interface TreeIds { base: string } +const idsOf = (base: string) => ({ title: `${base}-title`, summary: `${base}-summary`, keys: `${base}-keys`, list: `${base}-list`, toggle: `${base}-toggle` }); + +/** Whether the figure's nodes are stops (a roving tab index) in this state. */ +export function hasStops(m: Model, dyn: Dyn): boolean { + if (!dyn.layout) return false; + if (dyn.layout === "drawn") return true; + return m.type !== "sequence" && m.type !== "schema"; +} +/** Whether the nodes are images named by a sentence in this state (before script, the types whose stack has lines). */ +function nodesAreImages(m: Model, dyn: Dyn): boolean { + if (m.type === "sequence" || m.type === "schema") return dyn.layout === "drawn"; + return true; +} + +/** How many sides a group reaches (the start or the end column): each adds space-4 to the least width. */ +export function groupReach(m: Model): number { + let reach = 0; + for (const g of m.groups) { + const cols = g.members.map((id) => m.byId.get(id)!.col); + if (!cols.length) continue; + if (Math.min(...cols) === 1) reach |= 1; + if (Math.max(...cols) === m.cols) reach |= 2; + } + return (reach & 1) + ((reach >> 1) & 1); +} + +/** The figure's columns as the least-width rules count them: a sequence's participants, a data flow's step columns, everyone else's tracks. */ +export function columnCount(m: Model): number { return m.type === "sequence" ? m.nodes.length : m.cols; } + +// ---- The stacked drawing's plan: routes and gaps from the order alone (1.13) ---- + +export type StackRoute = "down" | "up" | "trunk" | "rail" | "end-down" | "end-up"; +export interface StackPlan { routes: StackRoute[]; gutter: boolean; lanes: number[]; exits: number[]; gaps: Record<string, number>; third: boolean } + +/** The stacked drawing's routes, end lanes and the gap above each card (in px of the space scale), from the author's order. */ +export function stackPlan(m: Model): StackPlan { + const order = m.nodes; + const spine = (i: number) => m.type === "data-flow" || !order[i]!.branch; + const routes: StackRoute[] = m.edges.map((e) => { + const a = m.byId.get(e.from)!.i, b = m.byId.get(e.to)!.i; + const between = order.slice(Math.min(a, b) + 1, Math.max(a, b)); + const onlyBranches = between.every((n) => !spine(n.i)); + if (b === a + 1 && !(spine(a) && !spine(b))) return "down"; + if (b === a - 1) return "up"; + if (b > a && spine(a) && !spine(b) && onlyBranches) return "trunk"; + if (b > a && spine(a) && spine(b) && onlyBranches) return "rail"; + return b > a ? "end-down" : "end-up"; + }); + const ends = m.edges.map((e, k) => ({ e, k })).filter(({ k }) => routes[k] === "end-down" || routes[k] === "end-up"); + const span = (e: MEdge) => { const a = m.byId.get(e.from)!.i, b = m.byId.get(e.to)!.i; return [Math.min(a, b), Math.max(a, b)] as const; }; + const overlaps = (x: MEdge, y: MEdge) => { const [a1, b1] = span(x), [a2, b2] = span(y); return a1 < b2 && a2 < b1; }; + // The end lane inside the cards serves only lines that leave a branch, pass only branches and run alone; otherwise every end line takes the gutter. + const laneOk = ends.every(({ e }) => { + const a = m.byId.get(e.from)!.i; + const [lo, hi] = span(e); + return !spine(a) && order.slice(lo + 1, hi).every((n) => !spine(n.i)) && ends.every((o) => o.e === e || !overlaps(o.e, e)); + }); + const gutter = ends.length > 0 && (m.type === "data-flow" || !laneOk); + // Lanes in the gutter: nested (1.7 rule 3): of two overlapping lines the one that travels farther takes the outer lane; equal travel, the earlier is inside. + const travel = (e: MEdge) => { const [a, b] = span(e); return b - a; }; + const lanes = m.edges.map(() => 0); + let third = false; + for (const { e, k } of ends) { + const inner = ends.filter((o) => o.e !== e && overlaps(o.e, e) && (travel(o.e) < travel(e) || (travel(o.e) === travel(e) && o.k < k))); + lanes[k] = inner.length ? 1 : 0; + if (inner.length > 1 || ends.filter((o) => o.e !== e && overlaps(o.e, e)).length > 1) { + // Three overlapping end lines at once need a third lane. + const others = ends.filter((o) => o.e !== e && overlaps(o.e, e)); + if (others.some((o) => others.some((p) => p !== o && overlaps(o.e, p.e)))) third = true; + } + } + // Where an end line leaves its card: the middle, or the thirds when two leave one card (the farther one nearer the top going down, nearer the bottom going up). + const exits = m.edges.map(() => 0.5); + for (const n of order) { + const leaving = ends.filter(({ e }) => e.from === n.id); + if (leaving.length < 2) continue; + const down = leaving.filter(({ k }) => routes[k] === "end-down").sort((x, y) => travel(y.e) - travel(x.e) || x.k - y.k); + const up = leaving.filter(({ k }) => routes[k] === "end-up").sort((x, y) => travel(x.e) - travel(y.e) || y.k - x.k); + [...down, ...up].forEach(({ k }, j, all) => { exits[k] = all.length === 2 ? (j === 0 ? 1 / 3 : 2 / 3) : (j + 1) / (all.length + 1); }); + } + // The gap above each card (1.13): 32 for a plain entry, 40 for a branch entry with its label beside the elbow, 48 for a labelled stem, rail + // entry or end-line turn, 64 when two labelled entries share it or a turn from the card above and a turn into the card below share it. + // A data flow keeps 48 between every step. + const gaps: Record<string, number> = {}; + for (let b = 1; b < order.length; b++) { + const card = order[b]!, above = order[b - 1]!; + let labelled = 0, gap = m.type === "data-flow" ? 48 : 32, turnInto = false, turnFrom = false; + m.edges.forEach((e, k) => { + const r = routes[k]!; + const ia = m.byId.get(e.from)!.i, ib = m.byId.get(e.to)!.i; + const into = ib === b && (r === "down" || r === "trunk" || r === "rail" || r === "end-down"); + const upInto = ia === b && ib === b - 1 && r === "up"; + const turnBelowAbove = ib === b - 1 && r === "end-up"; + if (into && (r === "trunk" || r === "end-down")) turnInto = true; + if (turnBelowAbove) turnFrom = true; + if ((into || upInto || turnBelowAbove) && e.label) { + labelled++; + gap = Math.max(gap, r === "trunk" ? 40 : 48); + } + }); + if (labelled > 1 || (turnInto && turnFrom)) gap = 64; + gaps[card.id] = gap; + void above; + } + return { routes, gutter, lanes, exits, gaps, third }; +} + +// ---- Swatches: each drawn exactly as its mark ---- + +const svgA = (w: number, hgt: number): VAttrs => ({ width: w, height: hgt, viewBox: `0 0 ${w} ${hgt}`, "aria-hidden": "true", focusable: "false" }); + +/** A line swatch, 24 wide and 16 tall: the same stroke, dash and head as the line. */ +function lineSwatch(P: string, kind: DiagramLineKind | "fk"): VElement { + const k = kind === "fk" ? "plain" : kind; + const y = k === "main" ? 8 : 8.5; + const end = 24; + const shaftEnd = k === "dashed" ? end - 1 : end - 7; + return h("svg", { class: `${P}-swatch`, "data-kind": k, ...svgA(24, 16) }, + kind === "fk" ? h("circle", { class: `${P}-dot`, cx: 3, cy: y, r: 3 }) : null, + h("path", { class: `${P}-line`, "data-kind": k, d: `M${kind === "fk" ? 3 : 0} ${y}H${shaftEnd}` }), + k === "dashed" + ? h("path", { class: `${P}-tip`, "data-kind": k, "data-open": "", d: `M${end - 8} ${y - 4}L${end} ${y}L${end - 8} ${y + 4}` }) + : h("path", { class: `${P}-tip`, "data-kind": k, d: `M${end} ${y}L${end - 8} ${y - 4}L${end - 8} ${y + 4}Z` })); +} +function boxSwatch(P: string, shape: "box" | "terminal" | "decision" | "focal" | "group"): VElement { + if (shape === "decision") return h("svg", { class: `${P}-swatch`, "data-shape": shape, ...svgA(16, 16) }, h("path", { class: `${P}-swatch-shape`, d: "M8 2.5L14.5 8L8 13.5L1.5 8Z" })); + if (shape === "terminal") return h("svg", { class: `${P}-swatch`, "data-shape": shape, ...svgA(16, 16) }, h("rect", { class: `${P}-swatch-shape`, x: 0.5, y: 3.5, width: 15, height: 9, rx: 4.5 })); + return h("svg", { class: `${P}-swatch`, "data-shape": shape, ...svgA(16, 16) }, h("rect", { class: `${P}-swatch-shape`, x: 0.5, y: 2.5, width: 15, height: 11, rx: 2 })); +} + +/** The key, built from the marks the model draws: shapes, main, plain, dashed, the foreign-key line, the focal node, the group. */ +function keyTree(P: string, m: Model): VElement | null { + const entries: VElement[] = []; + const entry = (swatch: VElement, words: string, attrs: VAttrs = {}) => entries.push(h("li", { class: `${P}-entry`, ...attrs }, swatch, h("span", null, words))); + if (m.type === "flowchart") { + const used = new Set(m.nodes.map((n) => n.shape)); + if (used.has("terminal")) entry(boxSwatch(P, "terminal"), m.shapeLabels.terminal); + if (used.has("box")) entry(boxSwatch(P, "box"), m.shapeLabels.step); + if (used.has("decision")) entry(boxSwatch(P, "decision"), m.shapeLabels.decision); + } + const kinds = new Set<DiagramLineKind>(m.type === "sequence" ? m.steps.flatMap((s) => ("n" in s ? [s.kind] : [])) : m.edges.filter((e) => !e.fk).map((e) => e.kind)); + for (const k of ["main", "plain", "dashed"] as const) { + const words = m.legend[k]; + if (kinds.has(k) && words) entry(lineSwatch(P, k), words, { "data-line": "" }); + } + if (m.type === "schema" && m.edges.length) { + // The foreign-key line where it is drawn; where it is not, the row says it, and so does the key. + entry(lineSwatch(P, "fk"), m.legend.plain ?? "A foreign key, to the key it references", { "data-line": "", "data-when": "drawn" }); + entries.push(h("li", { class: `${P}-entry`, "data-when": "stacked" }, h("span", { class: `${P}-fk-mark`, "aria-hidden": "true" }, "→"), h("span", null, "A foreign key, written in the row"))); + } + if (m.nodes.some((n) => n.focal) && m.legend.focal) entry(boxSwatch(P, "focal"), m.legend.focal, { "data-focal": "" }); + if (m.groups.length && m.legend.group) entry(boxSwatch(P, "group"), m.legend.group); + if (!entries.length) return null; + return h("div", { class: `${P}-key` }, h("ul", { class: `${P}-legend`, "aria-label": "Key" }, entries)); +} + +/** The swatch drawn inline in the stacked sequence and in its list: a short arrow like its kind. */ +function inlineArrow(P: string, kind: DiagramLineKind): VElement { + const y = kind === "main" ? 6 : 6.5; + return h("svg", { class: `${P}-arrow`, "data-kind": kind, ...svgA(20, 12) }, + h("path", { class: `${P}-line`, "data-kind": kind, d: `M0 ${y}H${kind === "dashed" ? 19 : 13}` }), + kind === "dashed" + ? h("path", { class: `${P}-tip`, "data-kind": kind, "data-open": "", d: `M12 ${y - 4}L20 ${y}L12 ${y + 4}` }) + : h("path", { class: `${P}-tip`, "data-kind": kind, d: `M20 ${y}L12 ${y - 4}L12 ${y + 4}Z` })); +} + +// ---- Nodes ---- + +function nodeText(P: string, m: Model, n: MNode): VChild[] { + if (n.shape === "decision") return [h("span", { class: `${P}-words` }, h("span", { class: `${P}-name` }, n.name))]; + const kids: VNode[] = []; + if (m.type === "data-flow") kids.push(h("span", { class: `${P}-kind` }, n.kind!, h("span", { class: `${P}-lane-word` }, ` · ${n.laneLabel}`))); + else if (n.kind) kids.push(h("span", { class: `${P}-kind` }, n.kind)); + kids.push(h("span", { class: `${P}-name` }, n.name)); + if (n.detail) kids.push(h("span", { class: `${P}-detail`, "data-mono": n.mono ? "" : undefined }, n.detail)); + return kids; +} + +function tableText(P: string, n: MNode): VChild[] { + return [ + h("span", { class: `${P}-th` }, h("span", { class: `${P}-tname` }, n.name)), + h("span", { class: `${P}-rows` }, (n.columns ?? []).map((c, k) => h("span", { class: `${P}-row`, "data-row": k, "data-key": c.key }, + h("span", { class: `${P}-keyseat` }, c.key ?? ""), + h("span", { class: `${P}-cname` }, c.name), + c.ref ? h("span", { class: `${P}-ctype`, "data-ref": "" }, `→ ${c.ref.table}`) : c.type ? h("span", { class: `${P}-ctype` }, c.type) : null))), + n.more ? h("span", { class: `${P}-more` }, `+ ${n.more} more`) : null, + ]; +} + +const gapVar = (px: number) => { + const step: Record<number, string> = { 32: "space-8", 40: "space-10", 48: "space-12", 64: "space-16" }; + return step[px] ? `var(--basalt-${step[px]})` : `${px}px`; +}; + +interface TreeContext { P: string; ids: ReturnType<typeof idsOf>; level?: number; plan: StackPlan | null; hidden: string } + +function nodeTree(ctx: TreeContext, m: Model, n: MNode, dyn: Dyn): VElement { + const { P } = ctx; + const images = nodesAreImages(m, dyn) || dyn.keep === n.id; + const stops = hasStops(m, dyn); + const style: string[] = [`--_c:${n.col}`, `--_r:${n.row}`, `--_r2:${n.row2 + 1}`]; + if (m.type === "data-flow") style.push(`--_lc:${n.col + 1}`); + if (m.type === "sequence") style.push(`--_c2:${n.col + 1}`); + const plan = ctx.plan; + if (plan && n.i > 0) { + const base = plan.gaps[n.id] ?? 32; + const grow = dyn.grow?.[n.id] ?? 0; + style.push(`--_gap:${grow ? `calc(${gapVar(base)} + var(--basalt-space-4) * ${grow})` : gapVar(base)}`); + } + if (dyn.heights?.[n.id]) style.push(`--_h:${dyn.heights[n.id]}px`); + const tabbable = stops ? (dyn.stop === n.id ? 0 : -1) : dyn.keep === n.id ? -1 : undefined; + return h("div", { + class: `${P}-node`, + "data-node": n.id, + "data-shape": n.shape, + "data-focal": n.focal ? "" : undefined, + "data-branch": n.branch ? "" : undefined, + "data-level": ctx.level, + style: style.join(";"), + role: images ? "img" : undefined, + "aria-label": images ? nodeSentence(m, n) : undefined, + tabindex: tabbable, + }, + n.shape === "decision" ? h("svg", { class: `${P}-diamond`, viewBox: "0 0 100 100", preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false" }, h("path", { d: "M50 0L100 50L50 100L0 50Z" })) : null, + n.shape === "table" ? tableText(P, n) : nodeText(P, m, n)); +} + +function drawingChildren(ctx: TreeContext, m: Model, dyn: Dyn): VNode[] { + const { P } = ctx; + const out: VNode[] = []; + if (m.type === "data-flow") { + out.push(...m.lanes.map((l, k) => h("div", { class: `${P}-lane`, style: `--_r:${k + 1}`, "aria-hidden": "true" }, h("span", { class: `${P}-lane-name` }, l.label)))); + } + if (m.type === "architecture") { + for (const g of m.groups) { + const mem = g.members.map((id) => m.byId.get(id)!); + if (!mem.length) continue; + const c1 = Math.min(...mem.map((n) => n.col)), c2 = Math.max(...mem.map((n) => n.col)), r1 = Math.min(...mem.map((n) => n.row)), r2 = Math.max(...mem.map((n) => n.row2)); + out.push(h("div", { class: `${P}-gbox`, "data-group": g.id, style: `--_c:${c1};--_c2:${c2 + 1};--_r:${r1};--_r2:${r2 + 1}`, "aria-hidden": "true" }, h("span", { class: `${P}-glabel` }, g.label))); + } + } + if (m.type === "sequence") { + out.push(h("ul", { class: `${P}-cast` }, m.nodes.map((n) => h("li", { class: `${P}-actor` }, nodeTree(ctx, m, n, dyn))))); + out.push(sequenceSteps(ctx, m)); + return out; + } + // Nodes in the author's order; a group's members are wrapped once, so the stacked drawing can draw its box around them. + let k = 0; + while (k < m.nodes.length) { + const n = m.nodes[k]!; + const g = n.group ? m.groups.find((x) => x.id === n.group) : undefined; + if (!g) { out.push(nodeTree(ctx, m, n, dyn)); k++; continue; } + const run: MNode[] = []; + while (k < m.nodes.length && m.nodes[k]!.group === g.id) run.push(m.nodes[k++]!); + out.push(h("div", { class: `${P}-group`, "data-group": g.id }, h("span", { class: `${P}-glabel`, "aria-hidden": "true" }, g.label), run.map((x) => nodeTree(ctx, m, x, dyn)))); + } + return out; +} + +function sequenceSteps(ctx: TreeContext, m: Model): VElement { + const { P } = ctx; + const blocks: VNode[] = []; + let list: VElement | null = null; + for (const s of m.steps) { + if ("band" in s) { list = null; blocks.push(h("p", { class: `${P}-band` }, h("span", null, s.band))); continue; } + if (!list) { list = h("ol", { class: `${P}-msgs`, start: s.n }); blocks.push(list); } + const a = m.byId.get(s.from), b = m.byId.get(s.to); + const ca = a?.col ?? 1, cb = b?.col ?? 1; + const self = ca === cb; + const last = self && ca === m.nodes.length; + const word = kindWord(m, s.kind); + list.c.push(h("li", { class: `${P}-msg`, "data-kind": s.kind, "data-from": s.from, "data-to": s.to, "data-self": self ? (last ? "start" : "end") : undefined, style: `--_a:${Math.min(ca, cb)};--_b:${Math.max(ca, cb) + 1}` }, + h("span", { class: `${P}-said` }, h("span", { class: `${P}-num` }, String(s.n)), h("span", { class: `${P}-mlabel` }, s.label)), + h("span", { class: `${P}-route` }, a?.short ?? s.from, " ", inlineArrow(P, s.kind), h("span", { class: ctx.hidden }, " to "), " ", b?.short ?? s.to, word ? ` · ${word}` : ""), + s.note ? h("span", { class: `${P}-note` }, s.note) : null)); + } + return h("div", { class: `${P}-steps` }, blocks); +} + +// ---- The list ("View as list") ---- + +function listTree(P: string, m: Model): VNode[] { + const sub = Math.min(6, m.heading + 1); + const H = (text: string) => h(`h${sub}`, { class: `${P}-list-head` }, text); + const strong = (s: string) => h("strong", null, s); + const code = (s: string) => h("code", { class: `${P}-code` }, s); + const name = (id: string) => m.byId.get(id)?.name ?? id; + const kw = (k: DiagramLineKind) => { const w = kindWord(m, k); return w ? ` (${w})` : ""; }; + const focal = (n: MNode) => (n.focal && m.legend.focal ? ` ${sentence(m.legend.focal)}` : ""); + if (m.type === "architecture") { + const part = (n: MNode) => h("li", null, strong(n.name), n.kind ? `, ${n.kind}` : "", n.detail ? [". ", n.mono ? code(n.detail) : n.detail, /[.!?]$/.test(n.detail) ? "" : "."] : /[.!?]$/.test(n.kind ?? n.name) ? "" : ".", focal(n)); + const out: VNode[] = [H("Parts")]; + const loose = m.nodes.filter((n) => !n.group); + if (loose.length) out.push(h("ul", { class: `${P}-list-items` }, loose.map(part))); + for (const g of m.groups) { + out.push(h("p", { class: `${P}-list-group` }, g.label)); + out.push(h("ul", { class: `${P}-list-items` }, g.members.map((id) => part(m.byId.get(id)!)))); + } + out.push(H("Connections")); + out.push(h("ol", { class: `${P}-list-items` }, m.edges.map((e) => h("li", null, strong(name(e.from)), " to ", strong(name(e.to)), e.label ? [": ", code(e.label)] : "", `${kw(e.kind)}.`)))); + return out; + } + if (m.type === "flowchart") { + const num = (id: string) => (m.byId.get(id)?.i ?? 0) + 1; + return [h("ol", { class: `${P}-list-items` }, m.nodes.map((n) => { + const exits = m.edges.filter((e) => e.from === n.id); + const what = n.shape === "decision" ? "Decision" : n.shape === "terminal" ? (exits.length ? "Start" : "End") : "Step"; + const stop = !n.detail && /[.!?]$/.test(n.name) ? " " : ". "; + return h("li", null, strong(n.name), n.detail ? [", ", n.mono ? code(n.detail) : n.detail] : "", `${stop}${what}.`, focal(n), + exits.length ? h("ul", { class: `${P}-list-exits` }, exits.map((e) => h("li", null, e.label ? `If ${e.label}: go to ${num(e.to)}, ` : `Then: go to ${num(e.to)}, `, strong(name(e.to)), e.kind === "main" && m.legend.main ? ` (${m.legend.main})` : ""))) : null); + }))]; + } + if (m.type === "data-flow") { + return [h("ol", { class: `${P}-list-items` }, m.nodes.map((n) => { + const exits = m.edges.filter((e) => e.from === n.id); + return h("li", null, `${n.laneLabel}: `, strong(n.name), n.detail ? [", ", n.mono ? code(n.detail) : n.detail] : "", ".", focal(n), + exits.length ? [" Then ", ...exits.flatMap((e, j) => [j ? "; " : "", `to step ${m.byId.get(e.to)!.step}, `, strong(name(e.to)), e.label ? [": ", code(e.label)] : "", kw(e.kind)]), "."] : ""); + }))]; + } + if (m.type === "sequence") { + const out: VNode[] = [H("Participants"), h("ul", { class: `${P}-list-items` }, m.nodes.map((n) => h("li", null, strong(n.name), n.kind ? `, ${n.kind}` : "", ".", focal(n))))]; + out.push(H("Messages")); + let list: VElement | null = null; + for (const s of m.steps) { + if ("band" in s) { list = null; out.push(h("p", { class: `${P}-list-group` }, s.band)); continue; } + if (!list) { list = h("ol", { class: `${P}-list-items`, start: s.n }); out.push(list); } + list.c.push(h("li", null, code(s.label), ": ", strong(name(s.from)), " to ", strong(name(s.to)), `${kw(s.kind)}.`, s.note ? ` ${sentence(upperFirst(s.note))}` : "")); + } + return out; + } + // schema + const out: VNode[] = []; + for (const n of m.nodes) { + out.push(h("p", { class: `${P}-list-group` }, code(n.name), focal(n))); + out.push(h("ul", { class: `${P}-list-items` }, [ + ...(n.columns ?? []).map((c) => h("li", null, code(c.name), c.key === "PK" ? ", primary key" : c.key === "FK" ? ", foreign key" : "", c.ref ? [", references ", code(`${c.ref.table}.${c.ref.column}`)] : c.type ? `, ${c.type}` : "")), + ...(n.more ? [h("li", null, `and ${n.more} more ${n.more === 1 ? "column" : "columns"}`)] : []), + ])); + } + return out; +} + +/** The keys sentence (hidden), which describes the drawing to a screen reader. */ +function keysSentence(m: Model): string { + const noun = m.type === "architecture" ? "part" : m.type === "sequence" ? "participant" : m.type === "schema" ? "table" : "step"; + return `Arrow keys move to the next or the previous ${noun}, in the author's order; Home and End go to the ends; Escape clears the trace.`; +} + +/** The key hint's entries: the keys and their words. */ +export function hintEntries(m: Model): Array<{ keys: string[]; words: string }> { + return [{ keys: ["←", "→"], words: stopNoun(m) }, { keys: ["Home", "End"], words: "the ends" }, { keys: ["Esc"], words: "clear" }]; +} + +export interface FigureOptions { + /** The class prefix: "basalt-diagram" in React, "diagram" in the HTML skill. */ + prefix: string; + /** A unique base for the figure's ids. */ + base: string; + /** React's surface level for the nodes (the skill's stylesheet works the level out itself). */ + level?: number; + /** Extra attributes for the root (React's className, the caller's props stay React's). */ + className?: string; + hasSource?: boolean; + /** The class of the hidden text. */ + hiddenClass: string; +} + +/** The whole figure. Before script runs `dyn` is empty; the same tree, with the measured `dyn`, is what script settles on. */ +export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { + const P = o.prefix; + const ids = idsOf(o.base); + const plan = m.type === "sequence" || m.type === "schema" ? null : stackPlan(m); + const ctx: TreeContext = { P, ids, level: o.level, plan, hidden: o.hiddenClass }; + const drawn = dyn.layout === "drawn"; + const stops = hasStops(m, dyn); + const group = m.type === "sequence" || m.type === "schema" ? drawn : true; + const Head = `h${m.heading}`; + const style: string[] = [`--_cols:${columnCount(m)}`]; + if (m.type === "architecture" && m.groups.length) { + // The drawn layout keeps room for a group's box where it reaches an edge: space-8 above, space-4 at a side and below. + const members = m.groups.flatMap((g) => g.members.map((id) => m.byId.get(id)!)); + const pad = (on: boolean, step: string) => (on ? `var(--basalt-space-${step})` : "0px"); + style.push(`--_gpad:${pad(members.some((n) => n.row === 1), "8")} ${pad(members.some((n) => n.col === m.cols), "4")} ${pad(members.some((n) => n.row2 === m.rows), "4")} ${pad(members.some((n) => n.col === 1), "4")}`); + } + if (m.type === "schema" && dyn.track) style.push(`--_track:${dyn.track}px`); + return h("figure", { + class: o.className ? `${P} ${o.className}` : P, + "aria-labelledby": ids.title, + "data-type": m.type, + "data-cols": columnCount(m), + "data-reach": m.type === "architecture" ? groupReach(m) : undefined, + "data-gutter": plan?.gutter ? "" : undefined, + "data-layout": dyn.layout, + "data-measured": dyn.layout ? "" : undefined, + style: style.join(";"), + }, + h("div", { class: `${P}-head` }, h(Head, { id: ids.title, class: `${P}-title` }, m.title), o.hasSource ? h("p", { class: `${P}-source` }, { slot: "source" }) : null), + h("div", { + class: `${P}-drawing`, + role: group ? "group" : undefined, + "aria-roledescription": group ? "diagram" : undefined, + "aria-labelledby": group ? ids.title : undefined, + "aria-describedby": group ? `${ids.summary} ${ids.keys}` : undefined, + "data-stops": stops ? "" : undefined, + }, drawingChildren(ctx, m, dyn), h("div", { class: `${P}-ink`, "aria-hidden": "true" }), h("span", { class: `${P}-ruler`, "aria-hidden": "true" })), + keyTree(P, m), + h("p", { class: `${P}-hint`, "data-kbd-hint": "", "aria-hidden": "true" }, { slot: "hint" }), + h("div", { class: `${P}-foot` }, { slot: "toggle" }), + h("div", { id: ids.list, class: `${P}-list`, hidden: !dyn.open }, listTree(P, m)), + h("span", { id: ids.keys, class: o.hiddenClass }, keysSentence(m)), + h("figcaption", { id: ids.summary, class: `${P}-summary` }, { slot: "summary" })); +} + +export const figureIds = idsOf; + +// ============================================================================================================================================ +// Measuring and drawing (script only) +// ============================================================================================================================================ + +export interface Pt { x: number; y: number } +export interface Rect { l: number; t: number; r: number; b: number } +type Dir = "up" | "down" | "left" | "right"; +export interface GNode { id: string; rect: Rect; shape: Shape; i: number } +export interface GLine { + /** The edge's index, or a message's number in a sequence. */ + i: number; + from: string; + to: string; + kind: DiagramLineKind; + pts: Pt[]; + /** The tip of the head and the way it points. */ + tip: Pt; + dir: Dir; + /** A foreign key's dot, on the row it leaves. */ + dot?: Pt; + width: number; +} +export interface GLabel { i: number; text: string; box: Rect; on: boolean } +export interface GCross { top: number; under: number; at: Pt; underVertical: boolean } +export interface Geo { + w: number; + h: number; + nodes: GNode[]; + lines: GLine[]; + lifelines: Array<{ x: number; y1: number; y2: number }>; + labels: GLabel[]; + crossings: GCross[]; + /** Lines that pass through a node (by edge index), labels that found no seat, words that do not fit their span. */ + through: number[]; + unseated: number[]; + /** The offset of the drawing's origin from the device pixel grid, so lines can be snapped to it. */ + ox: number; + oy: number; +} + +interface Tokens { + space: (step: string) => number; + node: number; table: number; lane: number; step: number; head: number; guide: number; + hair: number; line: number; cut: number; dot: number; dash: number; dashGap: number; + wide: number; cap: number; radius: number; radiusXs: number; +} + +function readTokens(el: Element): Tokens { + const style = getComputedStyle(el); + const px = (name: string, fallback: number) => { const v = parseFloat(style.getPropertyValue(`--basalt-${name}`)); return Number.isFinite(v) ? v : fallback; }; + const cache = new Map<string, number>(); + return { + space: (step) => { if (!cache.has(step)) cache.set(step, px(`space-${step}`, parseFloat(step.replace("-", ".")) * 4)); return cache.get(step)!; }, + node: px("size-diagram-node", 144), table: px("size-diagram-table", 224), lane: px("size-diagram-lane", 120), step: px("size-diagram-step", 56), + head: px("size-diagram-head", 8), guide: px("size-diagram-guide-dash", 4), hair: px("size-hairline", 1), line: px("size-chart-line", 2), + cut: px("size-cut", 2), dot: px("size-dot", 6), dash: px("size-chart-dash", 6), dashGap: px("size-chart-dash-gap", 4), + wide: px("size-breakpoint-container-lg", 640), cap: px("size-breakpoint-container", 480), radius: px("radius-md", 8), radiusXs: px("radius-xs", 4), + }; +} + +const strokeOf = (kind: DiagramLineKind, tk: Tokens) => (kind === "main" ? tk.line : tk.hair); +const rectOf = (el: Element, origin: DOMRect): Rect => { const r = el.getBoundingClientRect(); return { l: r.left - origin.left, t: r.top - origin.top, r: r.right - origin.left, b: r.bottom - origin.top }; }; +const hit = (a: Rect, b: Rect, eps = 0.01) => a.l < b.r - eps && a.r > b.l + eps && a.t < b.b - eps && a.b > b.t + eps; +const grow = (a: Rect, p: number): Rect => ({ l: a.l - p, r: a.r + p, t: a.t - p, b: a.b + p }); + +// ---- Shapes: where a line meets a node, and what a label must keep clear of ---- + +function contour(n: GNode, side: DiagramSide, along: number): Pt { + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + const vertical = side === "top" || side === "bottom"; + if (n.shape === "decision") { + if (vertical) { const x = along; const dy = hh * Math.max(0, 1 - Math.abs(x - cx) / hw); return { x, y: side === "top" ? cy - dy : cy + dy }; } + const y = along; const dx = hw * Math.max(0, 1 - Math.abs(y - cy) / hh); return { x: side === "left" ? cx - dx : cx + dx, y }; + } + if (n.shape === "terminal") { + const rr = Math.min(hw, hh); + if (vertical) { + const x = along; const ex = Math.min(Math.max(x, l + rr), r - rr); const dx = x - ex; + const dy = Math.abs(dx) >= rr ? 0 : Math.sqrt(rr * rr - dx * dx); + return { x, y: Math.abs(dx) < 1e-6 ? (side === "top" ? t : b) : side === "top" ? cy - dy : cy + dy }; + } + const y = along; const dy = y - cy; const dx = Math.abs(dy) >= rr ? 0 : Math.sqrt(rr * rr - dy * dy); + return { x: side === "left" ? l + rr - dx : r - rr + dx, y }; + } + if (vertical) return { x: along, y: side === "top" ? t : b }; + return { x: side === "left" ? l : r, y: along }; +} + +/** Whether a point is inside a node as drawn (a diamond, a capsule, a box), at least `pad` in from its edge. */ +function insideShape(p: Pt, n: GNode, pad: number): boolean { + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + if (n.shape === "decision") return Math.abs(p.x - cx) / hw + Math.abs(p.y - cy) / hh < 1 - pad / Math.min(hw, hh); + if (n.shape === "terminal") { + const rr = Math.min(hw, hh); + const ex = Math.min(Math.max(p.x, l + rr), r - rr); + return Math.hypot(p.x - ex, p.y - cy) < rr - pad; + } + return p.x > l + pad && p.x < r - pad && p.y > t + pad && p.y < b - pad; +} + +/** A box against a node's drawn shape (1.8: a node is tested as it is drawn, never as its bounding box). */ +function boxHitsShape(box: Rect, n: GNode): boolean { + if (!hit(box, n.rect)) return false; + if (n.shape !== "decision" && n.shape !== "terminal") return true; + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + if (n.shape === "decision") { + const px = Math.max(box.l, Math.min(cx, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + return Math.abs(px - cx) / hw + Math.abs(py - cy) / hh < 1 - 1e-6; + } + const rr = Math.min(hh, hw); + if (hit(box, { l: l + rr, r: r - rr, t, b })) return true; + for (const ex of [l + rr, r - rr]) { + const px = Math.max(box.l, Math.min(ex, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + if (Math.hypot(px - ex, py - cy) < rr - 0.01) return true; + } + return false; +} + +function segmentThrough(a: Pt, b: Pt, n: GNode): boolean { + const len = Math.hypot(b.x - a.x, b.y - a.y); + const steps = Math.max(2, Math.ceil(len / 2)); + for (let k = 1; k < steps; k++) { + const f = k / steps; + if (f * len < 1.5 || (1 - f) * len < 1.5) continue; + if (insideShape({ x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }, n, 1)) return true; + } + return false; +} + +// ---- Measuring words ---- + +function ruler(drawing: Element, P: string) { + const el = drawing.querySelector<HTMLElement>(`.${P}-ruler`)!; + const known = new Map<string, number>(); + return (text: string, font: "name" | "name-500" | "mono" | "sans" | "table" | "label") => { + const key = `${font}|${text}`; + if (!known.has(key)) { el.setAttribute("data-f", font); el.textContent = text; known.set(key, el.getBoundingClientRect().width); el.textContent = ""; } + return known.get(key)!; + }; +} +const words = (s?: string) => (s ? s.split(/\s+/).filter(Boolean) : []); + +/** The figure's measured minimums (1.11, rule 2): the widest unbreakable word of any node, a table's widest row, on top of the tokens. */ +function minimums(m: Model, tk: Tokens, measure: ReturnType<typeof ruler>) { + const s = tk.space; + let track = tk.node; + let table = tk.table; + for (const n of m.nodes) { + if (n.shape === "table") { + for (const c of n.columns ?? []) { + const type = c.ref ? `→ ${c.ref.table}` : c.type ?? ""; + const row = s("6") + measure(c.name, "mono") + (type ? s("3") + measure(type, "mono") : 0) + 2 * s("3") + 2 * tk.hair; + table = Math.max(table, Math.ceil(row)); + } + table = Math.max(table, Math.ceil(measure(n.name, "table") + 2 * s("3") + 2 * tk.hair)); + continue; + } + const pad = n.shape === "terminal" ? 2 * s("5") : 2 * s("3"); + let widest = 0; + for (const w of words(n.name)) widest = Math.max(widest, measure(w, n.shape === "decision" ? "name-500" : "name")); + if (m.type !== "data-flow") for (const w of words(n.kind)) widest = Math.max(widest, measure(w, "mono")); + for (const w of words(n.detail)) widest = Math.max(widest, measure(w, n.mono ? "mono" : "sans")); + const need = n.shape === "decision" ? widest / 0.62 : widest + pad + 2 * tk.hair; + track = Math.max(track, Math.ceil(need)); + } + const n = columnCount(m); + let least: number; + if (m.type === "data-flow") least = tk.lane + n * (track + s("12")); + else if (m.type === "schema") least = n * table + (n - 1) * s("12"); + else if (m.type === "sequence") least = n * tk.node + (n - 1) * s("5"); + else least = n * track + (n - 1) * s("16") + groupReach(m) * s("4"); + return { track, table, least: Math.max(tk.wide, least) }; +} + +// ---- Snapping: a 1px line on half pixels, a 2px line on whole ones, in the page's own pixel grid ---- + +function snapper(ox: number, oy: number) { + return { + x: (v: number, w: number) => (w % 2 === 1 ? Math.round(v + ox - 0.5) + 0.5 - ox : Math.round(v + ox) - ox), + y: (v: number, w: number) => (w % 2 === 1 ? Math.round(v + oy - 0.5) + 0.5 - oy : Math.round(v + oy) - oy), + }; +} + +/** A route's last segment's direction, and the line ended on its contour. */ +function finish(pts: Pt[]): Dir { + const a = pts[pts.length - 2]!, b = pts[pts.length - 1]!; + if (Math.abs(a.x - b.x) < 0.01) return b.y > a.y ? "down" : "up"; + return b.x > a.x ? "right" : "left"; +} + +/** Snaps every horizontal run's y and vertical run's x, keeping the ends on their axis. */ +function snapRoute(pts: Pt[], w: number, sn: ReturnType<typeof snapper>): Pt[] { + const q = pts.map((p) => ({ ...p })); + for (let k = 1; k < q.length; k++) { + const a = q[k - 1]!, b = q[k]!; + if (Math.abs(a.x - b.x) < 0.75) { const x = sn.x(a.x, w); a.x = x; b.x = x; } + else if (Math.abs(a.y - b.y) < 0.75) { const y = sn.y(a.y, w); a.y = y; b.y = y; } + } + // Drop points that no longer turn. + const out: Pt[] = [q[0]!]; + for (let k = 1; k < q.length; k++) { + const p = q[k]!, last = out[out.length - 1]!; + if (Math.abs(p.x - last.x) < 0.01 && Math.abs(p.y - last.y) < 0.01) continue; + if (out.length >= 2) { + const prev = out[out.length - 2]!; + const straight = (Math.abs(prev.x - last.x) < 0.01 && Math.abs(last.x - p.x) < 0.01) || (Math.abs(prev.y - last.y) < 0.01 && Math.abs(last.y - p.y) < 0.01); + if (straight) { out[out.length - 1] = p; continue; } + } + out.push(p); + } + return out; +} + +const segmentsOf = (pts: Pt[]) => pts.slice(1).map((p, k) => [pts[k]!, p] as const); + +function findCrossings(lines: GLine[], lit?: (line: GLine) => boolean): GCross[] { + const out: GCross[] = []; + const e = 0.75; + for (let a = 0; a < lines.length; a++) for (let b = a + 1; b < lines.length; b++) { + const A = lines[a]!, B = lines[b]!; + for (const [p1, p2] of segmentsOf(A.pts)) for (const [q1, q2] of segmentsOf(B.pts)) { + const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; + if (aH === bH) continue; + const [h1, h2, v1, v2] = aH ? [p1, p2, q1, q2] : [q1, q2, p1, p2]; + const x = v1.x, y = h1.y; + if (x > Math.min(h1.x, h2.x) + e && x < Math.max(h1.x, h2.x) - e && y > Math.min(v1.y, v2.y) + e && y < Math.max(v1.y, v2.y) - e) { + const hLine = aH ? a : b, vLine = aH ? b : a; + // The horizontal run is on top; a traced line is on top of an untraced one. + let top = hLine, under = vLine; + if (lit) { const lh = lit(lines[hLine]!), lv = lit(lines[vLine]!); if (lv && !lh) { top = vLine; under = hLine; } } + out.push({ top, under, at: { x, y }, underVertical: under === vLine }); + } + } + } + return out; +} + +// ---- The drawn layout (1.6) ---- + +interface Grid { cols: Array<[number, number]>; rows: Array<[number, number]> } +function readGrid(drawing: HTMLElement): Grid { + const cs = getComputedStyle(drawing); + const list = (v: string) => v.split(/\s+/).map(parseFloat).filter((x) => Number.isFinite(x)); + const tracks = (sizes: number[], start: number, gap: number) => { const out: Array<[number, number]> = []; let x = start; for (const s of sizes) { out.push([x, x + s]); x += s + gap; } return out; }; + return { + cols: tracks(list(cs.gridTemplateColumns), parseFloat(cs.paddingLeft) || 0, parseFloat(cs.columnGap) || 0), + rows: tracks(list(cs.gridTemplateRows), parseFloat(cs.paddingTop) || 0, parseFloat(cs.rowGap) || 0), + }; +} + +const isH = (s: DiagramSide) => s === "left" || s === "right"; +const opposite: Record<DiagramSide, DiagramSide> = { top: "bottom", bottom: "top", left: "right", right: "left" }; + +function defaultSides(a: MNode, b: MNode): [DiagramSide, DiagramSide] { + if (a.row === b.row) return b.col > a.col ? ["right", "left"] : ["left", "right"]; + if (a.col === b.col) return b.row > a.row ? ["bottom", "top"] : ["top", "bottom"]; + return [b.col > a.col ? "right" : "left", b.row > a.row ? "top" : "bottom"]; +} + +interface Port { edge: number; end: "from" | "to"; node: MNode; side: DiagramSide; far: MNode; straight: boolean; f: number } + +/** Slots on a side (1.6): one line at the middle; a straight line keeps it and the others take the quarter nearer their far end; two at the quarters; three at quarter, middle, quarter. */ +function assignSlots(m: Model, sides: Array<[DiagramSide, DiagramSide]>, warn: (s: string) => void): Port[] { + const ports: Port[] = []; + m.edges.forEach((e, k) => { + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + const [s1, s2] = sides[k]!; + const straight = (a.row === b.row && isH(s1) && isH(s2) && s1 === opposite[s2]) || (a.col === b.col && !isH(s1) && !isH(s2) && s1 === opposite[s2]); + ports.push({ edge: k, end: "from", node: a, side: s1, far: b, straight, f: 0.5 }, { edge: k, end: "to", node: b, side: s2, far: a, straight, f: 0.5 }); + }); + const bySide = new Map<string, Port[]>(); + for (const p of ports) { const key = `${p.node.id}.${p.side}`; if (!bySide.has(key)) bySide.set(key, []); bySide.get(key)!.push(p); } + for (const [key, list] of bySide) { + if (list[0]!.node.shape === "decision") continue; // a decision's lines leave its four points + const along = (p: Port) => (isH(p.side) ? p.far.row - p.node.row : p.far.col - p.node.col); + const straight = list.filter((p) => p.straight), rest = list.filter((p) => !p.straight); + // Nested: the line whose far end is farther along takes the slot nearer that way. + rest.sort((x, y) => along(x) - along(y) || (isH(x.side) ? x.far.col - y.far.col : x.far.row - y.far.row) * (along(x) < 0 ? 1 : -1)); + if (list.length > 3) warn(`${key.replace(".", " has ")} has ${list.length} lines on one side; more than three is an error: use another side`); + if (straight.length) rest.forEach((p) => { p.f = along(p) < 0 ? 0.25 : 0.75; }); + else if (rest.length === 2) { rest[0]!.f = 0.25; rest[1]!.f = 0.75; } + else if (rest.length === 3) { rest[0]!.f = 0.25; rest[1]!.f = 0.5; rest[2]!.f = 0.75; } + else if (rest.length > 3) rest.forEach((p, j) => { p.f = (j + 1) / (rest.length + 1); }); + } + return ports; +} + +/** The derived ports of a drawn layout (1.6), for the derivation table: each line's sides and its slot on each (a fraction along the side). */ +export function derivedPorts(m: Model): Array<{ from: string; to: string; fromSide: DiagramSide; toSide: DiagramSide; fromSlot: number; toSlot: number }> { + const sides = m.edges.map((e) => { const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; const [d1, d2] = defaultSides(a, b); return [e.fromSide ?? d1, e.toSide ?? d2] as [DiagramSide, DiagramSide]; }); + const ports = assignSlots(m, sides, () => {}); + return m.edges.map((e, k) => ({ from: e.from, to: e.to, fromSide: sides[k]![0], toSide: sides[k]![1], fromSlot: ports.find((p) => p.edge === k && p.end === "from")!.f, toSlot: ports.find((p) => p.edge === k && p.end === "to")!.f })); +} + +function portPoint(n: GNode, side: DiagramSide, f: number): Pt { + const { l, t, r, b } = n.rect; + return isH(side) ? contour(n, side, t + (b - t) * f) : contour(n, side, l + (r - l) * f); +} + +interface DrawnInput { m: Model; tk: Tokens; P: string; drawing: HTMLElement; origin: DOMRect; warn: (s: string) => void } + +function gNodes(m: Model, drawing: HTMLElement, origin: DOMRect, P: string): Map<string, GNode> { + const out = new Map<string, GNode>(); + drawing.querySelectorAll<HTMLElement>(`.${P}-node`).forEach((el) => { + const n = m.byId.get(el.dataset.node!); + if (n) out.set(n.id, { id: n.id, rect: rectOf(el, origin), shape: n.shape, i: n.i }); + }); + return out; +} + +interface Obstacles { rects: Rect[]; heads: Rect[] } + +function headBox(line: GLine, tk: Tokens): Rect { + const L = tk.head, W = tk.head / 2, { x, y } = line.tip; + if (line.dir === "down") return { l: x - W, r: x + W, t: y - L, b: y }; + if (line.dir === "up") return { l: x - W, r: x + W, t: y, b: y + L }; + if (line.dir === "right") return { l: x - L, r: x, t: y - W, b: y + W }; + return { l: x, r: x + L, t: y - W, b: y + W }; +} + +const segRect = (a: Pt, b: Pt, w: number): Rect => ({ l: Math.min(a.x, b.x) - w / 2, r: Math.max(a.x, b.x) + w / 2, t: Math.min(a.y, b.y) - w / 2, b: Math.max(a.y, b.y) + w / 2 }); + +/** Seats labels by 1.8: runs longest first, their clear shaft's middle then thirds; on the line, above, below (or beside). */ +function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacles, groups: Rect[], bounds: Rect, tk: Tokens, measure: ReturnType<typeof ruler>): { labels: GLabel[]; unseated: number[] } { + const s = tk.space; + const placed: Rect[] = []; + const labels: GLabel[] = []; + const unseated: number[] = []; + const GROW = s("1"); + const order = lines.filter((l) => m.edges[l.i]?.label).sort((a, b) => Number(m.edges[b.i]!.kind === "main") - Number(m.edges[a.i]!.kind === "main") || a.i - b.i); + for (const line of order) { + const text = m.edges[line.i]!.label!; + const w = measure(text, "label"), hgt = 16; + const last = line.pts.length - 2; + const runs: Array<{ horiz: boolean; c: number; p: number; q: number; len: number; pri: number }> = []; + segmentsOf(line.pts).forEach(([a, b], k) => { + const horiz = Math.abs(a.y - b.y) < 0.01; + const s0 = horiz ? a.x : a.y; + let t0 = horiz ? b.x : b.y; + const dir = Math.sign(t0 - s0) || 1; + if (k === last) t0 -= dir * tk.head; // the clear shaft: the run without the head + let parts: Array<[number, number]> = [[s0, t0]]; + for (const g of groups) for (const edgeAt of horiz ? [g.l, g.r] : [g.t, g.b]) { + const c = horiz ? a.y : a.x; + const within = horiz ? c > g.t && c < g.b : c > g.l && c < g.r; + if (!within) continue; + parts = parts.flatMap(([p, q]) => (edgeAt > Math.min(p, q) + 1 && edgeAt < Math.max(p, q) - 1 ? [[p, edgeAt], [edgeAt, q]] as Array<[number, number]> : [[p, q]] as Array<[number, number]>)); + } + const outside = (p: number, q: number) => { const mid = (p + q) / 2; const pt = horiz ? { x: mid, y: a.y } : { x: a.x, y: mid }; return !groups.some((g) => pt.x > g.l && pt.x < g.r && pt.y > g.t && pt.y < g.b); }; + for (const [p, q] of parts) runs.push({ horiz, c: horiz ? a.y : a.x, p, q, len: Math.abs(q - p), pri: parts.length > 1 && outside(p, q) ? 1 : 0 }); + }); + runs.sort((x, y) => y.pri - x.pri || y.len - x.len); + let chosen: { box: Rect; on: boolean } | null = null; + const clear = (box: Rect) => { + const G = grow(box, GROW); + if (box.l < bounds.l || box.r > bounds.r || box.t < bounds.t || box.b > bounds.b) return false; + if (nodes.some((n) => boxHitsShape(G, n))) return false; + if (placed.some((p) => hit(G, p))) return false; + if (obstacles.heads.some((h0) => hit(G, h0))) return false; + if (obstacles.rects.some((r) => hit(G, r))) return false; + return !lines.some((o) => o.i !== line.i && segmentsOf(o.pts).some(([a, b]) => hit(G, segRect(a, b, o.width)))); + }; + for (const run of runs) { + for (const f of [1 / 2, 1 / 3, 2 / 3]) { + const mid = run.p + (run.q - run.p) * f; + const cands: Array<{ box: Rect; on: boolean }> = []; + const off = s("2") + line.width / 2; + if (run.horiz) { + if (run.len >= w + 2 * s("1") + s("3-5")) cands.push({ box: { l: mid - w / 2 - s("1"), r: mid + w / 2 + s("1"), t: run.c - hgt / 2, b: run.c + hgt / 2 }, on: true }); + cands.push({ box: { l: mid - w / 2, r: mid + w / 2, t: run.c - off - hgt, b: run.c - off }, on: false }); + cands.push({ box: { l: mid - w / 2, r: mid + w / 2, t: run.c + off, b: run.c + off + hgt }, on: false }); + } else { + if (run.len >= hgt + s("3")) cands.push({ box: { l: run.c - w / 2 - s("1"), r: run.c + w / 2 + s("1"), t: mid - hgt / 2, b: mid + hgt / 2 }, on: true }); + cands.push({ box: { l: run.c + off, r: run.c + off + w, t: mid - hgt / 2, b: mid + hgt / 2 }, on: false }); + cands.push({ box: { l: run.c - off - w, r: run.c - off, t: mid - hgt / 2, b: mid + hgt / 2 }, on: false }); + } + chosen = cands.find((c) => clear(c.box)) ?? null; + if (chosen) break; + } + if (chosen) break; + } + if (!chosen) { unseated.push(line.i); continue; } + placed.push(chosen.box); + labels.push({ i: line.i, text, box: chosen.box, on: chosen.on }); + } + return { labels, unseated }; +} + +function obstaclesOf(drawing: HTMLElement, origin: DOMRect, P: string, rowGap: number): { obstacles: Obstacles; groups: Rect[] } { + const rects: Rect[] = []; + const groups: Rect[] = []; + drawing.querySelectorAll<HTMLElement>(`.${P}-gbox, .${P}-group`).forEach((el) => { + if (el.getClientRects().length === 0 || getComputedStyle(el).display === "contents") return; + const g = rectOf(el, origin); + groups.push(g); + rects.push({ l: g.l, r: g.r, t: g.t, b: g.t + 1 }, { l: g.l, r: g.r, t: g.b - 1, b: g.b }, { l: g.l, r: g.l + 1, t: g.t, b: g.b }, { l: g.r - 1, r: g.r, t: g.t, b: g.b }); + const label = el.querySelector(`:scope > .${P}-glabel`); + if (label && label.getClientRects().length) rects.push(rectOf(label, origin)); + }); + drawing.querySelectorAll<HTMLElement>(`.${P}-lane`).forEach((el, k) => { + if (!el.getClientRects().length) return; + const lane = rectOf(el, origin); + if (k > 0) rects.push({ l: lane.l, r: lane.r, t: lane.t - rowGap / 2 - 0.5, b: lane.t - rowGap / 2 + 0.5 }); + const name = el.querySelector(`.${P}-lane-name`); + if (name) rects.push(rectOf(name, origin)); + }); + return { obstacles: { rects, heads: [] }, groups }; +} + +function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Geo { + const { m, tk, P, drawing, origin, warn } = input; + const s = tk.space; + const map = gNodes(m, drawing, origin, P); + const nodes = [...map.values()]; + const grid = readGrid(drawing); + const ox = origin.left - Math.floor(origin.left), oy = origin.top - Math.floor(origin.top); + const sn = snapper(ox, oy); + const W = drawing.clientWidth, H = drawing.clientHeight; + const trackOf = (n: MNode) => (m.type === "data-flow" ? n.col + 1 : n.col); + const rowGap = parseFloat(getComputedStyle(drawing).rowGap) || 0; + const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], ox, oy }; + + if (m.type === "sequence") return sequenceGeometry(input, geo, sn); + + // Sides and slots. + let sides: Array<[DiagramSide, DiagramSide]>; + let ports: Port[] = []; + if (m.type === "schema") { + sides = m.edges.map((e) => { + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + if (a.col === b.col) { const side: DiagramSide = a.col === m.cols ? "left" : "right"; return [side, side]; } + return b.col > a.col ? ["right", "left"] : ["left", "right"]; + }); + } else { + sides = m.edges.map((e) => { const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; const [d1, d2] = defaultSides(a, b); return [e.fromSide ?? d1, e.toSide ?? d2]; }); + ports = assignSlots(m, sides, warn); + } + + // End points. + const rowY = (id: string, row: number) => { + const el = drawing.querySelector<HTMLElement>(`.${P}-node[data-node="${CSS.escape(id)}"] .${P}-row[data-row="${row}"]`); + if (!el) return 0; + const r = rectOf(el, origin); + return (r.t + r.b) / 2; + }; + const ends = m.edges.map((e, k) => { + const [s1, s2] = sides[k]!; + const a = map.get(e.from)!, b = map.get(e.to)!; + const w = strokeOf(e.kind, tk); + if (e.fk) { + const y1 = sn.y(rowY(e.from, e.fromRow!), w), y2 = sn.y(rowY(e.to, e.toRow!), w); + return { p1: { x: s1 === "right" ? a.rect.r : a.rect.l, y: y1 }, p2: { x: s2 === "right" ? b.rect.r : b.rect.l, y: y2 } }; + } + const f1 = ports.find((p) => p.edge === k && p.end === "from")!.f, f2 = ports.find((p) => p.edge === k && p.end === "to")!.f; + let p1 = portPoint(a, s1, f1), p2 = portPoint(b, s2, f2); + // Snap the axis the line leaves and enters on; a straight line shares one. + if (isH(s1)) p1 = { ...p1, y: sn.y(p1.y, w) }; else p1 = { ...p1, x: sn.x(p1.x, w) }; + if (isH(s2)) p2 = { ...p2, y: sn.y(p2.y, w) }; else p2 = { ...p2, x: sn.x(p2.x, w) }; + if (isH(s1) && isH(s2) && Math.abs(p1.y - p2.y) < 1.01) p2 = { ...p2, y: p1.y }; + if (!isH(s1) && !isH(s2) && Math.abs(p1.x - p2.x) < 1.01) p2 = { ...p2, x: p1.x }; + // The end that a snap moved sits on the contour again. + p1 = isH(s1) ? contour(a, s1, p1.y) : contour(a, s1, p1.x); + p2 = isH(s2) ? contour(b, s2, p2.y) : contour(b, s2, p2.x); + return { p1, p2 }; + }); + + // Jogs: which gutter each two-elbow line turns in, and which lines share a lane (lines to one port, a foreign key's bus). + const jogs = new Map<string, { span: [number, number]; vertical: boolean; members: Map<string, number[]> }>(); + m.edges.forEach((e, k) => { + const [s1, s2] = sides[k]!; + const { p1, p2 } = ends[k]!; + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + let key: string | null = null, span: [number, number] | null = null, vertical = false; + if (isH(s1) && isH(s2) && s1 !== s2 && Math.abs(p1.y - p2.y) > 0.5) { + const ti = trackOf(b); + const leftSide = s2 === "left"; + const t1 = grid.cols[(leftSide ? ti - 1 : ti) - 1], t2 = grid.cols[(leftSide ? ti : ti + 1) - 1]; + if (t1 && t2) { key = `c${leftSide ? ti - 1 : ti}`; span = [t1[1], t2[0]]; vertical = true; } + void a; + } else if (!isH(s1) && !isH(s2) && s1 !== s2 && Math.abs(p1.x - p2.x) > 0.5) { + const topSide = s2 === "top"; + const ri = topSide ? b.row - 1 : b.row2; + const r1 = grid.rows[ri - 1], r2 = grid.rows[ri]; + if (r1 && r2) { key = `r${ri}`; span = [r1[1], r2[0]]; vertical = false; } + } + if (!key || !span) return; + if (!jogs.has(key)) jogs.set(key, { span, vertical, members: new Map() }); + const port = `${e.to}.${s2}.${Math.round(vertical ? p2.y : p2.x)}`; + const g = jogs.get(key)!; + if (!g.members.has(port)) g.members.set(port, []); + g.members.get(port)!.push(k); + }); + + const lanes = new Map<number, number>(); + const route = (k: number): Pt[] => { + const [s1, s2] = sides[k]!; + const { p1, p2 } = ends[k]!; + if (isH(s1) && isH(s2)) { + if (s1 === s2) { const x = s1 === "right" ? Math.max(p1.x, p2.x) + s("4") : Math.min(p1.x, p2.x) - s("4"); return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; } + if (Math.abs(p1.y - p2.y) <= 0.5) return [p1, { x: p2.x, y: p1.y }]; + const x = lanes.get(k) ?? (p1.x + p2.x) / 2; + return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; + } + if (!isH(s1) && !isH(s2)) { + if (s1 === s2) { const y = s1 === "bottom" ? Math.max(p1.y, p2.y) + s("4") : Math.min(p1.y, p2.y) - s("4"); return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; } + if (Math.abs(p1.x - p2.x) <= 0.5) return [p1, { x: p1.x, y: p2.y }]; + const y = lanes.get(k) ?? (p1.y + p2.y) / 2; + return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; + } + if (isH(s1)) return [p1, { x: p2.x, y: p1.y }, p2]; + return [p1, { x: p1.x, y: p2.y }, p2]; + }; + const build = (): GLine[] => m.edges.map((e, k) => { + const w = strokeOf(e.kind, tk); + const pts = snapRoute(route(k), w, sn); + return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), dot: e.fk ? pts[0] : undefined, width: w }; + }); + const score = (lines: GLine[]) => findCrossings(lines).length * 1000 + throughOf(lines, nodes, m).length; + // Each gutter: its lanes evenly spaced (at least space-3 apart), in the order that crosses least. + // Lanes are needed only where jogs run beside each other: jogs whose runs along the gutter do not overlap each take its middle. + const runOf = (members: number[], vertical: boolean): [number, number] => { + const ys = members.flatMap((k) => { const { p1, p2 } = ends[k]!; return vertical ? [p1.y, p2.y] : [p1.x, p2.x]; }); + return [Math.min(...ys), Math.max(...ys)]; + }; + for (const [, g] of jogs) { + const ports = [...g.members.values()].map((members) => ({ members, run: runOf(members, g.vertical) })).sort((a, b) => a.run[0] - b.run[0]); + const clusters: Array<typeof ports> = []; + for (const p of ports) { + const last = clusters[clusters.length - 1]; + // Two jogs share the middle only when a clear space-8 parts them; closer, they would read as one line. + if (last && last.some((q) => q.run[0] < p.run[1] + s("8") && p.run[0] < q.run[1] + s("8"))) last.push(p); else clusters.push([p]); + } + for (const cluster of clusters) { + const groupsOf = cluster.map((c) => c.members); + const count = groupsOf.length; + const step = (g.span[1] - g.span[0]) / (count + 1); + if (step < s("3")) warn(`a gutter holds ${count} lanes side by side, closer than space-3`); + let best: number[][] = groupsOf, bestScore = Infinity; + for (const perm of permutations(groupsOf)) { + perm.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); + const sc = score(build()); + if (sc < bestScore) { bestScore = sc; best = perm; } + } + best.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); + } + } + geo.lines = build(); + // Relations two columns apart are not drawn: the row writes its target (1.12). + if (m.type === "schema") { + geo.lines = geo.lines.filter((l) => { + const a = m.byId.get(l.from)!, b = m.byId.get(l.to)!; + if (Math.abs(a.col - b.col) > 1) { warn(`${l.from} to ${l.to} is two columns apart, so its line is not drawn; its row still writes the target`); return false; } + return true; + }); + } + geo.crossings = findCrossings(geo.lines); + geo.through = throughOf(geo.lines, nodes, m); + const { obstacles, groups } = obstaclesOf(drawing, origin, P, rowGap); + obstacles.heads = geo.lines.map((l) => headBox(l, tk)); + const seats = seatLabels(m, geo.lines, nodes, obstacles, groups, { l: 0, t: 0, r: W, b: H }, tk, measure); + geo.labels = seats.labels; + geo.unseated = seats.unseated; + return geo; +} + +function* permutations<T>(items: T[]): Generator<T[]> { + if (items.length <= 1) { yield items.slice(); return; } + if (items.length > 5) { yield items.slice(); return; } + for (let k = 0; k < items.length; k++) { + const rest = items.slice(0, k).concat(items.slice(k + 1)); + for (const p of permutations(rest)) yield [items[k]!, ...p]; + } +} + +function throughOf(lines: GLine[], nodes: GNode[], m: Model): number[] { + const out: number[] = []; + for (const l of lines) { + const segs = segmentsOf(l.pts); + if (nodes.some((n) => segs.some(([a, b]) => segmentThrough(a, b, n)))) out.push(l.i); + } + void m; + return out; +} + +function sequenceGeometry(input: DrawnInput, geo: Geo, sn: ReturnType<typeof snapper>): Geo { + const { m, tk, P, drawing, origin } = input; + const s = tk.space; + const heads = new Map<string, Rect>(); + drawing.querySelectorAll<HTMLElement>(`.${P}-node`).forEach((el) => heads.set(el.dataset.node!, rectOf(el, origin))); + const steps = drawing.querySelector(`.${P}-steps`); + const bottom = steps ? rectOf(steps, origin).b : geo.h; + const xOf = (id: string) => { const r = heads.get(id); return r ? sn.x((r.l + r.r) / 2, tk.hair) : 0; }; + for (const n of m.nodes) { const r = heads.get(n.id); if (r) geo.lifelines.push({ x: xOf(n.id), y1: r.b, y2: bottom }); } + const spanOf = (n: MNode) => { const r = heads.get(n.id)!; return r; }; + drawing.querySelectorAll<HTMLElement>(`.${P}-msg`).forEach((li) => { + const from = li.dataset.from!, to = li.dataset.to!; + const kind = (li.dataset.kind ?? "plain") as DiagramLineKind; + const w = strokeOf(kind, tk); + const r = rectOf(li, origin); + const y = sn.y((r.t + r.b) / 2, w); + const num = Number(li.querySelector(`.${P}-num`)?.textContent ?? 0); + const x1 = xOf(from), x2 = xOf(to); + let pts: Pt[]; + if (from === to) { + const out = li.dataset.self === "start" ? -s("6") : s("6"); + const yt = sn.y(y - s("2"), w), yb = sn.y(y + s("2"), w); + pts = [{ x: x1, y: yt }, { x: sn.x(x1 + out, w), y: yt }, { x: sn.x(x1 + out, w), y: yb }, { x: x1, y: yb }]; + } else pts = [{ x: x1, y }, { x: x2, y }]; + geo.lines.push({ i: num, from, to, kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), width: w }); + // Every label and note fits between the lifelines it spans, space-2 clear each side (1.11, rule 3). + const said = li.querySelector(`.${P}-said`), note = li.querySelector(`.${P}-note`); + const a = m.byId.get(from), b = m.byId.get(to); + if (!a || !b) return; + const room = from === to + ? (() => { const next = m.nodes[a.i + (li.dataset.self === "start" ? -1 : 1)]; const limit = next ? xOf(next.id) : li.dataset.self === "start" ? 0 : geo.w; return Math.abs(limit - x1) - s("6") - s("2-5") - s("2"); })() + : Math.abs(x2 - x1) - 2 * s("2"); + const need = Math.max(said ? said.getBoundingClientRect().width : 0, note ? note.getBoundingClientRect().width : 0); + if (need > room + 0.5) geo.unseated.push(num); + void spanOf; + }); + return geo; +} + +// ---- The stacked drawing (1.13) ---- + +function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, plan: StackPlan): { geo: Geo; grow: Record<string, number> } { + const { m, tk, P, drawing, origin, warn } = input; + const s = tk.space; + const map = gNodes(m, drawing, origin, P); + const nodes = [...map.values()]; + const ox = origin.left - Math.floor(origin.left), oy = origin.top - Math.floor(origin.top); + const sn = snapper(ox, oy); + const W = drawing.clientWidth, H = drawing.clientHeight; + const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], ox, oy }; + const growBy: Record<string, number> = {}; + if (m.type === "sequence" || m.type === "schema") return { geo, grow: growBy }; + // The right edge a spine card has where each card sits (the group's inside, or the drawing's less the gutter). + const columnRight = new Map<string, number>(); + drawing.querySelectorAll<HTMLElement>(`.${P}-node`).forEach((el) => { + const parent = el.parentElement!; + const pr = rectOf(parent, origin); + const cs = getComputedStyle(parent); + columnRight.set(el.dataset.node!, pr.r - (parseFloat(cs.paddingRight) || 0) - (parseFloat(cs.borderRightWidth) || 0)); + }); + const order = m.nodes; + const card = (i: number) => map.get(order[i]!.id)!; + const labelSeats: Array<{ k: number; box: Rect; on: boolean; card: string }> = []; + const lineW = (k: number) => strokeOf(m.edges[k]!.kind, tk); + m.edges.forEach((e, k) => { + const r = plan.routes[k]!; + const a = map.get(e.from)!, b = map.get(e.to)!; + const w = lineW(k); + let pts: Pt[] = []; + const label = e.label; + const lw = label ? measure(label, "label") : 0; + const lh = 16; + const turn = s("4"); + if (r === "down" || r === "up") { + const lo = Math.max(a.rect.l, b.rect.l), hi = Math.min(a.rect.r, b.rect.r); + const x = sn.x((lo + hi) / 2, w); + pts = r === "down" ? [contour(a, "bottom", x), contour(b, "top", x)] : [contour(a, "top", x), contour(b, "bottom", x)]; + if (label) { + // Centred on the stem's clear shaft, with a plate; a stem split by a group's boundary takes its outside part. + let y1 = Math.min(pts[0]!.y, pts[1]!.y), y2 = Math.max(pts[0]!.y, pts[1]!.y); + if (r === "down") y2 -= tk.head; else y1 += tk.head; + const boxes = [...drawing.querySelectorAll<HTMLElement>(`.${P}-group`)].map((g) => rectOf(g, origin)); + let parts: Array<[number, number]> = [[y1, y2]]; + for (const g of boxes) for (const at of [g.t, g.b]) parts = parts.flatMap(([p, q]) => (at > p + 1 && at < q - 1 ? [[p, at], [at, q]] as Array<[number, number]> : [[p, q]] as Array<[number, number]>)); + const inside = (p: number, q: number) => boxes.some((g) => (p + q) / 2 > g.t && (p + q) / 2 < g.b && x > g.l && x < g.r); + if (parts.length > 1) { + const outer = parts.filter(([p, q]) => !inside(p, q)); + const pick = (outer.length ? outer : parts).reduce((best, part) => (part[1] - part[0] > best[1] - best[0] ? part : best)); + [y1, y2] = pick; + } + const cy = (y1 + y2) / 2; + labelSeats.push({ k, box: { l: x - lw / 2 - s("1"), r: x + lw / 2 + s("1"), t: cy - lh / 2, b: cy + lh / 2 }, on: true, card: r === "down" ? e.to : e.from }); + } + } else if (r === "trunk" || r === "rail") { + const x = sn.x(Math.max(a.rect.l, r === "rail" ? b.rect.l : a.rect.l) + (r === "trunk" ? s("8") : s("3")), w); + const start = contour(a, "bottom", x); + if (r === "rail") { + pts = [start, contour(b, "top", x)]; + if (label) { const cy = b.rect.t - s("6"); labelSeats.push({ k, box: { l: x + s("2-5"), r: x + s("2-5") + lw, t: cy - lh / 2, b: cy + lh / 2 }, on: false, card: e.to }); } + } else { + const ex = sn.x(b.rect.l + s("6"), w); + const ty = sn.y(b.rect.t - turn, w); + pts = [start, { x, y: ty }, { x: ex, y: ty }, contour(b, "top", ex)]; + if (label) labelSeats.push({ k, box: { l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }, on: false, card: e.to }); + } + } else { + // An end line: out the end side, along the end lane or the gutter, into the card's top (down) or bottom (up), space-6 in from its end edge. + const right = Math.min(columnRight.get(e.from) ?? W, columnRight.get(e.to) ?? W); + const laneX = sn.x(plan.gutter ? right + (plan.lanes[k] ? 2 * s("3-5") : s("3-5")) : right - s("2-5"), w); + const yExit = sn.y(a.rect.t + (a.rect.b - a.rect.t) * plan.exits[k]!, w); + const exit = contour(a, "right", yExit); + const ex = sn.x(b.rect.r - s("6"), w); + const down = r === "end-down"; + const ty = sn.y(down ? b.rect.t - turn : b.rect.b + turn, w); + pts = [exit, { x: laneX, y: exit.y }, { x: laneX, y: ty }, { x: ex, y: ty }, contour(b, down ? "top" : "bottom", ex)]; + if (label) labelSeats.push({ k, box: { l: ex - s("2-5") - lw, r: ex - s("2-5"), t: ty - lh / 2, b: ty + lh / 2 }, on: false, card: down ? e.to : order[b.i + 1]?.id ?? e.to }); + } + const snapped = snapRoute(pts, w, sn); + geo.lines.push({ i: k, from: e.from, to: e.to, kind: e.kind, pts: snapped, tip: snapped[snapped.length - 1]!, dir: finish(snapped), width: w }); + }); + geo.crossings = findCrossings(geo.lines); + geo.through = throughOf(geo.lines, nodes, m); + // Fixed seats, checked: a label that does not fit takes a line of its own above its card, and the gap grows 16. + const { obstacles, groups } = obstaclesOf(drawing, origin, P, 0); + obstacles.heads = geo.lines.map((l) => headBox(l, tk)); + const placed: Rect[] = []; + const bounds = { l: 0, t: 0, r: W, b: H }; + for (const seat of labelSeats) { + const line = geo.lines.find((l) => l.i === seat.k)!; + const G = grow(seat.box, s("1")); + const ownHead = headBox(line, tk); + const bad = seat.box.l < bounds.l - 0.5 || seat.box.r > bounds.r + 0.5 + || nodes.some((n) => boxHitsShape(G, n)) + || placed.some((p) => hit(G, p)) + || obstacles.heads.some((h0) => h0 !== ownHead && hit(G, h0)) + || obstacles.rects.some((r) => hit(G, r)) + || geo.lines.some((o) => o.i !== seat.k && segmentsOf(o.pts).some(([a, b]) => hit(G, segRect(a, b, o.width)))); + if (bad) { growBy[seat.card] = (growBy[seat.card] ?? 0) + 1; geo.unseated.push(seat.k); } + placed.push(seat.box); + geo.labels.push({ i: seat.k, text: m.edges[seat.k]!.label!, box: seat.box, on: seat.on }); + } + void groups; + if (plan.third) warn("three end lines overlap in the stacked drawing; two lanes is the most (use the drawn layout or reorder)"); + return { geo, grow: growBy }; +} + +// ---- The ink: one string of SVG and labels, the same in React and in the skill ---- + +function pathD(pts: Pt[], radius: number): string { + const f = (n: number) => String(Math.round(n * 100) / 100); + let d = `M${f(pts[0]!.x)} ${f(pts[0]!.y)}`; + for (let k = 1; k < pts.length - 1; k++) { + const a = pts[k - 1]!, b = pts[k]!, c = pts[k + 1]!; + const d1 = Math.hypot(b.x - a.x, b.y - a.y), d2 = Math.hypot(c.x - b.x, c.y - b.y); + const r = Math.min(radius, d1 / 2, d2 / 2); + if (r < 0.5) { d += `L${f(b.x)} ${f(b.y)}`; continue; } + const p0 = { x: b.x + ((a.x - b.x) / d1) * r, y: b.y + ((a.y - b.y) / d1) * r }; + const p3 = { x: b.x + ((c.x - b.x) / d2) * r, y: b.y + ((c.y - b.y) / d2) * r }; + d += `L${f(p0.x)} ${f(p0.y)}Q${f(b.x)} ${f(b.y)} ${f(p3.x)} ${f(p3.y)}`; + } + const z = pts[pts.length - 1]!; + return `${d}L${f(z.x)} ${f(z.y)}`; +} + +const unit: Record<Dir, Pt> = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } }; + +function lineMarkup(P: string, l: GLine, tk: Tokens, maskId: string | null, radius: number): string { + const u = unit[l.dir]; + const open = l.kind === "dashed"; + const L = tk.head, W2 = tk.head / 2; + // The head's tip touches the contour; the line stops under the head (an open head's shaft runs on into it). + const stop = open ? 1 : L - 1; + const pts = l.pts.map((p) => ({ ...p })); + const last = pts[pts.length - 1]!; + last.x -= u.x * stop; last.y -= u.y * stop; + const bx = l.tip.x - u.x * L, by = l.tip.y - u.y * L; + const px = -u.y * W2, py = u.x * W2; + const r2 = (n: number) => Math.round(n * 100) / 100; + const head = open + ? `<path class="${P}-tip" data-kind="${l.kind}" data-open="" d="M${r2(bx + px)} ${r2(by + py)}L${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx - px)} ${r2(by - py)}"/>` + : `<path class="${P}-tip" data-kind="${l.kind}" d="M${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx + px)} ${r2(by + py)}L${r2(bx - px)} ${r2(by - py)}Z"/>`; + const dot = l.dot ? `<circle class="${P}-dot" cx="${r2(l.dot.x)}" cy="${r2(l.dot.y)}" r="${tk.dot / 2}"/>` : ""; + return `<g class="${P}-edge" data-edge="${l.i}" data-from="${escapeHtml(l.from)}" data-to="${escapeHtml(l.to)}"><path class="${P}-line" data-kind="${l.kind}" d="${pathD(pts, radius)}"${maskId ? ` mask="url(#${maskId})"` : ""}/>${head}${dot}</g>`; +} + +function masksMarkup(P: string, geo: Geo, tk: Tokens, base: string): { defs: string; ids: Map<number, string> } { + const ids = new Map<number, string>(); + const byLine = new Map<number, GCross[]>(); + for (const c of geo.crossings) { if (!byLine.has(c.under)) byLine.set(c.under, []); byLine.get(c.under)!.push(c); } + let defs = ""; + for (const [k, list] of byLine) { + const id = `${base}-cut-${k}`; + ids.set(k, id); + const holes = list.map((c) => { + const top = geo.lines[c.top]!, under = geo.lines[c.under]!; + const across = top.width / 2 + tk.cut, beside = under.width / 2 + 1; + return c.underVertical + ? `<rect x="${c.at.x - beside}" y="${c.at.y - across}" width="${2 * beside}" height="${2 * across}" fill="black"/>` + : `<rect x="${c.at.x - across}" y="${c.at.y - beside}" width="${2 * across}" height="${2 * beside}" fill="black"/>`; + }).join(""); + defs += `<mask id="${id}" maskUnits="userSpaceOnUse" x="0" y="0" width="${geo.w}" height="${geo.h}"><rect x="0" y="0" width="${geo.w}" height="${geo.h}" fill="white"/>${holes}</mask>`; + } + void P; + return { defs, ids }; +} + +/** The drawing's ink: the SVG (lines, heads, dots, lifelines, cuts) and the labels, as one string. */ +export function inkHtml(P: string, geo: Geo, tk: Tokens, base: string): string { + const { defs, ids } = masksMarkup(P, geo, tk, base); + const lifelines = geo.lifelines.map((l) => `<path class="${P}-life" d="M${l.x} ${l.y1}V${l.y2}"/>`).join(""); + const lines = geo.lines.map((l, k) => lineMarkup(P, l, tk, ids.get(k) ?? null, l.from === l.to ? tk.radiusXs : tk.radius)).join(""); + const svg = `<svg class="${P}-svg" width="${geo.w}" height="${geo.h}" viewBox="0 0 ${geo.w} ${geo.h}" focusable="false">${defs ? `<defs>${defs}</defs>` : ""}${lifelines}<g class="${P}-edges">${lines}</g></svg>`; + const labels = geo.labels.map((l) => `<span class="${P}-label" data-edge="${l.i}"${l.on ? ' data-on=""' : ""} style="left:${Math.round(l.box.l * 100) / 100}px;top:${Math.round(l.box.t * 100) / 100}px;width:${Math.round((l.box.r - l.box.l) * 100) / 100}px">${escapeHtml(l.text)}</span>`).join(""); + return svg + labels; +} + +// ---- Laying a figure out ---- + +export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Tokens | null } + +/** + * Measures the figure and settles its layout (1.11): the drawn layout when the figure is at least 640 wide, every track holds its widest + * word, every label seats and no line passes through a node; otherwise the stack. `apply` writes a state into the DOM (the same markup the + * tree gives for it), so each try is measured as it would be drawn. + */ +export function measureFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn: (s: string) => void): Measured { + const drawing = fig.querySelector<HTMLElement>(`.${P}-drawing`); + if (!drawing) return { dyn: current, geo: null, ink: "", tokens: null }; + const tk = readTokens(fig); + const measure = ruler(drawing, P); + const mins = minimums(m, tk, measure); + const W = fig.clientWidth; + const focusedId = (() => { const a = document.activeElement as HTMLElement | null; return a && drawing.contains(a) && a.dataset.node ? a.dataset.node : undefined; })(); + const stopOf = (d: Dyn): Dyn => { + if (!hasStops(m, d)) return { ...d, stop: d.stop ?? m.nodes[0]?.id, keep: focusedId && !(d.layout === "drawn") ? focusedId : undefined }; + return { ...d, stop: d.stop && m.byId.has(d.stop) ? d.stop : m.nodes[0]?.id, keep: undefined }; + }; + const heightsFor = (d: Dyn): Dyn => { + if (m.type !== "flowchart") return d; + apply({ ...d, heights: undefined }); + const heights: Record<string, number> = {}; + drawing.querySelectorAll<HTMLElement>(`.${P}-node[data-shape="decision"]`).forEach((el) => { + const words = el.querySelector(`.${P}-words`); + if (!words) return; + const nr = el.getBoundingClientRect(), wr = words.getBoundingClientRect(); + const box = { w: wr.width + 2 * tk.space("2-5"), h: wr.height + 2 * tk.space("2") }; + const a = nr.width / 2; + const denom = 1 - box.w / 2 / a; + const half = denom > 0.05 ? box.h / 2 / denom : box.h * 10; + heights[el.dataset.node!] = Math.max(tk.space("16"), Math.ceil(nr.width / 5), Math.ceil(2 * half)); + }); + return { ...d, heights }; + }; + const input = (): DrawnInput => ({ m, tk, P, drawing, origin: drawing.getBoundingClientRect(), warn }); + if (W >= mins.least) { + let d = stopOf({ ...current, layout: "drawn", grow: undefined, track: undefined }); + d = heightsFor(d); + apply(d); + const geo = drawnGeometry(input(), measure); + if (!geo.through.length && !geo.unseated.length) { + if (geo.crossings.length) warn(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the drawn layout: ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); + return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; + } + // At a width the figure should fit by its tokens and words, a failure is the author's to fix. + if (geo.through.length) warn(`the drawn layout does not fit at ${Math.round(W)}px: ${geo.through.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", ")} would pass through a node`); + if (geo.unseated.length) warn(`the drawn layout does not fit at ${Math.round(W)}px: no clean seat for ${geo.unseated.map((k) => (m.type === "sequence" ? `message ${k}` : `"${m.edges[k]?.label}"`)).join(", ")}`); + } + let d = stopOf({ ...current, layout: "stacked", heights: undefined, grow: {}, track: m.type === "schema" ? mins.table : undefined }); + d = heightsFor(d); + apply(d); + if (m.type === "sequence" || m.type === "schema") return { dyn: d, geo: null, ink: "", tokens: tk }; + const plan = stackPlan(m); + let out = stackedGeometry(input(), measure, plan); + for (let tries = 0; tries < 6 && Object.keys(out.grow).length; tries++) { + const grown = { ...(d.grow ?? {}) }; + for (const [id, n] of Object.entries(out.grow)) grown[id] = (grown[id] ?? 0) + n; + d = { ...d, grow: grown }; + apply(d); + out = stackedGeometry(input(), measure, plan); + } + const geo = out.geo; + if (geo.crossings.length) warn(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the stacked drawing (each is cut): ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); + if (geo.through.length) warn(`in the stacked drawing ${geo.through.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", ")} passes through a node`); + return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; +} + +function lineName(m: Model, l: GLine): string { + const a = m.byId.get(l.from)?.name ?? l.from, b = m.byId.get(l.to)?.name ?? l.to; + return `${a} to ${b}`; +} + +// ============================================================================================================================================ +// Tracing and the keys +// ============================================================================================================================================ + +/** + * Traces one node (or clears with null): its lines take the main ink and keep their width, dash and head, their labels lift to primary, + * every other line dims, and the node and its neighbours lift their rim (1.15). Cuts are worked out again, a traced line on top. + */ +export function applyTrace(fig: HTMLElement, P: string, geo: Geo | null, tokens: Tokens | null, base: string, id: string | null): void { + const near = new Set<string>(); + if (id) { + near.add(id); + for (const l of geo?.lines ?? []) { if (l.from === id) near.add(l.to); if (l.to === id) near.add(l.from); } + } + fig.toggleAttribute("data-tracing", Boolean(id)); + fig.querySelectorAll<HTMLElement>(`.${P}-node`).forEach((el) => el.toggleAttribute("data-near", near.has(el.dataset.node!))); + if (!geo || !tokens) return; + const lit = (l: GLine) => Boolean(id) && (l.from === id || l.to === id); + const edges = fig.querySelector(`.${P}-edges`); + const groupEls = new Map<string, Element>(); + fig.querySelectorAll(`.${P}-edge`).forEach((g) => groupEls.set(g.getAttribute("data-edge")!, g)); + for (const l of geo.lines) { + const g = groupEls.get(String(l.i)); + if (!g) continue; + g.toggleAttribute("data-lit", lit(l)); + g.toggleAttribute("data-dim", Boolean(id) && !lit(l)); + } + fig.querySelectorAll<HTMLElement>(`.${P}-label`).forEach((el) => { + const l = geo.lines.find((x) => String(x.i) === el.dataset.edge); + el.toggleAttribute("data-lit", Boolean(l && lit(l))); + }); + // A traced line is drawn on top, and the cuts are worked out again. + if (edges) for (const l of geo.lines) if (lit(l)) { const g = groupEls.get(String(l.i)); if (g) edges.appendChild(g); } + const crossings = findCrossings(geo.lines, lit); + const { defs, ids } = masksMarkup(P, { ...geo, crossings }, tokens, base); + const svg = fig.querySelector(`.${P}-svg`); + if (!svg) return; + let defsEl = svg.querySelector("defs"); + if (!defsEl && defs) { defsEl = document.createElementNS("http://www.w3.org/2000/svg", "defs"); svg.insertBefore(defsEl, svg.firstChild); } + if (defsEl) defsEl.innerHTML = defs; + geo.lines.forEach((l, k) => { + const path = groupEls.get(String(l.i))?.querySelector(`.${P}-line`); + if (!path) return; + const mask = ids.get(k); + if (mask) path.setAttribute("mask", `url(#${mask})`); else path.removeAttribute("mask"); + }); +} + +/** The node a key moves to (1.14): → ↓ the next, ← ↑ the one before, in the author's order, stopping at the ends; Home and End the ends. */ +export function keyTarget(m: Model, from: string, key: string): string | null { + const i = m.byId.get(from)?.i ?? 0; + const n = m.nodes.length; + let to: number; + if (key === "ArrowRight" || key === "ArrowDown") to = i + 1; + else if (key === "ArrowLeft" || key === "ArrowUp") to = i - 1; + else if (key === "Home") to = 0; + else if (key === "End") to = n - 1; + else return null; + return m.nodes[Math.max(0, Math.min(n - 1, to))]!.id; +} + +/** + * Brings the DOM's attributes in line with the tree for a new state: the figure, the drawing, every node and the list, walked in step. Text, + * slots and the ink are left alone; the attributes tracing sets (data-lit, data-dim, data-near, data-tracing) are kept. + */ +const MANAGED = ["data-layout", "data-measured", "role", "aria-roledescription", "aria-labelledby", "aria-describedby", "aria-label", "tabindex", "data-stops", "hidden"]; +const MANAGED_STYLE = ["--_track", "--_h", "--_gap"]; +export function syncAttributes(el: Element, v: VNode): void { + if (typeof v === "string" || "slot" in v) return; + // Only what a state changes is managed: an attribute or style the caller added (an id, a class, its own style) stays. + for (const name of MANAGED) if (!(name in v.a) || v.a[name] === undefined || v.a[name] === null || v.a[name] === false) el.removeAttribute(name); + for (const [k, value] of Object.entries(v.a)) { + if (k === "class") continue; + if (k === "style") { + const style = (el as HTMLElement).style; + const decls = new Map(String(value ?? "").split(";").map((d) => { const at = d.indexOf(":"); return [d.slice(0, at).trim(), d.slice(at + 1).trim()] as const; }).filter(([n]) => n)); + for (const [n, val] of decls) if (style.getPropertyValue(n).trim() !== val) style.setProperty(n, val); + for (const n of MANAGED_STYLE) if (!decls.has(n)) style.removeProperty(n); + continue; + } + if (value === undefined || value === null || value === false) { el.removeAttribute(k); continue; } + const s = value === true ? "" : String(value); + if (el.getAttribute(k) !== s) el.setAttribute(k, s); + } + if (v.t === "svg" || (typeof v.a.class === "string" && /-(ink|ruler)$/.test(v.a.class))) return; + const kids = v.c.filter((c): c is VElement => typeof c !== "string" && !("slot" in c)); + const els = [...el.children]; + if (v.c.some((c) => typeof c !== "string" && "slot" in c)) return; + kids.forEach((c, k) => { const child = els[k]; if (child && child.tagName.toLowerCase() === c.t) syncAttributes(child, c); }); +} diff --git a/packages/react/src/diagram-figure.tsx b/packages/react/src/diagram-figure.tsx new file mode 100644 index 00000000..3f5bc813 --- /dev/null +++ b/packages/react/src/diagram-figure.tsx @@ -0,0 +1,196 @@ +import * as React from "react"; + +import { Kbd } from "./kbd"; +import { usePanelLevel } from "./layers"; +import { + applyTrace, buildModel, figureTree, hasStops, hintEntries, keyTarget, measureFigure, syncAttributes, +} from "./diagram-core"; +import type { DiagramLegend, DiagramSpec, Dyn, Measured, VNode } from "./diagram-core"; + +// The figure every diagram shares (DECISIONS 269): the title, the drawing, the key, the key hint, the required summary and "View as list". +// Not exported from the package: each of the five diagrams is its own module on top of it. The markup is the engine's tree, so it is the +// HTML skill's markup too; the drawing is measured before the first paint and again when the figure's width changes or its fonts arrive. + +export interface DiagramFigureProps extends Omit<React.ComponentProps<"figure">, "children" | "title"> { + /** What the diagram shows. Required: it names the figure and its drawing. */ + title: string; + /** The heading level of the title (default 3); the list's sub-headings are one level under it. */ + heading?: 2 | 3 | 4 | 5 | 6; + /** Where it came from, under the title. */ + source?: React.ReactNode; + /** Required. The sentence under the drawing that says what it shows. */ + summary: React.ReactNode; + /** The words for the marks. The key is built from what is drawn; main, dashed and the focal node must have words when drawn. */ + legend?: DiagramLegend; +} + +const P = "basalt-diagram"; +declare const process: { env: { NODE_ENV?: string } }; + +const CAMEL: Record<string, string> = { class: "className", tabindex: "tabIndex", for: "htmlFor", viewbox: "viewBox" }; +function styleObject(style: string): Record<string, string> { + const out: Record<string, string> = {}; + for (const part of style.split(";")) { + const at = part.indexOf(":"); + if (at > 0) out[part.slice(0, at).trim()] = part.slice(at + 1).trim(); + } + return out; +} + +/** The engine's tree as React elements; slots are React's own, the ink is set as HTML (it is the same string the skill writes). */ +function toReact(v: VNode, slots: Record<string, React.ReactNode>, ink: string, root?: Record<string, unknown>): React.ReactNode { + if (typeof v === "string") return v; + if ("slot" in v) return slots[v.slot] ?? null; + const props: Record<string, unknown> = {}; + for (const [k, value] of Object.entries(v.a)) { + if (value === undefined || value === null || value === false) continue; + if (k === "style") props.style = styleObject(String(value)); + else props[CAMEL[k] ?? k] = value === true ? (k === "hidden" ? true : "") : value; + } + if (typeof v.a.class === "string" && v.a.class.endsWith("-ink")) { + props.dangerouslySetInnerHTML = { __html: ink }; + return React.createElement(v.t, props); + } + if (root) Object.assign(props, root, { className: [props.className, root.className].filter(Boolean).join(" "), style: { ...(props.style as object), ...(root.style as object) } }); + return React.createElement(v.t, props, ...v.c.map((c) => toReact(c, slots, ink))); +} + +let warned: Set<string> | undefined; +function warnOnce(component: string, message: string) { + warned ??= new Set(); + const key = `${component}: ${message}`; + if (warned.has(key)) return; + warned.add(key); + console.warn(`Basalt ${key}`); +} + +export interface DiagramFigureInternalProps extends DiagramFigureProps { + spec: DiagramSpec; + component: string; +} + +export function DiagramFigure({ spec, component, title: _title, heading: _heading, legend: _legend, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ...props }: DiagramFigureInternalProps) { + const base = `dg${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; + const level = usePanelLevel(); + const model = React.useMemo(() => buildModel(spec), [spec]); + const figRef = React.useRef<HTMLElement>(null); + const [dyn, setDyn] = React.useState<Dyn>({}); + const [ink, setInk] = React.useState(""); + const measured = React.useRef<Measured | null>(null); + const dynRef = React.useRef(dyn); + dynRef.current = dyn; + const [focusTrace, setFocusTrace] = React.useState<string | null>(null); + const [hoverTrace, setHoverTrace] = React.useState<string | null>(null); + const options = React.useMemo(() => ({ prefix: P, base, level, hasSource: source !== undefined && source !== null, hiddenClass: "basalt-visually-hidden" }), [base, level, source]); + + // Development only: a bundler that sets NODE_ENV to production drops this block, strings included. + React.useEffect(() => { + if (process.env.NODE_ENV !== "production") for (const w of model.warnings) warnOnce(component, w); + }, [model, component]); + + const measure = React.useCallback(() => { + const fig = figRef.current; + if (!fig) return; + const warn = (message: string) => { if (process.env.NODE_ENV !== "production") warnOnce(component, message); }; + const result = measureFigure(fig, model, P, base, dynRef.current, (d) => syncAttributes(fig, figureTree(model, d, options)), warn); + measured.current = result; + dynRef.current = result.dyn; + setDyn(result.dyn); + setInk(result.ink); + }, [model, base, options, component]); + + // Measured before the first paint, then whenever the figure's width changes or the real faces arrive. + React.useLayoutEffect(() => { + measure(); + const fig = figRef.current; + if (!fig) return undefined; + let width = fig.clientWidth; + let frame = 0; + const observer = new ResizeObserver(() => { + if (Math.abs(fig.clientWidth - width) < 0.5) return; + width = fig.clientWidth; + cancelAnimationFrame(frame); + frame = requestAnimationFrame(measure); + }); + observer.observe(fig); + let live = true; + document.fonts?.ready.then(() => { if (live) measure(); }); + return () => { live = false; observer.disconnect(); cancelAnimationFrame(frame); }; + }, [measure]); + + const trace = focusTrace ?? hoverTrace; + React.useLayoutEffect(() => { + const fig = figRef.current; + if (fig) applyTrace(fig, P, measured.current?.geo ?? null, measured.current?.tokens ?? null, base, trace); + }, [trace, ink, base]); + + const nodeOf = (target: EventTarget | null) => { + const el = (target as HTMLElement | null)?.closest?.<HTMLElement>(`.${P}-node`); + return el && figRef.current?.contains(el) ? el : null; + }; + const stops = hasStops(model, dyn); + + const root = { + ref: figRef, + className, + style, + ...props, + onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => { + onKeyDown?.(event); + const node = nodeOf(event.target); + if (!node || event.defaultPrevented) return; + if (event.key === "Escape") { if (focusTrace || hoverTrace) { event.preventDefault(); setFocusTrace(null); setHoverTrace(null); } return; } + if (!stops) return; + const to = keyTarget(model, node.dataset.node!, event.key); + if (!to) return; + event.preventDefault(); + const next = { ...dynRef.current, stop: to }; + dynRef.current = next; + setDyn(next); + figRef.current?.querySelector<HTMLElement>(`.${P}-node[data-node="${CSS.escape(to)}"]`)?.focus({ preventScroll: false }); + }, + onFocus: (event: React.FocusEvent<HTMLElement>) => { + onFocus?.(event); + const node = nodeOf(event.target); + if (!node) return; + const id = node.dataset.node!; + // Tracing follows the keyboard's focus (:focus-visible), so a press that focuses a node traces nothing. + setFocusTrace(node.matches(":focus-visible") ? id : null); + if (stops && dynRef.current.stop !== id) { const next = { ...dynRef.current, stop: id }; dynRef.current = next; setDyn(next); } + }, + onBlur: (event: React.FocusEvent<HTMLElement>) => { + onBlur?.(event); + const left = nodeOf(event.target); + if (!left) return; + if (!nodeOf(event.relatedTarget)) setFocusTrace(null); + // A node kept as a stop in a stack with no stops stops being one once focus has left it. + if (dynRef.current.keep === left.dataset.node) { const next = { ...dynRef.current, keep: undefined }; dynRef.current = next; setDyn(next); } + }, + onPointerOver: (event: React.PointerEvent<HTMLElement>) => { + onPointerOver?.(event); + if (event.pointerType !== "mouse" || !window.matchMedia("(hover: hover)").matches) return; + const node = nodeOf(event.target); + setHoverTrace(node && hasStops(model, dynRef.current) ? node.dataset.node! : null); + }, + onPointerLeave: (event: React.PointerEvent<HTMLElement>) => { onPointerLeave?.(event); setHoverTrace(null); }, + }; + + const toggle = ( + <button + type="button" + className="basalt-button basalt-diagram-toggle" + data-variant="secondary" + data-size="sm" + aria-expanded={Boolean(dyn.open)} + aria-controls={`${base}-list`} + onClick={() => { const next = { ...dynRef.current, open: !dynRef.current.open }; dynRef.current = next; setDyn(next); }} + > + <span className="basalt-button-label">{dyn.open ? "Hide the list" : "View as list"}</span> + </button> + ); + const hint = hintEntries(model).map((entry) => ( + <span key={entry.words}>{entry.keys.map((k, i) => <React.Fragment key={k}>{i ? " " : null}<Kbd>{k}</Kbd></React.Fragment>)} {entry.words}</span> + )); + const tree = figureTree(model, dyn, options); + return toReact(tree, { source, summary, hint, toggle }, ink, root) as React.ReactElement; +} diff --git a/packages/react/src/flowchart-diagram.tsx b/packages/react/src/flowchart-diagram.tsx new file mode 100644 index 00000000..4fb3f4fb --- /dev/null +++ b/packages/react/src/flowchart-diagram.tsx @@ -0,0 +1,22 @@ +import * as React from "react"; + +import { DiagramFigure } from "./diagram-figure"; +import type { DiagramFigureProps } from "./diagram-figure"; +import type { DiagramEdge, DiagramShapeLabels, FlowchartNode } from "./diagram-core"; + +export type { DiagramEdge, DiagramLegend, DiagramLineKind, DiagramShapeLabels, DiagramSide, FlowchartNode } from "./diagram-core"; + +export interface FlowchartDiagramProps extends DiagramFigureProps { + /** The steps in the author's order; the first is the start. A shape carries the type: a step (the default), a decision or a terminal. */ + nodes: FlowchartNode[]; + /** The lines, by node id. A branch's label is its condition; `main` is the usual path. */ + edges: DiagramEdge[]; + /** The key's words for the shapes (default "Start or end", "Step", "Decision"). */ + shapeLabels?: DiagramShapeLabels; +} + +/** A flowchart (DECISIONS 269): shape carries type, so every shape has a 3:1 contour; a decision is a diamond behind its words. */ +export function FlowchartDiagram({ nodes, edges, shapeLabels, title, heading, legend, ...props }: FlowchartDiagramProps) { + const spec = React.useMemo(() => ({ type: "flowchart" as const, title, heading, legend, nodes, edges, shapeLabels }), [title, heading, legend, nodes, edges, shapeLabels]); + return <DiagramFigure {...props} title={title} heading={heading} legend={legend} spec={spec} component="FlowchartDiagram" />; +} diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index d4214b8b..402c7606 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -91,6 +91,16 @@ export { Prose } from "./prose"; export { ChartGroup, TimeChart } from "./chart"; export { trailingMean } from "./trailing-mean"; export type { ChartGroupProps, ChartKind, ChartLaneGeometry, ChartPlan, ChartSeries, TimeChartProps } from "./chart"; +export { ArchitectureDiagram } from "./architecture-diagram"; +export type { ArchitectureDiagramProps, ArchitectureNode, DiagramEdge, DiagramFigureProps, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramNode, DiagramSide } from "./architecture-diagram"; +export { FlowchartDiagram } from "./flowchart-diagram"; +export type { DiagramShapeLabels, FlowchartDiagramProps, FlowchartNode } from "./flowchart-diagram"; +export { DataFlowDiagram } from "./data-flow-diagram"; +export type { DataFlowDiagramProps, DataFlowLane, DataFlowNode } from "./data-flow-diagram"; +export { SequenceDiagram } from "./sequence-diagram"; +export type { SequenceDiagramProps, SequenceParticipant, SequenceStep } from "./sequence-diagram"; +export { SchemaDiagram } from "./schema-diagram"; +export type { SchemaColumn, SchemaDiagramProps, SchemaTable } from "./schema-diagram"; export { PhaseChart } from "./phase-chart"; export type { PhaseCall, PhaseChartProps } from "./phase-chart"; export { ShareBar } from "./share-bar"; diff --git a/packages/react/src/schema-diagram.tsx b/packages/react/src/schema-diagram.tsx new file mode 100644 index 00000000..0a4038d8 --- /dev/null +++ b/packages/react/src/schema-diagram.tsx @@ -0,0 +1,21 @@ +import * as React from "react"; + +import { DiagramFigure } from "./diagram-figure"; +import type { DiagramFigureProps } from "./diagram-figure"; +import type { SchemaTable } from "./diagram-core"; + +export type { DiagramLegend, SchemaColumn, SchemaTable } from "./diagram-core"; + +export interface SchemaDiagramProps extends DiagramFigureProps { + /** + * The tables in the author's order. A foreign key is `references: "incidents.id"` on its column and nothing else: the row's "→ incidents", + * the line, the sentence and the list all come from it. The referenced column must be one of the shown columns. + */ + tables: SchemaTable[]; +} + +/** A database schema (DECISIONS 269): table cards with keys and a few columns; drawn, a line from each foreign key to the key it references. */ +export function SchemaDiagram({ tables, title, heading, legend, ...props }: SchemaDiagramProps) { + const spec = React.useMemo(() => ({ type: "schema" as const, title, heading, legend, tables }), [title, heading, legend, tables]); + return <DiagramFigure {...props} title={title} heading={heading} legend={legend} spec={spec} component="SchemaDiagram" />; +} diff --git a/packages/react/src/sequence-diagram.tsx b/packages/react/src/sequence-diagram.tsx new file mode 100644 index 00000000..3186ee71 --- /dev/null +++ b/packages/react/src/sequence-diagram.tsx @@ -0,0 +1,20 @@ +import * as React from "react"; + +import { DiagramFigure } from "./diagram-figure"; +import type { DiagramFigureProps } from "./diagram-figure"; +import type { SequenceParticipant, SequenceStep } from "./diagram-core"; + +export type { DiagramLegend, DiagramLineKind, SequenceParticipant, SequenceStep } from "./diagram-core"; + +export interface SequenceDiagramProps extends DiagramFigureProps { + /** The participants, start to end. `short` names one in the stacked list. */ + participants: SequenceParticipant[]; + /** The messages in order, numbered through; `{ band }` names a phase. A reply or a stream is `dashed`. */ + steps: SequenceStep[]; +} + +/** A sequence diagram (DECISIONS 269): a head and a lifeline a participant, a 56px row a message; stacked, a numbered list. */ +export function SequenceDiagram({ participants, steps, title, heading, legend, ...props }: SequenceDiagramProps) { + const spec = React.useMemo(() => ({ type: "sequence" as const, title, heading, legend, participants, steps }), [title, heading, legend, participants, steps]); + return <DiagramFigure {...props} title={title} heading={heading} legend={legend} spec={spec} component="SequenceDiagram" />; +} diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css index 2c3052e0..34983fcb 100644 --- a/packages/react/src/styles/components.css +++ b/packages/react/src/styles/components.css @@ -4178,6 +4178,437 @@ .basalt-chart-table tbody th { background-color: Canvas; background-image: none; } } + /* ---- Diagrams (DECISIONS 269, revised by 270): boxes and the lines between them ---- + Monochrome: nothing takes a colour, the accent or a status. Nodes are panels one level above what the figure sits in; one may be + focal, in inverted ink. Three lines named by their look (main 2px primary, plain 1px secondary, dashed 1px 6 on 4 off), and the key + says what each means. The drawing is laid out in real CSS pixels at its measured width; nothing scrolls sideways. + The drawn layout and the stack differ by one switch, --_drawn, on the drawing: empty when drawn, `initial` when stacked. Each property + that differs reads it as `--_d-x: var(--_drawn) <drawn value>` and `prop: var(--_d-x, <stacked value>)`, so one declaration serves + the script's choice (data-layout) and, before script, the least-width rules below. --_ground is the fill the figure sits on: plates and + cuts are drawn in it. The implementation hasn't been reviewed. */ + .basalt-diagram { + --_ground: var(--_surface, var(--basalt-surface-page)); + container-type: inline-size; + display: flex; + flex-direction: column; + gap: var(--basalt-space-4); + width: 100%; + min-width: 0; + margin: 0; + font-family: var(--basalt-font-family-sans); + } + .basalt-diagram-head { display: flex; flex-direction: column; gap: var(--basalt-space-0-5); min-width: 0; } + .basalt-diagram-title { margin: 0; color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-md-tracking); } + .basalt-diagram-source { margin: 0; color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + + /* The drawing. Stacked: one column in the author's order, at most size-breakpoint-container wide on the start edge (the schema's grid of + cards takes the figure's width). Drawn: the author's grid. */ + .basalt-diagram-drawing { + --_drawn: initial; + --_d-display: var(--_drawn) grid; + --_d-max: var(--_drawn) none; + --_d-cols: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr)); + --_d-gap: var(--_drawn) var(--_row-gap) var(--_col-gap); + --_d-pad: var(--_drawn) var(--_gpad, 0); + --_row-gap: var(--basalt-space-12); + --_col-gap: var(--basalt-space-16); + position: relative; + box-sizing: border-box; + display: var(--_d-display, flex); + flex-direction: column; + grid-template-columns: var(--_d-cols, none); + gap: var(--_d-gap, 0); + width: 100%; + max-width: var(--_d-max, var(--basalt-size-breakpoint-container)); + min-width: 0; + padding: var(--_d-pad, 0 var(--_gutter, 0) 0 0); + } + .basalt-diagram[data-layout="drawn"] > .basalt-diagram-drawing { --_drawn: ; } + .basalt-diagram[data-layout="stacked"] > .basalt-diagram-drawing { --_drawn: initial; } + .basalt-diagram[data-gutter] > .basalt-diagram-drawing { --_gutter: var(--basalt-space-10); } + .basalt-diagram[data-type="data-flow"] > .basalt-diagram-drawing { + --_d-cols: var(--_drawn) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr)); + --_row-gap: var(--basalt-space-10); + --_col-gap: var(--basalt-space-12); + } + .basalt-diagram[data-type="schema"] > .basalt-diagram-drawing { + --_row-gap: var(--basalt-space-8); + --_col-gap: var(--basalt-space-12); + display: grid; + grid-template-columns: var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr))); + gap: var(--_d-gap, var(--basalt-space-4)); + align-items: start; + max-width: none; + } + .basalt-diagram[data-type="sequence"] > .basalt-diagram-drawing { display: flex; gap: 0; } + + /* A node: a panel with the rim, radius 8, space-2-5 by space-3; its kind, name and detail wrap inside it, with break-word only as the net. */ + .basalt-diagram-node { + --_d-gc: var(--_drawn) var(--_c); + --_d-gr: var(--_drawn) var(--_r) / var(--_r2); + --_d-mt: var(--_drawn) 0; + --_d-align: var(--_drawn) center; + position: relative; + z-index: 1; + box-sizing: border-box; + display: flex; + flex-direction: column; + min-width: 0; + grid-column: var(--_d-gc, auto); + grid-row: var(--_d-gr, auto); + align-self: var(--_d-align, stretch); + margin-block-start: var(--_d-mt, var(--_gap, 0)); + padding: var(--basalt-space-2-5) var(--basalt-space-3); + background: var(--_surface, var(--basalt-surface-1)); + border: var(--basalt-size-hairline) solid var(--basalt-border-rim); + border-top-color: var(--basalt-border-rim-top); + border-radius: var(--basalt-radius-md); + color: var(--basalt-text-primary); + overflow-wrap: break-word; + outline: none; + transition: border-color var(--basalt-duration-fast) var(--basalt-ease-out); + } + .basalt-diagram[data-type="data-flow"] .basalt-diagram-node { --_d-gc: var(--_drawn) var(--_lc); } + .basalt-diagram-node[data-branch] { --_d-mi: var(--_drawn) 0; margin-inline: var(--_d-mi, var(--basalt-space-12) var(--basalt-space-6)); } + .basalt-diagram-node:focus-visible { z-index: 2; outline: var(--basalt-size-focus-width) solid var(--basalt-border-focus); outline-offset: var(--basalt-size-focus-offset); } + .basalt-diagram-node[data-near] { border-color: var(--basalt-border-hover); } + .basalt-diagram-kind { color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-lane-word { --_d-lw: var(--_drawn) none; display: var(--_d-lw, inline); } + .basalt-diagram-name { color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-detail { margin-block-start: var(--basalt-space-0-5); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-detail[data-mono] { font-family: var(--basalt-font-family-mono); } + + /* The focal node: inverted ink; its quiet lines at opacity-amount, at full strength under more contrast. */ + .basalt-diagram-node[data-focal] { background: var(--basalt-diagram-focal); border-color: var(--basalt-diagram-focal); } + .basalt-diagram-node[data-focal] :is(.basalt-diagram-name, .basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { color: var(--basalt-diagram-focal-ink); } + .basalt-diagram-node[data-focal] :is(.basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { opacity: var(--basalt-opacity-amount); } + + /* A flowchart's shapes carry its types, so each has a 3:1 contour in place of the rim: one colour on every side. */ + .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal]) { border-color: var(--basalt-diagram-structure); } + .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal])[data-near] { border-color: var(--basalt-text-secondary); } + .basalt-diagram-node[data-shape="terminal"] { align-items: center; padding-inline: var(--basalt-space-5); border-radius: var(--basalt-radius-full); text-align: center; } + /* A decision: a diamond behind its words, the words at 500 within 62% of its width. Before script it is a plain box of its words at least + space-16 tall; once measured it is as tall as its words need, never under space-16 nor flatter than 5:1. */ + .basalt-diagram-node[data-shape="decision"] { justify-content: center; align-items: center; height: var(--_h, auto); min-height: var(--basalt-space-16); padding: var(--basalt-space-2) var(--basalt-space-2-5); text-align: center; } + .basalt-diagram-words { position: relative; max-width: 62%; } + .basalt-diagram-node[data-shape="decision"] .basalt-diagram-name { font-weight: var(--basalt-font-weight-medium); text-wrap: balance; } + .basalt-diagram-diamond { display: none; position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } + .basalt-diagram-diamond path { fill: var(--_surface, var(--basalt-surface-1)); stroke: var(--basalt-diagram-structure); stroke-width: var(--basalt-size-hairline); vector-effect: non-scaling-stroke; transition: stroke var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram[data-measured] .basalt-diagram-node[data-shape="decision"] { background: none; border-color: transparent; } + .basalt-diagram[data-measured] .basalt-diagram-node[data-shape="decision"] .basalt-diagram-diamond { display: block; } + .basalt-diagram-node[data-shape="decision"][data-near] .basalt-diagram-diamond path { stroke: var(--basalt-text-secondary); } + .basalt-diagram-node[data-shape="decision"][data-focal] .basalt-diagram-diamond path { fill: var(--basalt-diagram-focal); stroke: var(--basalt-diagram-focal); } + + /* A group: a transparent box with a 1px dashed structure edge, radius 12, its label at the top start. Stacked, the box wraps its members; + drawn, the members sit in the author's grid and the box spans their cells, space-4 outside them and space-8 above. */ + .basalt-diagram-group { + --_d-gd: var(--_drawn) contents; + position: relative; + box-sizing: border-box; + display: var(--_d-gd, flex); + flex-direction: column; + margin-block-start: var(--basalt-space-12); + padding: var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5); + border: var(--basalt-size-hairline) dashed var(--basalt-diagram-structure); + border-radius: var(--basalt-radius-lg); + } + .basalt-diagram-group:first-child { margin-block-start: 0; } + .basalt-diagram-group > .basalt-diagram-glabel + .basalt-diagram-node { --_d-mt: 0; } + .basalt-diagram-glabel { position: absolute; top: var(--basalt-space-2); inset-inline-start: var(--basalt-space-3); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); white-space: nowrap; } + .basalt-diagram-group > .basalt-diagram-glabel { --_d-gl: var(--_drawn) none; display: var(--_d-gl, block); } + .basalt-diagram-gbox { + --_d-gb: var(--_drawn) block; + position: relative; + display: var(--_d-gb, none); + grid-column: var(--_c) / var(--_c2); + grid-row: var(--_r) / var(--_r2); + margin: calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4)); + border: var(--basalt-size-hairline) dashed var(--basalt-diagram-structure); + border-radius: var(--basalt-radius-lg); + pointer-events: none; + } + + /* A data flow's lanes: bands ruled apart with the divider, centred in the row gap, the first unruled; the name carries the lane. */ + .basalt-diagram-lane { --_d-ln: var(--_drawn) flex; position: relative; display: var(--_d-ln, none); grid-column: 1 / -1; grid-row: var(--_r); align-items: center; pointer-events: none; } + .basalt-diagram-lane + .basalt-diagram-lane::before { content: ""; position: absolute; inset-inline: 0; top: calc(-1 * var(--basalt-space-5)); border-top: var(--basalt-size-hairline) solid var(--basalt-border-divider); } + .basalt-diagram-lane-name { box-sizing: border-box; width: var(--basalt-size-diagram-lane); padding-inline-end: var(--basalt-space-3); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + + /* The ink: lines, heads, dots, lifelines and labels, drawn by script over the drawing (and under the nodes). */ + .basalt-diagram-ink { position: absolute; inset: 0; z-index: 0; pointer-events: none; } + .basalt-diagram-svg { position: absolute; top: 0; left: 0; overflow: visible; } + .basalt-diagram-ruler { position: absolute; visibility: hidden; white-space: pre; pointer-events: none; } + .basalt-diagram-ruler[data-f="name"] { font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-ruler[data-f="name-500"] { font: var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-ruler[data-f="table"] { font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-ruler:is([data-f="mono"], [data-f="label"]) { font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-ruler[data-f="sans"] { font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-line { fill: none; stroke: var(--basalt-diagram-edge); stroke-width: var(--basalt-size-hairline); transition: stroke var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram-line[data-kind="main"] { stroke: var(--basalt-diagram-edge-main); stroke-width: var(--basalt-size-chart-line); } + .basalt-diagram-line[data-kind="dashed"] { stroke-dasharray: var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap); stroke-linecap: butt; } + .basalt-diagram-tip { fill: var(--basalt-diagram-edge); transition: fill var(--basalt-duration-fast) var(--basalt-ease-out), stroke var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram-tip[data-kind="main"] { fill: var(--basalt-diagram-edge-main); } + .basalt-diagram-tip[data-open] { fill: none; stroke: var(--basalt-diagram-edge); stroke-width: var(--basalt-size-hairline); stroke-linecap: round; stroke-linejoin: round; } + .basalt-diagram-dot { fill: var(--basalt-diagram-edge); } + .basalt-diagram-life { fill: none; stroke: var(--basalt-diagram-structure); stroke-width: var(--basalt-size-hairline); stroke-dasharray: var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash); } + /* A trace changes ink, never weight, dash or head: the node's own lines take the main ink, every other line dims to the input boundary. */ + .basalt-diagram-edge[data-lit] .basalt-diagram-line { stroke: var(--basalt-diagram-edge-main); } + .basalt-diagram-edge[data-lit] .basalt-diagram-tip:not([data-open]), .basalt-diagram-edge[data-lit] .basalt-diagram-dot { fill: var(--basalt-diagram-edge-main); } + .basalt-diagram-edge[data-lit] .basalt-diagram-tip[data-open] { stroke: var(--basalt-diagram-edge-main); } + .basalt-diagram-edge[data-dim] .basalt-diagram-line { stroke: var(--basalt-diagram-edge-dim); } + .basalt-diagram-edge[data-dim] .basalt-diagram-tip:not([data-open]), .basalt-diagram-edge[data-dim] .basalt-diagram-dot { fill: var(--basalt-diagram-edge-dim); } + .basalt-diagram-edge[data-dim] .basalt-diagram-tip[data-open] { stroke: var(--basalt-diagram-edge-dim); } + /* An edge label: one line of Mono in the line's secondary ink; on its own line it sits on a plate of the ground, with no radius. */ + .basalt-diagram-label { position: absolute; box-sizing: border-box; height: var(--basalt-text-xs-line-height); color: var(--basalt-diagram-edge); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); text-align: center; white-space: nowrap; transition: color var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram-label[data-on] { background: var(--_ground); } + .basalt-diagram-label[data-lit] { color: var(--basalt-diagram-edge-main); } + + /* The sequence: drawn, a head per participant in equal columns space-5 apart and a 56px row a message; stacked, a strip of chips and a + numbered list that says each message's sender, receiver and kind. */ + .basalt-diagram-cast { + --_d-cd: var(--_drawn) grid; + display: var(--_d-cd, flex); + flex-wrap: wrap; + grid-template-columns: repeat(var(--_cols, 1), minmax(0, 1fr)); + gap: var(--_d-cast-gap, var(--basalt-space-1-5)); + --_d-cast-gap: var(--_drawn) var(--basalt-space-5); + margin: 0; + padding: 0; + list-style: none; + } + .basalt-diagram-actor { display: flex; min-width: 0; } + .basalt-diagram-node[data-shape="participant"] { + --_d-pd: var(--_drawn) var(--basalt-space-2-5) var(--basalt-space-3); + --_d-pr: var(--_drawn) var(--basalt-radius-md); + --_d-pa: var(--_drawn) center; + flex: var(--_d-pflex, none); + --_d-pflex: var(--_drawn) 1; + align-items: center; + justify-content: var(--_d-pa, center); + min-height: var(--_d-ph, var(--basalt-size-badge)); + --_d-ph: var(--_drawn) 0; + padding: var(--_d-pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline))); + border-radius: var(--_d-pr, var(--basalt-radius-xs)); + text-align: center; + } + .basalt-diagram-node[data-shape="participant"]:not([data-focal]) { + --_d-pbg: var(--_drawn) var(--_surface, var(--basalt-surface-1)); + --_d-pbc: var(--_drawn) var(--basalt-border-rim); + --_d-pbt: var(--_drawn) var(--basalt-border-rim-top); + background: var(--_d-pbg, none); + border-color: var(--_d-pbc, var(--basalt-border-hairline)); + border-top-color: var(--_d-pbt, var(--basalt-border-hairline)); + } + .basalt-diagram-node[data-shape="participant"] .basalt-diagram-kind { --_d-pk: var(--_drawn) block; display: var(--_d-pk, none); } + .basalt-diagram-node[data-shape="participant"] .basalt-diagram-name { font-size: var(--_d-pn, var(--basalt-text-xs-size)); line-height: var(--_d-pnl, var(--basalt-text-xs-line-height)); font-weight: var(--_d-pw, var(--basalt-font-weight-medium)); --_d-pn: var(--_drawn) var(--basalt-text-sm-size); --_d-pnl: var(--_drawn) var(--basalt-text-sm-line-height); --_d-pw: var(--_drawn) var(--basalt-font-weight-semibold); } + .basalt-diagram-steps { --_d-sp: var(--_drawn) var(--basalt-space-4); position: relative; z-index: 1; padding-block-start: var(--_d-sp, var(--basalt-space-4)); } + .basalt-diagram-msgs { margin: 0; padding: 0; list-style: none; } + .basalt-diagram-msg { + --_d-md: var(--_drawn) grid; + --_d-mc: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr)); + --_d-mr: var(--_drawn) 1fr 1fr; + --_d-mh: var(--_drawn) var(--basalt-size-diagram-step); + --_d-mg: var(--_drawn) 0 var(--basalt-space-5); + display: grid; + grid-template-columns: var(--_d-mc, var(--basalt-space-8) minmax(0, 1fr)); + grid-template-rows: var(--_d-mr, auto); + column-gap: var(--basalt-space-5); + gap: var(--_d-mg, 0); + height: var(--_d-mh, auto); + padding-block: var(--_d-mpb, var(--basalt-space-2-5)); + --_d-mpb: var(--_drawn) 0; + border-top: var(--_d-mb, var(--basalt-size-hairline) solid var(--basalt-border-divider)); + --_d-mb: var(--_drawn) 0; + font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); + } + .basalt-diagram-said { --_d-sd: var(--_drawn) block; display: var(--_d-sd, contents); grid-column: var(--_a) / var(--_b); grid-row: 1; align-self: end; justify-self: center; margin-block-end: calc(var(--basalt-space-1) + var(--basalt-size-hairline)); padding-inline: var(--basalt-space-1-5); background: var(--_ground); white-space: nowrap; } + .basalt-diagram-num { grid-column: 1; color: var(--basalt-text-tertiary); font-variant-numeric: tabular-nums; } + .basalt-diagram-said .basalt-diagram-num { margin-inline-end: var(--_d-nm, 0); --_d-nm: var(--_drawn) var(--basalt-space-1-5); } + .basalt-diagram-mlabel { grid-column: 2; color: var(--basalt-text-primary); font-family: var(--basalt-font-family-mono); } + .basalt-diagram-route { --_d-rd: var(--_drawn) none; display: var(--_d-rd, inline-flex); grid-column: 2; align-items: center; gap: var(--basalt-space-1); flex-wrap: wrap; color: var(--basalt-text-secondary); } + .basalt-diagram-note { --_d-nd: var(--_drawn) 2; grid-column: var(--_d-nc, 2); --_d-nc: var(--_drawn) var(--_a) / var(--_b); grid-row: var(--_d-nd, auto); align-self: start; justify-self: var(--_d-nj, stretch); --_d-nj: var(--_drawn) center; margin-block-start: var(--_d-nmt, 0); --_d-nmt: var(--_drawn) calc(var(--basalt-space-1) + var(--basalt-size-hairline)); padding-inline: var(--_d-npi, 0); --_d-npi: var(--_drawn) var(--basalt-space-1-5); background: var(--_d-nbg, none); --_d-nbg: var(--_drawn) var(--_ground); color: var(--basalt-text-tertiary); white-space: var(--_d-nws, normal); --_d-nws: var(--_drawn) nowrap; } + /* A self-call's words start space-2-5 after its loop (the plate's own padding is part of that); on the last participant they go on the start side. */ + .basalt-diagram-msg[data-self="end"] :is(.basalt-diagram-said, .basalt-diagram-note) { --_d-sj: var(--_drawn) start; justify-self: var(--_d-sj, stretch); --_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1)); margin-inline-start: var(--_d-sm, 0); } + .basalt-diagram-msg[data-self="start"] :is(.basalt-diagram-said, .basalt-diagram-note) { --_d-sj: var(--_drawn) end; justify-self: var(--_d-sj, stretch); --_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1)); margin-inline-end: var(--_d-sm, 0); } + .basalt-diagram-arrow { flex: none; overflow: visible; } + /* A band names a phase: drawn, a 36px row with a full-width divider rule and its words on a plate; stacked, a line of words. */ + .basalt-diagram-band { + --_d-bh: var(--_drawn) var(--basalt-size-control-lg); + --_d-bj: var(--_drawn) center; + position: relative; + display: flex; + align-items: center; + justify-content: var(--_d-bj, flex-start); + height: var(--_d-bh, auto); + margin: var(--_d-bm, var(--basalt-space-5) 0 var(--basalt-space-2)); + --_d-bm: var(--_drawn) 0; + color: var(--basalt-text-secondary); + font: var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); + } + .basalt-diagram-band::before { --_d-br: var(--_drawn) ""; content: var(--_d-br, none); position: absolute; inset-inline: 0; top: 50%; border-top: var(--basalt-size-hairline) solid var(--basalt-border-divider); } + .basalt-diagram-band > span { position: relative; padding-inline: var(--_d-bp, 0); --_d-bp: var(--_drawn) var(--basalt-space-1-5); background: var(--_ground); } + + /* A schema's table: the node box with no padding, a header band, 28px rows of Mono (a key seat, the name, the type or "→ table"). */ + .basalt-diagram-node[data-shape="table"] { align-self: start; padding: 0; overflow-wrap: normal; } + .basalt-diagram-th { padding: var(--basalt-space-2) var(--basalt-space-3); border-bottom: var(--basalt-size-hairline) solid var(--basalt-border-divider); } + .basalt-diagram-node[data-focal] .basalt-diagram-th { border-bottom-color: var(--basalt-diagram-focal-rule); } + .basalt-diagram-tname { color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-rows { display: flex; flex-direction: column; padding-block: var(--basalt-space-1); } + .basalt-diagram-row { display: flex; flex-wrap: wrap; align-items: center; column-gap: var(--basalt-space-3); min-height: var(--basalt-size-control-sm); padding-inline: var(--basalt-space-3); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-keyseat { flex: none; width: var(--basalt-space-6); margin-inline-end: calc(-1 * var(--basalt-space-3)); color: var(--basalt-text-tertiary); } + .basalt-diagram-cname { flex: 1 0 auto; color: var(--basalt-text-primary); } + .basalt-diagram-ctype { margin-inline-start: auto; color: var(--basalt-text-tertiary); } + .basalt-diagram-ctype[data-ref] { color: var(--basalt-text-secondary); } + .basalt-diagram-more { padding: 0 var(--basalt-space-3) var(--basalt-space-2); color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + + /* The key: under the drawing over a divider, each swatch drawn as its mark. */ + .basalt-diagram-key { padding-block-start: var(--basalt-space-3); border-top: var(--basalt-size-hairline) solid var(--basalt-border-divider); } + .basalt-diagram-legend { display: flex; flex-wrap: wrap; gap: var(--basalt-space-2) var(--basalt-space-5); margin: 0; padding: 0; list-style: none; color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-entry { display: inline-flex; align-items: center; gap: var(--basalt-space-1-5); } + .basalt-diagram[data-layout="drawn"] .basalt-diagram-entry[data-when="stacked"], .basalt-diagram[data-layout="stacked"] .basalt-diagram-entry[data-when="drawn"], .basalt-diagram:not([data-layout]) .basalt-diagram-entry[data-when="drawn"] { display: none; } + .basalt-diagram-swatch { flex: none; overflow: visible; } + .basalt-diagram-swatch-shape { fill: var(--_ground); stroke: var(--basalt-diagram-structure); stroke-width: var(--basalt-size-hairline); } + .basalt-diagram-swatch[data-shape="focal"] .basalt-diagram-swatch-shape { fill: var(--basalt-diagram-focal); stroke: var(--basalt-diagram-focal); } + .basalt-diagram-swatch[data-shape="group"] .basalt-diagram-swatch-shape { fill: none; stroke-dasharray: var(--basalt-space-1) var(--basalt-space-0-5); } + .basalt-diagram-fk-mark { color: var(--basalt-text-secondary); font-family: var(--basalt-font-family-mono); } + + .basalt-diagram-hint { display: flex; flex-wrap: wrap; gap: var(--basalt-space-1) var(--basalt-space-4); margin: 0; color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-hint > span { display: inline-flex; align-items: center; gap: var(--basalt-space-1); } + .basalt-diagram[data-layout="stacked"]:is([data-type="sequence"], [data-type="schema"]) .basalt-diagram-hint { display: none; } + .basalt-diagram-summary { order: 1; max-width: var(--basalt-size-prose-width); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); text-wrap: pretty; } + .basalt-diagram-foot { order: 2; display: flex; } + /* "View as list": real lists, no box round them. */ + .basalt-diagram-list { order: 3; max-width: var(--basalt-size-prose-width); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-list[hidden] { display: none; } + .basalt-diagram-list strong { color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-semibold); } + .basalt-diagram-code { color: var(--basalt-text-primary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-list-head { margin: var(--basalt-space-4) 0 var(--basalt-space-2); color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + .basalt-diagram-list-head:first-child { margin-block-start: 0; } + .basalt-diagram-list-group { margin: var(--basalt-space-3) 0 var(--basalt-space-1); color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-medium); } + .basalt-diagram-list-items { display: flex; flex-direction: column; gap: var(--basalt-space-1); margin: 0; padding-inline-start: var(--basalt-space-5); } + .basalt-diagram-list-exits { margin: var(--basalt-space-1) 0 0; padding-inline-start: var(--basalt-space-5); } + @media (pointer: coarse) { + .basalt-diagram-toggle { min-height: var(--basalt-size-tap-min); } + } + @media (prefers-reduced-motion: reduce) { + .basalt-diagram-node, .basalt-diagram-line, .basalt-diagram-tip, .basalt-diagram-label, .basalt-diagram-diamond path { transition: none; } + } + @media (prefers-contrast: more) { + .basalt-diagram-node[data-focal] :is(.basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { opacity: 1; } + } + + /* Before script: the stack, and the author's grid only from the figure's least width (1.11, 1.19): the track minimums and gaps summed from + the tokens, never under 640. One rule per least width for two to six columns; a figure of more columns stays stacked until script. */ + /* stylelint-disable-next-line basalt/container-length -- size-breakpoint-container-lg (640px), the floor of every least width: architecture and flowchart up to 3 columns, data flow and schema 2, sequence up to 4 */ + @container (width >= 640px) { + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="1"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="3"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="1"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="3"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="1"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="1"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="1"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="3"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } + } + /* stylelint-disable-next-line basalt/container-length -- a data flow of 3 step columns: size-diagram-lane (120) + 3 × (size-diagram-node 144 + space-12 48) = 696px */ + @container (width >= 696px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="3"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- 4 columns: 4 × size-diagram-node (144) + 3 × space-16 (64) = 768px; and a schema of 3: 3 × size-diagram-table (224) + 2 × space-12 (48) = 768px */ + @container (width >= 768px) { + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="0"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="4"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="3"] > .basalt-diagram-drawing { --_drawn: ; } + } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 4 columns whose group reaches one side: 4 × 144 + 3 × 64 + space-4 (16) = 784px */ + @container (width >= 784px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 4 columns reaching both sides: 4 × 144 + 3 × 64 + 2 × 16 = 800px; a sequence of 5: 5 × size-diagram-node (144) + 4 × space-5 (20) = 800px */ + @container (width >= 800px) { + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="2"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } + } + /* stylelint-disable-next-line basalt/container-length -- a data flow of 4 step columns: 120 + 4 × (144 + 48) = 888px */ + @container (width >= 888px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a sequence of 6: 6 × 144 + 5 × 20 = 964px */ + @container (width >= 964px) { .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- 5 columns: 5 × 144 + 4 × 64 = 976px */ + @container (width >= 976px) { + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="0"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } + } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 5 columns reaching one side: 5 × 144 + 4 × 64 + 16 = 992px */ + @container (width >= 992px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 5 columns reaching both sides: 5 × 144 + 4 × 64 + 2 × 16 = 1008px */ + @container (width >= 1008px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="2"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a schema of 4: 4 × size-diagram-table (224) + 3 × space-12 (48) = 1040px */ + @container (width >= 1040px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a data flow of 5 step columns: 120 + 5 × (144 + 48) = 1080px */ + @container (width >= 1080px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- 6 columns: 6 × 144 + 5 × 64 = 1184px */ + @container (width >= 1184px) { + .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="0"] > .basalt-diagram-drawing, + .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } + } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 6 columns reaching one side: 6 × 144 + 5 × 64 + 16 = 1200px */ + @container (width >= 1200px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 6 columns reaching both sides: 6 × 144 + 5 × 64 + 2 × 16 = 1216px */ + @container (width >= 1216px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="2"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a data flow of 6 step columns: 120 + 6 × (144 + 48) = 1272px */ + @container (width >= 1272px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a schema of 5: 5 × 224 + 4 × 48 = 1312px */ + @container (width >= 1312px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a schema of 6: 6 × 224 + 5 × 48 = 1584px */ + @container (width >= 1584px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } } + /* Where scripting is off: always stacked, the list open, no toggle and no line in the key (no line is drawn). */ + @media (scripting: none) { + /* An id's weight in a :not(), so this outweighs every least-width rule above. */ + .basalt-diagram:not(#basalt-diagram-no-id) > .basalt-diagram-drawing { --_drawn: initial; } + .basalt-diagram-list[hidden] { display: block; } + .basalt-diagram-foot, .basalt-diagram-entry[data-line], .basalt-diagram-hint { display: none; } + } + + @media (forced-colors: active) { + /* After the rules above, at their specificity or more, for every kind, text role and trace state (1.17). */ + .basalt-diagram-svg, .basalt-diagram-swatch, .basalt-diagram-arrow { forced-color-adjust: none; } + .basalt-diagram .basalt-diagram-line, .basalt-diagram .basalt-diagram-line[data-kind] { stroke: CanvasText; } + .basalt-diagram .basalt-diagram-tip, .basalt-diagram .basalt-diagram-tip[data-kind], .basalt-diagram .basalt-diagram-dot { fill: CanvasText; } + .basalt-diagram .basalt-diagram-tip[data-open], .basalt-diagram .basalt-diagram-tip[data-kind][data-open] { fill: none; stroke: CanvasText; } + .basalt-diagram .basalt-diagram-edge[data-dim] .basalt-diagram-line { stroke: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-dim] :is(.basalt-diagram-tip:not([data-open]), .basalt-diagram-dot) { fill: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-dim] .basalt-diagram-tip[data-open] { stroke: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-lit] .basalt-diagram-line { stroke: Highlight; } + .basalt-diagram .basalt-diagram-edge[data-lit] :is(.basalt-diagram-tip:not([data-open]), .basalt-diagram-dot) { fill: Highlight; } + .basalt-diagram .basalt-diagram-edge[data-lit] .basalt-diagram-tip[data-open] { stroke: Highlight; } + .basalt-diagram .basalt-diagram-life { stroke: GrayText; } + .basalt-diagram .basalt-diagram-label { color: CanvasText; forced-color-adjust: none; } + .basalt-diagram .basalt-diagram-label[data-on] { background: Canvas; } + .basalt-diagram .basalt-diagram-label[data-lit] { color: Highlight; } + .basalt-diagram .basalt-diagram-swatch-shape { fill: Canvas; stroke: CanvasText; } + .basalt-diagram .basalt-diagram-swatch[data-shape="group"] .basalt-diagram-swatch-shape { fill: none; stroke: GrayText; } + .basalt-diagram .basalt-diagram-swatch[data-shape="focal"] .basalt-diagram-swatch-shape { fill: CanvasText; stroke: CanvasText; } + .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal]), .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal])[data-near] { border-color: CanvasText; } + .basalt-diagram .basalt-diagram-diamond { forced-color-adjust: none; } + .basalt-diagram .basalt-diagram-diamond path, .basalt-diagram .basalt-diagram-node[data-near] .basalt-diagram-diamond path { fill: Canvas; stroke: CanvasText; } + .basalt-diagram .basalt-diagram-group, .basalt-diagram .basalt-diagram-gbox { border-color: GrayText; } + .basalt-diagram .basalt-diagram-lane + .basalt-diagram-lane::before, .basalt-diagram .basalt-diagram-band::before { border-color: GrayText; } + .basalt-diagram .basalt-diagram-hint { color: GrayText; } + .basalt-diagram :is(.basalt-diagram-kind, .basalt-diagram-name, .basalt-diagram-detail, .basalt-diagram-glabel, .basalt-diagram-lane-name, .basalt-diagram-title, .basalt-diagram-source, .basalt-diagram-num, .basalt-diagram-mlabel, .basalt-diagram-route, .basalt-diagram-note, .basalt-diagram-band, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more, .basalt-diagram-legend, .basalt-diagram-fk-mark) { color: CanvasText; } + .basalt-diagram .basalt-diagram-node:focus-visible { outline-color: Highlight; } + /* The focal node is CanvasText under Canvas ink with forced-color-adjust: none, every colour set by hand, so no backplate sits under its words. */ + .basalt-diagram .basalt-diagram-node[data-focal], .basalt-diagram .basalt-diagram-node[data-focal][data-near] { forced-color-adjust: none; background: CanvasText; border-color: CanvasText; } + .basalt-diagram .basalt-diagram-node[data-focal] :is(.basalt-diagram-name, .basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { color: Canvas; opacity: 1; } + .basalt-diagram .basalt-diagram-node[data-focal] .basalt-diagram-th { border-bottom-color: Canvas; } + .basalt-diagram .basalt-diagram-node[data-focal]:focus-visible { outline: var(--basalt-size-focus-width) solid Highlight; } + .basalt-diagram .basalt-diagram-node[data-focal][data-shape="decision"] .basalt-diagram-diamond path { fill: CanvasText; stroke: CanvasText; } + } + @media print { + .basalt-diagram-svg, .basalt-diagram-swatch, .basalt-diagram-arrow { print-color-adjust: exact; } + .basalt-diagram-hint { display: none; } + } + /* ---- Lit figures, the headline frame and N1's figures (DECISIONS 153) ---- Ported from the owner's approved prototypes, with the council's changes. The lit gradient is three neutral stops that each hold 3:1 on levels 0 to 3; a lit line is one stroke in the top stop; there is no area under a line, no cursor, no halo and no plate on a trend. The implementation hasn't been reviewed. */ diff --git a/packages/react/test/diagram-geometry.mjs b/packages/react/test/diagram-geometry.mjs new file mode 100644 index 00000000..3bfde819 --- /dev/null +++ b/packages/react/test/diagram-geometry.mjs @@ -0,0 +1,143 @@ +// The diagrams' geometry, read from what is drawn (DECISIONS 269 and 270, section 7): the paths and heads of the SVG, the label boxes and the nodes' +// boxes, the way the decision's proofs read Draft A. One function, evaluated in the page, so React's tests and the HTML skill's read the same things. +// `inspect(prefix, figureSelector)` returns the figure's layout and a list of problems, each a sentence; an empty list is a clean drawing. + +export function inspectSource() { + return `(${inspect.toString()})`; +} + +/* eslint-disable */ +function inspect(P, selector) { + const fig = document.querySelector(selector); + const drawing = fig.querySelector(`.${P}-drawing`); + const o = drawing.getBoundingClientRect(); + const R = (el) => { const r = el.getBoundingClientRect(); return { l: r.left - o.left, t: r.top - o.top, r: r.right - o.left, b: r.bottom - o.top }; }; + const hit = (a, b, e = 0.01) => a.l < b.r - e && a.r > b.l + e && a.t < b.b - e && a.b > b.t + e; + const grow = (a, p) => ({ l: a.l - p, t: a.t - p, r: a.r + p, b: a.b + p }); + const problems = []; + const layout = fig.getAttribute("data-layout"); + const type = fig.getAttribute("data-type"); + const nodes = [...drawing.querySelectorAll(`.${P}-node`)].map((el) => ({ id: el.dataset.node, shape: el.dataset.shape, el, ...R(el) })); + const inside = (p, n, pad) => { + const cx = (n.l + n.r) / 2, cy = (n.t + n.b) / 2, hw = (n.r - n.l) / 2, hh = (n.b - n.t) / 2; + if (n.shape === "decision" && fig.hasAttribute("data-measured")) return Math.abs(p.x - cx) / hw + Math.abs(p.y - cy) / hh < 1 - pad / Math.min(hw, hh); + if (n.shape === "terminal") { const rr = Math.min(hw, hh); const ex = Math.min(Math.max(p.x, n.l + rr), n.r - rr); return Math.hypot(p.x - ex, p.y - cy) < rr - pad; } + return p.x > n.l + pad && p.x < n.r - pad && p.y > n.t + pad && p.y < n.b - pad; + }; + const boxOnShape = (box, n) => { + if (!hit(box, n)) return false; + const steps = 6; + for (let i = 0; i <= steps; i++) for (let j = 0; j <= steps; j++) if (inside({ x: box.l + ((box.r - box.l) * i) / steps, y: box.t + ((box.b - box.t) * j) / steps }, n, 0)) return true; + // A shape's own point inside the box (a diamond's vertex in a wide label). + const cx = (n.l + n.r) / 2, cy = (n.t + n.b) / 2; + for (const p of [{ x: n.l, y: cy }, { x: n.r, y: cy }, { x: cx, y: n.t }, { x: cx, y: n.b }]) if (p.x > box.l && p.x < box.r && p.y > box.t && p.y < box.b) return true; + return false; + }; + // ---- lines, from their paths: the corners (a Q's control point), the stop, the tip ---- + const lines = [...drawing.querySelectorAll(`.${P}-edge`)].map((g) => { + const d = g.querySelector(`.${P}-line`).getAttribute("d"); + const pts = []; + for (const m of d.matchAll(/([MLQ])([^MLQ]*)/g)) { + const n = m[2].trim().split(/[ ,]+/).map(Number); + if (m[1] === "Q") { pts.pop(); pts.push({ x: n[0], y: n[1] }); } else pts.push({ x: n[0], y: n[1] }); + } + const tipEl = g.querySelector(`.${P}-tip`); + const tn = tipEl.getAttribute("d").match(/-?[\d.]+/g).map(Number); + const open = tipEl.hasAttribute("data-open"); + const tip = open ? { x: tn[2], y: tn[3] } : { x: tn[0], y: tn[1] }; + const width = parseFloat(getComputedStyle(g.querySelector(`.${P}-line`)).strokeWidth); + const full = pts.slice(0, -1).concat([tip]); + return { i: g.dataset.edge, from: g.dataset.from, to: g.dataset.to, pts: full, stop: pts[pts.length - 1], tip, width, tipEl }; + }); + const segs = (l) => l.pts.slice(1).map((p, k) => [l.pts[k], p]); + const segRect = (a, b, w) => ({ l: Math.min(a.x, b.x) - w / 2, r: Math.max(a.x, b.x) + w / 2, t: Math.min(a.y, b.y) - w / 2, b: Math.max(a.y, b.y) + w / 2 }); + const heads = lines.map((l) => ({ i: l.i, ...R(l.tipEl) })); + const labels = [...drawing.querySelectorAll(`.${P}-label`)].map((el) => ({ i: el.dataset.edge, text: el.textContent, el, ...R(el) })); + const rules = []; + drawing.querySelectorAll(`.${P}-gbox, .${P}-group`).forEach((el) => { + if (!el.getClientRects().length || getComputedStyle(el).display === "contents") return; + const g = R(el); + rules.push({ what: "a group's boundary", l: g.l, r: g.r, t: g.t, b: g.t + 1 }, { what: "a group's boundary", l: g.l, r: g.r, t: g.b - 1, b: g.b }, { what: "a group's boundary", l: g.l, r: g.l + 1, t: g.t, b: g.b }, { what: "a group's boundary", l: g.r - 1, r: g.r, t: g.t, b: g.b }); + const label = el.querySelector(`:scope > .${P}-glabel`); + if (label && label.getClientRects().length && getComputedStyle(label).display !== "none") rules.push({ what: "a group's label", ...R(label) }); + }); + drawing.querySelectorAll(`.${P}-lane`).forEach((el, k) => { + if (!el.getClientRects().length) return; + const lane = R(el); + if (k > 0) { const y = lane.t - parseFloat(getComputedStyle(drawing).rowGap) / 2; rules.push({ what: "a lane rule", l: lane.l, r: lane.r, t: y - 0.5, b: y + 0.5 }); } + rules.push({ what: "a lane's name", ...R(el.querySelector(`.${P}-lane-name`)) }); + }); + + // ---- scroll ---- + if (document.documentElement.scrollWidth > innerWidth + 0.5) problems.push(`the page scrolls sideways (${document.documentElement.scrollWidth} in ${innerWidth})`); + if (fig.scrollWidth > fig.clientWidth + 0.5) problems.push(`the figure scrolls sideways (${fig.scrollWidth} in ${fig.clientWidth})`); + if (drawing.getBoundingClientRect().right > fig.getBoundingClientRect().right + 0.5) problems.push("the drawing is wider than its figure"); + // ---- nodes ---- + for (let a = 0; a < nodes.length; a++) for (let b = a + 1; b < nodes.length; b++) if (hit(nodes[a], nodes[b], 0.5)) problems.push(`${nodes[a].id} is on ${nodes[b].id}`); + for (const n of nodes) { + n.el.querySelectorAll(`.${P}-kind, .${P}-name, .${P}-detail, .${P}-tname, .${P}-cname, .${P}-ctype, .${P}-keyseat, .${P}-more`).forEach((t) => { + if (!t.getClientRects().length) return; + for (const rect of t.getClientRects()) { + const r = { l: rect.left - o.left, t: rect.top - o.top, r: rect.right - o.left, b: rect.bottom - o.top }; + if (r.r - r.l < 0.5) continue; + if (r.l < n.l - 0.5 || r.r > n.r + 0.5 || r.t < n.t - 0.5 || r.b > n.b + 0.5) problems.push(`"${t.textContent}" leaves its box (${n.id})`); + if (n.shape === "decision" && fig.hasAttribute("data-measured")) for (const p of [{ x: r.l, y: r.t }, { x: r.r, y: r.t }, { x: r.l, y: r.b }, { x: r.r, y: r.b }]) if (!inside(p, n, -0.5)) { problems.push(`"${t.textContent}" leaves its diamond (${n.id})`); break; } + } + if (getComputedStyle(t).textOverflow === "ellipsis" || t.scrollWidth > t.clientWidth + 1) problems.push(`"${t.textContent}" is cut`); + }); + if (n.shape === "decision" && fig.hasAttribute("data-measured")) { + const w = n.r - n.l, h = n.b - n.t; + if (h < 64 - 0.5) problems.push(`the decision ${n.id} is ${h.toFixed(1)} tall, under 64`); + if (w / h > 5.001) problems.push(`the decision ${n.id} is ${(w / h).toFixed(2)}:1, flatter than 5:1`); + } + } + // ---- lines ---- + for (const l of lines) { + for (const n of nodes) for (const [a, b] of segs(l)) { + const len = Math.hypot(b.x - a.x, b.y - a.y), steps = Math.max(2, Math.ceil(len / 2)); + let through = false; + for (let k = 1; k < steps && !through; k++) { const f = k / steps; if (f * len < 1.5 || (1 - f) * len < 1.5) continue; if (inside({ x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }, n, 1)) through = true; } + if (through) { problems.push(`${l.from} to ${l.to} passes through ${n.id}`); break; } + } + // the head on its line's axis, and its tip on the contour of the node it points at + const [a, b] = segs(l)[segs(l).length - 1]; + const vertical = Math.abs(a.x - b.x) < 0.01; + if (vertical ? Math.abs(l.stop.x - l.tip.x) > 0.01 : Math.abs(l.stop.y - l.tip.y) > 0.01) problems.push(`${l.from} to ${l.to}: its head is off its line's axis`); + const target = nodes.find((n) => n.id === l.to); + if (target && !fig.querySelector(`.${P}-msg`)) { + const near = [-0.75, 0.75].some((d) => inside({ x: l.tip.x + (vertical ? 0 : d), y: l.tip.y + (vertical ? d : 0) }, target, 0)) && ![-0.75, 0.75].every((d) => inside({ x: l.tip.x + (vertical ? 0 : d), y: l.tip.y + (vertical ? d : 0) }, target, 0)); + if (!near && !(target.shape === "table")) problems.push(`${l.from} to ${l.to}: its tip (${l.tip.x.toFixed(1)}, ${l.tip.y.toFixed(1)}) is not on ${l.to}'s contour`); + } + } + // crossings + const crossings = []; + for (let x = 0; x < lines.length; x++) for (let y = x + 1; y < lines.length; y++) for (const [p1, p2] of segs(lines[x])) for (const [q1, q2] of segs(lines[y])) { + const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; + if (aH === bH) continue; + const [h1, h2, v1, v2] = aH ? [p1, p2, q1, q2] : [q1, q2, p1, p2]; + if (v1.x > Math.min(h1.x, h2.x) + 0.75 && v1.x < Math.max(h1.x, h2.x) - 0.75 && h1.y > Math.min(v1.y, v2.y) + 0.75 && h1.y < Math.max(v1.y, v2.y) - 0.75) crossings.push({ a: lines[x], b: lines[y], x: v1.x, y: h1.y, under: aH ? lines[y] : lines[x] }); + } + const cuts = crossings.map((c) => { const path = drawing.querySelector(`.${P}-edge[data-edge="${c.under.i}"] .${P}-line`); return Boolean(path?.getAttribute("mask")); }); + // ---- labels ---- + for (const lab of labels) { + const G = grow(lab, 0); + for (const n of nodes) if (boxOnShape(G, n)) problems.push(`the label "${lab.text}" is on ${n.id}`); + for (const other of labels) if (other !== lab && hit(G, other)) problems.push(`the label "${lab.text}" is on the label "${other.text}"`); + for (const h of heads) if (hit(G, h, 0.5)) problems.push(`the label "${lab.text}" is on a head`); + for (const r of rules) if (hit(G, r)) problems.push(`the label "${lab.text}" is on ${r.what}`); + for (const l of lines) if (l.i !== lab.i && segs(l).some(([a, b]) => hit(G, segRect(a, b, l.width)))) problems.push(`${l.from} to ${l.to} runs through the label "${lab.text}"`); + if (lab.l < -0.5 || lab.r > drawing.clientWidth + 0.5) problems.push(`the label "${lab.text}" leaves the drawing`); + if (lab.el.scrollWidth > lab.el.clientWidth + 1) problems.push(`the label "${lab.text}" is cut`); + } + // ---- the stack's width ---- + if (layout === "stacked" && type !== "schema" && drawing.getBoundingClientRect().width > 480.5) problems.push(`the stacked drawing is ${drawing.getBoundingClientRect().width.toFixed(1)} wide`); + // ---- type size ---- + fig.querySelectorAll("*").forEach((el) => { if (!el.getClientRects().length || ![...el.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim())) return; const size = parseFloat(getComputedStyle(el).fontSize); if (size < 12 && !el.closest(".basalt-visually-hidden, .visually-hidden, [aria-hidden='true'] .x")) problems.push(`"${el.textContent.trim().slice(0, 30)}" is ${size}px`); }); + return { + layout, type, width: fig.clientWidth, problems: [...new Set(problems)], + lines: lines.map((l) => ({ i: l.i, from: l.from, to: l.to, pts: l.pts, width: l.width })), + labels: labels.map((l) => ({ i: l.i, text: l.text })), + crossings: crossings.map((c, k) => ({ a: `${c.a.from}>${c.a.to}`, b: `${c.b.from}>${c.b.to}`, cut: cuts[k] })), + nodes: nodes.map((n) => ({ id: n.id, shape: n.shape, w: n.r - n.l, h: n.b - n.t, l: n.l, t: n.t })), + }; +} diff --git a/packages/react/test/diagrams.test.mjs b/packages/react/test/diagrams.test.mjs new file mode 100644 index 00000000..d2911865 --- /dev/null +++ b/packages/react/test/diagrams.test.mjs @@ -0,0 +1,671 @@ +// Basalt's diagrams (DECISIONS 269, revised by 270; review round 56): the five components drawn from CIMIP's five diagrams and from fixtures built to +// test one rule each, in Chromium against the built package with the real stylesheet. Section 7 of the decision is the list this file follows: +// geometry at every width, the fit rule, seats, the end gutter, derivation, accessibility, tracing, the modes, before script, and the rules. +// The geometry is read from what is drawn (test/diagram-geometry.mjs). The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import { pathToFileURL } from "node:url"; + +import * as React from "react"; +import { webkit } from "playwright"; + +import { inspectSource } from "./diagram-geometry.mjs"; +import { bundleFixture, fixturePage, launch, pixels, pkg } from "./support.mjs"; + +const require = createRequire(import.meta.url); +const { renderToString } = require("react-dom/server"); +const axeSource = fs.readFileSync(require.resolve("axe-core/axe.min.js"), "utf8"); +const DATA = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8")); +const KEYS = Object.keys(DATA); +const COMPONENT = { architecture: "ArchitectureDiagram", flowchart: "FlowchartDiagram", "data-flow": "DataFlowDiagram", sequence: "SequenceDiagram", schema: "SchemaDiagram" }; +const P = "basalt-diagram"; +const font = (file) => fs.readFileSync(path.join(pkg, "dist", "fonts", file)).toString("base64"); +const FONTS = `@font-face{font-family:"Geist";src:url(data:font/woff2;base64,${font("Geist-Variable.woff2")}) format("woff2");font-weight:100 900}@font-face{font-family:"Geist Mono";src:url(data:font/woff2;base64,${font("GeistMono-Variable.woff2")}) format("woff2");font-weight:100 900}`; +const PAGE = `${FONTS} body{background:var(--basalt-surface-page);margin:0;padding:16px;box-sizing:border-box} #root{max-width:1104px;margin:0 auto}`; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +// The host: `window.__set(list)` draws a list of { key, type, props } (props are the fixture's, less `type`); each figure has the id `fig-<key>`. +const HOST = ` +import data from "./test/fixtures/cimip-diagrams.json"; +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, "data-flow": B.DataFlowDiagram, sequence: B.SequenceDiagram, schema: B.SchemaDiagram }; +window.DATA = data; +const all = () => Object.entries(data).map(([key, d]) => { const { type, ...props } = d; return { key, type, props }; }); +function Host() { + const [list, setList] = React.useState(all); + window.__set = (next) => flushSync(() => setList(next)); + return <div style={{ display: "grid", gap: 64 }}>{list.map(({ key, type, props, card }) => { const X = C[type]; const fig = <X key={key} id={"fig-" + key} {...props} />; return card ? <B.Card key={key}>{fig}</B.Card> : fig; })}</div>; +} +createRoot(document.getElementById("root")).render(<Host />);`; + +const frames = (page, n = 3) => page.evaluate((n) => new Promise((resolve) => { let k = 0; const step = () => (++k >= n ? resolve() : requestAnimationFrame(step)); requestAnimationFrame(step); }), n); + +async function diagramPage(options = {}) { + const { theme = "dark", viewport = { width: 1440, height: 1000 }, ...rest } = options; + const { page, errors } = await fixturePage(browser, HOST, { theme, viewport, ...rest }); + const warnings = []; + page.on("console", (m) => { if (m.type() === "warning" || m.type() === "error") warnings.push(m.text()); }); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + return { page, errors, warnings }; +} +const inspect = (page, key) => page.evaluate(`${inspectSource()}("${P}", "#fig-${key}")`); +async function resize(page, width) { + await page.setViewportSize({ width, height: 1000 }); + await frames(page, 4); +} +async function audit(page) { + await page.evaluate(() => { document.title = "Basalt"; document.documentElement.lang = "en"; }); + if (!(await page.evaluate(() => Boolean(window.axe)))) await page.addScriptTag({ content: axeSource }); + const result = await page.evaluate(() => window.axe.run(document, { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] }, resultTypes: ["violations"] })); + return result.violations.map((v) => `${v.id}: ${v.help} (${v.nodes.map((n) => n.target.join(" ")).slice(0, 3).join("; ")})`); +} + +// The test widths of section 7: 320 to 1440 in steps of 16, the named widths, and each example's first drawn width and the pixel before it (found below). +const WIDTHS = [...new Set([...Array.from({ length: 71 }, (_, k) => 320 + 16 * k), 359, 360, 390, 412, 479, 480, 481, 639, 640, 641])].sort((a, b) => a - b); +const PAD = 32; // the host page's padding: a figure is the viewport less 32 + +describe("geometry: the five examples at every test width", () => { + test("nothing scrolls, overlaps, is cut or crosses; every edge and label is drawn; the stack is at most 480 and no decision is flatter than 5:1", async () => { + const { page, errors } = await diagramPage(); + // Each example's first drawn width, found by growing the figure a pixel at a time across the band where it can turn on. + const first = {}; + for (let w = 640; w <= 1104 && Object.keys(first).length < KEYS.length; w += 1) { + await resize(page, w + PAD); + for (const key of KEYS) if (!(key in first) && (await page.getAttribute(`#fig-${key}`, "data-layout")) === "drawn") first[key] = w; + } + assert.deepEqual(Object.keys(first).sort(), [...KEYS].sort(), `every example draws by the 1,104px row: ${JSON.stringify(first)}`); + const widths = [...new Set([...WIDTHS, ...Object.values(first).flatMap((w) => [w + PAD, w + PAD - 1])])].sort((a, b) => a - b); + const failures = []; + for (const width of widths) { + await resize(page, width); + for (const key of KEYS) { + const r = await inspect(page, key); + const d = DATA[key]; + const issues = [...r.problems]; + if (r.crossings.length) issues.push(`${r.crossings.length} crossing(s): ${r.crossings.map((c) => `${c.a} and ${c.b}`).join(", ")}`); + if (d.type !== "sequence" && d.type !== "schema") { + if (r.lines.length !== d.edges.length) issues.push(`${r.lines.length} of ${d.edges.length} lines drawn`); + const labelled = d.edges.filter((e) => e.label).length; + if (r.labels.length !== labelled) issues.push(`${r.labels.length} of ${labelled} labels drawn`); + } + if (d.type === "schema") { + const fks = d.tables.flatMap((t) => t.columns.filter((c) => c.references)).length; + if (r.layout === "drawn" && r.lines.length !== fks) issues.push(`${r.lines.length} of ${fks} foreign-key lines drawn`); + if (r.layout === "stacked" && r.lines.length) issues.push("a stacked schema draws lines"); + const written = await page.locator(`#fig-${key} .${P}-ctype[data-ref]`).count(); + if (written !== fks) issues.push(`${written} of ${fks} foreign-key rows write their target`); + } + if (d.type === "sequence" && r.layout === "drawn" && r.lines.length !== d.steps.filter((s) => !s.band).length) issues.push("a message is missing"); + if (r.layout === "drawn" && width - PAD < first[key]) issues.push(`drawn at ${width - PAD}, under its first drawn width ${first[key]}`); + if (r.layout === "stacked" && width - PAD >= first[key]) issues.push(`stacked at ${width - PAD}, at or over its first drawn width ${first[key]}`); + if (issues.length) failures.push(`${key} at a ${width - PAD}px figure (${r.layout}): ${issues.slice(0, 4).join("; ")}`); + } + } + assert.deepEqual(failures, []); + assert.deepEqual(errors, []); + // The decision's figures, measured on Draft A: the architecture from 784, the data flow from 1,080, the sequence about 810 and the schema about 1,060. The + // flowchart turns on later here (see the round's notes): its two-line decision at a 177px track is taller than Draft A's, and "responder" waits for it. + assert.equal(first.architecture, 784); + assert.equal(first.dataFlow, 1080); + assert.ok(first.sequence >= 790 && first.sequence <= 830, `sequence from ${first.sequence}`); + assert.ok(first.schema >= 1040 && first.schema <= 1070, `schema from ${first.schema}`); + assert.ok(first.flowchart >= 880 && first.flowchart <= 1000, `flowchart from ${first.flowchart}`); + await page.close(); + }); + + test("in the light theme too, at 1440, 390 and 360", async () => { + const { page } = await diagramPage({ theme: "light" }); + for (const width of [1440, 390, 360]) { + await resize(page, width); + for (const key of KEYS) assert.deepEqual((await inspect(page, key)).problems, [], `${key} at ${width}`); + } + await page.close(); + }); + + test("on the 1,104px page row all five are drawn; in a card (level 2) too", async () => { + const { page } = await diagramPage(); + for (const key of KEYS) assert.equal(await page.getAttribute(`#fig-${key}`, "data-layout"), "drawn", key); + await page.evaluate(() => window.__set(Object.entries(window.DATA).map(([key, d]) => { const { type, ...props } = d; return { key, type, props, card: true }; }))); + await frames(page, 4); + const levels = await page.$$eval(`.${P}-node`, (els) => [...new Set(els.map((e) => e.getAttribute("data-level")))]); + assert.deepEqual(levels, ["2"], "a node in a card is a panel at level 2"); + await page.close(); + }); +}); + +// ---- Fixtures built to test one rule each ---- +const node = (id, col, row, extra = {}) => ({ id, name: id.toUpperCase(), kind: "part", detail: "a detail", col, row, ...extra }); + +describe("the fit rule (1.11) and seats (1.8)", () => { + test("a fixture with a 200px word stays stacked until its track holds the word", async () => { + const { page } = await diagramPage(); + const word = "Supercalifragilisticexpialidocious"; + await page.addStyleTag({ content: "#root{max-width:none}" }); + await page.evaluate((word) => window.__set([{ key: "wide", type: "architecture", props: { title: "Wide", summary: "A wide word.", nodes: [{ id: "a", name: word, col: 1, row: 1 }, { id: "b", name: "B", col: 2, row: 1 }, { id: "c", name: "C", col: 3, row: 1 }, { id: "d", name: "D", col: 4, row: 1 }], edges: [{ from: "a", to: "b" }] } }]), word); + await frames(page, 4); + // Measured as the engine measures a name: its own ruler, in the name's face. + const need = await page.evaluate((word) => { const r = document.querySelector("#fig-wide .basalt-diagram-ruler"); r.setAttribute("data-f", "name"); r.textContent = word; const w = r.getBoundingClientRect().width; r.textContent = ""; return w; }, word); + assert.ok(need > 200, `the word is ${need}px`); + const track = Math.ceil(need + 2 * 12 + 2); + const least = 4 * track + 3 * 64; + for (const [w, layout] of [[least - 2, "stacked"], [least + 2, "drawn"]]) { + await resize(page, w + PAD); + assert.equal(await page.getAttribute("#fig-wide", "data-layout"), layout, `at ${w}`); + } + await page.close(); + }); + + test("a fixture whose label has no clean seat stays stacked", async () => { + const { page, warnings } = await diagramPage(); + // Two nodes side by side with a label as long as the rule allows and a gutter too short for it anywhere: the nodes fill their row and a node sits above and below. + await page.evaluate(() => window.__set([{ key: "noseat", type: "architecture", props: { title: "No seat", summary: "A label with no seat.", nodes: [ + { id: "a", name: "A", col: 1, row: 2 }, { id: "b", name: "B", col: 2, row: 2 }, { id: "c", name: "C", col: 1, row: 1 }, { id: "d", name: "D", col: 2, row: 1 }, { id: "e", name: "E", col: 1, row: 3 }, { id: "f", name: "F", col: 2, row: 3 }, + { id: "g", name: "G", col: 3, row: 2 }, { id: "h", name: "H", col: 4, row: 2 }], + edges: [{ from: "a", to: "b", label: "a label of twenty-eight char" }, { from: "c", to: "a" }, { from: "a", to: "e" }, { from: "d", to: "b" }, { from: "b", to: "f" }] } }])); + await frames(page, 4); + assert.equal(await page.getAttribute("#fig-noseat", "data-layout"), "stacked", "no seat, no drawn layout"); + // The same figure with a label that seats is drawn at the same width: the label alone decided it. + await page.evaluate(() => window.__set([{ key: "noseat", type: "architecture", props: { title: "No seat", summary: "A label with a seat.", nodes: [ + { id: "a", name: "A", col: 1, row: 2 }, { id: "b", name: "B", col: 2, row: 2 }, { id: "c", name: "C", col: 1, row: 1 }, { id: "d", name: "D", col: 2, row: 1 }, { id: "e", name: "E", col: 1, row: 3 }, { id: "f", name: "F", col: 2, row: 3 }, + { id: "g", name: "G", col: 3, row: 2 }, { id: "h", name: "H", col: 4, row: 2 }], + edges: [{ from: "a", to: "b", label: "ok" }, { from: "c", to: "a" }, { from: "a", to: "e" }, { from: "d", to: "b" }, { from: "b", to: "f" }] } }])); + await frames(page, 4); + assert.equal(await page.getAttribute("#fig-noseat", "data-layout"), "drawn"); + void warnings; + await page.close(); + }); + + test("seats: every label of the three seated examples is space-2 clear of its stroke, off its own head, at the first drawn width and every width above", async () => { + const { page } = await diagramPage(); + for (const width of [880, 946, 1000, 1040, 1080, 1104, 1136].map((w) => w + PAD)) { + await resize(page, width); + for (const key of ["architecture", "flowchart", "dataFlow"]) { + if ((await page.getAttribute(`#fig-${key}`, "data-layout")) !== "drawn") continue; + const r = await page.evaluate(({ P, key }) => { + const fig = document.querySelector(`#fig-${key}`), o = fig.querySelector(`.${P}-drawing`).getBoundingClientRect(); + return [...fig.querySelectorAll(`.${P}-label`)].map((el) => { + const b = el.getBoundingClientRect(), g = fig.querySelector(`.${P}-edge[data-edge="${el.dataset.edge}"]`); + const path = g.querySelector(`.${P}-line`), w = parseFloat(getComputedStyle(path).strokeWidth); + const tip = g.querySelector(`.${P}-tip`).getBoundingClientRect(); + const d = path.getAttribute("d").match(/-?[\d.]+/g).map(Number); + const xs = [], ys = []; + for (let k = 0; k < d.length; k += 2) { xs.push(d[k] + o.left); ys.push(d[k + 1] + o.top); } + // the clearance from the label box to the nearest horizontal run under or over it (on-line labels sit on their plate) + let clear = Infinity; + for (let k = 1; k < xs.length; k++) if (Math.abs(ys[k] - ys[k - 1]) < 0.01 && Math.min(xs[k], xs[k - 1]) < b.right && Math.max(xs[k], xs[k - 1]) > b.left) clear = Math.min(clear, Math.max(b.top - (ys[k] + w / 2), (ys[k] - w / 2) - b.bottom)); + const onHead = b.left < tip.right && b.right > tip.left && b.top < tip.bottom && b.bottom > tip.top; + return { text: el.textContent, on: el.hasAttribute("data-on"), clear, onHead }; + }); + }, { P, key }); + for (const l of r) { + assert.ok(!l.onHead, `${key} at ${width - PAD}: "${l.text}" is on its own head`); + if (!l.on && Number.isFinite(l.clear) && l.clear > -1) assert.ok(l.clear >= 8 - 0.01, `${key} at ${width - PAD}: "${l.text}" is ${l.clear.toFixed(2)}px clear of its stroke`); + } + if (key === "flowchart") for (const name of ["observer", "responder"]) assert.ok(r.some((l) => l.text === name), `"${name}" seats`); + if (key === "dataFlow") assert.ok(r.some((l) => l.text === "trim"), `"trim" seats`); + } + } + await page.close(); + }); + + test("no decision is flatter than 5:1 or under 64 tall: a two-column flowchart on the page row, and at 480 and 607", async () => { + const { page } = await diagramPage(); + await page.evaluate(() => window.__set([{ key: "two", type: "flowchart", props: { title: "Two", summary: "Two columns.", legend: { main: "Usual" }, nodes: [ + { id: "s", shape: "terminal", name: "Start", col: 1, row: 1 }, { id: "q", shape: "decision", name: "Yes?", col: 1, row: 2 }, { id: "n", shape: "terminal", name: "No", col: 2, row: 2, branch: true }, { id: "e", shape: "terminal", name: "End", col: 1, row: 3 }], + edges: [{ from: "s", to: "q", kind: "main" }, { from: "q", to: "n", label: "no" }, { from: "q", to: "e", kind: "main", label: "yes" }] } }])); + for (const width of [1440, 480 + PAD, 607 + PAD, 390]) { + await resize(page, width); + const r = await inspect(page, "two"); + assert.deepEqual(r.problems, [], `at ${width}`); + const q = r.nodes.find((n) => n.id === "q"); + assert.ok(q.w / q.h <= 5.001 && q.h >= 64 - 0.5, `at ${width} the decision is ${q.w.toFixed(0)} by ${q.h.toFixed(0)}`); + } + await page.close(); + }); +}); + +describe("the stacked drawing's end gutter (1.13)", () => { + const spine = (edges) => ({ title: "Gutter", summary: "Three spine cards.", legend: {}, nodes: ["a", "b", "c", "d"].map((id, k) => node(id, 1, k + 1)), edges }); + for (const [name, edges, crossings] of [ + ["A to C", [{ from: "a", to: "c", label: "past b" }], 0], + ["C to A", [{ from: "c", to: "a", label: "back up" }], 0], + ["both", [{ from: "a", to: "c", label: "past b" }, { from: "c", to: "a", label: "back up" }], 1], + ]) { + test(`${name}: no line through or inside a card and no label on one, at every test width; ${crossings} crossing${crossings === 1 ? ", with its cut" : "s"}`, async () => { + const { page } = await diagramPage(); + await page.evaluate((spec) => window.__set([{ key: "gutter", type: "architecture", props: spec }]), spine(edges)); + for (const width of WIDTHS.filter((w) => w <= 1440)) { + await resize(page, width); + const r = await inspect(page, "gutter"); + assert.equal(r.layout, "stacked"); + assert.deepEqual(r.problems, [], `at ${width}`); + assert.equal(r.crossings.length, crossings, `at ${width}: ${JSON.stringify(r.crossings)}`); + for (const c of r.crossings) assert.ok(c.cut, `at ${width} the crossing of ${c.a} and ${c.b} is not cut`); + } + // While a node is traced, the crossing keeps a cut. + if (crossings) { + await page.focus("#fig-gutter .basalt-diagram-node[data-node='a']").catch(() => {}); + await page.keyboard.press("Tab").catch(() => {}); + await page.evaluate(() => document.querySelector("#fig-gutter .basalt-diagram-node[data-node='a']").focus({ focusVisible: true })); + await frames(page); + assert.equal(await page.locator("#fig-gutter .basalt-diagram-line[mask]").count(), 1, "the crossing keeps one cut while tracing"); + } + await page.close(); + }); + } +}); + +describe("derivation (1.6, 1.13): the sides, slots and stacked routes of the examples equal the recorded table", () => { + test("ports and routes", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const table = (key) => core.derivedPorts(core.buildModel(DATA[key])).map((p) => `${p.from}>${p.to} ${p.fromSide}@${p.fromSlot} ${p.toSide}@${p.toSlot}`); + assert.deepEqual(table("architecture"), [ + "browser>alb right@0.5 left@0.5", "alb>svc right@0.5 left@0.5", "svc>aurora top@0.5 left@0.5", "svc>s3 right@0.5 left@0.5", "svc>ecs bottom@0.25 right@0.5", + "svc>bedrock right@0.75 left@0.5", "svc>agent bottom@0.5 top@0.5", "ecs>agent bottom@0.5 left@0.5", "agent>bedrock right@0.25 bottom@0.5", "agent>cw right@0.75 left@0.5", "agent>sys bottom@0.5 top@0.5"]); + assert.deepEqual(table("flowchart"), [ + "req>risk bottom@0.5 top@0.5", "risk>who bottom@0.5 top@0.5", "who>obs left@0.5 right@0.5", "who>med right@0.5 left@0.5", "who>may bottom@0.5 top@0.5", "med>wait right@0.5 left@0.5", + "med>may bottom@0.5 right@0.5", "may>first bottom@0.5 top@0.5", "first>told left@0.5 right@0.5", "first>rec bottom@0.5 top@0.5"]); + assert.deepEqual(table("dataFlow"), ["send>append right@0.5 top@0.5", "append>row right@0.5 top@0.5", "row>hear right@0.5 top@0.5", "hear>see right@0.5 top@0.5", "row>seal left@0.5 right@0.5", "row>seg bottom@0.5 top@0.5"]); + const routes = (key) => core.stackPlan(core.buildModel(DATA[key])).routes; + assert.deepEqual(routes("architecture"), ["down", "down", "trunk", "trunk", "trunk", "trunk", "rail", "end-down", "up", "trunk", "rail"]); + assert.deepEqual(routes("flowchart"), ["down", "down", "trunk", "trunk", "rail", "down", "end-down", "down", "trunk", "rail"]); + assert.deepEqual(routes("dataFlow"), ["down", "down", "down", "down", "end-down", "end-down"]); + assert.equal(core.stackPlan(core.buildModel(DATA.dataFlow)).gutter, true, "a data flow's bypasses run in the gutter"); + assert.equal(core.stackPlan(core.buildModel(DATA.architecture)).gutter, false, "the architecture's one end line leaves a branch and passes branches: the end lane"); + // 6 of the 27 edges name a side (the decision's count). + const named = ["architecture", "flowchart", "dataFlow"].flatMap((k) => DATA[k].edges).filter((e) => e.fromSide || e.toSide).length; + assert.equal(named, 6); + // A third overlapping end line is a development error. + const third = core.buildModel({ type: "architecture", title: "t", nodes: ["a", "b", "c", "d", "e"].map((id, k) => node(id, 1, k + 1)), edges: [{ from: "a", to: "d" }, { from: "b", to: "e" }, { from: "a", to: "e" }] }); + assert.equal(core.stackPlan(third).third, true); + }); + + test("a foreign key's row, line, sentence and list entry all come from `references`", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const m = core.buildModel(DATA.schema); + assert.equal(m.edges.length, 9); + const runs = m.byId.get("agent_runs"); + assert.match(core.nodeSentence(m, runs), /References incidents \(incident_id\), sandboxes \(sandbox_id\)\. Referenced by approvals \(run_id\)\./); + const html = core.toHtml(core.figureTree(m, {}, { prefix: "x", base: "b", hiddenClass: "h" })); + assert.match(html, /<span class="x-ctype" data-ref="">→ sandboxes<\/span>/); + assert.match(html, /<code class="x-code">sandbox_id<\/code>, foreign key, references <code class="x-code">sandboxes\.id<\/code>/); + const bad = core.buildModel({ type: "schema", title: "t", tables: [{ name: "a", col: 1, row: 1, columns: [{ name: "x", references: "b.nope" }] }, { name: "b", col: 2, row: 1, columns: [{ name: "id" }] }] }); + assert.ok(bad.warnings.some((w) => /not a shown column/.test(w))); + }); +}); + +describe("accessibility (1.14)", () => { + test("axe in both themes on all five, drawn and stacked, the list open and closed", async () => { + for (const theme of ["dark", "light"]) { + const { page } = await diagramPage({ theme }); + for (const width of [1440, 390]) { + await resize(page, width); + assert.deepEqual(await audit(page), [], `${theme} at ${width}, closed`); + for (const key of KEYS) await page.click(`#fig-${key} .${P}-toggle`); + await frames(page); + assert.deepEqual(await audit(page), [], `${theme} at ${width}, open`); + for (const key of KEYS) await page.click(`#fig-${key} .${P}-toggle`); + } + await page.close(); + } + }); + + test("the drawing is a named, described group; each node a sentence; one tab stop; the keys; Esc; Tab leaves", async () => { + const { page } = await diagramPage(); + const group = page.locator(`#fig-architecture .${P}-drawing`); + assert.equal(await group.getAttribute("role"), "group"); + assert.equal(await group.getAttribute("aria-roledescription"), "diagram"); + const [labelled, described] = await Promise.all([group.getAttribute("aria-labelledby"), group.getAttribute("aria-describedby")]); + assert.equal(await page.locator(`[id="${labelled}"]`).innerText(), DATA.architecture.title); + const [summary, keys] = described.split(" "); + assert.equal(await page.locator(`[id="${summary}"]`).innerText(), DATA.architecture.summary); + assert.match(await page.locator(`[id="${keys}"]`).textContent(), /Arrow keys/); + assert.equal(await page.getAttribute(`#fig-architecture .${P}-node[data-node="svc"]`, "aria-label"), + "cimip service, ECS service. N tasks · stateless. In AWS · your account. From: ALB. To: Aurora PostgreSQL (SQL · NOTIFY), S3 (PUT), ECS (RunTask), Bedrock (scribe), Agent sandbox (HTTP + SSE). The service."); + assert.match(await page.getAttribute(`#fig-dataFlow .${P}-node[data-node="row"]`, "aria-label"), /^Event row \+ NOTIFY, Step 3 of 7, Aurora\./); + assert.match(await page.getAttribute(`#fig-sequence .${P}-node[data-node="svc"]`, "aria-label"), /Sends 7 messages and receives 6\./); + assert.equal(await page.locator(`#fig-architecture .${P}-node[tabindex="0"]`).count(), 1, "one tab stop"); + assert.equal(await page.locator(`#fig-architecture .${P}-svg`).evaluate((svg) => svg.closest("[aria-hidden='true']") !== null), true, "the SVG is hidden"); + await page.focus(`#fig-architecture .${P}-node[data-node="browser"]`); + const at = () => page.evaluate(() => document.activeElement?.dataset.node); + for (const [key, to] of [["ArrowRight", "alb"], ["ArrowDown", "svc"], ["ArrowLeft", "alb"], ["ArrowUp", "browser"], ["ArrowUp", "browser"], ["End", "sys"], ["ArrowRight", "sys"], ["Home", "browser"]]) { + await page.keyboard.press(key); + assert.equal(await at(), to, `${key}`); + } + await page.keyboard.press("ArrowRight"); + assert.equal(await page.locator(`#fig-architecture .${P}-node[tabindex="0"]`).getAttribute("data-node"), "alb", "the stop follows focus"); + assert.ok(await page.locator(`#fig-architecture`).evaluate((f) => f.hasAttribute("data-tracing")), "keyboard focus traces"); + await page.keyboard.press("Escape"); + assert.equal(await at(), "alb", "Esc keeps focus"); + assert.ok(!(await page.locator(`#fig-architecture`).evaluate((f) => f.hasAttribute("data-tracing"))), "Esc clears the trace"); + await page.keyboard.press("Tab"); + assert.ok(await page.evaluate(() => document.activeElement?.classList.contains("basalt-diagram-toggle")), "Tab leaves the drawing for the list's toggle"); + await page.close(); + }); + + test("the stacked sequence and schema have no stops and no hint; the list's facts are the data's, each once", async () => { + const { page } = await diagramPage({ viewport: { width: 390, height: 900 } }); + for (const key of ["sequence", "schema"]) { + assert.equal(await page.locator(`#fig-${key} .${P}-node[tabindex]`).count(), 0, `${key} has no stops`); + assert.equal(await page.locator(`#fig-${key} .${P}-hint`).isVisible(), false); + assert.equal(await page.locator(`#fig-${key} .${P}-drawing`).getAttribute("role"), null); + } + for (const key of KEYS) await page.click(`#fig-${key} .${P}-toggle`); + const text = (key) => page.locator(`#fig-${key} .${P}-list`).innerText(); + const arch = await text("architecture"); + for (const n of DATA.architecture.nodes) assert.ok(arch.includes(n.name), n.name); + for (const e of DATA.architecture.edges) if (e.label) assert.equal(arch.split(`: ${e.label} (`).length - 1, 1, `the line "${e.label}" once`); + assert.match(arch, /cimip service to Aurora PostgreSQL: SQL · NOTIFY \(Call\)\./); + const flow = await text("flowchart"); + for (const n of DATA.flowchart.nodes) assert.equal(flow.split(`${n.name}`).length - 1 >= 1, true, n.name); + assert.equal(flow.split("May decide, high risk asks twice").length - 1, 1, "each node is written once"); + assert.match(flow, /If responder: go to 5, Risk medium or lower\?/); + const df = await text("dataFlow"); + assert.match(df, /Aurora: Event row \+ NOTIFY, one transaction\.( The one transaction\.)? Then to step 4, Hears it: NOTIFY \(The message's path\); to step 6, Keeps the newest 300: trim \(Housekeeping\); to step 7, Sealed segment: once 200 wait \(Later, in a batch\)\./); + const seq = await text("sequence"); + assert.match(seq, /RunTask: cimip service to ECS \(Setup\)\. Idempotency token = sandbox id\./); + const schema = await text("schema"); + assert.match(schema, /incident_id, primary key, references incidents\.id/); + assert.match(schema, /and 8 more columns/); + // Text is never under 12px, the list's code included. + const small = await page.$$eval(`.${P}-list *`, (els) => els.filter((e) => e.getClientRects().length && parseFloat(getComputedStyle(e).fontSize) < 12).map((e) => e.textContent)); + assert.deepEqual(small, []); + await page.close(); + }); + + for (const engine of ["chromium", "webkit"]) { + test(`${engine}: focus and the roving stop survive 390 to 1440 and back; a focused table keeps focus and its ring into a stack with no stops`, async (t) => { + let b = browser; + if (engine === "webkit") { try { b = await webkit.launch(); } catch { t.skip("WebKit is not installed"); return; } } + try { + const { page } = await fixturePage(b, HOST, { theme: "dark", viewport: { width: 1440, height: 1000 } }); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + for (const key of ["architecture", "flowchart", "dataFlow"]) { + const id = DATA[key].nodes[2].id; + await page.focus(`#fig-${key} .${P}-node[data-node="${id}"]`); + for (const width of [390, 900, 1440, 390, 1440]) { + await resize(page, width); + assert.equal(await page.evaluate(() => document.activeElement?.dataset.node), id, `${key} at ${width}: focus stayed`); + assert.equal(await page.getAttribute(`#fig-${key} .${P}-node[data-node="${id}"]`, "tabindex"), "0", `${key} at ${width}: the stop stayed`); + } + } + // The schema drawn at 1440: focus a table, narrow into the stack (no stops): focus and its ring stay; once focus leaves, it is no longer a stop. + await resize(page, 1440); + await page.focus(`#fig-schema .${P}-node[data-node="incidents"]`); + await page.keyboard.press("ArrowRight"); + await page.keyboard.press("ArrowLeft"); + await resize(page, 390); + assert.equal(await page.evaluate(() => document.activeElement?.dataset.node), "incidents", "focus stays on the table"); + assert.equal(await page.getAttribute(`#fig-schema .${P}-node[data-node="incidents"]`, "tabindex"), "-1"); + if (engine === "chromium") assert.notEqual(await page.$eval(`#fig-schema .${P}-node[data-node="incidents"]`, (el) => getComputedStyle(el).outlineStyle), "none", "its ring stays"); + await page.keyboard.press("Tab"); + await frames(page); + assert.equal(await page.getAttribute(`#fig-schema .${P}-node[data-node="incidents"]`, "tabindex"), null, "no longer a stop once focus left"); + await page.close(); + } finally { if (b !== browser) await b.close(); } + }); + } + + test("the toggle is at least 44px on touch", async () => { + const { page } = await diagramPage({ viewport: { width: 390, height: 900 }, hasTouch: true, isMobile: true }); + const h = await page.$eval(`#fig-architecture .${P}-toggle`, (el) => el.getBoundingClientRect().height); + assert.ok(h >= 44, `${h}`); + await page.close(); + }); +}); + +describe("tracing (1.15)", () => { + test("a traced line keeps its width, dash and head; a label keeps its box; the rest dim to the input boundary; leaving clears it", async () => { + const { page } = await diagramPage(); + const read = () => page.$$eval(`#fig-architecture .${P}-edge`, (gs) => gs.sort((a, b) => a.dataset.edge - b.dataset.edge).map((g) => { const p = g.querySelector(".basalt-diagram-line"), s = getComputedStyle(p); return { lit: g.hasAttribute("data-lit"), dim: g.hasAttribute("data-dim"), w: s.strokeWidth, dash: s.strokeDasharray, stroke: s.stroke, tip: g.querySelector(".basalt-diagram-tip").getAttribute("d") }; })); + const labels = () => page.$$eval(`#fig-architecture .${P}-label`, (ls) => ls.map((l) => { const r = l.getBoundingClientRect(); return [r.width, r.height, r.x, r.y]; })); + const restLines = await read(), restLabels = await labels(); + await page.hover(`#fig-architecture .${P}-node[data-node="svc"]`); + await page.waitForTimeout(150); + const traced = await read(); + const input = await page.evaluate(() => { const s = document.createElement("i"); s.style.color = "var(--basalt-border-input)"; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; }); + const main = await page.evaluate(() => { const s = document.createElement("i"); s.style.color = "var(--basalt-text-primary)"; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; }); + traced.forEach((l, k) => { + assert.equal(l.w, restLines[k].w, "width kept"); + assert.equal(l.dash, restLines[k].dash, "dash kept"); + assert.equal(l.tip, restLines[k].tip, "head kept"); + assert.equal(l.stroke, l.lit ? main : input); + }); + assert.ok(traced.some((l) => l.lit) && traced.some((l) => l.dim)); + assert.deepEqual(await labels(), restLabels, "a label's box does not move or change size"); + await page.mouse.move(2, 2); + await page.waitForTimeout(150); + assert.ok((await read()).every((l) => !l.lit && !l.dim), "nothing is left traced after the pointer leaves"); + // A press focuses a node and traces nothing. + await page.click(`#fig-architecture .${P}-node[data-node="alb"]`); + await page.mouse.move(2, 2); + await page.waitForTimeout(150); + assert.ok((await read()).every((l) => !l.lit), "a press traces nothing"); + await page.close(); + }); + + test("on touch (no hover) a tap traces nothing", async () => { + const { page } = await diagramPage({ hasTouch: true, isMobile: true, viewport: { width: 1440, height: 1000 } }); + await page.tap(`#fig-architecture .${P}-node[data-node="svc"]`); + await page.waitForTimeout(150); + assert.equal(await page.locator(`#fig-architecture .${P}-edge[data-lit]`).count(), 0); + await page.close(); + }); +}); + +describe("modes (1.16 to 1.19)", () => { + for (const scheme of ["dark", "light"]) for (const theme of ["dark", "light"]) { + test(`forced colours (${scheme} palette) under a saved ${theme} theme: lines, heads and contours in system colours, the focal node legible on its own fill`, async () => { + const { page } = await diagramPage({ theme, forcedColors: "active", colorScheme: scheme }); + const r = await page.evaluate(() => { + const sys = (name) => { const s = document.createElement("i"); s.style.color = name; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; }; + const main = document.querySelector("#fig-architecture .basalt-diagram-line[data-kind='main']"); + const contour = getComputedStyle(document.querySelector("#fig-flowchart .basalt-diagram-node[data-shape='terminal']")).borderTopColor; + const focal = document.querySelector("#fig-architecture .basalt-diagram-node[data-focal]"); + return { canvasText: sys("CanvasText"), canvas: sys("Canvas"), gray: sys("GrayText"), main: getComputedStyle(main).stroke, contour, focalFill: getComputedStyle(focal).backgroundColor, focalName: getComputedStyle(focal.querySelector(".basalt-diagram-name")).color, focalKind: getComputedStyle(focal.querySelector(".basalt-diagram-kind")).color, life: getComputedStyle(document.querySelector("#fig-sequence .basalt-diagram-life")).stroke, group: getComputedStyle(document.querySelector("#fig-architecture .basalt-diagram-gbox")).borderTopColor }; + }); + assert.equal(r.main, r.canvasText, "the main line is CanvasText"); + assert.equal(r.contour, r.canvasText, "a flowchart contour is CanvasText"); + assert.equal(r.life, r.gray, "a lifeline is GrayText"); + assert.equal(r.group, r.gray, "a group's boundary is GrayText"); + assert.equal(r.focalFill, r.canvasText, "the focal fill is CanvasText"); + assert.equal(r.focalName, r.canvas, "the focal words are Canvas"); + assert.equal(r.focalKind, r.canvas); + // The pixels under the focal node's words: the words against the fill they sit on, never against a Canvas backplate. The word box's pixels hold two + // colours, the fill and the ink; a backplate would make the fill there Canvas, and the ink's contrast against its surround 1:1. + const box = await page.locator("#fig-architecture .basalt-diagram-node[data-focal] .basalt-diagram-name").boundingBox(); + const px = await pixels(page, { x: Math.floor(box.x), y: Math.floor(box.y), width: Math.ceil(box.width), height: Math.ceil(box.height) }); + const L = (c) => { const f = (v) => { const s = v / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]); }; + const ratio = (a, b) => { const [x, y] = [L(a), L(b)].sort((m, n) => n - m); return (x + 0.05) / (y + 0.05); }; + const parse = (c) => c.match(/\d+/g).slice(0, 3).map(Number); + const fill = parse(r.focalFill), canvas = parse(r.canvas); + const fillShare = px.filter((p) => ratio(p, fill) < 1.1).length / px.length; + assert.ok(fillShare > 0.4, `${Math.round(fillShare * 100)}% of the words' box is the fill: a backplate would cover it`); + const strongest = Math.max(...px.map((p) => ratio(p, fill))); + assert.ok(strongest >= 4.5, `the words are ${strongest.toFixed(2)}:1 on their fill`); + assert.ok(ratio(fill, canvas) >= 3, "the fill stands 3:1 off Canvas"); + assert.equal(await page.evaluate(() => getComputedStyle(document.querySelector("#fig-architecture .basalt-diagram-node[data-focal]")).forcedColorAdjust), "none"); + await page.close(); + }); + } + + test("more contrast: the focal node's quiet ink at full strength; the structure and dimmed lines stay on the input boundary", async () => { + for (const theme of ["dark", "light"]) { + const { page } = await diagramPage({ theme, contrast: "more" }); + const r = await page.evaluate(() => ({ + opacity: getComputedStyle(document.querySelector("#fig-architecture .basalt-diagram-node[data-focal] .basalt-diagram-kind")).opacity, + structure: getComputedStyle(document.querySelector("#fig-architecture .basalt-diagram-gbox")).borderTopColor, + input: (() => { const s = document.createElement("i"); s.style.color = "var(--basalt-border-input)"; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; })(), + })); + assert.equal(r.opacity, "1"); + assert.equal(r.structure, r.input); + await page.close(); + } + }); + + test("reduced motion: no transition on a trace", async () => { + const { page } = await diagramPage({ reducedMotion: "reduce" }); + const d = await page.$eval(`#fig-architecture .${P}-line`, (el) => getComputedStyle(el).transitionDuration); + assert.equal(d, "0s"); + await page.close(); + }); + + test("print: the lines print and the key hint does not", async () => { + const { page } = await diagramPage(); + await page.emulateMedia({ media: "print" }); + assert.equal(await page.$eval(`#fig-architecture .${P}-svg`, (el) => getComputedStyle(el).printColorAdjust), "exact"); + assert.equal(await page.locator(`#fig-architecture .${P}-hint`).isVisible(), false); + assert.equal(await page.locator(`#fig-architecture .${P}-svg .${P}-line`).count(), 11); + assert.equal(await page.$eval(`#fig-architecture .${P}-svg`, (el) => getComputedStyle(el).display !== "none" && getComputedStyle(el.querySelector(".basalt-diagram-line")).visibility === "visible"), true); + await page.close(); + }); +}); + +describe("contrast as rendered", () => { + for (const theme of ["dark", "light"]) { + test(`${theme}: the strongest pixel across a 1px line, a dash, a diamond's slope and a capsule's contour is 3:1 at 2x`, async () => { + const { page } = await diagramPage({ theme, deviceScaleFactor: 2, viewport: { width: 1440, height: 2400 } }); + const L = (c) => { const f = (v) => { const x = v / 255; return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]); }; + const ratio = (a, b) => { const [x, y] = [L(a), L(b)].sort((m, n) => n - m); return (x + 0.05) / (y + 0.05); }; + const ground = await page.evaluate(() => getComputedStyle(document.body).backgroundColor.match(/\d+/g).slice(0, 3).map(Number)); + const strongest = async (clip) => Math.max(...(await pixels(page, clip)).map((p) => ratio(p, ground))); + const at = (sel) => page.locator(sel).boundingBox(); + // A plain 1px line: svc to S3, across the gutter; a dash: ECS to the sandbox's horizontal run. + const svc = await at(`#fig-architecture .${P}-node[data-node="svc"]`), s3 = await at(`#fig-architecture .${P}-node[data-node="s3"]`); + const plain = await strongest({ x: svc.x + svc.width + 4, y: svc.y + svc.height / 2 - 4, width: 6, height: 8 }); + const agent = await at(`#fig-architecture .${P}-node[data-node="agent"]`); + const dash = await strongest({ x: agent.x - 40, y: agent.y + agent.height / 2 - 4, width: 24, height: 8 }); + // A diamond's slope, and a capsule's curve. + const who = await at(`#fig-flowchart .${P}-node[data-node="who"]`); + const slope = await strongest({ x: who.x + who.width * 0.25 - 3, y: who.y + who.height * 0.25 - 3, width: 6, height: 6 }); + const obs = await at(`#fig-flowchart .${P}-node[data-node="obs"]`); + const curve = await strongest({ x: obs.x, y: obs.y + 2, width: 8, height: 8 }); + for (const [name, r] of [["a plain line", plain], ["a dash", dash], ["a diamond's slope", slope], ["a capsule's contour", curve]]) assert.ok(r >= 3, `${theme}: ${name} is ${r.toFixed(2)}:1`); + void s3; + await page.close(); + }); + } +}); + +describe("before script (1.19)", () => { + let basalt; + const ssr = async (key, extra = {}) => { + basalt ??= await import(pathToFileURL(path.join(pkg, "dist", "index.js")).href); + const { type, ...props } = DATA[key]; + return renderToString(React.createElement(basalt[COMPONENT[type]], { id: `fig-${key}`, ...props, ...extra })); + }; + const css = () => fs.readFileSync(path.join(pkg, "dist", "styles.css"), "utf8"); + + test("with JavaScript off each figure holds its title, every node's text, the summary and the open list, and no toggle", async () => { + const html = (await Promise.all(KEYS.map((k) => ssr(k)))).join(""); + const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1440, height: 1000 } }); + const page = await context.newPage(); + await page.setContent(`<html data-theme="dark"><head><style>${css()}${PAGE}</style></head><body><div id="root">${html}</div></body></html>`); + for (const key of KEYS) { + const d = DATA[key]; + const text = await page.locator(`#fig-${key}`).innerText(); + assert.ok(text.includes(d.title) && text.includes(d.summary), key); + for (const n of d.nodes ?? d.participants ?? d.tables) assert.ok(text.includes(n.name), `${key}: ${n.name}`); + assert.equal(await page.locator(`#fig-${key} .${P}-list`).isVisible(), true, `${key}: the list is open`); + assert.equal(await page.locator(`#fig-${key} .${P}-toggle`).isVisible(), false, `${key}: no toggle`); + assert.equal(await page.getAttribute(`#fig-${key}`, "data-layout"), null); + const stacked = await page.$eval(`#fig-${key} .${P}-drawing`, (el) => getComputedStyle(el).display !== "grid" || el.closest("[data-type='schema']") !== null); + assert.ok(stacked, `${key} is stacked where scripting is off`); + } + await context.close(); + }); + + test("server markup hydrates with no warning; with hydration delayed each example is stacked under its least width and on the grid from it", async () => { + const LEAST = { architecture: 784, flowchart: 768, dataFlow: 1080, sequence: 640, schema: 1040 }; + for (const key of KEYS) for (const width of [640, LEAST[key] - 1, LEAST[key]]) { + const html = await ssr(key); + const page = await browser.newPage({ viewport: { width: width + PAD, height: 1000 } }); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") errors.push(m.text()); }); + await page.setContent(`<html data-theme="dark"><head><style>${css()}${PAGE}</style></head><body><div id="root">${html}</div></body></html>`); + await page.evaluate(() => document.fonts.ready); + const grid = await page.$eval(`#fig-${key} .${P}-drawing`, (el) => getComputedStyle(el.querySelector(".basalt-diagram-cast") ?? el).display === "grid"); + const schema = key === "schema"; + const drawnExpected = width >= LEAST[key] && width >= 640 && (width > 640 || LEAST[key] === 640); + if (!schema) assert.equal(grid, drawnExpected, `${key} at ${width} before script`); + else assert.equal(await page.$eval(`#fig-${key} .${P}-drawing`, (el) => getComputedStyle(el).gridTemplateColumns.split(" ").length), drawnExpected ? 4 : Math.max(1, Math.floor((width + 16) / (224 + 16))), `${key} at ${width} before script`); + // No card narrower than its minimum, and no text outside its box. + const r = await page.evaluate(`${inspectSource()}("${P}", "#fig-${key}")`); + assert.deepEqual(r.problems.filter((p) => /leaves|cut|scrolls|wider/.test(p)), [], `${key} at ${width} before script`); + if (grid && !schema) for (const n of r.nodes) assert.ok(n.w >= (key === "dataFlow" || key === "architecture" || key === "flowchart" ? 144 : 0) - 0.5, `${key}: ${n.id} is ${n.w}px before script`); + // Then hydrate. + const { type, ...props } = DATA[key]; + await page.addScriptTag({ content: await bundleFixture(`import { hydrateRoot } from "react-dom/client"; import data from "./test/fixtures/cimip-diagrams.json"; const { type, ...props } = data["${key}"]; hydrateRoot(document.getElementById("root"), React.createElement(B.${COMPONENT[type]}, { id: "fig-${key}", ...props }));`) }); + await frames(page, 4); + assert.deepEqual(errors, [], `${key} hydrates with no warning`); + void props; + await page.close(); + } + }); + + test("a seven-column figure stays stacked before script at every width", async () => { + basalt ??= await import(pathToFileURL(path.join(pkg, "dist", "index.js")).href); + const nodes = Array.from({ length: 7 }, (_, k) => node(`n${k}`, k + 1, 1)); + const html = renderToString(React.createElement(basalt.ArchitectureDiagram, { id: "seven", title: "Seven", summary: "Seven columns.", nodes, edges: [] })); + const page = await browser.newPage({ viewport: { width: 2400, height: 800 } }); + await page.setContent(`<html data-theme="dark"><head><style>${css()} body{margin:0}</style></head><body>${html}</body></html>`); + for (const width of [640, 1104, 1440, 2400]) { + await page.setViewportSize({ width, height: 800 }); + assert.notEqual(await page.$eval(`#seven .${P}-drawing`, (el) => getComputedStyle(el).display), "grid", `at ${width}`); + } + await page.close(); + }); + + test("at 1440 the architecture, data flow, sequence and schema do not move when script arrives; the flowchart moves only by its decisions' heights", async () => { + for (const key of KEYS) { + const html = await ssr(key); + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); + await page.setContent(`<html data-theme="dark"><head><style>${css()}${PAGE}</style></head><body><div id="root">${html}</div></body></html>`); + await page.evaluate(() => document.fonts.ready); + const boxes = () => page.$$eval(`#fig-${key} .${P}-node`, (els) => els.map((e) => { const r = e.getBoundingClientRect(); return { id: e.dataset.node, x: Math.round(r.x * 2) / 2, y: Math.round(r.y * 2) / 2, w: Math.round(r.width * 2) / 2, h: Math.round(r.height * 2) / 2, decision: e.dataset.shape === "decision" }; })); + const before = await boxes(); + await page.addScriptTag({ content: await bundleFixture(`import { hydrateRoot } from "react-dom/client"; import data from "./test/fixtures/cimip-diagrams.json"; const { type, ...props } = data["${key}"]; hydrateRoot(document.getElementById("root"), React.createElement(B.${COMPONENT[DATA[key].type]}, { id: "fig-${key}", ...props }));`) }); + await frames(page, 4); + const after = await boxes(); + if (key === "flowchart") { + // Every box keeps its column; rows move by the decisions' heights only. + before.forEach((b, k) => { assert.equal(after[k].x, b.x, `${b.id} x`); assert.equal(after[k].w, b.w, `${b.id} width`); if (!b.decision) assert.equal(after[k].h, b.h, `${b.id} height`); }); + } else assert.deepEqual(after, before, `${key} moved when script arrived`); + await page.close(); + } + }); +}); + +describe("rules", () => { + test("the diagrams' styles use tokens, and text is never under 12px", async () => { + const section = fs.readFileSync(path.join(pkg, "src", "styles", "components.css"), "utf8").split("/* ---- Diagrams (DECISIONS 269")[1].split("/* ---- Lit figures")[0]; + assert.doesNotMatch(section.replace(/\/\*[\s\S]*?\*\//g, ""), /#[0-9a-f]{3,8}\b|rgb\(|hsl\(|oklch\(/i, "no raw colour"); + assert.doesNotMatch(section, /text-(?:2xs|3xs)/, "no type under text-xs"); + }); + + test("an app that imports one diagram does not load another's module", async () => { + const esbuild = await import("esbuild"); + const out = await esbuild.build({ stdin: { contents: `import { ArchitectureDiagram } from "./dist/index.js"; console.log(ArchitectureDiagram);`, resolveDir: pkg, loader: "js" }, bundle: true, write: false, metafile: true, format: "esm", external: ["react", "react-dom", "react/jsx-runtime", "@base-ui/react", "@base-ui/react/*", "@phosphor-icons/react", "@phosphor-icons/react/*", "cmdk", "shiki"], logLevel: "silent" }); + const inputs = Object.entries(Object.values(out.metafile.outputs)[0].inputs).filter(([, v]) => v.bytesInOutput > 0).map(([k]) => k); + for (const other of ["flowchart-diagram", "data-flow-diagram", "sequence-diagram", "schema-diagram", "chart"]) assert.ok(!inputs.some((f) => f.endsWith(`dist/${other}.js`)), `${other} is loaded`); + assert.ok(inputs.some((f) => f.endsWith("dist/architecture-diagram.js"))); + }); + + test("the engine does no work when its module loads", async () => { + const source = fs.readFileSync(path.join(pkg, "src", "diagram-core.ts"), "utf8"); + const topLevel = source.split("\n").filter((l) => /^(const|let|var) /.test(l)); + for (const line of topLevel) assert.match(line, /^const \w+(?:: [^=]+)? = (?:\[|\{|"|'|\d|\(|new (?:Set|Map)\(\[)/, `a module-scope value that is not a literal or a function: ${line}`); + // No statement at module scope calls anything. + assert.doesNotMatch(source, /^[a-zA-Z_$][\w$.]*\(/m, "a call at module scope"); + }); +}); diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index 71b8c18a..7d53fc67 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -16,6 +16,7 @@ "AppHeader": 488, "AppShell": 99096, "AppTile": 1112, + "ArchitectureDiagram": 60723, "ArrowDownGlyph": 2868, "ArrowLeftGlyph": 2869, "ArrowRightGlyph": 2859, @@ -65,6 +66,7 @@ "CopyGlyph": 2884, "Countdown": 2920, "CoverageStrip": 1570, + "DataFlowDiagram": 60740, "DateAge": 2527, "DescriptionColumns": 216, "DescriptionItem": 578, @@ -97,6 +99,7 @@ "Fieldset": 6390, "FilterResult": 698, "FilterToolbar": 774, + "FlowchartDiagram": 60727, "Form": 8730, "FormGrid": 383, "FormGridItem": 628, @@ -207,6 +210,7 @@ "RunsGlyph": 3128, "STATUS_MESSAGE_MS": 26, "SandboxesGlyph": 2963, + "SchemaDiagram": 60679, "SearchDialog": 85332, "SearchGlyph": 3181, "SearchResult": 684, @@ -218,6 +222,7 @@ "SegmentedControl": 19383, "Select": 139960, "Separator": 4531, + "SequenceDiagram": 60709, "SettingsGlyph": 3100, "ShareBar": 1411, "Sheet": 70433, @@ -233,7 +238,7 @@ "ShortcutList": 10032, "SingleKeysSwitch": 17082, "SiteBrand": 1302, - "SiteFooter": 14780, + "SiteFooter": 14782, "SiteHeader": 175837, "SiteLockupDefs": 694, "SiteMenu": 168176, @@ -290,7 +295,7 @@ "TabsPanels": 385, "Terminal": 32255, "Text": 922, - "TextButton": 10415, + "TextButton": 10414, "TextMorph": 4504, "Textarea": 26909, "ThemeChoiceControl": 4794, @@ -369,11 +374,11 @@ "useWaitMark": 303 }, "package": { - "bytes": 760909, - "gzip": 250516 + "bytes": 813323, + "gzip": 269844 }, "styles": { - "bytes": 306245, - "gzip": 40103 + "bytes": 339096, + "gzip": 44067 } } diff --git a/packages/react/test/fixtures/cimip-diagrams.json b/packages/react/test/fixtures/cimip-diagrams.json new file mode 100644 index 00000000..42712b52 --- /dev/null +++ b/packages/react/test/fixtures/cimip-diagrams.json @@ -0,0 +1,186 @@ +{ + "architecture": { + "type": "architecture", + "title": "How a request reaches the agent", + "source": "docs/architecture.md, \"The shape\"", + "summary": "Requests travel from the browser over HTTPS through the ALB to the cimip service. The service writes to Aurora PostgreSQL, puts sealed segments in S3, calls Bedrock for the scribe and has ECS start one agent sandbox per incident. It streams HTTP + SSE to the sandbox, which calls Bedrock for inference, sends its logs to CloudWatch and runs approved tools against production.", + "legend": { "main": "Request path", "plain": "Call", "dashed": "Async or one-way", "focal": "The service" }, + "groups": [{ "id": "aws", "label": "AWS · your account" }], + "nodes": [ + { "id": "browser", "kind": "client", "name": "Browser", "detail": "Edge on iOS, Android", "col": 1, "row": 2 }, + { "id": "alb", "kind": "load balancer", "name": "ALB", "detail": "OIDC sign-in · HTTP/2", "detailMono": true, "group": "aws", "col": 2, "row": 2 }, + { "id": "svc", "kind": "ECS service", "name": "cimip service", "detail": "N tasks · stateless", "detailMono": true, "focal": true, "group": "aws", "col": 3, "row": 2 }, + { "id": "aurora", "kind": "database", "name": "Aurora PostgreSQL", "detail": "metadata · live window", "detailMono": true, "group": "aws", "col": 4, "row": 1, "branch": true }, + { "id": "s3", "kind": "object store", "name": "S3", "detail": "sealed segments · transcripts", "detailMono": true, "group": "aws", "col": 4, "row": 2, "branch": true }, + { "id": "ecs", "kind": "control plane", "name": "ECS", "detail": "RunTask · StopTask", "detailMono": true, "group": "aws", "col": 2, "row": 3, "branch": true }, + { "id": "bedrock", "kind": "model", "name": "Bedrock", "detail": "the scribe · the agent", "group": "aws", "col": 4, "row": 3, "branch": true }, + { "id": "agent", "kind": "ECS task · one per incident", "name": "Agent sandbox", "detail": "private IP · :8080", "detailMono": true, "group": "aws", "col": 3, "row": 4 }, + { "id": "cw", "kind": "logs", "name": "CloudWatch", "detail": "the agent's logs, traces", "group": "aws", "col": 4, "row": 5, "branch": true }, + { "id": "sys", "kind": "your systems", "name": "Production", "detail": "read-only tools", "group": "aws", "col": 3, "row": 5 } + ], + "edges": [ + { "from": "browser", "to": "alb", "kind": "main", "label": "HTTPS" }, + { "from": "alb", "to": "svc", "kind": "main" }, + { "from": "svc", "to": "aurora", "label": "SQL · NOTIFY", "fromSide": "top", "toSide": "left" }, + { "from": "svc", "to": "s3", "label": "PUT" }, + { "from": "svc", "to": "ecs", "label": "RunTask", "fromSide": "bottom", "toSide": "right" }, + { "from": "svc", "to": "bedrock", "label": "scribe", "toSide": "left" }, + { "from": "svc", "to": "agent", "kind": "main", "label": "HTTP + SSE" }, + { "from": "ecs", "to": "agent", "kind": "dashed", "label": "starts", "fromSide": "bottom", "toSide": "left" }, + { "from": "agent", "to": "bedrock", "label": "inference" }, + { "from": "agent", "to": "cw", "kind": "dashed", "label": "logs", "toSide": "left" }, + { "from": "agent", "to": "sys", "label": "tools · approved actions" } + ] + }, + "flowchart": { + "type": "flowchart", + "title": "Who may decide what the agent asks to run", + "source": "docs/agent-contract.md and the approvals section of the architecture", + "summary": "When the agent asks to run a command, CIMIP sets the higher of the two risk levels, then checks the decider's role: observers cannot decide, commanders and deputies may always decide, responders may decide only at medium risk or lower, and the first recorded decision stands.", + "legend": { "main": "Usual path", "focal": "CIMIP's own step" }, + "nodes": [ + { "id": "req", "shape": "terminal", "name": "Agent asks to run a command", "detail": "approval.requested", "detailMono": true, "col": 2, "row": 1 }, + { "id": "risk", "name": "CIMIP sets the risk", "detail": "higher of the agent's and its own", "focal": true, "col": 2, "row": 2 }, + { "id": "who", "shape": "decision", "name": "Who is deciding?", "col": 2, "row": 3 }, + { "id": "obs", "shape": "terminal", "name": "Can't decide", "detail": "observers only read", "col": 1, "row": 3, "branch": true }, + { "id": "med", "shape": "decision", "name": "Risk medium or lower?", "col": 3, "row": 3, "branch": true }, + { "id": "wait", "shape": "terminal", "name": "Waits for the commander or deputy", "col": 4, "row": 3, "branch": true }, + { "id": "may", "name": "May decide", "detail": "high risk asks twice", "col": 2, "row": 4 }, + { "id": "first", "shape": "decision", "name": "First decision?", "col": 2, "row": 5 }, + { "id": "told", "shape": "terminal", "name": "Told it was already decided", "col": 1, "row": 5, "branch": true }, + { "id": "rec", "shape": "terminal", "name": "Recorded, then sent until acknowledged", "col": 2, "row": 6 } + ], + "edges": [ + { "from": "req", "to": "risk", "kind": "main" }, + { "from": "risk", "to": "who", "kind": "main" }, + { "from": "who", "to": "obs", "label": "observer" }, + { "from": "who", "to": "med", "label": "responder" }, + { "from": "who", "to": "may", "kind": "main", "label": "commander or deputy" }, + { "from": "med", "to": "wait", "label": "no" }, + { "from": "med", "to": "may", "label": "yes", "fromSide": "bottom", "toSide": "right" }, + { "from": "may", "to": "first", "kind": "main" }, + { "from": "first", "to": "told", "label": "no" }, + { "from": "first", "to": "rec", "kind": "main", "label": "yes" } + ] + }, + "dataFlow": { + "type": "data-flow", + "title": "How one message reaches everyone in the room", + "source": "\"The log\"", + "summary": "Marcus's browser posts a message to cimip task A, which inserts an event row and fires NOTIFY in one Aurora transaction. Every cimip task listens and streams the event over SSE to Priya's browser, while Aurora keeps the newest 300 rows and seals older batches of 200 to S3.", + "legend": { "main": "The message's path", "plain": "Housekeeping", "dashed": "Later, in a batch", "focal": "The one transaction" }, + "lanes": [ + { "id": "marcus", "label": "Marcus's browser" }, + { "id": "task-a", "label": "cimip task A" }, + { "id": "aurora", "label": "Aurora" }, + { "id": "task-b", "label": "cimip task B" }, + { "id": "priya", "label": "Priya's browser" }, + { "id": "s3", "label": "S3" } + ], + "nodes": [ + { "id": "send", "lane": "marcus", "name": "Sends a message", "detail": "POST · retry key", "detailMono": true, "col": 1 }, + { "id": "append", "lane": "task-a", "name": "Appends it", "detail": "row lock → next seq", "detailMono": true, "col": 2 }, + { "id": "row", "lane": "aurora", "name": "Event row + NOTIFY", "detail": "one transaction", "focal": true, "col": 3 }, + { "id": "hear", "lane": "task-b", "name": "Hears it", "detail": "LISTEN, every task", "detailMono": true, "col": 4 }, + { "id": "see", "lane": "priya", "name": "Sees it", "detail": "SSE · one stream a tab", "detailMono": true, "col": 5 }, + { "id": "seal", "lane": "aurora", "name": "Keeps the newest 300", "detail": "older rows deleted once sealed", "col": 2 }, + { "id": "seg", "lane": "s3", "name": "Sealed segment", "detail": "200 events · SHA-256", "detailMono": true, "col": 3 } + ], + "edges": [ + { "from": "send", "to": "append", "kind": "main" }, + { "from": "append", "to": "row", "kind": "main", "label": "INSERT" }, + { "from": "row", "to": "hear", "kind": "main", "label": "NOTIFY" }, + { "from": "hear", "to": "see", "kind": "main", "label": "SSE" }, + { "from": "row", "to": "seal", "label": "trim" }, + { "from": "row", "to": "seg", "kind": "dashed", "label": "once 200 wait" } + ] + }, + "sequence": { + "type": "sequence", + "title": "An @agent run, from the mention to the approved action", + "source": "\"Runs and sandboxes\" and the agent contract", + "summary": "Marcus mentions @agent in the room. The cimip service records the run, starts and health-checks an ECS sandbox on the incident's first run, posts the run, streams the turn back to Marcus, and relays Marcus's approval until the sandbox says it is done.", + "legend": { "main": "Request", "plain": "Setup", "dashed": "Stream or reply", "focal": "The service" }, + "participants": [ + { "id": "marcus", "kind": "person", "name": "Marcus, in the room", "short": "Marcus" }, + { "id": "svc", "kind": "ECS service", "name": "cimip service", "focal": true }, + { "id": "ecs", "kind": "control plane", "name": "ECS" }, + { "id": "agent", "kind": "ECS task", "name": "Agent sandbox" } + ], + "steps": [ + { "from": "marcus", "to": "svc", "kind": "main", "label": "@agent check the proxy", "note": "a message in the room" }, + { "from": "svc", "to": "svc", "label": "records the run", "note": "run.started, one transaction" }, + { "band": "First run on an incident only" }, + { "from": "svc", "to": "ecs", "label": "RunTask", "note": "idempotency token = sandbox id" }, + { "from": "svc", "to": "ecs", "label": "DescribeTasks", "note": "until it has a private IP" }, + { "from": "svc", "to": "agent", "label": "GET /healthz", "note": "up to a minute" }, + { "band": "Every run" }, + { "from": "svc", "to": "agent", "kind": "main", "label": "POST /v1/runs", "note": "facts, recent transcript, prompt" }, + { "from": "agent", "to": "svc", "kind": "dashed", "label": "events, over SSE", "note": "status · tool.started · finding" }, + { "from": "svc", "to": "marcus", "kind": "dashed", "label": "the turn, as it happens", "note": "text in 40 ms frames, not stored" }, + { "from": "agent", "to": "svc", "kind": "main", "label": "approval.requested", "note": "the exact command · risk: medium" }, + { "band": "The agent waits for a person" }, + { "from": "marcus", "to": "svc", "kind": "main", "label": "Approve", "note": "first decision stands" }, + { "from": "svc", "to": "agent", "kind": "main", "label": "POST /v1/runs/{id}/input", "note": "sent until acknowledged" }, + { "from": "agent", "to": "svc", "kind": "dashed", "label": "done", "note": "outcome: completed" } + ] + }, + "schema": { + "type": "schema", + "title": "The tables an incident and its runs live in", + "source": "server/db/schema.ts; each table shows its keys and a few columns", + "summary": "Eight PostgreSQL tables center on incidents: memberships, room_events, log_segments, sandboxes and agent_runs reference incidents.id; memberships and incidents reference users.id; agent_runs references sandboxes.id; and approvals references agent_runs.id.", + "legend": { "plain": "A foreign key, to the key it references", "focal": "The table the others reference" }, + "tables": [ + { "name": "memberships", "col": 1, "row": 3, "more": 8, "columns": [ + { "name": "incident_id", "key": "PK", "references": "incidents.id" }, + { "name": "user_id", "key": "PK", "references": "users.id" }, + { "name": "role", "type": "text" }, + { "name": "state", "type": "text" }, + { "name": "deputy", "type": "boolean" } ] }, + { "name": "room_events", "col": 1, "row": 1, "more": 4, "columns": [ + { "name": "incident_id", "key": "PK", "references": "incidents.id" }, + { "name": "seq", "key": "PK", "type": "integer" }, + { "name": "channel", "type": "room | bridge" }, + { "name": "body", "type": "jsonb" } ] }, + { "name": "log_segments", "col": 1, "row": 2, "more": 4, "columns": [ + { "name": "incident_id", "key": "PK", "references": "incidents.id" }, + { "name": "first_seq", "key": "PK", "type": "integer" }, + { "name": "key", "type": "S3 key" }, + { "name": "sha256", "type": "text" } ] }, + { "name": "incidents", "col": 2, "row": [1, 2], "focal": true, "more": 10, "columns": [ + { "name": "id", "key": "PK", "type": "text" }, + { "name": "number", "type": "unique" }, + { "name": "title", "type": "text" }, + { "name": "severity", "type": "text" }, + { "name": "status", "type": "text" }, + { "name": "commander_id", "key": "FK", "references": "users.id" }, + { "name": "last_seq", "type": "integer" }, + { "name": "summary", "type": "text" } ] }, + { "name": "users", "col": 2, "row": 3, "more": 2, "columns": [ + { "name": "id", "key": "PK", "type": "text" }, + { "name": "subject", "type": "unique" }, + { "name": "name", "type": "text" }, + { "name": "roles", "type": "jsonb" } ] }, + { "name": "sandboxes", "col": 3, "row": 3, "more": 5, "columns": [ + { "name": "id", "key": "PK", "type": "text" }, + { "name": "incident_id", "key": "FK", "references": "incidents.id" }, + { "name": "state", "type": "text" }, + { "name": "endpoint", "type": "private IP" } ] }, + { "name": "agent_runs", "col": 3, "row": [1, 2], "more": 14, "columns": [ + { "name": "id", "key": "PK", "type": "text" }, + { "name": "incident_id", "key": "FK", "references": "incidents.id" }, + { "name": "sandbox_id", "key": "FK", "references": "sandboxes.id" }, + { "name": "kind", "type": "responder | ask" }, + { "name": "status", "type": "text" }, + { "name": "agent_cursor", "type": "integer" }, + { "name": "owner", "type": "lease" } ] }, + { "name": "approvals", "col": 4, "row": 1, "more": 8, "columns": [ + { "name": "id", "key": "PK", "type": "text" }, + { "name": "run_id", "key": "FK", "references": "agent_runs.id" }, + { "name": "command", "type": "text" }, + { "name": "risk", "type": "low | medium | high" }, + { "name": "status", "type": "pending" } ] } + ] + } +} diff --git a/packages/tokens/build.mjs b/packages/tokens/build.mjs index 15610453..cc0bcfa2 100644 --- a/packages/tokens/build.mjs +++ b/packages/tokens/build.mjs @@ -134,6 +134,8 @@ const MORE_CONTRAST = { "border-field": "field-contrast", // A hovered edge is never fainter than the edge at rest (decision 145): it steps to secondary ink, a colour the theme already has. "border-hover": "text-secondary", + // A diagram's focal table draws its header rule as the other theme's input boundary (DECISIONS 269, 1.18). + "diagram-focal-rule": "diagram-focal-rule-contrast", }; for (const [token, alias] of Object.entries(MORE_CONTRAST)) { for (const name of [token, alias]) if (!lightNames.includes(`--${PREFIX}-${name}`)) throw new Error(`more contrast: --${PREFIX}-${name} does not exist`); diff --git a/packages/tokens/test/contrast.test.mjs b/packages/tokens/test/contrast.test.mjs index 6eec9f22..be48361f 100644 --- a/packages/tokens/test/contrast.test.mjs +++ b/packages/tokens/test/contrast.test.mjs @@ -844,7 +844,7 @@ const MORE = Object.fromEntries([...moreBlock[2].matchAll(/--basalt-([\w-]+): va const more = (theme, name) => color(theme, MORE[name] ?? name); test("more contrast: lines step to border-input, tertiary ink to text-secondary and a field's boundary to text-secondary, and nothing else is replaced", () => { - assert.deepEqual(MORE, { "border-hairline": "line-contrast", "border-rim": "line-contrast", "border-rim-top": "line-contrast", "border-divider": "line-contrast", "text-tertiary": "ink-contrast", "border-field": "field-contrast", "border-hover": "text-secondary" }); + assert.deepEqual(MORE, { "border-hairline": "line-contrast", "border-rim": "line-contrast", "border-rim-top": "line-contrast", "border-divider": "line-contrast", "text-tertiary": "ink-contrast", "border-field": "field-contrast", "border-hover": "text-secondary", "diagram-focal-rule": "diagram-focal-rule-contrast" }); // the block is declared on every selector that sets a theme, the system-dark rule's own selector included, so it wins in both themes for (const selector of [":root", '[data-theme="light"]', '[data-theme="dark"]', ".light", ".dark", ':root:not([data-theme="light"]):not(.light)']) assert.ok(moreBlock[1].includes(selector), `the mode is not declared on ${selector}`); assert.ok(tokensCss.indexOf("prefers-contrast: more") > tokensCss.indexOf("@media (prefers-color-scheme: dark)"), "the mode comes after the system-dark rule, which it must outrank"); @@ -955,3 +955,45 @@ for (const theme of THEMES) { atLeast(theme, "text-primary", 4.5, [["surface-raised (the open sources button)", color(theme, "surface-raised")]]); }); } + +// ---- Diagrams (DECISIONS 269 and 270, 1.1): seven aliases and no new colour, each proved on levels 0 to 3, in both themes and under more contrast ---- +for (const theme of THEMES) { + const levels = LEVELS.map((n) => [n, color(theme, n)]); + test(`${theme}: the diagram roles are aliases of colours the theme already has`, () => { + assert.deepEqual(color(theme, "diagram-edge-main"), color(theme, "text-primary")); + assert.deepEqual(color(theme, "diagram-edge"), color(theme, "text-secondary")); + assert.deepEqual(color(theme, "diagram-edge-dim"), color(theme, "border-input")); + assert.deepEqual(color(theme, "diagram-structure"), color(theme, "border-input")); + assert.deepEqual(color(theme, "diagram-focal"), color(theme, "action-primary")); + assert.deepEqual(color(theme, "diagram-focal-ink"), color(theme, "action-primary-text")); + assert.deepEqual(color(theme, "diagram-focal-rule"), color(theme, theme === "dark" ? "black-8" : "white-6")); + assert.deepEqual(color(theme, "diagram-focal-rule-contrast"), color(theme, theme === "dark" ? "black-45" : "white-38")); + }); + + test(`${theme}: every diagram line and structure holds 3:1 on levels 0 to 3, and under more contrast (1.4.11)`, () => { + for (const name of ["diagram-edge-main", "diagram-edge", "diagram-edge-dim", "diagram-structure"]) { + atLeast(theme, name, 3, levels); + for (const [bgName, bg] of levels) assert.ok(ratio(over(more(theme, name), bg), bg) >= 3, `${theme}: ${name} on ${bgName} under more contrast`); + } + // The edge label's ink is the plain line's: text, 4.5:1 on the ground it sits on (its plate is that ground). + atLeast(theme, "diagram-edge", 4.5, levels); + }); + + test(`${theme}: the focal node's words hold 4.5:1 on its fill, full and at opacity-amount, and the fill stands 3:1 off every level`, () => { + const fill = color(theme, "diagram-focal"); + const ink = color(theme, "diagram-focal-ink"); + const amount = Number.parseFloat(tokens.primitives["opacity-amount"].css); + assert.ok(ratio(ink, fill) >= 4.5, `${theme}: focal ink on its fill is ${fmt(ratio(ink, fill))}:1`); + const quiet = over({ ...ink, alpha: amount }, fill); + assert.ok(ratio(quiet, fill) >= 4.5, `${theme}: focal ink at opacity-amount is ${fmt(ratio(quiet, fill))}:1`); + for (const [bgName, bg] of levels) assert.ok(ratio(fill, bg) >= 3, `${theme}: the focal fill on ${bgName} is ${fmt(ratio(fill, bg))}:1`); + // Under more contrast the quiet ink is at full strength, and the header rule is the other theme's input boundary. + const rule = over(more(theme, "diagram-focal-rule"), fill); + assert.ok(ratio(rule, fill) >= 3, `${theme}: the focal table's rule under more contrast is ${fmt(ratio(rule, fill))}:1`); + }); + + test(`${theme}: a node's text holds 4.5:1 on the level it is drawn at, and a traced line stays 3:1 while the rest dim`, () => { + for (const name of ["text-primary", "text-secondary", "text-tertiary"]) atLeast(theme, name, 4.5, levels.slice(1)); + atLeast(theme, "diagram-edge-dim", 3, levels); + }); +} diff --git a/packages/tokens/test/repeated-numbers.test.mjs b/packages/tokens/test/repeated-numbers.test.mjs index 30161807..c051ec59 100644 --- a/packages/tokens/test/repeated-numbers.test.mjs +++ b/packages/tokens/test/repeated-numbers.test.mjs @@ -34,8 +34,48 @@ test("the duration export is every duration token with a name, in milliseconds", for (const name of Object.keys(duration)) assert.equal(durations[`duration${name[0].toUpperCase()}${name.slice(1)}`], duration[name], `durations.duration${name} is not duration.${name}`); }); -// The widths a query may name: the breakpoint tokens, and the one sum the command list documents (its list column, a gap and the container breakpoint). -const WIDTHS = new Set([...Object.values(breakpoint), px("size-list-width") + px("space-4") + breakpoint.container]); +/** + * A diagram's least width (DECISIONS 269 and 270, 1.11 and 1.19): its track minimums and gaps summed from the tokens, never under the drawn layout's floor + * (size-breakpoint-container-lg). `reach` is how many sides an architecture's group reaches. + */ +function leastWidth(type, n, reach = 0) { + const sum = type === "data-flow" ? px("size-diagram-lane") + n * (px("size-diagram-node") + px("space-12")) + : type === "schema" ? n * px("size-diagram-table") + (n - 1) * px("space-12") + : type === "sequence" ? n * px("size-diagram-node") + (n - 1) * px("space-5") + : n * px("size-diagram-node") + (n - 1) * px("space-16") + reach * px("space-4"); + return Math.max(breakpoint.containerLg, sum); +} +const DIAGRAM_WIDTHS = ["architecture", "flowchart", "data-flow", "schema", "sequence"].flatMap((type) => [1, 2, 3, 4, 5, 6].flatMap((n) => (type === "architecture" ? [0, 1, 2] : [0]).map((r) => leastWidth(type, n, r)))); +// The widths a query may name: the breakpoint tokens, the one sum the command list documents (its list column, a gap and the container breakpoint), and a diagram's least widths. +const WIDTHS = new Set([...Object.values(breakpoint), px("size-list-width") + px("space-4") + breakpoint.container, ...DIAGRAM_WIDTHS]); + +test("each of the diagrams' least-width rules is the sum of tokens for every figure it names (DECISIONS 270, 1.19)", () => { + const css = read("packages", "react", "src", "styles", "components.css"); + const rules = [...css.matchAll(/@container \(width >= (\d+)px\) \{([^@]*?--_drawn: ; \})/g)].filter((m) => m[2].includes("basalt-diagram")); + assert.ok(rules.length >= 15, `found ${rules.length} least-width rules`); + const covered = new Set(); + for (const [, width, body] of rules) { + for (const selector of body.split(",")) { + const types = [...selector.matchAll(/data-type="([a-z-]+)"/g)].map((m) => m[1]); + const cols = [...selector.matchAll(/data-cols="(\d)"/g)].map((m) => Number(m[1])); + const reach = selector.match(/data-reach="(\d)"/)?.[1]; + for (const type of types) for (const n of cols) { + // An architecture rule with no reach serves every reach, so each must sum to the rule's width. + for (const r of reach !== undefined ? [Number(reach)] : type === "architecture" ? [0, 1, 2] : [0]) { + const expected = leastWidth(type, n, r); + assert.equal(Number(width), expected, `${type} of ${n} columns, reach ${r}, is drawn before script from ${width}px, but its least width is ${expected}`); + covered.add(`${type}:${n}:${r}`); + } + } + } + // The lint exception above the rule names the sum. + const before = css.slice(0, css.indexOf(`@container (width >= ${width}px)`)); + assert.match(before.slice(before.lastIndexOf("/*")), new RegExp(`${width}px|size-breakpoint-container-lg \\(${width}px\\)`), `the exception above the ${width}px rule does not name its sum`); + } + for (const type of ["architecture", "flowchart", "data-flow", "schema", "sequence"]) for (const n of [2, 3, 4, 5, 6]) for (const r of type === "architecture" ? [0, 1, 2] : [0]) { + assert.ok(covered.has(`${type}:${n}:${r}`), `no least-width rule for a ${type} of ${n} columns${type === "architecture" ? ` reaching ${r} sides` : ""}`); + } +}); const queryNumbers = (css) => [...css.matchAll(/@(?:media|container)\b[^{]*\{/g)].flatMap((query) => [...query[0].matchAll(/(\d+(?:\.\d+)?)px/g)].map((match) => ({ query: query[0].trim(), number: Number(match[1]) }))); test("every pixel width in a media or container query of React's sheet is a breakpoint token (or the command list's sum of tokens)", () => { diff --git a/packages/tokens/tokens/primitives.tokens.json b/packages/tokens/tokens/primitives.tokens.json index 646af753..3a939e7b 100644 --- a/packages/tokens/tokens/primitives.tokens.json +++ b/packages/tokens/tokens/primitives.tokens.json @@ -1179,6 +1179,54 @@ }, "$description": "A marks row's height, a default the app can set: one kind of reading across a run of days (DECISIONS 153, consent row 10)." }, + "diagram-node": { + "$type": "dimension", + "$value": { + "value": 144, + "unit": "px" + }, + "$description": "The least width of a node's track in a diagram's drawn layout; a track is also as wide as its widest unbreakable word, measured (DECISIONS 269)." + }, + "diagram-table": { + "$type": "dimension", + "$value": { + "value": 224, + "unit": "px" + }, + "$description": "The least width of a schema diagram's table; a table is also as wide as its widest row on one line, measured (DECISIONS 269)." + }, + "diagram-lane": { + "$type": "dimension", + "$value": { + "value": 120, + "unit": "px" + }, + "$description": "A data flow diagram's lane-name column, at the start of the drawn layout (DECISIONS 269)." + }, + "diagram-step": { + "$type": "dimension", + "$value": { + "value": 56, + "unit": "px" + }, + "$description": "A sequence diagram's message row: the line at its middle, the number and label above it, the note below (DECISIONS 269)." + }, + "diagram-head": { + "$type": "dimension", + "$value": { + "value": 8, + "unit": "px" + }, + "$description": "A diagram's arrowhead, its length and its width, for every kind of line (DECISIONS 269)." + }, + "diagram-guide-dash": { + "$type": "dimension", + "$value": { + "value": 4, + "unit": "px" + }, + "$description": "A sequence diagram's lifeline dash, on and off (4 on 4 off), unlike a message's 6 on 4 off (DECISIONS 269)." + }, "meter-marker": { "$type": "dimension", "$value": { diff --git a/packages/tokens/tokens/theme.dark.tokens.json b/packages/tokens/tokens/theme.dark.tokens.json index bbc8e799..88fc6511 100644 --- a/packages/tokens/tokens/theme.dark.tokens.json +++ b/packages/tokens/tokens/theme.dark.tokens.json @@ -233,6 +233,40 @@ "$description": "The last stop of a lit mark's gradient, at the foot of the plot: the kit's own, raised so it holds 3:1 on levels 0 to 3." } }, + "diagram": { + "edge-main": { + "$value": "{color.text.primary}", + "$description": "A diagram's main line and its head, and a traced line (DECISIONS 269). 3:1 or better on levels 0 to 3." + }, + "edge": { + "$value": "{color.text.secondary}", + "$description": "A diagram's plain and dashed lines and their heads, a foreign key's line and dot, and an edge label's ink." + }, + "edge-dim": { + "$value": "{color.border.input}", + "$description": "Every other line of a diagram while one node is traced: quieter, still 3:1. The input boundary; it does not step under more contrast." + }, + "structure": { + "$value": "{color.border.input}", + "$description": "A diagram's group boundary, a sequence's lifeline and a flowchart shape's contour: 3:1, because each carries meaning. It does not step under more contrast." + }, + "focal": { + "$value": "{color.action.primary}", + "$description": "A diagram's focal node: its fill and its edge, inverted ink. At most one a diagram, and never the accent." + }, + "focal-ink": { + "$value": "{color.action.primary-text}", + "$description": "Ink on the focal node; its kind and detail are this ink at opacity-amount." + }, + "focal-rule": { + "$value": "{color.black.8}", + "$description": "The focal table's header rule. Decorative: the other theme's divider, because the focal fill is the other theme's ground." + }, + "focal-rule-contrast": { + "$value": "{color.black.45}", + "$description": "Under more contrast, the focal table's header rule: the other theme's input boundary (DECISIONS 269, 1.18). An alias, no new colour." + } + }, "art": { "field": { "$value": "{color.neutral.0}", diff --git a/packages/tokens/tokens/theme.light.tokens.json b/packages/tokens/tokens/theme.light.tokens.json index 818bbd51..0dcef21c 100644 --- a/packages/tokens/tokens/theme.light.tokens.json +++ b/packages/tokens/tokens/theme.light.tokens.json @@ -233,6 +233,40 @@ "$description": "The last stop of a lit mark's gradient, at the foot of the plot: the kit's own, raised so it holds 3:1 on levels 0 to 3." } }, + "diagram": { + "edge-main": { + "$value": "{color.text.primary}", + "$description": "A diagram's main line and its head, and a traced line (DECISIONS 269). 3:1 or better on levels 0 to 3." + }, + "edge": { + "$value": "{color.text.secondary}", + "$description": "A diagram's plain and dashed lines and their heads, a foreign key's line and dot, and an edge label's ink." + }, + "edge-dim": { + "$value": "{color.border.input}", + "$description": "Every other line of a diagram while one node is traced: quieter, still 3:1. The input boundary; it does not step under more contrast." + }, + "structure": { + "$value": "{color.border.input}", + "$description": "A diagram's group boundary, a sequence's lifeline and a flowchart shape's contour: 3:1, because each carries meaning. It does not step under more contrast." + }, + "focal": { + "$value": "{color.action.primary}", + "$description": "A diagram's focal node: its fill and its edge, inverted ink. At most one a diagram, and never the accent." + }, + "focal-ink": { + "$value": "{color.action.primary-text}", + "$description": "Ink on the focal node; its kind and detail are this ink at opacity-amount." + }, + "focal-rule": { + "$value": "{color.white.6}", + "$description": "The focal table's header rule. Decorative: the other theme's divider, because the focal fill is the other theme's ground." + }, + "focal-rule-contrast": { + "$value": "{color.white.38}", + "$description": "Under more contrast, the focal table's header rule: the other theme's input boundary (DECISIONS 269, 1.18). An alias, no new colour." + } + }, "art": { "field": { "$value": "{color.neutral.98}", diff --git a/tools/html-skill/build.mjs b/tools/html-skill/build.mjs index 6c14279d..53cc5390 100644 --- a/tools/html-skill/build.mjs +++ b/tools/html-skill/build.mjs @@ -91,7 +91,10 @@ function filterTokens(css, keep) { const TYPE_LAYOUT_TOKEN = /^--basalt-(?:text-(?:6xl|7xl|hero-narrow|display-narrow)-|space-32\b|size-section-gap|size-display-measure\b)/; /** The link rows' row size (DECISIONS 152), the same way: the `link-rows` module's, out of the core, which has no room for a token only some pages use. */ const LINK_ROWS_TOKEN = /^--basalt-size-row\b/; -const inCore = Object.assign((name) => !MODULE_TOKEN.test(name) && !TYPE_LAYOUT_TOKEN.test(name) && !LINK_ROWS_TOKEN.test(name), { keepsOther: true }); +/** The diagram roles and lengths (DECISIONS 269), the same way: the `diagram` module's, out of the core. */ +const DIAGRAM_TOKEN = /^--basalt-(?:diagram-|size-diagram-)/; +const inCore = Object.assign((name) => !MODULE_TOKEN.test(name) && !TYPE_LAYOUT_TOKEN.test(name) && !LINK_ROWS_TOKEN.test(name) && !DIAGRAM_TOKEN.test(name), { keepsOther: true }); +const inDiagram = Object.assign((name) => DIAGRAM_TOKEN.test(name), { keepsOther: false }); const inLinkRows = Object.assign((name) => LINK_ROWS_TOKEN.test(name), { keepsOther: false }); const inArt = Object.assign((name) => MODULE_TOKEN.test(name), { keepsOther: false }); const inTypeLayout = Object.assign((name) => TYPE_LAYOUT_TOKEN.test(name), { keepsOther: false }); @@ -221,6 +224,28 @@ const glyphSvg = (name) => { }; const minifyJs = (code) => minify(code.replace(/%glyph-svg:([\w-]+)%/g, (_, name) => glyphSvg(name)).replace(/%glyph:([\w-]+)%/g, (_, name) => glyphPath(name)).replace(/%bp-(md|lg|container-sm|container-lg|container)%/g, (_, name) => BREAKPOINTS[name]).replace(/%duration-(confirm)%/g, (_, name) => DURATIONS[name]), "js"); +/** + * The diagram module's stylesheet: the diagrams section of packages/react/src/styles/components.css (from its heading to the next section's), with React's + * class prefix as the skill's and React's surface levels as the skill's panel variables (a node is the next level, the ground is the panel's own). + */ +function diagramCss() { + const react = fs.readFileSync(path.join(repo, "packages", "react", "src", "styles", "components.css"), "utf8"); + const start = react.indexOf(" /* ---- Diagrams (DECISIONS 269"); + const end = react.indexOf(" /* ---- ", start + 10); + if (start < 0 || end < 0) throw new Error("html-skill: the diagrams section of packages/react/src/styles/components.css moved; update diagramCss"); + const css = react.slice(start, end) + .replaceAll("var(--_surface, var(--basalt-surface-1))", "var(--panel-next, var(--basalt-surface-1))") + .replaceAll("var(--_surface, var(--basalt-surface-page))", "var(--panel-bg, var(--basalt-surface-page))") + .replaceAll(".basalt-diagram", ".diagram"); + if (css.includes("--_surface")) throw new Error("html-skill: the diagrams section reads --_surface in a form diagramCss does not rename"); + return `@layer basalt {\n${css}\n}\n`; +} +/** A module whose source imports React's engine (the diagram module): bundled into one script, the import inlined. */ +function bundleModule(file) { + const out = esbuild.buildSync({ entryPoints: [file], bundle: true, format: "iife", platform: "browser", target: "es2020", write: false, logLevel: "silent", legalComments: "inline", charset: "utf8" }); + return out.outputFiles[0].text; +} + /** The module names in src/modules.json, in the order they are added to a page. */ export function moduleNames() { return Object.keys(JSON.parse(src("modules.json")).modules); @@ -241,9 +266,13 @@ export function build() { if (name === "art") files["parts/art.css"] = minifyCss(dedupeSystemDark(filterTokens(tokensCss(), inArt))); // The type-layout module's tokens come before its own rules, as the tokens come before the core's. const tokens = name === "type-layout" ? `${filterTokens(tokensCss(), inTypeLayout)}\n` : name === "link-rows" ? `${filterTokens(tokensCss(), inLinkRows)}\n` : ""; + // The diagram module's stylesheet is React's own section, renamed (diagramCss), so the two cannot drift; its script bundles React's engine. + if (name === "diagram") files["parts/diagram.css"] = minifyCss(`${dedupeSystemDark(filterTokens(tokensCss(), inDiagram))}\n${diagramCss()}`); for (const ext of ["css", "js"]) { const file = path.join(srcDir, "modules", `${name}.${ext}`); - if (fs.existsSync(file)) files[`parts/${name}.${ext}`] = ext === "css" ? minifyCss(tokens + fs.readFileSync(file, "utf8")) : minifyJs(fs.readFileSync(file, "utf8")); + if (!fs.existsSync(file)) continue; + if (ext === "js" && name === "diagram") files[`parts/${name}.js`] = minifyJs(bundleModule(file)); + else files[`parts/${name}.${ext}`] = ext === "css" ? minifyCss(tokens + fs.readFileSync(file, "utf8")) : minifyJs(fs.readFileSync(file, "utf8")); } } // The icon paths are Phosphor's (MIT), so a page that draws them carries Phosphor's whole notice, as a legal comment a minifier keeps. diff --git a/tools/html-skill/src/compose.mjs b/tools/html-skill/src/compose.mjs index 272b537a..f8d526b0 100644 --- a/tools/html-skill/src/compose.mjs +++ b/tools/html-skill/src/compose.mjs @@ -28,6 +28,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import vm from "node:vm"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -539,7 +540,8 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = }); for (const name of use) if (!(name in manifest.modules)) throw new Error(`basalt:use names "${name}", which is not a module (modules: ${Object.keys(manifest.modules).join(", ")})`); - const content = held.restore(markup).replace(/^\s+/, ""); + const diagramNotes = []; + const content = writeDiagrams(held.restore(markup).replace(/^\s+/, ""), parts, diagramNotes); title ||= held.h1 || "Untitled page"; // an empty <title> names nothing: the heading does // Detection reads markup and code, never comments: a word written about in a comment (an HTML one, or one inside a script or a style) brings nothing in. @@ -587,7 +589,41 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = "</html>", "", ].join("\n"); - return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), bytes: Buffer.byteLength(html) }; + return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), diagrams: diagramNotes, bytes: Buffer.byteLength(html) }; +} + +/** + * A diagram's words, written into the page (DECISIONS 269, 1.19): each `<figure class="diagram">` that holds only its JSON gets the markup the diagram module's + * script would write for it, from that same script (parts/diagram.js, run here without a page), so the page reads before any script runs. The figure's own + * attributes stay (its class joins ours, its id stays); the JSON stays for the script. A figure whose JSON does not parse is left for the script, which says why. + */ +function writeDiagrams(content, parts, notes) { + if (!/\bdata-diagram\b/.test(content) || !exists(parts, "diagram.js")) return content; + let markup = null; + let serial = 0; + const figure = /<figure\b((?:"[^"]*"|'[^']*'|[^>"'])*)>(\s*<script\b(?:"[^"]*"|'[^']*'|[^>"'])*\bdata-diagram\b(?:"[^"]*"|'[^']*'|[^>"'])*>)([\s\S]*?)(<\/script\s*>)(\s*)<\/figure\s*>/gi; + return content.replace(figure, (whole, attrs, open, json, close) => { + if (!/\bclass\s*=\s*(?:"[^"]*\bdiagram\b[^"]*"|'[^']*\bdiagram\b[^']*')/.test(attrs) || /\bdata-diagram-drawn\b/.test(attrs)) return whole; + let spec; + try { spec = JSON.parse(json); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); return whole; } + if (!markup) { + const context = { window: { Basalt: { _: { step() {}, esc: (x) => x } } }, console: { warn() {}, error() {}, log() {} } }; + vm.runInNewContext(read(parts, "diagram.js"), context); + markup = context.window.Basalt._.diagramMarkup; + } + const made = markup(spec, `dg${++serial}`); + for (const w of made.warnings) notes.push(`${spec.title ?? "a diagram"}: ${w}`); + const ours = [...made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]); + const theirs = [...attrs.matchAll(/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g)].map((m) => [m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? ""]); + const merged = new Map(theirs); + for (const [k, v] of ours) { + if (k === "class") merged.set("class", [...new Set(`${merged.get("class") ?? ""} ${v}`.split(/\s+/).filter(Boolean))].join(" ")); + else if (k === "style") merged.set("style", merged.has("style") ? `${v};${merged.get("style")}` : v); + else merged.set(k, v); + } + const tag = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; + return `${tag}${open}${json}${close}${made.inner}</figure>`; + }); } /** The module lines of SKILL.md's "## Modules" index: [{ name, trigger, warning }]. A line is `- **name** \`trigger\`: warning`. */ @@ -707,6 +743,7 @@ if (isMain) { const say = (l) => (l.name in result.built ? ` ${l.name}: built by the ${result.built[l.name]}; nothing to check.` : ` ${l.name}: ${l.warning}`); if (warnings.length) console.log(`Check before you hand it over (the full text of one: --usage NAME):\n${warnings.map(say).join("\n")}`); } + for (const note of result.diagrams) console.log(`Diagram: ${note}`); // After the page and the modules' lines: what the body references that is not in the file. The page is written; the warning is for the one who handed it over. if (result.external.length) console.log(`Warning: ${result.external.length} reference${result.external.length === 1 ? "" : "s"} leave${result.external.length === 1 ? "s" : ""} the file, and a page is one file with no network (nothing loads offline; a link is the reader's to follow):\n${result.external.map((line) => ` ${line}`).join("\n")}`); } catch (e) { diff --git a/tools/html-skill/src/modules.json b/tools/html-skill/src/modules.json index 6f69410e..03ddece1 100644 --- a/tools/html-skill/src/modules.json +++ b/tools/html-skill/src/modules.json @@ -1,7 +1,7 @@ { "$comment": "Which parts of the skill's CSS and JS a page gets. The core is always in. A module is in when the page's body has one of its classes, attributes or tags, matches one of its text patterns, or is named in a <!-- basalt:use name --> comment, and when another module needs it (requires). Modules are added in the order listed here, which is the order of the source files' cascade. classes: every class the module's CSS styles (the test checks them against the CSS and against SKILL.md). budget: the most bytes its minified CSS and JS may reach together. budgets: skillMd (SKILL.md, the context an agent pays: never above what it was), core (the CSS and JS of every page). icons: Phosphor names the module's script draws itself. Raised in the first parity PR (the owner's \"bring up the parity\"): forms (the number-input, search-clear and file-input chrome), disclosure (the native details marker), status (the accent reader and the forced-colours badge border), spinner (a fixed 16px ring), and the new number, range and accent modules. skillMd rose 10555 to 10900 for the new rules (number field, native chrome, the braille rule, the accent). Raised in the second parity PR (popup rows, levels and the segment's pill): segment 1400 to 3700 (the shared sliding pill: its script, 1.5 KB, and its CSS with the pill's two fallbacks), rows 3600 to 4300 (#27's plate-in-a-row geometry, the plate per level, the glide's shared plate and the forced-colours lit row, net of the removed bar), palette 9400 to 11300 (the glide's script, 2.4 KB: it follows the lit row, travels on a pointer, snaps on a key, and fades in place on leaving). The art module (DECISIONS 101 and 104) is the token groups only some pages name, taken out of the core so the core stays under its cap: the chart roles and lengths, the art colours, the aspect ratios and the stage headroom, in both themes (2087 bytes at 2100; it grows only when a token of those groups is added). A page gets it when its body names one of them, a var() in its own style included. The every-module page has no cap of its own (owner, DECISIONS 79): each part is capped, and a page carries only the parts it uses. usage: the most bytes of a module's usage text (src/usage/NAME.md; core.usage for core.md), which compose.mjs --usage prints on demand. It is context an agent pays only for the modules its page uses, so it is capped per part as SKILL.md and the CSS and script are (DECISIONS 79 and 109). Each is set a little above what its text was when the usage moved out of SKILL.md (DECISIONS 109); raising one needs a reason in the PR, and a rise of 40 to 50% is the owner's. textWords: each text pattern said in words, which compose.mjs --usage prints instead of the regular expression (one for each entry of text, in order). builds: modules a module requires whose markup its script writes, so --usage prints a line saying so instead of their usage text (the palette builds its own rows and key chips). The council's clarity check of the usage texts (all three: not yet clear) raised eight caps because the texts gained what an agent had to guess: callout 200 to 700 (the icon and one wrapper div around the title and body as markup, the four status icons, the role React's Callout renders), palette 1100 to 1300 (an item shown whole, keys as an array, keywords), stats 450 to 800 (a snippet of the figures and of the dl), tabs 500 to 650 (the unselected panels), code 250 to 450 (the markup and what each token class means), segment 150 to 300 (a click does not switch it), progress 150 to 350 (the empty span that paints the fill), theme 250 to 400 (leave the button empty), and accent 250 to 300. Topbar went down, 700 to 500, as its build detail was cut. Raised in the usage PR (the council's clarity check): palette 11300 to 11450 (the module grew 11283 to 11448, +165, about 1.5%), for the guard that makes a string `keys` warn and draw no chip instead of throwing in `keys.filter`, which the palette's usage already promised. Round 2 of the clarity check: tabs 650 to 750 (the panel's top space shown in the snippet, and that the script selects a tab on click). Raised in the site-icons and status PR (skill-parity part A, DECISIONS 106 and 107): status 1650 to 1900 (the neutral, pending and running marks, the badge's real border, and the forced-colours disc, net of the red danger word it drops) and its usage 400 to 1000 (every status in words, the word alone, running, forced colours); rows 4300 to 4450 (the profile list's seat rule and the status parts on a lit row) and its usage 300 to 600 (the profile list, with the one mistake: never an empty element for the seat). New: the links module (2671 bytes: the social row, the new-tab arrow's CSS and the script that draws it; budget 2750) and its usage (1746 bytes; cap 1850), which carries the social link, the glyph set, icon only and the new tab. Dropping Regular halves icons.json. Added in the overlay PR (skill-parity-4, batch 7 step 2, DECISIONS 108): the shared plate leaves palette.js for a glide module (the palette, a menu and the notification centre all call it), so the palette's cap went down, 11450 to 9250, and rows 4450 to 3850 (the plate's CSS moved to glide); and the overlay layer comes in as seven modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: popover (the native popup shell), menu, dialog (the dialog and alert dialog), sheet (on every side, the top one the site header's narrow menu), tooltip, toast and notifications (the centre). skillMd is unchanged in its cap (the eight new index lines fit within it); the core is unchanged in bytes. Added in the figures and charts PR (skill-parity-5, batch 7 step 3, DECISIONS 108): four modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: meter (React's Meter, CSS only, 2581 bytes), dlist (the description list, CSS only, 1265), terminal (the code block's transcript: its CSS, 3242, and the script that draws the gutter, the copy button and the replay, 4824) and chart (React's TimeChart and ChartGroup: 7313 of CSS and 23262 of script, which port chart.tsx's scale, layout, lane, labels, sentences, keyboard and table; it needs the art tokens, the table and the kbd chips, and a page without a chart carries none of it). Stats grew for the source line (budget 700 to 850, 798 bytes; its usage 800 to 950, 675 to 899 bytes, +33%, under the owner's 40 to 50%). skillMd is unchanged in its cap (four index lines fit within it); the core is unchanged in bytes. Added in the forms and selection PR (skill-parity-6, batch 7 step 4, DECISIONS 108): six modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: select (React's Select: the native select's closed trigger in every browser and, where `appearance: base-select` is shipped, the styled list with its two-line rows; a small script that says which input lit a row, 7740 bytes before it, choice (Checkbox, Radio, RadioGroup and Switch as styled native inputs; CSS only, with the first-frame rule), choice-card (ChoiceCard; CSS only), toggle (the pressed toggle's plate and check seat on .btn; CSS only), selection (a table's checkbox column: its fixed width and the script that sets aria-selected, the mixed header box and the count) and loops (the page-level hold on every loop with its switch: the held look and the script that stores it). The select's styles left forms, whose budget fell 3650 to 3250. skillMd rose 8621 to the size of its six new index lines, within its cap; the core is unchanged in bytes; compose adds the stored-hold line to the head of a page that has the loops module. Revised in the same PR (the lead's review of the build): the select gains select.js (one row is lit at a time, by whichever of the pointer and the keys moved last), and choice, toggle, selection and loops carry the first-frame rule, so a state a script sets on load (a mixed header box, the stored hold) paints at once with no crossfade. Added in the navigation and layout PR (skill-parity-7, batch 7 step 5, DECISIONS 108): five modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: glyph (Basalt's core glyphs drawn by name, at rest and selected, from a table the build works out from the drawn set; a page carries only the glyphs it names, and the drawing of a core glyph from data-glyph left the sheet module, which draws none now), nav (React's Nav: the sidebar's, the narrow menu's and More's rows, with the shared hugging pill), topbar-nav (the site header's links, one action and narrow menu, built by script from the bar's markup), app-shell (the shell, its sidebar and rail, and the app header) and tab-bar (the phone tab bar). The topbar module became the site header's bar (React's SiteHeader, DECISIONS 108: 56px with its line inside, the 44 by 44 brand target, the narrow-screen buttons, the derived sticky offset), budget 1600 to 3200 because its rules gained the app header's shared smoke, and its usage 500 to 750 (+50%) for the lockup's markup (the links, action and menu are topbar-nav's usage). Glide 3700 to 3950: the navigation's pill is a shape inside the row that the plate follows (about 200 bytes). The core's usage 2000 to 2100 (+5%): h2 is the Section step, the prose column's measure, and a link already 44px tall needs no margin. skillMd rose 9317 to 9863 for five index lines, under its cap; the core CSS grew 38 bytes (the layout tokens replace raw lengths, the gutter is one derived property, h2, .prose and .lead follow foundations) and the core script is unchanged. A module's media query writes %bp-md%, %bp-lg% or %bp-container% and the build substitutes the breakpoint tokens. Added in the tables and filters PR (skill-parity-8, batch 7 step 6, DECISIONS 108): the existing table module gains React's table additions (DECISIONS 95: the row header, \"Not observed\", the row density and the scroll hint with its small script), budget 1400 to 3000 (it was 1134 bytes of CSS; it is 2168 of CSS and 693 of script) and its usage 700 to 950 (+36%); and two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: still-table (React's Table with `columns`: the fixed layout from a colgroup, the whole header cell as the sort button with its reserved seat, aria-sort, the pinned columns and their divider, the empty row; 4767 of CSS and 3264 of script, budget 8200) and filter (React's MultiSelect and FilterResult: the chips, the trigger and checklist with the search band from ten values, Clear held in place, the one debounced result line, and the narrowing of a table by `data-column`; 8240 of CSS and 7978 of script, budget 16400; it needs the popover, glide, glyph and choice modules). The core is unchanged in bytes. skillMd rose 9863 to 10128 for two index lines and the CaretUpDown icon's name, within its cap. Added in the commands PR (skill-parity-9, batch 7 step 7, DECISIONS 103 and 108): one new module a page carries only when it uses it, command-list (React's CommandList: the command panel set in the page, list plus preview, the push; it extends the palette and needs rows, kbd and glide; 5229 of CSS and 8734 of script, budget 14000, usage 2150). Two-line rows come to the existing modules: rows 3850 to 5350 (the described row's grid and description line, the push's chevron: 1481 bytes of CSS, the same rules React's menu rows carry), palette 9250 to 9900 (its rows are one function the list shares, with the description and the two-tier ranking of title matches over keyword and description matches; +636) and its usage 1300 to 1350, rows' usage 600 to 800, and glide 3950 to 4000 (a host that is idle counts as having no lit row, +54). skillMd rose 10128 to 10259 for one index line, within its cap; the core's CSS grew 24 bytes (.split.aside takes size-list-width in place of its raw 20rem: the same 320px, so no pixel moves) and the core script is unchanged. Added in the art PR (skill-parity-10, batch 7 step 8, DECISIONS 104 and 108): two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: stage (React's Stage and PairedArt: full-bleed art under the site header, the pull-up by the sticky offset, the headroom, the paired art that follows the page's theme, and the forced-colours and print rules; CSS only, 1179 bytes) and framed-art (React's FramedArt: the figure, its rim and radius, the reserved box, the placeholder and the failed alt, the caption and credit; 2208 bytes of CSS and the 733-byte script that sets the frame's phase); both need the art tokens. The bar stays smoked over a stage: React clears it only over a stage that passed the headroom test helper, and a page has no test run (DECISIONS 108's note), so the skill builds no clear state. skillMd rose 10259 to 10500 for two index lines, within its cap; the core is unchanged in bytes. The callout gained the status rim in the same PR (DECISIONS 82, D8's status callouts): success, warning and danger draw their border in the status colour at 45% mixed in sRGB over the callout's own level, one solid colour on every side, and CanvasText in forced colours with the icon; the status colour is now one property the icon and the rim read. Its budget rose 900 to 1150 (the module is 1089 bytes, from 792: +297, about 37%); its usage is unchanged. Added in the overlays-and-the-rest PR (skill-parity-11, batch 7 step 9, DECISIONS 90 and 108): the last two parts of D8's part 5, each a module a page carries only when it uses it, with its own cap and usage cap set a little above its size: combobox (React's Combobox: the input with its caret button inside, the popup of the menu's rows with the glide's shared plate and two-line options, the filtering, the keys, the hidden value, the empty message and the check; 4342 of CSS and 6423 of script, budget 10900, usage 2150; it needs forms, popover and glide, and builds the last two) and sparkline (React's Sparkline: the label and latest value, the line, the axis, the empty sentence and the loading line that breathes; 1609 of CSS and 1874 of script, budget 3600, usage 950). The combobox copies the menu's row rules, as the select's list does, because React's Combobox renders MenuItem rows (a 40px hit area, a 36px plate) and the skill's .row is the palette's 44px: it carries no menu script. popover.js gains the combobox popup in the list of popups that keep focus where it is (+21 bytes, within its cap). skillMd rose 10500 to 10724 for two index lines, within its cap; the core is unchanged in bytes. Added in the motion-rules PR (DECISIONS 136 and 139): one module, ambient (a page's one ambient loop: CSS 828 bytes, script 433, budget 1300, usage 800), taken out of loops so the hold's own module grows only by the icon toggle's glyph swap (loops 2000 to 2200, +10%; its usage 1300 to 1650 for the icon form and the new settings-row sentence, +27%); and the chart's entrance (`entrance: true`: the marks' animations, their conditions and the redraw that restarts them at the elapsed time, 23262 to 25299 bytes of script; budget 30700 to 32800, +7%, usage 2500 to 2950, +18%). The core grew by the three tokens (27704 to 27862 bytes of CSS, under its cap). its stage usage gained the ambient art's line (1650 to 1750, +6%). skillMd rose 10724 to the size of the ambient index line, within its cap. Raised again in the motion-rules amendment (DECISIONS 143): chart 32800 to 33800 (script 25299 to 26375 bytes, +4%; +10% over the 30700 it began with) for the glide a new data set makes mid-entrance, print settling it, and `Basalt.pageChange()`; its usage 2950 to 3150 (+26% over the 2500 it began with). Raised in the second motion-rules amendment (DECISIONS 148): chart 33800 to 34400 (script 26375 to 26970 bytes: a line and its markers glide from their drawn geometry, and `beforeprint` settles the entrance; +12% over the 30700 it began with); topbar-nav 6900 to 7500 (+8.7%: the narrow menu's pause row, its CSS and 275 bytes of script, DECISIONS 148 item 2); loops usage 1650 to 1800 (+38% over the 1300 it began with, for the icon form's `title` and the menu row). Raised in the audit-design-b PR (DECISIONS 138 and 139): still-table 8200 to 13400 (+63%: the module was 7927 bytes and is 13311; the cut cell's plate, its focus stops and its dismissal, ported from React's cell-peek.ts, are 4273 bytes of script and 1111 of CSS; a still table that truncates needs them). The same PR: core usage 2100 to 2250 (+7%: the skip link, one bullet), forms usage 350 to 480 (+37%: the required mark), still-table usage 1950 to 2150 (+10%: the cut cell and the width rule), notifications usage 1050 to 1100 (+5%: the 44px entry on touch). The skip link's rim and radius took the core 30457 to 30609 bytes, under its cap (the rules that hang it under the bar are the topbar module's: 3200 to 3600, +12.5%); core 30720 to 31050 (+1.1%, DECISIONS 147: also the bar's links left out of the rule: the pseudo-element that makes a short standalone link a 44 by 44 target), skip-link script in the topbar module (3200 to 4150 over this PR, +30%: the rules that hang the link under the bar, 3600, and the script that reads the bar's real edge, 4150), sparkline 3600 to 4050 (+12.5%: React's ticker structure, so the value copies once on its line, and in forced colours the strips go and the number is plain text), forms budget 3250 to 3500 (+7.7%: the necessity word), notifications 9050 to 9250 (+2.2%: the 44px entry). Raised in the audit-design-b PR's E2 port (DECISIONS 138 and 139: the core set draws check, close, the chevrons, copy, plus, minus and search wherever a component draws them): the modules that drew a Phosphor icon for one of those now carry the core glyph's whole SVG, written in at build time (`%glyph-svg:name%`, the markup the glyph module's `_.glyph(name)` returns, so no module needs the glyph module and a page pays for nothing it does not use), and the Phosphor path of the same icon leaves the page. Each module's own bytes rose by that markup, and a page's total moved by what the Phosphor path it no longer carries saves: menu 8600 to 8900 (+303), combobox 10900 to 11200 (+303), copy 1900 to 2400 (+640), terminal 8100 to 8850 (+761), toast 13850 to 14150 (+325), number 2900 to 3400 (+557), filter 16400 to 17050 (+785), palette 9900 to 10450 (+536); the command list shares the palette's search drawing and fell 20 bytes. Set in integration-nov15, where the type-layout, motion-rules and audit-design-b branches meet: the combined tree measured SKILL.md 10959 bytes (each side's cap was 10900: both added index lines), core 31192 bytes (caps 30720 and 31050: the page-row and display rules, the three motion tokens and the skip link and 44px target rules all land in the core CSS) and core usage 2348 bytes (caps 2300 and 2250: type-layout's line and the skip-link bullet), so each is set to the measured bytes rounded up to the next 50: skillMd 10900 to 11000, core 31050 to 31200, core usage 2300 to 2350. Raised in the audit-design PR (decisions 138 and 139, parts A, D and C11): core 30720 to 31600 (+2.9%: the more-contrast block and its three aliases, and the field boundary token, every page carries as React does; the shadow-pill token is gone; the script gained `reserve`, 240 bytes), segment 3700 to 4100 and tabs 2300 to 2700 (the chosen label is 600 against 400, its width reserved by a span that carries its own copy, drawn unseen at 600; the pill's drop shadow is gone), and the segment's usage 300 to 380 (the weight and the glyph-only button). Raised again in the audit-design-a amendment (decision 145): core 31600 to 32300 (reserve() also reserves a label that is not plain text), segment 4100 to 5100 and tabs 2700 to 3500 (the second copy of such a label, and an icon drawn in both its forms), glyph 1100 to 1300 (a glyph in a segment or tab is drawn in both forms). Raised in the second audit-design-a amendment (decision 149): core 32300 to 32800 (reserve() builds the second copy of a label without any id, name, reference or hidden control, and does not copy a frame or media), segment 5100 to 5400 and its usage 380 to 500 (the 600 is on the label, the one-line rule and the usage text); the still-table cap is back at 8200, as the wash is on every cell again. Return 3 of the audit-design-a build (decision 149): tabs 3500 to 3700 (a tab the script has not reserved is 600 itself when selected, and one it declined is marked; the same two lines are in segment, which stays under 5400). Raised in the audit-fix-c2 PR (engineering, no pixel changes): toast 13850 to 14350 (the module was 13789 bytes and is 14288, +499, 3.6%) for F6, which focuses the Notifications region and Shift+Tab or Escape from it (or from the first toast) leaves it for where focus came from (and keeps a dialog's focus trap from wrapping it), as Base UI's viewport does in React, and for placing the region from focus (in the modal that holds it, or in the body), so a toast is never under a backdrop or in an inert modal whatever order the modals opened in (A3-09); the palette module grew 9864 to 9897 of its 9900 so that a palette opened over a modal sits inside it; topbar 3200 to 3250 (3123 to 3233, +110) for the scroll margin on what the bar holds, so a Tab into the bar from a scrolled page does not scroll the page (React's rule from PR #66); stage usage 1650 to 1750 (1580 to 1713, +8%) for the art's new place in the markup, after the content (A1-09), the stage's own CSS rising 1179 to 1208 within its 1250. skillMd rose 10724 to 10876 for the sentence that says a body may carry head tags, within its 10900. compose.mjs, the tool an agent runs, has no cap here (it is never in a page): it grew 21673 to 38153 bytes for the tokenizer that reads a body as HTML does and the head tags. Raised in the site-parts PR (DECISIONS 146, round 39), which folds each new part into the module it belongs with, so SKILL.md gains no index line (it has 41 bytes under its cap and a new module needs about 100): topbar 4150 to 17600 (+13450: the site footer and its disclosures, the lockup by pixel density, and a bar that arrives or leaves and returns, with its observer; a page that has a .topbar and no footer carries them too: the alternative, a module for each, needs its own index line and so SKILL.md bytes) and its usage 950 to 2900 (the footer's markup, the lockup's and the phase's); theme 650 to 4550 (the three-word theme choice: its CSS 2230 bytes and its script, 2277, with arrows, storage and the system listener) and its usage 400 to 1150 (the choice's markup written in full, so the right word is chosen before any script); segment 3700 to 3800 (a radio group's checked state besides a pressed button); stage 1250 to 2150 (its first script, 768 bytes, for fit and anchor) and its usage 1750 to 2000; framed-art 3000 to 3900 (drawn art in the frame: fit, anchor, no scaling strokes) and its usage 1250 to 1400. SKILL.md rose 10959 to 10992 (the topbar and theme index lines name .site-footer and .theme-choice). The head's theme line also writes data-theme-choice. Raised in site-parts return 2 (DECISIONS 146 B1 and B4): theme 4550 to 5350 (+800: the icon form of the theme choice, [data-theme-menu], whose button shows the theme in use, is named for the choice and opens the page's own .menu of three radio rows, in the theme script's 3073 bytes; the menu and popover modules are the page's, brought by its markup, so no module line was added and SKILL.md is 10993 of 11000) and its usage 1150 to 2200 (+91%: the menu's markup is written in full, and the deprecated toggle is said once); app-shell usage 2000 to 2100 and topbar-nav usage 1900 to 1950 (the theme control leaves the bar's text; the tools and the end cluster come in). The two example bodies still carry the deprecated data-theme-toggle. Return 2, F3 (DECISIONS 146 F): stage 2150 to 2250 (script 842 bytes: slice is the stage's default, as a frame's, and a drawing's own preserveAspectRatio stands unless the stage names data-fit or data-anchor) and its usage 2000 to 2150. framed-art 3900 to 4000 (a drawing's own preserveAspectRatio stands unless the figure names data-fit or data-anchor, +101 bytes). Return 3: theme 5350 to 5900 (script +569 bytes: who wrote data-theme, so System follows the system's change live and a theme the page set by hand, or a .dark or .light root, survives it). Raised in the controls port (DECISIONS 154): skillMd 11000 to 11200 for two index lines (link-tabs and option-chips, 214 bytes together), and core 31200 to 31600 for the nine tokens the port adds to every page's token CSS (the control rungs 44 to 64, two container widths, the confirm hold and the amount's opacity, 311 bytes). New modules (DECISIONS 154): link-tabs 2700 (its sizes, the 640 container step, the forced-colours underline, and the select that replaces the row under 720 with its 590-byte script, A15; it requires the select module), option-chips 5700 (the chip's states each written for a native radio inside a label, which needs :has on every one, plus the 1 KB script that keeps an aria-disabled chip reachable and never chosen). Return 3 (DECISIONS 154 conformance): link-tabs 2700 to 3100 and its usage 1650 to 1850 (the select's height for each row size, and a script that reads aria-current when it is needed and watches it move: 3,048 bytes), option-chips 5700 to 6700 (each state written twice, as a state attribute and as :has(), so no browser needs :has(): 4,975 CSS and 1,623 script). Return 4 (DECISIONS 158, Q2): link-tabs 3100 to 4300 and its usage 1850 to 2400 (the \"Go to\" label drawn at the select's start with its measured clearance, the select's accessible name kept as the words and the chosen page's, and the key hold that keeps a letter or an arrow on the closed select from navigating: 4,174 bytes, CSS 2,951 and script 1,223). Raised in the links-and-rows port (DECISIONS 152; the owner's approval is the lead's to confirm): the new link-rows module (5050 bytes of CSS, 50 of them for Castle's big-row arrow stepping colour over duration-fast, return 1, 1500 of usage: the directory's and the big rows' CSS, whose arrow is a core glyph drawn as a mask, and their tokens, size-row taken out of the core like type-layout's), disclosure 1550 to 3500 (Show all: the track, the clip and the settle, 1.5 KB of script and 1.8 KB of CSS), copy 2400 to 3500 (the form with words: the one cell and its script). SKILL.md rose 10959 to 10997 for one line, within its 11000 cap. Raised in the charts port PR (DECISIONS 153, D7a): chart 34400 to 34650 (script 26970 to 27270 bytes, +1.1% on the 34283 it was: `Basalt.trailingMean`, the trend maths React exports as `trailingMean`, 300 bytes), its usage 3150 to 3350 (+6%: one line for it). The tokens the batch adds (chart-lit-top, -mid and -base in both themes, size-chart-plot-sm, size-chart-row, size-meter-marker and radius-2xs) took the art module 2087 to 2546 bytes (budget 2100 to 2600, +24%: the chart tokens are its group) and the core 31192 to 31250 (cap 31200 to 31300, +0.3%: radius-2xs). Only D7a names a skill module in the charts ballot; the lit marks, the headline frame, the phase chart, the share bar, the coverage strip, the marks row and the range meter are React-only in this batch. Added in the overlays-and-search PR (DECISIONS 155, D10b and D13a): the sheet gains React's head, body and foot (the 44px close, the 20/28 title over a 13px count, the divider and the safe areas; its CSS 3.6 to 5.2 KB, budget 4050 to 5250, +30%) and its usage 1050 to 1450 (+38%: the anatomy and the step's focus, two bullets); and one new module a page carries only when it uses it, search (React's SearchDialog: the form, the field's -2 outline, the count line, the fixed-height results area and the rows with their picture slots and full-bleed hover wash; CSS only, 4368 bytes, budget 4400, usage 2050; it requires the dialog). The dialog's title draws no ring when script focuses it. skillMd rose 10959 to 11079 for the search line (the sheet's line is unchanged: its usage carries the anatomy), so its cap rose 11000 to 11100 (+0.9%). The core's CSS grew 31192 to 31421 bytes for the six new size tokens (the wide dialog, the search trigger and the logo and picture slots of a search result): its cap rose 31200 to 31450 (+0.8%). The two 44px values (the sheet's close and the search field) are local to their modules, with a lint exception that says they join the controls batch's size token (DECISIONS 154). Set in integration-nov15b, where audit-design-a, audit-fix-c2, site-parts, port-controls, port-links-rows, port-charts and port-overlays-search meet: the combined tree measured SKILL.md 11560 bytes (the caps were 11000, 11100 and 11200: each side added index lines), core 34086 bytes (caps 31300 to 33550: every side's rules land in the core CSS and script), topbar 17660 (17600 from site-parts, plus audit-fix-c2's skip-link and focus work), number 3453 (3400), palette 11379 (11000, audit-fix-c2's hosted scrim plus the core search glyph), dialog 5120 (5100), toast 15692 (15400) and stage usage 2248 (2150), each over every side's cap, so each is set to the measured bytes rounded up to the next 50: skillMd 11200 to 11600, core 33550 to 34100, topbar 17600 to 17700, number 3400 to 3500, palette 11000 to 11400, dialog 5100 to 5150, toast 15400 to 15700, stage usage 2150 to 2250. The segment cap is the base's 5400 plus port-controls' 100 (5500), unchanged by the merge. Raised in integration-nov15b, join 2 (a link tab takes the selected state, DECISIONS 138 A, 145, 149 and 154's D12 row): link-tabs 4300 to 5750 (+34%: the module was 4174 bytes and is 5736; the 600 against 400, the reserved width and the second copy of a composed label, an icon drawn in both its forms, the same rules a tab carries, 1,530 bytes of CSS and script) and its usage 2400 to 2550 (+6%: one bullet). The cap is the measured bytes rounded up to the next 50; a module that needs the tab's rules carries them as the segment and tabs modules do, so a page without link tabs pays nothing. Raised in the panels, art and parts port (DECISIONS 162): table 3000 to 3150 and its usage 950 to 1450 (the flat form and the two-line cell), stage 2250 to 2600 and its usage 2250 to 3100 (the closing block: its held art, forced colours and print; its section gap is type-layout's --basalt-section-gap, which a page with data-closing brings), the new app-tile 4300 (a 120-point polygon clip and the hairline's mask of the same outline), captioned 2000 and period 1400; skillMd 11600 to 11950 for one index line each for captioned, app-tile and period (358 bytes; the file is 11918). Raised in the logs, status and forms port (DECISIONS 162): core 34100 to 34200 (the new size-field-label-inline token, 80px, is written into every page's tokens: 25 bytes); dlist 1300 to 1900 and its usage 950 to 1060 (the stacked form, R9 and R10: a title over its text, 20px between entries, no divider; one usage line). Raised in audit-fix-c6 (the owner's cap, raised by the builder and for the owner to confirm): glyph 1300 to 1900, for redrawing a glyph when its ancestor's aria-current or data-current moves (the lists that hold glyphs are watched). Raised in the colour-ink-ladder build (DECISIONS 166): core 34200 to 34350 (the four lifted dark inks are four new primitives, each written into every page's tokens: the core measured 34307). Raised in the audit-2-design build (DECISIONS 167, Q7a): disclosure 3500 to 3800 (the core chevron drawn as a mask in place of two borders: the module measured 3755). Joined in the integration of c7 (#86) and c10 (#91): option-chips 6750 to 6850 (c7's reset resync and c10's data-ready together measure 6839). Raised in table-sort-3 (DECISIONS 257 and 261, the owner's pick: three sort states, the arrow after the label, explainers on column titles): still-table 13400 to 14650 (+9.3%: the module was 13343 bytes and is 14602; the end-aligned label's move by a transform, its right-to-left sign and the indicator that waits for it on a fine pointer, 912 bytes of CSS; the third state, the sort from the table's own order and a .explainer kept out of the button, 347 bytes of script) and its usage 2150 to 2250 (2197: the third state and the own order); the new explainer module 5850 (5842: a manual native popover opened from the sort button on hover, keyboard focus and a long press, placed above the header or beside it, 1752 bytes of CSS and 4090 of script; a page without explainers pays nothing) and its usage 900; skillMd 12250 to 12400 for the explainer's index line (113 bytes; the file is 12352). Each cap is the measured bytes rounded up to the next 50. Raised in table-sort-3's fix pass (Astra's review): explainer 5850 to 6900 (+18%: 5842 to 6864 bytes; the gap between the header and the card kept while a pointer crosses it, the close when its header leaves the view whatever has focus, the dismissal held until pointer and focus have both left, and its page-wide listeners and timers scoped to an open card and stopped when the table leaves the page, 1,022 bytes of script).", "budgets": { - "skillMd": 12400, + "skillMd": 12500, "core": 34550 }, "core": { @@ -697,6 +697,90 @@ "kbd" ] }, + "diagram": { + "classes": [ + "diagram", + "diagram-actor", + "diagram-arrow", + "diagram-band", + "diagram-cast", + "diagram-cname", + "diagram-code", + "diagram-ctype", + "diagram-detail", + "diagram-diamond", + "diagram-dot", + "diagram-drawing", + "diagram-edge", + "diagram-entry", + "diagram-fk-mark", + "diagram-foot", + "diagram-gbox", + "diagram-glabel", + "diagram-group", + "diagram-head", + "diagram-hint", + "diagram-ink", + "diagram-key", + "diagram-keyseat", + "diagram-kind", + "diagram-label", + "diagram-lane", + "diagram-lane-name", + "diagram-lane-word", + "diagram-legend", + "diagram-life", + "diagram-line", + "diagram-list", + "diagram-list-exits", + "diagram-list-group", + "diagram-list-head", + "diagram-list-items", + "diagram-mlabel", + "diagram-more", + "diagram-msg", + "diagram-msgs", + "diagram-name", + "diagram-node", + "diagram-note", + "diagram-num", + "diagram-route", + "diagram-row", + "diagram-rows", + "diagram-ruler", + "diagram-said", + "diagram-source", + "diagram-steps", + "diagram-summary", + "diagram-svg", + "diagram-swatch", + "diagram-swatch-shape", + "diagram-th", + "diagram-tip", + "diagram-title", + "diagram-tname", + "diagram-toggle", + "diagram-words" + ], + "attrs": [ + "data-diagram" + ], + "text": [ + "Basalt\\s*\\.\\s*diagram\\b" + ], + "textWords": [ + "a call to Basalt.diagram" + ], + "requires": [ + "art", + "kbd" + ], + "budget": 82300, + "usage": 2600, + "builds": [ + "kbd" + ] + }, "sparkline": { "classes": [ "sparkline", diff --git a/tools/html-skill/src/modules/diagram.js b/tools/html-skill/src/modules/diagram.js new file mode 100644 index 00000000..822c3120 --- /dev/null +++ b/tools/html-skill/src/modules/diagram.js @@ -0,0 +1,161 @@ +/* Basalt HTML script, diagram module (DECISIONS 269, revised by 270): `<figure class="diagram">` holding `<script type="application/json" + data-diagram>` is drawn from that JSON (the React props, key for key), or `Basalt.diagram(figure, spec)` draws one from script. The engine + is React's own (packages/react/src/diagram-core.ts): build.mjs bundles it into this module, so the skill and React lay out, route, seat + and draw the same pixels. compose.mjs runs `Basalt._.diagramMarkup` at build time and writes each figure's words into the page, so it + reads before any script runs; this script then measures it, draws its lines and labels, and wires the keys, the trace and the list. + Source: tools/html-skill/src/modules/diagram.js (do not edit the copy in the skill folder). */ +import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, keyTarget, measureFigure, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts"; + +(function (B) { + 'use strict'; + var _ = B._; + var P = 'diagram'; + var serial = 0; + + function options(base, spec) { + return { prefix: P, base: base, hasSource: spec.source !== undefined && spec.source !== null && spec.source !== '', hiddenClass: 'visually-hidden' }; + } + function slots(model, spec, base, open) { + var kbd = function (k) { return '<kbd class="kbd">' + escapeHtml(k) + '</kbd>'; }; + return { + source: escapeHtml(String(spec.source || '')), + summary: escapeHtml(String(spec.summary || '')), + hint: hintEntries(model).map(function (e) { return '<span>' + e.keys.map(kbd).join(' ') + ' ' + escapeHtml(e.words) + '</span>'; }).join(''), + toggle: '<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="' + (open ? 'true' : 'false') + '" aria-controls="' + base + '-list"><span>' + (open ? 'Hide the list' : 'View as list') + '</span></button>', + }; + } + + /** The figure's markup before script runs: its attributes and its inside, as compose.mjs writes it (and as this script writes it for a figure that has none). */ + function markup(spec, base) { + var model = buildModel(spec); + var tree = figureTree(model, {}, options(base, spec)); + var html = toHtml(tree, slots(model, spec, base, false)); + var open = html.indexOf('>'); + return { open: html.slice(0, open + 1), inner: html.slice(open + 1, html.length - '</figure>'.length), warnings: model.warnings }; + } + + function draw(figure, spec) { + if (figure.__diagram) figure.__diagram.stop(); + var base = (figure.getAttribute('aria-labelledby') || '').replace(/-title$/, ''); + var model = buildModel(spec); + if (!figure.querySelector(':scope > .diagram-drawing')) { + // No markup from compose (a figure drawn from script): write it now, keeping the JSON and the figure's own attributes. + while (document.getElementById('dg' + (++serial) + '-title')) { /* the next free base */ } + base = 'dg' + serial; + var made = markup(spec, base); + var holder = document.createElement('div'); + holder.innerHTML = made.open + '</figure>'; + var fresh = holder.firstChild; + for (var a = 0; a < fresh.attributes.length; a++) { + var at = fresh.attributes[a]; + if (at.name === 'class') figure.classList.add.apply(figure.classList, at.value.split(' ')); + else if (at.name === 'style') figure.style.cssText = at.value + ';' + figure.style.cssText; + else figure.setAttribute(at.name, at.value); + } + figure.querySelectorAll(':scope > :not(script[data-diagram])').forEach(function (el) { el.remove(); }); + figure.insertAdjacentHTML('beforeend', made.inner); + } + model.warnings.forEach(function (w) { console.warn('Basalt diagram: ' + w); }); + var opts = options(base, spec); + var state = {}; + var measured = null; + var focusTrace = null, hoverTrace = null; + var warned = {}; + var warn = function (m) { if (!warned[m]) { warned[m] = 1; console.warn('Basalt diagram: ' + m); } }; + var apply = function (d) { syncAttributes(figure, figureTree(model, d, opts)); }; + var ink = figure.querySelector('.diagram-ink'); + var toggle = figure.querySelector('.diagram-toggle'); + + function retrace() { applyTrace(figure, P, measured && measured.geo, measured && measured.tokens, base, focusTrace || hoverTrace); } + function layout() { + measured = measureFigure(figure, model, P, base, state, apply, warn); + state = measured.dyn; + apply(state); + if (ink) ink.innerHTML = measured.ink; + retrace(); + } + function setState(next) { state = next; apply(state); } + var nodeOf = function (t) { var el = t && t.closest ? t.closest('.diagram-node') : null; return el && figure.contains(el) ? el : null; }; + + function onKey(event) { + var node = nodeOf(event.target); + if (!node || event.defaultPrevented) return; + if (event.key === 'Escape') { if (focusTrace || hoverTrace) { event.preventDefault(); focusTrace = hoverTrace = null; retrace(); } return; } + if (!hasStops(model, state)) return; + var to = keyTarget(model, node.getAttribute('data-node'), event.key); + if (!to) return; + event.preventDefault(); + setState(Object.assign({}, state, { stop: to })); + var el = figure.querySelector('.diagram-node[data-node="' + CSS.escape(to) + '"]'); + if (el) el.focus(); + } + function onFocusIn(event) { + var node = nodeOf(event.target); + if (!node) return; + var id = node.getAttribute('data-node'); + // Tracing follows the keyboard's focus (:focus-visible), so a press that focuses a node traces nothing. + focusTrace = node.matches(':focus-visible') ? id : null; + if (hasStops(model, state) && state.stop !== id) setState(Object.assign({}, state, { stop: id })); + retrace(); + } + function onFocusOut(event) { + var left = nodeOf(event.target); + if (!left) return; + if (!nodeOf(event.relatedTarget)) focusTrace = null; + if (state.keep === left.getAttribute('data-node')) setState(Object.assign({}, state, { keep: undefined })); + retrace(); + } + function onOver(event) { + if (event.pointerType !== 'mouse' || !matchMedia('(hover: hover)').matches) return; + var node = nodeOf(event.target); + var next = node && hasStops(model, state) ? node.getAttribute('data-node') : null; + if (next !== hoverTrace) { hoverTrace = next; retrace(); } + } + function onLeave() { if (hoverTrace) { hoverTrace = null; retrace(); } } + function onToggle() { + var open = !state.open; + setState(Object.assign({}, state, { open: open })); + toggle.setAttribute('aria-expanded', String(open)); + toggle.firstElementChild.textContent = open ? 'Hide the list' : 'View as list'; + } + + figure.addEventListener('keydown', onKey); + figure.addEventListener('focusin', onFocusIn); + figure.addEventListener('focusout', onFocusOut); + figure.addEventListener('pointerover', onOver); + figure.addEventListener('pointerleave', onLeave); + if (toggle) toggle.addEventListener('click', onToggle); + layout(); + var width = figure.clientWidth, frame = 0, live = true; + var observer = new ResizeObserver(function () { + if (Math.abs(figure.clientWidth - width) < 0.5) return; + width = figure.clientWidth; + cancelAnimationFrame(frame); + frame = requestAnimationFrame(layout); + }); + observer.observe(figure); + if (document.fonts) document.fonts.ready.then(function () { if (live) layout(); }); + figure.__diagram = { + stop: function () { + live = false; observer.disconnect(); cancelAnimationFrame(frame); + figure.removeEventListener('keydown', onKey); figure.removeEventListener('focusin', onFocusIn); figure.removeEventListener('focusout', onFocusOut); + figure.removeEventListener('pointerover', onOver); figure.removeEventListener('pointerleave', onLeave); + if (toggle) toggle.removeEventListener('click', onToggle); + }, + layout: layout, + }; + } + + function wireDiagrams() { + document.querySelectorAll('figure.diagram').forEach(function (figure) { + if (figure.__diagram) return; + var source = figure.querySelector(':scope > script[data-diagram]'); + if (!source) return; + try { draw(figure, JSON.parse(source.textContent)); } catch (e) { console.error('Basalt diagram: this figure could not be drawn', e); } + }); + } + + _.diagramMarkup = markup; + B.diagram = function (figure, spec) { draw(figure, spec); }; + _.step(62, 'wireDiagrams', wireDiagrams); +})(window.Basalt); diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md new file mode 100644 index 00000000..c0089b27 --- /dev/null +++ b/tools/html-skill/src/usage/diagram.md @@ -0,0 +1,23 @@ +# diagram + +``` +<figure class="diagram"> + <script type="application/json" data-diagram> + { "type": "architecture", "title": "How a request reaches the agent", "source": "docs/architecture.md", + "summary": "…", "legend": { "main": "Request path", "plain": "Call", "dashed": "Async or one-way", "focal": "The service" }, + "groups": [{ "id": "aws", "label": "AWS · your account" }], + "nodes": [{ "id": "svc", "kind": "ECS service", "name": "cimip service", "detail": "N tasks", "detailMono": true, + "focal": true, "group": "aws", "col": 3, "row": 2 }], + "edges": [{ "from": "alb", "to": "svc", "kind": "main", "label": "HTTP" }] } + </script> +</figure> +``` + +Boxes and the lines between them. `compose.mjs` writes the figure's words into the page (it reads before script); the script draws the lines, the labels, the keys and "View as list". `Basalt.diagram(figure, spec)` draws one from script. + +- **Five shapes of data** (`type`): `architecture` (`nodes` with `group`, `groups`, `edges`); `flowchart` (`nodes` with `shape`: `step`, `decision` or `terminal`, the first node the start; `edges`, a branch's `label` its condition); `data-flow` (`lanes`, `nodes` with `lane` and `col`, its step columns; `edges`); `sequence` (`participants` with `short`; `steps`: `{ from, to, label, note, kind }` or `{ band }`); `schema` (`tables`: `name`, `col`, `row` or `[first, last]`, `columns` with `key` `PK`/`FK` and `references: "table.column"`, `more`). +- **Order is one thing:** the array's order is the stacked order, the focus order, the list's, a data flow's step numbers and a sequence's message numbers. +- **Place, don't route:** `col` and `row` are whole tracks from 1. Sides, slots, jogs, lanes, the group's box and a foreign key's line are derived. Write `fromSide` or `toSide` (`top`, `right`, `bottom`, `left`) only to change the default. `branch: true` indents a node in the stacked drawing. +- **Lines:** `kind` is `main` (2px), `plain` (default) or `dashed` (a reply, a stream). One `label` each, at most 28 characters. `legend` gives each kind its words; `main`, `dashed` and a `focal` node must have words. One node at most is `focal`. +- **Required:** `title`, `summary` (what it shows, in a sentence). `source`, `heading` (2 to 6, default 3). +- Monochrome: nothing takes a colour. The drawn layout is used only where it fits; otherwise the figure is stacked, one column at most 480 wide. diff --git a/tools/html-skill/test/compose.test.mjs b/tools/html-skill/test/compose.test.mjs index bf5879e8..b332c01d 100644 --- a/tools/html-skill/test/compose.test.mjs +++ b/tools/html-skill/test/compose.test.mjs @@ -392,7 +392,8 @@ describe("the command line", () => { test("uses no network and no module outside node:, so it runs from the skill folder anywhere", () => { const source = read(skillDir, "compose.mjs"); - assert.deepEqual([...source.matchAll(/^import .* from "([^"]+)"/gm)].map((m) => m[1]).sort(), ["node:fs", "node:path", "node:url"]); + // node:vm runs the diagram module's own script to write a figure's words into the page (DECISIONS 269, 1.19): still Node's own, no network. + assert.deepEqual([...source.matchAll(/^import .* from "([^"]+)"/gm)].map((m) => m[1]).sort(), ["node:fs", "node:path", "node:url", "node:vm"]); assert.doesNotMatch(source, /\bfetch\(|https?\.request|node:(net|http|https|dns|child_process)/); }); }); diff --git a/tools/html-skill/test/diagrams.test.mjs b/tools/html-skill/test/diagrams.test.mjs new file mode 100644 index 00000000..6c0f4db9 --- /dev/null +++ b/tools/html-skill/test/diagrams.test.mjs @@ -0,0 +1,166 @@ +// The skill's `diagram` module (DECISIONS 269, revised by 270): the five CIMIP diagrams composed into a page, against React's components drawn at the same width. +// The module bundles React's engine, so the two must lay out, route, seat and draw the same pixels: the ink (every path, head, dot and label) is compared as markup, +// each node's box to the half pixel, and the parts' computed styles. Then what compose.mjs writes before any script runs, the keys, the trace, the modes and axe. +// Written for DECISIONS 269 section 7; the implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; + +import { compose } from "../../../.agent/skills/basalt-html/compose.mjs"; +import { inspectSource } from "../../../packages/react/test/diagram-geometry.mjs"; +import { fixturePage, launch as launchReact, pkg } from "../../../packages/react/test/support.mjs"; +import { launch, openHtml } from "./support.mjs"; + +const require = createRequire(import.meta.url); +const axeSource = fs.readFileSync(require.resolve("axe-core/axe.min.js"), "utf8"); +const DATA = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8")); +const KEYS = Object.keys(DATA); +const font = (file) => fs.readFileSync(path.join(pkg, "dist", "fonts", file)).toString("base64"); +const FONTS = `@font-face{font-family:"Geist";src:url(data:font/woff2;base64,${font("Geist-Variable.woff2")}) format("woff2");font-weight:100 900}@font-face{font-family:"Geist Mono";src:url(data:font/woff2;base64,${font("GeistMono-Variable.woff2")}) format("woff2");font-weight:100 900}`; + +let browser; +let reactBrowser; +before(async () => { browser = await launch(); reactBrowser = await launchReact(); }); +after(async () => { await browser?.close(); await reactBrowser?.close(); }); + +/** A body with one figure per example (or the ones named), in a column as wide as `width`. */ +const body = (keys = KEYS, width = 1104) => `<title>Diagrams
${keys.map((k) => `
`).join("")}
`; +const page = (keys, width) => compose(body(keys, width)).html; + +const REACT = ` +import data from "./test/fixtures/cimip-diagrams.json"; +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, "data-flow": B.DataFlowDiagram, sequence: B.SequenceDiagram, schema: B.SchemaDiagram }; +function Host() { return
{Object.entries(data).map(([key, d]) => { const X = C[d.type]; const { type, ...props } = d; return ; })}
; } +createRoot(document.getElementById("root")).render();`; +async function reactPage(theme, viewport) { + const { page: p, errors } = await fixturePage(reactBrowser, REACT, { theme, viewport }); + await p.addStyleTag({ content: `${FONTS} body{margin:0;background:var(--basalt-surface-page)} #root{display:block}` }); + await p.evaluate(() => document.fonts.ready); + await p.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))))); + return { page: p, errors }; +} +/** The figure's ink and node boxes, with React's prefix and ids written as the skill's, so the two can be compared as they are. */ +const read = (p, key, prefix) => p.evaluate(({ key, prefix }) => { + const fig = document.querySelector(`#fig-${key}`); + const base = fig.getAttribute("aria-labelledby").replace(/-title$/, ""); + const ink = fig.querySelector(`.${prefix}-ink`).innerHTML.replaceAll(`${prefix}-`, "P-").replaceAll(base, "BASE"); + const o = fig.querySelector(`.${prefix}-drawing`).getBoundingClientRect(); + const boxes = [...fig.querySelectorAll(`.${prefix}-node`)].map((n) => { const r = n.getBoundingClientRect(); return [n.dataset.node, Math.round((r.left - o.left) * 2) / 2, Math.round((r.top - o.top) * 2) / 2, Math.round(r.width * 2) / 2, Math.round(r.height * 2) / 2]; }); + const style = (sel) => { const el = fig.querySelector(sel); if (!el) return null; const s = getComputedStyle(el); return [s.backgroundColor, s.borderTopColor, s.borderTopWidth, s.borderRadius, s.color, s.fontSize, s.fontWeight, s.lineHeight, s.fontFamily, s.paddingTop, s.paddingLeft]; }; + return { layout: fig.getAttribute("data-layout"), ink, boxes, styles: [`.${prefix}-node`, `.${prefix}-node[data-focal]`, `.${prefix}-name`, `.${prefix}-kind`, `.${prefix}-detail`, `.${prefix}-label`, `.${prefix}-legend`, `.${prefix}-summary`, `.${prefix}-title`, `.${prefix}-hint`, `.${prefix}-gbox`, `.${prefix}-lane-name`, `.${prefix}-row`, `.${prefix}-tname`, `.${prefix}-msg`, `.${prefix}-band`].map(style) }; +}, { key, prefix }); + +describe("parity with React", () => { + for (const theme of ["dark", "light"]) for (const width of [1440, 390]) { + test(`${theme} at ${width}: the same layout, the same ink, the same boxes and the same styles for all five`, async () => { + const viewport = { width, height: 1000 }; + const react = await reactPage(theme, viewport); + const skill = await openHtml(browser, page(), { scheme: theme, width }); + for (const key of KEYS) { + const a = await read(react.page, key, "basalt-diagram"); + const b = await read(skill.page, key, "diagram"); + assert.equal(b.layout, a.layout, `${key}: layout`); + assert.deepEqual(b.boxes, a.boxes, `${key}: node boxes`); + assert.equal(b.ink, a.ink, `${key}: the ink`); + assert.deepEqual(b.styles, a.styles, `${key}: computed styles`); + } + assert.deepEqual(react.errors, []); + assert.deepEqual(skill.errors, []); + await react.page.close(); + await skill.context.close(); + }); + } +}); + +describe("the page before script (1.19)", () => { + test("compose.mjs writes every figure's words: the title, every node, the key, the summary and the list", () => { + const html = page(); + for (const key of KEYS) { + const d = DATA[key]; + const at = html.indexOf(`id="fig-${key}"`); + const figure = html.slice(at, html.indexOf("", at)); + assert.ok(figure.includes('class="diagram-drawing"'), `${key}: the drawing is in the page`); + for (const n of d.nodes ?? d.participants ?? d.tables) assert.ok(figure.includes(`>${n.name.replaceAll("&", "&").replaceAll("'", "'")}<`), `${key}: ${n.name}`); + assert.ok(figure.includes(`class="diagram-summary"`), `${key}: the summary`); + assert.ok(figure.includes(`class="diagram-list"`), `${key}: the list`); + assert.ok(figure.includes("data-diagram>"), `${key}: the JSON stays for the script`); + } + }); + + test("with JavaScript off each figure is stacked, its list open and no toggle", async () => { + const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1440, height: 1000 } }); + const p = await context.newPage(); + await p.setContent(page()); + for (const key of KEYS) { + assert.equal(await p.locator(`#fig-${key} .diagram-list`).isVisible(), true, key); + assert.equal(await p.locator(`#fig-${key} .diagram-toggle`).isVisible(), false, key); + if (key !== "schema" && key !== "sequence") assert.notEqual(await p.$eval(`#fig-${key} .diagram-drawing`, (el) => getComputedStyle(el).display), "grid", `${key} is stacked`); + } + await context.close(); + }); + + test("a figure drawn from script (Basalt.diagram) is the same as one compose.mjs wrote", async () => { + const skill = await openHtml(browser, compose(`D
`).html, { scheme: "dark" }); + await skill.page.evaluate((spec) => window.Basalt.diagram(document.getElementById("fig-a"), spec), DATA.architecture); + await skill.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + const written = await openHtml(browser, compose(`D
`).html, { scheme: "dark" }); + const a = await read(skill.page, "a", "diagram"), b = await read(written.page, "a", "diagram"); + assert.equal(a.ink, b.ink); + assert.deepEqual(a.boxes, b.boxes); + assert.deepEqual(skill.errors, []); + await skill.context.close(); + await written.context.close(); + }); +}); + +describe("behaviour", () => { + test("geometry at 1440, 640 and 390: nothing overlaps, crosses, is cut or scrolls", async () => { + for (const width of [1440, 640, 390]) { + const skill = await openHtml(browser, page(), { scheme: "dark", width }); + for (const key of KEYS) { + const r = await skill.page.evaluate(`${inspectSource()}("diagram", "#fig-${key}")`); + assert.deepEqual(r.problems, [], `${key} at ${width}`); + assert.deepEqual(r.crossings, [], `${key} at ${width}`); + } + await skill.context.close(); + } + }); + + test("one tab stop, the arrow keys, Esc, the trace by keyboard and the list's toggle", async () => { + const skill = await openHtml(browser, page(["architecture"]), { scheme: "dark" }); + const p = skill.page; + assert.equal(await p.locator("#fig-architecture .diagram-node[tabindex='0']").count(), 1); + await p.focus("#fig-architecture .diagram-node[data-node='browser']"); + await p.keyboard.press("ArrowRight"); + assert.equal(await p.evaluate(() => document.activeElement.dataset.node), "alb"); + assert.ok(await p.locator("#fig-architecture .diagram-edge[data-lit]").count() > 0, "keyboard focus traces"); + await p.keyboard.press("Escape"); + assert.equal(await p.locator("#fig-architecture .diagram-edge[data-lit]").count(), 0); + await p.click("#fig-architecture .diagram-toggle"); + assert.equal(await p.locator("#fig-architecture .diagram-list").isVisible(), true); + assert.equal(await p.locator("#fig-architecture .diagram-toggle").innerText(), "Hide the list"); + await skill.context.close(); + }); + + test("axe in both themes, drawn and stacked", async () => { + for (const scheme of ["dark", "light"]) for (const width of [1440, 390]) { + const skill = await openHtml(browser, page(), { scheme, width }); + await skill.page.addScriptTag({ content: axeSource }); + const result = await skill.page.evaluate(() => window.axe.run(document, { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] }, resultTypes: ["violations"] })); + assert.deepEqual(result.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).slice(0, 3).join("; ")}`), [], `${scheme} at ${width}`); + await skill.context.close(); + } + }); + + test("the module's stylesheet is React's section renamed, and its script carries React's engine", () => { + const parts = path.join(path.dirname(require.resolve("../../../.agent/skills/basalt-html/compose.mjs")), "parts"); + const css = fs.readFileSync(path.join(parts, "diagram.css"), "utf8"); + const js = fs.readFileSync(path.join(parts, "diagram.js"), "utf8"); + assert.doesNotMatch(css, /basalt-diagram-|--_surface\b/, "no React class or level variable is left"); + assert.match(css, /\.diagram-node/); + assert.match(css, /--basalt-diagram-edge-main/, "the module carries its tokens"); + assert.match(js, /diagramMarkup/); + }); +}); diff --git a/tools/review/round56.tsx b/tools/review/round56.tsx new file mode 100644 index 00000000..a4006602 --- /dev/null +++ b/tools/review/round56.tsx @@ -0,0 +1,150 @@ +// Round 56: Basalt's diagrams (DECISIONS 269, revised by 270). A heavy council round decided on one draft (Draft A, Neon's; the second drafter sat out on a +// usage limit), checked by Astra and decided by Fable, who revised six objections after the final positions. Built by Opus from the decision; the +// implementation has not been reviewed. The content is CIMIP's five diagrams (the owner's prototype, with the decision's corrections). States: at rest +// (`default`), a node traced by the pointer (`hover`), the list open (`list`), forced colours and more contrast. Each is shot at 1440 (drawn), at 672 (a +// 640px figure: the stack, 480 wide), at 390 and at 360. + +import * as React from "react"; + +import { ArchitectureDiagram, DataFlowDiagram, FlowchartDiagram, SchemaDiagram, SequenceDiagram } from "../../packages/react/src/index"; +import data from "../../packages/react/test/fixtures/cimip-diagrams.json"; +import type { Round } from "./rounds"; + +type Key = keyof typeof data; +const FOCAL: Record = { architecture: "svc", flowchart: "who", dataFlow: "row", sequence: "svc", schema: "incidents" }; + +function Diagram({ k, state }: { k: Key; state: string }) { + const host = React.useRef(null); + React.useEffect(() => { + const el = host.current; + if (!el) return; + // The walkthrough's "hover" state rests a real pointer on the element marked data-wt-hover: here, a node the trace is worth seeing on. + el.querySelector(`[data-node="${FOCAL[k]}"]`)?.setAttribute("data-wt-hover", ""); + if (state === "list") el.querySelector(".basalt-diagram-toggle")?.click(); + }, [k, state]); + const { type, ...props } = data[k] as (typeof data)[Key] & { type: string }; + void type; + const figure = (() => { + switch (k) { + case "architecture": return )} />; + case "flowchart": return )} />; + case "dataFlow": return )} />; + case "sequence": return )} />; + default: return )} />; + } + })(); + return
{figure}
; +} + +const STATES = ["hover@1440", "list", "forced-colours@1440", "forced-colours@390", "more-contrast@1440"]; +const TRY_COMMON = [ + "Resize the window across the fit width: the drawing turns on only where everything fits, and below it the figure is the stacked drawing, at most 480 wide, on the start edge.", + "Tab into the drawing: one stop. → ↓ the next part, ← ↑ the one before, Home and End the ends; the part's lines lift to primary ink and the rest dim. Esc clears the trace and keeps focus; Tab leaves.", + "Hover a part with a mouse: the same trace. On a phone nothing traces and nothing is a target.", + "Open \"View as list\": the same facts as real lists. Try forced colours (Windows High Contrast, or DevTools' emulation) under both saved themes.", +]; +const COMMON = [ + "Decided by the council (DECISIONS 269, revised by 270, a handoff): the owner sees this PR before it merges. The implementation has not been reviewed.", + "Monochrome: no colour, no accent, no status. One focal node in inverted ink, which the key names in the author's words. Three lines named by their look: main 2px primary with a filled head, plain 1px secondary, dashed 1px 6 on 4 off with an open head.", + "The drawn layout is used only when it fits (1.11): the figure 640 wide, every track as wide as its widest word, every label on a clean seat, no line through a node. Otherwise stacked (1.13). Sides, slots, jogs, lanes, groups and foreign keys are derived; the author places nodes on a grid and names a side only to change it.", + "The words are in the HTML before script; before script the grid is used only from the figure's least width (1.19).", +]; + +export const ROUND_56: Round = { + id: "56", + title: "Diagrams: architecture, flowchart, data flow, sequence and schema (DECISIONS 269, 270)", + reviewed: false, + summary: + "Five diagram components and the HTML skill's diagram module, built from the council's decision (DECISIONS 269, revised by 270 after the final positions): Draft A's grammar with a measured fit rule, derived routes, a 3:1 contour on flowchart shapes, cut crossings, tracing by ink only, and the words in the page before script. CIMIP's five diagrams are the content. Built by Opus; the implementation has not been reviewed, and the tests were written but not run (DECISIONS 271 paused test runs). Shot at 1440, at a 640px figure, at 390 and at 360, in both themes, with a trace, the list, forced colours and more contrast.", + steps: [ + { + id: "architecture", + name: "Architecture", + intro: "How a request reaches the agent: nodes with a kind, a name and a detail, a group, and all three kinds of line.", + decisions: [ + ...COMMON, + "A group is a transparent box with a 1px dashed structure edge, radius 12, its label at the top start; its box is its members'. Stacked, the box wraps its members.", + "Stacked: a spine and indented branches; the rail at space-3 and the trunk at space-8 from the spine's start edge; ECS's \"starts\" runs in the end lane inside the cards because it leaves a branch and passes only a branch. One thing to look at on purpose (decision, section 2): the rail is a 2px vertical line down the start edge, the part nearest the vertical bar the owner ruled out as a mark.", + "Corrected from the owner's prototype: the summary says what the lines say (\"puts sealed segments in S3, calls Bedrock for the scribe\"), and the key says \"The service\" where the prototype said \"Focal\".", + ], + tryIt: TRY_COMMON, + states: [...STATES], + widths: [1440, 672, 390, 360], + scales: [2], + height: 2400, + touch: true, + demo: ({ state }) => , + }, + { + id: "flowchart", + name: "Flowchart", + intro: "Who may decide what the agent asks to run: shape carries type, so every shape has a 3:1 contour.", + decisions: [ + ...COMMON, + "A step is the box, a start or end a capsule, a decision a diamond behind its words (the name at 500, wrapping at 62% of the track). A decision is at least space-16 tall and never flatter than 5:1, drawn or stacked.", + "Built differently from the decision's estimate: the decision measured the flowchart drawing from 880 on Draft A's geometry; here it draws from 946. At a 177px track \"Risk medium or lower?\" wraps to two lines, its diamond (sized exactly as 1.12 says) is 109 tall, and its slope reaches 0.6px into the clean seat of \"responder\", so by \"no seat, no drawn layout\" the stack holds until 946. The options are in the PR's notes; nothing was changed to move it.", + ], + tryIt: TRY_COMMON, + states: [...STATES], + widths: [1440, 672, 390, 360], + scales: [2], + height: 2400, + touch: true, + demo: ({ state }) => , + }, + { + id: "data-flow", + name: "Data flow", + intro: "How one message reaches everyone in the room: lanes as bands, steps numbered in order.", + decisions: [ + ...COMMON, + "Lanes are bands ruled apart with the divider, centred in the row gap, named at the start; a node's kind line is its step number. Stacked, a step says its lane: \"Step 3 · Aurora\".", + "Stacked, the two bypasses from step 3 run in the end gutter outside the cards and nest (1.7 rule 3): the one that travels farther leaves higher and takes the outer lane, so they never cross.", + "Drawn only from 1,080: below it the five step columns cannot each be 144 wide.", + ], + tryIt: TRY_COMMON, + states: [...STATES], + widths: [1440, 672, 390, 360], + scales: [2], + height: 2400, + touch: true, + demo: ({ state }) => , + }, + { + id: "sequence", + name: "Sequence", + intro: "An @agent run, from the mention to the approved action: a head and a lifeline a participant, a 56px row a message.", + decisions: [ + ...COMMON, + "Lifelines are 1px structure ink dashed 4 on 4 off; a message's number and label sit above its line and its note below, on plates that mask the lifelines; a self-call is a small loop; a reply or a stream is dashed; a band is a ruled line of words, never a frame. No emphasis weight (Draft A made message 9 heavier; cut).", + "Stacked: a strip of participant chips and a numbered list that names each message's sender, an inline arrow drawn like its kind, its receiver and the kind's word. The list has no stops and no key hint.", + "Not cut: where a message passes over another participant's lifeline the lifeline is not broken (the decision's cuts are for lines crossing lines). Noted for the owner.", + ], + tryIt: TRY_COMMON, + states: [...STATES], + widths: [1440, 672, 390, 360], + scales: [2], + height: 2400, + touch: true, + demo: ({ state }) => , + }, + { + id: "schema", + name: "Database schema", + intro: "The tables an incident and its runs live in: table cards, and a line from each foreign key to the key it references.", + decisions: [ + ...COMMON, + "A foreign key is one record (`references: \"incidents.id\"`): the row's \"→ incidents\", the line, the sentence and the list come from it. Lines to one key share a bus; tables in one column use a turn-back.", + "The decision's placement (memberships beside users, agent_runs above sandboxes) draws with no crossing. Stacked, the cards sit in an auto-fit grid with no lines, because every foreign-key row writes its target; the key says so.", + "The focal table is inverted, its keys, types and \"+ n more\" at opacity-amount, its header rule diagram-focal-rule.", + ], + tryIt: TRY_COMMON, + states: [...STATES], + widths: [1440, 672, 390, 360], + scales: [2], + height: 2400, + touch: true, + demo: ({ state }) => , + }, + ], +}; diff --git a/tools/review/rounds.tsx b/tools/review/rounds.tsx index 11a36d7f..f69544ec 100644 --- a/tools/review/rounds.tsx +++ b/tools/review/rounds.tsx @@ -121,6 +121,7 @@ import { ROUND_52 } from "./round52"; import { ROUND_53 } from "./round53"; import { ROUND_54 } from "./round54"; import { ROUND_55 } from "./round55"; +import { ROUND_56 } from "./round56"; export interface Step { id: string; @@ -681,3 +682,4 @@ ROUNDS.push(ROUND_52); ROUNDS.push(ROUND_53); ROUNDS.push(ROUND_54); ROUNDS.push(ROUND_55); +ROUNDS.push(ROUND_56); From 8c9233c9f18e9f568864804dbd4726ce5db63392 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:30:32 -0600 Subject: [PATCH 2/4] Diagrams: fix round 1 of the code review (DECISIONS 281 and 282) - A composed figure keeps its stop and its list: the attribute updater pairs each tree element with the next DOM element of its tag and class, so the JSON script is passed over. - The author's data is checked at the model's boundary: text is made a string; the heading, a line's kind, a side and a key take one of their values or the default, with a warning; a track is a whole number. Element and attribute names are checked, and every value in the ink is escaped. - React: a caller's ref is set beside the figure's own; on the root only the state's attributes are written, so a caller's hidden and ARIA stay. - The stack's end lanes are allocated across each overlapping set; a third lane is reported. Two stems between one pair take the quarter points, in the stack and in the drawn layout. A stem's label tries the middle and then the thirds. A stack that still overlaps draws no lines. - A route that would leave the drawing fails the fit. - A decision's words wrap at 62% of the track (the border-box). A sequence's least width uses its measured participants. - A measured decision never shows its box's border, traced or in forced colours. - The composer finds figures with its own tag reader in the held body, so examples in a textarea, comment or script are left alone and an unquoted class works. - Polish: the roving stop moves by two attributes in the skill; the plan, sentences, key and list are worked out once per model; a gutter is scored by its own lines; development checks are off in a React production build. A second Basalt.diagram call rewrites the markup. The list carries every kind's word and the sequence's bands as sub-headings. The usage example defines both ends. - The diagram module's cap goes from 82,300 to 87,200 bytes (87,119 now). The test files are unchanged in this commit (the owner skipped them for now). Nothing here has been run in a browser. Co-Authored-By: Claude Opus 5.5 --- .agent/skills/basalt-html/compose.mjs | 56 ++- .agent/skills/basalt-html/parts/diagram.css | 2 +- .agent/skills/basalt-html/parts/diagram.js | 2 +- .agent/skills/basalt-html/parts/manifest.json | 2 +- .../skills/basalt-html/parts/usage/diagram.md | 3 +- packages/react/src/diagram-core.ts | 379 ++++++++++++------ packages/react/src/diagram-figure.tsx | 17 +- packages/react/src/styles/components.css | 18 +- tools/html-skill/src/compose.mjs | 56 ++- tools/html-skill/src/modules.json | 2 +- tools/html-skill/src/modules/diagram.js | 37 +- tools/html-skill/src/usage/diagram.md | 3 +- 12 files changed, 398 insertions(+), 179 deletions(-) diff --git a/.agent/skills/basalt-html/compose.mjs b/.agent/skills/basalt-html/compose.mjs index e45a2164..f3d8550c 100644 --- a/.agent/skills/basalt-html/compose.mjs +++ b/.agent/skills/basalt-html/compose.mjs @@ -304,7 +304,7 @@ export function readBody(body, stats = {}) { const placeholder = new RegExp(`${mark}(\\d+)${mark}(\\s*)`, "g"); const blank = (item) => { let text = item.text; for (const [a, b] of [...item.comments].reverse()) text = text.slice(0, a) + " " + text.slice(b); return text; }; return { - text: out, saved, scripts, placeholder, whole, h1: h1 && !h1.open ? h1.text.trim() : null, + text: out, saved, scripts, placeholder, mark, whole, h1: h1 && !h1.open ? h1.text.trim() : null, // The text put back; with `bare`, as detection reads it: no comment (an HTML one, or one in a nested element, or in a script). restore: (s, bare = false) => s.replace(placeholder, (_, k, ws) => { const item = saved[Number(k)]; @@ -541,7 +541,7 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = for (const name of use) if (!(name in manifest.modules)) throw new Error(`basalt:use names "${name}", which is not a module (modules: ${Object.keys(manifest.modules).join(", ")})`); const diagramNotes = []; - const content = writeDiagrams(held.restore(markup).replace(/^\s+/, ""), parts, diagramNotes); + const content = held.restore(writeDiagrams(markup, held, parts, diagramNotes)).replace(/^\s+/, ""); title ||= held.h1 || "Untitled page"; // an empty names nothing: the heading does // Detection reads markup and code, never comments: a word written about in a comment (an HTML one, or one inside a script or a style) brings nothing in. @@ -596,34 +596,52 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = * A diagram's words, written into the page (DECISIONS 281, 1.19): each `<figure class="diagram">` that holds only its JSON gets the markup the diagram module's * script would write for it, from that same script (parts/diagram.js, run here without a page), so the page reads before any script runs. The figure's own * attributes stay (its class joins ours, its id stays); the JSON stays for the script. A figure whose JSON does not parse is left for the script, which says why. + * + * It reads the body as readBody left it: every comment, script, style, textarea, title, svg and template is a placeholder there, so a figure written as an + * example inside one is text and is never expanded. A figure is found by the composer's own tag reader (quoted, single-quoted or unquoted attributes alike), + * and is expanded only when its class list holds `diagram` and its content is one `script` with `data-diagram` and nothing else but white space. */ -function writeDiagrams(content, parts, notes) { - if (!/\bdata-diagram\b/.test(content) || !exists(parts, "diagram.js")) return content; - let markup = null; +function writeDiagrams(markup, held, parts, notes) { + if (!exists(parts, "diagram.js")) return markup; + const mark = held.mark; + const json = new RegExp(`^(\\s*)${mark}(\\d+)${mark}(\\s*)</figure(?=[\\t\\n\\f\\r />])[^>]*>`, "i"); + let engine = null; let serial = 0; - const figure = /<figure\b((?:"[^"]*"|'[^']*'|[^>"'])*)>(\s*<script\b(?:"[^"]*"|'[^']*'|[^>"'])*\bdata-diagram\b(?:"[^"]*"|'[^']*'|[^>"'])*>)([\s\S]*?)(<\/script\s*>)(\s*)<\/figure\s*>/gi; - return content.replace(figure, (whole, attrs, open, json, close) => { - if (!/\bclass\s*=\s*(?:"[^"]*\bdiagram\b[^"]*"|'[^']*\bdiagram\b[^']*')/.test(attrs) || /\bdata-diagram-drawn\b/.test(attrs)) return whole; + let out = ""; + let at = 0; + for (let i = markup.indexOf("<"); i !== -1; i = markup.indexOf("<", i + 1)) { + if (!/^<figure[\t\n\f\r />]/i.test(markup.slice(i, i + 8))) continue; + const tag = readTag(markup, i); + if (!tag.terminated || tag.close) continue; + const attrs = new Map(); + for (const [k, v] of tag.attrs) if (!attrs.has(k)) attrs.set(k, v); // the first of a repeated attribute wins, as in a browser + if (!(attrs.get("class") ?? "").split(/[\t\n\f\r ]+/).includes("diagram") || attrs.has("data-diagram-drawn")) continue; + const inside = json.exec(markup.slice(tag.end)); + const item = inside && held.saved[Number(inside[2])]; + if (!item || item.kind !== "script" || !item.attrs.some(([k]) => k === "data-diagram")) continue; let spec; - try { spec = JSON.parse(json); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); return whole; } - if (!markup) { + try { spec = JSON.parse(item.inner); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); continue; } + if (!engine) { const context = { window: { Basalt: { _: { step() {}, esc: (x) => x } } }, console: { warn() {}, error() {}, log() {} } }; vm.runInNewContext(read(parts, "diagram.js"), context); - markup = context.window.Basalt._.diagramMarkup; + engine = context.window.Basalt._.diagramMarkup; } - const made = markup(spec, `dg${++serial}`); + let made; + try { made = engine(spec, `dg${++serial}`); } catch (e) { notes.push(`${spec?.title ?? "a diagram"} could not be written (${e.message}); the page's script will say so`); continue; } for (const w of made.warnings) notes.push(`${spec.title ?? "a diagram"}: ${w}`); - const ours = [...made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]); - const theirs = [...attrs.matchAll(/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g)].map((m) => [m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? ""]); - const merged = new Map(theirs); - for (const [k, v] of ours) { + const merged = new Map(attrs); + for (const [, k, v] of made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)) { if (k === "class") merged.set("class", [...new Set(`${merged.get("class") ?? ""} ${v}`.split(/\s+/).filter(Boolean))].join(" ")); else if (k === "style") merged.set("style", merged.has("style") ? `${v};${merged.get("style")}` : v); else merged.set(k, v); } - const tag = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; - return `${tag}${open}${json}${close}${made.inner}</figure>`; - }); + const open = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; + const end = tag.end + inside[0].length; + out += markup.slice(at, i) + open + inside[1] + `${mark}${inside[2]}${mark}` + inside[3] + made.inner + "</figure>"; + at = end; + i = end - 1; + } + return out + markup.slice(at); } /** The module lines of SKILL.md's "## Modules" index: [{ name, trigger, warning }]. A line is `- **name** \`trigger\`: warning`. */ diff --git a/.agent/skills/basalt-html/parts/diagram.css b/.agent/skills/basalt-html/parts/diagram.css index 6c04c128..2f0cfe5e 100644 --- a/.agent/skills/basalt-html/parts/diagram.css +++ b/.agent/skills/basalt-html/parts/diagram.css @@ -1 +1 @@ -:root{--basalt-size-diagram-node: 144px;--basalt-size-diagram-table: 224px;--basalt-size-diagram-lane: 120px;--basalt-size-diagram-step: 56px;--basalt-size-diagram-head: 8px;--basalt-size-diagram-guide-dash: 4px}:root,[data-theme=light],.light{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-white-6);--basalt-diagram-focal-rule-contrast: var(--basalt-white-38)}[data-theme=dark],.dark{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}}@media(prefers-contrast:more){:root,[data-theme=light],[data-theme=dark],.light,.dark,:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-diagram-focal-rule-contrast)}}@layer basalt{.diagram{--_ground: var(--panel-bg, var(--basalt-surface-page));container-type:inline-size;display:flex;flex-direction:column;gap:var(--basalt-space-4);width:100%;min-width:0;margin:0;font-family:var(--basalt-font-family-sans)}.diagram-head{display:flex;flex-direction:column;gap:var(--basalt-space-0-5);min-width:0}.diagram-title{margin:0;color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans);letter-spacing:var(--basalt-text-md-tracking)}.diagram-source{margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-drawing{--_drawn: initial;--_d-display: var(--_drawn) grid;--_d-max: var(--_drawn) none;--_d-cols: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-gap: var(--_drawn) var(--_row-gap) var(--_col-gap);--_d-pad: var(--_drawn) var(--_gpad, 0);--_row-gap: var(--basalt-space-12);--_col-gap: var(--basalt-space-16);position:relative;box-sizing:border-box;display:var(--_d-display, flex);flex-direction:column;grid-template-columns:var(--_d-cols, none);gap:var(--_d-gap, 0);width:100%;max-width:var(--_d-max, var(--basalt-size-breakpoint-container));min-width:0;padding:var(--_d-pad, 0 var(--_gutter, 0) 0 0)}.diagram[data-layout=drawn]>.diagram-drawing{--_drawn: }.diagram[data-layout=stacked]>.diagram-drawing{--_drawn: initial}.diagram[data-gutter]>.diagram-drawing{--_gutter: var(--basalt-space-10)}.diagram[data-type=data-flow]>.diagram-drawing{--_d-cols: var(--_drawn) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr));--_row-gap: var(--basalt-space-10);--_col-gap: var(--basalt-space-12)}.diagram[data-type=schema]>.diagram-drawing{--_row-gap: var(--basalt-space-8);--_col-gap: var(--basalt-space-12);display:grid;grid-template-columns:var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));gap:var(--_d-gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram-node{--_d-gc: var(--_drawn) var(--_c);--_d-gr: var(--_drawn) var(--_r) / var(--_r2);--_d-mt: var(--_drawn) 0;--_d-align: var(--_drawn) center;position:relative;z-index:1;box-sizing:border-box;display:flex;flex-direction:column;min-width:0;grid-column:var(--_d-gc, auto);grid-row:var(--_d-gr, auto);align-self:var(--_d-align, stretch);margin-block-start:var(--_d-mt, var(--_gap, 0));padding:var(--basalt-space-2-5) var(--basalt-space-3);background:var(--panel-next, var(--basalt-surface-1));border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);color:var(--basalt-text-primary);overflow-wrap:break-word;outline:none;transition:border-color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-type=data-flow] .diagram-node{--_d-gc: var(--_drawn) var(--_lc)}.diagram-node[data-branch]{--_d-mi: var(--_drawn) 0;margin-inline:var(--_d-mi, var(--basalt-space-12) var(--basalt-space-6))}.diagram-node:focus-visible{z-index:2;outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:var(--basalt-size-focus-offset)}.diagram-node[data-near]{border-color:var(--basalt-border-hover)}.diagram-kind{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-lane-word{--_d-lw: var(--_drawn) none;display:var(--_d-lw, inline)}.diagram-name{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-detail{margin-block-start:var(--basalt-space-0-5);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-detail[data-mono]{font-family:var(--basalt-font-family-mono)}.diagram-node[data-focal]{background:var(--basalt-diagram-focal);border-color:var(--basalt-diagram-focal)}.diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:var(--basalt-diagram-focal-ink)}.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:var(--basalt-opacity-amount)}.diagram[data-type=flowchart] .diagram-node:not([data-focal]){border-color:var(--basalt-diagram-structure)}.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:var(--basalt-text-secondary)}.diagram-node[data-shape=terminal]{align-items:center;padding-inline:var(--basalt-space-5);border-radius:var(--basalt-radius-full);text-align:center}.diagram-node[data-shape=decision]{justify-content:center;align-items:center;height:var(--_h, auto);min-height:var(--basalt-space-16);padding:var(--basalt-space-2) var(--basalt-space-2-5);text-align:center}.diagram-words{position:relative;max-width:62%}.diagram-node[data-shape=decision] .diagram-name{font-weight:var(--basalt-font-weight-medium);text-wrap:balance}.diagram-diamond{display:none;position:absolute;inset:0;width:100%;height:100%;overflow:visible}.diagram-diamond path{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);vector-effect:non-scaling-stroke;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-measured] .diagram-node[data-shape=decision]{background:none;border-color:transparent}.diagram[data-measured] .diagram-node[data-shape=decision] .diagram-diamond{display:block}.diagram-node[data-shape=decision][data-near] .diagram-diamond path{stroke:var(--basalt-text-secondary)}.diagram-node[data-shape=decision][data-focal] .diagram-diamond path{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-group{--_d-gd: var(--_drawn) contents;position:relative;box-sizing:border-box;display:var(--_d-gd, flex);flex-direction:column;margin-block-start:var(--basalt-space-12);padding:var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5);border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg)}.diagram-group:first-child{margin-block-start:0}.diagram-group>.diagram-glabel+.diagram-node{--_d-mt: 0}.diagram-glabel{position:absolute;top:var(--basalt-space-2);inset-inline-start:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);white-space:nowrap}.diagram-group>.diagram-glabel{--_d-gl: var(--_drawn) none;display:var(--_d-gl, block)}.diagram-gbox{--_d-gb: var(--_drawn) block;position:relative;display:var(--_d-gb, none);grid-column:var(--_c) / var(--_c2);grid-row:var(--_r) / var(--_r2);margin:calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4));border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-lane{--_d-ln: var(--_drawn) flex;position:relative;display:var(--_d-ln, none);grid-column:1 / -1;grid-row:var(--_r);align-items:center;pointer-events:none}.diagram-lane+.diagram-lane:before{content:"";position:absolute;inset-inline:0;top:calc(-1 * var(--basalt-space-5));border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-lane-name{box-sizing:border-box;width:var(--basalt-size-diagram-lane);padding-inline-end:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-ink{position:absolute;inset:0;z-index:0;pointer-events:none}.diagram-svg{position:absolute;top:0;left:0;overflow:visible}.diagram-ruler{position:absolute;visibility:hidden;white-space:pre;pointer-events:none}.diagram-ruler[data-f=name]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=name-500]{font:var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=table]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-ruler:is([data-f=mono],[data-f=label]){font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-ruler[data-f=sans]{font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-line{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main);stroke-width:var(--basalt-size-chart-line)}.diagram-line[data-kind=dashed]{stroke-dasharray:var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap);stroke-linecap:butt}.diagram-tip{fill:var(--basalt-diagram-edge);transition:fill var(--basalt-duration-fast) var(--basalt-ease-out),stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-tip[data-kind=main]{fill:var(--basalt-diagram-edge-main)}.diagram-tip[data-open]{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:round;stroke-linejoin:round}.diagram-dot{fill:var(--basalt-diagram-edge)}.diagram-life{fill:none;stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);stroke-dasharray:var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash)}.diagram-edge[data-lit] .diagram-line{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip:not([data-open]),.diagram-edge[data-lit] .diagram-dot{fill:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip:not([data-open]),.diagram-edge[data-dim] .diagram-dot{fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-label{position:absolute;box-sizing:border-box;height:var(--basalt-text-xs-line-height);color:var(--basalt-diagram-edge);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);text-align:center;white-space:nowrap;transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-label[data-on]{background:var(--_ground)}.diagram-label[data-lit]{color:var(--basalt-diagram-edge-main)}.diagram-cast{--_d-cd: var(--_drawn) grid;display:var(--_d-cd, flex);flex-wrap:wrap;grid-template-columns:repeat(var(--_cols, 1),minmax(0,1fr));gap:var(--_d-cast-gap, var(--basalt-space-1-5));--_d-cast-gap: var(--_drawn) var(--basalt-space-5);margin:0;padding:0;list-style:none}.diagram-actor{display:flex;min-width:0}.diagram-node[data-shape=participant]{--_d-pd: var(--_drawn) var(--basalt-space-2-5) var(--basalt-space-3);--_d-pr: var(--_drawn) var(--basalt-radius-md);--_d-pa: var(--_drawn) center;flex:var(--_d-pflex, none);--_d-pflex: var(--_drawn) 1;align-items:center;justify-content:var(--_d-pa, center);min-height:var(--_d-ph, var(--basalt-size-badge));--_d-ph: var(--_drawn) 0;padding:var(--_d-pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline)));border-radius:var(--_d-pr, var(--basalt-radius-xs));text-align:center}.diagram-node[data-shape=participant]:not([data-focal]){--_d-pbg: var(--_drawn) var(--panel-next, var(--basalt-surface-1));--_d-pbc: var(--_drawn) var(--basalt-border-rim);--_d-pbt: var(--_drawn) var(--basalt-border-rim-top);background:var(--_d-pbg, none);border-color:var(--_d-pbc, var(--basalt-border-hairline));border-top-color:var(--_d-pbt, var(--basalt-border-hairline))}.diagram-node[data-shape=participant] .diagram-kind{--_d-pk: var(--_drawn) block;display:var(--_d-pk, none)}.diagram-node[data-shape=participant] .diagram-name{font-size:var(--_d-pn, var(--basalt-text-xs-size));line-height:var(--_d-pnl, var(--basalt-text-xs-line-height));font-weight:var(--_d-pw, var(--basalt-font-weight-medium));--_d-pn: var(--_drawn) var(--basalt-text-sm-size);--_d-pnl: var(--_drawn) var(--basalt-text-sm-line-height);--_d-pw: var(--_drawn) var(--basalt-font-weight-semibold)}.diagram-steps{--_d-sp: var(--_drawn) var(--basalt-space-4);position:relative;z-index:1;padding-block-start:var(--_d-sp, var(--basalt-space-4))}.diagram-msgs{margin:0;padding:0;list-style:none}.diagram-msg{--_d-md: var(--_drawn) grid;--_d-mc: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-mr: var(--_drawn) 1fr 1fr;--_d-mh: var(--_drawn) var(--basalt-size-diagram-step);--_d-mg: var(--_drawn) 0 var(--basalt-space-5);display:grid;grid-template-columns:var(--_d-mc, var(--basalt-space-8) minmax(0, 1fr));grid-template-rows:var(--_d-mr, auto);column-gap:var(--basalt-space-5);gap:var(--_d-mg, 0);height:var(--_d-mh, auto);padding-block:var(--_d-mpb, var(--basalt-space-2-5));--_d-mpb: var(--_drawn) 0;border-top:var(--_d-mb, var(--basalt-size-hairline) solid var(--basalt-border-divider));--_d-mb: var(--_drawn) 0;font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-said{--_d-sd: var(--_drawn) block;display:var(--_d-sd, contents);grid-column:var(--_a) / var(--_b);grid-row:1;align-self:end;justify-self:center;margin-block-end:calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--basalt-space-1-5);background:var(--_ground);white-space:nowrap}.diagram-num{grid-column:1;color:var(--basalt-text-tertiary);font-variant-numeric:tabular-nums}.diagram-said .diagram-num{margin-inline-end:var(--_d-nm, 0);--_d-nm: var(--_drawn) var(--basalt-space-1-5)}.diagram-mlabel{grid-column:2;color:var(--basalt-text-primary);font-family:var(--basalt-font-family-mono)}.diagram-route{--_d-rd: var(--_drawn) none;display:var(--_d-rd, inline-flex);grid-column:2;align-items:center;gap:var(--basalt-space-1);flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-note{--_d-nd: var(--_drawn) 2;grid-column:var(--_d-nc, 2);--_d-nc: var(--_drawn) var(--_a) / var(--_b);grid-row:var(--_d-nd, auto);align-self:start;justify-self:var(--_d-nj, stretch);--_d-nj: var(--_drawn) center;margin-block-start:var(--_d-nmt, 0);--_d-nmt: var(--_drawn) calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--_d-npi, 0);--_d-npi: var(--_drawn) var(--basalt-space-1-5);background:var(--_d-nbg, none);--_d-nbg: var(--_drawn) var(--_ground);color:var(--basalt-text-tertiary);white-space:var(--_d-nws, normal);--_d-nws: var(--_drawn) nowrap}.diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) start;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-start:var(--_d-sm, 0)}.diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) end;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-end:var(--_d-sm, 0)}.diagram-arrow{flex:none;overflow:visible}.diagram-band{--_d-bh: var(--_drawn) var(--basalt-size-control-lg);--_d-bj: var(--_drawn) center;position:relative;display:flex;align-items:center;justify-content:var(--_d-bj, flex-start);height:var(--_d-bh, auto);margin:var(--_d-bm, var(--basalt-space-5) 0 var(--basalt-space-2));--_d-bm: var(--_drawn) 0;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-band:before{--_d-br: var(--_drawn) "";content:var(--_d-br, none);position:absolute;inset-inline:0;top:50%;border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-band>span{position:relative;padding-inline:var(--_d-bp, 0);--_d-bp: var(--_drawn) var(--basalt-space-1-5);background:var(--_ground)}.diagram-node[data-shape=table]{align-self:start;padding:0;overflow-wrap:normal}.diagram-th{padding:var(--basalt-space-2) var(--basalt-space-3);border-bottom:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-node[data-focal] .diagram-th{border-bottom-color:var(--basalt-diagram-focal-rule)}.diagram-tname{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-rows{display:flex;flex-direction:column;padding-block:var(--basalt-space-1)}.diagram-row{display:flex;flex-wrap:wrap;align-items:center;column-gap:var(--basalt-space-3);min-height:var(--basalt-size-control-sm);padding-inline:var(--basalt-space-3);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-keyseat{flex:none;width:var(--basalt-space-6);margin-inline-end:calc(-1 * var(--basalt-space-3));color:var(--basalt-text-tertiary)}.diagram-cname{flex:1 0 auto;color:var(--basalt-text-primary)}.diagram-ctype{margin-inline-start:auto;color:var(--basalt-text-tertiary)}.diagram-ctype[data-ref]{color:var(--basalt-text-secondary)}.diagram-more{padding:0 var(--basalt-space-3) var(--basalt-space-2);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-key{padding-block-start:var(--basalt-space-3);border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-legend{display:flex;flex-wrap:wrap;gap:var(--basalt-space-2) var(--basalt-space-5);margin:0;padding:0;list-style:none;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-entry{display:inline-flex;align-items:center;gap:var(--basalt-space-1-5)}.diagram[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram:not([data-layout]) .diagram-entry[data-when=drawn]{display:none}.diagram-swatch{flex:none;overflow:visible}.diagram-swatch-shape{fill:var(--_ground);stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline)}.diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke-dasharray:var(--basalt-space-1) var(--basalt-space-0-5)}.diagram-fk-mark{color:var(--basalt-text-secondary);font-family:var(--basalt-font-family-mono)}.diagram-hint{display:flex;flex-wrap:wrap;gap:var(--basalt-space-1) var(--basalt-space-4);margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-hint>span{display:inline-flex;align-items:center;gap:var(--basalt-space-1)}.diagram[data-layout=stacked]:is([data-type=sequence],[data-type=schema]) .diagram-hint{display:none}.diagram-summary{order:1;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans);text-wrap:pretty}.diagram-foot{order:2;display:flex}.diagram-list{order:3;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list[hidden]{display:none}.diagram-list strong{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-code{color:var(--basalt-text-primary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-list-head{margin:var(--basalt-space-4) 0 var(--basalt-space-2);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list-head:first-child{margin-block-start:0}.diagram-list-group{margin:var(--basalt-space-3) 0 var(--basalt-space-1);color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-medium)}.diagram-list-items{display:flex;flex-direction:column;gap:var(--basalt-space-1);margin:0;padding-inline-start:var(--basalt-space-5)}.diagram-list-exits{margin:var(--basalt-space-1) 0 0;padding-inline-start:var(--basalt-space-5)}@media(pointer:coarse){.diagram-toggle{min-height:var(--basalt-size-tap-min)}}@media(prefers-reduced-motion:reduce){.diagram-node,.diagram-line,.diagram-tip,.diagram-label,.diagram-diamond path{transition:none}}@media(prefers-contrast:more){.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:1}}@container (width >= 640px){.diagram:not([data-layout])[data-type=architecture][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 696px){.diagram:not([data-layout])[data-type=data-flow][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 768px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="4"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 784px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 800px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 888px){.diagram:not([data-layout])[data-type=data-flow][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 964px){.diagram:not([data-layout])[data-type=sequence][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 976px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 992px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1008px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 1080px){.diagram:not([data-layout])[data-type=data-flow][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1184px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1200px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1216px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1272px){.diagram:not([data-layout])[data-type=data-flow][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1312px){.diagram:not([data-layout])[data-type=schema][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]>.diagram-drawing{--_drawn: }}@media(scripting:none){.diagram:not(#basalt-diagram-no-id)>.diagram-drawing{--_drawn: initial}.diagram-list[hidden]{display:block}.diagram-foot,.diagram-entry[data-line],.diagram-hint{display:none}}@media(forced-colors:active){.diagram-svg,.diagram-swatch,.diagram-arrow{forced-color-adjust:none}.diagram .diagram-line,.diagram .diagram-line[data-kind]{stroke:CanvasText}.diagram .diagram-tip,.diagram .diagram-tip[data-kind],.diagram .diagram-dot{fill:CanvasText}.diagram .diagram-tip[data-open],.diagram .diagram-tip[data-kind][data-open]{fill:none;stroke:CanvasText}.diagram .diagram-edge[data-dim] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-dim] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:GrayText}.diagram .diagram-edge[data-dim] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-edge[data-lit] .diagram-line{stroke:Highlight}.diagram .diagram-edge[data-lit] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:Highlight}.diagram .diagram-edge[data-lit] .diagram-tip[data-open]{stroke:Highlight}.diagram .diagram-life{stroke:GrayText}.diagram .diagram-label{color:CanvasText;forced-color-adjust:none}.diagram .diagram-label[data-on]{background:Canvas}.diagram .diagram-label[data-lit]{color:Highlight}.diagram .diagram-swatch-shape{fill:Canvas;stroke:CanvasText}.diagram .diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke:GrayText}.diagram .diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:CanvasText;stroke:CanvasText}.diagram[data-type=flowchart] .diagram-node:not([data-focal]),.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:CanvasText}.diagram .diagram-diamond{forced-color-adjust:none}.diagram .diagram-diamond path,.diagram .diagram-node[data-near] .diagram-diamond path{fill:Canvas;stroke:CanvasText}.diagram .diagram-group,.diagram .diagram-gbox{border-color:GrayText}.diagram .diagram-lane+.diagram-lane:before,.diagram .diagram-band:before{border-color:GrayText}.diagram .diagram-hint{color:GrayText}.diagram :is(.diagram-kind,.diagram-name,.diagram-detail,.diagram-glabel,.diagram-lane-name,.diagram-title,.diagram-source,.diagram-num,.diagram-mlabel,.diagram-route,.diagram-note,.diagram-band,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more,.diagram-legend,.diagram-fk-mark){color:CanvasText}.diagram .diagram-node:focus-visible{outline-color:Highlight}.diagram .diagram-node[data-focal],.diagram .diagram-node[data-focal][data-near]{forced-color-adjust:none;background:CanvasText;border-color:CanvasText}.diagram .diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:Canvas;opacity:1}.diagram .diagram-node[data-focal] .diagram-th{border-bottom-color:Canvas}.diagram .diagram-node[data-focal]:focus-visible{outline:var(--basalt-size-focus-width) solid Highlight}.diagram .diagram-node[data-focal][data-shape=decision] .diagram-diamond path{fill:CanvasText;stroke:CanvasText}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow{print-color-adjust:exact}.diagram-hint{display:none}}} +:root{--basalt-size-diagram-node: 144px;--basalt-size-diagram-table: 224px;--basalt-size-diagram-lane: 120px;--basalt-size-diagram-step: 56px;--basalt-size-diagram-head: 8px;--basalt-size-diagram-guide-dash: 4px}:root,[data-theme=light],.light{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-white-6);--basalt-diagram-focal-rule-contrast: var(--basalt-white-38)}[data-theme=dark],.dark{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}}@media(prefers-contrast:more){:root,[data-theme=light],[data-theme=dark],.light,.dark,:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-diagram-focal-rule-contrast)}}@layer basalt{.diagram{--_ground: var(--panel-bg, var(--basalt-surface-page));container-type:inline-size;display:flex;flex-direction:column;gap:var(--basalt-space-4);width:100%;min-width:0;margin:0;font-family:var(--basalt-font-family-sans)}.diagram-head{display:flex;flex-direction:column;gap:var(--basalt-space-0-5);min-width:0}.diagram-title{margin:0;color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans);letter-spacing:var(--basalt-text-md-tracking)}.diagram-source{margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-drawing{--_drawn: initial;--_d-display: var(--_drawn) grid;--_d-max: var(--_drawn) none;--_d-cols: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-gap: var(--_drawn) var(--_row-gap) var(--_col-gap);--_d-pad: var(--_drawn) var(--_gpad, 0);--_row-gap: var(--basalt-space-12);--_col-gap: var(--basalt-space-16);position:relative;box-sizing:border-box;display:var(--_d-display, flex);flex-direction:column;grid-template-columns:var(--_d-cols, none);gap:var(--_d-gap, 0);width:100%;max-width:var(--_d-max, var(--basalt-size-breakpoint-container));min-width:0;padding:var(--_d-pad, 0 var(--_gutter, 0) 0 0)}.diagram[data-layout=drawn]>.diagram-drawing{--_drawn: }.diagram[data-layout=stacked]>.diagram-drawing{--_drawn: initial}.diagram[data-gutter]>.diagram-drawing{--_gutter: var(--basalt-space-10)}.diagram[data-type=data-flow]>.diagram-drawing{--_d-cols: var(--_drawn) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr));--_row-gap: var(--basalt-space-10);--_col-gap: var(--basalt-space-12)}.diagram[data-type=schema]>.diagram-drawing{--_row-gap: var(--basalt-space-8);--_col-gap: var(--basalt-space-12);display:grid;grid-template-columns:var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));gap:var(--_d-gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram-node{--_d-gc: var(--_drawn) var(--_c);--_d-gr: var(--_drawn) var(--_r) / var(--_r2);--_d-mt: var(--_drawn) 0;--_d-align: var(--_drawn) center;position:relative;z-index:1;box-sizing:border-box;display:flex;flex-direction:column;min-width:0;grid-column:var(--_d-gc, auto);grid-row:var(--_d-gr, auto);align-self:var(--_d-align, stretch);margin-block-start:var(--_d-mt, var(--_gap, 0));padding:var(--basalt-space-2-5) var(--basalt-space-3);background:var(--panel-next, var(--basalt-surface-1));border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);color:var(--basalt-text-primary);overflow-wrap:break-word;outline:none;transition:border-color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-type=data-flow] .diagram-node{--_d-gc: var(--_drawn) var(--_lc)}.diagram-node[data-branch]{--_d-mi: var(--_drawn) 0;margin-inline:var(--_d-mi, var(--basalt-space-12) var(--basalt-space-6))}.diagram-node:focus-visible{z-index:2;outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:var(--basalt-size-focus-offset)}.diagram-node[data-near]{border-color:var(--basalt-border-hover)}.diagram-kind{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-lane-word{--_d-lw: var(--_drawn) none;display:var(--_d-lw, inline)}.diagram-name{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-detail{margin-block-start:var(--basalt-space-0-5);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-detail[data-mono]{font-family:var(--basalt-font-family-mono)}.diagram-node[data-focal]{background:var(--basalt-diagram-focal);border-color:var(--basalt-diagram-focal)}.diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:var(--basalt-diagram-focal-ink)}.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:var(--basalt-opacity-amount)}.diagram[data-type=flowchart] .diagram-node:not([data-focal]){border-color:var(--basalt-diagram-structure)}.diagram[data-type=flowchart] .diagram-node:not([data-focal],[data-shape=decision])[data-near]{border-color:var(--basalt-text-secondary)}.diagram-node[data-shape=terminal]{align-items:center;padding-inline:var(--basalt-space-5);border-radius:var(--basalt-radius-full);text-align:center}.diagram-node[data-shape=decision]{justify-content:center;align-items:center;height:var(--_h, auto);min-height:var(--basalt-space-16);padding:var(--basalt-space-2) var(--basalt-space-2-5);text-align:center}.diagram-words{position:relative;max-width:calc(62% + (var(--basalt-space-2-5) + var(--basalt-size-hairline)) * 1.24)}.diagram-node[data-shape=decision] .diagram-name{font-weight:var(--basalt-font-weight-medium);text-wrap:balance}.diagram-diamond{display:none;position:absolute;inset:0;width:100%;height:100%;overflow:visible}.diagram-diamond path{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);vector-effect:non-scaling-stroke;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-measured] .diagram-node[data-shape=decision]{background:none;border-color:transparent}.diagram[data-measured] .diagram-node[data-shape=decision] .diagram-diamond{display:block}.diagram-node[data-shape=decision][data-near] .diagram-diamond path{stroke:var(--basalt-text-secondary)}.diagram-node[data-shape=decision][data-focal] .diagram-diamond path{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-group{--_d-gd: var(--_drawn) contents;position:relative;box-sizing:border-box;display:var(--_d-gd, flex);flex-direction:column;margin-block-start:var(--basalt-space-12);padding:var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5);border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg)}.diagram-group:first-child{margin-block-start:0}.diagram-group>.diagram-glabel+.diagram-node{--_d-mt: 0}.diagram-glabel{position:absolute;top:var(--basalt-space-2);inset-inline-start:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);white-space:nowrap}.diagram-group>.diagram-glabel{--_d-gl: var(--_drawn) none;display:var(--_d-gl, block)}.diagram-gbox{--_d-gb: var(--_drawn) block;position:relative;display:var(--_d-gb, none);grid-column:var(--_c) / var(--_c2);grid-row:var(--_r) / var(--_r2);margin:calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4));border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-lane{--_d-ln: var(--_drawn) flex;position:relative;display:var(--_d-ln, none);grid-column:1 / -1;grid-row:var(--_r);align-items:center;pointer-events:none}.diagram-lane+.diagram-lane:before{content:"";position:absolute;inset-inline:0;top:calc(-1 * var(--basalt-space-5));border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-lane-name{box-sizing:border-box;width:var(--basalt-size-diagram-lane);padding-inline-end:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-ink{position:absolute;inset:0;z-index:0;pointer-events:none}.diagram-svg{position:absolute;top:0;left:0;overflow:visible}.diagram-ruler{position:absolute;visibility:hidden;white-space:pre;pointer-events:none}.diagram-ruler[data-f=name]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=name-500]{font:var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=table]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-ruler:is([data-f=mono],[data-f=label]){font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-ruler[data-f=sans]{font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-line{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main);stroke-width:var(--basalt-size-chart-line)}.diagram-line[data-kind=dashed]{stroke-dasharray:var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap);stroke-linecap:butt}.diagram-tip{fill:var(--basalt-diagram-edge);transition:fill var(--basalt-duration-fast) var(--basalt-ease-out),stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-tip[data-kind=main]{fill:var(--basalt-diagram-edge-main)}.diagram-tip[data-open]{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:round;stroke-linejoin:round}.diagram-dot{fill:var(--basalt-diagram-edge)}.diagram-life{fill:none;stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);stroke-dasharray:var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash)}.diagram-edge[data-lit] .diagram-line{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip:not([data-open]),.diagram-edge[data-lit] .diagram-dot{fill:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip:not([data-open]),.diagram-edge[data-dim] .diagram-dot{fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-label{position:absolute;box-sizing:border-box;height:var(--basalt-text-xs-line-height);color:var(--basalt-diagram-edge);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);text-align:center;white-space:nowrap;transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-label[data-on]{background:var(--_ground)}.diagram-label[data-lit]{color:var(--basalt-diagram-edge-main)}.diagram-cast{--_d-cd: var(--_drawn) grid;display:var(--_d-cd, flex);flex-wrap:wrap;grid-template-columns:repeat(var(--_cols, 1),minmax(0,1fr));gap:var(--_d-cast-gap, var(--basalt-space-1-5));--_d-cast-gap: var(--_drawn) var(--basalt-space-5);margin:0;padding:0;list-style:none}.diagram-actor{display:flex;min-width:0}.diagram-node[data-shape=participant]{--_d-pd: var(--_drawn) var(--basalt-space-2-5) var(--basalt-space-3);--_d-pr: var(--_drawn) var(--basalt-radius-md);--_d-pa: var(--_drawn) center;flex:var(--_d-pflex, none);--_d-pflex: var(--_drawn) 1;align-items:center;justify-content:var(--_d-pa, center);min-height:var(--_d-ph, var(--basalt-size-badge));--_d-ph: var(--_drawn) 0;padding:var(--_d-pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline)));border-radius:var(--_d-pr, var(--basalt-radius-xs));text-align:center}.diagram-node[data-shape=participant]:not([data-focal]){--_d-pbg: var(--_drawn) var(--panel-next, var(--basalt-surface-1));--_d-pbc: var(--_drawn) var(--basalt-border-rim);--_d-pbt: var(--_drawn) var(--basalt-border-rim-top);background:var(--_d-pbg, none);border-color:var(--_d-pbc, var(--basalt-border-hairline));border-top-color:var(--_d-pbt, var(--basalt-border-hairline))}.diagram-node[data-shape=participant] .diagram-kind{--_d-pk: var(--_drawn) block;display:var(--_d-pk, none)}.diagram-node[data-shape=participant] .diagram-name{font-size:var(--_d-pn, var(--basalt-text-xs-size));line-height:var(--_d-pnl, var(--basalt-text-xs-line-height));font-weight:var(--_d-pw, var(--basalt-font-weight-medium));--_d-pn: var(--_drawn) var(--basalt-text-sm-size);--_d-pnl: var(--_drawn) var(--basalt-text-sm-line-height);--_d-pw: var(--_drawn) var(--basalt-font-weight-semibold)}.diagram-steps{--_d-sp: var(--_drawn) var(--basalt-space-4);position:relative;z-index:1;padding-block-start:var(--_d-sp, var(--basalt-space-4))}.diagram-msgs{margin:0;padding:0;list-style:none}.diagram-msg{--_d-md: var(--_drawn) grid;--_d-mc: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-mr: var(--_drawn) 1fr 1fr;--_d-mh: var(--_drawn) var(--basalt-size-diagram-step);--_d-mg: var(--_drawn) 0 var(--basalt-space-5);display:grid;grid-template-columns:var(--_d-mc, var(--basalt-space-8) minmax(0, 1fr));grid-template-rows:var(--_d-mr, auto);column-gap:var(--basalt-space-5);gap:var(--_d-mg, 0);height:var(--_d-mh, auto);padding-block:var(--_d-mpb, var(--basalt-space-2-5));--_d-mpb: var(--_drawn) 0;border-top:var(--_d-mb, var(--basalt-size-hairline) solid var(--basalt-border-divider));--_d-mb: var(--_drawn) 0;font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-said{--_d-sd: var(--_drawn) block;display:var(--_d-sd, contents);grid-column:var(--_a) / var(--_b);grid-row:1;align-self:end;justify-self:center;margin-block-end:calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--basalt-space-1-5);background:var(--_ground);white-space:nowrap}.diagram-num{grid-column:1;color:var(--basalt-text-tertiary);font-variant-numeric:tabular-nums}.diagram-said .diagram-num{margin-inline-end:var(--_d-nm, 0);--_d-nm: var(--_drawn) var(--basalt-space-1-5)}.diagram-mlabel{grid-column:2;color:var(--basalt-text-primary);font-family:var(--basalt-font-family-mono)}.diagram-route{--_d-rd: var(--_drawn) none;display:var(--_d-rd, inline-flex);grid-column:2;align-items:center;gap:var(--basalt-space-1);flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-note{--_d-nd: var(--_drawn) 2;grid-column:var(--_d-nc, 2);--_d-nc: var(--_drawn) var(--_a) / var(--_b);grid-row:var(--_d-nd, auto);align-self:start;justify-self:var(--_d-nj, stretch);--_d-nj: var(--_drawn) center;margin-block-start:var(--_d-nmt, 0);--_d-nmt: var(--_drawn) calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--_d-npi, 0);--_d-npi: var(--_drawn) var(--basalt-space-1-5);background:var(--_d-nbg, none);--_d-nbg: var(--_drawn) var(--_ground);color:var(--basalt-text-tertiary);white-space:var(--_d-nws, normal);--_d-nws: var(--_drawn) nowrap}.diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) start;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-start:var(--_d-sm, 0)}.diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) end;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-end:var(--_d-sm, 0)}.diagram-arrow{flex:none;overflow:visible}.diagram-band{--_d-bh: var(--_drawn) var(--basalt-size-control-lg);--_d-bj: var(--_drawn) center;position:relative;display:flex;align-items:center;justify-content:var(--_d-bj, flex-start);height:var(--_d-bh, auto);margin:var(--_d-bm, var(--basalt-space-5) 0 var(--basalt-space-2));--_d-bm: var(--_drawn) 0;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-band:before{--_d-br: var(--_drawn) "";content:var(--_d-br, none);position:absolute;inset-inline:0;top:50%;border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-band>span{position:relative;padding-inline:var(--_d-bp, 0);--_d-bp: var(--_drawn) var(--basalt-space-1-5);background:var(--_ground)}.diagram-node[data-shape=table]{align-self:start;padding:0;overflow-wrap:normal}.diagram-th{padding:var(--basalt-space-2) var(--basalt-space-3);border-bottom:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-node[data-focal] .diagram-th{border-bottom-color:var(--basalt-diagram-focal-rule)}.diagram-tname{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-rows{display:flex;flex-direction:column;padding-block:var(--basalt-space-1)}.diagram-row{display:flex;flex-wrap:wrap;align-items:center;column-gap:var(--basalt-space-3);min-height:var(--basalt-size-control-sm);padding-inline:var(--basalt-space-3);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-keyseat{flex:none;width:var(--basalt-space-6);margin-inline-end:calc(-1 * var(--basalt-space-3));color:var(--basalt-text-tertiary)}.diagram-cname{flex:1 0 auto;color:var(--basalt-text-primary)}.diagram-ctype{margin-inline-start:auto;color:var(--basalt-text-tertiary)}.diagram-ctype[data-ref]{color:var(--basalt-text-secondary)}.diagram-more{padding:0 var(--basalt-space-3) var(--basalt-space-2);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-key{padding-block-start:var(--basalt-space-3);border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-legend{display:flex;flex-wrap:wrap;gap:var(--basalt-space-2) var(--basalt-space-5);margin:0;padding:0;list-style:none;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-entry{display:inline-flex;align-items:center;gap:var(--basalt-space-1-5)}.diagram[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram:not([data-layout]) .diagram-entry[data-when=drawn]{display:none}.diagram-swatch{flex:none;overflow:visible}.diagram-swatch-shape{fill:var(--_ground);stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline)}.diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke-dasharray:var(--basalt-space-1) var(--basalt-space-0-5)}.diagram-fk-mark{color:var(--basalt-text-secondary);font-family:var(--basalt-font-family-mono)}.diagram-hint{display:flex;flex-wrap:wrap;gap:var(--basalt-space-1) var(--basalt-space-4);margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-hint>span{display:inline-flex;align-items:center;gap:var(--basalt-space-1)}.diagram[data-layout=stacked]:is([data-type=sequence],[data-type=schema]) .diagram-hint{display:none}.diagram-summary{order:1;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans);text-wrap:pretty}.diagram-foot{order:2;display:flex}.diagram-list{order:3;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list[hidden]{display:none}.diagram-list strong{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-code{color:var(--basalt-text-primary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-list-head{margin:var(--basalt-space-4) 0 var(--basalt-space-2);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list-head:first-child{margin-block-start:0}.diagram-list-group{margin:var(--basalt-space-3) 0 var(--basalt-space-1);color:var(--basalt-text-primary);font-size:inherit;font-weight:var(--basalt-font-weight-medium);line-height:inherit}.diagram-list-items{display:flex;flex-direction:column;gap:var(--basalt-space-1);margin:0;padding-inline-start:var(--basalt-space-5)}.diagram-list-exits{margin:var(--basalt-space-1) 0 0;padding-inline-start:var(--basalt-space-5)}@media(pointer:coarse){.diagram-toggle{min-height:var(--basalt-size-tap-min)}}@media(prefers-reduced-motion:reduce){.diagram-node,.diagram-line,.diagram-tip,.diagram-label,.diagram-diamond path{transition:none}}@media(prefers-contrast:more){.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:1}}@container (width >= 640px){.diagram:not([data-layout])[data-type=architecture][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 696px){.diagram:not([data-layout])[data-type=data-flow][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 768px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="4"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 784px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 800px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 888px){.diagram:not([data-layout])[data-type=data-flow][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 964px){.diagram:not([data-layout])[data-type=sequence][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 976px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 992px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1008px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 1080px){.diagram:not([data-layout])[data-type=data-flow][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1184px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1200px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1216px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1272px){.diagram:not([data-layout])[data-type=data-flow][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1312px){.diagram:not([data-layout])[data-type=schema][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]>.diagram-drawing{--_drawn: }}@media(scripting:none){.diagram:not(#basalt-diagram-no-id)>.diagram-drawing{--_drawn: initial}.diagram-list[hidden]{display:block}.diagram-foot,.diagram-entry[data-line],.diagram-hint{display:none}}@media(forced-colors:active){.diagram-svg,.diagram-swatch,.diagram-arrow{forced-color-adjust:none}.diagram .diagram-line,.diagram .diagram-line[data-kind]{stroke:CanvasText}.diagram .diagram-tip,.diagram .diagram-tip[data-kind],.diagram .diagram-dot{fill:CanvasText}.diagram .diagram-tip[data-open],.diagram .diagram-tip[data-kind][data-open]{fill:none;stroke:CanvasText}.diagram .diagram-edge[data-dim] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-dim] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:GrayText}.diagram .diagram-edge[data-dim] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-edge[data-lit] .diagram-line{stroke:Highlight}.diagram .diagram-edge[data-lit] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:Highlight}.diagram .diagram-edge[data-lit] .diagram-tip[data-open]{stroke:Highlight}.diagram .diagram-life{stroke:GrayText}.diagram .diagram-label{color:CanvasText;forced-color-adjust:none}.diagram .diagram-label[data-on]{background:Canvas}.diagram .diagram-label[data-lit]{color:Highlight}.diagram .diagram-swatch-shape{fill:Canvas;stroke:CanvasText}.diagram .diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke:GrayText}.diagram .diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:CanvasText;stroke:CanvasText}.diagram[data-type=flowchart] .diagram-node:not([data-focal]),.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:CanvasText}.diagram[data-measured][data-type=flowchart] .diagram-node[data-shape=decision][data-shape]{forced-color-adjust:none;background:none;border-color:transparent}.diagram .diagram-diamond{forced-color-adjust:none}.diagram .diagram-diamond path,.diagram .diagram-node[data-near] .diagram-diamond path{fill:Canvas;stroke:CanvasText}.diagram .diagram-group,.diagram .diagram-gbox{border-color:GrayText}.diagram .diagram-lane+.diagram-lane:before,.diagram .diagram-band:before{border-color:GrayText}.diagram .diagram-hint{color:GrayText}.diagram :is(.diagram-kind,.diagram-name,.diagram-detail,.diagram-glabel,.diagram-lane-name,.diagram-title,.diagram-source,.diagram-num,.diagram-mlabel,.diagram-route,.diagram-note,.diagram-band,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more,.diagram-legend,.diagram-fk-mark){color:CanvasText}.diagram .diagram-node:focus-visible{outline-color:Highlight}.diagram .diagram-node[data-focal],.diagram .diagram-node[data-focal][data-near]{forced-color-adjust:none;background:CanvasText;border-color:CanvasText}.diagram .diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:Canvas;opacity:1}.diagram .diagram-node[data-focal] .diagram-th{border-bottom-color:Canvas}.diagram .diagram-node[data-focal]:focus-visible{outline:var(--basalt-size-focus-width) solid Highlight}.diagram .diagram-node[data-focal][data-shape=decision] .diagram-diamond path{fill:CanvasText;stroke:CanvasText}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow{print-color-adjust:exact}.diagram-hint{display:none}}} diff --git a/.agent/skills/basalt-html/parts/diagram.js b/.agent/skills/basalt-html/parts/diagram.js index 10ce884f..dd5a0a6f 100644 --- a/.agent/skills/basalt-html/parts/diagram.js +++ b/.agent/skills/basalt-html/parts/diagram.js @@ -1 +1 @@ -(()=>{var Nt=["top","right","bottom","left"];function $t(t){const e=[],n=i=>{e.push(i)},a={...t.legend??{}},o=typeof t.stepLabel=="function"?t.stepLabel:typeof t.stepLabel=="string"?(i=>t.stepLabel.replace("{n}",String(i))):i=>`Step ${i}`,s={terminal:"Start or end",step:"Step",decision:"Decision",...t.shapeLabels??{}},r=[],d=[];let h=[];const l=[],c=[],u=t.type;if(u==="architecture"||u==="flowchart"){for(const i of t.nodes??[]){const g=u==="flowchart"&&i.shape==="decision"?"decision":u==="flowchart"&&i.shape==="terminal"?"terminal":"box";r.push({id:i.id,i:r.length,name:i.name,kind:g==="decision"?void 0:i.kind,detail:g==="decision"?void 0:i.detail,mono:!!i.detailMono,focal:!!i.focal,col:i.col,row:i.row,row2:i.row,branch:!!i.branch,shape:g,group:u==="architecture"?i.group:void 0})}if(u==="architecture")for(const i of t.groups??[])l.push({...i,members:r.filter(g=>g.group===i.id).map(g=>g.id)})}else if(u==="data-flow"){h=t.lanes??[];const i=new Map(h.map((g,b)=>[g.id,b+1]));for(const g of t.nodes??[]){const b=i.get(g.lane);b===void 0&&n(`a node (${g.id}) names the lane "${g.lane}", which is not in lanes`);const m=r.length+1;r.push({id:g.id,i:r.length,name:g.name,kind:o(m),detail:g.detail,mono:!!g.detailMono,focal:!!g.focal,col:g.col,row:b??1,row2:b??1,branch:!1,shape:"box",lane:b??1,laneLabel:h[(b??1)-1]?.label??g.lane,step:m})}}else if(u==="sequence"){(t.participants??[]).forEach((g,b)=>r.push({id:g.id,i:b,name:g.name,kind:g.kind,mono:!1,focal:!!g.focal,col:b+1,row:1,row2:1,branch:!1,shape:"participant",short:g.short??g.name}));let i=0;for(const g of t.steps??[])"band"in g?c.push({band:g.band}):c.push({n:++i,from:g.from,to:g.to,label:g.label,note:g.note,kind:g.kind??"plain"})}else if(u==="schema")for(const i of t.tables??[]){const[g,b]=Array.isArray(i.row)?i.row:[i.row,i.row];r.push({id:i.name,i:r.length,name:i.name,mono:!0,focal:!!i.focal,col:i.col,row:g,row2:b,branch:!1,shape:"table",more:i.more,columns:i.columns.map(m=>({name:m.name,type:m.type,key:m.key}))})}const p=new Map;for(const i of r)i.id?p.has(i.id)&&n(`the id "${i.id}" is used twice`):n("a node has no id"),p.set(i.id,i);if(u==="schema")(t.tables??[]).forEach(i=>i.columns.forEach((g,b)=>{if(!g.references)return;const[m,x]=g.references.split("."),B=p.get(m??""),v=B?.columns?.findIndex(I=>I.name===x)??-1;if(!B||v<0){n(`${i.name}.${g.name} references ${g.references}, which is not a shown column`);return}const _=p.get(i.name);_.columns[b].ref={table:m,column:x,row:v},d.push({i:d.length,from:i.name,to:m,kind:"plain",fromRow:b,toRow:v,fk:!0})}));else if(u!=="sequence")for(const i of t.edges??[]){if(!p.has(i.from)||!p.has(i.to)){n(`a line names ${p.has(i.from)?i.to:i.from}, which is not a node`);continue}i.label&&i.label.length>wt&&n(`the label "${i.label}" is over ${wt} characters: longer words belong in the node or the summary`);for(const g of[i.fromSide,i.toSide])g&&!Nt.includes(g)&&n(`"${g}" is not a side (top, right, bottom or left)`);d.push({i:d.length,from:i.from,to:i.to,kind:i.kind??"plain",label:i.label||void 0,fromSide:i.fromSide,toSide:i.toSide})}else for(const i of c)"n"in i&&(!p.has(i.from)||!p.has(i.to))&&n(`message ${i.n} names ${p.has(i.from)?i.to:i.from}, which is not a participant`);if(u!=="sequence"){const i=new Map;for(const g of r)for(let b=g.row;b<=g.row2;b++){const m=`${g.col}:${b}`;i.has(m)&&n(`${g.id} and ${i.get(m)} share the cell at column ${g.col}, row ${b}`),i.set(m,g.id)}}for(const i of l){const g=i.members.map(x=>p.get(x));if(!g.length)continue;const b={c1:Math.min(...g.map(x=>x.col)),c2:Math.max(...g.map(x=>x.col)),r1:Math.min(...g.map(x=>x.row)),r2:Math.max(...g.map(x=>x.row2))};for(const x of r)x.group!==i.id&&x.col>=b.c1&&x.col<=b.c2&&x.row>=b.r1&&x.row<=b.r2&&n(`${x.id} is inside the box of the group "${i.label}" but not a member`);const m=g.map(x=>x.i);Math.max(...m)-Math.min(...m)+1!==m.length&&n(`the members of the group "${i.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const i of r)i.group&&!l.some(g=>g.id===i.group)&&n(`${i.id} names the group "${i.group}", which is not in groups`);r.filter(i=>i.focal).length>1&&n("more than one node is focal: a diagram has one at most");const M=new Set(u==="sequence"?c.flatMap(i=>"n"in i?[i.kind]:[]):d.map(i=>i.kind));M.has("main")&&!a.main&&n("main lines are drawn but the legend has no words for them (legend.main)"),M.has("dashed")&&!a.dashed&&n("dashed lines are drawn but the legend has no words for them (legend.dashed)"),r.some(i=>i.focal)&&!a.focal&&n("a focal node is drawn but the legend has no words for what it marks (legend.focal)");const f=Math.max(1,...r.map(i=>i.col)),y=u==="data-flow"?Math.max(1,h.length):Math.max(1,...r.map(i=>i.row2));return{type:u,title:t.title,heading:t.heading??3,legend:a,nodes:r,byId:p,edges:d,groups:l,lanes:h,steps:c,cols:f,rows:y,shapeLabels:s,stepWord:o,warnings:e}}var wt=28,at=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""},Gt=t=>t.charAt(0).toUpperCase()+t.slice(1);function xt(t,e){return t.legend[e]}function Dt(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function Vt(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const a=(e.columns??[]).filter(s=>s.ref).map(s=>`${s.ref.table} (${s.name})`),o=t.edges.filter(s=>s.to===e.id).map(s=>`${s.from} (${t.byId.get(s.from).columns[s.fromRow].name})`);a.length&&n.push(`References ${a.join(", ")}.`),o.length&&n.push(`Referenced by ${o.join(", ")}.`)}else if(t.type==="sequence"){const a=t.steps.filter(s=>"n"in s&&s.from===e.id).length,o=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(at(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${a} ${a===1?"message":"messages"} and receives ${o}.`)}else{const a=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?Dt(t,e):e.kind;if(n.push(at(a?`${e.name}, ${a}`:e.name)),e.detail&&n.push(at(e.detail)),e.group){const r=t.groups.find(d=>d.id===e.group);r&&n.push(`In ${r.label}.`)}const o=t.edges.filter(r=>r.to===e.id).map(r=>`${t.byId.get(r.from).name}${r.label?` (${r.label})`:""}`),s=t.edges.filter(r=>r.from===e.id).map(r=>`${t.byId.get(r.to).name}${r.label?` (${r.label})`:""}`);o.length&&n.push(`From: ${o.join(", ")}.`),s.length&&n.push(`To: ${s.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(at(t.legend.focal)),n.join(" ")}function Zt(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function $(t,e,...n){const a=[];for(const o of n.flat(1/0))o!=null&&o!==!1&&!Array.isArray(o)&&a.push(o);return{t,a:e??{},c:a}}var Kt={"&":"&","<":"<",">":">",'"':""","'":"'"},tt=t=>t.replace(/[&<>"']/g,e=>Kt[e]),Ut=" br img input meta link hr path polygon polyline circle rect line ";function Mt(t,e={}){if(typeof t=="string")return tt(t);if("slot"in t)return e[t.slot]??"";let n="";for(const[a,o]of Object.entries(t.a))o==null||o===!1||(n+=o===!0?` ${a}`:` ${a}="${tt(String(o))}"`);return Ut.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(a=>Mt(a,e)).join("")}</${t.t}>`}var Xt=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function rt(t,e){return e.layout?e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema":!1}function Yt(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function vt(t){let e=0;for(const n of t.groups){const a=n.members.map(o=>t.byId.get(o).col);a.length&&(Math.min(...a)===1&&(e|=1),Math.max(...a)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function ht(t){return t.type==="sequence"?t.nodes.length:t.cols}function kt(t){const e=t.nodes,n=f=>t.type==="data-flow"||!e[f].branch,a=t.edges.map(f=>{const y=t.byId.get(f.from).i,i=t.byId.get(f.to).i,b=e.slice(Math.min(y,i)+1,Math.max(y,i)).every(m=>!n(m.i));return i===y+1&&!(n(y)&&!n(i))?"down":i===y-1?"up":i>y&&n(y)&&!n(i)&&b?"trunk":i>y&&n(y)&&n(i)&&b?"rail":i>y?"end-down":"end-up"}),o=t.edges.map((f,y)=>({e:f,k:y})).filter(({k:f})=>a[f]==="end-down"||a[f]==="end-up"),s=f=>{const y=t.byId.get(f.from).i,i=t.byId.get(f.to).i;return[Math.min(y,i),Math.max(y,i)]},r=(f,y)=>{const[i,g]=s(f),[b,m]=s(y);return i<m&&b<g},d=o.every(({e:f})=>{const y=t.byId.get(f.from).i,[i,g]=s(f);return!n(y)&&e.slice(i+1,g).every(b=>!n(b.i))&&o.every(b=>b.e===f||!r(b.e,f))}),h=o.length>0&&(t.type==="data-flow"||!d),l=f=>{const[y,i]=s(f);return i-y},c=t.edges.map(()=>0);let u=!1;for(const{e:f,k:y}of o){const i=o.filter(g=>g.e!==f&&r(g.e,f)&&(l(g.e)<l(f)||l(g.e)===l(f)&&g.k<y));if(c[y]=i.length?1:0,i.length>1||o.filter(g=>g.e!==f&&r(g.e,f)).length>1){const g=o.filter(b=>b.e!==f&&r(b.e,f));g.some(b=>g.some(m=>m!==b&&r(b.e,m.e)))&&(u=!0)}}const p=t.edges.map(()=>.5);for(const f of e){const y=o.filter(({e:b})=>b.from===f.id);if(y.length<2)continue;const i=y.filter(({k:b})=>a[b]==="end-down").sort((b,m)=>l(m.e)-l(b.e)||b.k-m.k),g=y.filter(({k:b})=>a[b]==="end-up").sort((b,m)=>l(b.e)-l(m.e)||m.k-b.k);[...i,...g].forEach(({k:b},m,x)=>{p[b]=x.length===2?m===0?1/3:2/3:(m+1)/(x.length+1)})}const M={};for(let f=1;f<e.length;f++){const y=e[f],i=e[f-1];let g=0,b=t.type==="data-flow"?48:32,m=!1,x=!1;t.edges.forEach((B,v)=>{const _=a[v],I=t.byId.get(B.from).i,j=t.byId.get(B.to).i,F=j===f&&(_==="down"||_==="trunk"||_==="rail"||_==="end-down"),G=I===f&&j===f-1&&_==="up",A=j===f-1&&_==="end-up";F&&(_==="trunk"||_==="end-down")&&(m=!0),A&&(x=!0),(F||G||A)&&B.label&&(g++,b=Math.max(b,_==="trunk"?40:48))}),(g>1||m&&x)&&(b=64),M[y.id]=b}return{routes:a,gutter:h,lanes:c,exits:p,gaps:M,third:u}}var ct=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function St(t,e){const n=e==="fk"?"plain":e,a=n==="main"?8:8.5,o=24,s=n==="dashed"?o-1:o-7;return $("svg",{class:`${t}-swatch`,"data-kind":n,...ct(24,16)},e==="fk"?$("circle",{class:`${t}-dot`,cx:3,cy:a,r:3}):null,$("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${a}H${s}`}),n==="dashed"?$("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${o-8} ${a-4}L${o} ${a}L${o-8} ${a+4}`}):$("path",{class:`${t}-tip`,"data-kind":n,d:`M${o} ${a}L${o-8} ${a-4}L${o-8} ${a+4}Z`}))}function dt(t,e){return e==="decision"?$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):$("svg",{class:`${t}-swatch`,"data-shape":e,...ct(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function Jt(t,e){const n=[],a=(s,r,d={})=>n.push($("li",{class:`${t}-entry`,...d},s,$("span",null,r)));if(e.type==="flowchart"){const s=new Set(e.nodes.map(r=>r.shape));s.has("terminal")&&a(dt(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&a(dt(t,"box"),e.shapeLabels.step),s.has("decision")&&a(dt(t,"decision"),e.shapeLabels.decision)}const o=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind));for(const s of["main","plain","dashed"]){const r=e.legend[s];o.has(s)&&r&&a(St(t,s),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(a(St(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"}),n.push($("li",{class:`${t}-entry`,"data-when":"stacked"},$("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},"→"),$("span",null,"A foreign key, written in the row")))),e.nodes.some(s=>s.focal)&&e.legend.focal&&a(dt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&a(dt(t,"group"),e.legend.group),n.length?$("div",{class:`${t}-key`},$("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function Qt(t,e){const n=e==="main"?6:6.5;return $("svg",{class:`${t}-arrow`,"data-kind":e,...ct(20,12)},$("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?$("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):$("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function Pt(t,e,n){if(n.shape==="decision")return[$("span",{class:`${t}-words`},$("span",{class:`${t}-name`},n.name))];const a=[];return e.type==="data-flow"?a.push($("span",{class:`${t}-kind`},n.kind,$("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&a.push($("span",{class:`${t}-kind`},n.kind)),a.push($("span",{class:`${t}-name`},n.name)),n.detail&&a.push($("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.detail)),a}function te(t,e){return[$("span",{class:`${t}-th`},$("span",{class:`${t}-tname`},e.name)),$("span",{class:`${t}-rows`},(e.columns??[]).map((n,a)=>$("span",{class:`${t}-row`,"data-row":a,"data-key":n.key},$("span",{class:`${t}-keyseat`},n.key??""),$("span",{class:`${t}-cname`},n.name),n.ref?$("span",{class:`${t}-ctype`,"data-ref":""},`→ ${n.ref.table}`):n.type?$("span",{class:`${t}-ctype`},n.type):null))),e.more?$("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Et=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function pt(t,e,n,a){const{P:o}=t,s=Yt(e,a)||a.keep===n.id,r=rt(e,a),d=[`--_c:${n.col}`,`--_r:${n.row}`,`--_r2:${n.row2+1}`];e.type==="data-flow"&&d.push(`--_lc:${n.col+1}`),e.type==="sequence"&&d.push(`--_c2:${n.col+1}`);const h=t.plan;if(h&&n.i>0){const c=h.gaps[n.id]??32,u=a.grow?.[n.id]??0;d.push(`--_gap:${u?`calc(${Et(c)} + var(--basalt-space-4) * ${u})`:Et(c)}`)}a.heights?.[n.id]&&d.push(`--_h:${a.heights[n.id]}px`);const l=r?a.stop===n.id?0:-1:a.keep===n.id?-1:void 0;return $("div",{class:`${o}-node`,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-level":t.level,style:d.join(";"),role:s?"img":void 0,"aria-label":s?Vt(e,n):void 0,tabindex:l},n.shape==="decision"?$("svg",{class:`${o}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},$("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.shape==="table"?te(o,n):Pt(o,e,n))}function ee(t,e,n){const{P:a}=t,o=[];if(e.type==="data-flow"&&o.push(...e.lanes.map((r,d)=>$("div",{class:`${a}-lane`,style:`--_r:${d+1}`,"aria-hidden":"true"},$("span",{class:`${a}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const d=r.members.map(p=>e.byId.get(p));if(!d.length)continue;const h=Math.min(...d.map(p=>p.col)),l=Math.max(...d.map(p=>p.col)),c=Math.min(...d.map(p=>p.row)),u=Math.max(...d.map(p=>p.row2));o.push($("div",{class:`${a}-gbox`,"data-group":r.id,style:`--_c:${h};--_c2:${l+1};--_r:${c};--_r2:${u+1}`,"aria-hidden":"true"},$("span",{class:`${a}-glabel`},r.label)))}if(e.type==="sequence")return o.push($("ul",{class:`${a}-cast`},e.nodes.map(r=>$("li",{class:`${a}-actor`},pt(t,e,r,n))))),o.push(ne(t,e)),o;let s=0;for(;s<e.nodes.length;){const r=e.nodes[s],d=r.group?e.groups.find(l=>l.id===r.group):void 0;if(!d){o.push(pt(t,e,r,n)),s++;continue}const h=[];for(;s<e.nodes.length&&e.nodes[s].group===d.id;)h.push(e.nodes[s++]);o.push($("div",{class:`${a}-group`,"data-group":d.id},$("span",{class:`${a}-glabel`,"aria-hidden":"true"},d.label),h.map(l=>pt(t,e,l,n))))}return o}function ne(t,e){const{P:n}=t,a=[];let o=null;for(const s of e.steps){if("band"in s){o=null,a.push($("p",{class:`${n}-band`},$("span",null,s.band)));continue}o||(o=$("ol",{class:`${n}-msgs`,start:s.n}),a.push(o));const r=e.byId.get(s.from),d=e.byId.get(s.to),h=r?.col??1,l=d?.col??1,c=h===l,u=c&&h===e.nodes.length,p=xt(e,s.kind);o.c.push($("li",{class:`${n}-msg`,"data-kind":s.kind,"data-from":s.from,"data-to":s.to,"data-self":c?u?"start":"end":void 0,style:`--_a:${Math.min(h,l)};--_b:${Math.max(h,l)+1}`},$("span",{class:`${n}-said`},$("span",{class:`${n}-num`},String(s.n)),$("span",{class:`${n}-mlabel`},s.label)),$("span",{class:`${n}-route`},r?.short??s.from," ",Qt(n,s.kind),$("span",{class:t.hidden}," to ")," ",d?.short??s.to,p?` · ${p}`:""),s.note?$("span",{class:`${n}-note`},s.note):null))}return $("div",{class:`${n}-steps`},a)}function se(t,e){const n=Math.min(6,e.heading+1),a=c=>$(`h${n}`,{class:`${t}-list-head`},c),o=c=>$("strong",null,c),s=c=>$("code",{class:`${t}-code`},c),r=c=>e.byId.get(c)?.name??c,d=c=>{const u=xt(e,c);return u?` (${u})`:""},h=c=>c.focal&&e.legend.focal?` ${at(e.legend.focal)}`:"";if(e.type==="architecture"){const c=M=>$("li",null,o(M.name),M.kind?`, ${M.kind}`:"",M.detail?[". ",M.mono?s(M.detail):M.detail,/[.!?]$/.test(M.detail)?"":"."]:/[.!?]$/.test(M.kind??M.name)?"":".",h(M)),u=[a("Parts")],p=e.nodes.filter(M=>!M.group);p.length&&u.push($("ul",{class:`${t}-list-items`},p.map(c)));for(const M of e.groups)u.push($("p",{class:`${t}-list-group`},M.label)),u.push($("ul",{class:`${t}-list-items`},M.members.map(f=>c(e.byId.get(f)))));return u.push(a("Connections")),u.push($("ol",{class:`${t}-list-items`},e.edges.map(M=>$("li",null,o(r(M.from))," to ",o(r(M.to)),M.label?[": ",s(M.label)]:"",`${d(M.kind)}.`)))),u}if(e.type==="flowchart"){const c=u=>(e.byId.get(u)?.i??0)+1;return[$("ol",{class:`${t}-list-items`},e.nodes.map(u=>{const p=e.edges.filter(y=>y.from===u.id),M=u.shape==="decision"?"Decision":u.shape==="terminal"?p.length?"Start":"End":"Step",f=!u.detail&&/[.!?]$/.test(u.name)?" ":". ";return $("li",null,o(u.name),u.detail?[", ",u.mono?s(u.detail):u.detail]:"",`${f}${M}.`,h(u),p.length?$("ul",{class:`${t}-list-exits`},p.map(y=>$("li",null,y.label?`If ${y.label}: go to ${c(y.to)}, `:`Then: go to ${c(y.to)}, `,o(r(y.to)),y.kind==="main"&&e.legend.main?` (${e.legend.main})`:""))):null)}))]}if(e.type==="data-flow")return[$("ol",{class:`${t}-list-items`},e.nodes.map(c=>{const u=e.edges.filter(p=>p.from===c.id);return $("li",null,`${c.laneLabel}: `,o(c.name),c.detail?[", ",c.mono?s(c.detail):c.detail]:"",".",h(c),u.length?[" Then ",...u.flatMap((p,M)=>[M?"; ":"",`to step ${e.byId.get(p.to).step}, `,o(r(p.to)),p.label?[": ",s(p.label)]:"",d(p.kind)]),"."]:"")}))];if(e.type==="sequence"){const c=[a("Participants"),$("ul",{class:`${t}-list-items`},e.nodes.map(p=>$("li",null,o(p.name),p.kind?`, ${p.kind}`:"",".",h(p))))];c.push(a("Messages"));let u=null;for(const p of e.steps){if("band"in p){u=null,c.push($("p",{class:`${t}-list-group`},p.band));continue}u||(u=$("ol",{class:`${t}-list-items`,start:p.n}),c.push(u)),u.c.push($("li",null,s(p.label),": ",o(r(p.from))," to ",o(r(p.to)),`${d(p.kind)}.`,p.note?` ${at(Gt(p.note))}`:""))}return c}const l=[];for(const c of e.nodes)l.push($("p",{class:`${t}-list-group`},s(c.name),h(c))),l.push($("ul",{class:`${t}-list-items`},[...(c.columns??[]).map(u=>$("li",null,s(u.name),u.key==="PK"?", primary key":u.key==="FK"?", foreign key":"",u.ref?[", references ",s(`${u.ref.table}.${u.ref.column}`)]:u.type?`, ${u.type}`:"")),...c.more?[$("li",null,`and ${c.more} more ${c.more===1?"column":"columns"}`)]:[]]));return l}function oe(t){return`Arrow keys move to the next or the previous ${t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step"}, in the author's order; Home and End go to the ends; Escape clears the trace.`}function ae(t){return[{keys:["←","→"],words:Zt(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}function Lt(t,e,n){const a=n.prefix,o=Xt(n.base),s=t.type==="sequence"||t.type==="schema"?null:kt(t),r={P:a,ids:o,level:n.level,plan:s,hidden:n.hiddenClass},d=e.layout==="drawn",h=rt(t,e),l=t.type==="sequence"||t.type==="schema"?d:!0,c=`h${t.heading}`,u=[`--_cols:${ht(t)}`];if(t.type==="architecture"&&t.groups.length){const p=t.groups.flatMap(f=>f.members.map(y=>t.byId.get(y))),M=(f,y)=>f?`var(--basalt-space-${y})`:"0px";u.push(`--_gpad:${M(p.some(f=>f.row===1),"8")} ${M(p.some(f=>f.col===t.cols),"4")} ${M(p.some(f=>f.row2===t.rows),"4")} ${M(p.some(f=>f.col===1),"4")}`)}return t.type==="schema"&&e.track&&u.push(`--_track:${e.track}px`),$("figure",{class:n.className?`${a} ${n.className}`:a,"aria-labelledby":o.title,"data-type":t.type,"data-cols":ht(t),"data-reach":t.type==="architecture"?vt(t):void 0,"data-gutter":s?.gutter?"":void 0,"data-layout":e.layout,"data-measured":e.layout?"":void 0,style:u.join(";")},$("div",{class:`${a}-head`},$(c,{id:o.title,class:`${a}-title`},t.title),n.hasSource?$("p",{class:`${a}-source`},{slot:"source"}):null),$("div",{class:`${a}-drawing`,role:l?"group":void 0,"aria-roledescription":l?"diagram":void 0,"aria-labelledby":l?o.title:void 0,"aria-describedby":l?`${o.summary} ${o.keys}`:void 0,"data-stops":h?"":void 0},ee(r,t,e),$("div",{class:`${a}-ink`,"aria-hidden":"true"}),$("span",{class:`${a}-ruler`,"aria-hidden":"true"})),Jt(a,t),$("p",{class:`${a}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),$("div",{class:`${a}-foot`},{slot:"toggle"}),$("div",{id:o.list,class:`${a}-list`,hidden:!e.open},se(a,t)),$("span",{id:o.keys,class:n.hiddenClass},oe(t)),$("figcaption",{id:o.summary,class:`${a}-summary`},{slot:"summary"}))}function re(t){const e=getComputedStyle(t),n=(o,s)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${o}`));return Number.isFinite(r)?r:s},a=new Map;return{space:o=>(a.has(o)||a.set(o,n(`space-${o}`,parseFloat(o.replace("-","."))*4)),a.get(o)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4)}}var ft=(t,e)=>t==="main"?e.line:e.hair,Q=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},P=(t,e,n=.01)=>t.l<e.r-n&&t.r>e.l+n&&t.t<e.b-n&&t.b>e.t+n,At=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function Y(t,e,n){const{l:a,t:o,r:s,b:r}=t.rect,d=(a+s)/2,h=(o+r)/2,l=(s-a)/2,c=(r-o)/2,u=e==="top"||e==="bottom";if(t.shape==="decision"){if(u){const f=n,y=c*Math.max(0,1-Math.abs(f-d)/l);return{x:f,y:e==="top"?h-y:h+y}}const p=n,M=l*Math.max(0,1-Math.abs(p-h)/c);return{x:e==="left"?d-M:d+M,y:p}}if(t.shape==="terminal"){const p=Math.min(l,c);if(u){const i=n,g=Math.min(Math.max(i,a+p),s-p),b=i-g,m=Math.abs(b)>=p?0:Math.sqrt(p*p-b*b);return{x:i,y:Math.abs(b)<1e-6?e==="top"?o:r:e==="top"?h-m:h+m}}const M=n,f=M-h,y=Math.abs(f)>=p?0:Math.sqrt(p*p-f*f);return{x:e==="left"?a+p-y:s-p+y,y:M}}return u?{x:n,y:e==="top"?o:r}:{x:e==="left"?a:s,y:n}}function ie(t,e,n){const{l:a,t:o,r:s,b:r}=e.rect,d=(a+s)/2,h=(o+r)/2,l=(s-a)/2,c=(r-o)/2;if(e.shape==="decision")return Math.abs(t.x-d)/l+Math.abs(t.y-h)/c<1-n/Math.min(l,c);if(e.shape==="terminal"){const u=Math.min(l,c),p=Math.min(Math.max(t.x,a+u),s-u);return Math.hypot(t.x-p,t.y-h)<u-n}return t.x>a+n&&t.x<s-n&&t.y>o+n&&t.y<r-n}function qt(t,e){if(!P(t,e.rect))return!1;if(e.shape!=="decision"&&e.shape!=="terminal")return!0;const{l:n,t:a,r:o,b:s}=e.rect,r=(n+o)/2,d=(a+s)/2,h=(o-n)/2,l=(s-a)/2;if(e.shape==="decision"){const u=Math.max(t.l,Math.min(r,t.r)),p=Math.max(t.t,Math.min(d,t.b));return Math.abs(u-r)/h+Math.abs(p-d)/l<1-1e-6}const c=Math.min(l,h);if(P(t,{l:n+c,r:o-c,t:a,b:s}))return!0;for(const u of[n+c,o-c]){const p=Math.max(t.l,Math.min(u,t.r)),M=Math.max(t.t,Math.min(d,t.b));if(Math.hypot(p-u,M-d)<c-.01)return!0}return!1}function le(t,e,n){const a=Math.hypot(e.x-t.x,e.y-t.y),o=Math.max(2,Math.ceil(a/2));for(let s=1;s<o;s++){const r=s/o;if(!(r*a<1.5||(1-r)*a<1.5)&&ie({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r},n,1))return!0}return!1}function ce(t,e){const n=t.querySelector(`.${e}-ruler`),a=new Map;return(o,s)=>{const r=`${s}|${o}`;return a.has(r)||(n.setAttribute("data-f",s),n.textContent=o,a.set(r,n.getBoundingClientRect().width),n.textContent=""),a.get(r)}}var gt=t=>t?t.split(/\s+/).filter(Boolean):[];function de(t,e,n){const a=e.space;let o=e.node,s=e.table;for(const h of t.nodes){if(h.shape==="table"){for(const p of h.columns??[]){const M=p.ref?`→ ${p.ref.table}`:p.type??"",f=a("6")+n(p.name,"mono")+(M?a("3")+n(M,"mono"):0)+2*a("3")+2*e.hair;s=Math.max(s,Math.ceil(f))}s=Math.max(s,Math.ceil(n(h.name,"table")+2*a("3")+2*e.hair));continue}const l=h.shape==="terminal"?2*a("5"):2*a("3");let c=0;for(const p of gt(h.name))c=Math.max(c,n(p,h.shape==="decision"?"name-500":"name"));if(t.type!=="data-flow")for(const p of gt(h.kind))c=Math.max(c,n(p,"mono"));for(const p of gt(h.detail))c=Math.max(c,n(p,h.mono?"mono":"sans"));const u=h.shape==="decision"?c/.62:c+l+2*e.hair;o=Math.max(o,Math.ceil(u))}const r=ht(t);let d;return t.type==="data-flow"?d=e.lane+r*(o+a("12")):t.type==="schema"?d=r*s+(r-1)*a("12"):t.type==="sequence"?d=r*e.node+(r-1)*a("5"):d=r*o+(r-1)*a("16")+vt(t)*a("4"),{track:o,table:s,least:Math.max(e.wide,d)}}function It(t,e){return{x:(n,a)=>a%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,a)=>a%2===1?Math.round(n+e-.5)+.5-e:Math.round(n+e)-e}}function yt(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ct(t,e,n){const a=t.map(s=>({...s}));for(let s=1;s<a.length;s++){const r=a[s-1],d=a[s];if(Math.abs(r.x-d.x)<.75){const h=n.x(r.x,e);r.x=h,d.x=h}else if(Math.abs(r.y-d.y)<.75){const h=n.y(r.y,e);r.y=h,d.y=h}}const o=[a[0]];for(let s=1;s<a.length;s++){const r=a[s],d=o[o.length-1];if(!(Math.abs(r.x-d.x)<.01&&Math.abs(r.y-d.y)<.01)){if(o.length>=2){const h=o[o.length-2];if(Math.abs(h.x-d.x)<.01&&Math.abs(d.x-r.x)<.01||Math.abs(h.y-d.y)<.01&&Math.abs(d.y-r.y)<.01){o[o.length-1]=r;continue}}o.push(r)}}return o}var it=t=>t.slice(1).map((e,n)=>[t[n],e]);function ut(t,e){const n=[];for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){const r=t[o],d=t[s];for(const[h,l]of it(r.pts))for(const[c,u]of it(d.pts)){const p=Math.abs(h.y-l.y)<.01,M=Math.abs(c.y-u.y)<.01;if(p===M)continue;const[f,y,i,g]=p?[h,l,c,u]:[c,u,h,l],b=i.x,m=f.y;if(b>Math.min(f.x,y.x)+.75&&b<Math.max(f.x,y.x)-.75&&m>Math.min(i.y,g.y)+.75&&m<Math.max(i.y,g.y)-.75){const x=p?o:s,B=p?s:o;let v=x,_=B;if(e){const I=e(t[x]);e(t[B])&&!I&&(v=B,_=x)}n.push({top:v,under:_,at:{x:b,y:m},underVertical:_===B})}}}return n}function fe(t){const e=getComputedStyle(t),n=o=>o.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),a=(o,s,r)=>{const d=[];let h=s;for(const l of o)d.push([h,h+l]),h+=l+r;return d};return{cols:a(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:a(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var D=t=>t==="left"||t==="right",Bt={top:"bottom",bottom:"top",left:"right",right:"left"};function ue(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function he(t,e,n){const a=[];t.edges.forEach((s,r)=>{const d=t.byId.get(s.from),h=t.byId.get(s.to),[l,c]=e[r],u=d.row===h.row&&D(l)&&D(c)&&l===Bt[c]||d.col===h.col&&!D(l)&&!D(c)&&l===Bt[c];a.push({edge:r,end:"from",node:d,side:l,far:h,straight:u,f:.5},{edge:r,end:"to",node:h,side:c,far:d,straight:u,f:.5})});const o=new Map;for(const s of a){const r=`${s.node.id}.${s.side}`;o.has(r)||o.set(r,[]),o.get(r).push(s)}for(const[s,r]of o){if(r[0].node.shape==="decision")continue;const d=c=>D(c.side)?c.far.row-c.node.row:c.far.col-c.node.col,h=r.filter(c=>c.straight),l=r.filter(c=>!c.straight);l.sort((c,u)=>d(c)-d(u)||(D(c.side)?c.far.col-u.far.col:c.far.row-u.far.row)*(d(c)<0?1:-1)),r.length>3&&n(`${s.replace("."," has ")} has ${r.length} lines on one side; more than three is an error: use another side`),h.length?l.forEach(c=>{c.f=d(c)<0?.25:.75}):l.length===2?(l[0].f=.25,l[1].f=.75):l.length===3?(l[0].f=.25,l[1].f=.5,l[2].f=.75):l.length>3&&l.forEach((c,u)=>{c.f=(u+1)/(l.length+1)})}return a}function _t(t,e,n){const{l:a,t:o,r:s,b:r}=t.rect;return D(e)?Y(t,e,o+(r-o)*n):Y(t,e,a+(s-a)*n)}function Ot(t,e,n,a){const o=new Map;return e.querySelectorAll(`.${a}-node`).forEach(s=>{const r=t.byId.get(s.dataset.node);r&&o.set(r.id,{id:r.id,rect:Q(s,n),shape:r.shape,i:r.i})}),o}function mt(t,e){const n=e.head,a=e.head/2,{x:o,y:s}=t.tip;return t.dir==="down"?{l:o-a,r:o+a,t:s-n,b:s}:t.dir==="up"?{l:o-a,r:o+a,t:s,b:s+n}:t.dir==="right"?{l:o-n,r:o,t:s-a,b:s+a}:{l:o,r:o+n,t:s-a,b:s+a}}var jt=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function pe(t,e,n,a,o,s,r,d){const h=r.space,l=[],c=[],u=[],p=h("1"),M=e.filter(f=>t.edges[f.i]?.label).sort((f,y)=>+(t.edges[y.i].kind==="main")-+(t.edges[f.i].kind==="main")||f.i-y.i);for(const f of M){const y=t.edges[f.i].label,i=d(y,"label"),g=16,b=f.pts.length-2,m=[];it(f.pts).forEach(([v,_],I)=>{const j=Math.abs(v.y-_.y)<.01,F=j?v.x:v.y;let G=j?_.x:_.y;const A=Math.sign(G-F)||1;I===b&&(G-=A*r.head);let z=[[F,G]];for(const O of o)for(const R of j?[O.l,O.r]:[O.t,O.b]){const w=j?v.y:v.x;(j?w>O.t&&w<O.b:w>O.l&&w<O.r)&&(z=z.flatMap(([E,k])=>R>Math.min(E,k)+1&&R<Math.max(E,k)-1?[[E,R],[R,k]]:[[E,k]]))}const W=(O,R)=>{const w=(O+R)/2,C=j?{x:w,y:v.y}:{x:v.x,y:w};return!o.some(E=>C.x>E.l&&C.x<E.r&&C.y>E.t&&C.y<E.b)};for(const[O,R]of z)m.push({horiz:j,c:j?v.y:v.x,p:O,q:R,len:Math.abs(R-O),pri:z.length>1&&W(O,R)?1:0})}),m.sort((v,_)=>_.pri-v.pri||_.len-v.len);let x=null;const B=v=>{const _=At(v,p);return v.l<s.l||v.r>s.r||v.t<s.t||v.b>s.b||n.some(I=>qt(_,I))||l.some(I=>P(_,I))||a.heads.some(I=>P(_,I))||a.rects.some(I=>P(_,I))?!1:!e.some(I=>I.i!==f.i&&it(I.pts).some(([j,F])=>P(_,jt(j,F,I.width))))};for(const v of m){for(const _ of[1/2,1/3,2/3]){const I=v.p+(v.q-v.p)*_,j=[],F=h("2")+f.width/2;if(v.horiz?(v.len>=i+2*h("1")+h("3-5")&&j.push({box:{l:I-i/2-h("1"),r:I+i/2+h("1"),t:v.c-g/2,b:v.c+g/2},on:!0}),j.push({box:{l:I-i/2,r:I+i/2,t:v.c-F-g,b:v.c-F},on:!1}),j.push({box:{l:I-i/2,r:I+i/2,t:v.c+F,b:v.c+F+g},on:!1})):(v.len>=g+h("3")&&j.push({box:{l:v.c-i/2-h("1"),r:v.c+i/2+h("1"),t:I-g/2,b:I+g/2},on:!0}),j.push({box:{l:v.c+F,r:v.c+F+i,t:I-g/2,b:I+g/2},on:!1}),j.push({box:{l:v.c-F-i,r:v.c-F,t:I-g/2,b:I+g/2},on:!1})),x=j.find(G=>B(G.box))??null,x)break}if(x)break}if(!x){u.push(f.i);continue}l.push(x.box),c.push({i:f.i,text:y,box:x.box,on:x.on})}return{labels:c,unseated:u}}function Rt(t,e,n,a){const o=[],s=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const d=Q(r,e);s.push(d),o.push({l:d.l,r:d.r,t:d.t,b:d.t+1},{l:d.l,r:d.r,t:d.b-1,b:d.b},{l:d.l,r:d.l+1,t:d.t,b:d.b},{l:d.r-1,r:d.r,t:d.t,b:d.b});const h=r.querySelector(`:scope > .${n}-glabel`);h&&h.getClientRects().length&&o.push(Q(h,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,d)=>{if(!r.getClientRects().length)return;const h=Q(r,e);d>0&&o.push({l:h.l,r:h.r,t:h.t-a/2-.5,b:h.t-a/2+.5});const l=r.querySelector(`.${n}-lane-name`);l&&o.push(Q(l,e))}),{obstacles:{rects:o,heads:[]},groups:s}}function ge(t,e){const{m:n,tk:a,P:o,drawing:s,origin:r,warn:d}=t,h=a.space,l=Ot(n,s,r,o),c=[...l.values()],u=fe(s),p=r.left-Math.floor(r.left),M=r.top-Math.floor(r.top),f=It(p,M),y=s.clientWidth,i=s.clientHeight,g=w=>n.type==="data-flow"?w.col+1:w.col,b=parseFloat(getComputedStyle(s).rowGap)||0,m={w:y,h:i,nodes:c,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],ox:p,oy:M};if(n.type==="sequence")return ye(t,m,f);let x,B=[];n.type==="schema"?x=n.edges.map(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to);if(C.col===E.col){const k=C.col===n.cols?"left":"right";return[k,k]}return E.col>C.col?["right","left"]:["left","right"]}):(x=n.edges.map(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to),[k,L]=ue(C,E);return[w.fromSide??k,w.toSide??L]}),B=he(n,x,d));const v=(w,C)=>{const E=s.querySelector(`.${o}-node[data-node="${CSS.escape(w)}"] .${o}-row[data-row="${C}"]`);if(!E)return 0;const k=Q(E,r);return(k.t+k.b)/2},_=n.edges.map((w,C)=>{const[E,k]=x[C],L=l.get(w.from),H=l.get(w.to),N=ft(w.kind,a);if(w.fk){const T=f.y(v(w.from,w.fromRow),N),U=f.y(v(w.to,w.toRow),N);return{p1:{x:E==="right"?L.rect.r:L.rect.l,y:T},p2:{x:k==="right"?H.rect.r:H.rect.l,y:U}}}const V=B.find(T=>T.edge===C&&T.end==="from").f,Z=B.find(T=>T.edge===C&&T.end==="to").f;let S=_t(L,E,V),q=_t(H,k,Z);return D(E)?S={...S,y:f.y(S.y,N)}:S={...S,x:f.x(S.x,N)},D(k)?q={...q,y:f.y(q.y,N)}:q={...q,x:f.x(q.x,N)},D(E)&&D(k)&&Math.abs(S.y-q.y)<1.01&&(q={...q,y:S.y}),!D(E)&&!D(k)&&Math.abs(S.x-q.x)<1.01&&(q={...q,x:S.x}),S=D(E)?Y(L,E,S.y):Y(L,E,S.x),q=D(k)?Y(H,k,q.y):Y(H,k,q.x),{p1:S,p2:q}}),I=new Map;n.edges.forEach((w,C)=>{const[E,k]=x[C],{p1:L,p2:H}=_[C],N=n.byId.get(w.from),V=n.byId.get(w.to);let Z=null,S=null,q=!1;if(D(E)&&D(k)&&E!==k&&Math.abs(L.y-H.y)>.5){const K=g(V),et=k==="left",st=u.cols[(et?K-1:K)-1],X=u.cols[(et?K:K+1)-1];st&&X&&(Z=`c${et?K-1:K}`,S=[st[1],X[0]],q=!0)}else if(!D(E)&&!D(k)&&E!==k&&Math.abs(L.x-H.x)>.5){const et=k==="top"?V.row-1:V.row2,st=u.rows[et-1],X=u.rows[et];st&&X&&(Z=`r${et}`,S=[st[1],X[0]],q=!1)}if(!Z||!S)return;I.has(Z)||I.set(Z,{span:S,vertical:q,members:new Map});const T=`${w.to}.${k}.${Math.round(q?H.y:H.x)}`,U=I.get(Z);U.members.has(T)||U.members.set(T,[]),U.members.get(T).push(C)});const j=new Map,F=w=>{const[C,E]=x[w],{p1:k,p2:L}=_[w];if(D(C)&&D(E)){if(C===E){const N=C==="right"?Math.max(k.x,L.x)+h("4"):Math.min(k.x,L.x)-h("4");return[k,{x:N,y:k.y},{x:N,y:L.y},L]}if(Math.abs(k.y-L.y)<=.5)return[k,{x:L.x,y:k.y}];const H=j.get(w)??(k.x+L.x)/2;return[k,{x:H,y:k.y},{x:H,y:L.y},L]}if(!D(C)&&!D(E)){if(C===E){const N=C==="bottom"?Math.max(k.y,L.y)+h("4"):Math.min(k.y,L.y)-h("4");return[k,{x:k.x,y:N},{x:L.x,y:N},L]}if(Math.abs(k.x-L.x)<=.5)return[k,{x:k.x,y:L.y}];const H=j.get(w)??(k.y+L.y)/2;return[k,{x:k.x,y:H},{x:L.x,y:H},L]}return D(C)?[k,{x:L.x,y:k.y},L]:[k,{x:k.x,y:L.y},L]},G=()=>n.edges.map((w,C)=>{const E=ft(w.kind,a),k=Ct(F(C),E,f);return{i:C,from:w.from,to:w.to,kind:w.kind,pts:k,tip:k[k.length-1],dir:yt(k),dot:w.fk?k[0]:void 0,width:E}}),A=w=>ut(w).length*1e3+bt(w,c,n).length,z=(w,C)=>{const E=w.flatMap(k=>{const{p1:L,p2:H}=_[k];return C?[L.y,H.y]:[L.x,H.x]});return[Math.min(...E),Math.max(...E)]};for(const[,w]of I){const C=[...w.members.values()].map(k=>({members:k,run:z(k,w.vertical)})).sort((k,L)=>k.run[0]-L.run[0]),E=[];for(const k of C){const L=E[E.length-1];L&&L.some(H=>H.run[0]<k.run[1]+h("8")&&k.run[0]<H.run[1]+h("8"))?L.push(k):E.push([k])}for(const k of E){const L=k.map(S=>S.members),H=L.length,N=(w.span[1]-w.span[0])/(H+1);N<h("3")&&d(`a gutter holds ${H} lanes side by side, closer than space-3`);let V=L,Z=1/0;for(const S of Tt(L)){S.forEach((T,U)=>T.forEach(K=>j.set(K,w.span[0]+N*(U+1))));const q=A(G());q<Z&&(Z=q,V=S)}V.forEach((S,q)=>S.forEach(T=>j.set(T,w.span[0]+N*(q+1))))}}m.lines=G(),n.type==="schema"&&(m.lines=m.lines.filter(w=>{const C=n.byId.get(w.from),E=n.byId.get(w.to);return Math.abs(C.col-E.col)>1?(d(`${w.from} to ${w.to} is two columns apart, so its line is not drawn; its row still writes the target`),!1):!0})),m.crossings=ut(m.lines),m.through=bt(m.lines,c,n);const{obstacles:W,groups:O}=Rt(s,r,o,b);W.heads=m.lines.map(w=>mt(w,a));const R=pe(n,m.lines,c,W,O,{l:0,t:0,r:y,b:i},a,e);return m.labels=R.labels,m.unseated=R.unseated,m}function*Tt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e<t.length;e++){const n=t.slice(0,e).concat(t.slice(e+1));for(const a of Tt(n))yield[t[e],...a]}}function bt(t,e,n){const a=[];for(const o of t){const s=it(o.pts);e.some(r=>s.some(([d,h])=>le(d,h,r)))&&a.push(o.i)}return a}function ye(t,e,n){const{m:a,tk:o,P:s,drawing:r,origin:d}=t,h=o.space,l=new Map;r.querySelectorAll(`.${s}-node`).forEach(f=>l.set(f.dataset.node,Q(f,d)));const c=r.querySelector(`.${s}-steps`),u=c?Q(c,d).b:e.h,p=f=>{const y=l.get(f);return y?n.x((y.l+y.r)/2,o.hair):0};for(const f of a.nodes){const y=l.get(f.id);y&&e.lifelines.push({x:p(f.id),y1:y.b,y2:u})}const M=f=>l.get(f.id);return r.querySelectorAll(`.${s}-msg`).forEach(f=>{const y=f.dataset.from,i=f.dataset.to,g=f.dataset.kind??"plain",b=ft(g,o),m=Q(f,d),x=n.y((m.t+m.b)/2,b),B=Number(f.querySelector(`.${s}-num`)?.textContent??0),v=p(y),_=p(i);let I;if(y===i){const O=f.dataset.self==="start"?-h("6"):h("6"),R=n.y(x-h("2"),b),w=n.y(x+h("2"),b);I=[{x:v,y:R},{x:n.x(v+O,b),y:R},{x:n.x(v+O,b),y:w},{x:v,y:w}]}else I=[{x:v,y:x},{x:_,y:x}];e.lines.push({i:B,from:y,to:i,kind:g,pts:I,tip:I[I.length-1],dir:yt(I),width:b});const j=f.querySelector(`.${s}-said`),F=f.querySelector(`.${s}-note`),G=a.byId.get(y),A=a.byId.get(i);if(!G||!A)return;const z=y===i?(()=>{const O=a.nodes[G.i+(f.dataset.self==="start"?-1:1)],R=O?p(O.id):f.dataset.self==="start"?0:e.w;return Math.abs(R-v)-h("6")-h("2-5")-h("2")})():Math.abs(_-v)-2*h("2");Math.max(j?j.getBoundingClientRect().width:0,F?F.getBoundingClientRect().width:0)>z+.5&&e.unseated.push(B)}),e}function Ht(t,e,n){const{m:a,tk:o,P:s,drawing:r,origin:d,warn:h}=t,l=o.space,c=Ot(a,r,d,s),u=[...c.values()],p=d.left-Math.floor(d.left),M=d.top-Math.floor(d.top),f=It(p,M),y=r.clientWidth,i=r.clientHeight,g={w:y,h:i,nodes:u,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],ox:p,oy:M},b={};if(a.type==="sequence"||a.type==="schema")return{geo:g,grow:b};const m=new Map;r.querySelectorAll(`.${s}-node`).forEach(A=>{const z=A.parentElement,W=Q(z,d),O=getComputedStyle(z);m.set(A.dataset.node,W.r-(parseFloat(O.paddingRight)||0)-(parseFloat(O.borderRightWidth)||0))});const x=a.nodes,B=A=>c.get(x[A].id),v=[],_=A=>ft(a.edges[A].kind,o);a.edges.forEach((A,z)=>{const W=n.routes[z],O=c.get(A.from),R=c.get(A.to),w=_(z);let C=[];const E=A.label,k=E?e(E,"label"):0,L=16,H=l("4");if(W==="down"||W==="up"){const V=Math.max(O.rect.l,R.rect.l),Z=Math.min(O.rect.r,R.rect.r),S=f.x((V+Z)/2,w);if(C=W==="down"?[Y(O,"bottom",S),Y(R,"top",S)]:[Y(O,"top",S),Y(R,"bottom",S)],E){let q=Math.min(C[0].y,C[1].y),T=Math.max(C[0].y,C[1].y);W==="down"?T-=o.head:q+=o.head;const U=[...r.querySelectorAll(`.${s}-group`)].map(X=>Q(X,d));let K=[[q,T]];for(const X of U)for(const ot of[X.t,X.b])K=K.flatMap(([J,nt])=>ot>J+1&&ot<nt-1?[[J,ot],[ot,nt]]:[[J,nt]]);const et=(X,ot)=>U.some(J=>(X+ot)/2>J.t&&(X+ot)/2<J.b&&S>J.l&&S<J.r);if(K.length>1){const X=K.filter(([J,nt])=>!et(J,nt));[q,T]=(X.length?X:K).reduce((J,nt)=>nt[1]-nt[0]>J[1]-J[0]?nt:J)}const st=(q+T)/2;v.push({k:z,box:{l:S-k/2-l("1"),r:S+k/2+l("1"),t:st-L/2,b:st+L/2},on:!0,card:W==="down"?A.to:A.from})}}else if(W==="trunk"||W==="rail"){const V=f.x(Math.max(O.rect.l,W==="rail"?R.rect.l:O.rect.l)+l(W==="trunk"?"8":"3"),w),Z=Y(O,"bottom",V);if(W==="rail"){if(C=[Z,Y(R,"top",V)],E){const S=R.rect.t-l("6");v.push({k:z,box:{l:V+l("2-5"),r:V+l("2-5")+k,t:S-L/2,b:S+L/2},on:!1,card:A.to})}}else{const S=f.x(R.rect.l+l("6"),w),q=f.y(R.rect.t-H,w);C=[Z,{x:V,y:q},{x:S,y:q},Y(R,"top",S)],E&&v.push({k:z,box:{l:S+l("2-5"),r:S+l("2-5")+k,t:q-L/2,b:q+L/2},on:!1,card:A.to})}}else{const V=Math.min(m.get(A.from)??y,m.get(A.to)??y),Z=f.x(n.gutter?V+(n.lanes[z]?2*l("3-5"):l("3-5")):V-l("2-5"),w),S=f.y(O.rect.t+(O.rect.b-O.rect.t)*n.exits[z],w),q=Y(O,"right",S),T=f.x(R.rect.r-l("6"),w),U=W==="end-down",K=f.y(U?R.rect.t-H:R.rect.b+H,w);C=[q,{x:Z,y:q.y},{x:Z,y:K},{x:T,y:K},Y(R,U?"top":"bottom",T)],E&&v.push({k:z,box:{l:T-l("2-5")-k,r:T-l("2-5"),t:K-L/2,b:K+L/2},on:!1,card:U?A.to:x[R.i+1]?.id??A.to})}const N=Ct(C,w,f);g.lines.push({i:z,from:A.from,to:A.to,kind:A.kind,pts:N,tip:N[N.length-1],dir:yt(N),width:w})}),g.crossings=ut(g.lines),g.through=bt(g.lines,u,a);const{obstacles:I,groups:j}=Rt(r,d,s,0);I.heads=g.lines.map(A=>mt(A,o));const F=[],G={l:0,t:0,r:y,b:i};for(const A of v){const z=g.lines.find(w=>w.i===A.k),W=At(A.box,l("1")),O=mt(z,o);(A.box.l<G.l-.5||A.box.r>G.r+.5||u.some(w=>qt(W,w))||F.some(w=>P(W,w))||I.heads.some(w=>w!==O&&P(W,w))||I.rects.some(w=>P(W,w))||g.lines.some(w=>w.i!==A.k&&it(w.pts).some(([C,E])=>P(W,jt(C,E,w.width)))))&&(b[A.card]=(b[A.card]??0)+1,g.unseated.push(A.k)),F.push(A.box),g.labels.push({i:A.k,text:a.edges[A.k].label,box:A.box,on:A.on})}return n.third&&h("three end lines overlap in the stacked drawing; two lanes is the most (use the drawn layout or reorder)"),{geo:g,grow:b}}function me(t,e){const n=s=>String(Math.round(s*100)/100);let a=`M${n(t[0].x)} ${n(t[0].y)}`;for(let s=1;s<t.length-1;s++){const r=t[s-1],d=t[s],h=t[s+1],l=Math.hypot(d.x-r.x,d.y-r.y),c=Math.hypot(h.x-d.x,h.y-d.y),u=Math.min(e,l/2,c/2);if(u<.5){a+=`L${n(d.x)} ${n(d.y)}`;continue}const p={x:d.x+(r.x-d.x)/l*u,y:d.y+(r.y-d.y)/l*u},M={x:d.x+(h.x-d.x)/c*u,y:d.y+(h.y-d.y)/c*u};a+=`L${n(p.x)} ${n(p.y)}Q${n(d.x)} ${n(d.y)} ${n(M.x)} ${n(M.y)}`}const o=t[t.length-1];return`${a}L${n(o.x)} ${n(o.y)}`}var be={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function $e(t,e,n,a,o){const s=be[e.dir],r=e.kind==="dashed",d=n.head,h=n.head/2,l=r?1:d-1,c=e.pts.map(m=>({...m})),u=c[c.length-1];u.x-=s.x*l,u.y-=s.y*l;const p=e.tip.x-s.x*d,M=e.tip.y-s.y*d,f=-s.y*h,y=s.x*h,i=m=>Math.round(m*100)/100,g=r?`<path class="${t}-tip" data-kind="${e.kind}" data-open="" d="M${i(p+f)} ${i(M+y)}L${i(e.tip.x)} ${i(e.tip.y)}L${i(p-f)} ${i(M-y)}"/>`:`<path class="${t}-tip" data-kind="${e.kind}" d="M${i(e.tip.x)} ${i(e.tip.y)}L${i(p+f)} ${i(M+y)}L${i(p-f)} ${i(M-y)}Z"/>`,b=e.dot?`<circle class="${t}-dot" cx="${i(e.dot.x)}" cy="${i(e.dot.y)}" r="${n.dot/2}"/>`:"";return`<g class="${t}-edge" data-edge="${e.i}" data-from="${tt(e.from)}" data-to="${tt(e.to)}"><path class="${t}-line" data-kind="${e.kind}" d="${me(c,o)}"${a?` mask="url(#${a})"`:""}/>${g}${b}</g>`}function Ft(t,e,n,a){const o=new Map,s=new Map;for(const d of e.crossings)s.has(d.under)||s.set(d.under,[]),s.get(d.under).push(d);let r="";for(const[d,h]of s){const l=`${a}-cut-${d}`;o.set(d,l);const c=h.map(u=>{const p=e.lines[u.top],M=e.lines[u.under],f=p.width/2+n.cut,y=M.width/2+1;return u.underVertical?`<rect x="${u.at.x-y}" y="${u.at.y-f}" width="${2*y}" height="${2*f}" fill="black"/>`:`<rect x="${u.at.x-f}" y="${u.at.y-y}" width="${2*f}" height="${2*y}" fill="black"/>`}).join("");r+=`<mask id="${l}" maskUnits="userSpaceOnUse" x="0" y="0" width="${e.w}" height="${e.h}"><rect x="0" y="0" width="${e.w}" height="${e.h}" fill="white"/>${c}</mask>`}return{defs:r,ids:o}}function zt(t,e,n,a){const{defs:o,ids:s}=Ft(t,e,n,a),r=e.lifelines.map(c=>`<path class="${t}-life" d="M${c.x} ${c.y1}V${c.y2}"/>`).join(""),d=e.lines.map((c,u)=>$e(t,c,n,s.get(u)??null,c.from===c.to?n.radiusXs:n.radius)).join(""),h=`<svg class="${t}-svg" width="${e.w}" height="${e.h}" viewBox="0 0 ${e.w} ${e.h}" focusable="false">${o?`<defs>${o}</defs>`:""}${r}<g class="${t}-edges">${d}</g></svg>`,l=e.labels.map(c=>`<span class="${t}-label" data-edge="${c.i}"${c.on?' data-on=""':""} style="left:${Math.round(c.box.l*100)/100}px;top:${Math.round(c.box.t*100)/100}px;width:${Math.round((c.box.r-c.box.l)*100)/100}px">${tt(c.text)}</span>`).join("");return h+l}function we(t,e,n,a,o,s,r){const d=t.querySelector(`.${n}-drawing`);if(!d)return{dyn:o,geo:null,ink:"",tokens:null};const h=re(t),l=ce(d,n),c=de(e,h,l),u=t.clientWidth,p=(()=>{const x=document.activeElement;return x&&d.contains(x)&&x.dataset.node?x.dataset.node:void 0})(),M=x=>rt(e,x)?{...x,stop:x.stop&&e.byId.has(x.stop)?x.stop:e.nodes[0]?.id,keep:void 0}:{...x,stop:x.stop??e.nodes[0]?.id,keep:p&&x.layout!=="drawn"?p:void 0},f=x=>{if(e.type!=="flowchart")return x;s({...x,heights:void 0});const B={};return d.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(v=>{const _=v.querySelector(`.${n}-words`);if(!_)return;const I=v.getBoundingClientRect(),j=_.getBoundingClientRect(),F={w:j.width+2*h.space("2-5"),h:j.height+2*h.space("2")},G=I.width/2,A=1-F.w/2/G,z=A>.05?F.h/2/A:F.h*10;B[v.dataset.node]=Math.max(h.space("16"),Math.ceil(I.width/5),Math.ceil(2*z))}),{...x,heights:B}},y=()=>({m:e,tk:h,P:n,drawing:d,origin:d.getBoundingClientRect(),warn:r});if(u>=c.least){let x=M({...o,layout:"drawn",grow:void 0,track:void 0});x=f(x),s(x);const B=ge(y(),l);if(!B.through.length&&!B.unseated.length)return B.crossings.length&&r(`${B.crossings.length} crossing${B.crossings.length===1?"":"s"} in the drawn layout: ${B.crossings.map(v=>`${lt(e,B.lines[v.top])} over ${lt(e,B.lines[v.under])}`).join("; ")}`),{dyn:x,geo:B,ink:zt(n,B,h,a),tokens:h};B.through.length&&r(`the drawn layout does not fit at ${Math.round(u)}px: ${B.through.map(v=>lt(e,B.lines.find(_=>_.i===v))).join(", ")} would pass through a node`),B.unseated.length&&r(`the drawn layout does not fit at ${Math.round(u)}px: no clean seat for ${B.unseated.map(v=>e.type==="sequence"?`message ${v}`:`"${e.edges[v]?.label}"`).join(", ")}`)}let i=M({...o,layout:"stacked",heights:void 0,grow:{},track:e.type==="schema"?c.table:void 0});if(i=f(i),s(i),e.type==="sequence"||e.type==="schema")return{dyn:i,geo:null,ink:"",tokens:h};const g=kt(e);let b=Ht(y(),l,g);for(let x=0;x<6&&Object.keys(b.grow).length;x++){const B={...i.grow??{}};for(const[v,_]of Object.entries(b.grow))B[v]=(B[v]??0)+_;i={...i,grow:B},s(i),b=Ht(y(),l,g)}const m=b.geo;return m.crossings.length&&r(`${m.crossings.length} crossing${m.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${m.crossings.map(x=>`${lt(e,m.lines[x.top])} over ${lt(e,m.lines[x.under])}`).join("; ")}`),m.through.length&&r(`in the stacked drawing ${m.through.map(x=>lt(e,m.lines.find(B=>B.i===x))).join(", ")} passes through a node`),{dyn:i,geo:m,ink:zt(n,m,h,a),tokens:h}}function lt(t,e){const n=t.byId.get(e.from)?.name??e.from,a=t.byId.get(e.to)?.name??e.to;return`${n} to ${a}`}function xe(t,e,n,a,o,s){const r=new Set;if(s){r.add(s);for(const y of n?.lines??[])y.from===s&&r.add(y.to),y.to===s&&r.add(y.from)}if(t.toggleAttribute("data-tracing",!!s),t.querySelectorAll(`.${e}-node`).forEach(y=>y.toggleAttribute("data-near",r.has(y.dataset.node))),!n||!a)return;const d=y=>!!s&&(y.from===s||y.to===s),h=t.querySelector(`.${e}-edges`),l=new Map;t.querySelectorAll(`.${e}-edge`).forEach(y=>l.set(y.getAttribute("data-edge"),y));for(const y of n.lines){const i=l.get(String(y.i));i&&(i.toggleAttribute("data-lit",d(y)),i.toggleAttribute("data-dim",!!s&&!d(y)))}if(t.querySelectorAll(`.${e}-label`).forEach(y=>{const i=n.lines.find(g=>String(g.i)===y.dataset.edge);y.toggleAttribute("data-lit",!!(i&&d(i)))}),h){for(const y of n.lines)if(d(y)){const i=l.get(String(y.i));i&&h.appendChild(i)}}const c=ut(n.lines,d),{defs:u,ids:p}=Ft(e,{...n,crossings:c},a,o),M=t.querySelector(`.${e}-svg`);if(!M)return;let f=M.querySelector("defs");!f&&u&&(f=document.createElementNS("http://www.w3.org/2000/svg","defs"),M.insertBefore(f,M.firstChild)),f&&(f.innerHTML=u),n.lines.forEach((y,i)=>{const g=l.get(String(y.i))?.querySelector(`.${e}-line`);if(!g)return;const b=p.get(i);b?g.setAttribute("mask",`url(#${b})`):g.removeAttribute("mask")})}function Me(t,e,n){const a=t.byId.get(e)?.i??0,o=t.nodes.length;let s;if(n==="ArrowRight"||n==="ArrowDown")s=a+1;else if(n==="ArrowLeft"||n==="ArrowUp")s=a-1;else if(n==="Home")s=0;else if(n==="End")s=o-1;else return null;return t.nodes[Math.max(0,Math.min(o-1,s))].id}var ve=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],ke=["--_track","--_h","--_gap"];function Wt(t,e){if(typeof e=="string"||"slot"in e)return;for(const o of ve)(!(o in e.a)||e.a[o]===void 0||e.a[o]===null||e.a[o]===!1)&&t.removeAttribute(o);for(const[o,s]of Object.entries(e.a)){if(o==="class")continue;if(o==="style"){const d=t.style,h=new Map(String(s??"").split(";").map(l=>{const c=l.indexOf(":");return[l.slice(0,c).trim(),l.slice(c+1).trim()]}).filter(([l])=>l));for(const[l,c]of h)d.getPropertyValue(l).trim()!==c&&d.setProperty(l,c);for(const l of ke)h.has(l)||d.removeProperty(l);continue}if(s==null||s===!1){t.removeAttribute(o);continue}const r=s===!0?"":String(s);t.getAttribute(o)!==r&&t.setAttribute(o,r)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class))return;const n=e.c.filter(o=>typeof o!="string"&&!("slot"in o)),a=[...t.children];e.c.some(o=>typeof o!="string"&&"slot"in o)||n.forEach((o,s)=>{const r=a[s];r&&r.tagName.toLowerCase()===o.t&&Wt(r,o)})}(function(t){"use strict";var e=t._,n="diagram",a=0;function o(l,c){return{prefix:n,base:l,hasSource:c.source!==void 0&&c.source!==null&&c.source!=="",hiddenClass:"visually-hidden"}}function s(l,c,u,p){var M=function(f){return'<kbd class="kbd">'+tt(f)+"</kbd>"};return{source:tt(String(c.source||"")),summary:tt(String(c.summary||"")),hint:ae(l).map(function(f){return"<span>"+f.keys.map(M).join(" ")+" "+tt(f.words)+"</span>"}).join(""),toggle:'<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="'+(p?"true":"false")+'" aria-controls="'+u+'-list"><span>'+(p?"Hide the list":"View as list")+"</span></button>"}}function r(l,c){var u=$t(l),p=Lt(u,{},o(c,l)),M=Mt(p,s(u,l,c,!1)),f=M.indexOf(">");return{open:M.slice(0,f+1),inner:M.slice(f+1,M.length-9),warnings:u.warnings}}function d(l,c){l.__diagram&&l.__diagram.stop();var u=(l.getAttribute("aria-labelledby")||"").replace(/-title$/,""),p=$t(c);if(!l.querySelector(":scope > .diagram-drawing")){for(;document.getElementById("dg"+ ++a+"-title"););u="dg"+a;var M=r(c,u),f=document.createElement("div");f.innerHTML=M.open+"</figure>";for(var y=f.firstChild,i=0;i<y.attributes.length;i++){var g=y.attributes[i];g.name==="class"?l.classList.add.apply(l.classList,g.value.split(" ")):g.name==="style"?l.style.cssText=g.value+";"+l.style.cssText:l.setAttribute(g.name,g.value)}l.querySelectorAll(":scope > :not(script[data-diagram])").forEach(function(S){S.remove()}),l.insertAdjacentHTML("beforeend",M.inner)}p.warnings.forEach(function(S){console.warn("Basalt diagram: "+S)});var b=o(u,c),m={},x=null,B=null,v=null,_={},I=function(S){_[S]||(_[S]=1,console.warn("Basalt diagram: "+S))},j=function(S){Wt(l,Lt(p,S,b))},F=l.querySelector(".diagram-ink"),G=l.querySelector(".diagram-toggle");function A(){xe(l,n,x&&x.geo,x&&x.tokens,u,B||v)}function z(){x=we(l,p,n,u,m,j,I),m=x.dyn,j(m),F&&(F.innerHTML=x.ink),A()}function W(S){m=S,j(m)}var O=function(S){var q=S&&S.closest?S.closest(".diagram-node"):null;return q&&l.contains(q)?q:null};function R(S){var q=O(S.target);if(!(!q||S.defaultPrevented)){if(S.key==="Escape"){(B||v)&&(S.preventDefault(),B=v=null,A());return}if(rt(p,m)){var T=Me(p,q.getAttribute("data-node"),S.key);if(T){S.preventDefault(),W(Object.assign({},m,{stop:T}));var U=l.querySelector('.diagram-node[data-node="'+CSS.escape(T)+'"]');U&&U.focus()}}}}function w(S){var q=O(S.target);if(q){var T=q.getAttribute("data-node");B=q.matches(":focus-visible")?T:null,rt(p,m)&&m.stop!==T&&W(Object.assign({},m,{stop:T})),A()}}function C(S){var q=O(S.target);q&&(O(S.relatedTarget)||(B=null),m.keep===q.getAttribute("data-node")&&W(Object.assign({},m,{keep:void 0})),A())}function E(S){if(!(S.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var q=O(S.target),T=q&&rt(p,m)?q.getAttribute("data-node"):null;T!==v&&(v=T,A())}}function k(){v&&(v=null,A())}function L(){var S=!m.open;W(Object.assign({},m,{open:S})),G.setAttribute("aria-expanded",String(S)),G.firstElementChild.textContent=S?"Hide the list":"View as list"}l.addEventListener("keydown",R),l.addEventListener("focusin",w),l.addEventListener("focusout",C),l.addEventListener("pointerover",E),l.addEventListener("pointerleave",k),G&&G.addEventListener("click",L),z();var H=l.clientWidth,N=0,V=!0,Z=new ResizeObserver(function(){Math.abs(l.clientWidth-H)<.5||(H=l.clientWidth,cancelAnimationFrame(N),N=requestAnimationFrame(z))});Z.observe(l),document.fonts&&document.fonts.ready.then(function(){V&&z()}),l.__diagram={stop:function(){V=!1,Z.disconnect(),cancelAnimationFrame(N),l.removeEventListener("keydown",R),l.removeEventListener("focusin",w),l.removeEventListener("focusout",C),l.removeEventListener("pointerover",E),l.removeEventListener("pointerleave",k),G&&G.removeEventListener("click",L)},layout:z}}function h(){document.querySelectorAll("figure.diagram").forEach(function(l){if(!l.__diagram){var c=l.querySelector(":scope > script[data-diagram]");if(c)try{d(l,JSON.parse(c.textContent))}catch(u){console.error("Basalt diagram: this figure could not be drawn",u)}}})}e.diagramMarkup=r,t.diagram=function(l,c){d(l,c)},e.step(62,"wireDiagrams",h)})(window.Basalt)})(); +(()=>{var Ut=["top","right","bottom","left"],Xt=["main","plain","dashed"],Jt=[2,3,4,5,6],tt=t=>t==null||t===""?void 0:String(t);function xt(t,e={}){const n=e.checks!==!1,o=[],a=c=>{o.push(c)},s=t.legend??{},r={};for(const c of["main","plain","dashed","focal","group"]){const p=tt(s[c]);p&&(r[c]=p)}const l=t.stepLabel,d=typeof l=="function"?c=>String(l(c)):typeof l=="string"?(c=>l.replace("{n}",String(c))):c=>`Step ${c}`,m=t.shapeLabels??{},h={terminal:tt(m.terminal)??"Start or end",step:tt(m.step)??"Step",decision:tt(m.decision)??"Decision"},i=t.heading===void 0?3:Jt.includes(t.heading)?t.heading:(a(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),f=(c,p)=>c==null?"plain":Xt.includes(c)?c:(a(`"${String(c)}" is not a kind of line (main, plain or dashed): ${p} is drawn plain`),"plain"),w=c=>{if(c!=null){if(Ut.includes(c))return c;a(`"${String(c)}" is not a side (top, right, bottom or left): the derived side is used`)}},y=(c,p)=>typeof c=="number"&&Number.isInteger(c)&&c>=1?c:(a(`${p} is ${JSON.stringify(c)}, not a whole number from 1: it is placed at 1`),1),u=[],g=[];let v=[];const T=[],E=[],M=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(M)||a(`"${String(M)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),M==="architecture"||M==="flowchart"){for(const c of t.nodes??[]){const p=M==="flowchart"&&c.shape==="decision"?"decision":M==="flowchart"&&c.shape==="terminal"?"terminal":"box",b=String(c.id??""),L=y(c.row,`the row of ${b}`);u.push({id:b,i:u.length,name:String(c.name??""),kind:p==="decision"?void 0:tt(c.kind),detail:p==="decision"?void 0:tt(c.detail),mono:!!c.detailMono,focal:!!c.focal,col:y(c.col,`the column of ${b}`),row:L,row2:L,branch:!!c.branch,shape:p,group:M==="architecture"?tt(c.group):void 0})}if(M==="architecture")for(const c of t.groups??[]){const p=String(c.id??"");T.push({id:p,label:String(c.label??""),members:u.filter(b=>b.group===p).map(b=>b.id)})}}else if(M==="data-flow"){v=(t.lanes??[]).map(p=>({id:String(p.id??""),label:String(p.label??"")}));const c=new Map(v.map((p,b)=>[p.id,b+1]));for(const p of t.nodes??[]){const b=String(p.id??""),L=String(p.lane??""),R=c.get(L);R===void 0&&a(`a node (${b}) names the lane "${L}", which is not in lanes`);const q=u.length+1;u.push({id:b,i:u.length,name:String(p.name??""),kind:d(q),detail:tt(p.detail),mono:!!p.detailMono,focal:!!p.focal,col:y(p.col,`the column of ${b}`),row:R??1,row2:R??1,branch:!1,shape:"box",lane:R??1,laneLabel:v[(R??1)-1]?.label??L,step:q})}}else if(M==="sequence"){(t.participants??[]).forEach((p,b)=>{const L=String(p.name??"");u.push({id:String(p.id??""),i:b,name:L,kind:tt(p.kind),mono:!1,focal:!!p.focal,col:b+1,row:1,row2:1,branch:!1,shape:"participant",short:tt(p.short)??L})});let c=0;for(const p of t.steps??[])"band"in p?E.push({band:String(p.band??"")}):(c++,E.push({n:c,from:String(p.from??""),to:String(p.to??""),label:String(p.label??""),note:tt(p.note),kind:f(p.kind,`message ${c}`)}))}else if(M==="schema")for(const c of t.tables??[]){const p=String(c.name??""),[b,L]=Array.isArray(c.row)?c.row:[c.row,c.row],R=y(b,`the row of ${p}`),q=Math.max(R,y(L,`the last row of ${p}`)),H=c.more===void 0||c.more===null?void 0:Number.isInteger(c.more)&&c.more>0?c.more:(a(`${p}'s "more" is ${JSON.stringify(c.more)}, not a whole number from 1: it is left out`),void 0);u.push({id:p,i:u.length,name:p,mono:!0,focal:!!c.focal,col:y(c.col,`the column of ${p}`),row:R,row2:q,branch:!1,shape:"table",more:H,columns:(c.columns??[]).map(O=>({name:String(O.name??""),type:tt(O.type),key:O.key==="PK"||O.key==="FK"?O.key:(O.key!==void 0&&O.key!==null&&a(`${p}.${String(O.name)}'s key is "${String(O.key)}", not PK or FK: it is left out`),void 0)}))})}const z=new Map;for(const c of u)c.id?z.has(c.id)&&a(`the id "${c.id}" is used twice`):a("a node has no id"),z.set(c.id,c);if(M==="schema")(t.tables??[]).forEach(c=>(c.columns??[]).forEach((p,b)=>{const L=tt(p.references);if(!L)return;const[R,q]=L.split("."),H=z.get(R??""),O=H?.columns?.findIndex(V=>V.name===q)??-1;if(!H||O<0){a(`${String(c.name)}.${String(p.name)} references ${L}, which is not a shown column`);return}const j=z.get(String(c.name??""));j.columns[b].ref={table:R,column:q,row:O},g.push({i:g.length,from:j.id,to:R,kind:"plain",fromRow:b,toRow:O,fk:!0})}));else if(M!=="sequence")for(const c of t.edges??[]){const p=String(c.from??""),b=String(c.to??"");if(!z.has(p)||!z.has(b)){a(`a line names ${z.has(p)?b:p}, which is not a node`);continue}const L=tt(c.label);L&&L.length>Mt&&a(`the label "${L}" is over ${Mt} characters: longer words belong in the node or the summary`),g.push({i:g.length,from:p,to:b,kind:f(c.kind,`the line from ${p} to ${b}`),label:L,fromSide:w(c.fromSide),toSide:w(c.toSide)})}else for(const c of E)"n"in c&&(!z.has(c.from)||!z.has(c.to))&&a(`message ${c.n} names ${z.has(c.from)?c.to:c.from}, which is not a participant`);if(n&&M!=="sequence"){const c=new Map;for(const p of u)for(let b=p.row;b<=p.row2;b++){const L=`${p.col}:${b}`;c.has(L)&&a(`${p.id} and ${c.get(L)} share the cell at column ${p.col}, row ${b}`),c.set(L,p.id)}}if(n){for(const p of T){const b=p.members.map(q=>z.get(q));if(!b.length)continue;const L={c1:Math.min(...b.map(q=>q.col)),c2:Math.max(...b.map(q=>q.col)),r1:Math.min(...b.map(q=>q.row)),r2:Math.max(...b.map(q=>q.row2))};for(const q of u)q.group!==p.id&&q.col>=L.c1&&q.col<=L.c2&&q.row>=L.r1&&q.row<=L.r2&&a(`${q.id} is inside the box of the group "${p.label}" but not a member`);const R=b.map(q=>q.i);Math.max(...R)-Math.min(...R)+1!==R.length&&a(`the members of the group "${p.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const p of u)p.group&&!T.some(b=>b.id===p.group)&&a(`${p.id} names the group "${p.group}", which is not in groups`);u.filter(p=>p.focal).length>1&&a("more than one node is focal: a diagram has one at most");const c=new Set(M==="sequence"?E.flatMap(p=>"n"in p?[p.kind]:[]):g.map(p=>p.kind));c.has("main")&&!r.main&&a("main lines are drawn but the legend has no words for them (legend.main)"),c.has("dashed")&&!r.dashed&&a("dashed lines are drawn but the legend has no words for them (legend.dashed)"),u.some(p=>p.focal)&&!r.focal&&a("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const $=Math.max(1,...u.map(c=>c.col)),A=M==="data-flow"?Math.max(1,v.length):Math.max(1,...u.map(c=>c.row2));return{type:M,title:String(t.title??""),heading:i,legend:r,nodes:u,byId:z,edges:g,groups:T,lanes:v,steps:E,cols:$,rows:A,shapeLabels:h,stepWord:d,warnings:o,memo:new Map}}function ht(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var Mt=28,it=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""},Yt=t=>t.charAt(0).toUpperCase()+t.slice(1);function vt(t,e){return t.legend[e]}function Qt(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function Pt(t,e){return ht(t,`sentence:${e.i}`,()=>te(t,e))}function te(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const o=(e.columns??[]).filter(s=>s.ref).map(s=>`${s.ref.table} (${s.name})`),a=t.edges.filter(s=>s.to===e.id).map(s=>`${s.from} (${t.byId.get(s.from).columns[s.fromRow].name})`);o.length&&n.push(`References ${o.join(", ")}.`),a.length&&n.push(`Referenced by ${a.join(", ")}.`)}else if(t.type==="sequence"){const o=t.steps.filter(s=>"n"in s&&s.from===e.id).length,a=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(it(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${o} ${o===1?"message":"messages"} and receives ${a}.`)}else{const o=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?Qt(t,e):e.kind;if(n.push(it(o?`${e.name}, ${o}`:e.name)),e.detail&&n.push(it(e.detail)),e.group){const r=t.groups.find(l=>l.id===e.group);r&&n.push(`In ${r.label}.`)}const a=t.edges.filter(r=>r.to===e.id).map(r=>`${t.byId.get(r.from).name}${r.label?` (${r.label})`:""}`),s=t.edges.filter(r=>r.from===e.id).map(r=>`${t.byId.get(r.to).name}${r.label?` (${r.label})`:""}`);a.length&&n.push(`From: ${a.join(", ")}.`),s.length&&n.push(`To: ${s.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(it(t.legend.focal)),n.join(" ")}function ee(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function x(t,e,...n){const o=[];for(const a of n.flat(1/0))a!=null&&a!==!1&&!Array.isArray(a)&&o.push(a);return{t,a:e??{},c:o}}var ne={"&":"&","<":"<",">":">",'"':""","'":"'"},st=t=>t.replace(/[&<>"']/g,e=>ne[e]),se=" br img input meta link hr path polygon polyline circle rect line ";function kt(t,e={}){if(typeof t=="string")return st(t);if("slot"in t)return e[t.slot]??"";if(!/^[a-z][a-z0-9]*$/.test(t.t))throw new Error(`diagram: "${t.t}" is not an element name`);let n="";for(const[o,a]of Object.entries(t.a))if(!(a==null||a===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(o))throw new Error(`diagram: "${o}" is not an attribute name`);n+=a===!0?` ${o}`:` ${o}="${st(String(a))}"`}return se.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(o=>kt(o,e)).join("")}</${t.t}>`}var oe=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function lt(t,e){return e.layout?e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema":!1}function ae(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function St(t){let e=0;for(const n of t.groups){const o=n.members.map(a=>t.byId.get(a).col);o.length&&(Math.min(...o)===1&&(e|=1),Math.max(...o)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function mt(t){return t.type==="sequence"?t.nodes.length:t.cols}function Et(t){return ht(t,"plan",()=>re(t))}function re(t){const e=t.nodes,n=u=>t.type==="data-flow"||!e[u].branch,o=t.edges.map(u=>{const g=t.byId.get(u.from).i,v=t.byId.get(u.to).i,E=e.slice(Math.min(g,v)+1,Math.max(g,v)).every(M=>!n(M.i));return v===g+1&&!(n(g)&&!n(v))?"down":v===g-1?"up":v>g&&n(g)&&!n(v)&&E?"trunk":v>g&&n(g)&&n(v)&&E?"rail":v>g?"end-down":"end-up"}),a=t.edges.map((u,g)=>({e:u,k:g})).filter(({k:u})=>o[u]==="end-down"||o[u]==="end-up"),s=u=>{const g=t.byId.get(u.from).i,v=t.byId.get(u.to).i;return[Math.min(g,v),Math.max(g,v)]},r=(u,g)=>{const[v,T]=s(u),[E,M]=s(g);return v<M&&E<T},l=a.every(({e:u})=>{const g=t.byId.get(u.from).i,[v,T]=s(u);return!n(g)&&e.slice(v+1,T).every(E=>!n(E.i))&&a.every(E=>E.e===u||!r(E.e,u))}),d=a.length>0&&(t.type==="data-flow"||!l),m=u=>{const[g,v]=s(u);return v-g},h=t.edges.map(()=>0);let i=!1;const f=[];for(const u of[...a].sort((g,v)=>m(g.e)-m(v.e)||g.k-v.k)){let g=0;for(const v of f)r(v.e,u.e)&&(g=Math.max(g,h[v.k]+1));h[u.k]=g,g>1&&(i=!0),f.push(u)}const w=t.edges.map(()=>.5);for(const u of e){const g=a.filter(({e:E})=>E.from===u.id);if(g.length<2)continue;const v=g.filter(({k:E})=>o[E]==="end-down").sort((E,M)=>m(M.e)-m(E.e)||E.k-M.k),T=g.filter(({k:E})=>o[E]==="end-up").sort((E,M)=>m(E.e)-m(M.e)||M.k-E.k);[...v,...T].forEach(({k:E},M,z)=>{w[E]=z.length===2?M===0?1/3:2/3:(M+1)/(z.length+1)})}const y={};for(let u=1;u<e.length;u++){const g=e[u],v=e[u-1];let T=0,E=t.type==="data-flow"?48:32,M=!1,z=!1;t.edges.forEach(($,A)=>{const c=o[A],p=t.byId.get($.from).i,b=t.byId.get($.to).i,L=b===u&&(c==="down"||c==="trunk"||c==="rail"||c==="end-down"),R=p===u&&b===u-1&&c==="up",q=b===u-1&&c==="end-up";L&&(c==="trunk"||c==="end-down")&&(M=!0),q&&(z=!0),(L||R||q)&&$.label&&(T++,E=Math.max(E,c==="trunk"?40:48))}),(T>1||M&&z)&&(E=64),y[g.id]=E}return{routes:o,gutter:d,lanes:h,exits:w,gaps:y,third:i}}var dt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function At(t,e){const n=e==="fk"?"plain":e,o=n==="main"?8:8.5,a=24,s=n==="dashed"?a-1:a-7;return x("svg",{class:`${t}-swatch`,"data-kind":n,...dt(24,16)},e==="fk"?x("circle",{class:`${t}-dot`,cx:3,cy:o,r:3}):null,x("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${o}H${s}`}),n==="dashed"?x("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${a-8} ${o-4}L${a} ${o}L${a-8} ${o+4}`}):x("path",{class:`${t}-tip`,"data-kind":n,d:`M${a} ${o}L${a-8} ${o-4}L${a-8} ${o+4}Z`}))}function ut(t,e){return e==="decision"?x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function ie(t,e){return ht(e,`key:${t}`,()=>le(t,e))}function le(t,e){const n=[],o=(s,r,l={})=>n.push(x("li",{class:`${t}-entry`,...l},s,x("span",null,r)));if(e.type==="flowchart"){const s=new Set(e.nodes.map(r=>r.shape));s.has("terminal")&&o(ut(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&o(ut(t,"box"),e.shapeLabels.step),s.has("decision")&&o(ut(t,"decision"),e.shapeLabels.decision)}const a=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind));for(const s of["main","plain","dashed"]){const r=e.legend[s];a.has(s)&&r&&o(At(t,s),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(o(At(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"}),n.push(x("li",{class:`${t}-entry`,"data-when":"stacked"},x("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},"→"),x("span",null,"A foreign key, written in the row")))),e.nodes.some(s=>s.focal)&&e.legend.focal&&o(ut(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&o(ut(t,"group"),e.legend.group),n.length?x("div",{class:`${t}-key`},x("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function ce(t,e){const n=e==="main"?6:6.5;return x("svg",{class:`${t}-arrow`,"data-kind":e,...dt(20,12)},x("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?x("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):x("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function de(t,e,n){if(n.shape==="decision")return[x("span",{class:`${t}-words`},x("span",{class:`${t}-name`},n.name))];const o=[];return e.type==="data-flow"?o.push(x("span",{class:`${t}-kind`},n.kind,x("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&o.push(x("span",{class:`${t}-kind`},n.kind)),o.push(x("span",{class:`${t}-name`},n.name)),n.detail&&o.push(x("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.detail)),o}function ue(t,e){return[x("span",{class:`${t}-th`},x("span",{class:`${t}-tname`},e.name)),x("span",{class:`${t}-rows`},(e.columns??[]).map((n,o)=>x("span",{class:`${t}-row`,"data-row":o,"data-key":n.key},x("span",{class:`${t}-keyseat`},n.key??""),x("span",{class:`${t}-cname`},n.name),n.ref?x("span",{class:`${t}-ctype`,"data-ref":""},`→ ${n.ref.table}`):n.type?x("span",{class:`${t}-ctype`},n.type):null))),e.more?x("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Lt=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function yt(t,e,n,o){const{P:a}=t,s=ae(e,o)||o.keep===n.id,r=lt(e,o),l=[`--_c:${n.col}`,`--_r:${n.row}`,`--_r2:${n.row2+1}`];e.type==="data-flow"&&l.push(`--_lc:${n.col+1}`),e.type==="sequence"&&l.push(`--_c2:${n.col+1}`);const d=t.plan;if(d&&n.i>0){const h=d.gaps[n.id]??32,i=o.grow?.[n.id]??0;l.push(`--_gap:${i?`calc(${Lt(h)} + var(--basalt-space-4) * ${i})`:Lt(h)}`)}o.heights?.[n.id]&&l.push(`--_h:${o.heights[n.id]}px`);const m=r?o.stop===n.id?0:-1:o.keep===n.id?-1:void 0;return x("div",{class:`${a}-node`,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-level":t.level,style:l.join(";"),role:s?"img":void 0,"aria-label":s?Pt(e,n):void 0,tabindex:m},n.shape==="decision"?x("svg",{class:`${a}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},x("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.shape==="table"?ue(a,n):de(a,e,n))}function fe(t,e,n){const{P:o}=t,a=[];if(e.type==="data-flow"&&a.push(...e.lanes.map((r,l)=>x("div",{class:`${o}-lane`,style:`--_r:${l+1}`,"aria-hidden":"true"},x("span",{class:`${o}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const l=r.members.map(f=>e.byId.get(f));if(!l.length)continue;const d=Math.min(...l.map(f=>f.col)),m=Math.max(...l.map(f=>f.col)),h=Math.min(...l.map(f=>f.row)),i=Math.max(...l.map(f=>f.row2));a.push(x("div",{class:`${o}-gbox`,"data-group":r.id,style:`--_c:${d};--_c2:${m+1};--_r:${h};--_r2:${i+1}`,"aria-hidden":"true"},x("span",{class:`${o}-glabel`},r.label)))}if(e.type==="sequence")return a.push(x("ul",{class:`${o}-cast`},e.nodes.map(r=>x("li",{class:`${o}-actor`},yt(t,e,r,n))))),a.push(he(t,e)),a;let s=0;for(;s<e.nodes.length;){const r=e.nodes[s],l=r.group?e.groups.find(m=>m.id===r.group):void 0;if(!l){a.push(yt(t,e,r,n)),s++;continue}const d=[];for(;s<e.nodes.length&&e.nodes[s].group===l.id;)d.push(e.nodes[s++]);a.push(x("div",{class:`${o}-group`,"data-group":l.id},x("span",{class:`${o}-glabel`,"aria-hidden":"true"},l.label),d.map(m=>yt(t,e,m,n))))}return a}function he(t,e){const{P:n}=t,o=[];let a=null;for(const s of e.steps){if("band"in s){a=null,o.push(x("p",{class:`${n}-band`},x("span",null,s.band)));continue}a||(a=x("ol",{class:`${n}-msgs`,start:s.n}),o.push(a));const r=e.byId.get(s.from),l=e.byId.get(s.to),d=r?.col??1,m=l?.col??1,h=d===m,i=h&&d===e.nodes.length,f=vt(e,s.kind);a.c.push(x("li",{class:`${n}-msg`,"data-kind":s.kind,"data-from":s.from,"data-to":s.to,"data-self":h?i?"start":"end":void 0,style:`--_a:${Math.min(d,m)};--_b:${Math.max(d,m)+1}`},x("span",{class:`${n}-said`},x("span",{class:`${n}-num`},String(s.n)),x("span",{class:`${n}-mlabel`},s.label)),x("span",{class:`${n}-route`},r?.short??s.from," ",ce(n,s.kind),x("span",{class:t.hidden}," to ")," ",l?.short??s.to,f?` · ${f}`:""),s.note?x("span",{class:`${n}-note`},s.note):null))}return x("div",{class:`${n}-steps`},o)}function pe(t,e){return ht(e,`list:${t}`,()=>ge(t,e))}function ge(t,e){const n=Math.min(6,e.heading+1),o=h=>x(`h${n}`,{class:`${t}-list-head`},h),a=h=>x("strong",null,h),s=h=>x("code",{class:`${t}-code`},h),r=h=>e.byId.get(h)?.name??h,l=h=>{const i=vt(e,h);return i?` (${i})`:""},d=h=>h.focal&&e.legend.focal?` ${it(e.legend.focal)}`:"";if(e.type==="architecture"){const h=w=>x("li",null,a(w.name),w.kind?`, ${w.kind}`:"",w.detail?[". ",w.mono?s(w.detail):w.detail,/[.!?]$/.test(w.detail)?"":"."]:/[.!?]$/.test(w.kind??w.name)?"":".",d(w)),i=[o("Parts")],f=e.nodes.filter(w=>!w.group);f.length&&i.push(x("ul",{class:`${t}-list-items`},f.map(h)));for(const w of e.groups)i.push(x("p",{class:`${t}-list-group`},w.label)),i.push(x("ul",{class:`${t}-list-items`},w.members.map(y=>h(e.byId.get(y)))));return i.push(o("Connections")),i.push(x("ol",{class:`${t}-list-items`},e.edges.map(w=>x("li",null,a(r(w.from))," to ",a(r(w.to)),w.label?[": ",s(w.label)]:"",`${l(w.kind)}.`)))),i}if(e.type==="flowchart"){const h=i=>(e.byId.get(i)?.i??0)+1;return[x("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const f=e.edges.filter(u=>u.from===i.id),w=i.shape==="decision"?"Decision":i.shape==="terminal"?f.length?"Start":"End":"Step",y=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return x("li",null,a(i.name),i.detail?[", ",i.mono?s(i.detail):i.detail]:"",`${y}${w}.`,d(i),f.length?x("ul",{class:`${t}-list-exits`},f.map(u=>x("li",null,u.label?`If ${u.label}: go to ${h(u.to)}, `:`Then: go to ${h(u.to)}, `,a(r(u.to)),l(u.kind)))):null)}))]}if(e.type==="data-flow")return[x("ol",{class:`${t}-list-items`},e.nodes.map(h=>{const i=e.edges.filter(f=>f.from===h.id);return x("li",null,`${h.laneLabel}: `,a(h.name),h.detail?[", ",h.mono?s(h.detail):h.detail]:"",".",d(h),i.length?[" Then ",...i.flatMap((f,w)=>[w?"; ":"",`to step ${e.byId.get(f.to).step}, `,a(r(f.to)),f.label?[": ",s(f.label)]:"",l(f.kind)]),"."]:"")}))];if(e.type==="sequence"){const h=[o("Participants"),x("ul",{class:`${t}-list-items`},e.nodes.map(f=>x("li",null,a(f.name),f.kind?`, ${f.kind}`:"",".",d(f))))];h.push(o("Messages"));let i=null;for(const f of e.steps){if("band"in f){i=null,h.push(x(`h${n}`,{class:`${t}-list-group`},f.band));continue}i||(i=x("ol",{class:`${t}-list-items`,start:f.n}),h.push(i)),i.c.push(x("li",null,s(f.label),": ",a(r(f.from))," to ",a(r(f.to)),`${l(f.kind)}.`,f.note?` ${it(Yt(f.note))}`:""))}return h}const m=[];for(const h of e.nodes)m.push(x("p",{class:`${t}-list-group`},s(h.name),d(h))),m.push(x("ul",{class:`${t}-list-items`},[...(h.columns??[]).map(i=>x("li",null,s(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",s(`${i.ref.table}.${i.ref.column}`)]:i.type?`, ${i.type}`:"")),...h.more?[x("li",null,`and ${h.more} more ${h.more===1?"column":"columns"}`)]:[]]));return m}function me(t){return`Arrow keys move to the next or the previous ${t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step"}, in the author's order; Home and End go to the ends; Escape clears the trace.`}function ye(t){return[{keys:["←","→"],words:ee(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}function qt(t,e,n){const o=n.prefix,a=oe(n.base),s=t.type==="sequence"||t.type==="schema"?null:Et(t),r={P:o,ids:a,level:n.level,plan:s,hidden:n.hiddenClass},l=e.layout==="drawn",d=lt(t,e),m=t.type==="sequence"||t.type==="schema"?l:!0,h=`h${t.heading}`,i=[`--_cols:${mt(t)}`];if(t.type==="architecture"&&t.groups.length){const f=t.groups.flatMap(y=>y.members.map(u=>t.byId.get(u))),w=(y,u)=>y?`var(--basalt-space-${u})`:"0px";i.push(`--_gpad:${w(f.some(y=>y.row===1),"8")} ${w(f.some(y=>y.col===t.cols),"4")} ${w(f.some(y=>y.row2===t.rows),"4")} ${w(f.some(y=>y.col===1),"4")}`)}return t.type==="schema"&&e.track&&i.push(`--_track:${e.track}px`),x("figure",{class:n.className?`${o} ${n.className}`:o,"aria-labelledby":a.title,"data-type":t.type,"data-cols":mt(t),"data-reach":t.type==="architecture"?St(t):void 0,"data-gutter":s?.gutter?"":void 0,"data-layout":e.layout,"data-measured":e.layout?"":void 0,style:i.join(";")},x("div",{class:`${o}-head`},x(h,{id:a.title,class:`${o}-title`},t.title),n.hasSource?x("p",{class:`${o}-source`},{slot:"source"}):null),x("div",{class:`${o}-drawing`,role:m?"group":void 0,"aria-roledescription":m?"diagram":void 0,"aria-labelledby":m?a.title:void 0,"aria-describedby":m?`${a.summary} ${a.keys}`:void 0,"data-stops":d?"":void 0},fe(r,t,e),x("div",{class:`${o}-ink`,"aria-hidden":"true"}),x("span",{class:`${o}-ruler`,"aria-hidden":"true"})),ie(o,t),x("p",{class:`${o}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),x("div",{class:`${o}-foot`},{slot:"toggle"}),x("div",{id:a.list,class:`${o}-list`,hidden:!e.open},pe(o,t)),x("span",{id:a.keys,class:n.hiddenClass},me(t)),x("figcaption",{id:a.summary,class:`${o}-summary`},{slot:"summary"}))}function $e(t){const e=getComputedStyle(t),n=(a,s)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${a}`));return Number.isFinite(r)?r:s},o=new Map;return{space:a=>(o.has(a)||o.set(a,n(`space-${a}`,parseFloat(a.replace("-","."))*4)),o.get(a)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4)}}var pt=(t,e)=>t==="main"?e.line:e.hair,ot=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},at=(t,e,n=.01)=>t.l<e.r-n&&t.r>e.l+n&&t.t<e.b-n&&t.b>e.t+n,It=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function P(t,e,n){const{l:o,t:a,r:s,b:r}=t.rect,l=(o+s)/2,d=(a+r)/2,m=(s-o)/2,h=(r-a)/2,i=e==="top"||e==="bottom";if(t.shape==="decision"){if(i){const y=n,u=h*Math.max(0,1-Math.abs(y-l)/m);return{x:y,y:e==="top"?d-u:d+u}}const f=n,w=m*Math.max(0,1-Math.abs(f-d)/h);return{x:e==="left"?l-w:l+w,y:f}}if(t.shape==="terminal"){const f=Math.min(m,h);if(i){const g=n,v=Math.min(Math.max(g,o+f),s-f),T=g-v,E=Math.abs(T)>=f?0:Math.sqrt(f*f-T*T);return{x:g,y:Math.abs(T)<1e-6?e==="top"?a:r:e==="top"?d-E:d+E}}const w=n,y=w-d,u=Math.abs(y)>=f?0:Math.sqrt(f*f-y*y);return{x:e==="left"?o+f-u:s-f+u,y:w}}return i?{x:n,y:e==="top"?a:r}:{x:e==="left"?o:s,y:n}}function be(t,e,n){const{l:o,t:a,r:s,b:r}=e.rect,l=(o+s)/2,d=(a+r)/2,m=(s-o)/2,h=(r-a)/2;if(e.shape==="decision")return Math.abs(t.x-l)/m+Math.abs(t.y-d)/h<1-n/Math.min(m,h);if(e.shape==="terminal"){const i=Math.min(m,h),f=Math.min(Math.max(t.x,o+i),s-i);return Math.hypot(t.x-f,t.y-d)<i-n}return t.x>o+n&&t.x<s-n&&t.y>a+n&&t.y<r-n}function Ot(t,e){if(!at(t,e.rect))return!1;if(e.shape!=="decision"&&e.shape!=="terminal")return!0;const{l:n,t:o,r:a,b:s}=e.rect,r=(n+a)/2,l=(o+s)/2,d=(a-n)/2,m=(s-o)/2;if(e.shape==="decision"){const i=Math.max(t.l,Math.min(r,t.r)),f=Math.max(t.t,Math.min(l,t.b));return Math.abs(i-r)/d+Math.abs(f-l)/m<1-1e-6}const h=Math.min(m,d);if(at(t,{l:n+h,r:a-h,t:o,b:s}))return!0;for(const i of[n+h,a-h]){const f=Math.max(t.l,Math.min(i,t.r)),w=Math.max(t.t,Math.min(l,t.b));if(Math.hypot(f-i,w-l)<h-.01)return!0}return!1}function we(t,e,n){const o=Math.hypot(e.x-t.x,e.y-t.y),a=Math.max(2,Math.ceil(o/2));for(let s=1;s<a;s++){const r=s/a;if(!(r*o<1.5||(1-r)*o<1.5)&&be({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r},n,1))return!0}return!1}function xe(t,e){const n=t.querySelector(`.${e}-ruler`),o=new Map;return(a,s)=>{const r=`${s}|${a}`;return o.has(r)||(n.setAttribute("data-f",s),n.textContent=a,o.set(r,n.getBoundingClientRect().width),n.textContent=""),o.get(r)}}var $t=t=>t?t.split(/\s+/).filter(Boolean):[];function Me(t,e,n){const o=e.space;let a=e.node,s=e.table;for(const d of t.nodes){if(d.shape==="table"){for(const f of d.columns??[]){const w=f.ref?`→ ${f.ref.table}`:f.type??"",y=o("6")+n(f.name,"mono")+(w?o("3")+n(w,"mono"):0)+2*o("3")+2*e.hair;s=Math.max(s,Math.ceil(y))}s=Math.max(s,Math.ceil(n(d.name,"table")+2*o("3")+2*e.hair));continue}const m=d.shape==="terminal"?2*o("5"):2*o("3");let h=0;for(const f of $t(d.name))h=Math.max(h,n(f,d.shape==="decision"?"name-500":"name"));if(t.type!=="data-flow")for(const f of $t(d.kind))h=Math.max(h,n(f,"mono"));for(const f of $t(d.detail))h=Math.max(h,n(f,d.mono?"mono":"sans"));const i=d.shape==="decision"?h/.62:h+m+2*e.hair;a=Math.max(a,Math.ceil(i))}const r=mt(t);let l;return t.type==="data-flow"?l=e.lane+r*(a+o("12")):t.type==="schema"?l=r*s+(r-1)*o("12"):t.type==="sequence"?l=r*a+(r-1)*o("5"):l=r*a+(r-1)*o("16")+St(t)*o("4"),{track:a,table:s,least:Math.max(e.wide,l)}}function _t(t,e){return{x:(n,o)=>o%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,o)=>o%2===1?Math.round(n+e-.5)+.5-e:Math.round(n+e)-e}}function bt(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ct(t,e,n){const o=t.map(s=>({...s}));for(let s=1;s<o.length;s++){const r=o[s-1],l=o[s];if(Math.abs(r.x-l.x)<.75){const d=n.x(r.x,e);r.x=d,l.x=d}else if(Math.abs(r.y-l.y)<.75){const d=n.y(r.y,e);r.y=d,l.y=d}}const a=[o[0]];for(let s=1;s<o.length;s++){const r=o[s],l=a[a.length-1];if(!(Math.abs(r.x-l.x)<.01&&Math.abs(r.y-l.y)<.01)){if(a.length>=2){const d=a[a.length-2];if(Math.abs(d.x-l.x)<.01&&Math.abs(l.x-r.x)<.01||Math.abs(d.y-l.y)<.01&&Math.abs(l.y-r.y)<.01){a[a.length-1]=r;continue}}a.push(r)}}return a}var ct=t=>t.slice(1).map((e,n)=>[t[n],e]);function gt(t,e,n){const o=[];for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++){const l=t[s],d=t[r];if(!(n&&!n.has(l.i)&&!n.has(d.i)))for(const[m,h]of ct(l.pts))for(const[i,f]of ct(d.pts)){const w=Math.abs(m.y-h.y)<.01,y=Math.abs(i.y-f.y)<.01;if(w===y)continue;const[u,g,v,T]=w?[m,h,i,f]:[i,f,m,h],E=v.x,M=u.y;if(E>Math.min(u.x,g.x)+.75&&E<Math.max(u.x,g.x)-.75&&M>Math.min(v.y,T.y)+.75&&M<Math.max(v.y,T.y)-.75){const z=w?s:r,$=w?r:s;let A=z,c=$;if(e){const p=e(t[z]);e(t[$])&&!p&&(A=$,c=z)}o.push({top:A,under:c,at:{x:E,y:M},underVertical:c===$})}}}return o}function ve(t){const e=getComputedStyle(t),n=a=>a.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),o=(a,s,r)=>{const l=[];let d=s;for(const m of a)l.push([d,d+m]),d+=m+r;return l};return{cols:o(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:o(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var Z=t=>t==="left"||t==="right",Bt={top:"bottom",bottom:"top",left:"right",right:"left"};function ke(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function Se(t,e,n){const o=[];t.edges.forEach((s,r)=>{const l=t.byId.get(s.from),d=t.byId.get(s.to),[m,h]=e[r],i=l.row===d.row&&Z(m)&&Z(h)&&m===Bt[h]||l.col===d.col&&!Z(m)&&!Z(h)&&m===Bt[h];o.push({edge:r,end:"from",node:l,side:m,far:d,straight:i,f:.5},{edge:r,end:"to",node:d,side:h,far:l,straight:i,f:.5})});const a=new Map;for(const s of o){const r=`${s.node.id}.${s.side}`;a.has(r)||a.set(r,[]),a.get(r).push(s)}for(const[s,r]of a){if(r[0].node.shape==="decision")continue;const l=i=>Z(i.side)?i.far.row-i.node.row:i.far.col-i.node.col,d=r.filter(i=>i.straight),m=r.filter(i=>!i.straight);m.sort((i,f)=>l(i)-l(f)||(Z(i.side)?i.far.col-f.far.col:i.far.row-f.far.row)*(l(i)<0?1:-1)),r.length>3&&n(`${s.replace("."," has ")} has ${r.length} lines on one side; more than three is an error: use another side`),d.length?m.forEach(i=>{i.f=l(i)<0?.25:.75}):m.length===2?(m[0].f=.25,m[1].f=.75):m.length===3?(m[0].f=.25,m[1].f=.5,m[2].f=.75):m.length>3&&m.forEach((i,f)=>{i.f=(f+1)/(m.length+1)});const h=new Map;for(const i of d)h.has(i.far.id)||h.set(i.far.id,[]),h.get(i.far.id).push(i);for(const i of h.values())i.length>1&&i.sort((f,w)=>f.edge-w.edge).forEach((f,w)=>{f.f=i.length===2?w===0?.25:.75:(w+1)/(i.length+1)})}return o}function Tt(t,e,n){const{l:o,t:a,r:s,b:r}=t.rect;return Z(e)?P(t,e,a+(r-a)*n):P(t,e,o+(s-o)*n)}function Rt(t,e,n,o){const a=new Map;return e.querySelectorAll(`.${o}-node`).forEach(s=>{const r=t.byId.get(s.dataset.node);r&&a.set(r.id,{id:r.id,rect:ot(s,n),shape:r.shape,i:r.i})}),a}function jt(t,e){const n=e.head,o=e.head/2,{x:a,y:s}=t.tip;return t.dir==="down"?{l:a-o,r:a+o,t:s-n,b:s}:t.dir==="up"?{l:a-o,r:a+o,t:s,b:s+n}:t.dir==="right"?{l:a-n,r:a,t:s-o,b:s+o}:{l:a,r:a+n,t:s-o,b:s+o}}var Ft=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function Ee(t,e,n,o,a,s,r,l){const d=r.space,m=[],h=[],i=[],f=d("1"),w=e.filter(y=>t.edges[y.i]?.label).sort((y,u)=>+(t.edges[u.i].kind==="main")-+(t.edges[y.i].kind==="main")||y.i-u.i);for(const y of w){const u=t.edges[y.i].label,g=l(u,"label"),v=16,T=y.pts.length-2,E=[];ct(y.pts).forEach(([$,A],c)=>{const p=Math.abs($.y-A.y)<.01,b=p?$.x:$.y;let L=p?A.x:A.y;const R=Math.sign(L-b)||1;c===T&&(L-=R*r.head);let q=[[b,L]];for(const O of a)for(const j of p?[O.l,O.r]:[O.t,O.b]){const V=p?$.y:$.x;(p?V>O.t&&V<O.b:V>O.l&&V<O.r)&&(q=q.flatMap(([S,C])=>j>Math.min(S,C)+1&&j<Math.max(S,C)-1?[[S,j],[j,C]]:[[S,C]]))}const H=(O,j)=>{const V=(O+j)/2,J=p?{x:V,y:$.y}:{x:$.x,y:V};return!a.some(S=>J.x>S.l&&J.x<S.r&&J.y>S.t&&J.y<S.b)};for(const[O,j]of q)E.push({horiz:p,c:p?$.y:$.x,p:O,q:j,len:Math.abs(j-O),pri:q.length>1&&H(O,j)?1:0})}),E.sort(($,A)=>A.pri-$.pri||A.len-$.len);let M=null;const z=$=>{const A=It($,f);return $.l<s.l||$.r>s.r||$.t<s.t||$.b>s.b||n.some(c=>Ot(A,c))||m.some(c=>at(A,c))||o.heads.some(c=>at(A,c))||o.rects.some(c=>at(A,c))?!1:!e.some(c=>c.i!==y.i&&ct(c.pts).some(([p,b])=>at(A,Ft(p,b,c.width))))};for(const $ of E){for(const A of[1/2,1/3,2/3]){const c=$.p+($.q-$.p)*A,p=[],b=d("2")+y.width/2;if($.horiz?($.len>=g+2*d("1")+d("3-5")&&p.push({box:{l:c-g/2-d("1"),r:c+g/2+d("1"),t:$.c-v/2,b:$.c+v/2},on:!0}),p.push({box:{l:c-g/2,r:c+g/2,t:$.c-b-v,b:$.c-b},on:!1}),p.push({box:{l:c-g/2,r:c+g/2,t:$.c+b,b:$.c+b+v},on:!1})):($.len>=v+d("3")&&p.push({box:{l:$.c-g/2-d("1"),r:$.c+g/2+d("1"),t:c-v/2,b:c+v/2},on:!0}),p.push({box:{l:$.c+b,r:$.c+b+g,t:c-v/2,b:c+v/2},on:!1}),p.push({box:{l:$.c-b-g,r:$.c-b,t:c-v/2,b:c+v/2},on:!1})),M=p.find(L=>z(L.box))??null,M)break}if(M)break}if(!M){i.push(y.i);continue}m.push(M.box),h.push({i:y.i,text:u,box:M.box,on:M.on})}return{labels:h,unseated:i}}function Ht(t,e,n,o){const a=[],s=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const l=ot(r,e);s.push(l),a.push({l:l.l,r:l.r,t:l.t,b:l.t+1},{l:l.l,r:l.r,t:l.b-1,b:l.b},{l:l.l,r:l.l+1,t:l.t,b:l.b},{l:l.r-1,r:l.r,t:l.t,b:l.b});const d=r.querySelector(`:scope > .${n}-glabel`);d&&d.getClientRects().length&&a.push(ot(d,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,l)=>{if(!r.getClientRects().length)return;const d=ot(r,e);l>0&&a.push({l:d.l,r:d.r,t:d.t-o/2-.5,b:d.t-o/2+.5});const m=r.querySelector(`.${n}-lane-name`);m&&a.push(ot(m,e))}),{obstacles:{rects:a,heads:[]},groups:s}}function Ae(t,e){const{m:n,tk:o,P:a,drawing:s,origin:r,warn:l}=t,d=o.space,m=Rt(n,s,r,a),h=[...m.values()],i=ve(s),f=r.left-Math.floor(r.left),w=r.top-Math.floor(r.top),y=_t(f,w),u=s.clientWidth,g=s.clientHeight,v=S=>n.type==="data-flow"?S.col+1:S.col,T=parseFloat(getComputedStyle(s).rowGap)||0,E={w:u,h:g,nodes:h,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:f,oy:w};if(n.type==="sequence")return Le(t,E,y);let M,z=[];n.type==="schema"?M=n.edges.map(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to);if(C.col===B.col){const k=C.col===n.cols?"left":"right";return[k,k]}return B.col>C.col?["right","left"]:["left","right"]}):(M=n.edges.map(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to),[k,_]=ke(C,B);return[S.fromSide??k,S.toSide??_]}),z=Se(n,M,l??(()=>{})));const $=(S,C)=>{const B=s.querySelector(`.${a}-node[data-node="${CSS.escape(S)}"] .${a}-row[data-row="${C}"]`);if(!B)return 0;const k=ot(B,r);return(k.t+k.b)/2},A=n.edges.map((S,C)=>{const[B,k]=M[C],_=m.get(S.from),N=m.get(S.to),D=pt(S.kind,o);if(S.fk){const I=y.y($(S.from,S.fromRow),D),G=y.y($(S.to,S.toRow),D);return{p1:{x:B==="right"?_.rect.r:_.rect.l,y:I},p2:{x:k==="right"?N.rect.r:N.rect.l,y:G}}}const Y=z.find(I=>I.edge===C&&I.end==="from").f,K=z.find(I=>I.edge===C&&I.end==="to").f;let F=Tt(_,B,Y),W=Tt(N,k,K);return Z(B)?F={...F,y:y.y(F.y,D)}:F={...F,x:y.x(F.x,D)},Z(k)?W={...W,y:y.y(W.y,D)}:W={...W,x:y.x(W.x,D)},Z(B)&&Z(k)&&Math.abs(F.y-W.y)<1.01&&(W={...W,y:F.y}),!Z(B)&&!Z(k)&&Math.abs(F.x-W.x)<1.01&&(W={...W,x:F.x}),F=Z(B)?P(_,B,F.y):P(_,B,F.x),W=Z(k)?P(N,k,W.y):P(N,k,W.x),{p1:F,p2:W}}),c=new Map;n.edges.forEach((S,C)=>{const[B,k]=M[C],{p1:_,p2:N}=A[C],D=n.byId.get(S.from),Y=n.byId.get(S.to);let K=null,F=null,W=!1;if(Z(B)&&Z(k)&&B!==k&&Math.abs(_.y-N.y)>.5){const U=v(Y),et=k==="left",X=i.cols[(et?U-1:U)-1],Q=i.cols[(et?U:U+1)-1];X&&Q&&(K=`c${et?U-1:U}`,F=[X[1],Q[0]],W=!0)}else if(!Z(B)&&!Z(k)&&B!==k&&Math.abs(_.x-N.x)>.5){const et=k==="top"?Y.row-1:Y.row2,X=i.rows[et-1],Q=i.rows[et];X&&Q&&(K=`r${et}`,F=[X[1],Q[0]],W=!1)}if(!K||!F)return;c.has(K)||c.set(K,{span:F,vertical:W,members:new Map});const I=`${S.to}.${k}.${Math.round(W?N.y:N.x)}`,G=c.get(K);G.members.has(I)||G.members.set(I,[]),G.members.get(I).push(C)});const p=new Map,b=S=>{const[C,B]=M[S],{p1:k,p2:_}=A[S];if(Z(C)&&Z(B)){if(C===B){const D=C==="right"?Math.max(k.x,_.x)+d("4"):Math.min(k.x,_.x)-d("4");return[k,{x:D,y:k.y},{x:D,y:_.y},_]}if(Math.abs(k.y-_.y)<=.5)return[k,{x:_.x,y:k.y}];const N=p.get(S)??(k.x+_.x)/2;return[k,{x:N,y:k.y},{x:N,y:_.y},_]}if(!Z(C)&&!Z(B)){if(C===B){const D=C==="bottom"?Math.max(k.y,_.y)+d("4"):Math.min(k.y,_.y)-d("4");return[k,{x:k.x,y:D},{x:_.x,y:D},_]}if(Math.abs(k.x-_.x)<=.5)return[k,{x:k.x,y:_.y}];const N=p.get(S)??(k.y+_.y)/2;return[k,{x:k.x,y:N},{x:_.x,y:N},_]}return Z(C)?[k,{x:_.x,y:k.y},_]:[k,{x:k.x,y:_.y},_]},L=S=>{const C=n.edges[S],B=pt(C.kind,o),k=Ct(b(S),B,y);return{i:S,from:C.from,to:C.to,kind:C.kind,pts:k,tip:k[k.length-1],dir:bt(k),dot:C.fk?k[0]:void 0,width:B}},R=()=>n.edges.map((S,C)=>L(C));let q=null;const H=S=>{q??(q=R());const C=q.map(B=>S.has(B.i)?L(B.i):B);return{lines:C,score:gt(C,void 0,S).length*1e3+wt(C.filter(B=>S.has(B.i)),h,n).length}},O=(S,C)=>{const B=S.flatMap(k=>{const{p1:_,p2:N}=A[k];return C?[_.y,N.y]:[_.x,N.x]});return[Math.min(...B),Math.max(...B)]};for(const[,S]of c){const C=[...S.members.values()].map(k=>({members:k,run:O(k,S.vertical)})).sort((k,_)=>k.run[0]-_.run[0]),B=[];for(const k of C){const _=B[B.length-1];_&&_.some(N=>N.run[0]<k.run[1]+d("8")&&k.run[0]<N.run[1]+d("8"))?_.push(k):B.push([k])}for(const k of B){const _=k.map(I=>I.members),N=_.length,D=(S.span[1]-S.span[0])/(N+1);D<d("3")&&l?.(`a gutter holds ${N} lanes side by side, closer than space-3`);const Y=new Set(_.flat());let K=_,F=1/0,W=null;for(const I of Nt(_)){I.forEach((U,et)=>U.forEach(X=>p.set(X,S.span[0]+D*(et+1))));const G=H(Y);G.score<F&&(F=G.score,K=I,W=G.lines)}K.forEach((I,G)=>I.forEach(U=>p.set(U,S.span[0]+D*(G+1)))),q=W}}E.lines=R(),n.type==="schema"&&(E.lines=E.lines.filter(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to);return Math.abs(C.col-B.col)>1?(l?.(`${S.from} to ${S.to} is two columns apart, so its line is not drawn; its row still writes the target`),!1):!0})),E.crossings=gt(E.lines),E.through=wt(E.lines,h,n),E.outside=zt(E.lines,u,g,o);const{obstacles:j,groups:V}=Ht(s,r,a,T);j.heads=E.lines.map(S=>jt(S,o));const J=Ee(n,E.lines,h,j,V,{l:0,t:0,r:u,b:g},o,e);return E.labels=J.labels,E.unseated=J.unseated,E}function*Nt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e<t.length;e++){const n=t.slice(0,e).concat(t.slice(e+1));for(const o of Nt(n))yield[t[e],...o]}}function zt(t,e,n,o){const a=[];for(const s of t)s.pts.some((r,l)=>{const d=l===s.pts.length-1?Math.max(s.width/2,o.head/2):s.width/2;return r.x-d<-.5||r.x+d>e+.5||r.y-d<-.5||r.y+d>n+.5})&&a.push(s.i);return a}function wt(t,e,n){const o=[];for(const a of t){const s=ct(a.pts);e.some(r=>s.some(([l,d])=>we(l,d,r)))&&o.push(a.i)}return o}function Le(t,e,n){const{m:o,tk:a,P:s,drawing:r,origin:l}=t,d=a.space,m=new Map;r.querySelectorAll(`.${s}-node`).forEach(y=>m.set(y.dataset.node,ot(y,l)));const h=r.querySelector(`.${s}-steps`),i=h?ot(h,l).b:e.h,f=y=>{const u=m.get(y);return u?n.x((u.l+u.r)/2,a.hair):0};for(const y of o.nodes){const u=m.get(y.id);u&&e.lifelines.push({x:f(y.id),y1:u.b,y2:i})}const w=y=>m.get(y.id);return r.querySelectorAll(`.${s}-msg`).forEach(y=>{const u=y.dataset.from,g=y.dataset.to,v=y.dataset.kind??"plain",T=pt(v,a),E=ot(y,l),M=n.y((E.t+E.b)/2,T),z=Number(y.querySelector(`.${s}-num`)?.textContent??0),$=f(u),A=f(g);let c;if(u===g){const O=y.dataset.self==="start"?-d("6"):d("6"),j=n.y(M-d("2"),T),V=n.y(M+d("2"),T);c=[{x:$,y:j},{x:n.x($+O,T),y:j},{x:n.x($+O,T),y:V},{x:$,y:V}]}else c=[{x:$,y:M},{x:A,y:M}];e.lines.push({i:z,from:u,to:g,kind:v,pts:c,tip:c[c.length-1],dir:bt(c),width:T});const p=y.querySelector(`.${s}-said`),b=y.querySelector(`.${s}-note`),L=o.byId.get(u),R=o.byId.get(g);if(!L||!R)return;const q=u===g?(()=>{const O=o.nodes[L.i+(y.dataset.self==="start"?-1:1)],j=O?f(O.id):y.dataset.self==="start"?0:e.w;return Math.abs(j-$)-d("6")-d("2-5")-d("2")})():Math.abs(A-$)-2*d("2");Math.max(p?p.getBoundingClientRect().width:0,b?b.getBoundingClientRect().width:0)>q+.5&&e.unseated.push(z)}),e}function Wt(t,e,n){const{m:o,tk:a,P:s,drawing:r,origin:l}=t,d=a.space,m=Rt(o,r,l,s),h=[...m.values()],i=l.left-Math.floor(l.left),f=l.top-Math.floor(l.top),w=_t(i,f),y=r.clientWidth,u=r.clientHeight,g={w:y,h:u,nodes:h,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:i,oy:f},v={};if(o.type==="sequence"||o.type==="schema")return{geo:g,grow:v};const T=new Map;r.querySelectorAll(`.${s}-node`).forEach(b=>{const L=b.parentElement,R=ot(L,l),q=getComputedStyle(L);T.set(b.dataset.node,R.r-(parseFloat(q.paddingRight)||0)-(parseFloat(q.borderRightWidth)||0))});const E=o.nodes,M=b=>m.get(E[b].id),z=[],$=b=>pt(o.edges[b].kind,a);o.edges.forEach((b,L)=>{const R=n.routes[L],q=m.get(b.from),H=m.get(b.to),O=$(L);let j=[];const V=b.label,J=V?e(V,"label"):0,S=16,C=d("4");if(R==="down"||R==="up"){const k=Math.max(q.rect.l,H.rect.l),_=Math.min(q.rect.r,H.rect.r),N=o.edges.map((F,W)=>({o:F,j:W})).filter(({o:F,j:W})=>(n.routes[W]==="down"||n.routes[W]==="up")&&(F.from===b.from&&F.to===b.to||F.from===b.to&&F.to===b.from)),D=N.findIndex(F=>F.j===L),Y=N.length<2?.5:N.length===2?D===0?.25:.75:(D+1)/(N.length+1),K=w.x(k+(_-k)*Y,O);if(j=R==="down"?[P(q,"bottom",K),P(H,"top",K)]:[P(q,"top",K),P(H,"bottom",K)],V){let F=Math.min(j[0].y,j[1].y),W=Math.max(j[0].y,j[1].y);R==="down"?W-=a.head:F+=a.head;const I=[...r.querySelectorAll(`.${s}-group`)].map(X=>ot(X,l));let G=[[F,W]];for(const X of I)for(const Q of[X.t,X.b])G=G.flatMap(([nt,rt])=>Q>nt+1&&Q<rt-1?[[nt,Q],[Q,rt]]:[[nt,rt]]);const U=(X,Q)=>I.some(nt=>(X+Q)/2>nt.t&&(X+Q)/2<nt.b&&K>nt.l&&K<nt.r);if(G.length>1){const X=G.filter(([nt,rt])=>!U(nt,rt));[F,W]=(X.length?X:G).reduce((nt,rt)=>rt[1]-rt[0]>nt[1]-nt[0]?rt:nt)}const et=[1/2,1/3,2/3].map(X=>{const Q=F+(W-F)*X;return{l:K-J/2-d("1"),r:K+J/2+d("1"),t:Q-S/2,b:Q+S/2}});z.push({k:L,cands:et,on:!0,card:R==="down"?b.to:b.from})}}else if(R==="trunk"||R==="rail"){const k=w.x(Math.max(q.rect.l,R==="rail"?H.rect.l:q.rect.l)+d(R==="trunk"?"8":"3"),O),_=P(q,"bottom",k);if(R==="rail"){if(j=[_,P(H,"top",k)],V){const N=H.rect.t-d("6");z.push({k:L,cands:[{l:k+d("2-5"),r:k+d("2-5")+J,t:N-S/2,b:N+S/2}],on:!1,card:b.to})}}else{const N=w.x(H.rect.l+d("6"),O),D=w.y(H.rect.t-C,O);j=[_,{x:k,y:D},{x:N,y:D},P(H,"top",N)],V&&z.push({k:L,cands:[{l:N+d("2-5"),r:N+d("2-5")+J,t:D-S/2,b:D+S/2}],on:!1,card:b.to})}}else{const k=Math.min(T.get(b.from)??y,T.get(b.to)??y),_=w.x(n.gutter?k+(n.lanes[L]?2*d("3-5"):d("3-5")):k-d("2-5"),O),N=w.y(q.rect.t+(q.rect.b-q.rect.t)*n.exits[L],O),D=P(q,"right",N),Y=w.x(H.rect.r-d("6"),O),K=R==="end-down",F=w.y(K?H.rect.t-C:H.rect.b+C,O);j=[D,{x:_,y:D.y},{x:_,y:F},{x:Y,y:F},P(H,K?"top":"bottom",Y)],V&&z.push({k:L,cands:[{l:Y-d("2-5")-J,r:Y-d("2-5"),t:F-S/2,b:F+S/2}],on:!1,card:K?b.to:E[H.i+1]?.id??b.to})}const B=Ct(j,O,w);g.lines.push({i:L,from:b.from,to:b.to,kind:b.kind,pts:B,tip:B[B.length-1],dir:bt(B),width:O})}),g.crossings=gt(g.lines),g.through=wt(g.lines,h,o),g.outside=zt(g.lines,y,u,a);const{obstacles:A}=Ht(r,l,s,0);A.heads=g.lines.map(b=>jt(b,a));const c=[],p={l:0,t:0,r:y,b:u};for(const b of z){const L=H=>{const O=It(H,d("1"));return H.l<p.l-.5||H.r>p.r+.5||H.t<p.t-.5||H.b>p.b+.5||h.some(j=>Ot(O,j))||c.some(j=>at(O,j))||A.heads.some(j=>at(O,j))||A.rects.some(j=>at(O,j))||g.lines.some(j=>j.i!==b.k&&ct(j.pts).some(([V,J])=>at(O,Ft(V,J,j.width))))},R=b.cands.find(H=>!L(H));R||(v[b.card]=(v[b.card]??0)+1,g.unseated.push(b.k));const q=R??b.cands[0];c.push(q),g.labels.push({i:b.k,text:o.edges[b.k].label,box:q,on:b.on})}return{geo:g,grow:v}}function qe(t,e){const n=s=>String(Math.round(s*100)/100);let o=`M${n(t[0].x)} ${n(t[0].y)}`;for(let s=1;s<t.length-1;s++){const r=t[s-1],l=t[s],d=t[s+1],m=Math.hypot(l.x-r.x,l.y-r.y),h=Math.hypot(d.x-l.x,d.y-l.y),i=Math.min(e,m/2,h/2);if(i<.5){o+=`L${n(l.x)} ${n(l.y)}`;continue}const f={x:l.x+(r.x-l.x)/m*i,y:l.y+(r.y-l.y)/m*i},w={x:l.x+(d.x-l.x)/h*i,y:l.y+(d.y-l.y)/h*i};o+=`L${n(f.x)} ${n(f.y)}Q${n(l.x)} ${n(l.y)} ${n(w.x)} ${n(w.y)}`}const a=t[t.length-1];return`${o}L${n(a.x)} ${n(a.y)}`}var Ie={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function Oe(t,e,n,o,a){const s=Ie[e.dir],r=e.kind==="dashed",l=n.head,d=n.head/2,m=r?1:l-1,h=e.pts.map(M=>({...M})),i=h[h.length-1];i.x-=s.x*m,i.y-=s.y*m;const f=e.tip.x-s.x*l,w=e.tip.y-s.y*l,y=-s.y*d,u=s.x*d,g=M=>Math.round(M*100)/100,v=st(e.kind),T=r?`<path class="${t}-tip" data-kind="${v}" data-open="" d="M${g(f+y)} ${g(w+u)}L${g(e.tip.x)} ${g(e.tip.y)}L${g(f-y)} ${g(w-u)}"/>`:`<path class="${t}-tip" data-kind="${v}" d="M${g(e.tip.x)} ${g(e.tip.y)}L${g(f+y)} ${g(w+u)}L${g(f-y)} ${g(w-u)}Z"/>`,E=e.dot?`<circle class="${t}-dot" cx="${g(e.dot.x)}" cy="${g(e.dot.y)}" r="${n.dot/2}"/>`:"";return`<g class="${t}-edge" data-edge="${e.i}" data-from="${st(e.from)}" data-to="${st(e.to)}"><path class="${t}-line" data-kind="${v}" d="${qe(h,a)}"${o?` mask="url(#${st(o)})"`:""}/>${T}${E}</g>`}function Gt(t,e,n,o){const a=new Map,s=new Map;for(const l of e.crossings)s.has(l.under)||s.set(l.under,[]),s.get(l.under).push(l);let r="";for(const[l,d]of s){const m=`${o}-cut-${l}`;a.set(l,m);const h=d.map(i=>{const f=e.lines[i.top],w=e.lines[i.under],y=f.width/2+n.cut,u=w.width/2+1;return i.underVertical?`<rect x="${i.at.x-u}" y="${i.at.y-y}" width="${2*u}" height="${2*y}" fill="black"/>`:`<rect x="${i.at.x-y}" y="${i.at.y-u}" width="${2*y}" height="${2*u}" fill="black"/>`}).join("");r+=`<mask id="${st(m)}" maskUnits="userSpaceOnUse" x="0" y="0" width="${e.w}" height="${e.h}"><rect x="0" y="0" width="${e.w}" height="${e.h}" fill="white"/>${h}</mask>`}return{defs:r,ids:a}}function Dt(t,e,n,o){const{defs:a,ids:s}=Gt(t,e,n,o),r=e.lifelines.map(h=>`<path class="${t}-life" d="M${h.x} ${h.y1}V${h.y2}"/>`).join(""),l=e.lines.map((h,i)=>Oe(t,h,n,s.get(i)??null,h.from===h.to?n.radiusXs:n.radius)).join(""),d=`<svg class="${t}-svg" width="${e.w}" height="${e.h}" viewBox="0 0 ${e.w} ${e.h}" focusable="false">${a?`<defs>${a}</defs>`:""}${r}<g class="${t}-edges">${l}</g></svg>`,m=e.labels.map(h=>`<span class="${t}-label" data-edge="${h.i}"${h.on?' data-on=""':""} style="left:${Math.round(h.box.l*100)/100}px;top:${Math.round(h.box.t*100)/100}px;width:${Math.round((h.box.r-h.box.l)*100)/100}px">${st(h.text)}</span>`).join("");return d+m}function _e(t,e,n,o,a,s,r){const l=t.querySelector(`.${n}-drawing`);if(!l)return{dyn:a,geo:null,ink:"",tokens:null};const d=$e(t),m=xe(l,n),h=Me(e,d,m),i=t.clientWidth,f=(()=>{const $=document.activeElement;return $&&l.contains($)&&$.dataset.node?$.dataset.node:void 0})(),w=$=>lt(e,$)?{...$,stop:$.stop&&e.byId.has($.stop)?$.stop:e.nodes[0]?.id,keep:void 0}:{...$,stop:$.stop??e.nodes[0]?.id,keep:f&&$.layout!=="drawn"?f:void 0},y=$=>{if(e.type!=="flowchart")return $;s({...$,heights:void 0});const A={};return l.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(c=>{const p=c.querySelector(`.${n}-words`);if(!p)return;const b=c.getBoundingClientRect(),L=p.getBoundingClientRect(),R={w:L.width+2*d.space("2-5"),h:L.height+2*d.space("2")},q=b.width/2,H=1-R.w/2/q,O=H>.05?R.h/2/H:R.h*10;A[c.dataset.node]=Math.max(d.space("16"),Math.ceil(b.width/5),Math.ceil(2*O))}),{...$,heights:A}},u=()=>({m:e,tk:d,P:n,drawing:l,origin:l.getBoundingClientRect(),warn:r}),g=($,A)=>A.map(c=>ft(e,$.lines.find(p=>p.i===c))).join(", ");if(i>=h.least){let $=w({...a,layout:"drawn",grow:void 0,track:void 0});$=y($),s($);const A=Ae(u(),m);if(!A.through.length&&!A.unseated.length&&!A.outside.length)return A.crossings.length&&r?.(`${A.crossings.length} crossing${A.crossings.length===1?"":"s"} in the drawn layout: ${A.crossings.map(c=>`${ft(e,A.lines[c.top])} over ${ft(e,A.lines[c.under])}`).join("; ")}`),{dyn:$,geo:A,ink:Dt(n,A,d,o),tokens:d};A.through.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${g(A,A.through)} would pass through a node`),A.outside.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${g(A,A.outside)} would leave the drawing`),A.unseated.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: no clean seat for ${A.unseated.map(c=>e.type==="sequence"?`message ${c}`:`"${e.edges[c]?.label}"`).join(", ")}`)}let v=w({...a,layout:"stacked",heights:void 0,grow:{},track:e.type==="schema"?h.table:void 0});if(v=y(v),s(v),e.type==="sequence"||e.type==="schema")return{dyn:v,geo:null,ink:"",tokens:d};const T=Et(e);let E=Wt(u(),m,T);for(let $=0;$<6&&Object.keys(E.grow).length;$++){const A={...v.grow??{}};for(const[c,p]of Object.entries(E.grow))A[c]=(A[c]??0)+p;v={...v,grow:A},s(v),E=Wt(u(),m,T)}const M=E.geo;if(M.unseated.length>0||M.through.length>0||M.outside.length>0||T.third){M.unseated.length&&r?.(`the stacked drawing has no clean seat for ${[...new Set(M.unseated)].map(A=>`"${e.edges[A]?.label}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),M.through.length&&r?.(`in the stacked drawing ${g(M,M.through)} would pass through a node, so its lines are not drawn`),M.outside.length&&r?.(`in the stacked drawing ${g(M,M.outside)} would leave the drawing, so its lines are not drawn`),T.third&&r?.("the stacked drawing would need a third end lane, so its lines are not drawn");const $={...M,lines:[],labels:[],crossings:[]};return{dyn:{...v,grow:{}},geo:$,ink:"",tokens:d}}return M.crossings.length&&r?.(`${M.crossings.length} crossing${M.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${M.crossings.map($=>`${ft(e,M.lines[$.top])} over ${ft(e,M.lines[$.under])}`).join("; ")}`),{dyn:v,geo:M,ink:Dt(n,M,d,o),tokens:d}}function ft(t,e){const n=t.byId.get(e.from)?.name??e.from,o=t.byId.get(e.to)?.name??e.to;return`${n} to ${o}`}function Ce(t,e,n,o,a,s){const r=new Set;if(s){r.add(s);for(const u of n?.lines??[])u.from===s&&r.add(u.to),u.to===s&&r.add(u.from)}if(t.toggleAttribute("data-tracing",!!s),t.querySelectorAll(`.${e}-node`).forEach(u=>u.toggleAttribute("data-near",r.has(u.dataset.node))),!n||!o)return;const l=u=>!!s&&(u.from===s||u.to===s),d=t.querySelector(`.${e}-edges`),m=new Map;t.querySelectorAll(`.${e}-edge`).forEach(u=>m.set(u.getAttribute("data-edge"),u));for(const u of n.lines){const g=m.get(String(u.i));g&&(g.toggleAttribute("data-lit",l(u)),g.toggleAttribute("data-dim",!!s&&!l(u)))}if(t.querySelectorAll(`.${e}-label`).forEach(u=>{const g=n.lines.find(v=>String(v.i)===u.dataset.edge);u.toggleAttribute("data-lit",!!(g&&l(g)))}),d){for(const u of n.lines)if(l(u)){const g=m.get(String(u.i));g&&d.appendChild(g)}}const h=gt(n.lines,l),{defs:i,ids:f}=Gt(e,{...n,crossings:h},o,a),w=t.querySelector(`.${e}-svg`);if(!w)return;let y=w.querySelector("defs");!y&&i&&(y=document.createElementNS("http://www.w3.org/2000/svg","defs"),w.insertBefore(y,w.firstChild)),y&&(y.innerHTML=i),n.lines.forEach((u,g)=>{const v=m.get(String(u.i))?.querySelector(`.${e}-line`);if(!v)return;const T=f.get(g);T?v.setAttribute("mask",`url(#${T})`):v.removeAttribute("mask")})}function Be(t,e,n){const o=t.byId.get(e)?.i??0,a=t.nodes.length;let s;if(n==="ArrowRight"||n==="ArrowDown")s=o+1;else if(n==="ArrowLeft"||n==="ArrowUp")s=o-1;else if(n==="Home")s=0;else if(n==="End")s=a-1;else return null;return t.nodes[Math.max(0,Math.min(a-1,s))].id}var Te=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],Kt=["data-layout","data-measured"],Re=["--_track","--_h","--_gap"],Vt=t=>t==null||t===!1;function je(t,e){if(t.tagName.toLowerCase()!==e.t)return!1;const n=typeof e.a.class=="string"?e.a.class.split(" ")[0]:"";return!n||t.classList.contains(n)}function Zt(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const o=n?Kt:Te;for(const r of o)Vt(e.a[r])&&t.removeAttribute(r);for(const[r,l]of Object.entries(e.a)){if(r==="class")continue;if(r==="style"){const m=t.style,h=new Map(String(l??"").split(";").map(i=>{const f=i.indexOf(":");return[i.slice(0,f).trim(),i.slice(f+1).trim()]}).filter(([i])=>i));for(const[i,f]of h)m.getPropertyValue(i).trim()!==f&&m.setProperty(i,f);for(const i of Re)h.has(i)||m.removeProperty(i);continue}if(n&&!Kt.includes(r))continue;if(Vt(l)){t.removeAttribute(r);continue}const d=l===!0?"":String(l);t.getAttribute(r)!==d&&t.setAttribute(r,d)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class)||e.c.some(r=>typeof r!="string"&&"slot"in r))return;const a=[...t.children];let s=0;for(const r of e.c)if(!(typeof r=="string"||"slot"in r)){for(let l=s;l<a.length;l++)if(je(a[l],r)){Zt(a[l],r,!1),s=l+1;break}}}function Fe(t,e,n,o){if(n===o)return;const a=s=>t.querySelector(`.${e}-node[data-node="${CSS.escape(s)}"]`);n&&a(n)?.setAttribute("tabindex","-1"),a(o)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",o=0;function a(i,f){return{prefix:n,base:i,hasSource:f.source!==void 0&&f.source!==null&&f.source!=="",hiddenClass:"visually-hidden"}}function s(i,f,w,y){var u=function(g){return'<kbd class="kbd">'+st(g)+"</kbd>"};return{source:st(String(f.source||"")),summary:st(String(f.summary||"")),hint:ye(i).map(function(g){return"<span>"+g.keys.map(u).join(" ")+" "+st(g.words)+"</span>"}).join(""),toggle:'<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="'+(y?"true":"false")+'" aria-controls="'+st(w)+'-list"><span>'+(y?"Hide the list":"View as list")+"</span></button>"}}function r(i,f){var w=xt(i),y=qt(w,{},a(f,i)),u=kt(y,s(w,i,f,!1)),g=u.indexOf(">");return{open:u.slice(0,g+1),inner:u.slice(g+1,u.length-9),warnings:w.warnings}}var l=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-layout","data-measured"],d=["--_cols","--_gpad","--_track"];function m(i,f,w){i.__diagram&&i.__diagram.stop();var y=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),u=xt(f);if(!w||!y||!i.querySelector(":scope > .diagram-drawing")){if(!y||!i.querySelector("#"+CSS.escape(y+"-title"))){for(;document.getElementById("dg"+ ++o+"-title"););y="dg"+o}var g=r(f,y),v=document.createElement("div");v.innerHTML=g.open+"</figure>";var T=v.firstChild;l.forEach(function(I){i.removeAttribute(I)}),d.forEach(function(I){i.style.removeProperty(I)});for(var E=0;E<T.attributes.length;E++){var M=T.attributes[E];M.name==="class"?i.classList.add.apply(i.classList,M.value.split(" ")):M.name==="style"?i.style.cssText=M.value+";"+i.style.cssText:i.setAttribute(M.name,M.value)}i.querySelectorAll(":scope > :not(script[data-diagram])").forEach(function(I){I.remove()}),i.insertAdjacentHTML("beforeend",g.inner)}u.warnings.forEach(function(I){console.warn("Basalt diagram: "+I)});var z=a(y,f),$={},A=null,c=null,p=null,b={},L=function(I){b[I]||(b[I]=1,console.warn("Basalt diagram: "+I))},R=function(I){Zt(i,qt(u,I,z))},q=i.querySelector(".diagram-ink"),H=i.querySelector(".diagram-toggle");function O(){Ce(i,n,A&&A.geo,A&&A.tokens,y,c||p)}function j(){A=_e(i,u,n,y,$,R,L),$=A.dyn,R($),q&&(q.innerHTML=A.ink),O()}function V(I){$=I,R($)}function J(I){var G=$.stop;$=Object.assign({},$,{stop:I}),Fe(i,n,G,I)}var S=function(I){var G=I&&I.closest?I.closest(".diagram-node"):null;return G&&i.contains(G)?G:null};function C(I){var G=S(I.target);if(!(!G||I.defaultPrevented)){if(I.key==="Escape"){(c||p)&&(I.preventDefault(),c=p=null,O());return}if(lt(u,$)){var U=Be(u,G.getAttribute("data-node"),I.key);if(U){I.preventDefault(),J(U);var et=i.querySelector('.diagram-node[data-node="'+CSS.escape(U)+'"]');et&&et.focus()}}}}function B(I){var G=S(I.target);if(G){var U=G.getAttribute("data-node");c=G.matches(":focus-visible")?U:null,lt(u,$)&&$.stop!==U&&J(U),O()}}function k(I){var G=S(I.target);G&&(S(I.relatedTarget)||(c=null),$.keep===G.getAttribute("data-node")&&V(Object.assign({},$,{keep:void 0})),O())}function _(I){if(!(I.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var G=S(I.target),U=G&<(u,$)?G.getAttribute("data-node"):null;U!==p&&(p=U,O())}}function N(){p&&(p=null,O())}function D(){var I=!$.open;V(Object.assign({},$,{open:I})),H.setAttribute("aria-expanded",String(I)),H.firstElementChild.textContent=I?"Hide the list":"View as list"}i.addEventListener("keydown",C),i.addEventListener("focusin",B),i.addEventListener("focusout",k),i.addEventListener("pointerover",_),i.addEventListener("pointerleave",N),H&&H.addEventListener("click",D),j();var Y=i.clientWidth,K=0,F=!0,W=new ResizeObserver(function(){Math.abs(i.clientWidth-Y)<.5||(Y=i.clientWidth,cancelAnimationFrame(K),K=requestAnimationFrame(j))});W.observe(i),document.fonts&&document.fonts.ready.then(function(){F&&j()}),i.__diagram={stop:function(){F=!1,W.disconnect(),cancelAnimationFrame(K),i.removeEventListener("keydown",C),i.removeEventListener("focusin",B),i.removeEventListener("focusout",k),i.removeEventListener("pointerover",_),i.removeEventListener("pointerleave",N),H&&H.removeEventListener("click",D)},layout:j}}function h(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var f=i.querySelector(":scope > script[data-diagram]");if(f)try{m(i,JSON.parse(f.textContent),!0)}catch(w){console.error("Basalt diagram: this figure could not be drawn",w)}}})}e.diagramMarkup=r,t.diagram=function(i,f){m(i,f)},e.step(62,"wireDiagrams",h)})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/manifest.json b/.agent/skills/basalt-html/parts/manifest.json index d4a9270b..13dc1eaa 100644 --- a/.agent/skills/basalt-html/parts/manifest.json +++ b/.agent/skills/basalt-html/parts/manifest.json @@ -775,7 +775,7 @@ "art", "kbd" ], - "budget": 82300, + "budget": 87200, "usage": 2600, "builds": [ "kbd" diff --git a/.agent/skills/basalt-html/parts/usage/diagram.md b/.agent/skills/basalt-html/parts/usage/diagram.md index 11cf33da..bae2985d 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram.md +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -6,7 +6,8 @@ { "type": "architecture", "title": "How a request reaches the agent", "source": "docs/architecture.md", "summary": "…", "legend": { "main": "Request path", "plain": "Call", "dashed": "Async or one-way", "focal": "The service" }, "groups": [{ "id": "aws", "label": "AWS · your account" }], - "nodes": [{ "id": "svc", "kind": "ECS service", "name": "api service", "detail": "N tasks", "detailMono": true, + "nodes": [{ "id": "alb", "kind": "Load balancer", "name": "ALB", "col": 2, "row": 2 }, + { "id": "svc", "kind": "ECS service", "name": "api service", "detail": "N tasks", "detailMono": true, "focal": true, "group": "aws", "col": 3, "row": 2 }], "edges": [{ "from": "alb", "to": "svc", "kind": "main", "label": "HTTP" }] } </script> diff --git a/packages/react/src/diagram-core.ts b/packages/react/src/diagram-core.ts index 1750f099..57dcc367 100644 --- a/packages/react/src/diagram-core.ts +++ b/packages/react/src/diagram-core.ts @@ -132,58 +132,106 @@ export interface Model { shapeLabels: Required<DiagramShapeLabels>; stepWord: (n: number) => string; warnings: string[]; + /** Work that depends on the model alone, done once (see `memo`). */ + memo: Map<string, unknown>; } const SIDES: DiagramSide[] = ["top", "right", "bottom", "left"]; +const LINE_KINDS: DiagramLineKind[] = ["main", "plain", "dashed"]; +const HEADINGS = [2, 3, 4, 5, 6]; -/** Reads the author's data into the model. A problem the decision calls a development error is collected in `warnings`. */ -export function buildModel(spec: DiagramSpec): Model { +/** Text from the author's data: always a string (or nothing), so a value that is not one can never be read as markup. */ +const txt = (v: unknown): string | undefined => (v === undefined || v === null || v === "" ? undefined : String(v)); + +export interface BuildOptions { + /** Run the checks a development build reports (placement, groups, the key's words). Off, the model is read the same and nothing is checked. */ + checks?: boolean; +} + +/** + * Reads the author's data into the model. A problem the decision calls a development error is collected in `warnings`. Every value that + * reaches markup is checked here, at the boundary: text is made a string, a heading level, a line's kind, a side and a key are one of their + * few values (or the default, with a warning), and a track is a whole number from 1. + */ +export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model { + const checks = options.checks !== false; const warnings: string[] = []; const warn = (message: string) => { warnings.push(message); }; - const legend = { ...(spec.legend ?? {}) }; - const stepWord = typeof spec.stepLabel === "function" ? spec.stepLabel : typeof spec.stepLabel === "string" ? ((n: number) => (spec.stepLabel as string).replace("{n}", String(n))) : (n: number) => `Step ${n}`; - const shapeLabels = { terminal: "Start or end", step: "Step", decision: "Decision", ...(spec.shapeLabels ?? {}) }; + const legendIn = (spec.legend ?? {}) as Record<string, unknown>; + const legend: DiagramLegend = {}; + for (const k of ["main", "plain", "dashed", "focal", "group"] as const) { const w = txt(legendIn[k]); if (w) legend[k] = w; } + const stepLabel = spec.stepLabel; + const stepWord = typeof stepLabel === "function" ? (n: number) => String(stepLabel(n)) : typeof stepLabel === "string" ? ((n: number) => stepLabel.replace("{n}", String(n))) : (n: number) => `Step ${n}`; + const shapeIn = (spec.shapeLabels ?? {}) as Record<string, unknown>; + const shapeLabels = { terminal: txt(shapeIn.terminal) ?? "Start or end", step: txt(shapeIn.step) ?? "Step", decision: txt(shapeIn.decision) ?? "Decision" }; + const heading = spec.heading === undefined ? 3 : HEADINGS.includes(spec.heading as number) ? spec.heading : (warn(`heading ${String(spec.heading)} is not a level from 2 to 6: the title is an h3`), 3); + const kindOf = (k: unknown, where: string): DiagramLineKind => { + if (k === undefined || k === null) return "plain"; + if (LINE_KINDS.includes(k as DiagramLineKind)) return k as DiagramLineKind; + warn(`"${String(k)}" is not a kind of line (main, plain or dashed): ${where} is drawn plain`); + return "plain"; + }; + const sideOf = (v: unknown): DiagramSide | undefined => { + if (v === undefined || v === null) return undefined; + if (SIDES.includes(v as DiagramSide)) return v as DiagramSide; + warn(`"${String(v)}" is not a side (top, right, bottom or left): the derived side is used`); + return undefined; + }; + const trackOf = (v: unknown, what: string): number => { + if (typeof v === "number" && Number.isInteger(v) && v >= 1) return v; + warn(`${what} is ${JSON.stringify(v)}, not a whole number from 1: it is placed at 1`); + return 1; + }; const nodes: MNode[] = []; const edges: MEdge[] = []; let lanes: DataFlowLane[] = []; const groups: Model["groups"] = []; const steps: MStep[] = []; const type = spec.type; + if (!(["architecture", "flowchart", "data-flow", "sequence", "schema"] as unknown[]).includes(type)) warn(`"${String(type)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`); if (type === "architecture" || type === "flowchart") { for (const raw of (spec.nodes ?? []) as Array<ArchitectureNode & FlowchartNode>) { const shape: Shape = type === "flowchart" && raw.shape === "decision" ? "decision" : type === "flowchart" && raw.shape === "terminal" ? "terminal" : "box"; + const id = String(raw.id ?? ""); + const row = trackOf(raw.row, `the row of ${id}`); nodes.push({ - id: raw.id, i: nodes.length, name: raw.name, kind: shape === "decision" ? undefined : raw.kind, detail: shape === "decision" ? undefined : raw.detail, mono: Boolean(raw.detailMono), - focal: Boolean(raw.focal), col: raw.col, row: raw.row, row2: raw.row, branch: Boolean(raw.branch), shape, group: type === "architecture" ? raw.group : undefined, + id, i: nodes.length, name: String(raw.name ?? ""), kind: shape === "decision" ? undefined : txt(raw.kind), detail: shape === "decision" ? undefined : txt(raw.detail), mono: Boolean(raw.detailMono), + focal: Boolean(raw.focal), col: trackOf(raw.col, `the column of ${id}`), row, row2: row, branch: Boolean(raw.branch), shape, group: type === "architecture" ? txt(raw.group) : undefined, }); } - if (type === "architecture") for (const g of spec.groups ?? []) groups.push({ ...g, members: nodes.filter((n) => n.group === g.id).map((n) => n.id) }); + if (type === "architecture") for (const g of spec.groups ?? []) { const gid = String(g.id ?? ""); groups.push({ id: gid, label: String(g.label ?? ""), members: nodes.filter((n) => n.group === gid).map((n) => n.id) }); } } else if (type === "data-flow") { - lanes = spec.lanes ?? []; + lanes = (spec.lanes ?? []).map((l) => ({ id: String(l.id ?? ""), label: String(l.label ?? "") })); const laneIndex = new Map(lanes.map((l, k) => [l.id, k + 1])); for (const raw of (spec.nodes ?? []) as DataFlowNode[]) { - const lane = laneIndex.get(raw.lane); - if (lane === undefined) warn(`a node (${raw.id}) names the lane "${raw.lane}", which is not in lanes`); + const id = String(raw.id ?? ""); + const laneId = String(raw.lane ?? ""); + const lane = laneIndex.get(laneId); + if (lane === undefined) warn(`a node (${id}) names the lane "${laneId}", which is not in lanes`); const n = nodes.length + 1; nodes.push({ - id: raw.id, i: nodes.length, name: raw.name, kind: stepWord(n), detail: raw.detail, mono: Boolean(raw.detailMono), focal: Boolean(raw.focal), - col: raw.col, row: lane ?? 1, row2: lane ?? 1, branch: false, shape: "box", lane: lane ?? 1, laneLabel: lanes[(lane ?? 1) - 1]?.label ?? raw.lane, step: n, + id, i: nodes.length, name: String(raw.name ?? ""), kind: stepWord(n), detail: txt(raw.detail), mono: Boolean(raw.detailMono), focal: Boolean(raw.focal), + col: trackOf(raw.col, `the column of ${id}`), row: lane ?? 1, row2: lane ?? 1, branch: false, shape: "box", lane: lane ?? 1, laneLabel: lanes[(lane ?? 1) - 1]?.label ?? laneId, step: n, }); } } else if (type === "sequence") { - (spec.participants ?? []).forEach((p, k) => nodes.push({ id: p.id, i: k, name: p.name, kind: p.kind, mono: false, focal: Boolean(p.focal), col: k + 1, row: 1, row2: 1, branch: false, shape: "participant", short: p.short ?? p.name })); + (spec.participants ?? []).forEach((p, k) => { const name = String(p.name ?? ""); nodes.push({ id: String(p.id ?? ""), i: k, name, kind: txt(p.kind), mono: false, focal: Boolean(p.focal), col: k + 1, row: 1, row2: 1, branch: false, shape: "participant", short: txt(p.short) ?? name }); }); let n = 0; for (const s of spec.steps ?? []) { - if ("band" in s) steps.push({ band: s.band }); - else steps.push({ n: ++n, from: s.from, to: s.to, label: s.label, note: s.note, kind: s.kind ?? "plain" }); + if ("band" in s) steps.push({ band: String(s.band ?? "") }); + else { n++; steps.push({ n, from: String(s.from ?? ""), to: String(s.to ?? ""), label: String(s.label ?? ""), note: txt(s.note), kind: kindOf(s.kind, `message ${n}`) }); } } } else if (type === "schema") { for (const t of spec.tables ?? []) { + const name = String(t.name ?? ""); const [r1, r2] = Array.isArray(t.row) ? t.row : [t.row, t.row]; + const row = trackOf(r1, `the row of ${name}`); + const row2 = Math.max(row, trackOf(r2, `the last row of ${name}`)); + const more = t.more === undefined || t.more === null ? undefined : Number.isInteger(t.more) && t.more > 0 ? t.more : (warn(`${name}'s "more" is ${JSON.stringify(t.more)}, not a whole number from 1: it is left out`), undefined); nodes.push({ - id: t.name, i: nodes.length, name: t.name, mono: true, focal: Boolean(t.focal), col: t.col, row: r1, row2: r2, branch: false, shape: "table", more: t.more, - columns: t.columns.map((c) => ({ name: c.name, type: c.type, key: c.key })), + id: name, i: nodes.length, name, mono: true, focal: Boolean(t.focal), col: trackOf(t.col, `the column of ${name}`), row, row2, branch: false, shape: "table", more, + columns: (t.columns ?? []).map((c) => ({ name: String(c.name ?? ""), type: txt(c.type), key: c.key === "PK" || c.key === "FK" ? c.key : (c.key !== undefined && c.key !== null && warn(`${name}.${String(c.name)}'s key is "${String(c.key)}", not PK or FK: it is left out`), undefined) })), }); } } @@ -197,22 +245,24 @@ export function buildModel(spec: DiagramSpec): Model { // Schema: a foreign key is one record, `references` on the column; its line, its row's words, the sentence and the list all come from it. if (type === "schema") { - (spec.tables ?? []).forEach((t) => t.columns.forEach((c, k) => { - if (!c.references) return; - const [table, column] = c.references.split("."); + (spec.tables ?? []).forEach((t) => (t.columns ?? []).forEach((c, k) => { + const ref = txt(c.references); + if (!ref) return; + const [table, column] = ref.split("."); const target = byId.get(table ?? ""); const row = target?.columns?.findIndex((x) => x.name === column) ?? -1; - if (!target || row < 0) { warn(`${t.name}.${c.name} references ${c.references}, which is not a shown column`); return; } - const source = byId.get(t.name)!; + if (!target || row < 0) { warn(`${String(t.name)}.${String(c.name)} references ${ref}, which is not a shown column`); return; } + const source = byId.get(String(t.name ?? ""))!; source.columns![k]!.ref = { table: table!, column: column!, row }; - edges.push({ i: edges.length, from: t.name, to: table!, kind: "plain", fromRow: k, toRow: row, fk: true }); + edges.push({ i: edges.length, from: source.id, to: table!, kind: "plain", fromRow: k, toRow: row, fk: true }); })); } else if (type !== "sequence") { for (const e of spec.edges ?? []) { - if (!byId.has(e.from) || !byId.has(e.to)) { warn(`a line names ${!byId.has(e.from) ? e.from : e.to}, which is not a node`); continue; } - if (e.label && e.label.length > MAX_LABEL) warn(`the label "${e.label}" is over ${MAX_LABEL} characters: longer words belong in the node or the summary`); - for (const side of [e.fromSide, e.toSide]) if (side && !SIDES.includes(side)) warn(`"${side}" is not a side (top, right, bottom or left)`); - edges.push({ i: edges.length, from: e.from, to: e.to, kind: e.kind ?? "plain", label: e.label || undefined, fromSide: e.fromSide, toSide: e.toSide }); + const from = String(e.from ?? ""), to = String(e.to ?? ""); + if (!byId.has(from) || !byId.has(to)) { warn(`a line names ${!byId.has(from) ? from : to}, which is not a node`); continue; } + const label = txt(e.label); + if (label && label.length > MAX_LABEL) warn(`the label "${label}" is over ${MAX_LABEL} characters: longer words belong in the node or the summary`); + edges.push({ i: edges.length, from, to, kind: kindOf(e.kind, `the line from ${from} to ${to}`), label, fromSide: sideOf(e.fromSide), toSide: sideOf(e.toSide) }); } } else { for (const s of steps) if ("n" in s) { @@ -220,8 +270,8 @@ export function buildModel(spec: DiagramSpec): Model { } } - // Placement checks: two nodes in one cell, a non-member inside a group's box, more than one focal node. - if (type !== "sequence") { + // Placement checks (development only): two nodes in one cell, a non-member inside a group's box, more than one focal node. + if (checks && type !== "sequence") { const cells = new Map<string, string>(); for (const n of nodes) for (let r = n.row; r <= n.row2; r++) { const key = `${n.col}:${r}`; @@ -229,26 +279,33 @@ export function buildModel(spec: DiagramSpec): Model { cells.set(key, n.id); } } - for (const g of groups) { - const m = g.members.map((id) => byId.get(id)!); - if (!m.length) continue; - const box = { c1: Math.min(...m.map((n) => n.col)), c2: Math.max(...m.map((n) => n.col)), r1: Math.min(...m.map((n) => n.row)), r2: Math.max(...m.map((n) => n.row2)) }; - for (const n of nodes) if (n.group !== g.id && n.col >= box.c1 && n.col <= box.c2 && n.row >= box.r1 && n.row <= box.r2) warn(`${n.id} is inside the box of the group "${g.label}" but not a member`); - const idx = m.map((n) => n.i); - if (Math.max(...idx) - Math.min(...idx) + 1 !== idx.length) warn(`the members of the group "${g.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`); + if (checks) { + for (const g of groups) { + const m = g.members.map((id) => byId.get(id)!); + if (!m.length) continue; + const box = { c1: Math.min(...m.map((n) => n.col)), c2: Math.max(...m.map((n) => n.col)), r1: Math.min(...m.map((n) => n.row)), r2: Math.max(...m.map((n) => n.row2)) }; + for (const n of nodes) if (n.group !== g.id && n.col >= box.c1 && n.col <= box.c2 && n.row >= box.r1 && n.row <= box.r2) warn(`${n.id} is inside the box of the group "${g.label}" but not a member`); + const idx = m.map((n) => n.i); + if (Math.max(...idx) - Math.min(...idx) + 1 !== idx.length) warn(`the members of the group "${g.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`); + } + for (const n of nodes) if (n.group && !groups.some((g) => g.id === n.group)) warn(`${n.id} names the group "${n.group}", which is not in groups`); + if (nodes.filter((n) => n.focal).length > 1) warn("more than one node is focal: a diagram has one at most"); + // The key's words: main, dashed and the focal node must have them when drawn. + const kinds = new Set<DiagramLineKind>(type === "sequence" ? steps.flatMap((s) => ("n" in s ? [s.kind] : [])) : edges.map((e) => e.kind)); + if (kinds.has("main") && !legend.main) warn("main lines are drawn but the legend has no words for them (legend.main)"); + if (kinds.has("dashed") && !legend.dashed) warn("dashed lines are drawn but the legend has no words for them (legend.dashed)"); + if (nodes.some((n) => n.focal) && !legend.focal) warn("a focal node is drawn but the legend has no words for what it marks (legend.focal)"); } - for (const n of nodes) if (n.group && !groups.some((g) => g.id === n.group)) warn(`${n.id} names the group "${n.group}", which is not in groups`); - if (nodes.filter((n) => n.focal).length > 1) warn("more than one node is focal: a diagram has one at most"); - - // The key's words: main, dashed and the focal node must have them when drawn. - const kinds = new Set<DiagramLineKind>(type === "sequence" ? steps.flatMap((s) => ("n" in s ? [s.kind] : [])) : edges.map((e) => e.kind)); - if (kinds.has("main") && !legend.main) warn("main lines are drawn but the legend has no words for them (legend.main)"); - if (kinds.has("dashed") && !legend.dashed) warn("dashed lines are drawn but the legend has no words for them (legend.dashed)"); - if (nodes.some((n) => n.focal) && !legend.focal) warn("a focal node is drawn but the legend has no words for what it marks (legend.focal)"); const cols = Math.max(1, ...nodes.map((n) => n.col)); const rows = type === "data-flow" ? Math.max(1, lanes.length) : Math.max(1, ...nodes.map((n) => n.row2)); - return { type, title: spec.title, heading: spec.heading ?? 3, legend, nodes, byId, edges, groups, lanes, steps, cols, rows, shapeLabels, stepWord, warnings }; + return { type, title: String(spec.title ?? ""), heading: heading as Model["heading"], legend, nodes, byId, edges, groups, lanes, steps, cols, rows, shapeLabels, stepWord, warnings, memo: new Map() }; +} + +/** A value worked out once a model (the stack's plan, the sentences, the key and the list), kept on the model so a state change does not redo it. */ +function memo<T>(m: Model, key: string, make: () => T): T { + if (!m.memo.has(key)) m.memo.set(key, make()); + return m.memo.get(key) as T; } const MAX_LABEL = 28; @@ -272,6 +329,9 @@ function shapeWord(m: Model, n: MNode): string { /** The sentence a focusable node is named by: what it is, where it sits, what it connects from and to. */ export function nodeSentence(m: Model, n: MNode): string { + return memo(m, `sentence:${n.i}`, () => writeSentence(m, n)); +} +function writeSentence(m: Model, n: MNode): string { const parts: string[] = []; if (m.type === "schema") { parts.push(`${n.name}, table.`); @@ -328,9 +388,12 @@ const VOID = " br img input meta link hr path polygon polyline circle rect line export function toHtml(v: VNode, slots: Partial<Record<VSlot["slot"], string>> = {}): string { if (typeof v === "string") return escapeHtml(v); if ("slot" in v) return slots[v.slot] ?? ""; + // Names are the engine's own; a name that is not a plain one never reaches the page as syntax. + if (!/^[a-z][a-z0-9]*$/.test(v.t)) throw new Error(`diagram: "${v.t}" is not an element name`); let attrs = ""; for (const [k, value] of Object.entries(v.a)) { if (value === undefined || value === null || value === false) continue; + if (!/^[a-z][a-z0-9:-]*$/i.test(k)) throw new Error(`diagram: "${k}" is not an attribute name`); attrs += value === true ? ` ${k}` : ` ${k}="${escapeHtml(String(value))}"`; } if (VOID.includes(` ${v.t} `) && !v.c.length) return v.t === "path" || v.t === "polygon" || v.t === "polyline" || v.t === "circle" || v.t === "rect" || v.t === "line" ? `<${v.t}${attrs}/>` : `<${v.t}${attrs}>`; @@ -391,6 +454,9 @@ export interface StackPlan { routes: StackRoute[]; gutter: boolean; lanes: numbe /** The stacked drawing's routes, end lanes and the gap above each card (in px of the space scale), from the author's order. */ export function stackPlan(m: Model): StackPlan { + return memo(m, "plan", () => planStack(m)); +} +function planStack(m: Model): StackPlan { const order = m.nodes; const spine = (i: number) => m.type === "data-flow" || !order[i]!.branch; const routes: StackRoute[] = m.edges.map((e) => { @@ -413,18 +479,19 @@ export function stackPlan(m: Model): StackPlan { return !spine(a) && order.slice(lo + 1, hi).every((n) => !spine(n.i)) && ends.every((o) => o.e === e || !overlaps(o.e, e)); }); const gutter = ends.length > 0 && (m.type === "data-flow" || !laneOk); - // Lanes in the gutter: nested (1.7 rule 3): of two overlapping lines the one that travels farther takes the outer lane; equal travel, the earlier is inside. + // Lanes in the gutter, nested (1.7 rule 3): of two overlapping lines the one that travels farther takes the outer lane; equal travel, the + // earlier is inside. Allocated across each overlapping set: shortest first, each one lane outside every overlapping line already placed, + // so no two overlapping lines share a lane. A line that would need a third lane is the development error (`third`). const travel = (e: MEdge) => { const [a, b] = span(e); return b - a; }; const lanes = m.edges.map(() => 0); let third = false; - for (const { e, k } of ends) { - const inner = ends.filter((o) => o.e !== e && overlaps(o.e, e) && (travel(o.e) < travel(e) || (travel(o.e) === travel(e) && o.k < k))); - lanes[k] = inner.length ? 1 : 0; - if (inner.length > 1 || ends.filter((o) => o.e !== e && overlaps(o.e, e)).length > 1) { - // Three overlapping end lines at once need a third lane. - const others = ends.filter((o) => o.e !== e && overlaps(o.e, e)); - if (others.some((o) => others.some((p) => p !== o && overlaps(o.e, p.e)))) third = true; - } + const placed: typeof ends = []; + for (const it of [...ends].sort((x, y) => travel(x.e) - travel(y.e) || x.k - y.k)) { + let lane = 0; + for (const o of placed) if (overlaps(o.e, it.e)) lane = Math.max(lane, lanes[o.k]! + 1); + lanes[it.k] = lane; + if (lane > 1) third = true; + placed.push(it); } // Where an end line leaves its card: the middle, or the thirds when two leave one card (the farther one nearer the top going down, nearer the bottom going up). const exits = m.edges.map(() => 0.5); @@ -487,6 +554,9 @@ function boxSwatch(P: string, shape: "box" | "terminal" | "decision" | "focal" | /** The key, built from the marks the model draws: shapes, main, plain, dashed, the foreign-key line, the focal node, the group. */ function keyTree(P: string, m: Model): VElement | null { + return memo(m, `key:${P}`, () => buildKey(P, m)); +} +function buildKey(P: string, m: Model): VElement | null { const entries: VElement[] = []; const entry = (swatch: VElement, words: string, attrs: VAttrs = {}) => entries.push(h("li", { class: `${P}-entry`, ...attrs }, swatch, h("span", null, words))); if (m.type === "flowchart") { @@ -637,6 +707,9 @@ function sequenceSteps(ctx: TreeContext, m: Model): VElement { // ---- The list ("View as list") ---- function listTree(P: string, m: Model): VNode[] { + return memo(m, `list:${P}`, () => buildList(P, m)); +} +function buildList(P: string, m: Model): VNode[] { const sub = Math.min(6, m.heading + 1); const H = (text: string) => h(`h${sub}`, { class: `${P}-list-head` }, text); const strong = (s: string) => h("strong", null, s); @@ -664,7 +737,7 @@ function listTree(P: string, m: Model): VNode[] { const what = n.shape === "decision" ? "Decision" : n.shape === "terminal" ? (exits.length ? "Start" : "End") : "Step"; const stop = !n.detail && /[.!?]$/.test(n.name) ? " " : ". "; return h("li", null, strong(n.name), n.detail ? [", ", n.mono ? code(n.detail) : n.detail] : "", `${stop}${what}.`, focal(n), - exits.length ? h("ul", { class: `${P}-list-exits` }, exits.map((e) => h("li", null, e.label ? `If ${e.label}: go to ${num(e.to)}, ` : `Then: go to ${num(e.to)}, `, strong(name(e.to)), e.kind === "main" && m.legend.main ? ` (${m.legend.main})` : ""))) : null); + exits.length ? h("ul", { class: `${P}-list-exits` }, exits.map((e) => h("li", null, e.label ? `If ${e.label}: go to ${num(e.to)}, ` : `Then: go to ${num(e.to)}, `, strong(name(e.to)), kw(e.kind)))) : null); }))]; } if (m.type === "data-flow") { @@ -679,7 +752,8 @@ function listTree(P: string, m: Model): VNode[] { out.push(H("Messages")); let list: VElement | null = null; for (const s of m.steps) { - if ("band" in s) { list = null; out.push(h("p", { class: `${P}-list-group` }, s.band)); continue; } + // A band names a phase: a sub-heading, one level under the title's (4.4), drawn as the list's group line. + if ("band" in s) { list = null; out.push(h(`h${sub}`, { class: `${P}-list-group` }, s.band)); continue; } if (!list) { list = h("ol", { class: `${P}-list-items`, start: s.n }); out.push(list); } list.c.push(h("li", null, code(s.label), ": ", strong(name(s.from)), " to ", strong(name(s.to)), `${kw(s.kind)}.`, s.note ? ` ${sentence(upperFirst(s.note))}` : "")); } @@ -805,6 +879,8 @@ export interface Geo { /** Lines that pass through a node (by edge index), labels that found no seat, words that do not fit their span. */ through: number[]; unseated: number[]; + /** Lines (by edge index) that leave the drawing: a route the fit must refuse. */ + outside: number[]; /** The offset of the drawing's origin from the device pixel grid, so lines can be snapped to it. */ ox: number; oy: number; @@ -942,7 +1018,8 @@ function minimums(m: Model, tk: Tokens, measure: ReturnType<typeof ruler>) { let least: number; if (m.type === "data-flow") least = tk.lane + n * (track + s("12")); else if (m.type === "schema") least = n * table + (n - 1) * s("12"); - else if (m.type === "sequence") least = n * tk.node + (n - 1) * s("5"); + // A sequence's columns hold its participants: measured once script runs (the stylesheet before script has only the token floor). + else if (m.type === "sequence") least = n * track + (n - 1) * s("5"); else least = n * track + (n - 1) * s("16") + groupReach(m) * s("4"); return { track, table, least: Math.max(tk.wide, least) }; } @@ -988,11 +1065,12 @@ function snapRoute(pts: Pt[], w: number, sn: ReturnType<typeof snapper>): Pt[] { const segmentsOf = (pts: Pt[]) => pts.slice(1).map((p, k) => [pts[k]!, p] as const); -function findCrossings(lines: GLine[], lit?: (line: GLine) => boolean): GCross[] { +function findCrossings(lines: GLine[], lit?: (line: GLine) => boolean, only?: Set<number>): GCross[] { const out: GCross[] = []; const e = 0.75; for (let a = 0; a < lines.length; a++) for (let b = a + 1; b < lines.length; b++) { const A = lines[a]!, B = lines[b]!; + if (only && !only.has(A.i) && !only.has(B.i)) continue; for (const [p1, p2] of segmentsOf(A.pts)) for (const [q1, q2] of segmentsOf(B.pts)) { const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; if (aH === bH) continue; @@ -1056,6 +1134,11 @@ function assignSlots(m: Model, sides: Array<[DiagramSide, DiagramSide]>, warn: ( else if (rest.length === 2) { rest[0]!.f = 0.25; rest[1]!.f = 0.75; } else if (rest.length === 3) { rest[0]!.f = 0.25; rest[1]!.f = 0.5; rest[2]!.f = 0.75; } else if (rest.length > 3) rest.forEach((p, j) => { p.f = (j + 1) / (rest.length + 1); }); + // Two or more straight lines to one node (one each way) cannot all keep the middle: they would lie on one another. They take the side's slots by + // their count, in the author's order; the far end does the same, so each stays straight. + const byFar = new Map<string, Port[]>(); + for (const p of straight) { if (!byFar.has(p.far.id)) byFar.set(p.far.id, []); byFar.get(p.far.id)!.push(p); } + for (const same of byFar.values()) if (same.length > 1) same.sort((x, y) => x.edge - y.edge).forEach((p, j) => { p.f = same.length === 2 ? (j === 0 ? 0.25 : 0.75) : (j + 1) / (same.length + 1); }); } return ports; } @@ -1072,7 +1155,7 @@ function portPoint(n: GNode, side: DiagramSide, f: number): Pt { return isH(side) ? contour(n, side, t + (b - t) * f) : contour(n, side, l + (r - l) * f); } -interface DrawnInput { m: Model; tk: Tokens; P: string; drawing: HTMLElement; origin: DOMRect; warn: (s: string) => void } +interface DrawnInput { m: Model; tk: Tokens; P: string; drawing: HTMLElement; origin: DOMRect; warn?: (s: string) => void } function gNodes(m: Model, drawing: HTMLElement, origin: DOMRect, P: string): Map<string, GNode> { const out = new Map<string, GNode>(); @@ -1193,7 +1276,7 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const W = drawing.clientWidth, H = drawing.clientHeight; const trackOf = (n: MNode) => (m.type === "data-flow" ? n.col + 1 : n.col); const rowGap = parseFloat(getComputedStyle(drawing).rowGap) || 0; - const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], ox, oy }; + const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], outside: [], ox, oy }; if (m.type === "sequence") return sequenceGeometry(input, geo, sn); @@ -1208,7 +1291,7 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge }); } else { sides = m.edges.map((e) => { const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; const [d1, d2] = defaultSides(a, b); return [e.fromSide ?? d1, e.toSide ?? d2]; }); - ports = assignSlots(m, sides, warn); + ports = assignSlots(m, sides, warn ?? (() => {})); } // End points. @@ -1285,12 +1368,21 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge if (isH(s1)) return [p1, { x: p2.x, y: p1.y }, p2]; return [p1, { x: p1.x, y: p2.y }, p2]; }; - const build = (): GLine[] => m.edges.map((e, k) => { + const buildOne = (k: number): GLine => { + const e = m.edges[k]!; const w = strokeOf(e.kind, tk); const pts = snapRoute(route(k), w, sn); return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), dot: e.fk ? pts[0] : undefined, width: w }; - }); - const score = (lines: GLine[]) => findCrossings(lines).length * 1000 + throughOf(lines, nodes, m).length; + }; + const build = (): GLine[] => m.edges.map((_, k) => buildOne(k)); + // A gutter's lanes are scored by the lines in it alone: their crossings with every line, and the nodes they pass through. The other + // lines are not rebuilt or compared with each other, since a permutation of this gutter cannot change them. + let current: GLine[] | null = null; + const score = (members: Set<number>) => { + current ??= build(); + const lines = current.map((l) => (members.has(l.i) ? buildOne(l.i) : l)); + return { lines, score: findCrossings(lines, undefined, members).length * 1000 + throughOf(lines.filter((l) => members.has(l.i)), nodes, m).length }; + }; // Each gutter: its lanes evenly spaced (at least space-3 apart), in the order that crosses least. // Lanes are needed only where jogs run beside each other: jogs whose runs along the gutter do not overlap each take its middle. const runOf = (members: number[], vertical: boolean): [number, number] => { @@ -1309,14 +1401,16 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const groupsOf = cluster.map((c) => c.members); const count = groupsOf.length; const step = (g.span[1] - g.span[0]) / (count + 1); - if (step < s("3")) warn(`a gutter holds ${count} lanes side by side, closer than space-3`); - let best: number[][] = groupsOf, bestScore = Infinity; + if (step < s("3")) warn?.(`a gutter holds ${count} lanes side by side, closer than space-3`); + const inGutter = new Set(groupsOf.flat()); + let best: number[][] = groupsOf, bestScore = Infinity, bestLines: GLine[] | null = null; for (const perm of permutations(groupsOf)) { perm.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); - const sc = score(build()); - if (sc < bestScore) { bestScore = sc; best = perm; } + const tried = score(inGutter); + if (tried.score < bestScore) { bestScore = tried.score; best = perm; bestLines = tried.lines; } } best.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); + current = bestLines; } } geo.lines = build(); @@ -1324,12 +1418,13 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge if (m.type === "schema") { geo.lines = geo.lines.filter((l) => { const a = m.byId.get(l.from)!, b = m.byId.get(l.to)!; - if (Math.abs(a.col - b.col) > 1) { warn(`${l.from} to ${l.to} is two columns apart, so its line is not drawn; its row still writes the target`); return false; } + if (Math.abs(a.col - b.col) > 1) { warn?.(`${l.from} to ${l.to} is two columns apart, so its line is not drawn; its row still writes the target`); return false; } return true; }); } geo.crossings = findCrossings(geo.lines); geo.through = throughOf(geo.lines, nodes, m); + geo.outside = outsideOf(geo.lines, W, H, tk); const { obstacles, groups } = obstaclesOf(drawing, origin, P, rowGap); obstacles.heads = geo.lines.map((l) => headBox(l, tk)); const seats = seatLabels(m, geo.lines, nodes, obstacles, groups, { l: 0, t: 0, r: W, b: H }, tk, measure); @@ -1347,6 +1442,16 @@ function* permutations<T>(items: T[]): Generator<T[]> { } } +/** Lines any part of which (the stroke, or the head's width) is outside the drawing: the fit refuses them, so no route is drawn off the figure. */ +function outsideOf(lines: GLine[], W: number, H: number, tk: Tokens): number[] { + const out: number[] = []; + for (const l of lines) { + // The stroke's half width round every point, and the head's half width round its tip. + if (l.pts.some((p, k) => { const pad = k === l.pts.length - 1 ? Math.max(l.width / 2, tk.head / 2) : l.width / 2; return p.x - pad < -0.5 || p.x + pad > W + 0.5 || p.y - pad < -0.5 || p.y + pad > H + 0.5; })) out.push(l.i); + } + return out; +} + function throughOf(lines: GLine[], nodes: GNode[], m: Model): number[] { const out: number[] = []; for (const l of lines) { @@ -1399,14 +1504,14 @@ function sequenceGeometry(input: DrawnInput, geo: Geo, sn: ReturnType<typeof sna // ---- The stacked drawing (1.13) ---- function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, plan: StackPlan): { geo: Geo; grow: Record<string, number> } { - const { m, tk, P, drawing, origin, warn } = input; + const { m, tk, P, drawing, origin } = input; const s = tk.space; const map = gNodes(m, drawing, origin, P); const nodes = [...map.values()]; const ox = origin.left - Math.floor(origin.left), oy = origin.top - Math.floor(origin.top); const sn = snapper(ox, oy); const W = drawing.clientWidth, H = drawing.clientHeight; - const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], ox, oy }; + const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], outside: [], ox, oy }; const growBy: Record<string, number> = {}; if (m.type === "sequence" || m.type === "schema") return { geo, grow: growBy }; // The right edge a spine card has where each card sits (the group's inside, or the drawing's less the gutter). @@ -1419,7 +1524,9 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p }); const order = m.nodes; const card = (i: number) => map.get(order[i]!.id)!; - const labelSeats: Array<{ k: number; box: Rect; on: boolean; card: string }> = []; + // Each label's seats, in the order they are tried: a stem's are its clear shaft's middle and then its thirds (1.8's order); every other + // route has its one fixed seat (1.13). + const labelSeats: Array<{ k: number; cands: Rect[]; on: boolean; card: string }> = []; const lineW = (k: number) => strokeOf(m.edges[k]!.kind, tk); m.edges.forEach((e, k) => { const r = plan.routes[k]!; @@ -1432,7 +1539,12 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p const turn = s("4"); if (r === "down" || r === "up") { const lo = Math.max(a.rect.l, b.rect.l), hi = Math.min(a.rect.r, b.rect.r); - const x = sn.x((lo + hi) / 2, w); + // One stem between two cards keeps the middle. Two or more (one each way, say) would lie on one another there, so they take the side's + // slots as 1.6 gives them: the quarter points for two, quarter, middle, quarter for three, in the author's order. + const pair = m.edges.map((o, j) => ({ o, j })).filter(({ o, j }) => (plan.routes[j] === "down" || plan.routes[j] === "up") && ((o.from === e.from && o.to === e.to) || (o.from === e.to && o.to === e.from))); + const at = pair.findIndex((p) => p.j === k); + const slot = pair.length < 2 ? 0.5 : pair.length === 2 ? (at === 0 ? 0.25 : 0.75) : (at + 1) / (pair.length + 1); + const x = sn.x(lo + (hi - lo) * slot, w); pts = r === "down" ? [contour(a, "bottom", x), contour(b, "top", x)] : [contour(a, "top", x), contour(b, "bottom", x)]; if (label) { // Centred on the stem's clear shaft, with a plate; a stem split by a group's boundary takes its outside part. @@ -1447,20 +1559,20 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p const pick = (outer.length ? outer : parts).reduce((best, part) => (part[1] - part[0] > best[1] - best[0] ? part : best)); [y1, y2] = pick; } - const cy = (y1 + y2) / 2; - labelSeats.push({ k, box: { l: x - lw / 2 - s("1"), r: x + lw / 2 + s("1"), t: cy - lh / 2, b: cy + lh / 2 }, on: true, card: r === "down" ? e.to : e.from }); + const cands = [1 / 2, 1 / 3, 2 / 3].map((f) => { const cy = y1 + (y2 - y1) * f; return { l: x - lw / 2 - s("1"), r: x + lw / 2 + s("1"), t: cy - lh / 2, b: cy + lh / 2 }; }); + labelSeats.push({ k, cands, on: true, card: r === "down" ? e.to : e.from }); } } else if (r === "trunk" || r === "rail") { const x = sn.x(Math.max(a.rect.l, r === "rail" ? b.rect.l : a.rect.l) + (r === "trunk" ? s("8") : s("3")), w); const start = contour(a, "bottom", x); if (r === "rail") { pts = [start, contour(b, "top", x)]; - if (label) { const cy = b.rect.t - s("6"); labelSeats.push({ k, box: { l: x + s("2-5"), r: x + s("2-5") + lw, t: cy - lh / 2, b: cy + lh / 2 }, on: false, card: e.to }); } + if (label) { const cy = b.rect.t - s("6"); labelSeats.push({ k, cands: [{ l: x + s("2-5"), r: x + s("2-5") + lw, t: cy - lh / 2, b: cy + lh / 2 }], on: false, card: e.to }); } } else { const ex = sn.x(b.rect.l + s("6"), w); const ty = sn.y(b.rect.t - turn, w); pts = [start, { x, y: ty }, { x: ex, y: ty }, contour(b, "top", ex)]; - if (label) labelSeats.push({ k, box: { l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }, on: false, card: e.to }); + if (label) labelSeats.push({ k, cands: [{ l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }], on: false, card: e.to }); } } else { // An end line: out the end side, along the end lane or the gutter, into the card's top (down) or bottom (up), space-6 in from its end edge. @@ -1472,34 +1584,36 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p const down = r === "end-down"; const ty = sn.y(down ? b.rect.t - turn : b.rect.b + turn, w); pts = [exit, { x: laneX, y: exit.y }, { x: laneX, y: ty }, { x: ex, y: ty }, contour(b, down ? "top" : "bottom", ex)]; - if (label) labelSeats.push({ k, box: { l: ex - s("2-5") - lw, r: ex - s("2-5"), t: ty - lh / 2, b: ty + lh / 2 }, on: false, card: down ? e.to : order[b.i + 1]?.id ?? e.to }); + if (label) labelSeats.push({ k, cands: [{ l: ex - s("2-5") - lw, r: ex - s("2-5"), t: ty - lh / 2, b: ty + lh / 2 }], on: false, card: down ? e.to : order[b.i + 1]?.id ?? e.to }); } const snapped = snapRoute(pts, w, sn); geo.lines.push({ i: k, from: e.from, to: e.to, kind: e.kind, pts: snapped, tip: snapped[snapped.length - 1]!, dir: finish(snapped), width: w }); }); geo.crossings = findCrossings(geo.lines); geo.through = throughOf(geo.lines, nodes, m); - // Fixed seats, checked: a label that does not fit takes a line of its own above its card, and the gap grows 16. - const { obstacles, groups } = obstaclesOf(drawing, origin, P, 0); + geo.outside = outsideOf(geo.lines, W, H, tk); + // Seats, checked by 1.8's rule (a head counts, its own line's included): a label whose every seat fails grows the gap above its card by 16, + // and the figure is measured again; measureFigure draws no lines at all if any label is still without a clean seat after the last try. + const { obstacles } = obstaclesOf(drawing, origin, P, 0); obstacles.heads = geo.lines.map((l) => headBox(l, tk)); const placed: Rect[] = []; const bounds = { l: 0, t: 0, r: W, b: H }; for (const seat of labelSeats) { - const line = geo.lines.find((l) => l.i === seat.k)!; - const G = grow(seat.box, s("1")); - const ownHead = headBox(line, tk); - const bad = seat.box.l < bounds.l - 0.5 || seat.box.r > bounds.r + 0.5 - || nodes.some((n) => boxHitsShape(G, n)) - || placed.some((p) => hit(G, p)) - || obstacles.heads.some((h0) => h0 !== ownHead && hit(G, h0)) - || obstacles.rects.some((r) => hit(G, r)) - || geo.lines.some((o) => o.i !== seat.k && segmentsOf(o.pts).some(([a, b]) => hit(G, segRect(a, b, o.width)))); - if (bad) { growBy[seat.card] = (growBy[seat.card] ?? 0) + 1; geo.unseated.push(seat.k); } - placed.push(seat.box); - geo.labels.push({ i: seat.k, text: m.edges[seat.k]!.label!, box: seat.box, on: seat.on }); + const bad = (box: Rect) => { + const G = grow(box, s("1")); + return box.l < bounds.l - 0.5 || box.r > bounds.r + 0.5 || box.t < bounds.t - 0.5 || box.b > bounds.b + 0.5 + || nodes.some((n) => boxHitsShape(G, n)) + || placed.some((p) => hit(G, p)) + || obstacles.heads.some((h0) => hit(G, h0)) + || obstacles.rects.some((r) => hit(G, r)) + || geo.lines.some((o) => o.i !== seat.k && segmentsOf(o.pts).some(([a, b]) => hit(G, segRect(a, b, o.width)))); + }; + const box = seat.cands.find((c) => !bad(c)); + if (!box) { growBy[seat.card] = (growBy[seat.card] ?? 0) + 1; geo.unseated.push(seat.k); } + const use = box ?? seat.cands[0]!; + placed.push(use); + geo.labels.push({ i: seat.k, text: m.edges[seat.k]!.label!, box: use, on: seat.on }); } - void groups; - if (plan.third) warn("three end lines overlap in the stacked drawing; two lanes is the most (use the drawn layout or reorder)"); return { geo, grow: growBy }; } @@ -1535,11 +1649,13 @@ function lineMarkup(P: string, l: GLine, tk: Tokens, maskId: string | null, radi const bx = l.tip.x - u.x * L, by = l.tip.y - u.y * L; const px = -u.y * W2, py = u.x * W2; const r2 = (n: number) => Math.round(n * 100) / 100; + // Every value written into an attribute is escaped: a kind is one of three by the model, and the ids come from the page. + const kind = escapeHtml(l.kind); const head = open - ? `<path class="${P}-tip" data-kind="${l.kind}" data-open="" d="M${r2(bx + px)} ${r2(by + py)}L${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx - px)} ${r2(by - py)}"/>` - : `<path class="${P}-tip" data-kind="${l.kind}" d="M${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx + px)} ${r2(by + py)}L${r2(bx - px)} ${r2(by - py)}Z"/>`; + ? `<path class="${P}-tip" data-kind="${kind}" data-open="" d="M${r2(bx + px)} ${r2(by + py)}L${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx - px)} ${r2(by - py)}"/>` + : `<path class="${P}-tip" data-kind="${kind}" d="M${r2(l.tip.x)} ${r2(l.tip.y)}L${r2(bx + px)} ${r2(by + py)}L${r2(bx - px)} ${r2(by - py)}Z"/>`; const dot = l.dot ? `<circle class="${P}-dot" cx="${r2(l.dot.x)}" cy="${r2(l.dot.y)}" r="${tk.dot / 2}"/>` : ""; - return `<g class="${P}-edge" data-edge="${l.i}" data-from="${escapeHtml(l.from)}" data-to="${escapeHtml(l.to)}"><path class="${P}-line" data-kind="${l.kind}" d="${pathD(pts, radius)}"${maskId ? ` mask="url(#${maskId})"` : ""}/>${head}${dot}</g>`; + return `<g class="${P}-edge" data-edge="${l.i}" data-from="${escapeHtml(l.from)}" data-to="${escapeHtml(l.to)}"><path class="${P}-line" data-kind="${kind}" d="${pathD(pts, radius)}"${maskId ? ` mask="url(#${escapeHtml(maskId)})"` : ""}/>${head}${dot}</g>`; } function masksMarkup(P: string, geo: Geo, tk: Tokens, base: string): { defs: string; ids: Map<number, string> } { @@ -1557,7 +1673,7 @@ function masksMarkup(P: string, geo: Geo, tk: Tokens, base: string): { defs: str ? `<rect x="${c.at.x - beside}" y="${c.at.y - across}" width="${2 * beside}" height="${2 * across}" fill="black"/>` : `<rect x="${c.at.x - across}" y="${c.at.y - beside}" width="${2 * across}" height="${2 * beside}" fill="black"/>`; }).join(""); - defs += `<mask id="${id}" maskUnits="userSpaceOnUse" x="0" y="0" width="${geo.w}" height="${geo.h}"><rect x="0" y="0" width="${geo.w}" height="${geo.h}" fill="white"/>${holes}</mask>`; + defs += `<mask id="${escapeHtml(id)}" maskUnits="userSpaceOnUse" x="0" y="0" width="${geo.w}" height="${geo.h}"><rect x="0" y="0" width="${geo.w}" height="${geo.h}" fill="white"/>${holes}</mask>`; } void P; return { defs, ids }; @@ -1582,7 +1698,7 @@ export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Toke * word, every label seats and no line passes through a node; otherwise the stack. `apply` writes a state into the DOM (the same markup the * tree gives for it), so each try is measured as it would be drawn. */ -export function measureFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn: (s: string) => void): Measured { +export function measureFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn?: (s: string) => void): Measured { const drawing = fig.querySelector<HTMLElement>(`.${P}-drawing`); if (!drawing) return { dyn: current, geo: null, ink: "", tokens: null }; const tk = readTokens(fig); @@ -1611,18 +1727,20 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin return { ...d, heights }; }; const input = (): DrawnInput => ({ m, tk, P, drawing, origin: drawing.getBoundingClientRect(), warn }); + const names = (geo: Geo, list: number[]) => list.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", "); if (W >= mins.least) { let d = stopOf({ ...current, layout: "drawn", grow: undefined, track: undefined }); d = heightsFor(d); apply(d); const geo = drawnGeometry(input(), measure); - if (!geo.through.length && !geo.unseated.length) { - if (geo.crossings.length) warn(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the drawn layout: ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); + if (!geo.through.length && !geo.unseated.length && !geo.outside.length) { + if (geo.crossings.length) warn?.(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the drawn layout: ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; } // At a width the figure should fit by its tokens and words, a failure is the author's to fix. - if (geo.through.length) warn(`the drawn layout does not fit at ${Math.round(W)}px: ${geo.through.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", ")} would pass through a node`); - if (geo.unseated.length) warn(`the drawn layout does not fit at ${Math.round(W)}px: no clean seat for ${geo.unseated.map((k) => (m.type === "sequence" ? `message ${k}` : `"${m.edges[k]?.label}"`)).join(", ")}`); + if (geo.through.length) warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.through)} would pass through a node`); + if (geo.outside.length) warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.outside)} would leave the drawing`); + if (geo.unseated.length) warn?.(`the drawn layout does not fit at ${Math.round(W)}px: no clean seat for ${geo.unseated.map((k) => (m.type === "sequence" ? `message ${k}` : `"${m.edges[k]?.label}"`)).join(", ")}`); } let d = stopOf({ ...current, layout: "stacked", heights: undefined, grow: {}, track: m.type === "schema" ? mins.table : undefined }); d = heightsFor(d); @@ -1638,8 +1756,19 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin out = stackedGeometry(input(), measure, plan); } const geo = out.geo; - if (geo.crossings.length) warn(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the stacked drawing (each is cut): ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); - if (geo.through.length) warn(`in the stacked drawing ${geo.through.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", ")} passes through a node`); + // The stack is the last layout there is. If it still holds an overlap (a label with no clean seat after every try, a line through a node or + // off the drawing, or a third end lane), no drawing is returned that is known to overlap: the cards stay, in order, with no lines and no + // labels, as the stacked schema's do, and the list holds every connection. + const failed = geo.unseated.length > 0 || geo.through.length > 0 || geo.outside.length > 0 || plan.third; + if (failed) { + if (geo.unseated.length) warn?.(`the stacked drawing has no clean seat for ${[...new Set(geo.unseated)].map((k) => `"${m.edges[k]?.label}"`).join(", ")}, so its lines are not drawn; the list holds every connection`); + if (geo.through.length) warn?.(`in the stacked drawing ${names(geo, geo.through)} would pass through a node, so its lines are not drawn`); + if (geo.outside.length) warn?.(`in the stacked drawing ${names(geo, geo.outside)} would leave the drawing, so its lines are not drawn`); + if (plan.third) warn?.("the stacked drawing would need a third end lane, so its lines are not drawn"); + const bare: Geo = { ...geo, lines: [], labels: [], crossings: [] }; + return { dyn: { ...d, grow: {} }, geo: bare, ink: "", tokens: tk }; + } + if (geo.crossings.length) warn?.(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the stacked drawing (each is cut): ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; } @@ -1712,13 +1841,25 @@ export function keyTarget(m: Model, from: string, key: string): string | null { /** * Brings the DOM's attributes in line with the tree for a new state: the figure, the drawing, every node and the list, walked in step. Text, * slots and the ink are left alone; the attributes tracing sets (data-lit, data-dim, data-near, data-tracing) are kept. + * + * The root is the caller's element as much as the engine's: on it only the state's own attributes (the layout, whether it is measured, and the + * custom properties the state sets) are written, so a caller's `hidden`, ARIA, id, class and style stay. Inside it every element is the engine's. + * A tree element is paired with the next DOM element of its tag and class, so an element the tree does not hold (the HTML skill's JSON + * script, first in the figure) is passed over, never mistaken for the heading. */ const MANAGED = ["data-layout", "data-measured", "role", "aria-roledescription", "aria-labelledby", "aria-describedby", "aria-label", "tabindex", "data-stops", "hidden"]; +const ROOT_MANAGED = ["data-layout", "data-measured"]; const MANAGED_STYLE = ["--_track", "--_h", "--_gap"]; -export function syncAttributes(el: Element, v: VNode): void { +const absent = (value: VAttrs[string]) => value === undefined || value === null || value === false; +function pairs(el: Element, v: VElement): boolean { + if (el.tagName.toLowerCase() !== v.t) return false; + const cls = typeof v.a.class === "string" ? v.a.class.split(" ")[0] : ""; + return !cls || el.classList.contains(cls); +} +export function syncAttributes(el: Element, v: VNode, root = true): void { if (typeof v === "string" || "slot" in v) return; - // Only what a state changes is managed: an attribute or style the caller added (an id, a class, its own style) stays. - for (const name of MANAGED) if (!(name in v.a) || v.a[name] === undefined || v.a[name] === null || v.a[name] === false) el.removeAttribute(name); + const managed = root ? ROOT_MANAGED : MANAGED; + for (const name of managed) if (absent(v.a[name])) el.removeAttribute(name); for (const [k, value] of Object.entries(v.a)) { if (k === "class") continue; if (k === "style") { @@ -1728,13 +1869,25 @@ export function syncAttributes(el: Element, v: VNode): void { for (const n of MANAGED_STYLE) if (!decls.has(n)) style.removeProperty(n); continue; } - if (value === undefined || value === null || value === false) { el.removeAttribute(k); continue; } + if (root && !ROOT_MANAGED.includes(k)) continue; + if (absent(value)) { el.removeAttribute(k); continue; } const s = value === true ? "" : String(value); if (el.getAttribute(k) !== s) el.setAttribute(k, s); } if (v.t === "svg" || (typeof v.a.class === "string" && /-(ink|ruler)$/.test(v.a.class))) return; - const kids = v.c.filter((c): c is VElement => typeof c !== "string" && !("slot" in c)); - const els = [...el.children]; if (v.c.some((c) => typeof c !== "string" && "slot" in c)) return; - kids.forEach((c, k) => { const child = els[k]; if (child && child.tagName.toLowerCase() === c.t) syncAttributes(child, c); }); + const els = [...el.children]; + let at = 0; + for (const c of v.c) { + if (typeof c === "string" || "slot" in c) continue; + for (let j = at; j < els.length; j++) if (pairs(els[j]!, c)) { syncAttributes(els[j]!, c, false); at = j + 1; break; } + } +} + +/** Moves the roving stop from one node to another with no walk of the tree: the only attributes a stop changes are the two nodes' tab indexes. */ +export function moveStop(fig: Element, P: string, from: string | undefined, to: string): void { + if (from === to) return; + const node = (id: string) => fig.querySelector(`.${P}-node[data-node="${CSS.escape(id)}"]`); + if (from) node(from)?.setAttribute("tabindex", "-1"); + node(to)?.setAttribute("tabindex", "0"); } diff --git a/packages/react/src/diagram-figure.tsx b/packages/react/src/diagram-figure.tsx index 598e2843..e7bc8e4c 100644 --- a/packages/react/src/diagram-figure.tsx +++ b/packages/react/src/diagram-figure.tsx @@ -69,11 +69,18 @@ export interface DiagramFigureInternalProps extends DiagramFigureProps { component: string; } -export function DiagramFigure({ spec, component, title: _title, heading: _heading, legend: _legend, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ...props }: DiagramFigureInternalProps) { +export function DiagramFigure({ spec, component, title: _title, heading: _heading, legend: _legend, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ref: callerRef, ...props }: DiagramFigureInternalProps) { const base = `dg${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; const level = usePanelLevel(); - const model = React.useMemo(() => buildModel(spec), [spec]); + // The development checks (placement, groups, the key's words) cost production nothing: a bundler that sets NODE_ENV drops them. + const model = React.useMemo(() => buildModel(spec, { checks: process.env.NODE_ENV !== "production" }), [spec]); const figRef = React.useRef<HTMLElement>(null); + // The figure's own ref, which measuring reads, and the caller's, both set: a caller's ref never replaces the figure's. + const setRef = React.useCallback((el: HTMLElement | null) => { + figRef.current = el; + if (typeof callerRef === "function") callerRef(el); + else if (callerRef) callerRef.current = el; + }, [callerRef]); const [dyn, setDyn] = React.useState<Dyn>({}); const [ink, setInk] = React.useState(""); const measured = React.useRef<Measured | null>(null); @@ -91,7 +98,7 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin const measure = React.useCallback(() => { const fig = figRef.current; if (!fig) return; - const warn = (message: string) => { if (process.env.NODE_ENV !== "production") warnOnce(component, message); }; + const warn = process.env.NODE_ENV !== "production" ? (message: string) => warnOnce(component, message) : undefined; const result = measureFigure(fig, model, P, base, dynRef.current, (d) => syncAttributes(fig, figureTree(model, d, options)), warn); measured.current = result; dynRef.current = result.dyn; @@ -131,10 +138,10 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin const stops = hasStops(model, dyn); const root = { - ref: figRef, + ...props, + ref: setRef, className, style, - ...props, onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => { onKeyDown?.(event); const node = nodeOf(event.target); diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css index a8010b24..2fa0d3da 100644 --- a/packages/react/src/styles/components.css +++ b/packages/react/src/styles/components.css @@ -4520,14 +4520,16 @@ .basalt-diagram-node[data-focal] :is(.basalt-diagram-name, .basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { color: var(--basalt-diagram-focal-ink); } .basalt-diagram-node[data-focal] :is(.basalt-diagram-kind, .basalt-diagram-detail, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more) { opacity: var(--basalt-opacity-amount); } - /* A flowchart's shapes carry its types, so each has a 3:1 contour in place of the rim: one colour on every side. */ + /* A flowchart's shapes carry its types, so each has a 3:1 contour in place of the rim: one colour on every side. A measured decision's contour + is its diamond, so its box's border is never lifted (the diamond's stroke is, below). */ .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal]) { border-color: var(--basalt-diagram-structure); } - .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal])[data-near] { border-color: var(--basalt-text-secondary); } + .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal], [data-shape="decision"])[data-near] { border-color: var(--basalt-text-secondary); } .basalt-diagram-node[data-shape="terminal"] { align-items: center; padding-inline: var(--basalt-space-5); border-radius: var(--basalt-radius-full); text-align: center; } - /* A decision: a diamond behind its words, the words at 500 within 62% of its width. Before script it is a plain box of its words at least - space-16 tall; once measured it is as tall as its words need, never under space-16 nor flatter than 5:1. */ + /* A decision: a diamond behind its words, the words at 500 within 62% of its width (the track's: the box's border-box, so 62% of the content + box plus 62% of the padding and border, 1.24 of each side's). Before script it is a plain box of its words at least space-16 tall; once + measured it is as tall as its words need, never under space-16 nor flatter than 5:1. */ .basalt-diagram-node[data-shape="decision"] { justify-content: center; align-items: center; height: var(--_h, auto); min-height: var(--basalt-space-16); padding: var(--basalt-space-2) var(--basalt-space-2-5); text-align: center; } - .basalt-diagram-words { position: relative; max-width: 62%; } + .basalt-diagram-words { position: relative; max-width: calc(62% + (var(--basalt-space-2-5) + var(--basalt-size-hairline)) * 1.24); } .basalt-diagram-node[data-shape="decision"] .basalt-diagram-name { font-weight: var(--basalt-font-weight-medium); text-wrap: balance; } .basalt-diagram-diamond { display: none; position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } .basalt-diagram-diamond path { fill: var(--_surface, var(--basalt-surface-1)); stroke: var(--basalt-diagram-structure); stroke-width: var(--basalt-size-hairline); vector-effect: non-scaling-stroke; transition: stroke var(--basalt-duration-fast) var(--basalt-ease-out); } @@ -4720,7 +4722,7 @@ .basalt-diagram-code { color: var(--basalt-text-primary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } .basalt-diagram-list-head { margin: var(--basalt-space-4) 0 var(--basalt-space-2); color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } .basalt-diagram-list-head:first-child { margin-block-start: 0; } - .basalt-diagram-list-group { margin: var(--basalt-space-3) 0 var(--basalt-space-1); color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-medium); } + .basalt-diagram-list-group { margin: var(--basalt-space-3) 0 var(--basalt-space-1); color: var(--basalt-text-primary); font-size: inherit; font-weight: var(--basalt-font-weight-medium); line-height: inherit; } .basalt-diagram-list-items { display: flex; flex-direction: column; gap: var(--basalt-space-1); margin: 0; padding-inline-start: var(--basalt-space-5); } .basalt-diagram-list-exits { margin: var(--basalt-space-1) 0 0; padding-inline-start: var(--basalt-space-5); } @media (pointer: coarse) { @@ -4827,6 +4829,10 @@ .basalt-diagram .basalt-diagram-swatch[data-shape="group"] .basalt-diagram-swatch-shape { fill: none; stroke: GrayText; } .basalt-diagram .basalt-diagram-swatch[data-shape="focal"] .basalt-diagram-swatch-shape { fill: CanvasText; stroke: CanvasText; } .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal]), .basalt-diagram[data-type="flowchart"] .basalt-diagram-node:not([data-focal])[data-near] { border-color: CanvasText; } + /* A measured decision is drawn by its diamond alone: its box is not forced, so the transparent border (which a forced palette would paint) + and the focal fill stay off it, at rest, traced or focal. Its words take their colours from the rules here. The shape is named twice for the + weight of the traced and focal rules above. */ + .basalt-diagram[data-measured][data-type="flowchart"] .basalt-diagram-node[data-shape="decision"][data-shape] { forced-color-adjust: none; background: none; border-color: transparent; } .basalt-diagram .basalt-diagram-diamond { forced-color-adjust: none; } .basalt-diagram .basalt-diagram-diamond path, .basalt-diagram .basalt-diagram-node[data-near] .basalt-diagram-diamond path { fill: Canvas; stroke: CanvasText; } .basalt-diagram .basalt-diagram-group, .basalt-diagram .basalt-diagram-gbox { border-color: GrayText; } diff --git a/tools/html-skill/src/compose.mjs b/tools/html-skill/src/compose.mjs index e45a2164..f3d8550c 100644 --- a/tools/html-skill/src/compose.mjs +++ b/tools/html-skill/src/compose.mjs @@ -304,7 +304,7 @@ export function readBody(body, stats = {}) { const placeholder = new RegExp(`${mark}(\\d+)${mark}(\\s*)`, "g"); const blank = (item) => { let text = item.text; for (const [a, b] of [...item.comments].reverse()) text = text.slice(0, a) + " " + text.slice(b); return text; }; return { - text: out, saved, scripts, placeholder, whole, h1: h1 && !h1.open ? h1.text.trim() : null, + text: out, saved, scripts, placeholder, mark, whole, h1: h1 && !h1.open ? h1.text.trim() : null, // The text put back; with `bare`, as detection reads it: no comment (an HTML one, or one in a nested element, or in a script). restore: (s, bare = false) => s.replace(placeholder, (_, k, ws) => { const item = saved[Number(k)]; @@ -541,7 +541,7 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = for (const name of use) if (!(name in manifest.modules)) throw new Error(`basalt:use names "${name}", which is not a module (modules: ${Object.keys(manifest.modules).join(", ")})`); const diagramNotes = []; - const content = writeDiagrams(held.restore(markup).replace(/^\s+/, ""), parts, diagramNotes); + const content = held.restore(writeDiagrams(markup, held, parts, diagramNotes)).replace(/^\s+/, ""); title ||= held.h1 || "Untitled page"; // an empty <title> names nothing: the heading does // Detection reads markup and code, never comments: a word written about in a comment (an HTML one, or one inside a script or a style) brings nothing in. @@ -596,34 +596,52 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = * A diagram's words, written into the page (DECISIONS 281, 1.19): each `<figure class="diagram">` that holds only its JSON gets the markup the diagram module's * script would write for it, from that same script (parts/diagram.js, run here without a page), so the page reads before any script runs. The figure's own * attributes stay (its class joins ours, its id stays); the JSON stays for the script. A figure whose JSON does not parse is left for the script, which says why. + * + * It reads the body as readBody left it: every comment, script, style, textarea, title, svg and template is a placeholder there, so a figure written as an + * example inside one is text and is never expanded. A figure is found by the composer's own tag reader (quoted, single-quoted or unquoted attributes alike), + * and is expanded only when its class list holds `diagram` and its content is one `script` with `data-diagram` and nothing else but white space. */ -function writeDiagrams(content, parts, notes) { - if (!/\bdata-diagram\b/.test(content) || !exists(parts, "diagram.js")) return content; - let markup = null; +function writeDiagrams(markup, held, parts, notes) { + if (!exists(parts, "diagram.js")) return markup; + const mark = held.mark; + const json = new RegExp(`^(\\s*)${mark}(\\d+)${mark}(\\s*)</figure(?=[\\t\\n\\f\\r />])[^>]*>`, "i"); + let engine = null; let serial = 0; - const figure = /<figure\b((?:"[^"]*"|'[^']*'|[^>"'])*)>(\s*<script\b(?:"[^"]*"|'[^']*'|[^>"'])*\bdata-diagram\b(?:"[^"]*"|'[^']*'|[^>"'])*>)([\s\S]*?)(<\/script\s*>)(\s*)<\/figure\s*>/gi; - return content.replace(figure, (whole, attrs, open, json, close) => { - if (!/\bclass\s*=\s*(?:"[^"]*\bdiagram\b[^"]*"|'[^']*\bdiagram\b[^']*')/.test(attrs) || /\bdata-diagram-drawn\b/.test(attrs)) return whole; + let out = ""; + let at = 0; + for (let i = markup.indexOf("<"); i !== -1; i = markup.indexOf("<", i + 1)) { + if (!/^<figure[\t\n\f\r />]/i.test(markup.slice(i, i + 8))) continue; + const tag = readTag(markup, i); + if (!tag.terminated || tag.close) continue; + const attrs = new Map(); + for (const [k, v] of tag.attrs) if (!attrs.has(k)) attrs.set(k, v); // the first of a repeated attribute wins, as in a browser + if (!(attrs.get("class") ?? "").split(/[\t\n\f\r ]+/).includes("diagram") || attrs.has("data-diagram-drawn")) continue; + const inside = json.exec(markup.slice(tag.end)); + const item = inside && held.saved[Number(inside[2])]; + if (!item || item.kind !== "script" || !item.attrs.some(([k]) => k === "data-diagram")) continue; let spec; - try { spec = JSON.parse(json); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); return whole; } - if (!markup) { + try { spec = JSON.parse(item.inner); } catch (e) { notes.push(`a diagram's JSON does not parse (${e.message}); the page's script will say so`); continue; } + if (!engine) { const context = { window: { Basalt: { _: { step() {}, esc: (x) => x } } }, console: { warn() {}, error() {}, log() {} } }; vm.runInNewContext(read(parts, "diagram.js"), context); - markup = context.window.Basalt._.diagramMarkup; + engine = context.window.Basalt._.diagramMarkup; } - const made = markup(spec, `dg${++serial}`); + let made; + try { made = engine(spec, `dg${++serial}`); } catch (e) { notes.push(`${spec?.title ?? "a diagram"} could not be written (${e.message}); the page's script will say so`); continue; } for (const w of made.warnings) notes.push(`${spec.title ?? "a diagram"}: ${w}`); - const ours = [...made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]); - const theirs = [...attrs.matchAll(/\s([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g)].map((m) => [m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? ""]); - const merged = new Map(theirs); - for (const [k, v] of ours) { + const merged = new Map(attrs); + for (const [, k, v] of made.open.matchAll(/\s([\w:-]+)="([^"]*)"/g)) { if (k === "class") merged.set("class", [...new Set(`${merged.get("class") ?? ""} ${v}`.split(/\s+/).filter(Boolean))].join(" ")); else if (k === "style") merged.set("style", merged.has("style") ? `${v};${merged.get("style")}` : v); else merged.set(k, v); } - const tag = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; - return `${tag}${open}${json}${close}${made.inner}</figure>`; - }); + const open = `<figure${[...merged].map(([k, v]) => ` ${k}="${v.replaceAll('"', """)}"`).join("")}>`; + const end = tag.end + inside[0].length; + out += markup.slice(at, i) + open + inside[1] + `${mark}${inside[2]}${mark}` + inside[3] + made.inner + "</figure>"; + at = end; + i = end - 1; + } + return out + markup.slice(at); } /** The module lines of SKILL.md's "## Modules" index: [{ name, trigger, warning }]. A line is `- **name** \`trigger\`: warning`. */ diff --git a/tools/html-skill/src/modules.json b/tools/html-skill/src/modules.json index d4a9270b..13dc1eaa 100644 --- a/tools/html-skill/src/modules.json +++ b/tools/html-skill/src/modules.json @@ -775,7 +775,7 @@ "art", "kbd" ], - "budget": 82300, + "budget": 87200, "usage": 2600, "builds": [ "kbd" diff --git a/tools/html-skill/src/modules/diagram.js b/tools/html-skill/src/modules/diagram.js index f092f518..85cee7c5 100644 --- a/tools/html-skill/src/modules/diagram.js +++ b/tools/html-skill/src/modules/diagram.js @@ -4,7 +4,7 @@ and draw the same pixels. compose.mjs runs `Basalt._.diagramMarkup` at build time and writes each figure's words into the page, so it reads before any script runs; this script then measures it, draws its lines and labels, and wires the keys, the trace and the list. Source: tools/html-skill/src/modules/diagram.js (do not edit the copy in the skill folder). */ -import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, keyTarget, measureFigure, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts"; +import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, keyTarget, measureFigure, moveStop, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts"; (function (B) { 'use strict'; @@ -21,7 +21,7 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, source: escapeHtml(String(spec.source || '')), summary: escapeHtml(String(spec.summary || '')), hint: hintEntries(model).map(function (e) { return '<span>' + e.keys.map(kbd).join(' ') + ' ' + escapeHtml(e.words) + '</span>'; }).join(''), - toggle: '<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="' + (open ? 'true' : 'false') + '" aria-controls="' + base + '-list"><span>' + (open ? 'Hide the list' : 'View as list') + '</span></button>', + toggle: '<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="' + (open ? 'true' : 'false') + '" aria-controls="' + escapeHtml(base) + '-list"><span>' + (open ? 'Hide the list' : 'View as list') + '</span></button>', }; } @@ -34,18 +34,31 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, return { open: html.slice(0, open + 1), inner: html.slice(open + 1, html.length - '</figure>'.length), warnings: model.warnings }; } - function draw(figure, spec) { + // The attributes the figure's markup sets on the figure itself; a redraw clears them before it writes the new ones. + var OWN = ['aria-labelledby', 'data-type', 'data-cols', 'data-reach', 'data-gutter', 'data-layout', 'data-measured']; + var OWN_STYLE = ['--_cols', '--_gpad', '--_track']; + + /** + * Draws a figure. `attach` is the page's own wiring: a figure compose.mjs already wrote is measured as it is. Otherwise (a figure with no + * markup, or `Basalt.diagram(figure, spec)` drawing new data into one that has some) the markup is written from the spec first, so the + * words, the list and the sentences are the new data's. + */ + function draw(figure, spec, attach) { if (figure.__diagram) figure.__diagram.stop(); - var base = (figure.getAttribute('aria-labelledby') || '').replace(/-title$/, ''); + var base = (figure.getAttribute('aria-labelledby') || '').replace(/-title$/, '').replace(/[^A-Za-z0-9_-]/g, ''); var model = buildModel(spec); - if (!figure.querySelector(':scope > .diagram-drawing')) { - // No markup from compose (a figure drawn from script): write it now, keeping the JSON and the figure's own attributes. - while (document.getElementById('dg' + (++serial) + '-title')) { /* the next free base */ } - base = 'dg' + serial; + if (!attach || !base || !figure.querySelector(':scope > .diagram-drawing')) { + // Keep the figure's base when it has ours, so its ids stay; otherwise take the next free one. + if (!base || !figure.querySelector('#' + CSS.escape(base + '-title'))) { + while (document.getElementById('dg' + (++serial) + '-title')) { /* the next free base */ } + base = 'dg' + serial; + } var made = markup(spec, base); var holder = document.createElement('div'); holder.innerHTML = made.open + '</figure>'; var fresh = holder.firstChild; + OWN.forEach(function (n) { figure.removeAttribute(n); }); + OWN_STYLE.forEach(function (n) { figure.style.removeProperty(n); }); for (var a = 0; a < fresh.attributes.length; a++) { var at = fresh.attributes[a]; if (at.name === 'class') figure.classList.add.apply(figure.classList, at.value.split(' ')); @@ -75,6 +88,8 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, retrace(); } function setState(next) { state = next; apply(state); } + // A move of the roving stop touches the two nodes it moves between, not the whole figure. + function setStop(id) { var from = state.stop; state = Object.assign({}, state, { stop: id }); moveStop(figure, P, from, id); } var nodeOf = function (t) { var el = t && t.closest ? t.closest('.diagram-node') : null; return el && figure.contains(el) ? el : null; }; function onKey(event) { @@ -85,7 +100,7 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, var to = keyTarget(model, node.getAttribute('data-node'), event.key); if (!to) return; event.preventDefault(); - setState(Object.assign({}, state, { stop: to })); + setStop(to); var el = figure.querySelector('.diagram-node[data-node="' + CSS.escape(to) + '"]'); if (el) el.focus(); } @@ -95,7 +110,7 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, var id = node.getAttribute('data-node'); // Tracing follows the keyboard's focus (:focus-visible), so a press that focuses a node traces nothing. focusTrace = node.matches(':focus-visible') ? id : null; - if (hasStops(model, state) && state.stop !== id) setState(Object.assign({}, state, { stop: id })); + if (hasStops(model, state) && state.stop !== id) setStop(id); retrace(); } function onFocusOut(event) { @@ -151,7 +166,7 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, if (figure.__diagram) return; var source = figure.querySelector(':scope > script[data-diagram]'); if (!source) return; - try { draw(figure, JSON.parse(source.textContent)); } catch (e) { console.error('Basalt diagram: this figure could not be drawn', e); } + try { draw(figure, JSON.parse(source.textContent), true); } catch (e) { console.error('Basalt diagram: this figure could not be drawn', e); } }); } diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index 11cf33da..bae2985d 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -6,7 +6,8 @@ { "type": "architecture", "title": "How a request reaches the agent", "source": "docs/architecture.md", "summary": "…", "legend": { "main": "Request path", "plain": "Call", "dashed": "Async or one-way", "focal": "The service" }, "groups": [{ "id": "aws", "label": "AWS · your account" }], - "nodes": [{ "id": "svc", "kind": "ECS service", "name": "api service", "detail": "N tasks", "detailMono": true, + "nodes": [{ "id": "alb", "kind": "Load balancer", "name": "ALB", "col": 2, "row": 2 }, + { "id": "svc", "kind": "ECS service", "name": "api service", "detail": "N tasks", "detailMono": true, "focal": true, "group": "aws", "col": 3, "row": 2 }], "edges": [{ "from": "alb", "to": "svc", "kind": "main", "label": "HTTP" }] } </script> From e1a35bce3bdda1532b5dc943913b7d5c19cee59b Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:21:15 -0600 Subject: [PATCH 3/4] Diagrams: fix round 2 of the code and pixel reviews (DECISIONS 281 and 282) Neon's code review and Fable's pixel review of 8c9233c9, and the decider's answers to the builder's questions. - No-script list in the HTML skill: the open rule is important, so the core's [hidden] rule no longer closes it. - A stack that still overlaps draws no lines and is dressed as the no-script form: no line in the key, no key hint, no stops, the list open ("Hide the list"); it closes again when lines return, unless the reader opened it. Fixed seats (rail, trunk, end lines) take a line of their own as the gap grows, and a group's first member's grown gap is the group's margin, so Neon's wiped cases draw. - Labels are seated against each run's place before the half-pixel snap: the CIMIP flowchart is stacked to 959 and drawn at every whole width from 960 to 1104. - .basalt-diagram[hidden] hides; the list's code has no box in the skill. - Opposite end lines from one card leave up first; the end gutter is measured from the drawing's end, not a group's inside; turn-backs share a gutter's lanes with its jogs, dropped foreign keys take no lane, and a lane order that lays one run on another scores worst. - A labelled line in a 40px first or last row gets space-3 above and below when that is all it needs, so a one-row diagram can draw. - The React figure installs the hardware-key listener for its hint. - Decider's answers: Mono details break only at spaces; the schema key starts with "Primary key" and "Foreign key"; the copy changes; phase sub-headings one level under "Messages". - Polish: notes keep their case, schema table names are sub-headings, id-keyed records have no prototype, a zero-width figure waits to be shown, the walkthrough says its shots are labelled by the window. - The skill module stays under its 87,200 cap (87,158): the before-script rules use :is(), and the skill build writes the core's type roles and shorter private property names. Tests were not run or edited (the owner paused them). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .agent/skills/basalt-html/parts/diagram.css | 2 +- .agent/skills/basalt-html/parts/diagram.js | 2 +- .agent/skills/basalt-html/parts/manifest.json | 2 + docs/foundations.md | 13 +- packages/react/src/diagram-core.ts | 244 +++++++++++++----- packages/react/src/diagram-figure.tsx | 7 +- packages/react/src/styles/components.css | 56 ++-- .../react/test/fixtures/cimip-diagrams.json | 4 +- tools/html-skill/build.mjs | 7 +- tools/html-skill/src/modules.json | 2 + tools/html-skill/src/modules/diagram.js | 19 +- tools/review/round64.tsx | 9 +- 12 files changed, 242 insertions(+), 125 deletions(-) diff --git a/.agent/skills/basalt-html/parts/diagram.css b/.agent/skills/basalt-html/parts/diagram.css index 2f0cfe5e..b06bbdea 100644 --- a/.agent/skills/basalt-html/parts/diagram.css +++ b/.agent/skills/basalt-html/parts/diagram.css @@ -1 +1 @@ -:root{--basalt-size-diagram-node: 144px;--basalt-size-diagram-table: 224px;--basalt-size-diagram-lane: 120px;--basalt-size-diagram-step: 56px;--basalt-size-diagram-head: 8px;--basalt-size-diagram-guide-dash: 4px}:root,[data-theme=light],.light{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-white-6);--basalt-diagram-focal-rule-contrast: var(--basalt-white-38)}[data-theme=dark],.dark{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}}@media(prefers-contrast:more){:root,[data-theme=light],[data-theme=dark],.light,.dark,:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-diagram-focal-rule-contrast)}}@layer basalt{.diagram{--_ground: var(--panel-bg, var(--basalt-surface-page));container-type:inline-size;display:flex;flex-direction:column;gap:var(--basalt-space-4);width:100%;min-width:0;margin:0;font-family:var(--basalt-font-family-sans)}.diagram-head{display:flex;flex-direction:column;gap:var(--basalt-space-0-5);min-width:0}.diagram-title{margin:0;color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans);letter-spacing:var(--basalt-text-md-tracking)}.diagram-source{margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-drawing{--_drawn: initial;--_d-display: var(--_drawn) grid;--_d-max: var(--_drawn) none;--_d-cols: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-gap: var(--_drawn) var(--_row-gap) var(--_col-gap);--_d-pad: var(--_drawn) var(--_gpad, 0);--_row-gap: var(--basalt-space-12);--_col-gap: var(--basalt-space-16);position:relative;box-sizing:border-box;display:var(--_d-display, flex);flex-direction:column;grid-template-columns:var(--_d-cols, none);gap:var(--_d-gap, 0);width:100%;max-width:var(--_d-max, var(--basalt-size-breakpoint-container));min-width:0;padding:var(--_d-pad, 0 var(--_gutter, 0) 0 0)}.diagram[data-layout=drawn]>.diagram-drawing{--_drawn: }.diagram[data-layout=stacked]>.diagram-drawing{--_drawn: initial}.diagram[data-gutter]>.diagram-drawing{--_gutter: var(--basalt-space-10)}.diagram[data-type=data-flow]>.diagram-drawing{--_d-cols: var(--_drawn) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr));--_row-gap: var(--basalt-space-10);--_col-gap: var(--basalt-space-12)}.diagram[data-type=schema]>.diagram-drawing{--_row-gap: var(--basalt-space-8);--_col-gap: var(--basalt-space-12);display:grid;grid-template-columns:var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));gap:var(--_d-gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram-node{--_d-gc: var(--_drawn) var(--_c);--_d-gr: var(--_drawn) var(--_r) / var(--_r2);--_d-mt: var(--_drawn) 0;--_d-align: var(--_drawn) center;position:relative;z-index:1;box-sizing:border-box;display:flex;flex-direction:column;min-width:0;grid-column:var(--_d-gc, auto);grid-row:var(--_d-gr, auto);align-self:var(--_d-align, stretch);margin-block-start:var(--_d-mt, var(--_gap, 0));padding:var(--basalt-space-2-5) var(--basalt-space-3);background:var(--panel-next, var(--basalt-surface-1));border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);color:var(--basalt-text-primary);overflow-wrap:break-word;outline:none;transition:border-color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-type=data-flow] .diagram-node{--_d-gc: var(--_drawn) var(--_lc)}.diagram-node[data-branch]{--_d-mi: var(--_drawn) 0;margin-inline:var(--_d-mi, var(--basalt-space-12) var(--basalt-space-6))}.diagram-node:focus-visible{z-index:2;outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:var(--basalt-size-focus-offset)}.diagram-node[data-near]{border-color:var(--basalt-border-hover)}.diagram-kind{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-lane-word{--_d-lw: var(--_drawn) none;display:var(--_d-lw, inline)}.diagram-name{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-detail{margin-block-start:var(--basalt-space-0-5);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-detail[data-mono]{font-family:var(--basalt-font-family-mono)}.diagram-node[data-focal]{background:var(--basalt-diagram-focal);border-color:var(--basalt-diagram-focal)}.diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:var(--basalt-diagram-focal-ink)}.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:var(--basalt-opacity-amount)}.diagram[data-type=flowchart] .diagram-node:not([data-focal]){border-color:var(--basalt-diagram-structure)}.diagram[data-type=flowchart] .diagram-node:not([data-focal],[data-shape=decision])[data-near]{border-color:var(--basalt-text-secondary)}.diagram-node[data-shape=terminal]{align-items:center;padding-inline:var(--basalt-space-5);border-radius:var(--basalt-radius-full);text-align:center}.diagram-node[data-shape=decision]{justify-content:center;align-items:center;height:var(--_h, auto);min-height:var(--basalt-space-16);padding:var(--basalt-space-2) var(--basalt-space-2-5);text-align:center}.diagram-words{position:relative;max-width:calc(62% + (var(--basalt-space-2-5) + var(--basalt-size-hairline)) * 1.24)}.diagram-node[data-shape=decision] .diagram-name{font-weight:var(--basalt-font-weight-medium);text-wrap:balance}.diagram-diamond{display:none;position:absolute;inset:0;width:100%;height:100%;overflow:visible}.diagram-diamond path{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);vector-effect:non-scaling-stroke;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-measured] .diagram-node[data-shape=decision]{background:none;border-color:transparent}.diagram[data-measured] .diagram-node[data-shape=decision] .diagram-diamond{display:block}.diagram-node[data-shape=decision][data-near] .diagram-diamond path{stroke:var(--basalt-text-secondary)}.diagram-node[data-shape=decision][data-focal] .diagram-diamond path{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-group{--_d-gd: var(--_drawn) contents;position:relative;box-sizing:border-box;display:var(--_d-gd, flex);flex-direction:column;margin-block-start:var(--basalt-space-12);padding:var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5);border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg)}.diagram-group:first-child{margin-block-start:0}.diagram-group>.diagram-glabel+.diagram-node{--_d-mt: 0}.diagram-glabel{position:absolute;top:var(--basalt-space-2);inset-inline-start:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);white-space:nowrap}.diagram-group>.diagram-glabel{--_d-gl: var(--_drawn) none;display:var(--_d-gl, block)}.diagram-gbox{--_d-gb: var(--_drawn) block;position:relative;display:var(--_d-gb, none);grid-column:var(--_c) / var(--_c2);grid-row:var(--_r) / var(--_r2);margin:calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4));border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-lane{--_d-ln: var(--_drawn) flex;position:relative;display:var(--_d-ln, none);grid-column:1 / -1;grid-row:var(--_r);align-items:center;pointer-events:none}.diagram-lane+.diagram-lane:before{content:"";position:absolute;inset-inline:0;top:calc(-1 * var(--basalt-space-5));border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-lane-name{box-sizing:border-box;width:var(--basalt-size-diagram-lane);padding-inline-end:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-ink{position:absolute;inset:0;z-index:0;pointer-events:none}.diagram-svg{position:absolute;top:0;left:0;overflow:visible}.diagram-ruler{position:absolute;visibility:hidden;white-space:pre;pointer-events:none}.diagram-ruler[data-f=name]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=name-500]{font:var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-ruler[data-f=table]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-ruler:is([data-f=mono],[data-f=label]){font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-ruler[data-f=sans]{font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-line{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main);stroke-width:var(--basalt-size-chart-line)}.diagram-line[data-kind=dashed]{stroke-dasharray:var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap);stroke-linecap:butt}.diagram-tip{fill:var(--basalt-diagram-edge);transition:fill var(--basalt-duration-fast) var(--basalt-ease-out),stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-tip[data-kind=main]{fill:var(--basalt-diagram-edge-main)}.diagram-tip[data-open]{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:round;stroke-linejoin:round}.diagram-dot{fill:var(--basalt-diagram-edge)}.diagram-life{fill:none;stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);stroke-dasharray:var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash)}.diagram-edge[data-lit] .diagram-line{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip:not([data-open]),.diagram-edge[data-lit] .diagram-dot{fill:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip:not([data-open]),.diagram-edge[data-dim] .diagram-dot{fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-label{position:absolute;box-sizing:border-box;height:var(--basalt-text-xs-line-height);color:var(--basalt-diagram-edge);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono);text-align:center;white-space:nowrap;transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-label[data-on]{background:var(--_ground)}.diagram-label[data-lit]{color:var(--basalt-diagram-edge-main)}.diagram-cast{--_d-cd: var(--_drawn) grid;display:var(--_d-cd, flex);flex-wrap:wrap;grid-template-columns:repeat(var(--_cols, 1),minmax(0,1fr));gap:var(--_d-cast-gap, var(--basalt-space-1-5));--_d-cast-gap: var(--_drawn) var(--basalt-space-5);margin:0;padding:0;list-style:none}.diagram-actor{display:flex;min-width:0}.diagram-node[data-shape=participant]{--_d-pd: var(--_drawn) var(--basalt-space-2-5) var(--basalt-space-3);--_d-pr: var(--_drawn) var(--basalt-radius-md);--_d-pa: var(--_drawn) center;flex:var(--_d-pflex, none);--_d-pflex: var(--_drawn) 1;align-items:center;justify-content:var(--_d-pa, center);min-height:var(--_d-ph, var(--basalt-size-badge));--_d-ph: var(--_drawn) 0;padding:var(--_d-pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline)));border-radius:var(--_d-pr, var(--basalt-radius-xs));text-align:center}.diagram-node[data-shape=participant]:not([data-focal]){--_d-pbg: var(--_drawn) var(--panel-next, var(--basalt-surface-1));--_d-pbc: var(--_drawn) var(--basalt-border-rim);--_d-pbt: var(--_drawn) var(--basalt-border-rim-top);background:var(--_d-pbg, none);border-color:var(--_d-pbc, var(--basalt-border-hairline));border-top-color:var(--_d-pbt, var(--basalt-border-hairline))}.diagram-node[data-shape=participant] .diagram-kind{--_d-pk: var(--_drawn) block;display:var(--_d-pk, none)}.diagram-node[data-shape=participant] .diagram-name{font-size:var(--_d-pn, var(--basalt-text-xs-size));line-height:var(--_d-pnl, var(--basalt-text-xs-line-height));font-weight:var(--_d-pw, var(--basalt-font-weight-medium));--_d-pn: var(--_drawn) var(--basalt-text-sm-size);--_d-pnl: var(--_drawn) var(--basalt-text-sm-line-height);--_d-pw: var(--_drawn) var(--basalt-font-weight-semibold)}.diagram-steps{--_d-sp: var(--_drawn) var(--basalt-space-4);position:relative;z-index:1;padding-block-start:var(--_d-sp, var(--basalt-space-4))}.diagram-msgs{margin:0;padding:0;list-style:none}.diagram-msg{--_d-md: var(--_drawn) grid;--_d-mc: var(--_drawn) repeat(var(--_cols, 1), minmax(0, 1fr));--_d-mr: var(--_drawn) 1fr 1fr;--_d-mh: var(--_drawn) var(--basalt-size-diagram-step);--_d-mg: var(--_drawn) 0 var(--basalt-space-5);display:grid;grid-template-columns:var(--_d-mc, var(--basalt-space-8) minmax(0, 1fr));grid-template-rows:var(--_d-mr, auto);column-gap:var(--basalt-space-5);gap:var(--_d-mg, 0);height:var(--_d-mh, auto);padding-block:var(--_d-mpb, var(--basalt-space-2-5));--_d-mpb: var(--_drawn) 0;border-top:var(--_d-mb, var(--basalt-size-hairline) solid var(--basalt-border-divider));--_d-mb: var(--_drawn) 0;font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-said{--_d-sd: var(--_drawn) block;display:var(--_d-sd, contents);grid-column:var(--_a) / var(--_b);grid-row:1;align-self:end;justify-self:center;margin-block-end:calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--basalt-space-1-5);background:var(--_ground);white-space:nowrap}.diagram-num{grid-column:1;color:var(--basalt-text-tertiary);font-variant-numeric:tabular-nums}.diagram-said .diagram-num{margin-inline-end:var(--_d-nm, 0);--_d-nm: var(--_drawn) var(--basalt-space-1-5)}.diagram-mlabel{grid-column:2;color:var(--basalt-text-primary);font-family:var(--basalt-font-family-mono)}.diagram-route{--_d-rd: var(--_drawn) none;display:var(--_d-rd, inline-flex);grid-column:2;align-items:center;gap:var(--basalt-space-1);flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-note{--_d-nd: var(--_drawn) 2;grid-column:var(--_d-nc, 2);--_d-nc: var(--_drawn) var(--_a) / var(--_b);grid-row:var(--_d-nd, auto);align-self:start;justify-self:var(--_d-nj, stretch);--_d-nj: var(--_drawn) center;margin-block-start:var(--_d-nmt, 0);--_d-nmt: var(--_drawn) calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--_d-npi, 0);--_d-npi: var(--_drawn) var(--basalt-space-1-5);background:var(--_d-nbg, none);--_d-nbg: var(--_drawn) var(--_ground);color:var(--basalt-text-tertiary);white-space:var(--_d-nws, normal);--_d-nws: var(--_drawn) nowrap}.diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) start;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-start:var(--_d-sm, 0)}.diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_d-sj: var(--_drawn) end;justify-self:var(--_d-sj, stretch);--_d-sm: var(--_drawn) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-end:var(--_d-sm, 0)}.diagram-arrow{flex:none;overflow:visible}.diagram-band{--_d-bh: var(--_drawn) var(--basalt-size-control-lg);--_d-bj: var(--_drawn) center;position:relative;display:flex;align-items:center;justify-content:var(--_d-bj, flex-start);height:var(--_d-bh, auto);margin:var(--_d-bm, var(--basalt-space-5) 0 var(--basalt-space-2));--_d-bm: var(--_drawn) 0;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-band:before{--_d-br: var(--_drawn) "";content:var(--_d-br, none);position:absolute;inset-inline:0;top:50%;border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-band>span{position:relative;padding-inline:var(--_d-bp, 0);--_d-bp: var(--_drawn) var(--basalt-space-1-5);background:var(--_ground)}.diagram-node[data-shape=table]{align-self:start;padding:0;overflow-wrap:normal}.diagram-th{padding:var(--basalt-space-2) var(--basalt-space-3);border-bottom:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-node[data-focal] .diagram-th{border-bottom-color:var(--basalt-diagram-focal-rule)}.diagram-tname{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-rows{display:flex;flex-direction:column;padding-block:var(--basalt-space-1)}.diagram-row{display:flex;flex-wrap:wrap;align-items:center;column-gap:var(--basalt-space-3);min-height:var(--basalt-size-control-sm);padding-inline:var(--basalt-space-3);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono)}.diagram-keyseat{flex:none;width:var(--basalt-space-6);margin-inline-end:calc(-1 * var(--basalt-space-3));color:var(--basalt-text-tertiary)}.diagram-cname{flex:1 0 auto;color:var(--basalt-text-primary)}.diagram-ctype{margin-inline-start:auto;color:var(--basalt-text-tertiary)}.diagram-ctype[data-ref]{color:var(--basalt-text-secondary)}.diagram-more{padding:0 var(--basalt-space-3) var(--basalt-space-2);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-key{padding-block-start:var(--basalt-space-3);border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-legend{display:flex;flex-wrap:wrap;gap:var(--basalt-space-2) var(--basalt-space-5);margin:0;padding:0;list-style:none;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-entry{display:inline-flex;align-items:center;gap:var(--basalt-space-1-5)}.diagram[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram:not([data-layout]) .diagram-entry[data-when=drawn]{display:none}.diagram-swatch{flex:none;overflow:visible}.diagram-swatch-shape{fill:var(--_ground);stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline)}.diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke-dasharray:var(--basalt-space-1) var(--basalt-space-0-5)}.diagram-fk-mark{color:var(--basalt-text-secondary);font-family:var(--basalt-font-family-mono)}.diagram-hint{display:flex;flex-wrap:wrap;gap:var(--basalt-space-1) var(--basalt-space-4);margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans)}.diagram-hint>span{display:inline-flex;align-items:center;gap:var(--basalt-space-1)}.diagram[data-layout=stacked]:is([data-type=sequence],[data-type=schema]) .diagram-hint{display:none}.diagram-summary{order:1;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans);text-wrap:pretty}.diagram-foot{order:2;display:flex}.diagram-list{order:3;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list[hidden]{display:none}.diagram-list strong{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-code{color:var(--basalt-text-primary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-list-head{margin:var(--basalt-space-4) 0 var(--basalt-space-2);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans)}.diagram-list-head:first-child{margin-block-start:0}.diagram-list-group{margin:var(--basalt-space-3) 0 var(--basalt-space-1);color:var(--basalt-text-primary);font-size:inherit;font-weight:var(--basalt-font-weight-medium);line-height:inherit}.diagram-list-items{display:flex;flex-direction:column;gap:var(--basalt-space-1);margin:0;padding-inline-start:var(--basalt-space-5)}.diagram-list-exits{margin:var(--basalt-space-1) 0 0;padding-inline-start:var(--basalt-space-5)}@media(pointer:coarse){.diagram-toggle{min-height:var(--basalt-size-tap-min)}}@media(prefers-reduced-motion:reduce){.diagram-node,.diagram-line,.diagram-tip,.diagram-label,.diagram-diamond path{transition:none}}@media(prefers-contrast:more){.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:1}}@container (width >= 640px){.diagram:not([data-layout])[data-type=architecture][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=architecture][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=data-flow][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="1"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="3"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 696px){.diagram:not([data-layout])[data-type=data-flow][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 768px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="4"]>.diagram-drawing,.diagram:not([data-layout])[data-type=schema][data-cols="3"]>.diagram-drawing{--_drawn: }}@container (width >= 784px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 800px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="2"]>.diagram-drawing,.diagram:not([data-layout])[data-type=sequence][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 888px){.diagram:not([data-layout])[data-type=data-flow][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 964px){.diagram:not([data-layout])[data-type=sequence][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 976px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 992px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1008px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]>.diagram-drawing{--_drawn: }}@container (width >= 1080px){.diagram:not([data-layout])[data-type=data-flow][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1184px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="0"]>.diagram-drawing,.diagram:not([data-layout])[data-type=flowchart][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1200px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="1"]>.diagram-drawing{--_drawn: }}@container (width >= 1216px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="2"]>.diagram-drawing{--_drawn: }}@container (width >= 1272px){.diagram:not([data-layout])[data-type=data-flow][data-cols="6"]>.diagram-drawing{--_drawn: }}@container (width >= 1312px){.diagram:not([data-layout])[data-type=schema][data-cols="5"]>.diagram-drawing{--_drawn: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]>.diagram-drawing{--_drawn: }}@media(scripting:none){.diagram:not(#basalt-diagram-no-id)>.diagram-drawing{--_drawn: initial}.diagram-list[hidden]{display:block}.diagram-foot,.diagram-entry[data-line],.diagram-hint{display:none}}@media(forced-colors:active){.diagram-svg,.diagram-swatch,.diagram-arrow{forced-color-adjust:none}.diagram .diagram-line,.diagram .diagram-line[data-kind]{stroke:CanvasText}.diagram .diagram-tip,.diagram .diagram-tip[data-kind],.diagram .diagram-dot{fill:CanvasText}.diagram .diagram-tip[data-open],.diagram .diagram-tip[data-kind][data-open]{fill:none;stroke:CanvasText}.diagram .diagram-edge[data-dim] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-dim] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:GrayText}.diagram .diagram-edge[data-dim] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-edge[data-lit] .diagram-line{stroke:Highlight}.diagram .diagram-edge[data-lit] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:Highlight}.diagram .diagram-edge[data-lit] .diagram-tip[data-open]{stroke:Highlight}.diagram .diagram-life{stroke:GrayText}.diagram .diagram-label{color:CanvasText;forced-color-adjust:none}.diagram .diagram-label[data-on]{background:Canvas}.diagram .diagram-label[data-lit]{color:Highlight}.diagram .diagram-swatch-shape{fill:Canvas;stroke:CanvasText}.diagram .diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke:GrayText}.diagram .diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:CanvasText;stroke:CanvasText}.diagram[data-type=flowchart] .diagram-node:not([data-focal]),.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:CanvasText}.diagram[data-measured][data-type=flowchart] .diagram-node[data-shape=decision][data-shape]{forced-color-adjust:none;background:none;border-color:transparent}.diagram .diagram-diamond{forced-color-adjust:none}.diagram .diagram-diamond path,.diagram .diagram-node[data-near] .diagram-diamond path{fill:Canvas;stroke:CanvasText}.diagram .diagram-group,.diagram .diagram-gbox{border-color:GrayText}.diagram .diagram-lane+.diagram-lane:before,.diagram .diagram-band:before{border-color:GrayText}.diagram .diagram-hint{color:GrayText}.diagram :is(.diagram-kind,.diagram-name,.diagram-detail,.diagram-glabel,.diagram-lane-name,.diagram-title,.diagram-source,.diagram-num,.diagram-mlabel,.diagram-route,.diagram-note,.diagram-band,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more,.diagram-legend,.diagram-fk-mark){color:CanvasText}.diagram .diagram-node:focus-visible{outline-color:Highlight}.diagram .diagram-node[data-focal],.diagram .diagram-node[data-focal][data-near]{forced-color-adjust:none;background:CanvasText;border-color:CanvasText}.diagram .diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:Canvas;opacity:1}.diagram .diagram-node[data-focal] .diagram-th{border-bottom-color:Canvas}.diagram .diagram-node[data-focal]:focus-visible{outline:var(--basalt-size-focus-width) solid Highlight}.diagram .diagram-node[data-focal][data-shape=decision] .diagram-diamond path{fill:CanvasText;stroke:CanvasText}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow{print-color-adjust:exact}.diagram-hint{display:none}}} +:root{--basalt-size-diagram-node: 144px;--basalt-size-diagram-table: 224px;--basalt-size-diagram-lane: 120px;--basalt-size-diagram-step: 56px;--basalt-size-diagram-head: 8px;--basalt-size-diagram-guide-dash: 4px}:root,[data-theme=light],.light{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-white-6);--basalt-diagram-focal-rule-contrast: var(--basalt-white-38)}[data-theme=dark],.dark{--basalt-diagram-edge-main: var(--basalt-text-primary);--basalt-diagram-edge: var(--basalt-text-secondary);--basalt-diagram-edge-dim: var(--basalt-border-input);--basalt-diagram-structure: var(--basalt-border-input);--basalt-diagram-focal: var(--basalt-action-primary);--basalt-diagram-focal-ink: var(--basalt-action-primary-text);--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-black-8);--basalt-diagram-focal-rule-contrast: var(--basalt-black-45)}}@media(prefers-contrast:more){:root,[data-theme=light],[data-theme=dark],.light,.dark,:root:not([data-theme=light]):not(.light){--basalt-diagram-focal-rule: var(--basalt-diagram-focal-rule-contrast)}}@layer basalt{.diagram{--_ground: var(--panel-bg, var(--basalt-surface-page));container-type:inline-size;display:flex;flex-direction:column;gap:var(--basalt-space-4);width:100%;min-width:0;margin:0;font-family:var(--basalt-font-family-sans)}.diagram[hidden]{display:none}.diagram-head{display:flex;flex-direction:column;gap:var(--basalt-space-0-5);min-width:0}.diagram-title{margin:0;color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--bh-md);letter-spacing:var(--basalt-text-md-tracking)}.diagram-source{margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-drawing{--_D: initial;--_Display: var(--_D) grid;--_Max: var(--_D) none;--_Cols: var(--_D) repeat(var(--_cols, 1), minmax(0, 1fr));--_Gap: var(--_D) var(--_row-gap) var(--_col-gap);--_Pad: var(--_D) var(--_gpad, 0);--_row-gap: var(--basalt-space-12);--_col-gap: var(--basalt-space-16);position:relative;box-sizing:border-box;display:var(--_Display, flex);flex-direction:column;grid-template-columns:var(--_Cols, none);gap:var(--_Gap, 0);width:100%;max-width:var(--_Max, var(--basalt-size-breakpoint-container));min-width:0;padding:var(--_Pad, 0 var(--_gutter, 0) 0 0)}.diagram[data-layout=drawn]>.diagram-drawing{--_D: }.diagram[data-layout=stacked]>.diagram-drawing{--_D: initial}.diagram[data-gutter]>.diagram-drawing{--_gutter: var(--basalt-space-10)}.diagram[data-type=data-flow]>.diagram-drawing{--_Cols: var(--_D) var(--basalt-size-diagram-lane) repeat(var(--_cols, 1), minmax(0, 1fr));--_row-gap: var(--basalt-space-10);--_col-gap: var(--basalt-space-12)}.diagram[data-type=schema]>.diagram-drawing{--_row-gap: var(--basalt-space-8);--_col-gap: var(--basalt-space-12);display:grid;grid-template-columns:var(--_Cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));gap:var(--_Gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram-node{--_Gc: var(--_D) var(--_c);--_Gr: var(--_D) var(--_r) / var(--_r2);--_Mt: var(--_D) 0;--_Align: var(--_D) center;position:relative;z-index:1;box-sizing:border-box;display:flex;flex-direction:column;min-width:0;grid-column:var(--_Gc, auto);grid-row:var(--_Gr, auto);align-self:var(--_Align, stretch);margin-block-start:var(--_Mt, var(--_gap, 0));padding:var(--basalt-space-2-5) var(--basalt-space-3);background:var(--panel-next, var(--basalt-surface-1));border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);color:var(--basalt-text-primary);overflow-wrap:break-word;outline:none;transition:border-color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-type=data-flow] .diagram-node{--_Gc: var(--_D) var(--_lc)}.diagram-node[data-branch]{--_Mi: var(--_D) 0;margin-inline:var(--_Mi, var(--basalt-space-12) var(--basalt-space-6))}.diagram-node:focus-visible{z-index:2;outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:var(--basalt-size-focus-offset)}.diagram-node[data-near]{border-color:var(--basalt-border-hover)}.diagram-kind{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs-mono)}.diagram-lane-word{--_Lw: var(--_D) none;display:var(--_Lw, inline)}.diagram-name{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--bh-sm)}.diagram-detail{margin-block-start:var(--basalt-space-0-5);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-detail[data-mono]{font-family:var(--basalt-font-family-mono)}.diagram-run{display:inline-block;max-width:100%}.diagram-node[data-focal]{background:var(--basalt-diagram-focal);border-color:var(--basalt-diagram-focal)}.diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:var(--basalt-diagram-focal-ink)}.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:var(--basalt-opacity-amount)}.diagram[data-type=flowchart] .diagram-node:not([data-focal]){border-color:var(--basalt-diagram-structure)}.diagram[data-type=flowchart] .diagram-node:not([data-focal],[data-shape=decision])[data-near]{border-color:var(--basalt-text-secondary)}.diagram-node[data-shape=terminal]{align-items:center;padding-inline:var(--basalt-space-5);border-radius:var(--basalt-radius-full);text-align:center}.diagram-node[data-shape=decision]{justify-content:center;align-items:center;height:var(--_h, auto);min-height:var(--basalt-space-16);padding:var(--basalt-space-2) var(--basalt-space-2-5);text-align:center}.diagram-words{position:relative;max-width:calc(62% + (var(--basalt-space-2-5) + var(--basalt-size-hairline)) * 1.24)}.diagram-node[data-shape=decision] .diagram-name{font-weight:var(--basalt-font-weight-medium);text-wrap:balance}.diagram-diamond{display:none;position:absolute;inset:0;width:100%;height:100%;overflow:visible}.diagram-diamond path{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);vector-effect:non-scaling-stroke;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram[data-measured] .diagram-node[data-shape=decision]{background:none;border-color:transparent}.diagram[data-measured] .diagram-node[data-shape=decision] .diagram-diamond{display:block}.diagram-node[data-shape=decision][data-near] .diagram-diamond path{stroke:var(--basalt-text-secondary)}.diagram-node[data-shape=decision][data-focal] .diagram-diamond path{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-group{--_Gd: var(--_D) contents;position:relative;box-sizing:border-box;display:var(--_Gd, flex);flex-direction:column;margin-block-start:calc(var(--basalt-space-12) + var(--basalt-space-4) * var(--_ggrow, 0));padding:var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5);border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg)}.diagram-group:first-child{margin-block-start:0}.diagram-group>.diagram-glabel+.diagram-node{--_Mt: 0}.diagram-glabel{position:absolute;top:var(--basalt-space-2);inset-inline-start:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--bh-xs-mono);white-space:nowrap}.diagram-group>.diagram-glabel{--_Gl: var(--_D) none;display:var(--_Gl, block)}.diagram-gbox{--_Gb: var(--_D) block;position:relative;display:var(--_Gb, none);grid-column:var(--_c) / var(--_c2);grid-row:var(--_r) / var(--_r2);margin:calc(-1 * var(--basalt-space-8)) calc(-1 * var(--basalt-space-4)) calc(-1 * var(--basalt-space-4));border:var(--basalt-size-hairline) dashed var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-lane{--_Ln: var(--_D) flex;position:relative;display:var(--_Ln, none);grid-column:1 / -1;grid-row:var(--_r);align-items:center;pointer-events:none}.diagram-lane+.diagram-lane:before{content:"";position:absolute;inset-inline:0;top:calc(-1 * var(--basalt-space-5));border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-lane-name{box-sizing:border-box;width:var(--basalt-size-diagram-lane);padding-inline-end:var(--basalt-space-3);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--bh-xs)}.diagram-ink{position:absolute;inset:0;z-index:0;pointer-events:none}.diagram-svg{position:absolute;top:0;left:0;overflow:visible}.diagram-ruler{position:absolute;visibility:hidden;white-space:pre;pointer-events:none}.diagram-ruler[data-f=name]{font:var(--basalt-font-weight-semibold) var(--bh-sm)}.diagram-ruler[data-f=name-500]{font:var(--basalt-font-weight-medium) var(--bh-sm)}.diagram-ruler[data-f=table]{font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-ruler:is([data-f=mono],[data-f=label]){font:var(--basalt-font-weight-regular) var(--bh-xs-mono)}.diagram-ruler[data-f=sans]{font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-line{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main);stroke-width:var(--basalt-size-chart-line)}.diagram-line[data-kind=dashed]{stroke-dasharray:var(--basalt-size-chart-dash) var(--basalt-size-chart-dash-gap);stroke-linecap:butt}.diagram-tip{fill:var(--basalt-diagram-edge);transition:fill var(--basalt-duration-fast) var(--basalt-ease-out),stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-tip[data-kind=main]{fill:var(--basalt-diagram-edge-main)}.diagram-tip[data-open]{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:round;stroke-linejoin:round}.diagram-dot{fill:var(--basalt-diagram-edge)}.diagram-life{fill:none;stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);stroke-dasharray:var(--basalt-size-diagram-guide-dash) var(--basalt-size-diagram-guide-dash)}.diagram-edge[data-lit] .diagram-line{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip:not([data-open]),.diagram-edge[data-lit] .diagram-dot{fill:var(--basalt-diagram-edge-main)}.diagram-edge[data-lit] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip:not([data-open]),.diagram-edge[data-dim] .diagram-dot{fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-dim] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-label{position:absolute;box-sizing:border-box;height:var(--basalt-text-xs-line-height);color:var(--basalt-diagram-edge);font:var(--basalt-font-weight-regular) var(--bh-xs-mono);text-align:center;white-space:nowrap;transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-label[data-on]{background:var(--_ground)}.diagram-label[data-lit]{color:var(--basalt-diagram-edge-main)}.diagram-cast{--_Cd: var(--_D) grid;display:var(--_Cd, flex);flex-wrap:wrap;grid-template-columns:repeat(var(--_cols, 1),minmax(0,1fr));gap:var(--_Cast-gap, var(--basalt-space-1-5));--_Cast-gap: var(--_D) var(--basalt-space-5);margin:0;padding:0;list-style:none}.diagram-actor{display:flex;min-width:0}.diagram-node[data-shape=participant]{--_Pd: var(--_D) var(--basalt-space-2-5) var(--basalt-space-3);--_Pr: var(--_D) var(--basalt-radius-md);--_Pa: var(--_D) center;flex:var(--_Pflex, none);--_Pflex: var(--_D) 1;align-items:center;justify-content:var(--_Pa, center);min-height:var(--_Ph, var(--basalt-size-badge));--_Ph: var(--_D) 0;padding:var(--_Pd, 0 calc(var(--basalt-space-2) - var(--basalt-size-hairline)));border-radius:var(--_Pr, var(--basalt-radius-xs));text-align:center}.diagram-node[data-shape=participant]:not([data-focal]){--_Pbg: var(--_D) var(--panel-next, var(--basalt-surface-1));--_Pbc: var(--_D) var(--basalt-border-rim);--_Pbt: var(--_D) var(--basalt-border-rim-top);background:var(--_Pbg, none);border-color:var(--_Pbc, var(--basalt-border-hairline));border-top-color:var(--_Pbt, var(--basalt-border-hairline))}.diagram-node[data-shape=participant] .diagram-kind{--_Pk: var(--_D) block;display:var(--_Pk, none)}.diagram-node[data-shape=participant] .diagram-name{font-size:var(--_Pn, var(--basalt-text-xs-size));line-height:var(--_Pnl, var(--basalt-text-xs-line-height));font-weight:var(--_Pw, var(--basalt-font-weight-medium));--_Pn: var(--_D) var(--basalt-text-sm-size);--_Pnl: var(--_D) var(--basalt-text-sm-line-height);--_Pw: var(--_D) var(--basalt-font-weight-semibold)}.diagram-steps{--_Sp: var(--_D) var(--basalt-space-4);position:relative;z-index:1;padding-block-start:var(--_Sp, var(--basalt-space-4))}.diagram-msgs{margin:0;padding:0;list-style:none}.diagram-msg{--_Md: var(--_D) grid;--_Mc: var(--_D) repeat(var(--_cols, 1), minmax(0, 1fr));--_Mr: var(--_D) 1fr 1fr;--_Mh: var(--_D) var(--basalt-size-diagram-step);--_Mg: var(--_D) 0 var(--basalt-space-5);display:grid;grid-template-columns:var(--_Mc, var(--basalt-space-8) minmax(0, 1fr));grid-template-rows:var(--_Mr, auto);column-gap:var(--basalt-space-5);gap:var(--_Mg, 0);height:var(--_Mh, auto);padding-block:var(--_Mpb, var(--basalt-space-2-5));--_Mpb: var(--_D) 0;border-top:var(--_Mb, var(--basalt-size-hairline) solid var(--basalt-border-divider));--_Mb: var(--_D) 0;font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-said{--_Sd: var(--_D) block;display:var(--_Sd, contents);grid-column:var(--_a) / var(--_b);grid-row:1;align-self:end;justify-self:center;margin-block-end:calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--basalt-space-1-5);background:var(--_ground);white-space:nowrap}.diagram-num{grid-column:1;color:var(--basalt-text-tertiary);font-variant-numeric:tabular-nums}.diagram-said .diagram-num{margin-inline-end:var(--_Nm, 0);--_Nm: var(--_D) var(--basalt-space-1-5)}.diagram-mlabel{grid-column:2;color:var(--basalt-text-primary);font-family:var(--basalt-font-family-mono)}.diagram-route{--_Rd: var(--_D) none;display:var(--_Rd, inline-flex);grid-column:2;align-items:center;gap:var(--basalt-space-1);flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-note{--_Nd: var(--_D) 2;grid-column:var(--_Nc, 2);--_Nc: var(--_D) var(--_a) / var(--_b);grid-row:var(--_Nd, auto);align-self:start;justify-self:var(--_Nj, stretch);--_Nj: var(--_D) center;margin-block-start:var(--_Nmt, 0);--_Nmt: var(--_D) calc(var(--basalt-space-1) + var(--basalt-size-hairline));padding-inline:var(--_Npi, 0);--_Npi: var(--_D) var(--basalt-space-1-5);background:var(--_Nbg, none);--_Nbg: var(--_D) var(--_ground);color:var(--basalt-text-tertiary);white-space:var(--_Nws, normal);--_Nws: var(--_D) nowrap}.diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_Sj: var(--_D) start;justify-self:var(--_Sj, stretch);--_Sm: var(--_D) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-start:var(--_Sm, 0)}.diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_Sj: var(--_D) end;justify-self:var(--_Sj, stretch);--_Sm: var(--_D) calc(50% + var(--basalt-space-6) + var(--basalt-space-1));margin-inline-end:var(--_Sm, 0)}.diagram-arrow{flex:none;overflow:visible}.diagram-band{--_Bh: var(--_D) var(--basalt-size-control-lg);--_Bj: var(--_D) center;position:relative;display:flex;align-items:center;justify-content:var(--_Bj, flex-start);height:var(--_Bh, auto);margin:var(--_Bm, var(--basalt-space-5) 0 var(--basalt-space-2));--_Bm: var(--_D) 0;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--bh-xs)}.diagram-band:before{--_Br: var(--_D) "";content:var(--_Br, none);position:absolute;inset-inline:0;top:50%;border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-band>span{position:relative;padding-inline:var(--_Bp, 0);--_Bp: var(--_D) var(--basalt-space-1-5);background:var(--_ground)}.diagram-node[data-shape=table]{align-self:start;padding:0;overflow-wrap:normal}.diagram-th{padding:var(--basalt-space-2) var(--basalt-space-3);border-bottom:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-node[data-focal] .diagram-th{border-bottom-color:var(--basalt-diagram-focal-rule)}.diagram-tname{color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-rows{display:flex;flex-direction:column;padding-block:var(--basalt-space-1)}.diagram-row{display:flex;flex-wrap:wrap;align-items:center;column-gap:var(--basalt-space-3);min-height:var(--basalt-size-control-sm);padding-inline:var(--basalt-space-3);font:var(--basalt-font-weight-regular) var(--bh-xs-mono)}.diagram-keyseat{flex:none;width:var(--basalt-space-6);margin-inline-end:calc(-1 * var(--basalt-space-3));color:var(--basalt-text-tertiary)}.diagram-cname{flex:1 0 auto;color:var(--basalt-text-primary)}.diagram-ctype{margin-inline-start:auto;color:var(--basalt-text-tertiary)}.diagram-ctype[data-ref]{color:var(--basalt-text-secondary)}.diagram-more{padding:0 var(--basalt-space-3) var(--basalt-space-2);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-key{padding-block-start:var(--basalt-space-3);border-top:var(--basalt-size-hairline) solid var(--basalt-border-divider)}.diagram-legend{display:flex;flex-wrap:wrap;gap:var(--basalt-space-2) var(--basalt-space-5);margin:0;padding:0;list-style:none;color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-entry{display:inline-flex;align-items:center;gap:var(--basalt-space-1-5)}.diagram[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram:not([data-layout]) .diagram-entry[data-when=drawn]{display:none}.diagram-swatch{flex:none;overflow:visible}.diagram-swatch-shape{fill:var(--_ground);stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline)}.diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:var(--basalt-diagram-focal);stroke:var(--basalt-diagram-focal)}.diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke-dasharray:var(--basalt-space-1) var(--basalt-space-0-5)}.diagram-fk-mark{color:var(--basalt-text-secondary);font-family:var(--basalt-font-family-mono)}.diagram-key-letters{color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs-mono)}.diagram-hint{display:flex;flex-wrap:wrap;gap:var(--basalt-space-1) var(--basalt-space-4);margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram-hint>span{display:inline-flex;align-items:center;gap:var(--basalt-space-1)}.diagram[data-layout=stacked]:is([data-type=sequence],[data-type=schema]) .diagram-hint{display:none}.diagram[data-bare] :is(.diagram-entry[data-line],.diagram-hint){display:none}.diagram-summary{order:1;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--bh-sm);text-wrap:pretty}.diagram-foot{order:2;display:flex}.diagram-list{order:3;max-width:var(--basalt-size-prose-width);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-regular) var(--bh-sm)}.diagram-list[hidden]{display:none}.diagram-list strong{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-code{padding:0;border-radius:0;background:none;color:var(--basalt-text-primary);font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono)}.diagram-list-head{margin:var(--basalt-space-4) 0 var(--basalt-space-2);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--bh-sm)}.diagram-list-head:first-child{margin-block-start:0}.diagram-list-group{margin:var(--basalt-space-3) 0 var(--basalt-space-1);color:var(--basalt-text-primary);font-size:inherit;font-weight:var(--basalt-font-weight-medium);line-height:inherit}.diagram-list-items{display:flex;flex-direction:column;gap:var(--basalt-space-1);margin:0;padding-inline-start:var(--basalt-space-5)}.diagram-list-exits{margin:var(--basalt-space-1) 0 0;padding-inline-start:var(--basalt-space-5)}@media(pointer:coarse){.diagram-toggle{min-height:var(--basalt-size-tap-min)}}@media(prefers-reduced-motion:reduce){.diagram-node,.diagram-line,.diagram-tip,.diagram-label,.diagram-diamond path{transition:none}}@media(prefers-contrast:more){.diagram-node[data-focal] :is(.diagram-kind,.diagram-detail,.diagram-keyseat,.diagram-ctype,.diagram-more){opacity:1}}@container (width >= 640px){.diagram:not([data-layout]):is(:is([data-type=architecture],[data-type=flowchart]):is([data-cols="1"],[data-cols="2"],[data-cols="3"]),:is([data-type=data-flow],[data-type=schema]):is([data-cols="1"],[data-cols="2"]),[data-type=sequence]:is([data-cols="1"],[data-cols="2"],[data-cols="3"],[data-cols="4"]))>.diagram-drawing{--_D: }}@container (width >= 696px){.diagram:not([data-layout])[data-type=data-flow][data-cols="3"]>.diagram-drawing{--_D: }}@container (width >= 768px){.diagram:not([data-layout]):is([data-type=architecture][data-cols="4"][data-reach="0"],[data-type=flowchart][data-cols="4"],[data-type=schema][data-cols="3"])>.diagram-drawing{--_D: }}@container (width >= 784px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="1"]>.diagram-drawing{--_D: }}@container (width >= 800px){.diagram:not([data-layout]):is([data-type=architecture][data-cols="4"][data-reach="2"],[data-type=sequence][data-cols="5"])>.diagram-drawing{--_D: }}@container (width >= 888px){.diagram:not([data-layout])[data-type=data-flow][data-cols="4"]>.diagram-drawing{--_D: }}@container (width >= 964px){.diagram:not([data-layout])[data-type=sequence][data-cols="6"]>.diagram-drawing{--_D: }}@container (width >= 976px){.diagram:not([data-layout]):is([data-type=architecture][data-cols="5"][data-reach="0"],[data-type=flowchart][data-cols="5"])>.diagram-drawing{--_D: }}@container (width >= 992px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="1"]>.diagram-drawing{--_D: }}@container (width >= 1008px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="2"]>.diagram-drawing{--_D: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]>.diagram-drawing{--_D: }}@container (width >= 1080px){.diagram:not([data-layout])[data-type=data-flow][data-cols="5"]>.diagram-drawing{--_D: }}@container (width >= 1184px){.diagram:not([data-layout]):is([data-type=architecture][data-cols="6"][data-reach="0"],[data-type=flowchart][data-cols="6"])>.diagram-drawing{--_D: }}@container (width >= 1200px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="1"]>.diagram-drawing{--_D: }}@container (width >= 1216px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="2"]>.diagram-drawing{--_D: }}@container (width >= 1272px){.diagram:not([data-layout])[data-type=data-flow][data-cols="6"]>.diagram-drawing{--_D: }}@container (width >= 1312px){.diagram:not([data-layout])[data-type=schema][data-cols="5"]>.diagram-drawing{--_D: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]>.diagram-drawing{--_D: }}@media(scripting:none){.diagram:not(#basalt-diagram-no-id)>.diagram-drawing{--_D: initial}.diagram-list[hidden]{display:block!important}.diagram-foot,.diagram-entry[data-line],.diagram-hint{display:none}}@media(forced-colors:active){.diagram-svg,.diagram-swatch,.diagram-arrow{forced-color-adjust:none}.diagram .diagram-line,.diagram .diagram-line[data-kind]{stroke:CanvasText}.diagram .diagram-tip,.diagram .diagram-tip[data-kind],.diagram .diagram-dot{fill:CanvasText}.diagram .diagram-tip[data-open],.diagram .diagram-tip[data-kind][data-open]{fill:none;stroke:CanvasText}.diagram .diagram-edge[data-dim] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-dim] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:GrayText}.diagram .diagram-edge[data-dim] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-edge[data-lit] .diagram-line{stroke:Highlight}.diagram .diagram-edge[data-lit] :is(.diagram-tip:not([data-open]),.diagram-dot){fill:Highlight}.diagram .diagram-edge[data-lit] .diagram-tip[data-open]{stroke:Highlight}.diagram .diagram-life{stroke:GrayText}.diagram .diagram-label{color:CanvasText;forced-color-adjust:none}.diagram .diagram-label[data-on]{background:Canvas}.diagram .diagram-label[data-lit]{color:Highlight}.diagram .diagram-swatch-shape{fill:Canvas;stroke:CanvasText}.diagram .diagram-swatch[data-shape=group] .diagram-swatch-shape{fill:none;stroke:GrayText}.diagram .diagram-swatch[data-shape=focal] .diagram-swatch-shape{fill:CanvasText;stroke:CanvasText}.diagram[data-type=flowchart] .diagram-node:not([data-focal]),.diagram[data-type=flowchart] .diagram-node:not([data-focal])[data-near]{border-color:CanvasText}.diagram[data-measured][data-type=flowchart] .diagram-node[data-shape=decision][data-shape]{forced-color-adjust:none;background:none;border-color:transparent}.diagram .diagram-diamond{forced-color-adjust:none}.diagram .diagram-diamond path,.diagram .diagram-node[data-near] .diagram-diamond path{fill:Canvas;stroke:CanvasText}.diagram .diagram-group,.diagram .diagram-gbox{border-color:GrayText}.diagram .diagram-lane+.diagram-lane:before,.diagram .diagram-band:before{border-color:GrayText}.diagram .diagram-hint{color:GrayText}.diagram :is(.diagram-kind,.diagram-name,.diagram-detail,.diagram-glabel,.diagram-lane-name,.diagram-title,.diagram-source,.diagram-num,.diagram-mlabel,.diagram-route,.diagram-note,.diagram-band,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more,.diagram-legend,.diagram-fk-mark,.diagram-key-letters){color:CanvasText}.diagram .diagram-node:focus-visible{outline-color:Highlight}.diagram .diagram-node[data-focal],.diagram .diagram-node[data-focal][data-near]{forced-color-adjust:none;background:CanvasText;border-color:CanvasText}.diagram .diagram-node[data-focal] :is(.diagram-name,.diagram-kind,.diagram-detail,.diagram-tname,.diagram-cname,.diagram-keyseat,.diagram-ctype,.diagram-more){color:Canvas;opacity:1}.diagram .diagram-node[data-focal] .diagram-th{border-bottom-color:Canvas}.diagram .diagram-node[data-focal]:focus-visible{outline:var(--basalt-size-focus-width) solid Highlight}.diagram .diagram-node[data-focal][data-shape=decision] .diagram-diamond path{fill:CanvasText;stroke:CanvasText}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow{print-color-adjust:exact}.diagram-hint{display:none}}} diff --git a/.agent/skills/basalt-html/parts/diagram.js b/.agent/skills/basalt-html/parts/diagram.js index dd5a0a6f..8f079d3e 100644 --- a/.agent/skills/basalt-html/parts/diagram.js +++ b/.agent/skills/basalt-html/parts/diagram.js @@ -1 +1 @@ -(()=>{var Ut=["top","right","bottom","left"],Xt=["main","plain","dashed"],Jt=[2,3,4,5,6],tt=t=>t==null||t===""?void 0:String(t);function xt(t,e={}){const n=e.checks!==!1,o=[],a=c=>{o.push(c)},s=t.legend??{},r={};for(const c of["main","plain","dashed","focal","group"]){const p=tt(s[c]);p&&(r[c]=p)}const l=t.stepLabel,d=typeof l=="function"?c=>String(l(c)):typeof l=="string"?(c=>l.replace("{n}",String(c))):c=>`Step ${c}`,m=t.shapeLabels??{},h={terminal:tt(m.terminal)??"Start or end",step:tt(m.step)??"Step",decision:tt(m.decision)??"Decision"},i=t.heading===void 0?3:Jt.includes(t.heading)?t.heading:(a(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),f=(c,p)=>c==null?"plain":Xt.includes(c)?c:(a(`"${String(c)}" is not a kind of line (main, plain or dashed): ${p} is drawn plain`),"plain"),w=c=>{if(c!=null){if(Ut.includes(c))return c;a(`"${String(c)}" is not a side (top, right, bottom or left): the derived side is used`)}},y=(c,p)=>typeof c=="number"&&Number.isInteger(c)&&c>=1?c:(a(`${p} is ${JSON.stringify(c)}, not a whole number from 1: it is placed at 1`),1),u=[],g=[];let v=[];const T=[],E=[],M=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(M)||a(`"${String(M)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),M==="architecture"||M==="flowchart"){for(const c of t.nodes??[]){const p=M==="flowchart"&&c.shape==="decision"?"decision":M==="flowchart"&&c.shape==="terminal"?"terminal":"box",b=String(c.id??""),L=y(c.row,`the row of ${b}`);u.push({id:b,i:u.length,name:String(c.name??""),kind:p==="decision"?void 0:tt(c.kind),detail:p==="decision"?void 0:tt(c.detail),mono:!!c.detailMono,focal:!!c.focal,col:y(c.col,`the column of ${b}`),row:L,row2:L,branch:!!c.branch,shape:p,group:M==="architecture"?tt(c.group):void 0})}if(M==="architecture")for(const c of t.groups??[]){const p=String(c.id??"");T.push({id:p,label:String(c.label??""),members:u.filter(b=>b.group===p).map(b=>b.id)})}}else if(M==="data-flow"){v=(t.lanes??[]).map(p=>({id:String(p.id??""),label:String(p.label??"")}));const c=new Map(v.map((p,b)=>[p.id,b+1]));for(const p of t.nodes??[]){const b=String(p.id??""),L=String(p.lane??""),R=c.get(L);R===void 0&&a(`a node (${b}) names the lane "${L}", which is not in lanes`);const q=u.length+1;u.push({id:b,i:u.length,name:String(p.name??""),kind:d(q),detail:tt(p.detail),mono:!!p.detailMono,focal:!!p.focal,col:y(p.col,`the column of ${b}`),row:R??1,row2:R??1,branch:!1,shape:"box",lane:R??1,laneLabel:v[(R??1)-1]?.label??L,step:q})}}else if(M==="sequence"){(t.participants??[]).forEach((p,b)=>{const L=String(p.name??"");u.push({id:String(p.id??""),i:b,name:L,kind:tt(p.kind),mono:!1,focal:!!p.focal,col:b+1,row:1,row2:1,branch:!1,shape:"participant",short:tt(p.short)??L})});let c=0;for(const p of t.steps??[])"band"in p?E.push({band:String(p.band??"")}):(c++,E.push({n:c,from:String(p.from??""),to:String(p.to??""),label:String(p.label??""),note:tt(p.note),kind:f(p.kind,`message ${c}`)}))}else if(M==="schema")for(const c of t.tables??[]){const p=String(c.name??""),[b,L]=Array.isArray(c.row)?c.row:[c.row,c.row],R=y(b,`the row of ${p}`),q=Math.max(R,y(L,`the last row of ${p}`)),H=c.more===void 0||c.more===null?void 0:Number.isInteger(c.more)&&c.more>0?c.more:(a(`${p}'s "more" is ${JSON.stringify(c.more)}, not a whole number from 1: it is left out`),void 0);u.push({id:p,i:u.length,name:p,mono:!0,focal:!!c.focal,col:y(c.col,`the column of ${p}`),row:R,row2:q,branch:!1,shape:"table",more:H,columns:(c.columns??[]).map(O=>({name:String(O.name??""),type:tt(O.type),key:O.key==="PK"||O.key==="FK"?O.key:(O.key!==void 0&&O.key!==null&&a(`${p}.${String(O.name)}'s key is "${String(O.key)}", not PK or FK: it is left out`),void 0)}))})}const z=new Map;for(const c of u)c.id?z.has(c.id)&&a(`the id "${c.id}" is used twice`):a("a node has no id"),z.set(c.id,c);if(M==="schema")(t.tables??[]).forEach(c=>(c.columns??[]).forEach((p,b)=>{const L=tt(p.references);if(!L)return;const[R,q]=L.split("."),H=z.get(R??""),O=H?.columns?.findIndex(V=>V.name===q)??-1;if(!H||O<0){a(`${String(c.name)}.${String(p.name)} references ${L}, which is not a shown column`);return}const j=z.get(String(c.name??""));j.columns[b].ref={table:R,column:q,row:O},g.push({i:g.length,from:j.id,to:R,kind:"plain",fromRow:b,toRow:O,fk:!0})}));else if(M!=="sequence")for(const c of t.edges??[]){const p=String(c.from??""),b=String(c.to??"");if(!z.has(p)||!z.has(b)){a(`a line names ${z.has(p)?b:p}, which is not a node`);continue}const L=tt(c.label);L&&L.length>Mt&&a(`the label "${L}" is over ${Mt} characters: longer words belong in the node or the summary`),g.push({i:g.length,from:p,to:b,kind:f(c.kind,`the line from ${p} to ${b}`),label:L,fromSide:w(c.fromSide),toSide:w(c.toSide)})}else for(const c of E)"n"in c&&(!z.has(c.from)||!z.has(c.to))&&a(`message ${c.n} names ${z.has(c.from)?c.to:c.from}, which is not a participant`);if(n&&M!=="sequence"){const c=new Map;for(const p of u)for(let b=p.row;b<=p.row2;b++){const L=`${p.col}:${b}`;c.has(L)&&a(`${p.id} and ${c.get(L)} share the cell at column ${p.col}, row ${b}`),c.set(L,p.id)}}if(n){for(const p of T){const b=p.members.map(q=>z.get(q));if(!b.length)continue;const L={c1:Math.min(...b.map(q=>q.col)),c2:Math.max(...b.map(q=>q.col)),r1:Math.min(...b.map(q=>q.row)),r2:Math.max(...b.map(q=>q.row2))};for(const q of u)q.group!==p.id&&q.col>=L.c1&&q.col<=L.c2&&q.row>=L.r1&&q.row<=L.r2&&a(`${q.id} is inside the box of the group "${p.label}" but not a member`);const R=b.map(q=>q.i);Math.max(...R)-Math.min(...R)+1!==R.length&&a(`the members of the group "${p.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const p of u)p.group&&!T.some(b=>b.id===p.group)&&a(`${p.id} names the group "${p.group}", which is not in groups`);u.filter(p=>p.focal).length>1&&a("more than one node is focal: a diagram has one at most");const c=new Set(M==="sequence"?E.flatMap(p=>"n"in p?[p.kind]:[]):g.map(p=>p.kind));c.has("main")&&!r.main&&a("main lines are drawn but the legend has no words for them (legend.main)"),c.has("dashed")&&!r.dashed&&a("dashed lines are drawn but the legend has no words for them (legend.dashed)"),u.some(p=>p.focal)&&!r.focal&&a("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const $=Math.max(1,...u.map(c=>c.col)),A=M==="data-flow"?Math.max(1,v.length):Math.max(1,...u.map(c=>c.row2));return{type:M,title:String(t.title??""),heading:i,legend:r,nodes:u,byId:z,edges:g,groups:T,lanes:v,steps:E,cols:$,rows:A,shapeLabels:h,stepWord:d,warnings:o,memo:new Map}}function ht(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var Mt=28,it=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""},Yt=t=>t.charAt(0).toUpperCase()+t.slice(1);function vt(t,e){return t.legend[e]}function Qt(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function Pt(t,e){return ht(t,`sentence:${e.i}`,()=>te(t,e))}function te(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const o=(e.columns??[]).filter(s=>s.ref).map(s=>`${s.ref.table} (${s.name})`),a=t.edges.filter(s=>s.to===e.id).map(s=>`${s.from} (${t.byId.get(s.from).columns[s.fromRow].name})`);o.length&&n.push(`References ${o.join(", ")}.`),a.length&&n.push(`Referenced by ${a.join(", ")}.`)}else if(t.type==="sequence"){const o=t.steps.filter(s=>"n"in s&&s.from===e.id).length,a=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(it(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${o} ${o===1?"message":"messages"} and receives ${a}.`)}else{const o=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?Qt(t,e):e.kind;if(n.push(it(o?`${e.name}, ${o}`:e.name)),e.detail&&n.push(it(e.detail)),e.group){const r=t.groups.find(l=>l.id===e.group);r&&n.push(`In ${r.label}.`)}const a=t.edges.filter(r=>r.to===e.id).map(r=>`${t.byId.get(r.from).name}${r.label?` (${r.label})`:""}`),s=t.edges.filter(r=>r.from===e.id).map(r=>`${t.byId.get(r.to).name}${r.label?` (${r.label})`:""}`);a.length&&n.push(`From: ${a.join(", ")}.`),s.length&&n.push(`To: ${s.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(it(t.legend.focal)),n.join(" ")}function ee(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function x(t,e,...n){const o=[];for(const a of n.flat(1/0))a!=null&&a!==!1&&!Array.isArray(a)&&o.push(a);return{t,a:e??{},c:o}}var ne={"&":"&","<":"<",">":">",'"':""","'":"'"},st=t=>t.replace(/[&<>"']/g,e=>ne[e]),se=" br img input meta link hr path polygon polyline circle rect line ";function kt(t,e={}){if(typeof t=="string")return st(t);if("slot"in t)return e[t.slot]??"";if(!/^[a-z][a-z0-9]*$/.test(t.t))throw new Error(`diagram: "${t.t}" is not an element name`);let n="";for(const[o,a]of Object.entries(t.a))if(!(a==null||a===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(o))throw new Error(`diagram: "${o}" is not an attribute name`);n+=a===!0?` ${o}`:` ${o}="${st(String(a))}"`}return se.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(o=>kt(o,e)).join("")}</${t.t}>`}var oe=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function lt(t,e){return e.layout?e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema":!1}function ae(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function St(t){let e=0;for(const n of t.groups){const o=n.members.map(a=>t.byId.get(a).col);o.length&&(Math.min(...o)===1&&(e|=1),Math.max(...o)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function mt(t){return t.type==="sequence"?t.nodes.length:t.cols}function Et(t){return ht(t,"plan",()=>re(t))}function re(t){const e=t.nodes,n=u=>t.type==="data-flow"||!e[u].branch,o=t.edges.map(u=>{const g=t.byId.get(u.from).i,v=t.byId.get(u.to).i,E=e.slice(Math.min(g,v)+1,Math.max(g,v)).every(M=>!n(M.i));return v===g+1&&!(n(g)&&!n(v))?"down":v===g-1?"up":v>g&&n(g)&&!n(v)&&E?"trunk":v>g&&n(g)&&n(v)&&E?"rail":v>g?"end-down":"end-up"}),a=t.edges.map((u,g)=>({e:u,k:g})).filter(({k:u})=>o[u]==="end-down"||o[u]==="end-up"),s=u=>{const g=t.byId.get(u.from).i,v=t.byId.get(u.to).i;return[Math.min(g,v),Math.max(g,v)]},r=(u,g)=>{const[v,T]=s(u),[E,M]=s(g);return v<M&&E<T},l=a.every(({e:u})=>{const g=t.byId.get(u.from).i,[v,T]=s(u);return!n(g)&&e.slice(v+1,T).every(E=>!n(E.i))&&a.every(E=>E.e===u||!r(E.e,u))}),d=a.length>0&&(t.type==="data-flow"||!l),m=u=>{const[g,v]=s(u);return v-g},h=t.edges.map(()=>0);let i=!1;const f=[];for(const u of[...a].sort((g,v)=>m(g.e)-m(v.e)||g.k-v.k)){let g=0;for(const v of f)r(v.e,u.e)&&(g=Math.max(g,h[v.k]+1));h[u.k]=g,g>1&&(i=!0),f.push(u)}const w=t.edges.map(()=>.5);for(const u of e){const g=a.filter(({e:E})=>E.from===u.id);if(g.length<2)continue;const v=g.filter(({k:E})=>o[E]==="end-down").sort((E,M)=>m(M.e)-m(E.e)||E.k-M.k),T=g.filter(({k:E})=>o[E]==="end-up").sort((E,M)=>m(E.e)-m(M.e)||M.k-E.k);[...v,...T].forEach(({k:E},M,z)=>{w[E]=z.length===2?M===0?1/3:2/3:(M+1)/(z.length+1)})}const y={};for(let u=1;u<e.length;u++){const g=e[u],v=e[u-1];let T=0,E=t.type==="data-flow"?48:32,M=!1,z=!1;t.edges.forEach(($,A)=>{const c=o[A],p=t.byId.get($.from).i,b=t.byId.get($.to).i,L=b===u&&(c==="down"||c==="trunk"||c==="rail"||c==="end-down"),R=p===u&&b===u-1&&c==="up",q=b===u-1&&c==="end-up";L&&(c==="trunk"||c==="end-down")&&(M=!0),q&&(z=!0),(L||R||q)&&$.label&&(T++,E=Math.max(E,c==="trunk"?40:48))}),(T>1||M&&z)&&(E=64),y[g.id]=E}return{routes:o,gutter:d,lanes:h,exits:w,gaps:y,third:i}}var dt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function At(t,e){const n=e==="fk"?"plain":e,o=n==="main"?8:8.5,a=24,s=n==="dashed"?a-1:a-7;return x("svg",{class:`${t}-swatch`,"data-kind":n,...dt(24,16)},e==="fk"?x("circle",{class:`${t}-dot`,cx:3,cy:o,r:3}):null,x("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${o}H${s}`}),n==="dashed"?x("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${a-8} ${o-4}L${a} ${o}L${a-8} ${o+4}`}):x("path",{class:`${t}-tip`,"data-kind":n,d:`M${a} ${o}L${a-8} ${o-4}L${a-8} ${o+4}Z`}))}function ut(t,e){return e==="decision"?x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):x("svg",{class:`${t}-swatch`,"data-shape":e,...dt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function ie(t,e){return ht(e,`key:${t}`,()=>le(t,e))}function le(t,e){const n=[],o=(s,r,l={})=>n.push(x("li",{class:`${t}-entry`,...l},s,x("span",null,r)));if(e.type==="flowchart"){const s=new Set(e.nodes.map(r=>r.shape));s.has("terminal")&&o(ut(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&o(ut(t,"box"),e.shapeLabels.step),s.has("decision")&&o(ut(t,"decision"),e.shapeLabels.decision)}const a=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind));for(const s of["main","plain","dashed"]){const r=e.legend[s];a.has(s)&&r&&o(At(t,s),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(o(At(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"}),n.push(x("li",{class:`${t}-entry`,"data-when":"stacked"},x("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},"→"),x("span",null,"A foreign key, written in the row")))),e.nodes.some(s=>s.focal)&&e.legend.focal&&o(ut(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&o(ut(t,"group"),e.legend.group),n.length?x("div",{class:`${t}-key`},x("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function ce(t,e){const n=e==="main"?6:6.5;return x("svg",{class:`${t}-arrow`,"data-kind":e,...dt(20,12)},x("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?x("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):x("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function de(t,e,n){if(n.shape==="decision")return[x("span",{class:`${t}-words`},x("span",{class:`${t}-name`},n.name))];const o=[];return e.type==="data-flow"?o.push(x("span",{class:`${t}-kind`},n.kind,x("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&o.push(x("span",{class:`${t}-kind`},n.kind)),o.push(x("span",{class:`${t}-name`},n.name)),n.detail&&o.push(x("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.detail)),o}function ue(t,e){return[x("span",{class:`${t}-th`},x("span",{class:`${t}-tname`},e.name)),x("span",{class:`${t}-rows`},(e.columns??[]).map((n,o)=>x("span",{class:`${t}-row`,"data-row":o,"data-key":n.key},x("span",{class:`${t}-keyseat`},n.key??""),x("span",{class:`${t}-cname`},n.name),n.ref?x("span",{class:`${t}-ctype`,"data-ref":""},`→ ${n.ref.table}`):n.type?x("span",{class:`${t}-ctype`},n.type):null))),e.more?x("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Lt=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function yt(t,e,n,o){const{P:a}=t,s=ae(e,o)||o.keep===n.id,r=lt(e,o),l=[`--_c:${n.col}`,`--_r:${n.row}`,`--_r2:${n.row2+1}`];e.type==="data-flow"&&l.push(`--_lc:${n.col+1}`),e.type==="sequence"&&l.push(`--_c2:${n.col+1}`);const d=t.plan;if(d&&n.i>0){const h=d.gaps[n.id]??32,i=o.grow?.[n.id]??0;l.push(`--_gap:${i?`calc(${Lt(h)} + var(--basalt-space-4) * ${i})`:Lt(h)}`)}o.heights?.[n.id]&&l.push(`--_h:${o.heights[n.id]}px`);const m=r?o.stop===n.id?0:-1:o.keep===n.id?-1:void 0;return x("div",{class:`${a}-node`,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-level":t.level,style:l.join(";"),role:s?"img":void 0,"aria-label":s?Pt(e,n):void 0,tabindex:m},n.shape==="decision"?x("svg",{class:`${a}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},x("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.shape==="table"?ue(a,n):de(a,e,n))}function fe(t,e,n){const{P:o}=t,a=[];if(e.type==="data-flow"&&a.push(...e.lanes.map((r,l)=>x("div",{class:`${o}-lane`,style:`--_r:${l+1}`,"aria-hidden":"true"},x("span",{class:`${o}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const l=r.members.map(f=>e.byId.get(f));if(!l.length)continue;const d=Math.min(...l.map(f=>f.col)),m=Math.max(...l.map(f=>f.col)),h=Math.min(...l.map(f=>f.row)),i=Math.max(...l.map(f=>f.row2));a.push(x("div",{class:`${o}-gbox`,"data-group":r.id,style:`--_c:${d};--_c2:${m+1};--_r:${h};--_r2:${i+1}`,"aria-hidden":"true"},x("span",{class:`${o}-glabel`},r.label)))}if(e.type==="sequence")return a.push(x("ul",{class:`${o}-cast`},e.nodes.map(r=>x("li",{class:`${o}-actor`},yt(t,e,r,n))))),a.push(he(t,e)),a;let s=0;for(;s<e.nodes.length;){const r=e.nodes[s],l=r.group?e.groups.find(m=>m.id===r.group):void 0;if(!l){a.push(yt(t,e,r,n)),s++;continue}const d=[];for(;s<e.nodes.length&&e.nodes[s].group===l.id;)d.push(e.nodes[s++]);a.push(x("div",{class:`${o}-group`,"data-group":l.id},x("span",{class:`${o}-glabel`,"aria-hidden":"true"},l.label),d.map(m=>yt(t,e,m,n))))}return a}function he(t,e){const{P:n}=t,o=[];let a=null;for(const s of e.steps){if("band"in s){a=null,o.push(x("p",{class:`${n}-band`},x("span",null,s.band)));continue}a||(a=x("ol",{class:`${n}-msgs`,start:s.n}),o.push(a));const r=e.byId.get(s.from),l=e.byId.get(s.to),d=r?.col??1,m=l?.col??1,h=d===m,i=h&&d===e.nodes.length,f=vt(e,s.kind);a.c.push(x("li",{class:`${n}-msg`,"data-kind":s.kind,"data-from":s.from,"data-to":s.to,"data-self":h?i?"start":"end":void 0,style:`--_a:${Math.min(d,m)};--_b:${Math.max(d,m)+1}`},x("span",{class:`${n}-said`},x("span",{class:`${n}-num`},String(s.n)),x("span",{class:`${n}-mlabel`},s.label)),x("span",{class:`${n}-route`},r?.short??s.from," ",ce(n,s.kind),x("span",{class:t.hidden}," to ")," ",l?.short??s.to,f?` · ${f}`:""),s.note?x("span",{class:`${n}-note`},s.note):null))}return x("div",{class:`${n}-steps`},o)}function pe(t,e){return ht(e,`list:${t}`,()=>ge(t,e))}function ge(t,e){const n=Math.min(6,e.heading+1),o=h=>x(`h${n}`,{class:`${t}-list-head`},h),a=h=>x("strong",null,h),s=h=>x("code",{class:`${t}-code`},h),r=h=>e.byId.get(h)?.name??h,l=h=>{const i=vt(e,h);return i?` (${i})`:""},d=h=>h.focal&&e.legend.focal?` ${it(e.legend.focal)}`:"";if(e.type==="architecture"){const h=w=>x("li",null,a(w.name),w.kind?`, ${w.kind}`:"",w.detail?[". ",w.mono?s(w.detail):w.detail,/[.!?]$/.test(w.detail)?"":"."]:/[.!?]$/.test(w.kind??w.name)?"":".",d(w)),i=[o("Parts")],f=e.nodes.filter(w=>!w.group);f.length&&i.push(x("ul",{class:`${t}-list-items`},f.map(h)));for(const w of e.groups)i.push(x("p",{class:`${t}-list-group`},w.label)),i.push(x("ul",{class:`${t}-list-items`},w.members.map(y=>h(e.byId.get(y)))));return i.push(o("Connections")),i.push(x("ol",{class:`${t}-list-items`},e.edges.map(w=>x("li",null,a(r(w.from))," to ",a(r(w.to)),w.label?[": ",s(w.label)]:"",`${l(w.kind)}.`)))),i}if(e.type==="flowchart"){const h=i=>(e.byId.get(i)?.i??0)+1;return[x("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const f=e.edges.filter(u=>u.from===i.id),w=i.shape==="decision"?"Decision":i.shape==="terminal"?f.length?"Start":"End":"Step",y=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return x("li",null,a(i.name),i.detail?[", ",i.mono?s(i.detail):i.detail]:"",`${y}${w}.`,d(i),f.length?x("ul",{class:`${t}-list-exits`},f.map(u=>x("li",null,u.label?`If ${u.label}: go to ${h(u.to)}, `:`Then: go to ${h(u.to)}, `,a(r(u.to)),l(u.kind)))):null)}))]}if(e.type==="data-flow")return[x("ol",{class:`${t}-list-items`},e.nodes.map(h=>{const i=e.edges.filter(f=>f.from===h.id);return x("li",null,`${h.laneLabel}: `,a(h.name),h.detail?[", ",h.mono?s(h.detail):h.detail]:"",".",d(h),i.length?[" Then ",...i.flatMap((f,w)=>[w?"; ":"",`to step ${e.byId.get(f.to).step}, `,a(r(f.to)),f.label?[": ",s(f.label)]:"",l(f.kind)]),"."]:"")}))];if(e.type==="sequence"){const h=[o("Participants"),x("ul",{class:`${t}-list-items`},e.nodes.map(f=>x("li",null,a(f.name),f.kind?`, ${f.kind}`:"",".",d(f))))];h.push(o("Messages"));let i=null;for(const f of e.steps){if("band"in f){i=null,h.push(x(`h${n}`,{class:`${t}-list-group`},f.band));continue}i||(i=x("ol",{class:`${t}-list-items`,start:f.n}),h.push(i)),i.c.push(x("li",null,s(f.label),": ",a(r(f.from))," to ",a(r(f.to)),`${l(f.kind)}.`,f.note?` ${it(Yt(f.note))}`:""))}return h}const m=[];for(const h of e.nodes)m.push(x("p",{class:`${t}-list-group`},s(h.name),d(h))),m.push(x("ul",{class:`${t}-list-items`},[...(h.columns??[]).map(i=>x("li",null,s(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",s(`${i.ref.table}.${i.ref.column}`)]:i.type?`, ${i.type}`:"")),...h.more?[x("li",null,`and ${h.more} more ${h.more===1?"column":"columns"}`)]:[]]));return m}function me(t){return`Arrow keys move to the next or the previous ${t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step"}, in the author's order; Home and End go to the ends; Escape clears the trace.`}function ye(t){return[{keys:["←","→"],words:ee(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}function qt(t,e,n){const o=n.prefix,a=oe(n.base),s=t.type==="sequence"||t.type==="schema"?null:Et(t),r={P:o,ids:a,level:n.level,plan:s,hidden:n.hiddenClass},l=e.layout==="drawn",d=lt(t,e),m=t.type==="sequence"||t.type==="schema"?l:!0,h=`h${t.heading}`,i=[`--_cols:${mt(t)}`];if(t.type==="architecture"&&t.groups.length){const f=t.groups.flatMap(y=>y.members.map(u=>t.byId.get(u))),w=(y,u)=>y?`var(--basalt-space-${u})`:"0px";i.push(`--_gpad:${w(f.some(y=>y.row===1),"8")} ${w(f.some(y=>y.col===t.cols),"4")} ${w(f.some(y=>y.row2===t.rows),"4")} ${w(f.some(y=>y.col===1),"4")}`)}return t.type==="schema"&&e.track&&i.push(`--_track:${e.track}px`),x("figure",{class:n.className?`${o} ${n.className}`:o,"aria-labelledby":a.title,"data-type":t.type,"data-cols":mt(t),"data-reach":t.type==="architecture"?St(t):void 0,"data-gutter":s?.gutter?"":void 0,"data-layout":e.layout,"data-measured":e.layout?"":void 0,style:i.join(";")},x("div",{class:`${o}-head`},x(h,{id:a.title,class:`${o}-title`},t.title),n.hasSource?x("p",{class:`${o}-source`},{slot:"source"}):null),x("div",{class:`${o}-drawing`,role:m?"group":void 0,"aria-roledescription":m?"diagram":void 0,"aria-labelledby":m?a.title:void 0,"aria-describedby":m?`${a.summary} ${a.keys}`:void 0,"data-stops":d?"":void 0},fe(r,t,e),x("div",{class:`${o}-ink`,"aria-hidden":"true"}),x("span",{class:`${o}-ruler`,"aria-hidden":"true"})),ie(o,t),x("p",{class:`${o}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),x("div",{class:`${o}-foot`},{slot:"toggle"}),x("div",{id:a.list,class:`${o}-list`,hidden:!e.open},pe(o,t)),x("span",{id:a.keys,class:n.hiddenClass},me(t)),x("figcaption",{id:a.summary,class:`${o}-summary`},{slot:"summary"}))}function $e(t){const e=getComputedStyle(t),n=(a,s)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${a}`));return Number.isFinite(r)?r:s},o=new Map;return{space:a=>(o.has(a)||o.set(a,n(`space-${a}`,parseFloat(a.replace("-","."))*4)),o.get(a)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4)}}var pt=(t,e)=>t==="main"?e.line:e.hair,ot=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},at=(t,e,n=.01)=>t.l<e.r-n&&t.r>e.l+n&&t.t<e.b-n&&t.b>e.t+n,It=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function P(t,e,n){const{l:o,t:a,r:s,b:r}=t.rect,l=(o+s)/2,d=(a+r)/2,m=(s-o)/2,h=(r-a)/2,i=e==="top"||e==="bottom";if(t.shape==="decision"){if(i){const y=n,u=h*Math.max(0,1-Math.abs(y-l)/m);return{x:y,y:e==="top"?d-u:d+u}}const f=n,w=m*Math.max(0,1-Math.abs(f-d)/h);return{x:e==="left"?l-w:l+w,y:f}}if(t.shape==="terminal"){const f=Math.min(m,h);if(i){const g=n,v=Math.min(Math.max(g,o+f),s-f),T=g-v,E=Math.abs(T)>=f?0:Math.sqrt(f*f-T*T);return{x:g,y:Math.abs(T)<1e-6?e==="top"?a:r:e==="top"?d-E:d+E}}const w=n,y=w-d,u=Math.abs(y)>=f?0:Math.sqrt(f*f-y*y);return{x:e==="left"?o+f-u:s-f+u,y:w}}return i?{x:n,y:e==="top"?a:r}:{x:e==="left"?o:s,y:n}}function be(t,e,n){const{l:o,t:a,r:s,b:r}=e.rect,l=(o+s)/2,d=(a+r)/2,m=(s-o)/2,h=(r-a)/2;if(e.shape==="decision")return Math.abs(t.x-l)/m+Math.abs(t.y-d)/h<1-n/Math.min(m,h);if(e.shape==="terminal"){const i=Math.min(m,h),f=Math.min(Math.max(t.x,o+i),s-i);return Math.hypot(t.x-f,t.y-d)<i-n}return t.x>o+n&&t.x<s-n&&t.y>a+n&&t.y<r-n}function Ot(t,e){if(!at(t,e.rect))return!1;if(e.shape!=="decision"&&e.shape!=="terminal")return!0;const{l:n,t:o,r:a,b:s}=e.rect,r=(n+a)/2,l=(o+s)/2,d=(a-n)/2,m=(s-o)/2;if(e.shape==="decision"){const i=Math.max(t.l,Math.min(r,t.r)),f=Math.max(t.t,Math.min(l,t.b));return Math.abs(i-r)/d+Math.abs(f-l)/m<1-1e-6}const h=Math.min(m,d);if(at(t,{l:n+h,r:a-h,t:o,b:s}))return!0;for(const i of[n+h,a-h]){const f=Math.max(t.l,Math.min(i,t.r)),w=Math.max(t.t,Math.min(l,t.b));if(Math.hypot(f-i,w-l)<h-.01)return!0}return!1}function we(t,e,n){const o=Math.hypot(e.x-t.x,e.y-t.y),a=Math.max(2,Math.ceil(o/2));for(let s=1;s<a;s++){const r=s/a;if(!(r*o<1.5||(1-r)*o<1.5)&&be({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r},n,1))return!0}return!1}function xe(t,e){const n=t.querySelector(`.${e}-ruler`),o=new Map;return(a,s)=>{const r=`${s}|${a}`;return o.has(r)||(n.setAttribute("data-f",s),n.textContent=a,o.set(r,n.getBoundingClientRect().width),n.textContent=""),o.get(r)}}var $t=t=>t?t.split(/\s+/).filter(Boolean):[];function Me(t,e,n){const o=e.space;let a=e.node,s=e.table;for(const d of t.nodes){if(d.shape==="table"){for(const f of d.columns??[]){const w=f.ref?`→ ${f.ref.table}`:f.type??"",y=o("6")+n(f.name,"mono")+(w?o("3")+n(w,"mono"):0)+2*o("3")+2*e.hair;s=Math.max(s,Math.ceil(y))}s=Math.max(s,Math.ceil(n(d.name,"table")+2*o("3")+2*e.hair));continue}const m=d.shape==="terminal"?2*o("5"):2*o("3");let h=0;for(const f of $t(d.name))h=Math.max(h,n(f,d.shape==="decision"?"name-500":"name"));if(t.type!=="data-flow")for(const f of $t(d.kind))h=Math.max(h,n(f,"mono"));for(const f of $t(d.detail))h=Math.max(h,n(f,d.mono?"mono":"sans"));const i=d.shape==="decision"?h/.62:h+m+2*e.hair;a=Math.max(a,Math.ceil(i))}const r=mt(t);let l;return t.type==="data-flow"?l=e.lane+r*(a+o("12")):t.type==="schema"?l=r*s+(r-1)*o("12"):t.type==="sequence"?l=r*a+(r-1)*o("5"):l=r*a+(r-1)*o("16")+St(t)*o("4"),{track:a,table:s,least:Math.max(e.wide,l)}}function _t(t,e){return{x:(n,o)=>o%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,o)=>o%2===1?Math.round(n+e-.5)+.5-e:Math.round(n+e)-e}}function bt(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ct(t,e,n){const o=t.map(s=>({...s}));for(let s=1;s<o.length;s++){const r=o[s-1],l=o[s];if(Math.abs(r.x-l.x)<.75){const d=n.x(r.x,e);r.x=d,l.x=d}else if(Math.abs(r.y-l.y)<.75){const d=n.y(r.y,e);r.y=d,l.y=d}}const a=[o[0]];for(let s=1;s<o.length;s++){const r=o[s],l=a[a.length-1];if(!(Math.abs(r.x-l.x)<.01&&Math.abs(r.y-l.y)<.01)){if(a.length>=2){const d=a[a.length-2];if(Math.abs(d.x-l.x)<.01&&Math.abs(l.x-r.x)<.01||Math.abs(d.y-l.y)<.01&&Math.abs(l.y-r.y)<.01){a[a.length-1]=r;continue}}a.push(r)}}return a}var ct=t=>t.slice(1).map((e,n)=>[t[n],e]);function gt(t,e,n){const o=[];for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++){const l=t[s],d=t[r];if(!(n&&!n.has(l.i)&&!n.has(d.i)))for(const[m,h]of ct(l.pts))for(const[i,f]of ct(d.pts)){const w=Math.abs(m.y-h.y)<.01,y=Math.abs(i.y-f.y)<.01;if(w===y)continue;const[u,g,v,T]=w?[m,h,i,f]:[i,f,m,h],E=v.x,M=u.y;if(E>Math.min(u.x,g.x)+.75&&E<Math.max(u.x,g.x)-.75&&M>Math.min(v.y,T.y)+.75&&M<Math.max(v.y,T.y)-.75){const z=w?s:r,$=w?r:s;let A=z,c=$;if(e){const p=e(t[z]);e(t[$])&&!p&&(A=$,c=z)}o.push({top:A,under:c,at:{x:E,y:M},underVertical:c===$})}}}return o}function ve(t){const e=getComputedStyle(t),n=a=>a.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),o=(a,s,r)=>{const l=[];let d=s;for(const m of a)l.push([d,d+m]),d+=m+r;return l};return{cols:o(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:o(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var Z=t=>t==="left"||t==="right",Bt={top:"bottom",bottom:"top",left:"right",right:"left"};function ke(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function Se(t,e,n){const o=[];t.edges.forEach((s,r)=>{const l=t.byId.get(s.from),d=t.byId.get(s.to),[m,h]=e[r],i=l.row===d.row&&Z(m)&&Z(h)&&m===Bt[h]||l.col===d.col&&!Z(m)&&!Z(h)&&m===Bt[h];o.push({edge:r,end:"from",node:l,side:m,far:d,straight:i,f:.5},{edge:r,end:"to",node:d,side:h,far:l,straight:i,f:.5})});const a=new Map;for(const s of o){const r=`${s.node.id}.${s.side}`;a.has(r)||a.set(r,[]),a.get(r).push(s)}for(const[s,r]of a){if(r[0].node.shape==="decision")continue;const l=i=>Z(i.side)?i.far.row-i.node.row:i.far.col-i.node.col,d=r.filter(i=>i.straight),m=r.filter(i=>!i.straight);m.sort((i,f)=>l(i)-l(f)||(Z(i.side)?i.far.col-f.far.col:i.far.row-f.far.row)*(l(i)<0?1:-1)),r.length>3&&n(`${s.replace("."," has ")} has ${r.length} lines on one side; more than three is an error: use another side`),d.length?m.forEach(i=>{i.f=l(i)<0?.25:.75}):m.length===2?(m[0].f=.25,m[1].f=.75):m.length===3?(m[0].f=.25,m[1].f=.5,m[2].f=.75):m.length>3&&m.forEach((i,f)=>{i.f=(f+1)/(m.length+1)});const h=new Map;for(const i of d)h.has(i.far.id)||h.set(i.far.id,[]),h.get(i.far.id).push(i);for(const i of h.values())i.length>1&&i.sort((f,w)=>f.edge-w.edge).forEach((f,w)=>{f.f=i.length===2?w===0?.25:.75:(w+1)/(i.length+1)})}return o}function Tt(t,e,n){const{l:o,t:a,r:s,b:r}=t.rect;return Z(e)?P(t,e,a+(r-a)*n):P(t,e,o+(s-o)*n)}function Rt(t,e,n,o){const a=new Map;return e.querySelectorAll(`.${o}-node`).forEach(s=>{const r=t.byId.get(s.dataset.node);r&&a.set(r.id,{id:r.id,rect:ot(s,n),shape:r.shape,i:r.i})}),a}function jt(t,e){const n=e.head,o=e.head/2,{x:a,y:s}=t.tip;return t.dir==="down"?{l:a-o,r:a+o,t:s-n,b:s}:t.dir==="up"?{l:a-o,r:a+o,t:s,b:s+n}:t.dir==="right"?{l:a-n,r:a,t:s-o,b:s+o}:{l:a,r:a+n,t:s-o,b:s+o}}var Ft=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function Ee(t,e,n,o,a,s,r,l){const d=r.space,m=[],h=[],i=[],f=d("1"),w=e.filter(y=>t.edges[y.i]?.label).sort((y,u)=>+(t.edges[u.i].kind==="main")-+(t.edges[y.i].kind==="main")||y.i-u.i);for(const y of w){const u=t.edges[y.i].label,g=l(u,"label"),v=16,T=y.pts.length-2,E=[];ct(y.pts).forEach(([$,A],c)=>{const p=Math.abs($.y-A.y)<.01,b=p?$.x:$.y;let L=p?A.x:A.y;const R=Math.sign(L-b)||1;c===T&&(L-=R*r.head);let q=[[b,L]];for(const O of a)for(const j of p?[O.l,O.r]:[O.t,O.b]){const V=p?$.y:$.x;(p?V>O.t&&V<O.b:V>O.l&&V<O.r)&&(q=q.flatMap(([S,C])=>j>Math.min(S,C)+1&&j<Math.max(S,C)-1?[[S,j],[j,C]]:[[S,C]]))}const H=(O,j)=>{const V=(O+j)/2,J=p?{x:V,y:$.y}:{x:$.x,y:V};return!a.some(S=>J.x>S.l&&J.x<S.r&&J.y>S.t&&J.y<S.b)};for(const[O,j]of q)E.push({horiz:p,c:p?$.y:$.x,p:O,q:j,len:Math.abs(j-O),pri:q.length>1&&H(O,j)?1:0})}),E.sort(($,A)=>A.pri-$.pri||A.len-$.len);let M=null;const z=$=>{const A=It($,f);return $.l<s.l||$.r>s.r||$.t<s.t||$.b>s.b||n.some(c=>Ot(A,c))||m.some(c=>at(A,c))||o.heads.some(c=>at(A,c))||o.rects.some(c=>at(A,c))?!1:!e.some(c=>c.i!==y.i&&ct(c.pts).some(([p,b])=>at(A,Ft(p,b,c.width))))};for(const $ of E){for(const A of[1/2,1/3,2/3]){const c=$.p+($.q-$.p)*A,p=[],b=d("2")+y.width/2;if($.horiz?($.len>=g+2*d("1")+d("3-5")&&p.push({box:{l:c-g/2-d("1"),r:c+g/2+d("1"),t:$.c-v/2,b:$.c+v/2},on:!0}),p.push({box:{l:c-g/2,r:c+g/2,t:$.c-b-v,b:$.c-b},on:!1}),p.push({box:{l:c-g/2,r:c+g/2,t:$.c+b,b:$.c+b+v},on:!1})):($.len>=v+d("3")&&p.push({box:{l:$.c-g/2-d("1"),r:$.c+g/2+d("1"),t:c-v/2,b:c+v/2},on:!0}),p.push({box:{l:$.c+b,r:$.c+b+g,t:c-v/2,b:c+v/2},on:!1}),p.push({box:{l:$.c-b-g,r:$.c-b,t:c-v/2,b:c+v/2},on:!1})),M=p.find(L=>z(L.box))??null,M)break}if(M)break}if(!M){i.push(y.i);continue}m.push(M.box),h.push({i:y.i,text:u,box:M.box,on:M.on})}return{labels:h,unseated:i}}function Ht(t,e,n,o){const a=[],s=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const l=ot(r,e);s.push(l),a.push({l:l.l,r:l.r,t:l.t,b:l.t+1},{l:l.l,r:l.r,t:l.b-1,b:l.b},{l:l.l,r:l.l+1,t:l.t,b:l.b},{l:l.r-1,r:l.r,t:l.t,b:l.b});const d=r.querySelector(`:scope > .${n}-glabel`);d&&d.getClientRects().length&&a.push(ot(d,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,l)=>{if(!r.getClientRects().length)return;const d=ot(r,e);l>0&&a.push({l:d.l,r:d.r,t:d.t-o/2-.5,b:d.t-o/2+.5});const m=r.querySelector(`.${n}-lane-name`);m&&a.push(ot(m,e))}),{obstacles:{rects:a,heads:[]},groups:s}}function Ae(t,e){const{m:n,tk:o,P:a,drawing:s,origin:r,warn:l}=t,d=o.space,m=Rt(n,s,r,a),h=[...m.values()],i=ve(s),f=r.left-Math.floor(r.left),w=r.top-Math.floor(r.top),y=_t(f,w),u=s.clientWidth,g=s.clientHeight,v=S=>n.type==="data-flow"?S.col+1:S.col,T=parseFloat(getComputedStyle(s).rowGap)||0,E={w:u,h:g,nodes:h,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:f,oy:w};if(n.type==="sequence")return Le(t,E,y);let M,z=[];n.type==="schema"?M=n.edges.map(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to);if(C.col===B.col){const k=C.col===n.cols?"left":"right";return[k,k]}return B.col>C.col?["right","left"]:["left","right"]}):(M=n.edges.map(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to),[k,_]=ke(C,B);return[S.fromSide??k,S.toSide??_]}),z=Se(n,M,l??(()=>{})));const $=(S,C)=>{const B=s.querySelector(`.${a}-node[data-node="${CSS.escape(S)}"] .${a}-row[data-row="${C}"]`);if(!B)return 0;const k=ot(B,r);return(k.t+k.b)/2},A=n.edges.map((S,C)=>{const[B,k]=M[C],_=m.get(S.from),N=m.get(S.to),D=pt(S.kind,o);if(S.fk){const I=y.y($(S.from,S.fromRow),D),G=y.y($(S.to,S.toRow),D);return{p1:{x:B==="right"?_.rect.r:_.rect.l,y:I},p2:{x:k==="right"?N.rect.r:N.rect.l,y:G}}}const Y=z.find(I=>I.edge===C&&I.end==="from").f,K=z.find(I=>I.edge===C&&I.end==="to").f;let F=Tt(_,B,Y),W=Tt(N,k,K);return Z(B)?F={...F,y:y.y(F.y,D)}:F={...F,x:y.x(F.x,D)},Z(k)?W={...W,y:y.y(W.y,D)}:W={...W,x:y.x(W.x,D)},Z(B)&&Z(k)&&Math.abs(F.y-W.y)<1.01&&(W={...W,y:F.y}),!Z(B)&&!Z(k)&&Math.abs(F.x-W.x)<1.01&&(W={...W,x:F.x}),F=Z(B)?P(_,B,F.y):P(_,B,F.x),W=Z(k)?P(N,k,W.y):P(N,k,W.x),{p1:F,p2:W}}),c=new Map;n.edges.forEach((S,C)=>{const[B,k]=M[C],{p1:_,p2:N}=A[C],D=n.byId.get(S.from),Y=n.byId.get(S.to);let K=null,F=null,W=!1;if(Z(B)&&Z(k)&&B!==k&&Math.abs(_.y-N.y)>.5){const U=v(Y),et=k==="left",X=i.cols[(et?U-1:U)-1],Q=i.cols[(et?U:U+1)-1];X&&Q&&(K=`c${et?U-1:U}`,F=[X[1],Q[0]],W=!0)}else if(!Z(B)&&!Z(k)&&B!==k&&Math.abs(_.x-N.x)>.5){const et=k==="top"?Y.row-1:Y.row2,X=i.rows[et-1],Q=i.rows[et];X&&Q&&(K=`r${et}`,F=[X[1],Q[0]],W=!1)}if(!K||!F)return;c.has(K)||c.set(K,{span:F,vertical:W,members:new Map});const I=`${S.to}.${k}.${Math.round(W?N.y:N.x)}`,G=c.get(K);G.members.has(I)||G.members.set(I,[]),G.members.get(I).push(C)});const p=new Map,b=S=>{const[C,B]=M[S],{p1:k,p2:_}=A[S];if(Z(C)&&Z(B)){if(C===B){const D=C==="right"?Math.max(k.x,_.x)+d("4"):Math.min(k.x,_.x)-d("4");return[k,{x:D,y:k.y},{x:D,y:_.y},_]}if(Math.abs(k.y-_.y)<=.5)return[k,{x:_.x,y:k.y}];const N=p.get(S)??(k.x+_.x)/2;return[k,{x:N,y:k.y},{x:N,y:_.y},_]}if(!Z(C)&&!Z(B)){if(C===B){const D=C==="bottom"?Math.max(k.y,_.y)+d("4"):Math.min(k.y,_.y)-d("4");return[k,{x:k.x,y:D},{x:_.x,y:D},_]}if(Math.abs(k.x-_.x)<=.5)return[k,{x:k.x,y:_.y}];const N=p.get(S)??(k.y+_.y)/2;return[k,{x:k.x,y:N},{x:_.x,y:N},_]}return Z(C)?[k,{x:_.x,y:k.y},_]:[k,{x:k.x,y:_.y},_]},L=S=>{const C=n.edges[S],B=pt(C.kind,o),k=Ct(b(S),B,y);return{i:S,from:C.from,to:C.to,kind:C.kind,pts:k,tip:k[k.length-1],dir:bt(k),dot:C.fk?k[0]:void 0,width:B}},R=()=>n.edges.map((S,C)=>L(C));let q=null;const H=S=>{q??(q=R());const C=q.map(B=>S.has(B.i)?L(B.i):B);return{lines:C,score:gt(C,void 0,S).length*1e3+wt(C.filter(B=>S.has(B.i)),h,n).length}},O=(S,C)=>{const B=S.flatMap(k=>{const{p1:_,p2:N}=A[k];return C?[_.y,N.y]:[_.x,N.x]});return[Math.min(...B),Math.max(...B)]};for(const[,S]of c){const C=[...S.members.values()].map(k=>({members:k,run:O(k,S.vertical)})).sort((k,_)=>k.run[0]-_.run[0]),B=[];for(const k of C){const _=B[B.length-1];_&&_.some(N=>N.run[0]<k.run[1]+d("8")&&k.run[0]<N.run[1]+d("8"))?_.push(k):B.push([k])}for(const k of B){const _=k.map(I=>I.members),N=_.length,D=(S.span[1]-S.span[0])/(N+1);D<d("3")&&l?.(`a gutter holds ${N} lanes side by side, closer than space-3`);const Y=new Set(_.flat());let K=_,F=1/0,W=null;for(const I of Nt(_)){I.forEach((U,et)=>U.forEach(X=>p.set(X,S.span[0]+D*(et+1))));const G=H(Y);G.score<F&&(F=G.score,K=I,W=G.lines)}K.forEach((I,G)=>I.forEach(U=>p.set(U,S.span[0]+D*(G+1)))),q=W}}E.lines=R(),n.type==="schema"&&(E.lines=E.lines.filter(S=>{const C=n.byId.get(S.from),B=n.byId.get(S.to);return Math.abs(C.col-B.col)>1?(l?.(`${S.from} to ${S.to} is two columns apart, so its line is not drawn; its row still writes the target`),!1):!0})),E.crossings=gt(E.lines),E.through=wt(E.lines,h,n),E.outside=zt(E.lines,u,g,o);const{obstacles:j,groups:V}=Ht(s,r,a,T);j.heads=E.lines.map(S=>jt(S,o));const J=Ee(n,E.lines,h,j,V,{l:0,t:0,r:u,b:g},o,e);return E.labels=J.labels,E.unseated=J.unseated,E}function*Nt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e<t.length;e++){const n=t.slice(0,e).concat(t.slice(e+1));for(const o of Nt(n))yield[t[e],...o]}}function zt(t,e,n,o){const a=[];for(const s of t)s.pts.some((r,l)=>{const d=l===s.pts.length-1?Math.max(s.width/2,o.head/2):s.width/2;return r.x-d<-.5||r.x+d>e+.5||r.y-d<-.5||r.y+d>n+.5})&&a.push(s.i);return a}function wt(t,e,n){const o=[];for(const a of t){const s=ct(a.pts);e.some(r=>s.some(([l,d])=>we(l,d,r)))&&o.push(a.i)}return o}function Le(t,e,n){const{m:o,tk:a,P:s,drawing:r,origin:l}=t,d=a.space,m=new Map;r.querySelectorAll(`.${s}-node`).forEach(y=>m.set(y.dataset.node,ot(y,l)));const h=r.querySelector(`.${s}-steps`),i=h?ot(h,l).b:e.h,f=y=>{const u=m.get(y);return u?n.x((u.l+u.r)/2,a.hair):0};for(const y of o.nodes){const u=m.get(y.id);u&&e.lifelines.push({x:f(y.id),y1:u.b,y2:i})}const w=y=>m.get(y.id);return r.querySelectorAll(`.${s}-msg`).forEach(y=>{const u=y.dataset.from,g=y.dataset.to,v=y.dataset.kind??"plain",T=pt(v,a),E=ot(y,l),M=n.y((E.t+E.b)/2,T),z=Number(y.querySelector(`.${s}-num`)?.textContent??0),$=f(u),A=f(g);let c;if(u===g){const O=y.dataset.self==="start"?-d("6"):d("6"),j=n.y(M-d("2"),T),V=n.y(M+d("2"),T);c=[{x:$,y:j},{x:n.x($+O,T),y:j},{x:n.x($+O,T),y:V},{x:$,y:V}]}else c=[{x:$,y:M},{x:A,y:M}];e.lines.push({i:z,from:u,to:g,kind:v,pts:c,tip:c[c.length-1],dir:bt(c),width:T});const p=y.querySelector(`.${s}-said`),b=y.querySelector(`.${s}-note`),L=o.byId.get(u),R=o.byId.get(g);if(!L||!R)return;const q=u===g?(()=>{const O=o.nodes[L.i+(y.dataset.self==="start"?-1:1)],j=O?f(O.id):y.dataset.self==="start"?0:e.w;return Math.abs(j-$)-d("6")-d("2-5")-d("2")})():Math.abs(A-$)-2*d("2");Math.max(p?p.getBoundingClientRect().width:0,b?b.getBoundingClientRect().width:0)>q+.5&&e.unseated.push(z)}),e}function Wt(t,e,n){const{m:o,tk:a,P:s,drawing:r,origin:l}=t,d=a.space,m=Rt(o,r,l,s),h=[...m.values()],i=l.left-Math.floor(l.left),f=l.top-Math.floor(l.top),w=_t(i,f),y=r.clientWidth,u=r.clientHeight,g={w:y,h:u,nodes:h,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:i,oy:f},v={};if(o.type==="sequence"||o.type==="schema")return{geo:g,grow:v};const T=new Map;r.querySelectorAll(`.${s}-node`).forEach(b=>{const L=b.parentElement,R=ot(L,l),q=getComputedStyle(L);T.set(b.dataset.node,R.r-(parseFloat(q.paddingRight)||0)-(parseFloat(q.borderRightWidth)||0))});const E=o.nodes,M=b=>m.get(E[b].id),z=[],$=b=>pt(o.edges[b].kind,a);o.edges.forEach((b,L)=>{const R=n.routes[L],q=m.get(b.from),H=m.get(b.to),O=$(L);let j=[];const V=b.label,J=V?e(V,"label"):0,S=16,C=d("4");if(R==="down"||R==="up"){const k=Math.max(q.rect.l,H.rect.l),_=Math.min(q.rect.r,H.rect.r),N=o.edges.map((F,W)=>({o:F,j:W})).filter(({o:F,j:W})=>(n.routes[W]==="down"||n.routes[W]==="up")&&(F.from===b.from&&F.to===b.to||F.from===b.to&&F.to===b.from)),D=N.findIndex(F=>F.j===L),Y=N.length<2?.5:N.length===2?D===0?.25:.75:(D+1)/(N.length+1),K=w.x(k+(_-k)*Y,O);if(j=R==="down"?[P(q,"bottom",K),P(H,"top",K)]:[P(q,"top",K),P(H,"bottom",K)],V){let F=Math.min(j[0].y,j[1].y),W=Math.max(j[0].y,j[1].y);R==="down"?W-=a.head:F+=a.head;const I=[...r.querySelectorAll(`.${s}-group`)].map(X=>ot(X,l));let G=[[F,W]];for(const X of I)for(const Q of[X.t,X.b])G=G.flatMap(([nt,rt])=>Q>nt+1&&Q<rt-1?[[nt,Q],[Q,rt]]:[[nt,rt]]);const U=(X,Q)=>I.some(nt=>(X+Q)/2>nt.t&&(X+Q)/2<nt.b&&K>nt.l&&K<nt.r);if(G.length>1){const X=G.filter(([nt,rt])=>!U(nt,rt));[F,W]=(X.length?X:G).reduce((nt,rt)=>rt[1]-rt[0]>nt[1]-nt[0]?rt:nt)}const et=[1/2,1/3,2/3].map(X=>{const Q=F+(W-F)*X;return{l:K-J/2-d("1"),r:K+J/2+d("1"),t:Q-S/2,b:Q+S/2}});z.push({k:L,cands:et,on:!0,card:R==="down"?b.to:b.from})}}else if(R==="trunk"||R==="rail"){const k=w.x(Math.max(q.rect.l,R==="rail"?H.rect.l:q.rect.l)+d(R==="trunk"?"8":"3"),O),_=P(q,"bottom",k);if(R==="rail"){if(j=[_,P(H,"top",k)],V){const N=H.rect.t-d("6");z.push({k:L,cands:[{l:k+d("2-5"),r:k+d("2-5")+J,t:N-S/2,b:N+S/2}],on:!1,card:b.to})}}else{const N=w.x(H.rect.l+d("6"),O),D=w.y(H.rect.t-C,O);j=[_,{x:k,y:D},{x:N,y:D},P(H,"top",N)],V&&z.push({k:L,cands:[{l:N+d("2-5"),r:N+d("2-5")+J,t:D-S/2,b:D+S/2}],on:!1,card:b.to})}}else{const k=Math.min(T.get(b.from)??y,T.get(b.to)??y),_=w.x(n.gutter?k+(n.lanes[L]?2*d("3-5"):d("3-5")):k-d("2-5"),O),N=w.y(q.rect.t+(q.rect.b-q.rect.t)*n.exits[L],O),D=P(q,"right",N),Y=w.x(H.rect.r-d("6"),O),K=R==="end-down",F=w.y(K?H.rect.t-C:H.rect.b+C,O);j=[D,{x:_,y:D.y},{x:_,y:F},{x:Y,y:F},P(H,K?"top":"bottom",Y)],V&&z.push({k:L,cands:[{l:Y-d("2-5")-J,r:Y-d("2-5"),t:F-S/2,b:F+S/2}],on:!1,card:K?b.to:E[H.i+1]?.id??b.to})}const B=Ct(j,O,w);g.lines.push({i:L,from:b.from,to:b.to,kind:b.kind,pts:B,tip:B[B.length-1],dir:bt(B),width:O})}),g.crossings=gt(g.lines),g.through=wt(g.lines,h,o),g.outside=zt(g.lines,y,u,a);const{obstacles:A}=Ht(r,l,s,0);A.heads=g.lines.map(b=>jt(b,a));const c=[],p={l:0,t:0,r:y,b:u};for(const b of z){const L=H=>{const O=It(H,d("1"));return H.l<p.l-.5||H.r>p.r+.5||H.t<p.t-.5||H.b>p.b+.5||h.some(j=>Ot(O,j))||c.some(j=>at(O,j))||A.heads.some(j=>at(O,j))||A.rects.some(j=>at(O,j))||g.lines.some(j=>j.i!==b.k&&ct(j.pts).some(([V,J])=>at(O,Ft(V,J,j.width))))},R=b.cands.find(H=>!L(H));R||(v[b.card]=(v[b.card]??0)+1,g.unseated.push(b.k));const q=R??b.cands[0];c.push(q),g.labels.push({i:b.k,text:o.edges[b.k].label,box:q,on:b.on})}return{geo:g,grow:v}}function qe(t,e){const n=s=>String(Math.round(s*100)/100);let o=`M${n(t[0].x)} ${n(t[0].y)}`;for(let s=1;s<t.length-1;s++){const r=t[s-1],l=t[s],d=t[s+1],m=Math.hypot(l.x-r.x,l.y-r.y),h=Math.hypot(d.x-l.x,d.y-l.y),i=Math.min(e,m/2,h/2);if(i<.5){o+=`L${n(l.x)} ${n(l.y)}`;continue}const f={x:l.x+(r.x-l.x)/m*i,y:l.y+(r.y-l.y)/m*i},w={x:l.x+(d.x-l.x)/h*i,y:l.y+(d.y-l.y)/h*i};o+=`L${n(f.x)} ${n(f.y)}Q${n(l.x)} ${n(l.y)} ${n(w.x)} ${n(w.y)}`}const a=t[t.length-1];return`${o}L${n(a.x)} ${n(a.y)}`}var Ie={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function Oe(t,e,n,o,a){const s=Ie[e.dir],r=e.kind==="dashed",l=n.head,d=n.head/2,m=r?1:l-1,h=e.pts.map(M=>({...M})),i=h[h.length-1];i.x-=s.x*m,i.y-=s.y*m;const f=e.tip.x-s.x*l,w=e.tip.y-s.y*l,y=-s.y*d,u=s.x*d,g=M=>Math.round(M*100)/100,v=st(e.kind),T=r?`<path class="${t}-tip" data-kind="${v}" data-open="" d="M${g(f+y)} ${g(w+u)}L${g(e.tip.x)} ${g(e.tip.y)}L${g(f-y)} ${g(w-u)}"/>`:`<path class="${t}-tip" data-kind="${v}" d="M${g(e.tip.x)} ${g(e.tip.y)}L${g(f+y)} ${g(w+u)}L${g(f-y)} ${g(w-u)}Z"/>`,E=e.dot?`<circle class="${t}-dot" cx="${g(e.dot.x)}" cy="${g(e.dot.y)}" r="${n.dot/2}"/>`:"";return`<g class="${t}-edge" data-edge="${e.i}" data-from="${st(e.from)}" data-to="${st(e.to)}"><path class="${t}-line" data-kind="${v}" d="${qe(h,a)}"${o?` mask="url(#${st(o)})"`:""}/>${T}${E}</g>`}function Gt(t,e,n,o){const a=new Map,s=new Map;for(const l of e.crossings)s.has(l.under)||s.set(l.under,[]),s.get(l.under).push(l);let r="";for(const[l,d]of s){const m=`${o}-cut-${l}`;a.set(l,m);const h=d.map(i=>{const f=e.lines[i.top],w=e.lines[i.under],y=f.width/2+n.cut,u=w.width/2+1;return i.underVertical?`<rect x="${i.at.x-u}" y="${i.at.y-y}" width="${2*u}" height="${2*y}" fill="black"/>`:`<rect x="${i.at.x-y}" y="${i.at.y-u}" width="${2*y}" height="${2*u}" fill="black"/>`}).join("");r+=`<mask id="${st(m)}" maskUnits="userSpaceOnUse" x="0" y="0" width="${e.w}" height="${e.h}"><rect x="0" y="0" width="${e.w}" height="${e.h}" fill="white"/>${h}</mask>`}return{defs:r,ids:a}}function Dt(t,e,n,o){const{defs:a,ids:s}=Gt(t,e,n,o),r=e.lifelines.map(h=>`<path class="${t}-life" d="M${h.x} ${h.y1}V${h.y2}"/>`).join(""),l=e.lines.map((h,i)=>Oe(t,h,n,s.get(i)??null,h.from===h.to?n.radiusXs:n.radius)).join(""),d=`<svg class="${t}-svg" width="${e.w}" height="${e.h}" viewBox="0 0 ${e.w} ${e.h}" focusable="false">${a?`<defs>${a}</defs>`:""}${r}<g class="${t}-edges">${l}</g></svg>`,m=e.labels.map(h=>`<span class="${t}-label" data-edge="${h.i}"${h.on?' data-on=""':""} style="left:${Math.round(h.box.l*100)/100}px;top:${Math.round(h.box.t*100)/100}px;width:${Math.round((h.box.r-h.box.l)*100)/100}px">${st(h.text)}</span>`).join("");return d+m}function _e(t,e,n,o,a,s,r){const l=t.querySelector(`.${n}-drawing`);if(!l)return{dyn:a,geo:null,ink:"",tokens:null};const d=$e(t),m=xe(l,n),h=Me(e,d,m),i=t.clientWidth,f=(()=>{const $=document.activeElement;return $&&l.contains($)&&$.dataset.node?$.dataset.node:void 0})(),w=$=>lt(e,$)?{...$,stop:$.stop&&e.byId.has($.stop)?$.stop:e.nodes[0]?.id,keep:void 0}:{...$,stop:$.stop??e.nodes[0]?.id,keep:f&&$.layout!=="drawn"?f:void 0},y=$=>{if(e.type!=="flowchart")return $;s({...$,heights:void 0});const A={};return l.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(c=>{const p=c.querySelector(`.${n}-words`);if(!p)return;const b=c.getBoundingClientRect(),L=p.getBoundingClientRect(),R={w:L.width+2*d.space("2-5"),h:L.height+2*d.space("2")},q=b.width/2,H=1-R.w/2/q,O=H>.05?R.h/2/H:R.h*10;A[c.dataset.node]=Math.max(d.space("16"),Math.ceil(b.width/5),Math.ceil(2*O))}),{...$,heights:A}},u=()=>({m:e,tk:d,P:n,drawing:l,origin:l.getBoundingClientRect(),warn:r}),g=($,A)=>A.map(c=>ft(e,$.lines.find(p=>p.i===c))).join(", ");if(i>=h.least){let $=w({...a,layout:"drawn",grow:void 0,track:void 0});$=y($),s($);const A=Ae(u(),m);if(!A.through.length&&!A.unseated.length&&!A.outside.length)return A.crossings.length&&r?.(`${A.crossings.length} crossing${A.crossings.length===1?"":"s"} in the drawn layout: ${A.crossings.map(c=>`${ft(e,A.lines[c.top])} over ${ft(e,A.lines[c.under])}`).join("; ")}`),{dyn:$,geo:A,ink:Dt(n,A,d,o),tokens:d};A.through.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${g(A,A.through)} would pass through a node`),A.outside.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${g(A,A.outside)} would leave the drawing`),A.unseated.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: no clean seat for ${A.unseated.map(c=>e.type==="sequence"?`message ${c}`:`"${e.edges[c]?.label}"`).join(", ")}`)}let v=w({...a,layout:"stacked",heights:void 0,grow:{},track:e.type==="schema"?h.table:void 0});if(v=y(v),s(v),e.type==="sequence"||e.type==="schema")return{dyn:v,geo:null,ink:"",tokens:d};const T=Et(e);let E=Wt(u(),m,T);for(let $=0;$<6&&Object.keys(E.grow).length;$++){const A={...v.grow??{}};for(const[c,p]of Object.entries(E.grow))A[c]=(A[c]??0)+p;v={...v,grow:A},s(v),E=Wt(u(),m,T)}const M=E.geo;if(M.unseated.length>0||M.through.length>0||M.outside.length>0||T.third){M.unseated.length&&r?.(`the stacked drawing has no clean seat for ${[...new Set(M.unseated)].map(A=>`"${e.edges[A]?.label}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),M.through.length&&r?.(`in the stacked drawing ${g(M,M.through)} would pass through a node, so its lines are not drawn`),M.outside.length&&r?.(`in the stacked drawing ${g(M,M.outside)} would leave the drawing, so its lines are not drawn`),T.third&&r?.("the stacked drawing would need a third end lane, so its lines are not drawn");const $={...M,lines:[],labels:[],crossings:[]};return{dyn:{...v,grow:{}},geo:$,ink:"",tokens:d}}return M.crossings.length&&r?.(`${M.crossings.length} crossing${M.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${M.crossings.map($=>`${ft(e,M.lines[$.top])} over ${ft(e,M.lines[$.under])}`).join("; ")}`),{dyn:v,geo:M,ink:Dt(n,M,d,o),tokens:d}}function ft(t,e){const n=t.byId.get(e.from)?.name??e.from,o=t.byId.get(e.to)?.name??e.to;return`${n} to ${o}`}function Ce(t,e,n,o,a,s){const r=new Set;if(s){r.add(s);for(const u of n?.lines??[])u.from===s&&r.add(u.to),u.to===s&&r.add(u.from)}if(t.toggleAttribute("data-tracing",!!s),t.querySelectorAll(`.${e}-node`).forEach(u=>u.toggleAttribute("data-near",r.has(u.dataset.node))),!n||!o)return;const l=u=>!!s&&(u.from===s||u.to===s),d=t.querySelector(`.${e}-edges`),m=new Map;t.querySelectorAll(`.${e}-edge`).forEach(u=>m.set(u.getAttribute("data-edge"),u));for(const u of n.lines){const g=m.get(String(u.i));g&&(g.toggleAttribute("data-lit",l(u)),g.toggleAttribute("data-dim",!!s&&!l(u)))}if(t.querySelectorAll(`.${e}-label`).forEach(u=>{const g=n.lines.find(v=>String(v.i)===u.dataset.edge);u.toggleAttribute("data-lit",!!(g&&l(g)))}),d){for(const u of n.lines)if(l(u)){const g=m.get(String(u.i));g&&d.appendChild(g)}}const h=gt(n.lines,l),{defs:i,ids:f}=Gt(e,{...n,crossings:h},o,a),w=t.querySelector(`.${e}-svg`);if(!w)return;let y=w.querySelector("defs");!y&&i&&(y=document.createElementNS("http://www.w3.org/2000/svg","defs"),w.insertBefore(y,w.firstChild)),y&&(y.innerHTML=i),n.lines.forEach((u,g)=>{const v=m.get(String(u.i))?.querySelector(`.${e}-line`);if(!v)return;const T=f.get(g);T?v.setAttribute("mask",`url(#${T})`):v.removeAttribute("mask")})}function Be(t,e,n){const o=t.byId.get(e)?.i??0,a=t.nodes.length;let s;if(n==="ArrowRight"||n==="ArrowDown")s=o+1;else if(n==="ArrowLeft"||n==="ArrowUp")s=o-1;else if(n==="Home")s=0;else if(n==="End")s=a-1;else return null;return t.nodes[Math.max(0,Math.min(a-1,s))].id}var Te=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],Kt=["data-layout","data-measured"],Re=["--_track","--_h","--_gap"],Vt=t=>t==null||t===!1;function je(t,e){if(t.tagName.toLowerCase()!==e.t)return!1;const n=typeof e.a.class=="string"?e.a.class.split(" ")[0]:"";return!n||t.classList.contains(n)}function Zt(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const o=n?Kt:Te;for(const r of o)Vt(e.a[r])&&t.removeAttribute(r);for(const[r,l]of Object.entries(e.a)){if(r==="class")continue;if(r==="style"){const m=t.style,h=new Map(String(l??"").split(";").map(i=>{const f=i.indexOf(":");return[i.slice(0,f).trim(),i.slice(f+1).trim()]}).filter(([i])=>i));for(const[i,f]of h)m.getPropertyValue(i).trim()!==f&&m.setProperty(i,f);for(const i of Re)h.has(i)||m.removeProperty(i);continue}if(n&&!Kt.includes(r))continue;if(Vt(l)){t.removeAttribute(r);continue}const d=l===!0?"":String(l);t.getAttribute(r)!==d&&t.setAttribute(r,d)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class)||e.c.some(r=>typeof r!="string"&&"slot"in r))return;const a=[...t.children];let s=0;for(const r of e.c)if(!(typeof r=="string"||"slot"in r)){for(let l=s;l<a.length;l++)if(je(a[l],r)){Zt(a[l],r,!1),s=l+1;break}}}function Fe(t,e,n,o){if(n===o)return;const a=s=>t.querySelector(`.${e}-node[data-node="${CSS.escape(s)}"]`);n&&a(n)?.setAttribute("tabindex","-1"),a(o)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",o=0;function a(i,f){return{prefix:n,base:i,hasSource:f.source!==void 0&&f.source!==null&&f.source!=="",hiddenClass:"visually-hidden"}}function s(i,f,w,y){var u=function(g){return'<kbd class="kbd">'+st(g)+"</kbd>"};return{source:st(String(f.source||"")),summary:st(String(f.summary||"")),hint:ye(i).map(function(g){return"<span>"+g.keys.map(u).join(" ")+" "+st(g.words)+"</span>"}).join(""),toggle:'<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="'+(y?"true":"false")+'" aria-controls="'+st(w)+'-list"><span>'+(y?"Hide the list":"View as list")+"</span></button>"}}function r(i,f){var w=xt(i),y=qt(w,{},a(f,i)),u=kt(y,s(w,i,f,!1)),g=u.indexOf(">");return{open:u.slice(0,g+1),inner:u.slice(g+1,u.length-9),warnings:w.warnings}}var l=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-layout","data-measured"],d=["--_cols","--_gpad","--_track"];function m(i,f,w){i.__diagram&&i.__diagram.stop();var y=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),u=xt(f);if(!w||!y||!i.querySelector(":scope > .diagram-drawing")){if(!y||!i.querySelector("#"+CSS.escape(y+"-title"))){for(;document.getElementById("dg"+ ++o+"-title"););y="dg"+o}var g=r(f,y),v=document.createElement("div");v.innerHTML=g.open+"</figure>";var T=v.firstChild;l.forEach(function(I){i.removeAttribute(I)}),d.forEach(function(I){i.style.removeProperty(I)});for(var E=0;E<T.attributes.length;E++){var M=T.attributes[E];M.name==="class"?i.classList.add.apply(i.classList,M.value.split(" ")):M.name==="style"?i.style.cssText=M.value+";"+i.style.cssText:i.setAttribute(M.name,M.value)}i.querySelectorAll(":scope > :not(script[data-diagram])").forEach(function(I){I.remove()}),i.insertAdjacentHTML("beforeend",g.inner)}u.warnings.forEach(function(I){console.warn("Basalt diagram: "+I)});var z=a(y,f),$={},A=null,c=null,p=null,b={},L=function(I){b[I]||(b[I]=1,console.warn("Basalt diagram: "+I))},R=function(I){Zt(i,qt(u,I,z))},q=i.querySelector(".diagram-ink"),H=i.querySelector(".diagram-toggle");function O(){Ce(i,n,A&&A.geo,A&&A.tokens,y,c||p)}function j(){A=_e(i,u,n,y,$,R,L),$=A.dyn,R($),q&&(q.innerHTML=A.ink),O()}function V(I){$=I,R($)}function J(I){var G=$.stop;$=Object.assign({},$,{stop:I}),Fe(i,n,G,I)}var S=function(I){var G=I&&I.closest?I.closest(".diagram-node"):null;return G&&i.contains(G)?G:null};function C(I){var G=S(I.target);if(!(!G||I.defaultPrevented)){if(I.key==="Escape"){(c||p)&&(I.preventDefault(),c=p=null,O());return}if(lt(u,$)){var U=Be(u,G.getAttribute("data-node"),I.key);if(U){I.preventDefault(),J(U);var et=i.querySelector('.diagram-node[data-node="'+CSS.escape(U)+'"]');et&&et.focus()}}}}function B(I){var G=S(I.target);if(G){var U=G.getAttribute("data-node");c=G.matches(":focus-visible")?U:null,lt(u,$)&&$.stop!==U&&J(U),O()}}function k(I){var G=S(I.target);G&&(S(I.relatedTarget)||(c=null),$.keep===G.getAttribute("data-node")&&V(Object.assign({},$,{keep:void 0})),O())}function _(I){if(!(I.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var G=S(I.target),U=G&<(u,$)?G.getAttribute("data-node"):null;U!==p&&(p=U,O())}}function N(){p&&(p=null,O())}function D(){var I=!$.open;V(Object.assign({},$,{open:I})),H.setAttribute("aria-expanded",String(I)),H.firstElementChild.textContent=I?"Hide the list":"View as list"}i.addEventListener("keydown",C),i.addEventListener("focusin",B),i.addEventListener("focusout",k),i.addEventListener("pointerover",_),i.addEventListener("pointerleave",N),H&&H.addEventListener("click",D),j();var Y=i.clientWidth,K=0,F=!0,W=new ResizeObserver(function(){Math.abs(i.clientWidth-Y)<.5||(Y=i.clientWidth,cancelAnimationFrame(K),K=requestAnimationFrame(j))});W.observe(i),document.fonts&&document.fonts.ready.then(function(){F&&j()}),i.__diagram={stop:function(){F=!1,W.disconnect(),cancelAnimationFrame(K),i.removeEventListener("keydown",C),i.removeEventListener("focusin",B),i.removeEventListener("focusout",k),i.removeEventListener("pointerover",_),i.removeEventListener("pointerleave",N),H&&H.removeEventListener("click",D)},layout:j}}function h(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var f=i.querySelector(":scope > script[data-diagram]");if(f)try{m(i,JSON.parse(f.textContent),!0)}catch(w){console.error("Basalt diagram: this figure could not be drawn",w)}}})}e.diagramMarkup=r,t.diagram=function(i,f){m(i,f)},e.step(62,"wireDiagrams",h)})(window.Basalt)})(); +(()=>{var Pt=["top","right","bottom","left"],te=["main","plain","dashed"],ee=[2,3,4,5,6],ot=t=>t==null||t===""?void 0:String(t),ut=t=>Object.assign(Object.create(null),t),ht=(t,e)=>t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;function Et(t,e={}){const n=e.checks!==!1,a=[],s=c=>{a.push(c)},o=t.legend??{},r={};for(const c of["main","plain","dashed","focal","group"]){const p=ot(o[c]);p&&(r[c]=p)}const l=t.stepLabel,u=typeof l=="function"?c=>String(l(c)):typeof l=="string"?(c=>l.replace("{n}",String(c))):c=>`Step ${c}`,g=t.shapeLabels??{},h={terminal:ot(g.terminal)??"Start or end",step:ot(g.step)??"Step",decision:ot(g.decision)??"Decision"},i=t.heading===void 0?3:ee.includes(t.heading)?t.heading:(s(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),f=(c,p)=>c==null?"plain":te.includes(c)?c:(s(`"${String(c)}" is not a kind of line (main, plain or dashed): ${p} is drawn plain`),"plain"),x=c=>{if(c!=null){if(Pt.includes(c))return c;s(`"${String(c)}" is not a side (top, right, bottom or left): the derived side is used`)}},m=(c,p)=>typeof c=="number"&&Number.isInteger(c)&&c>=1?c:(s(`${p} is ${JSON.stringify(c)}, not a whole number from 1: it is placed at 1`),1),d=[],y=[];let w=[];const q=[],E=[],L=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(L)||s(`"${String(L)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),L==="architecture"||L==="flowchart"){for(const c of t.nodes??[]){const p=L==="flowchart"&&c.shape==="decision"?"decision":L==="flowchart"&&c.shape==="terminal"?"terminal":"box",b=String(c.id??""),k=m(c.row,`the row of ${b}`);d.push({id:b,i:d.length,name:String(c.name??""),kind:p==="decision"?void 0:ot(c.kind),detail:p==="decision"?void 0:ot(c.detail),mono:!!c.detailMono,focal:!!c.focal,col:m(c.col,`the column of ${b}`),row:k,row2:k,branch:!!c.branch,shape:p,group:L==="architecture"?ot(c.group):void 0})}if(L==="architecture")for(const c of t.groups??[]){const p=String(c.id??"");q.push({id:p,label:String(c.label??""),members:d.filter(b=>b.group===p).map(b=>b.id)})}}else if(L==="data-flow"){w=(t.lanes??[]).map(p=>({id:String(p.id??""),label:String(p.label??"")}));const c=new Map(w.map((p,b)=>[p.id,b+1]));for(const p of t.nodes??[]){const b=String(p.id??""),k=String(p.lane??""),R=c.get(k);R===void 0&&s(`a node (${b}) names the lane "${k}", which is not in lanes`);const M=d.length+1;d.push({id:b,i:d.length,name:String(p.name??""),kind:u(M),detail:ot(p.detail),mono:!!p.detailMono,focal:!!p.focal,col:m(p.col,`the column of ${b}`),row:R??1,row2:R??1,branch:!1,shape:"box",lane:R??1,laneLabel:w[(R??1)-1]?.label??k,step:M})}}else if(L==="sequence"){(t.participants??[]).forEach((p,b)=>{const k=String(p.name??"");d.push({id:String(p.id??""),i:b,name:k,kind:ot(p.kind),mono:!1,focal:!!p.focal,col:b+1,row:1,row2:1,branch:!1,shape:"participant",short:ot(p.short)??k})});let c=0;for(const p of t.steps??[])"band"in p?E.push({band:String(p.band??"")}):(c++,E.push({n:c,from:String(p.from??""),to:String(p.to??""),label:String(p.label??""),note:ot(p.note),kind:f(p.kind,`message ${c}`)}))}else if(L==="schema")for(const c of t.tables??[]){const p=String(c.name??""),[b,k]=Array.isArray(c.row)?c.row:[c.row,c.row],R=m(b,`the row of ${p}`),M=Math.max(R,m(k,`the last row of ${p}`)),G=c.more===void 0||c.more===null?void 0:Number.isInteger(c.more)&&c.more>0?c.more:(s(`${p}'s "more" is ${JSON.stringify(c.more)}, not a whole number from 1: it is left out`),void 0);d.push({id:p,i:d.length,name:p,mono:!0,focal:!!c.focal,col:m(c.col,`the column of ${p}`),row:R,row2:M,branch:!1,shape:"table",more:G,columns:(c.columns??[]).map(C=>({name:String(C.name??""),type:ot(C.type),key:C.key==="PK"||C.key==="FK"?C.key:(C.key!==void 0&&C.key!==null&&s(`${p}.${String(C.name)}'s key is "${String(C.key)}", not PK or FK: it is left out`),void 0)}))})}const _=new Map;for(const c of d)c.id?_.has(c.id)&&s(`the id "${c.id}" is used twice`):s("a node has no id"),_.set(c.id,c);if(L==="schema")(t.tables??[]).forEach(c=>(c.columns??[]).forEach((p,b)=>{const k=ot(p.references);if(!k)return;const[R,M]=k.split("."),G=_.get(R??""),C=G?.columns?.findIndex(W=>W.name===M)??-1;if(!G||C<0){s(`${String(c.name)}.${String(p.name)} references ${k}, which is not a shown column`);return}const K=_.get(String(c.name??""));K.columns[b].ref={table:R,column:M,row:C},y.push({i:y.length,from:K.id,to:R,kind:"plain",fromRow:b,toRow:C,fk:!0})}));else if(L!=="sequence")for(const c of t.edges??[]){const p=String(c.from??""),b=String(c.to??"");if(!_.has(p)||!_.has(b)){s(`a line names ${_.has(p)?b:p}, which is not a node`);continue}const k=ot(c.label);k&&k.length>At&&s(`the label "${k}" is over ${At} characters: longer words belong in the node or the summary`),y.push({i:y.length,from:p,to:b,kind:f(c.kind,`the line from ${p} to ${b}`),label:k,fromSide:x(c.fromSide),toSide:x(c.toSide)})}else for(const c of E)"n"in c&&(!_.has(c.from)||!_.has(c.to))&&s(`message ${c.n} names ${_.has(c.from)?c.to:c.from}, which is not a participant`);if(n&&L!=="sequence"){const c=new Map;for(const p of d)for(let b=p.row;b<=p.row2;b++){const k=`${p.col}:${b}`;c.has(k)&&s(`${p.id} and ${c.get(k)} share the cell at column ${p.col}, row ${b}`),c.set(k,p.id)}}if(n){for(const p of q){const b=p.members.map(M=>_.get(M));if(!b.length)continue;const k={c1:Math.min(...b.map(M=>M.col)),c2:Math.max(...b.map(M=>M.col)),r1:Math.min(...b.map(M=>M.row)),r2:Math.max(...b.map(M=>M.row2))};for(const M of d)M.group!==p.id&&M.col>=k.c1&&M.col<=k.c2&&M.row>=k.r1&&M.row<=k.r2&&s(`${M.id} is inside the box of the group "${p.label}" but not a member`);const R=b.map(M=>M.i);Math.max(...R)-Math.min(...R)+1!==R.length&&s(`the members of the group "${p.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const p of d)p.group&&!q.some(b=>b.id===p.group)&&s(`${p.id} names the group "${p.group}", which is not in groups`);d.filter(p=>p.focal).length>1&&s("more than one node is focal: a diagram has one at most");const c=new Set(L==="sequence"?E.flatMap(p=>"n"in p?[p.kind]:[]):y.map(p=>p.kind));c.has("main")&&!r.main&&s("main lines are drawn but the legend has no words for them (legend.main)"),c.has("dashed")&&!r.dashed&&s("dashed lines are drawn but the legend has no words for them (legend.dashed)"),d.some(p=>p.focal)&&!r.focal&&s("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const j=Math.max(1,...d.map(c=>c.col)),B=L==="data-flow"?Math.max(1,w.length):Math.max(1,...d.map(c=>c.row2));return{type:L,title:String(t.title??""),heading:i,legend:r,nodes:d,byId:_,edges:y,groups:q,lanes:w,steps:E,cols:j,rows:B,shapeLabels:h,stepWord:u,warnings:a,memo:new Map}}function bt(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var At=28,pt=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""};function Lt(t,e){return t.legend[e]}function ne(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function oe(t,e){return bt(t,`sentence:${e.i}`,()=>se(t,e))}function se(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const a=(e.columns??[]).filter(o=>o.ref).map(o=>`${o.ref.table} (${o.name})`),s=t.edges.filter(o=>o.to===e.id).map(o=>`${o.from} (${t.byId.get(o.from).columns[o.fromRow].name})`);a.length&&n.push(`References ${a.join(", ")}.`),s.length&&n.push(`Referenced by ${s.join(", ")}.`)}else if(t.type==="sequence"){const a=t.steps.filter(o=>"n"in o&&o.from===e.id).length,s=t.steps.filter(o=>"n"in o&&o.to===e.id).length;n.push(pt(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${a} ${a===1?"message":"messages"} and receives ${s}.`)}else{const a=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?ne(t,e):e.kind;if(n.push(pt(a?`${e.name}, ${a}`:e.name)),e.detail&&n.push(pt(e.detail)),e.group){const r=t.groups.find(l=>l.id===e.group);r&&n.push(`In ${r.label}.`)}const s=t.edges.filter(r=>r.to===e.id).map(r=>`${t.byId.get(r.from).name}${r.label?` (${r.label})`:""}`),o=t.edges.filter(r=>r.from===e.id).map(r=>`${t.byId.get(r.to).name}${r.label?` (${r.label})`:""}`);s.length&&n.push(`From: ${s.join(", ")}.`),o.length&&n.push(`To: ${o.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(pt(t.legend.focal)),n.join(" ")}function ae(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function $(t,e,...n){const a=[];for(const s of n.flat(1/0))s!=null&&s!==!1&&!Array.isArray(s)&&a.push(s);return{t,a:e??{},c:a}}var re={"&":"&","<":"<",">":">",'"':""","'":"'"},at=t=>t.replace(/[&<>"']/g,e=>re[e]),ie=" br img input meta link hr path polygon polyline circle rect line ";function qt(t,e={}){if(typeof t=="string")return at(t);if("slot"in t)return e[t.slot]??"";if(!/^[a-z][a-z0-9]*$/.test(t.t))throw new Error(`diagram: "${t.t}" is not an element name`);let n="";for(const[a,s]of Object.entries(t.a))if(!(s==null||s===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(a))throw new Error(`diagram: "${a}" is not an attribute name`);n+=s===!0?` ${a}`:` ${a}="${at(String(s))}"`}return ie.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(a=>qt(a,e)).join("")}</${t.t}>`}var le=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function ft(t,e){return!e.layout||e.bare?!1:e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema"}function ce(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function It(t){let e=0;for(const n of t.groups){const a=n.members.map(s=>t.byId.get(s).col);a.length&&(Math.min(...a)===1&&(e|=1),Math.max(...a)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function Mt(t){return t.type==="sequence"?t.nodes.length:t.cols}function Ot(t){return bt(t,"plan",()=>de(t))}function de(t){const e=t.nodes,n=d=>t.type==="data-flow"||!e[d].branch,a=t.edges.map(d=>{const y=t.byId.get(d.from).i,w=t.byId.get(d.to).i,E=e.slice(Math.min(y,w)+1,Math.max(y,w)).every(L=>!n(L.i));return w===y+1&&!(n(y)&&!n(w))?"down":w===y-1?"up":w>y&&n(y)&&!n(w)&&E?"trunk":w>y&&n(y)&&n(w)&&E?"rail":w>y?"end-down":"end-up"}),s=t.edges.map((d,y)=>({e:d,k:y})).filter(({k:d})=>a[d]==="end-down"||a[d]==="end-up"),o=d=>{const y=t.byId.get(d.from).i,w=t.byId.get(d.to).i;return[Math.min(y,w),Math.max(y,w)]},r=(d,y)=>{const[w,q]=o(d),[E,L]=o(y);return w<L&&E<q},l=s.every(({e:d})=>{const y=t.byId.get(d.from).i,[w,q]=o(d);return!n(y)&&e.slice(w+1,q).every(E=>!n(E.i))&&s.every(E=>E.e===d||!r(E.e,d))}),u=s.length>0&&(t.type==="data-flow"||!l),g=d=>{const[y,w]=o(d);return w-y},h=t.edges.map(()=>0);let i=!1;const f=[];for(const d of[...s].sort((y,w)=>g(y.e)-g(w.e)||y.k-w.k)){let y=0;for(const w of f)r(w.e,d.e)&&(y=Math.max(y,h[w.k]+1));h[d.k]=y,y>1&&(i=!0),f.push(d)}const x=t.edges.map(()=>.5);for(const d of e){const y=s.filter(({e:E})=>E.from===d.id);if(y.length<2)continue;const w=y.filter(({k:E})=>a[E]==="end-down").sort((E,L)=>g(L.e)-g(E.e)||E.k-L.k);[...y.filter(({k:E})=>a[E]==="end-up").sort((E,L)=>g(E.e)-g(L.e)||L.k-E.k),...w].forEach(({k:E},L,_)=>{x[E]=_.length===2?L===0?1/3:2/3:(L+1)/(_.length+1)})}const m=ut();for(let d=1;d<e.length;d++){const y=e[d],w=e[d-1];let q=0,E=t.type==="data-flow"?48:32,L=!1,_=!1;t.edges.forEach((j,B)=>{const c=a[B],p=t.byId.get(j.from).i,b=t.byId.get(j.to).i,k=b===d&&(c==="down"||c==="trunk"||c==="rail"||c==="end-down"),R=p===d&&b===d-1&&c==="up",M=b===d-1&&c==="end-up";k&&(c==="trunk"||c==="end-down")&&(L=!0),M&&(_=!0),(k||R||M)&&j.label&&(q++,E=Math.max(E,c==="trunk"?40:48))}),(q>1||L&&_)&&(E=64),m[y.id]=E}return{routes:a,gutter:u,lanes:h,exits:x,gaps:m,third:i}}var gt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function _t(t,e){const n=e==="fk"?"plain":e,a=n==="main"?8:8.5,s=24,o=n==="dashed"?s-1:s-7;return $("svg",{class:`${t}-swatch`,"data-kind":n,...gt(24,16)},e==="fk"?$("circle",{class:`${t}-dot`,cx:3,cy:a,r:3}):null,$("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${a}H${o}`}),n==="dashed"?$("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${s-8} ${a-4}L${s} ${a}L${s-8} ${a+4}`}):$("path",{class:`${t}-tip`,"data-kind":n,d:`M${s} ${a}L${s-8} ${a-4}L${s-8} ${a+4}Z`}))}function yt(t,e){return e==="decision"?$("svg",{class:`${t}-swatch`,"data-shape":e,...gt(16,16)},$("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?$("svg",{class:`${t}-swatch`,"data-shape":e,...gt(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):$("svg",{class:`${t}-swatch`,"data-shape":e,...gt(16,16)},$("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function ue(t,e){return bt(e,`key:${t}`,()=>fe(t,e))}function fe(t,e){const n=[],a=(o,r,l={})=>n.push($("li",{class:`${t}-entry`,...l},o,$("span",null,r)));if(e.type==="schema"){const o=new Set(e.nodes.flatMap(r=>(r.columns??[]).map(l=>l.key)));for(const[r,l]of[["PK","Primary key"],["FK","Foreign key"]])o.has(r)&&n.push($("li",{class:`${t}-entry`},$("span",{class:`${t}-key-letters`,"aria-hidden":"true"},r),$("span",null,l)))}if(e.type==="flowchart"){const o=new Set(e.nodes.map(r=>r.shape));o.has("terminal")&&a(yt(t,"terminal"),e.shapeLabels.terminal),o.has("box")&&a(yt(t,"box"),e.shapeLabels.step),o.has("decision")&&a(yt(t,"decision"),e.shapeLabels.decision)}const s=new Set(e.type==="sequence"?e.steps.flatMap(o=>"n"in o?[o.kind]:[]):e.edges.filter(o=>!o.fk).map(o=>o.kind));for(const o of["main","plain","dashed"]){const r=e.legend[o];s.has(o)&&r&&a(_t(t,o),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(a(_t(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"}),n.push($("li",{class:`${t}-entry`,"data-when":"stacked"},$("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},"→"),$("span",null,"The table a foreign key references")))),e.nodes.some(o=>o.focal)&&e.legend.focal&&a(yt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&a(yt(t,"group"),e.legend.group),n.length?$("div",{class:`${t}-key`},$("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function he(t,e){const n=e==="main"?6:6.5;return $("svg",{class:`${t}-arrow`,"data-kind":e,...gt(20,12)},$("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?$("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):$("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function pe(t,e,n){if(n.shape==="decision")return[$("span",{class:`${t}-words`},$("span",{class:`${t}-name`},n.name))];const a=[];return e.type==="data-flow"?a.push($("span",{class:`${t}-kind`},n.kind,$("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&a.push($("span",{class:`${t}-kind`},n.kind)),a.push($("span",{class:`${t}-name`},n.name)),n.detail&&a.push($("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.mono?wt(n.detail).flatMap((s,o)=>[o?" ":"",$("span",{class:`${t}-run`},s)]):n.detail)),a}function ge(t,e){return[$("span",{class:`${t}-th`},$("span",{class:`${t}-tname`},e.name)),$("span",{class:`${t}-rows`},(e.columns??[]).map((n,a)=>$("span",{class:`${t}-row`,"data-row":a,"data-key":n.key},$("span",{class:`${t}-keyseat`},n.key??""),$("span",{class:`${t}-cname`},n.name),n.ref?$("span",{class:`${t}-ctype`,"data-ref":""},`→ ${n.ref.table}`):n.type?$("span",{class:`${t}-ctype`},n.type):null))),e.more?$("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Ct=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function vt(t,e,n,a){const{P:s}=t,o=ce(e,a)||a.keep===n.id,r=ft(e,a),l=[`--_c:${n.col}`,`--_r:${n.row}`,`--_r2:${n.row2+1}`];e.type==="data-flow"&&l.push(`--_lc:${n.col+1}`),e.type==="sequence"&&l.push(`--_c2:${n.col+1}`);const u=t.plan;if(u&&n.i>0){const i=ht(u.gaps,n.id)??32,f=ht(a.grow,n.id)??0;l.push(`--_gap:${f?`calc(${Ct(i)} + var(--basalt-space-4) * ${f})`:Ct(i)}`)}const g=ht(a.heights,n.id);g&&l.push(`--_h:${g}px`);const h=r?a.stop===n.id?0:-1:a.keep===n.id?-1:void 0;return $("div",{class:`${s}-node`,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-level":t.level,style:l.join(";"),role:o?"img":void 0,"aria-label":o?oe(e,n):void 0,tabindex:h},n.shape==="decision"?$("svg",{class:`${s}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},$("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.shape==="table"?ge(s,n):pe(s,e,n))}function ye(t,e,n){const{P:a}=t,s=[];if(e.type==="data-flow"&&s.push(...e.lanes.map((r,l)=>$("div",{class:`${a}-lane`,style:`--_r:${l+1}`,"aria-hidden":"true"},$("span",{class:`${a}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const l=r.members.map(f=>e.byId.get(f));if(!l.length)continue;const u=Math.min(...l.map(f=>f.col)),g=Math.max(...l.map(f=>f.col)),h=Math.min(...l.map(f=>f.row)),i=Math.max(...l.map(f=>f.row2));s.push($("div",{class:`${a}-gbox`,"data-group":r.id,style:`--_c:${u};--_c2:${g+1};--_r:${h};--_r2:${i+1}`,"aria-hidden":"true"},$("span",{class:`${a}-glabel`},r.label)))}if(e.type==="sequence")return s.push($("ul",{class:`${a}-cast`},e.nodes.map(r=>$("li",{class:`${a}-actor`},vt(t,e,r,n))))),s.push(me(t,e)),s;let o=0;for(;o<e.nodes.length;){const r=e.nodes[o],l=r.group?e.groups.find(h=>h.id===r.group):void 0;if(!l){s.push(vt(t,e,r,n)),o++;continue}const u=[];for(;o<e.nodes.length&&e.nodes[o].group===l.id;)u.push(e.nodes[o++]);const g=t.plan?ht(n.grow,u[0].id)??0:0;s.push($("div",{class:`${a}-group`,"data-group":l.id,style:g?`--_ggrow:${g}`:void 0},$("span",{class:`${a}-glabel`,"aria-hidden":"true"},l.label),u.map(h=>vt(t,e,h,n))))}return s}function me(t,e){const{P:n}=t,a=[];let s=null;for(const o of e.steps){if("band"in o){s=null,a.push($("p",{class:`${n}-band`},$("span",null,o.band)));continue}s||(s=$("ol",{class:`${n}-msgs`,start:o.n}),a.push(s));const r=e.byId.get(o.from),l=e.byId.get(o.to),u=r?.col??1,g=l?.col??1,h=u===g,i=h&&u===e.nodes.length,f=Lt(e,o.kind);s.c.push($("li",{class:`${n}-msg`,"data-kind":o.kind,"data-from":o.from,"data-to":o.to,"data-self":h?i?"start":"end":void 0,style:`--_a:${Math.min(u,g)};--_b:${Math.max(u,g)+1}`},$("span",{class:`${n}-said`},$("span",{class:`${n}-num`},String(o.n)),$("span",{class:`${n}-mlabel`},o.label)),$("span",{class:`${n}-route`},r?.short??o.from," ",he(n,o.kind),$("span",{class:t.hidden}," to ")," ",l?.short??o.to,f?` · ${f}`:""),o.note?$("span",{class:`${n}-note`},o.note):null))}return $("div",{class:`${n}-steps`},a)}function be(t,e){return bt(e,`list:${t}`,()=>$e(t,e))}function $e(t,e){const n=Math.min(6,e.heading+1),a=h=>$(`h${n}`,{class:`${t}-list-head`},h),s=h=>$("strong",null,h),o=h=>$("code",{class:`${t}-code`},h),r=h=>e.byId.get(h)?.name??h,l=h=>{const i=Lt(e,h);return i?` (${i})`:""},u=h=>h.focal&&e.legend.focal?` ${pt(e.legend.focal)}`:"";if(e.type==="architecture"){const h=x=>$("li",null,s(x.name),x.kind?`, ${x.kind}`:"",x.detail?[". ",x.mono?o(x.detail):x.detail,/[.!?]$/.test(x.detail)?"":"."]:/[.!?]$/.test(x.kind??x.name)?"":".",u(x)),i=[a("Parts")],f=e.nodes.filter(x=>!x.group);f.length&&i.push($("ul",{class:`${t}-list-items`},f.map(h)));for(const x of e.groups)i.push($("p",{class:`${t}-list-group`},x.label)),i.push($("ul",{class:`${t}-list-items`},x.members.map(m=>h(e.byId.get(m)))));return i.push(a("Connections")),i.push($("ol",{class:`${t}-list-items`},e.edges.map(x=>$("li",null,s(r(x.from))," to ",s(r(x.to)),x.label?[": ",o(x.label)]:"",`${l(x.kind)}.`)))),i}if(e.type==="flowchart"){const h=i=>(e.byId.get(i)?.i??0)+1;return[$("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const f=e.edges.filter(d=>d.from===i.id),x=i.shape==="decision"?"Decision":i.shape==="terminal"?f.length?"Start":"End":"Step",m=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return $("li",null,s(i.name),i.detail?[", ",i.mono?o(i.detail):i.detail]:"",`${m}${x}.`,u(i),f.length?$("ul",{class:`${t}-list-exits`},f.map(d=>$("li",null,d.label?`If ${d.label}: go to ${h(d.to)}, `:`Then: go to ${h(d.to)}, `,s(r(d.to)),l(d.kind)))):null)}))]}if(e.type==="data-flow")return[$("ol",{class:`${t}-list-items`},e.nodes.map(h=>{const i=e.edges.filter(f=>f.from===h.id);return $("li",null,`${h.laneLabel}: `,s(h.name),h.detail?[", ",h.mono?o(h.detail):h.detail]:"",".",u(h),i.length?[" Then ",...i.flatMap((f,x)=>[x?"; ":"",`to step ${e.byId.get(f.to).step}, `,s(r(f.to)),f.label?[": ",o(f.label)]:"",l(f.kind)]),"."]:"")}))];if(e.type==="sequence"){const h=[a("Participants"),$("ul",{class:`${t}-list-items`},e.nodes.map(f=>$("li",null,s(f.name),f.kind?`, ${f.kind}`:"",".",u(f))))];h.push(a("Messages"));let i=null;for(const f of e.steps){if("band"in f){i=null,h.push($(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`},f.band));continue}i||(i=$("ol",{class:`${t}-list-items`,start:f.n}),h.push(i)),i.c.push($("li",null,o(f.label),": ",s(r(f.from))," to ",s(r(f.to)),`${l(f.kind)}.`,f.note?` ${pt(f.note)}`:""))}return h}const g=[];for(const h of e.nodes)g.push($(`h${n}`,{class:`${t}-list-group`},o(h.name),u(h))),g.push($("ul",{class:`${t}-list-items`},[...(h.columns??[]).map(i=>$("li",null,o(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",o(`${i.ref.table}.${i.ref.column}`)]:i.type?`, ${i.type}`:"")),...h.more?[$("li",null,`and ${h.more} more ${h.more===1?"column":"columns"}`)]:[]]));return g}function we(t){return`Arrow keys move to the next or the previous ${t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step"}, in the author's order; Home and End go to the ends; Escape clears the trace.`}function xe(t){return[{keys:["←","→"],words:ae(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}function Bt(t,e,n){const a=n.prefix,s=le(n.base),o=t.type==="sequence"||t.type==="schema"?null:Ot(t),r={P:a,ids:s,level:n.level,plan:o,hidden:n.hiddenClass},l=e.layout==="drawn",u=ft(t,e),g=t.type==="sequence"||t.type==="schema"?l:!0,h=`h${t.heading}`,i=[`--_cols:${Mt(t)}`];if(t.type==="architecture"&&t.groups.length||l&&e.pad){const f=t.type==="architecture"?t.groups.flatMap(d=>d.members.map(y=>t.byId.get(y))):[],x=(d,y,w)=>d?`var(--basalt-space-${y})`:w?`var(--basalt-space-${w})`:"0px",m=l&&e.pad?"3":void 0;i.push(`--_gpad:${x(f.some(d=>d.row===1),"8",m)} ${x(f.some(d=>d.col===t.cols),"4")} ${x(f.some(d=>d.row2===t.rows),"4",m)} ${x(f.some(d=>d.col===1),"4")}`)}return t.type==="schema"&&e.track&&i.push(`--_track:${e.track}px`),$("figure",{class:n.className?`${a} ${n.className}`:a,"aria-labelledby":s.title,"data-type":t.type,"data-cols":Mt(t),"data-reach":t.type==="architecture"?It(t):void 0,"data-gutter":o?.gutter?"":void 0,"data-layout":e.layout,"data-measured":e.layout?"":void 0,"data-bare":e.bare?"":void 0,style:i.join(";")},$("div",{class:`${a}-head`},$(h,{id:s.title,class:`${a}-title`},t.title),n.hasSource?$("p",{class:`${a}-source`},{slot:"source"}):null),$("div",{class:`${a}-drawing`,role:g?"group":void 0,"aria-roledescription":g?"diagram":void 0,"aria-labelledby":g?s.title:void 0,"aria-describedby":g?u?`${s.summary} ${s.keys}`:s.summary:void 0,"data-stops":u?"":void 0},ye(r,t,e),$("div",{class:`${a}-ink`,"aria-hidden":"true"}),$("span",{class:`${a}-ruler`,"aria-hidden":"true"})),ue(a,t),$("p",{class:`${a}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),$("div",{class:`${a}-foot`},{slot:"toggle"}),$("div",{id:s.list,class:`${a}-list`,hidden:!e.open},be(a,t)),$("span",{id:s.keys,class:n.hiddenClass},we(t)),$("figcaption",{id:s.summary,class:`${a}-summary`},{slot:"summary"}))}function Me(t){const e=getComputedStyle(t),n=(s,o)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${s}`));return Number.isFinite(r)?r:o},a=new Map;return{space:s=>(a.has(s)||a.set(s,n(`space-${s}`,parseFloat(s.replace("-","."))*4)),a.get(s)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4)}}var $t=(t,e)=>t==="main"?e.line:e.hair,rt=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},lt=(t,e,n=.01)=>t.l<e.r-n&&t.r>e.l+n&&t.t<e.b-n&&t.b>e.t+n,Tt=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function nt(t,e,n){const{l:a,t:s,r:o,b:r}=t.rect,l=(a+o)/2,u=(s+r)/2,g=(o-a)/2,h=(r-s)/2,i=e==="top"||e==="bottom";if(t.shape==="decision"){if(i){const m=n,d=h*Math.max(0,1-Math.abs(m-l)/g);return{x:m,y:e==="top"?u-d:u+d}}const f=n,x=g*Math.max(0,1-Math.abs(f-u)/h);return{x:e==="left"?l-x:l+x,y:f}}if(t.shape==="terminal"){const f=Math.min(g,h);if(i){const y=n,w=Math.min(Math.max(y,a+f),o-f),q=y-w,E=Math.abs(q)>=f?0:Math.sqrt(f*f-q*q);return{x:y,y:Math.abs(q)<1e-6?e==="top"?s:r:e==="top"?u-E:u+E}}const x=n,m=x-u,d=Math.abs(m)>=f?0:Math.sqrt(f*f-m*m);return{x:e==="left"?a+f-d:o-f+d,y:x}}return i?{x:n,y:e==="top"?s:r}:{x:e==="left"?a:o,y:n}}function ve(t,e,n){const{l:a,t:s,r:o,b:r}=e.rect,l=(a+o)/2,u=(s+r)/2,g=(o-a)/2,h=(r-s)/2;if(e.shape==="decision")return Math.abs(t.x-l)/g+Math.abs(t.y-u)/h<1-n/Math.min(g,h);if(e.shape==="terminal"){const i=Math.min(g,h),f=Math.min(Math.max(t.x,a+i),o-i);return Math.hypot(t.x-f,t.y-u)<i-n}return t.x>a+n&&t.x<o-n&&t.y>s+n&&t.y<r-n}function jt(t,e){if(!lt(t,e.rect))return!1;if(e.shape!=="decision"&&e.shape!=="terminal")return!0;const{l:n,t:a,r:s,b:o}=e.rect,r=(n+s)/2,l=(a+o)/2,u=(s-n)/2,g=(o-a)/2;if(e.shape==="decision"){const i=Math.max(t.l,Math.min(r,t.r)),f=Math.max(t.t,Math.min(l,t.b));return Math.abs(i-r)/u+Math.abs(f-l)/g<1-1e-6}const h=Math.min(g,u);if(lt(t,{l:n+h,r:s-h,t:a,b:o}))return!0;for(const i of[n+h,s-h]){const f=Math.max(t.l,Math.min(i,t.r)),x=Math.max(t.t,Math.min(l,t.b));if(Math.hypot(f-i,x-l)<h-.01)return!0}return!1}function ke(t,e,n){const a=Math.hypot(e.x-t.x,e.y-t.y),s=Math.max(2,Math.ceil(a/2));for(let o=1;o<s;o++){const r=o/s;if(!(r*a<1.5||(1-r)*a<1.5)&&ve({x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r},n,1))return!0}return!1}function Se(t,e){const n=t.querySelector(`.${e}-ruler`),a=new Map;return(s,o)=>{const r=`${o}|${s}`;return a.has(r)||(n.setAttribute("data-f",o),n.textContent=s,a.set(r,n.getBoundingClientRect().width),n.textContent=""),a.get(r)}}var wt=t=>t?t.split(/\s+/).filter(Boolean):[];function Ee(t,e,n){const a=e.space;let s=e.node,o=e.table;for(const u of t.nodes){if(u.shape==="table"){for(const f of u.columns??[]){const x=f.ref?`→ ${f.ref.table}`:f.type??"",m=a("6")+n(f.name,"mono")+(x?a("3")+n(x,"mono"):0)+2*a("3")+2*e.hair;o=Math.max(o,Math.ceil(m))}o=Math.max(o,Math.ceil(n(u.name,"table")+2*a("3")+2*e.hair));continue}const g=u.shape==="terminal"?2*a("5"):2*a("3");let h=0;for(const f of wt(u.name))h=Math.max(h,n(f,u.shape==="decision"?"name-500":"name"));if(t.type!=="data-flow")for(const f of wt(u.kind))h=Math.max(h,n(f,"mono"));for(const f of wt(u.detail))h=Math.max(h,n(f,u.mono?"mono":"sans"));const i=u.shape==="decision"?h/.62:h+g+2*e.hair;s=Math.max(s,Math.ceil(i))}const r=Mt(t);let l;return t.type==="data-flow"?l=e.lane+r*(s+a("12")):t.type==="schema"?l=r*o+(r-1)*a("12"):t.type==="sequence"?l=r*s+(r-1)*a("5"):l=r*s+(r-1)*a("16")+It(t)*a("4"),{track:s,table:o,least:Math.max(e.wide,l)}}function Rt(t,e){return{x:(n,a)=>a%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,a)=>a%2===1?Math.round(n+e-.5)+.5-e:Math.round(n+e)-e}}function kt(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ft(t,e,n){const a=t.map(o=>({...o}));for(let o=1;o<a.length;o++){const r=a[o-1],l=a[o];if(Math.abs(r.x-l.x)<.75){const u=n.x(r.x,e);r.x=u,l.x=u}else if(Math.abs(r.y-l.y)<.75){const u=n.y(r.y,e);r.y=u,l.y=u}}const s=[a[0]];for(let o=1;o<a.length;o++){const r=a[o],l=s[s.length-1];if(!(Math.abs(r.x-l.x)<.01&&Math.abs(r.y-l.y)<.01)){if(s.length>=2){const u=s[s.length-2];if(Math.abs(u.x-l.x)<.01&&Math.abs(l.x-r.x)<.01||Math.abs(u.y-l.y)<.01&&Math.abs(l.y-r.y)<.01){s[s.length-1]=r;continue}}s.push(r)}}return s}var ct=t=>t.slice(1).map((e,n)=>[t[n],e]);function xt(t,e,n){const a=[];for(let o=0;o<t.length;o++)for(let r=o+1;r<t.length;r++){const l=t[o],u=t[r];if(!(n&&!n.has(l.i)&&!n.has(u.i)))for(const[g,h]of ct(l.pts))for(const[i,f]of ct(u.pts)){const x=Math.abs(g.y-h.y)<.01,m=Math.abs(i.y-f.y)<.01;if(x===m)continue;const[d,y,w,q]=x?[g,h,i,f]:[i,f,g,h],E=w.x,L=d.y;if(E>Math.min(d.x,y.x)+.75&&E<Math.max(d.x,y.x)-.75&&L>Math.min(w.y,q.y)+.75&&L<Math.max(w.y,q.y)-.75){const _=x?o:r,j=x?r:o;let B=_,c=j;if(e){const p=e(t[_]);e(t[j])&&!p&&(B=j,c=_)}a.push({top:B,under:c,at:{x:E,y:L},underVertical:c===j})}}}return a}function Ae(t){const e=getComputedStyle(t),n=s=>s.split(/\s+/).map(parseFloat).filter(o=>Number.isFinite(o)),a=(s,o,r)=>{const l=[];let u=o;for(const g of s)l.push([u,u+g]),u+=g+r;return l};return{cols:a(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:a(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var U=t=>t==="left"||t==="right",Ht={top:"bottom",bottom:"top",left:"right",right:"left"};function Le(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function qe(t,e,n){const a=[];t.edges.forEach((o,r)=>{const l=t.byId.get(o.from),u=t.byId.get(o.to),[g,h]=e[r],i=l.row===u.row&&U(g)&&U(h)&&g===Ht[h]||l.col===u.col&&!U(g)&&!U(h)&&g===Ht[h];a.push({edge:r,end:"from",node:l,side:g,far:u,straight:i,f:.5},{edge:r,end:"to",node:u,side:h,far:l,straight:i,f:.5})});const s=new Map;for(const o of a){const r=`${o.node.id}.${o.side}`;s.has(r)||s.set(r,[]),s.get(r).push(o)}for(const[o,r]of s){if(r[0].node.shape==="decision")continue;const l=i=>U(i.side)?i.far.row-i.node.row:i.far.col-i.node.col,u=r.filter(i=>i.straight),g=r.filter(i=>!i.straight);g.sort((i,f)=>l(i)-l(f)||(U(i.side)?i.far.col-f.far.col:i.far.row-f.far.row)*(l(i)<0?1:-1)),r.length>3&&n(`${o.replace(".","'s ")} side has ${r.length} lines; more than three is an error: use another side`),u.length?g.forEach(i=>{i.f=l(i)<0?.25:.75}):g.length===2?(g[0].f=.25,g[1].f=.75):g.length===3?(g[0].f=.25,g[1].f=.5,g[2].f=.75):g.length>3&&g.forEach((i,f)=>{i.f=(f+1)/(g.length+1)});const h=new Map;for(const i of u)h.has(i.far.id)||h.set(i.far.id,[]),h.get(i.far.id).push(i);for(const i of h.values())i.length>1&&i.sort((f,x)=>f.edge-x.edge).forEach((f,x)=>{f.f=i.length===2?x===0?.25:.75:(x+1)/(i.length+1)})}return a}function Nt(t,e,n){const{l:a,t:s,r:o,b:r}=t.rect;return U(e)?nt(t,e,s+(r-s)*n):nt(t,e,a+(o-a)*n)}function zt(t,e,n,a){const s=new Map;return e.querySelectorAll(`.${a}-node`).forEach(o=>{const r=t.byId.get(o.dataset.node);r&&s.set(r.id,{id:r.id,rect:rt(o,n),shape:r.shape,i:r.i})}),s}function Wt(t,e){const n=e.head,a=e.head/2,{x:s,y:o}=t.tip;return t.dir==="down"?{l:s-a,r:s+a,t:o-n,b:o}:t.dir==="up"?{l:s-a,r:s+a,t:o,b:o+n}:t.dir==="right"?{l:s-n,r:s,t:o-a,b:o+a}:{l:s,r:s+n,t:o-a,b:o+a}}var Gt=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function Ie(t,e,n,a,s,o,r,l){const u=r.space,g=[],h=[],i=[],f=[],x=u("1"),m=e.filter(d=>t.edges[d.i]?.label).sort((d,y)=>+(t.edges[y.i].kind==="main")-+(t.edges[d.i].kind==="main")||d.i-y.i);for(const d of m){const y=t.edges[d.i].label,w=l(y,"label"),q=16,E=d.pts.length-2,L=[];ct(d.pts).forEach(([c,p],b)=>{const k=Math.abs(c.y-p.y)<.01,R=k?c.x:c.y;let M=k?p.x:p.y;const G=Math.sign(M-R)||1;b===E&&(M-=G*r.head);let C=[[R,M]];for(const V of s)for(const Z of k?[V.l,V.r]:[V.t,V.b]){const Y=k?c.y:c.x;(k?Y>V.t&&Y<V.b:Y>V.l&&Y<V.r)&&(C=C.flatMap(([O,T])=>Z>Math.min(O,T)+1&&Z<Math.max(O,T)-1?[[O,Z],[Z,T]]:[[O,T]]))}const K=(V,Z)=>{const Y=(V+Z)/2,S=k?{x:Y,y:c.y}:{x:c.x,y:Y};return!s.some(O=>S.x>O.l&&S.x<O.r&&S.y>O.t&&S.y<O.b)},W=d.axes?.[b]??(k?c.y:c.x);for(const[V,Z]of C)L.push({horiz:k,c:W,p:V,q:Z,len:Math.abs(Z-V),pri:C.length>1&&K(V,Z)?1:0})}),L.sort((c,p)=>p.pri-c.pri||p.len-c.len);let _=null,j=!1;const B=(c,p=!0)=>{const b=Tt(c,x);return p&&(c.l<o.l||c.r>o.r||c.t<o.t||c.b>o.b)||n.some(k=>jt(b,k))||g.some(k=>lt(b,k))||a.heads.some(k=>lt(b,k))||a.rects.some(k=>lt(b,k))?!1:!e.some(k=>k.i!==d.i&&ct(k.pts).some(([R,M])=>lt(b,Gt(R,M,k.width))))};for(const c of L){for(const p of[1/2,1/3,2/3]){const b=c.p+(c.q-c.p)*p,k=[],R=u("2")+d.width/2;if(c.horiz?(c.len>=w+2*u("1")+u("3-5")&&k.push({box:{l:b-w/2-u("1"),r:b+w/2+u("1"),t:c.c-q/2,b:c.c+q/2},on:!0}),k.push({box:{l:b-w/2,r:b+w/2,t:c.c-R-q,b:c.c-R},on:!1}),k.push({box:{l:b-w/2,r:b+w/2,t:c.c+R,b:c.c+R+q},on:!1})):(c.len>=q+u("3")&&k.push({box:{l:c.c-w/2-u("1"),r:c.c+w/2+u("1"),t:b-q/2,b:b+q/2},on:!0}),k.push({box:{l:c.c+R,r:c.c+R+w,t:b-q/2,b:b+q/2},on:!1}),k.push({box:{l:c.c-R-w,r:c.c-R,t:b-q/2,b:b+q/2},on:!1})),_=k.find(M=>B(M.box))??null,_)break;!j&&k.some(M=>B(M.box,!1))&&(j=!0)}if(_)break}if(!_){i.push(d.i),j&&f.push(d.i);continue}g.push(_.box),h.push({i:d.i,text:y,box:_.box,on:_.on})}return{labels:h,unseated:i,bounded:f}}function Dt(t,e,n,a){const s=[],o=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const l=rt(r,e);o.push(l),s.push({l:l.l,r:l.r,t:l.t,b:l.t+1},{l:l.l,r:l.r,t:l.b-1,b:l.b},{l:l.l,r:l.l+1,t:l.t,b:l.b},{l:l.r-1,r:l.r,t:l.t,b:l.b});const u=r.querySelector(`:scope > .${n}-glabel`);u&&u.getClientRects().length&&s.push(rt(u,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,l)=>{if(!r.getClientRects().length)return;const u=rt(r,e);l>0&&s.push({l:u.l,r:u.r,t:u.t-a/2-.5,b:u.t-a/2+.5});const g=r.querySelector(`.${n}-lane-name`);g&&s.push(rt(g,e))}),{obstacles:{rects:s,heads:[]},groups:o}}function Oe(t,e){const{m:n,tk:a,P:s,drawing:o,origin:r,warn:l}=t,u=a.space,g=zt(n,o,r,s),h=[...g.values()],i=Ae(o),f=r.left-Math.floor(r.left),x=r.top-Math.floor(r.top),m=Rt(f,x),d=o.clientWidth,y=o.clientHeight,w=S=>n.type==="data-flow"?S.col+1:S.col,q=parseFloat(getComputedStyle(o).rowGap)||0,E={w:d,h:y,nodes:h,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:f,oy:x};if(n.type==="sequence")return Ce(t,E,m);let L,_=[];n.type==="schema"?L=n.edges.map(S=>{const O=n.byId.get(S.from),T=n.byId.get(S.to);if(O.col===T.col){const A=O.col===n.cols?"left":"right";return[A,A]}return T.col>O.col?["right","left"]:["left","right"]}):(L=n.edges.map(S=>{const O=n.byId.get(S.from),T=n.byId.get(S.to),[A,I]=Le(O,T);return[S.fromSide??A,S.toSide??I]}),_=qe(n,L,l??(()=>{})));const j=(S,O)=>{const T=o.querySelector(`.${s}-node[data-node="${CSS.escape(S)}"] .${s}-row[data-row="${O}"]`);if(!T)return 0;const A=rt(T,r);return(A.t+A.b)/2},B=n.edges.map((S,O)=>{const[T,A]=L[O],I=g.get(S.from),N=g.get(S.to),H=$t(S.kind,a);if(S.fk){const D=j(S.from,S.fromRow),tt=j(S.to,S.toRow),et=m.y(D,H),P=m.y(tt,H);return{p1:{x:T==="right"?I.rect.r:I.rect.l,y:et},p2:{x:A==="right"?N.rect.r:N.rect.l,y:P},r1:D,r2:Math.abs(et-P)<.01?D:tt}}const X=_.find(D=>D.edge===O&&D.end==="from").f,Q=_.find(D=>D.edge===O&&D.end==="to").f;let z=Nt(I,T,X),v=Nt(N,A,Q);const F=U(T)?z.y:z.x;let J=U(A)?v.y:v.x;return U(T)?z={...z,y:m.y(z.y,H)}:z={...z,x:m.x(z.x,H)},U(A)?v={...v,y:m.y(v.y,H)}:v={...v,x:m.x(v.x,H)},U(T)&&U(A)&&Math.abs(z.y-v.y)<1.01&&(v={...v,y:z.y},J=F),!U(T)&&!U(A)&&Math.abs(z.x-v.x)<1.01&&(v={...v,x:z.x},J=F),z=U(T)?nt(I,T,z.y):nt(I,T,z.x),v=U(A)?nt(N,A,v.y):nt(N,A,v.x),{p1:z,p2:v,r1:F,r2:J}}),c=new Set;n.type==="schema"&&n.edges.forEach((S,O)=>{Math.abs(n.byId.get(S.from).col-n.byId.get(S.to).col)>1&&c.add(O)});const p=new Map,b=new Set;n.edges.forEach((S,O)=>{if(c.has(O))return;const[T,A]=L[O],{p1:I,p2:N}=B[O],H=n.byId.get(S.from),X=n.byId.get(S.to);let Q=null,z=null,v=!1;if(T===A){if(U(T)){const D=T==="right"?Math.max(w(H),w(X)):Math.min(w(H),w(X))-1,tt=i.cols[D-1],et=i.cols[D];tt&&et&&(Q=`c${D}`,z=[tt[1],et[0]],v=!0)}else{const D=T==="bottom"?Math.max(H.row2,X.row2):Math.min(H.row,X.row)-1,tt=i.rows[D-1],et=i.rows[D];tt&&et&&(Q=`r${D}`,z=[tt[1],et[0]],v=!1)}Q&&b.add(O)}else if(U(T)&&U(A)&&Math.abs(I.y-N.y)>.5){const D=w(X),tt=A==="left",et=i.cols[(tt?D-1:D)-1],P=i.cols[(tt?D:D+1)-1];et&&P&&(Q=`c${tt?D-1:D}`,z=[et[1],P[0]],v=!0)}else if(!U(T)&&!U(A)&&Math.abs(I.x-N.x)>.5){const tt=A==="top"?X.row-1:X.row2,et=i.rows[tt-1],P=i.rows[tt];et&&P&&(Q=`r${tt}`,z=[et[1],P[0]],v=!1)}if(!Q||!z)return;p.has(Q)||p.set(Q,{span:z,vertical:v,members:new Map});const F=`${S.to}.${A}.${Math.round(v?N.y:N.x)}`,J=p.get(Q);J.members.has(F)||J.members.set(F,[]),J.members.get(F).push(O)});const k=new Map,R=S=>{const[O,T]=L[S],{p1:A,p2:I}=B[S];if(U(O)&&U(T)){if(O===T){const H=k.get(S)??(O==="right"?Math.max(A.x,I.x)+u("4"):Math.min(A.x,I.x)-u("4"));return[A,{x:H,y:A.y},{x:H,y:I.y},I]}if(Math.abs(A.y-I.y)<=.5)return[A,{x:I.x,y:A.y}];const N=k.get(S)??(A.x+I.x)/2;return[A,{x:N,y:A.y},{x:N,y:I.y},I]}if(!U(O)&&!U(T)){if(O===T){const H=k.get(S)??(O==="bottom"?Math.max(A.y,I.y)+u("4"):Math.min(A.y,I.y)-u("4"));return[A,{x:A.x,y:H},{x:I.x,y:H},I]}if(Math.abs(A.x-I.x)<=.5)return[A,{x:A.x,y:I.y}];const N=k.get(S)??(A.y+I.y)/2;return[A,{x:A.x,y:N},{x:I.x,y:N},I]}return U(O)?[A,{x:I.x,y:A.y},I]:[A,{x:A.x,y:I.y},I]},M=S=>{const O=n.edges[S],T=$t(O.kind,a),A=R(S),I=Ft(A,T,m);let N;return A.length===I.length&&(N=ct(A).map(([H,X])=>Math.abs(H.y-X.y)<.75?(H.y+X.y)/2:(H.x+X.x)/2),N[0]=B[S].r1,N.length>1&&(N[N.length-1]=B[S].r2)),{i:S,from:O.from,to:O.to,kind:O.kind,pts:I,tip:I[I.length-1],dir:kt(I),dot:O.fk?I[0]:void 0,width:T,axes:N}},G=()=>n.edges.flatMap((S,O)=>c.has(O)?[]:[M(O)]);let C=null;const K=S=>{C??(C=G());const O=C.map(T=>S.has(T.i)?M(T.i):T);return{lines:O,score:_e(O,S)*1e5+xt(O,void 0,S).length*1e3+St(O.filter(T=>S.has(T.i)),h,n).length}},W=(S,O)=>{const T=S.flatMap(A=>{const{p1:I,p2:N}=B[A];return O?[I.y,N.y]:[I.x,N.x]});return[Math.min(...T),Math.max(...T)]};for(const[,S]of p){const O=[...S.members.values()].map(A=>({members:A,run:W(A,S.vertical)})).sort((A,I)=>A.run[0]-I.run[0]),T=[];for(const A of O){const I=T[T.length-1];I&&I.some(N=>N.run[0]<A.run[1]+u("8")&&A.run[0]<N.run[1]+u("8"))?I.push(A):T.push([A])}for(const A of T){if(A.every(F=>F.members.every(J=>b.has(J))))continue;const I=A.map(F=>F.members),N=I.length,H=(S.span[1]-S.span[0])/(N+1);H<u("3")&&l?.(`a gutter holds ${N} lanes side by side, closer than space-3`);const X=new Set(I.flat());let Q=I,z=1/0,v=null;for(const F of Kt(I)){F.forEach((D,tt)=>D.forEach(et=>k.set(et,S.span[0]+H*(tt+1))));const J=K(X);J.score<z&&(z=J.score,Q=F,v=J.lines)}Q.forEach((F,J)=>F.forEach(D=>k.set(D,S.span[0]+H*(J+1)))),C=v}}E.lines=G();for(const S of c)l?.(`${n.edges[S].from} to ${n.edges[S].to} is two columns apart, so its line is not drawn; its row still writes the target`);E.crossings=xt(E.lines),E.through=St(E.lines,h,n),E.outside=Vt(E.lines,d,y,a);const{obstacles:V,groups:Z}=Dt(o,r,s,q);V.heads=E.lines.map(S=>Wt(S,a));const Y=Ie(n,E.lines,h,V,Z,{l:0,t:0,r:d,b:y},a,e);return E.labels=Y.labels,E.unseated=Y.unseated,E.bounded=Y.bounded,E}function _e(t,e){let n=0;for(let a=0;a<t.length;a++)for(let s=a+1;s<t.length;s++){const o=t[a],r=t[s];if(!e.has(o.i)&&!e.has(r.i)||o.to===r.to&&Math.abs(o.tip.x-r.tip.x)<1&&Math.abs(o.tip.y-r.tip.y)<1)continue;const l=(o.width+r.width)/2+.5;for(const[u,g]of ct(o.pts))for(const[h,i]of ct(r.pts)){const f=Math.abs(u.y-g.y)<.01,x=Math.abs(h.y-i.y)<.01;if(f!==x)continue;const[m,d]=f?[u.y,h.y]:[u.x,h.x];if(Math.abs(m-d)>=l)continue;const[y,w]=f?[u.x,g.x]:[u.y,g.y],[q,E]=f?[h.x,i.x]:[h.y,i.y];Math.min(Math.max(y,w),Math.max(q,E))-Math.max(Math.min(y,w),Math.min(q,E))>1&&n++}}return n}function*Kt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e<t.length;e++){const n=t.slice(0,e).concat(t.slice(e+1));for(const a of Kt(n))yield[t[e],...a]}}function Vt(t,e,n,a){const s=[];for(const o of t)o.pts.some((r,l)=>{const u=l===o.pts.length-1?Math.max(o.width/2,a.head/2):o.width/2;return r.x-u<-.5||r.x+u>e+.5||r.y-u<-.5||r.y+u>n+.5})&&s.push(o.i);return s}function St(t,e,n){const a=[];for(const s of t){const o=ct(s.pts);e.some(r=>o.some(([l,u])=>ke(l,u,r)))&&a.push(s.i)}return a}function Ce(t,e,n){const{m:a,tk:s,P:o,drawing:r,origin:l}=t,u=s.space,g=new Map;r.querySelectorAll(`.${o}-node`).forEach(m=>g.set(m.dataset.node,rt(m,l)));const h=r.querySelector(`.${o}-steps`),i=h?rt(h,l).b:e.h,f=m=>{const d=g.get(m);return d?n.x((d.l+d.r)/2,s.hair):0};for(const m of a.nodes){const d=g.get(m.id);d&&e.lifelines.push({x:f(m.id),y1:d.b,y2:i})}const x=m=>g.get(m.id);return r.querySelectorAll(`.${o}-msg`).forEach(m=>{const d=m.dataset.from,y=m.dataset.to,w=m.dataset.kind??"plain",q=$t(w,s),E=rt(m,l),L=n.y((E.t+E.b)/2,q),_=Number(m.querySelector(`.${o}-num`)?.textContent??0),j=f(d),B=f(y);let c;if(d===y){const C=m.dataset.self==="start"?-u("6"):u("6"),K=n.y(L-u("2"),q),W=n.y(L+u("2"),q);c=[{x:j,y:K},{x:n.x(j+C,q),y:K},{x:n.x(j+C,q),y:W},{x:j,y:W}]}else c=[{x:j,y:L},{x:B,y:L}];e.lines.push({i:_,from:d,to:y,kind:w,pts:c,tip:c[c.length-1],dir:kt(c),width:q});const p=m.querySelector(`.${o}-said`),b=m.querySelector(`.${o}-note`),k=a.byId.get(d),R=a.byId.get(y);if(!k||!R)return;const M=d===y?(()=>{const C=a.nodes[k.i+(m.dataset.self==="start"?-1:1)],K=C?f(C.id):m.dataset.self==="start"?0:e.w;return Math.abs(K-j)-u("6")-u("2-5")-u("2")})():Math.abs(B-j)-2*u("2");Math.max(p?p.getBoundingClientRect().width:0,b?b.getBoundingClientRect().width:0)>M+.5&&e.unseated.push(_)}),e}function Zt(t,e,n,a=ut()){const{m:s,tk:o,P:r,drawing:l,origin:u}=t,g=o.space,h=zt(s,l,u,r),i=[...h.values()],f=u.left-Math.floor(u.left),x=u.top-Math.floor(u.top),m=Rt(f,x),d=l.clientWidth,y=l.clientHeight,w={w:d,h:y,nodes:i,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:f,oy:x},q=ut();if(s.type==="sequence"||s.type==="schema")return{geo:w,grow:q};const E=d-(parseFloat(getComputedStyle(l).paddingRight)||0),L=(M,G,C)=>{const K=[M];for(let W=1;W<=(ht(a,G)??0);W++)K.push({...M,t:M.t+C*g("4")*W,b:M.b+C*g("4")*W});return K},_=new Map;l.querySelectorAll(`.${r}-node`).forEach(M=>{const G=M.parentElement,C=rt(G,u),K=getComputedStyle(G);_.set(M.dataset.node,C.r-(parseFloat(K.paddingRight)||0)-(parseFloat(K.borderRightWidth)||0))});const j=s.nodes,B=M=>h.get(j[M].id),c=[],p=M=>$t(s.edges[M].kind,o);s.edges.forEach((M,G)=>{const C=n.routes[G],K=h.get(M.from),W=h.get(M.to),V=p(G);let Z=[];const Y=M.label,S=Y?e(Y,"label"):0,O=16,T=g("4");if(C==="down"||C==="up"){const I=Math.max(K.rect.l,W.rect.l),N=Math.min(K.rect.r,W.rect.r),H=s.edges.map((v,F)=>({o:v,j:F})).filter(({o:v,j:F})=>(n.routes[F]==="down"||n.routes[F]==="up")&&(v.from===M.from&&v.to===M.to||v.from===M.to&&v.to===M.from)),X=H.findIndex(v=>v.j===G),Q=H.length<2?.5:H.length===2?X===0?.25:.75:(X+1)/(H.length+1),z=m.x(I+(N-I)*Q,V);if(Z=C==="down"?[nt(K,"bottom",z),nt(W,"top",z)]:[nt(K,"top",z),nt(W,"bottom",z)],Y){let v=Math.min(Z[0].y,Z[1].y),F=Math.max(Z[0].y,Z[1].y);C==="down"?F-=o.head:v+=o.head;const J=[...l.querySelectorAll(`.${r}-group`)].map(P=>rt(P,u));let D=[[v,F]];for(const P of J)for(const it of[P.t,P.b])D=D.flatMap(([st,dt])=>it>st+1&&it<dt-1?[[st,it],[it,dt]]:[[st,dt]]);const tt=(P,it)=>J.some(st=>(P+it)/2>st.t&&(P+it)/2<st.b&&z>st.l&&z<st.r);if(D.length>1){const P=D.filter(([st,dt])=>!tt(st,dt));[v,F]=(P.length?P:D).reduce((st,dt)=>dt[1]-dt[0]>st[1]-st[0]?dt:st)}const et=[1/2,1/3,2/3].map(P=>{const it=v+(F-v)*P;return{l:z-S/2-g("1"),r:z+S/2+g("1"),t:it-O/2,b:it+O/2}});c.push({k:G,cands:et,on:!0,card:C==="down"?M.to:M.from})}}else if(C==="trunk"||C==="rail"){const I=m.x(Math.max(K.rect.l,C==="rail"?W.rect.l:K.rect.l)+g(C==="trunk"?"8":"3"),V),N=nt(K,"bottom",I);if(C==="rail"){if(Z=[N,nt(W,"top",I)],Y){const H=W.rect.t-g("6");c.push({k:G,cands:L({l:I+g("2-5"),r:I+g("2-5")+S,t:H-O/2,b:H+O/2},M.to,-1),on:!1,card:M.to})}}else{const H=m.x(W.rect.l+g("6"),V),X=m.y(W.rect.t-T,V);Z=[N,{x:I,y:X},{x:H,y:X},nt(W,"top",H)],Y&&c.push({k:G,cands:L({l:H+g("2-5"),r:H+g("2-5")+S,t:X-O/2,b:X+O/2},M.to,-1),on:!1,card:M.to})}}else{const I=Math.min(_.get(M.from)??d,_.get(M.to)??d),N=m.x(n.gutter?E+(n.lanes[G]?2*g("3-5"):g("3-5")):I-g("2-5"),V),H=m.y(K.rect.t+(K.rect.b-K.rect.t)*n.exits[G],V),X=nt(K,"right",H),Q=m.x(W.rect.r-g("6"),V),z=C==="end-down",v=m.y(z?W.rect.t-T:W.rect.b+T,V);Z=[X,{x:N,y:X.y},{x:N,y:v},{x:Q,y:v},nt(W,z?"top":"bottom",Q)];const F=z?M.to:j[W.i+1]?.id??M.to;Y&&c.push({k:G,cands:L({l:Q-g("2-5")-S,r:Q-g("2-5"),t:v-O/2,b:v+O/2},F,z?-1:1),on:!1,card:F})}const A=Ft(Z,V,m);w.lines.push({i:G,from:M.from,to:M.to,kind:M.kind,pts:A,tip:A[A.length-1],dir:kt(A),width:V})}),w.crossings=xt(w.lines),w.through=St(w.lines,i,s),w.outside=Vt(w.lines,d,y,o);const{obstacles:b}=Dt(l,u,r,0);b.heads=w.lines.map(M=>Wt(M,o));const k=[],R={l:0,t:0,r:d,b:y};for(const M of c){const G=W=>{const V=Tt(W,g("1"));return W.l<R.l-.5||W.r>R.r+.5||W.t<R.t-.5||W.b>R.b+.5||i.some(Z=>jt(V,Z))||k.some(Z=>lt(V,Z))||b.heads.some(Z=>lt(V,Z))||b.rects.some(Z=>lt(V,Z))||w.lines.some(Z=>Z.i!==M.k&&ct(Z.pts).some(([Y,S])=>lt(V,Gt(Y,S,Z.width))))},C=M.cands.find(W=>!G(W));C||(q[M.card]=(q[M.card]??0)+1,w.unseated.push(M.k));const K=C??M.cands[0];k.push(K),w.labels.push({i:M.k,text:s.edges[M.k].label,box:K,on:M.on})}return{geo:w,grow:q}}function Be(t,e){const n=o=>String(Math.round(o*100)/100);let a=`M${n(t[0].x)} ${n(t[0].y)}`;for(let o=1;o<t.length-1;o++){const r=t[o-1],l=t[o],u=t[o+1],g=Math.hypot(l.x-r.x,l.y-r.y),h=Math.hypot(u.x-l.x,u.y-l.y),i=Math.min(e,g/2,h/2);if(i<.5){a+=`L${n(l.x)} ${n(l.y)}`;continue}const f={x:l.x+(r.x-l.x)/g*i,y:l.y+(r.y-l.y)/g*i},x={x:l.x+(u.x-l.x)/h*i,y:l.y+(u.y-l.y)/h*i};a+=`L${n(f.x)} ${n(f.y)}Q${n(l.x)} ${n(l.y)} ${n(x.x)} ${n(x.y)}`}const s=t[t.length-1];return`${a}L${n(s.x)} ${n(s.y)}`}var Te={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function je(t,e,n,a,s){const o=Te[e.dir],r=e.kind==="dashed",l=n.head,u=n.head/2,g=r?1:l-1,h=e.pts.map(L=>({...L})),i=h[h.length-1];i.x-=o.x*g,i.y-=o.y*g;const f=e.tip.x-o.x*l,x=e.tip.y-o.y*l,m=-o.y*u,d=o.x*u,y=L=>Math.round(L*100)/100,w=at(e.kind),q=r?`<path class="${t}-tip" data-kind="${w}" data-open="" d="M${y(f+m)} ${y(x+d)}L${y(e.tip.x)} ${y(e.tip.y)}L${y(f-m)} ${y(x-d)}"/>`:`<path class="${t}-tip" data-kind="${w}" d="M${y(e.tip.x)} ${y(e.tip.y)}L${y(f+m)} ${y(x+d)}L${y(f-m)} ${y(x-d)}Z"/>`,E=e.dot?`<circle class="${t}-dot" cx="${y(e.dot.x)}" cy="${y(e.dot.y)}" r="${n.dot/2}"/>`:"";return`<g class="${t}-edge" data-edge="${e.i}" data-from="${at(e.from)}" data-to="${at(e.to)}"><path class="${t}-line" data-kind="${w}" d="${Be(h,s)}"${a?` mask="url(#${at(a)})"`:""}/>${q}${E}</g>`}function Xt(t,e,n,a){const s=new Map,o=new Map;for(const l of e.crossings)o.has(l.under)||o.set(l.under,[]),o.get(l.under).push(l);let r="";for(const[l,u]of o){const g=`${a}-cut-${l}`;s.set(l,g);const h=u.map(i=>{const f=e.lines[i.top],x=e.lines[i.under],m=f.width/2+n.cut,d=x.width/2+1;return i.underVertical?`<rect x="${i.at.x-d}" y="${i.at.y-m}" width="${2*d}" height="${2*m}" fill="black"/>`:`<rect x="${i.at.x-m}" y="${i.at.y-d}" width="${2*m}" height="${2*d}" fill="black"/>`}).join("");r+=`<mask id="${at(g)}" maskUnits="userSpaceOnUse" x="0" y="0" width="${e.w}" height="${e.h}"><rect x="0" y="0" width="${e.w}" height="${e.h}" fill="white"/>${h}</mask>`}return{defs:r,ids:s}}function Jt(t,e,n,a){const{defs:s,ids:o}=Xt(t,e,n,a),r=e.lifelines.map(h=>`<path class="${t}-life" d="M${h.x} ${h.y1}V${h.y2}"/>`).join(""),l=e.lines.map((h,i)=>je(t,h,n,o.get(i)??null,h.from===h.to?n.radiusXs:n.radius)).join(""),u=`<svg class="${t}-svg" width="${e.w}" height="${e.h}" viewBox="0 0 ${e.w} ${e.h}" focusable="false">${s?`<defs>${s}</defs>`:""}${r}<g class="${t}-edges">${l}</g></svg>`,g=e.labels.map(h=>`<span class="${t}-label" data-edge="${h.i}"${h.on?' data-on=""':""} style="left:${Math.round(h.box.l*100)/100}px;top:${Math.round(h.box.t*100)/100}px;width:${Math.round((h.box.r-h.box.l)*100)/100}px">${at(h.text)}</span>`).join("");return u+g}function Re(t,e,n,a,s,o,r){const l=t.querySelector(`.${n}-drawing`);if(!l||t.clientWidth===0)return{dyn:s,geo:null,ink:"",tokens:null};const u=Me(t),g=Se(l,n),h=Ee(e,u,g),i=t.clientWidth,f=(()=>{const B=document.activeElement;return B&&l.contains(B)&&B.dataset.node?B.dataset.node:void 0})(),x=B=>ft(e,B)?{...B,stop:B.stop&&e.byId.has(B.stop)?B.stop:e.nodes[0]?.id,keep:void 0}:{...B,stop:B.stop??e.nodes[0]?.id,keep:f&&B.layout!=="drawn"?f:void 0},m=B=>{if(e.type!=="flowchart")return B;o({...B,heights:void 0});const c=ut();return l.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(p=>{const b=p.querySelector(`.${n}-words`);if(!b)return;const k=p.getBoundingClientRect(),R=b.getBoundingClientRect(),M={w:R.width+2*u.space("2-5"),h:R.height+2*u.space("2")},G=k.width/2,C=1-M.w/2/G,K=C>.05?M.h/2/C:M.h*10;c[p.dataset.node]=Math.max(u.space("16"),Math.ceil(k.width/5),Math.ceil(2*K))}),{...B,heights:c}},d=()=>({m:e,tk:u,P:n,drawing:l,origin:l.getBoundingClientRect(),warn:r}),y=s.autoOpen?{open:!1,autoOpen:void 0}:{},w=(B,c)=>c.map(p=>mt(e,B.lines.find(b=>b.i===p))).join(", ");if(i>=h.least){const B=b=>{let k=x({...s,...y,layout:"drawn",grow:void 0,track:void 0,bare:void 0,pad:b||void 0});return k=m(k),o(k),{dd:k,g:Oe(d(),g)}};let{dd:c,g:p}=B(!1);if(!p.through.length&&!p.outside.length&&p.unseated.length&&p.unseated.every(b=>p.bounded?.includes(b))){const b=B(!0);!b.g.through.length&&!b.g.unseated.length&&!b.g.outside.length&&({dd:c,g:p}=b)}if(!p.through.length&&!p.unseated.length&&!p.outside.length)return p.crossings.length&&r?.(`${p.crossings.length} crossing${p.crossings.length===1?"":"s"} in the drawn layout: ${p.crossings.map(b=>`${mt(e,p.lines[b.top])} over ${mt(e,p.lines[b.under])}`).join("; ")}`),{dyn:c,geo:p,ink:Jt(n,p,u,a),tokens:u};p.through.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${w(p,p.through)} would pass through a node`),p.outside.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: ${w(p,p.outside)} would leave the drawing`),p.unseated.length&&r?.(`the drawn layout does not fit at ${Math.round(i)}px: no clean seat for ${p.unseated.map(b=>e.type==="sequence"?`message ${b}`:`"${e.edges[b]?.label}"`).join(", ")}`)}let q=x({...s,...y,layout:"stacked",heights:void 0,grow:ut(),track:e.type==="schema"?h.table:void 0,bare:void 0,pad:void 0});if(q=m(q),o(q),e.type==="sequence"||e.type==="schema")return{dyn:q,geo:null,ink:"",tokens:u};const E=Ot(e);let L=Zt(d(),g,E,q.grow);for(let B=0;B<6&&Object.keys(L.grow).length;B++){const c=ut(q.grow);for(const[p,b]of Object.entries(L.grow))c[p]=(ht(c,p)??0)+b;q={...q,grow:c},o(q),L=Zt(d(),g,E,c)}const _=L.geo;if(_.unseated.length>0||_.through.length>0||_.outside.length>0||E.third){_.unseated.length&&r?.(`the stacked drawing has no clean seat for ${[...new Set(_.unseated)].map(p=>`"${e.edges[p]?.label}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),_.through.length&&r?.(`in the stacked drawing ${w(_,_.through)} would pass through a node, so its lines are not drawn`),_.outside.length&&r?.(`in the stacked drawing ${w(_,_.outside)} would leave the drawing, so its lines are not drawn`),E.third&&r?.("the stacked drawing would need a third end lane, so its lines are not drawn");const B={..._,lines:[],labels:[],crossings:[]};return{dyn:x({...q,grow:ut(),bare:!0,open:s.bare?s.open:!0,autoOpen:s.bare?s.autoOpen:s.open?void 0:!0}),geo:B,ink:"",tokens:u}}return _.crossings.length&&r?.(`${_.crossings.length} crossing${_.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${_.crossings.map(B=>`${mt(e,_.lines[B.top])} over ${mt(e,_.lines[B.under])}`).join("; ")}`),{dyn:q,geo:_,ink:Jt(n,_,u,a),tokens:u}}function mt(t,e){const n=t.byId.get(e.from)?.name??e.from,a=t.byId.get(e.to)?.name??e.to;return`${n} to ${a}`}function Fe(t,e,n,a,s,o){const r=new Set;if(o){r.add(o);for(const d of n?.lines??[])d.from===o&&r.add(d.to),d.to===o&&r.add(d.from)}if(t.toggleAttribute("data-tracing",!!o),t.querySelectorAll(`.${e}-node`).forEach(d=>d.toggleAttribute("data-near",r.has(d.dataset.node))),!n||!a)return;const l=d=>!!o&&(d.from===o||d.to===o),u=t.querySelector(`.${e}-edges`),g=new Map;t.querySelectorAll(`.${e}-edge`).forEach(d=>g.set(d.getAttribute("data-edge"),d));for(const d of n.lines){const y=g.get(String(d.i));y&&(y.toggleAttribute("data-lit",l(d)),y.toggleAttribute("data-dim",!!o&&!l(d)))}if(t.querySelectorAll(`.${e}-label`).forEach(d=>{const y=n.lines.find(w=>String(w.i)===d.dataset.edge);d.toggleAttribute("data-lit",!!(y&&l(y)))}),u){for(const d of n.lines)if(l(d)){const y=g.get(String(d.i));y&&u.appendChild(y)}}const h=xt(n.lines,l),{defs:i,ids:f}=Xt(e,{...n,crossings:h},a,s),x=t.querySelector(`.${e}-svg`);if(!x)return;let m=x.querySelector("defs");!m&&i&&(m=document.createElementNS("http://www.w3.org/2000/svg","defs"),x.insertBefore(m,x.firstChild)),m&&(m.innerHTML=i),n.lines.forEach((d,y)=>{const w=g.get(String(d.i))?.querySelector(`.${e}-line`);if(!w)return;const q=f.get(y);q?w.setAttribute("mask",`url(#${q})`):w.removeAttribute("mask")})}function He(t,e,n){const a=t.byId.get(e)?.i??0,s=t.nodes.length;let o;if(n==="ArrowRight"||n==="ArrowDown")o=a+1;else if(n==="ArrowLeft"||n==="ArrowUp")o=a-1;else if(n==="Home")o=0;else if(n==="End")o=s-1;else return null;return t.nodes[Math.max(0,Math.min(s-1,o))].id}var Ne=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],Ut=["data-layout","data-measured","data-bare"],ze=["--_track","--_h","--_gap","--_ggrow","--_gpad"],Yt=t=>t==null||t===!1;function We(t,e){if(t.tagName.toLowerCase()!==e.t)return!1;const n=typeof e.a.class=="string"?e.a.class.split(" ")[0]:"";return!n||t.classList.contains(n)}function Qt(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const a=n?Ut:Ne;for(const r of a)Yt(e.a[r])&&t.removeAttribute(r);for(const[r,l]of Object.entries(e.a)){if(r==="class")continue;if(r==="style"){const g=t.style,h=new Map(String(l??"").split(";").map(i=>{const f=i.indexOf(":");return[i.slice(0,f).trim(),i.slice(f+1).trim()]}).filter(([i])=>i));for(const[i,f]of h)g.getPropertyValue(i).trim()!==f&&g.setProperty(i,f);for(const i of ze)h.has(i)||g.removeProperty(i);continue}if(n&&!Ut.includes(r))continue;if(Yt(l)){t.removeAttribute(r);continue}const u=l===!0?"":String(l);t.getAttribute(r)!==u&&t.setAttribute(r,u)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class)||e.c.some(r=>typeof r!="string"&&"slot"in r))return;const s=[...t.children];let o=0;for(const r of e.c)if(!(typeof r=="string"||"slot"in r)){for(let l=o;l<s.length;l++)if(We(s[l],r)){Qt(s[l],r,!1),o=l+1;break}}}function Ge(t,e,n,a){if(n===a)return;const s=o=>t.querySelector(`.${e}-node[data-node="${CSS.escape(o)}"]`);n&&s(n)?.setAttribute("tabindex","-1"),s(a)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",a=0;function s(i,f){return{prefix:n,base:i,hasSource:f.source!==void 0&&f.source!==null&&f.source!=="",hiddenClass:"visually-hidden"}}function o(i,f,x,m){var d=function(y){return'<kbd class="kbd">'+at(y)+"</kbd>"};return{source:at(String(f.source||"")),summary:at(String(f.summary||"")),hint:xe(i).map(function(y){return"<span>"+y.keys.map(d).join(" ")+" "+at(y.words)+"</span>"}).join(""),toggle:'<button type="button" class="btn diagram-toggle" data-variant="secondary" data-size="sm" aria-expanded="'+(m?"true":"false")+'" aria-controls="'+at(x)+'-list"><span>'+(m?"Hide the list":"View as list")+"</span></button>"}}function r(i,f){var x=Et(i),m=Bt(x,{},s(f,i)),d=qt(m,o(x,i,f,!1)),y=d.indexOf(">");return{open:d.slice(0,y+1),inner:d.slice(y+1,d.length-9),warnings:x.warnings}}var l=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-layout","data-measured","data-bare"],u=["--_cols","--_gpad","--_track"];function g(i,f,x){i.__diagram&&i.__diagram.stop();var m=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),d=Et(f);if(!x||!m||!i.querySelector(":scope > .diagram-drawing")){if(!m||!i.querySelector("#"+CSS.escape(m+"-title"))){for(;document.getElementById("dg"+ ++a+"-title"););m="dg"+a}var y=r(f,m),w=document.createElement("div");w.innerHTML=y.open+"</figure>";var q=w.firstChild;l.forEach(function(v){i.removeAttribute(v)}),u.forEach(function(v){i.style.removeProperty(v)});for(var E=0;E<q.attributes.length;E++){var L=q.attributes[E];L.name==="class"?i.classList.add.apply(i.classList,L.value.split(" ")):L.name==="style"?i.style.cssText=L.value+";"+i.style.cssText:i.setAttribute(L.name,L.value)}i.querySelectorAll(":scope > :not(script[data-diagram])").forEach(function(v){v.remove()}),i.insertAdjacentHTML("beforeend",y.inner)}d.warnings.forEach(function(v){console.warn("Basalt diagram: "+v)});var _=s(m,f),j={},B=null,c=null,p=null,b=Object.create(null),k=function(v){b[v]||(b[v]=1,console.warn("Basalt diagram: "+v))},R=function(v){Qt(i,Bt(d,v,_))},M=i.querySelector(".diagram-ink"),G=i.querySelector(".diagram-toggle");function C(){Fe(i,n,B&&B.geo,B&&B.tokens,m,c||p)}function K(){G&&(G.setAttribute("aria-expanded",String(!!j.open)),G.firstElementChild.textContent=j.open?"Hide the list":"View as list")}function W(){B=Re(i,d,n,m,j,R,k),j=B.dyn,R(j),K(),ft(d,j)||(p=null),M&&(M.innerHTML=B.ink),C()}function V(v){j=v,R(j)}function Z(v){var F=j.stop;j=Object.assign({},j,{stop:v}),Ge(i,n,F,v)}var Y=function(v){var F=v&&v.closest?v.closest(".diagram-node"):null;return F&&i.contains(F)?F:null};function S(v){var F=Y(v.target);if(!(!F||v.defaultPrevented)){if(v.key==="Escape"){(c||p)&&(v.preventDefault(),c=p=null,C());return}if(ft(d,j)){var J=He(d,F.getAttribute("data-node"),v.key);if(J){v.preventDefault(),Z(J);var D=i.querySelector('.diagram-node[data-node="'+CSS.escape(J)+'"]');D&&D.focus()}}}}function O(v){var F=Y(v.target);if(F){var J=F.getAttribute("data-node");c=F.matches(":focus-visible")?J:null,ft(d,j)&&j.stop!==J&&Z(J),C()}}function T(v){var F=Y(v.target);F&&(Y(v.relatedTarget)||(c=null),j.keep===F.getAttribute("data-node")&&V(Object.assign({},j,{keep:void 0})),C())}function A(v){if(!(v.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var F=Y(v.target),J=F&&ft(d,j)?F.getAttribute("data-node"):null;J!==p&&(p=J,C())}}function I(){p&&(p=null,C())}function N(){V(Object.assign({},j,{open:!j.open,autoOpen:void 0})),K()}i.addEventListener("keydown",S),i.addEventListener("focusin",O),i.addEventListener("focusout",T),i.addEventListener("pointerover",A),i.addEventListener("pointerleave",I),G&&G.addEventListener("click",N),W();var H=i.clientWidth,X=0,Q=!0,z=new ResizeObserver(function(){Math.abs(i.clientWidth-H)<.5||(H=i.clientWidth,cancelAnimationFrame(X),X=requestAnimationFrame(W))});z.observe(i),document.fonts&&document.fonts.ready.then(function(){Q&&W()}),i.__diagram={stop:function(){Q=!1,z.disconnect(),cancelAnimationFrame(X),i.removeEventListener("keydown",S),i.removeEventListener("focusin",O),i.removeEventListener("focusout",T),i.removeEventListener("pointerover",A),i.removeEventListener("pointerleave",I),G&&G.removeEventListener("click",N)},layout:W}}function h(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var f=i.querySelector(":scope > script[data-diagram]");if(f)try{g(i,JSON.parse(f.textContent),!0)}catch(x){console.error("Basalt diagram: this figure could not be drawn",x)}}})}e.diagramMarkup=r,t.diagram=function(i,f){g(i,f)},e.step(62,"wireDiagrams",h)})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/manifest.json b/.agent/skills/basalt-html/parts/manifest.json index 13dc1eaa..2ce034a6 100644 --- a/.agent/skills/basalt-html/parts/manifest.json +++ b/.agent/skills/basalt-html/parts/manifest.json @@ -722,6 +722,7 @@ "diagram-hint", "diagram-ink", "diagram-key", + "diagram-key-letters", "diagram-keyseat", "diagram-kind", "diagram-label", @@ -748,6 +749,7 @@ "diagram-row", "diagram-rows", "diagram-ruler", + "diagram-run", "diagram-said", "diagram-source", "diagram-steps", diff --git a/docs/foundations.md b/docs/foundations.md index 4322d893..5d689c6f 100644 --- a/docs/foundations.md +++ b/docs/foundations.md @@ -1691,7 +1691,8 @@ monochrome. Nothing takes a colour, the accent or a status. One node may be foca - Text is `text-xs` or `text-sm`. Nothing is under 12px. The drawing is laid out in real CSS pixels at its own measured width, never scaled through a `viewBox`, and nothing scrolls sideways. - A node is a panel one level above what the figure sits in: the rim, no shadow, radius 8, `space-2-5` by `space-3`. Its lines are a - kind (`text-xs` Mono, tertiary), a name (`text-sm` 600) and a detail (`text-xs` secondary, Mono only for an identifier). + kind (`text-xs` Mono, tertiary), a name (`text-sm` 600) and a detail (`text-xs` secondary, Mono only for an identifier). A Mono + detail breaks only at its spaces, never at a hyphen, and keeps the ordinary hyphen so a copy is exact (the decider's answers, review round 64). - **The focal node** is inverted: `diagram-focal` under `diagram-focal-ink`, its quiet lines at `opacity-amount`. One at most. The key says what it marks. @@ -1710,7 +1711,8 @@ monochrome. Nothing takes a colour, the accent or a status. One node may be foca - **A label** is `text-xs` Mono in secondary ink, one line, never cut. On its own line it has a ground-colour plate; beside its line it is `space-2` clear of the stroke. Seats are taken along the run's clear shaft (the run without its head). A seat is taken only if the label, grown `space-1`, overlaps no node as drawn (the diamond or the capsule, not its box), label, head, boundary, rule or other - line. + line. A seat is measured from its line's place before the half-pixel snap, so whether it fits never turns on which way a half pixel + fell, and from the first width a diagram draws at, it draws at every wider one (the decider's answers, review round 64). ### Fit @@ -1722,6 +1724,10 @@ monochrome. Nothing takes a colour, the accent or a status. One node may be foca A line that leaves or passes a spine card runs in an end gutter outside the cards (`space-10`, two lanes at most), down into a card's top or up into its bottom. A data flow is its steps in order with bypasses in that gutter. A sequence is a strip of participants and a numbered list that names each message's sender, receiver and kind. A schema is its cards in an auto-fit grid with no lines, because every foreign-key row writes its target. +- **A stack that would still overlap draws no lines** (the decider's answers, review round 64): a drawing known to overlap is never drawn, and all its lines go, + not some. It is dressed as where scripting is off: no line in the key, no key hint, no roving stops, and the list open (the toggle + stays and reads "Hide the list"). This is the one exception to every edge and label being present at every width; a development + build says so. - A name or a label is never cut at any width. ### The types @@ -1741,7 +1747,8 @@ monochrome. Nothing takes a colour, the accent or a status. One node may be foca ### The key, the summary and the list - The key is under the drawing and is built from the marks actually drawn, each swatch drawn like its mark. The author writes the - words. Main, dashed and the focal node must have them. + words. Main, dashed and the focal node must have them. A schema's key starts with the key seats it uses, the letters set as the + seat sets them, then "Primary key" and "Foreign key" (built in; the decider's answers, review round 64). - The summary is required. "View as list" opens the same facts as real lists in the same figure: the parts and connections, a flowchart's steps with each exit written once, a data flow's steps, a sequence's messages, a schema's tables. - The figure's words are in the HTML before script runs, and where scripting is off the list is open. Before script the figure is diff --git a/packages/react/src/diagram-core.ts b/packages/react/src/diagram-core.ts index 57dcc367..13466a60 100644 --- a/packages/react/src/diagram-core.ts +++ b/packages/react/src/diagram-core.ts @@ -142,6 +142,10 @@ const HEADINGS = [2, 3, 4, 5, 6]; /** Text from the author's data: always a string (or nothing), so a value that is not one can never be read as markup. */ const txt = (v: unknown): string | undefined => (v === undefined || v === null || v === "" ? undefined : String(v)); +/** A record keyed by the author's ids, with no prototype, so an id such as "toString" or "constructor" is only ever its own key. */ +const record = <T>(from?: Record<string, T>): Record<string, T> => Object.assign(Object.create(null) as Record<string, T>, from); +/** A value an id keys in a record, never one the record inherits. */ +const own = <T>(r: Record<string, T> | undefined, id: string): T | undefined => (r && Object.prototype.hasOwnProperty.call(r, id) ? r[id] : undefined); export interface BuildOptions { /** Run the checks a development build reports (placement, groups, the key's words). Off, the model is read the same and nothing is checked. */ @@ -315,7 +319,6 @@ const MAX_LABEL = 28; // ============================================================================================================================================ const sentence = (s: string) => { const t = s.trim(); return !t ? "" : /[.!?]$/.test(t) ? t : `${t}.`; }; -const upperFirst = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); /** A kind's word, from the key (none when the author gave none: an unkeyed plain line says "goes to"). */ export function kindWord(m: Model, kind: DiagramLineKind): string | undefined { return m.legend[kind]; } @@ -415,6 +418,13 @@ export interface Dyn { /** The schema's stacked track: its widest row, measured. */ track?: number; open?: boolean; + /** A stack that still overlaps after every try draws no lines (1.13): it is dressed as where scripting is off, with no line in the key, no + * key hint, no stops and the list open. */ + bare?: boolean; + /** The list was opened by a bare stack, not by the reader: it closes again when lines are drawn. A press of the toggle clears it. */ + autoOpen?: boolean; + /** The drawn layout keeps space-3 above its first row and below its last, so a label beside a line in a 40px row has a seat (1.8). */ + pad?: boolean; } export interface TreeIds { base: string } @@ -422,7 +432,7 @@ const idsOf = (base: string) => ({ title: `${base}-title`, summary: `${base}-sum /** Whether the figure's nodes are stops (a roving tab index) in this state. */ export function hasStops(m: Model, dyn: Dyn): boolean { - if (!dyn.layout) return false; + if (!dyn.layout || dyn.bare) return false; if (dyn.layout === "drawn") return true; return m.type !== "sequence" && m.type !== "schema"; } @@ -500,12 +510,13 @@ function planStack(m: Model): StackPlan { if (leaving.length < 2) continue; const down = leaving.filter(({ k }) => routes[k] === "end-down").sort((x, y) => travel(y.e) - travel(x.e) || x.k - y.k); const up = leaving.filter(({ k }) => routes[k] === "end-up").sort((x, y) => travel(x.e) - travel(y.e) || y.k - x.k); - [...down, ...up].forEach(({ k }, j, all) => { exits[k] = all.length === 2 ? (j === 0 ? 1 / 3 : 2 / 3) : (j + 1) / (all.length + 1); }); + // The lines going up leave above the lines going down, so a line out each way from one card never runs on the other in the lane. + [...up, ...down].forEach(({ k }, j, all) => { exits[k] = all.length === 2 ? (j === 0 ? 1 / 3 : 2 / 3) : (j + 1) / (all.length + 1); }); } // The gap above each card (1.13): 32 for a plain entry, 40 for a branch entry with its label beside the elbow, 48 for a labelled stem, rail // entry or end-line turn, 64 when two labelled entries share it or a turn from the card above and a turn into the card below share it. // A data flow keeps 48 between every step. - const gaps: Record<string, number> = {}; + const gaps = record<number>(); for (let b = 1; b < order.length; b++) { const card = order[b]!, above = order[b - 1]!; let labelled = 0, gap = m.type === "data-flow" ? 48 : 32, turnInto = false, turnFrom = false; @@ -559,6 +570,13 @@ function keyTree(P: string, m: Model): VElement | null { function buildKey(P: string, m: Model): VElement | null { const entries: VElement[] = []; const entry = (swatch: VElement, words: string, attrs: VAttrs = {}) => entries.push(h("li", { class: `${P}-entry`, ...attrs }, swatch, h("span", null, words))); + if (m.type === "schema") { + // The key seats' letters first, each where a seat holds it, set as the seat sets them, then their words. + const keys = new Set(m.nodes.flatMap((n) => (n.columns ?? []).map((c) => c.key))); + for (const [k, words] of [["PK", "Primary key"], ["FK", "Foreign key"]] as const) { + if (keys.has(k)) entries.push(h("li", { class: `${P}-entry` }, h("span", { class: `${P}-key-letters`, "aria-hidden": "true" }, k), h("span", null, words))); + } + } if (m.type === "flowchart") { const used = new Set(m.nodes.map((n) => n.shape)); if (used.has("terminal")) entry(boxSwatch(P, "terminal"), m.shapeLabels.terminal); @@ -573,7 +591,7 @@ function buildKey(P: string, m: Model): VElement | null { if (m.type === "schema" && m.edges.length) { // The foreign-key line where it is drawn; where it is not, the row says it, and so does the key. entry(lineSwatch(P, "fk"), m.legend.plain ?? "A foreign key, to the key it references", { "data-line": "", "data-when": "drawn" }); - entries.push(h("li", { class: `${P}-entry`, "data-when": "stacked" }, h("span", { class: `${P}-fk-mark`, "aria-hidden": "true" }, "→"), h("span", null, "A foreign key, written in the row"))); + entries.push(h("li", { class: `${P}-entry`, "data-when": "stacked" }, h("span", { class: `${P}-fk-mark`, "aria-hidden": "true" }, "→"), h("span", null, "The table a foreign key references"))); } if (m.nodes.some((n) => n.focal) && m.legend.focal) entry(boxSwatch(P, "focal"), m.legend.focal, { "data-focal": "" }); if (m.groups.length && m.legend.group) entry(boxSwatch(P, "group"), m.legend.group); @@ -599,7 +617,8 @@ function nodeText(P: string, m: Model, n: MNode): VChild[] { if (m.type === "data-flow") kids.push(h("span", { class: `${P}-kind` }, n.kind!, h("span", { class: `${P}-lane-word` }, ` · ${n.laneLabel}`))); else if (n.kind) kids.push(h("span", { class: `${P}-kind` }, n.kind)); kids.push(h("span", { class: `${P}-name` }, n.name)); - if (n.detail) kids.push(h("span", { class: `${P}-detail`, "data-mono": n.mono ? "" : undefined }, n.detail)); + // An identifier breaks only at its spaces: each run between them is kept whole (an ordinary hyphen stays, so a copy is exact). + if (n.detail) kids.push(h("span", { class: `${P}-detail`, "data-mono": n.mono ? "" : undefined }, n.mono ? words(n.detail).flatMap((w, j) => [j ? " " : "", h("span", { class: `${P}-run` }, w)]) : n.detail)); return kids; } @@ -630,11 +649,12 @@ function nodeTree(ctx: TreeContext, m: Model, n: MNode, dyn: Dyn): VElement { if (m.type === "sequence") style.push(`--_c2:${n.col + 1}`); const plan = ctx.plan; if (plan && n.i > 0) { - const base = plan.gaps[n.id] ?? 32; - const grow = dyn.grow?.[n.id] ?? 0; + const base = own(plan.gaps, n.id) ?? 32; + const grow = own(dyn.grow, n.id) ?? 0; style.push(`--_gap:${grow ? `calc(${gapVar(base)} + var(--basalt-space-4) * ${grow})` : gapVar(base)}`); } - if (dyn.heights?.[n.id]) style.push(`--_h:${dyn.heights[n.id]}px`); + const height = own(dyn.heights, n.id); + if (height) style.push(`--_h:${height}px`); const tabbable = stops ? (dyn.stop === n.id ? 0 : -1) : dyn.keep === n.id ? -1 : undefined; return h("div", { class: `${P}-node`, @@ -679,7 +699,9 @@ function drawingChildren(ctx: TreeContext, m: Model, dyn: Dyn): VNode[] { if (!g) { out.push(nodeTree(ctx, m, n, dyn)); k++; continue; } const run: MNode[] = []; while (k < m.nodes.length && m.nodes[k]!.group === g.id) run.push(m.nodes[k++]!); - out.push(h("div", { class: `${P}-group`, "data-group": g.id }, h("span", { class: `${P}-glabel`, "aria-hidden": "true" }, g.label), run.map((x) => nodeTree(ctx, m, x, dyn)))); + // A stacked group takes its first member's grown gap above its box (the member itself sits at the top of the box's padding). + const grow = ctx.plan ? own(dyn.grow, run[0]!.id) ?? 0 : 0; + out.push(h("div", { class: `${P}-group`, "data-group": g.id, style: grow ? `--_ggrow:${grow}` : undefined }, h("span", { class: `${P}-glabel`, "aria-hidden": "true" }, g.label), run.map((x) => nodeTree(ctx, m, x, dyn)))); } return out; } @@ -752,17 +774,18 @@ function buildList(P: string, m: Model): VNode[] { out.push(H("Messages")); let list: VElement | null = null; for (const s of m.steps) { - // A band names a phase: a sub-heading, one level under the title's (4.4), drawn as the list's group line. - if ("band" in s) { list = null; out.push(h(`h${sub}`, { class: `${P}-list-group` }, s.band)); continue; } + // A band names a phase: a sub-heading one level under "Messages" (never past h6), drawn as the list's group line. + if ("band" in s) { list = null; out.push(h(`h${Math.min(6, sub + 1)}`, { class: `${P}-list-group` }, s.band)); continue; } if (!list) { list = h("ol", { class: `${P}-list-items`, start: s.n }); out.push(list); } - list.c.push(h("li", null, code(s.label), ": ", strong(name(s.from)), " to ", strong(name(s.to)), `${kw(s.kind)}.`, s.note ? ` ${sentence(upperFirst(s.note))}` : "")); + list.c.push(h("li", null, code(s.label), ": ", strong(name(s.from)), " to ", strong(name(s.to)), `${kw(s.kind)}.`, s.note ? ` ${sentence(s.note)}` : "")); } return out; } // schema const out: VNode[] = []; for (const n of m.nodes) { - out.push(h("p", { class: `${P}-list-group` }, code(n.name), focal(n))); + // A table's name is a sub-heading one level under the title's, as "Parts" and "Connections" are. + out.push(h(`h${sub}`, { class: `${P}-list-group` }, code(n.name), focal(n))); out.push(h("ul", { class: `${P}-list-items` }, [ ...(n.columns ?? []).map((c) => h("li", null, code(c.name), c.key === "PK" ? ", primary key" : c.key === "FK" ? ", foreign key" : "", c.ref ? [", references ", code(`${c.ref.table}.${c.ref.column}`)] : c.type ? `, ${c.type}` : "")), ...(n.more ? [h("li", null, `and ${n.more} more ${n.more === 1 ? "column" : "columns"}`)] : []), @@ -807,11 +830,13 @@ export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { const group = m.type === "sequence" || m.type === "schema" ? drawn : true; const Head = `h${m.heading}`; const style: string[] = [`--_cols:${columnCount(m)}`]; - if (m.type === "architecture" && m.groups.length) { - // The drawn layout keeps room for a group's box where it reaches an edge: space-8 above, space-4 at a side and below. - const members = m.groups.flatMap((g) => g.members.map((id) => m.byId.get(id)!)); - const pad = (on: boolean, step: string) => (on ? `var(--basalt-space-${step})` : "0px"); - style.push(`--_gpad:${pad(members.some((n) => n.row === 1), "8")} ${pad(members.some((n) => n.col === m.cols), "4")} ${pad(members.some((n) => n.row2 === m.rows), "4")} ${pad(members.some((n) => n.col === 1), "4")}`); + if ((m.type === "architecture" && m.groups.length) || (drawn && dyn.pad)) { + // The drawn layout keeps room for a group's box where it reaches an edge: space-8 above, space-4 at a side and below. A padded layout + // (Dyn.pad) keeps at least space-3 above and below, for the seats beside a line in the first or the last row. + const members = m.type === "architecture" ? m.groups.flatMap((g) => g.members.map((id) => m.byId.get(id)!)) : []; + const pad = (on: boolean, step: string, least?: string) => (on ? `var(--basalt-space-${step})` : least ? `var(--basalt-space-${least})` : "0px"); + const block = drawn && dyn.pad ? "3" : undefined; + style.push(`--_gpad:${pad(members.some((n) => n.row === 1), "8", block)} ${pad(members.some((n) => n.col === m.cols), "4")} ${pad(members.some((n) => n.row2 === m.rows), "4", block)} ${pad(members.some((n) => n.col === 1), "4")}`); } if (m.type === "schema" && dyn.track) style.push(`--_track:${dyn.track}px`); return h("figure", { @@ -823,6 +848,7 @@ export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { "data-gutter": plan?.gutter ? "" : undefined, "data-layout": dyn.layout, "data-measured": dyn.layout ? "" : undefined, + "data-bare": dyn.bare ? "" : undefined, style: style.join(";"), }, h("div", { class: `${P}-head` }, h(Head, { id: ids.title, class: `${P}-title` }, m.title), o.hasSource ? h("p", { class: `${P}-source` }, { slot: "source" }) : null), @@ -831,7 +857,8 @@ export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { role: group ? "group" : undefined, "aria-roledescription": group ? "diagram" : undefined, "aria-labelledby": group ? ids.title : undefined, - "aria-describedby": group ? `${ids.summary} ${ids.keys}` : undefined, + // The keys sentence describes the drawing only where it has stops (a bare stack has none). + "aria-describedby": group ? (stops ? `${ids.summary} ${ids.keys}` : ids.summary) : undefined, "data-stops": stops ? "" : undefined, }, drawingChildren(ctx, m, dyn), h("div", { class: `${P}-ink`, "aria-hidden": "true" }), h("span", { class: `${P}-ruler`, "aria-hidden": "true" })), keyTree(P, m), @@ -865,10 +892,15 @@ export interface GLine { /** A foreign key's dot, on the row it leaves. */ dot?: Pt; width: number; + /** Each run's place across its axis before it was snapped (a run out of a decision is on the diamond's own centre line), by segment: labels + * are seated against these, so a seat never turns on which way a half pixel fell. */ + axes?: number[]; } export interface GLabel { i: number; text: string; box: Rect; on: boolean } export interface GCross { top: number; under: number; at: Pt; underVertical: boolean } export interface Geo { + /** Labels refused only because every seat left the drawing (a padded layout gives them room). */ + bounded?: number[]; w: number; h: number; nodes: GNode[]; @@ -1129,7 +1161,7 @@ function assignSlots(m: Model, sides: Array<[DiagramSide, DiagramSide]>, warn: ( const straight = list.filter((p) => p.straight), rest = list.filter((p) => !p.straight); // Nested: the line whose far end is farther along takes the slot nearer that way. rest.sort((x, y) => along(x) - along(y) || (isH(x.side) ? x.far.col - y.far.col : x.far.row - y.far.row) * (along(x) < 0 ? 1 : -1)); - if (list.length > 3) warn(`${key.replace(".", " has ")} has ${list.length} lines on one side; more than three is an error: use another side`); + if (list.length > 3) warn(`${key.replace(".", "'s ")} side has ${list.length} lines; more than three is an error: use another side`); if (straight.length) rest.forEach((p) => { p.f = along(p) < 0 ? 0.25 : 0.75; }); else if (rest.length === 2) { rest[0]!.f = 0.25; rest[1]!.f = 0.75; } else if (rest.length === 3) { rest[0]!.f = 0.25; rest[1]!.f = 0.5; rest[2]!.f = 0.75; } @@ -1179,11 +1211,12 @@ function headBox(line: GLine, tk: Tokens): Rect { const segRect = (a: Pt, b: Pt, w: number): Rect => ({ l: Math.min(a.x, b.x) - w / 2, r: Math.max(a.x, b.x) + w / 2, t: Math.min(a.y, b.y) - w / 2, b: Math.max(a.y, b.y) + w / 2 }); /** Seats labels by 1.8: runs longest first, their clear shaft's middle then thirds; on the line, above, below (or beside). */ -function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacles, groups: Rect[], bounds: Rect, tk: Tokens, measure: ReturnType<typeof ruler>): { labels: GLabel[]; unseated: number[] } { +function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacles, groups: Rect[], bounds: Rect, tk: Tokens, measure: ReturnType<typeof ruler>): { labels: GLabel[]; unseated: number[]; bounded: number[] } { const s = tk.space; const placed: Rect[] = []; const labels: GLabel[] = []; const unseated: number[] = []; + const bounded: number[] = []; const GROW = s("1"); const order = lines.filter((l) => m.edges[l.i]?.label).sort((a, b) => Number(m.edges[b.i]!.kind === "main") - Number(m.edges[a.i]!.kind === "main") || a.i - b.i); for (const line of order) { @@ -1205,13 +1238,15 @@ function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacl parts = parts.flatMap(([p, q]) => (edgeAt > Math.min(p, q) + 1 && edgeAt < Math.max(p, q) - 1 ? [[p, edgeAt], [edgeAt, q]] as Array<[number, number]> : [[p, q]] as Array<[number, number]>)); } const outside = (p: number, q: number) => { const mid = (p + q) / 2; const pt = horiz ? { x: mid, y: a.y } : { x: a.x, y: mid }; return !groups.some((g) => pt.x > g.l && pt.x < g.r && pt.y > g.t && pt.y < g.b); }; - for (const [p, q] of parts) runs.push({ horiz, c: horiz ? a.y : a.x, p, q, len: Math.abs(q - p), pri: parts.length > 1 && outside(p, q) ? 1 : 0 }); + const c = line.axes?.[k] ?? (horiz ? a.y : a.x); + for (const [p, q] of parts) runs.push({ horiz, c, p, q, len: Math.abs(q - p), pri: parts.length > 1 && outside(p, q) ? 1 : 0 }); }); runs.sort((x, y) => y.pri - x.pri || y.len - x.len); let chosen: { box: Rect; on: boolean } | null = null; - const clear = (box: Rect) => { + let inBounds = false; + const clear = (box: Rect, bounded = true) => { const G = grow(box, GROW); - if (box.l < bounds.l || box.r > bounds.r || box.t < bounds.t || box.b > bounds.b) return false; + if (bounded && (box.l < bounds.l || box.r > bounds.r || box.t < bounds.t || box.b > bounds.b)) return false; if (nodes.some((n) => boxHitsShape(G, n))) return false; if (placed.some((p) => hit(G, p))) return false; if (obstacles.heads.some((h0) => hit(G, h0))) return false; @@ -1234,14 +1269,15 @@ function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacl } chosen = cands.find((c) => clear(c.box)) ?? null; if (chosen) break; + if (!inBounds && cands.some((c) => clear(c.box, false))) inBounds = true; } if (chosen) break; } - if (!chosen) { unseated.push(line.i); continue; } + if (!chosen) { unseated.push(line.i); if (inBounds) bounded.push(line.i); continue; } placed.push(chosen.box); labels.push({ i: line.i, text, box: chosen.box, on: chosen.on }); } - return { labels, unseated }; + return { labels, unseated, bounded }; } function obstaclesOf(drawing: HTMLElement, origin: DOMRect, P: string, rowGap: number): { obstacles: Obstacles; groups: Rect[] } { @@ -1301,41 +1337,62 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const r = rectOf(el, origin); return (r.t + r.b) / 2; }; + // Each end's place across the axis it leaves or enters on, before it is snapped (`r1`, `r2`): what its label is seated against. const ends = m.edges.map((e, k) => { const [s1, s2] = sides[k]!; const a = map.get(e.from)!, b = map.get(e.to)!; const w = strokeOf(e.kind, tk); if (e.fk) { - const y1 = sn.y(rowY(e.from, e.fromRow!), w), y2 = sn.y(rowY(e.to, e.toRow!), w); - return { p1: { x: s1 === "right" ? a.rect.r : a.rect.l, y: y1 }, p2: { x: s2 === "right" ? b.rect.r : b.rect.l, y: y2 } }; + const r1 = rowY(e.from, e.fromRow!), r2 = rowY(e.to, e.toRow!); + const y1 = sn.y(r1, w), y2 = sn.y(r2, w); + return { p1: { x: s1 === "right" ? a.rect.r : a.rect.l, y: y1 }, p2: { x: s2 === "right" ? b.rect.r : b.rect.l, y: y2 }, r1, r2: Math.abs(y1 - y2) < 0.01 ? r1 : r2 }; } const f1 = ports.find((p) => p.edge === k && p.end === "from")!.f, f2 = ports.find((p) => p.edge === k && p.end === "to")!.f; let p1 = portPoint(a, s1, f1), p2 = portPoint(b, s2, f2); + const r1 = isH(s1) ? p1.y : p1.x; + let r2 = isH(s2) ? p2.y : p2.x; // Snap the axis the line leaves and enters on; a straight line shares one. if (isH(s1)) p1 = { ...p1, y: sn.y(p1.y, w) }; else p1 = { ...p1, x: sn.x(p1.x, w) }; if (isH(s2)) p2 = { ...p2, y: sn.y(p2.y, w) }; else p2 = { ...p2, x: sn.x(p2.x, w) }; - if (isH(s1) && isH(s2) && Math.abs(p1.y - p2.y) < 1.01) p2 = { ...p2, y: p1.y }; - if (!isH(s1) && !isH(s2) && Math.abs(p1.x - p2.x) < 1.01) p2 = { ...p2, x: p1.x }; + if (isH(s1) && isH(s2) && Math.abs(p1.y - p2.y) < 1.01) { p2 = { ...p2, y: p1.y }; r2 = r1; } + if (!isH(s1) && !isH(s2) && Math.abs(p1.x - p2.x) < 1.01) { p2 = { ...p2, x: p1.x }; r2 = r1; } // The end that a snap moved sits on the contour again. p1 = isH(s1) ? contour(a, s1, p1.y) : contour(a, s1, p1.x); p2 = isH(s2) ? contour(b, s2, p2.y) : contour(b, s2, p2.x); - return { p1, p2 }; + return { p1, p2, r1, r2 }; }); + // Relations two columns apart are not drawn: the row writes its target (1.12). They are left out before any lane is given, so they take none. + const dropped = new Set<number>(); + if (m.type === "schema") m.edges.forEach((e, k) => { if (Math.abs(m.byId.get(e.from)!.col - m.byId.get(e.to)!.col) > 1) dropped.add(k); }); - // Jogs: which gutter each two-elbow line turns in, and which lines share a lane (lines to one port, a foreign key's bus). + // Jogs: which gutter each two-elbow line turns in, and which lines share a lane (lines to one port, a foreign key's bus). A turn-back (out and + // back in on one side) runs in the gutter beside that side too, so it is given a lane with the jogs it runs beside. const jogs = new Map<string, { span: [number, number]; vertical: boolean; members: Map<string, number[]> }>(); + const turnBacks = new Set<number>(); m.edges.forEach((e, k) => { + if (dropped.has(k)) return; const [s1, s2] = sides[k]!; const { p1, p2 } = ends[k]!; const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; let key: string | null = null, span: [number, number] | null = null, vertical = false; - if (isH(s1) && isH(s2) && s1 !== s2 && Math.abs(p1.y - p2.y) > 0.5) { + if (s1 === s2) { + if (isH(s1)) { + const ti = s1 === "right" ? Math.max(trackOf(a), trackOf(b)) : Math.min(trackOf(a), trackOf(b)) - 1; + const t1 = grid.cols[ti - 1], t2 = grid.cols[ti]; + if (t1 && t2) { key = `c${ti}`; span = [t1[1], t2[0]]; vertical = true; } + } else { + const ri = s1 === "bottom" ? Math.max(a.row2, b.row2) : Math.min(a.row, b.row) - 1; + const r1 = grid.rows[ri - 1], r2 = grid.rows[ri]; + if (r1 && r2) { key = `r${ri}`; span = [r1[1], r2[0]]; vertical = false; } + } + if (key) turnBacks.add(k); + } else if (isH(s1) && isH(s2) && Math.abs(p1.y - p2.y) > 0.5) { const ti = trackOf(b); const leftSide = s2 === "left"; const t1 = grid.cols[(leftSide ? ti - 1 : ti) - 1], t2 = grid.cols[(leftSide ? ti : ti + 1) - 1]; if (t1 && t2) { key = `c${leftSide ? ti - 1 : ti}`; span = [t1[1], t2[0]]; vertical = true; } void a; - } else if (!isH(s1) && !isH(s2) && s1 !== s2 && Math.abs(p1.x - p2.x) > 0.5) { + } else if (!isH(s1) && !isH(s2) && Math.abs(p1.x - p2.x) > 0.5) { const topSide = s2 === "top"; const ri = topSide ? b.row - 1 : b.row2; const r1 = grid.rows[ri - 1], r2 = grid.rows[ri]; @@ -1354,13 +1411,13 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const [s1, s2] = sides[k]!; const { p1, p2 } = ends[k]!; if (isH(s1) && isH(s2)) { - if (s1 === s2) { const x = s1 === "right" ? Math.max(p1.x, p2.x) + s("4") : Math.min(p1.x, p2.x) - s("4"); return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; } + if (s1 === s2) { const x = lanes.get(k) ?? (s1 === "right" ? Math.max(p1.x, p2.x) + s("4") : Math.min(p1.x, p2.x) - s("4")); return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; } if (Math.abs(p1.y - p2.y) <= 0.5) return [p1, { x: p2.x, y: p1.y }]; const x = lanes.get(k) ?? (p1.x + p2.x) / 2; return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; } if (!isH(s1) && !isH(s2)) { - if (s1 === s2) { const y = s1 === "bottom" ? Math.max(p1.y, p2.y) + s("4") : Math.min(p1.y, p2.y) - s("4"); return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; } + if (s1 === s2) { const y = lanes.get(k) ?? (s1 === "bottom" ? Math.max(p1.y, p2.y) + s("4") : Math.min(p1.y, p2.y) - s("4")); return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; } if (Math.abs(p1.x - p2.x) <= 0.5) return [p1, { x: p1.x, y: p2.y }]; const y = lanes.get(k) ?? (p1.y + p2.y) / 2; return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; @@ -1371,17 +1428,26 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const buildOne = (k: number): GLine => { const e = m.edges[k]!; const w = strokeOf(e.kind, tk); - const pts = snapRoute(route(k), w, sn); - return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), dot: e.fk ? pts[0] : undefined, width: w }; + const raw = route(k); + const pts = snapRoute(raw, w, sn); + // The runs' places before the snap: the ends' own, and a lane's as given. Where the snap merged a run, the snapped places stand. + let axes: number[] | undefined; + if (raw.length === pts.length) { + axes = segmentsOf(raw).map(([a, b]) => (Math.abs(a.y - b.y) < 0.75 ? (a.y + b.y) / 2 : (a.x + b.x) / 2)); + axes[0] = ends[k]!.r1; + if (axes.length > 1) axes[axes.length - 1] = ends[k]!.r2; + } + return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), dot: e.fk ? pts[0] : undefined, width: w, axes }; }; - const build = (): GLine[] => m.edges.map((_, k) => buildOne(k)); + const build = (): GLine[] => m.edges.flatMap((_, k) => (dropped.has(k) ? [] : [buildOne(k)])); // A gutter's lanes are scored by the lines in it alone: their crossings with every line, and the nodes they pass through. The other // lines are not rebuilt or compared with each other, since a permutation of this gutter cannot change them. let current: GLine[] | null = null; const score = (members: Set<number>) => { current ??= build(); const lines = current.map((l) => (members.has(l.i) ? buildOne(l.i) : l)); - return { lines, score: findCrossings(lines, undefined, members).length * 1000 + throughOf(lines.filter((l) => members.has(l.i)), nodes, m).length }; + // A run laid on another line's run is worse than a crossing (a crossing is cut; lines on one another read as one), so it counts most. + return { lines, score: overlapsOf(lines, members) * 100000 + findCrossings(lines, undefined, members).length * 1000 + throughOf(lines.filter((l) => members.has(l.i)), nodes, m).length }; }; // Each gutter: its lanes evenly spaced (at least space-3 apart), in the order that crosses least. // Lanes are needed only where jogs run beside each other: jogs whose runs along the gutter do not overlap each take its middle. @@ -1398,6 +1464,8 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge if (last && last.some((q) => q.run[0] < p.run[1] + s("8") && p.run[0] < q.run[1] + s("8"))) last.push(p); else clusters.push([p]); } for (const cluster of clusters) { + // A turn-back alone keeps its own place, space-4 out from the side; beside a jog, the two share the gutter's lanes. + if (cluster.every((c) => c.members.every((k) => turnBacks.has(k)))) continue; const groupsOf = cluster.map((c) => c.members); const count = groupsOf.length; const step = (g.span[1] - g.span[0]) / (count + 1); @@ -1414,14 +1482,7 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge } } geo.lines = build(); - // Relations two columns apart are not drawn: the row writes its target (1.12). - if (m.type === "schema") { - geo.lines = geo.lines.filter((l) => { - const a = m.byId.get(l.from)!, b = m.byId.get(l.to)!; - if (Math.abs(a.col - b.col) > 1) { warn?.(`${l.from} to ${l.to} is two columns apart, so its line is not drawn; its row still writes the target`); return false; } - return true; - }); - } + for (const k of dropped) warn?.(`${m.edges[k]!.from} to ${m.edges[k]!.to} is two columns apart, so its line is not drawn; its row still writes the target`); geo.crossings = findCrossings(geo.lines); geo.through = throughOf(geo.lines, nodes, m); geo.outside = outsideOf(geo.lines, W, H, tk); @@ -1430,9 +1491,31 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>): Ge const seats = seatLabels(m, geo.lines, nodes, obstacles, groups, { l: 0, t: 0, r: W, b: H }, tk, measure); geo.labels = seats.labels; geo.unseated = seats.unseated; + geo.bounded = seats.bounded; return geo; } +/** Runs of two lines laid on one another (collinear and overlapping by more than a pixel), for lines in `only`. Lines that end on one point + * share a lane by design (a bus, 1.7), so they are not counted. */ +function overlapsOf(lines: GLine[], only: Set<number>): number { + let count = 0; + for (let a = 0; a < lines.length; a++) for (let b = a + 1; b < lines.length; b++) { + const A = lines[a]!, B = lines[b]!; + if (!only.has(A.i) && !only.has(B.i)) continue; + if (A.to === B.to && Math.abs(A.tip.x - B.tip.x) < 1 && Math.abs(A.tip.y - B.tip.y) < 1) continue; + const near = (A.width + B.width) / 2 + 0.5; + for (const [p1, p2] of segmentsOf(A.pts)) for (const [q1, q2] of segmentsOf(B.pts)) { + const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; + if (aH !== bH) continue; + const [ac, bc] = aH ? [p1.y, q1.y] : [p1.x, q1.x]; + if (Math.abs(ac - bc) >= near) continue; + const [a1, a2] = aH ? [p1.x, p2.x] : [p1.y, p2.y], [b1, b2] = aH ? [q1.x, q2.x] : [q1.y, q2.y]; + if (Math.min(Math.max(a1, a2), Math.max(b1, b2)) - Math.max(Math.min(a1, a2), Math.min(b1, b2)) > 1) count++; + } + } + return count; +} + function* permutations<T>(items: T[]): Generator<T[]> { if (items.length <= 1) { yield items.slice(); return; } if (items.length > 5) { yield items.slice(); return; } @@ -1503,7 +1586,7 @@ function sequenceGeometry(input: DrawnInput, geo: Geo, sn: ReturnType<typeof sna // ---- The stacked drawing (1.13) ---- -function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, plan: StackPlan): { geo: Geo; grow: Record<string, number> } { +function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, plan: StackPlan, grown: Record<string, number> = record()): { geo: Geo; grow: Record<string, number> } { const { m, tk, P, drawing, origin } = input; const s = tk.space; const map = gNodes(m, drawing, origin, P); @@ -1512,8 +1595,17 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p const sn = snapper(ox, oy); const W = drawing.clientWidth, H = drawing.clientHeight; const geo: Geo = { w: W, h: H, nodes, lines: [], lifelines: [], labels: [], crossings: [], through: [], unseated: [], outside: [], ox, oy }; - const growBy: Record<string, number> = {}; + const growBy = record<number>(); if (m.type === "sequence" || m.type === "schema") return { geo, grow: growBy }; + // The end gutter is outside the spine cards, from the drawing's end less its padding (where a group's box ends too), never from a card inside a group. + const spineEnd = W - (parseFloat(getComputedStyle(drawing).paddingRight) || 0); + // A fixed seat that does not fit takes a line of its own (1.13): each line of 16 the gap above its card has grown gives the seat one more + // place, a line further from the card, into the room the growth made (up for a seat above a card, down for one under the card above). + const lineSeats = (box: Rect, id: string, dir: 1 | -1): Rect[] => { + const out = [box]; + for (let j = 1; j <= (own(grown, id) ?? 0); j++) out.push({ ...box, t: box.t + dir * s("4") * j, b: box.b + dir * s("4") * j }); + return out; + }; // The right edge a spine card has where each card sits (the group's inside, or the drawing's less the gutter). const columnRight = new Map<string, number>(); drawing.querySelectorAll<HTMLElement>(`.${P}-node`).forEach((el) => { @@ -1567,24 +1659,25 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType<typeof ruler>, p const start = contour(a, "bottom", x); if (r === "rail") { pts = [start, contour(b, "top", x)]; - if (label) { const cy = b.rect.t - s("6"); labelSeats.push({ k, cands: [{ l: x + s("2-5"), r: x + s("2-5") + lw, t: cy - lh / 2, b: cy + lh / 2 }], on: false, card: e.to }); } + if (label) { const cy = b.rect.t - s("6"); labelSeats.push({ k, cands: lineSeats({ l: x + s("2-5"), r: x + s("2-5") + lw, t: cy - lh / 2, b: cy + lh / 2 }, e.to, -1), on: false, card: e.to }); } } else { const ex = sn.x(b.rect.l + s("6"), w); const ty = sn.y(b.rect.t - turn, w); pts = [start, { x, y: ty }, { x: ex, y: ty }, contour(b, "top", ex)]; - if (label) labelSeats.push({ k, cands: [{ l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }], on: false, card: e.to }); + if (label) labelSeats.push({ k, cands: lineSeats({ l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }, e.to, -1), on: false, card: e.to }); } } else { // An end line: out the end side, along the end lane or the gutter, into the card's top (down) or bottom (up), space-6 in from its end edge. const right = Math.min(columnRight.get(e.from) ?? W, columnRight.get(e.to) ?? W); - const laneX = sn.x(plan.gutter ? right + (plan.lanes[k] ? 2 * s("3-5") : s("3-5")) : right - s("2-5"), w); + const laneX = sn.x(plan.gutter ? spineEnd + (plan.lanes[k] ? 2 * s("3-5") : s("3-5")) : right - s("2-5"), w); const yExit = sn.y(a.rect.t + (a.rect.b - a.rect.t) * plan.exits[k]!, w); const exit = contour(a, "right", yExit); const ex = sn.x(b.rect.r - s("6"), w); const down = r === "end-down"; const ty = sn.y(down ? b.rect.t - turn : b.rect.b + turn, w); pts = [exit, { x: laneX, y: exit.y }, { x: laneX, y: ty }, { x: ex, y: ty }, contour(b, down ? "top" : "bottom", ex)]; - if (label) labelSeats.push({ k, cands: [{ l: ex - s("2-5") - lw, r: ex - s("2-5"), t: ty - lh / 2, b: ty + lh / 2 }], on: false, card: down ? e.to : order[b.i + 1]?.id ?? e.to }); + const into = down ? e.to : order[b.i + 1]?.id ?? e.to; + if (label) labelSeats.push({ k, cands: lineSeats({ l: ex - s("2-5") - lw, r: ex - s("2-5"), t: ty - lh / 2, b: ty + lh / 2 }, into, down ? -1 : 1), on: false, card: into }); } const snapped = snapRoute(pts, w, sn); geo.lines.push({ i: k, from: e.from, to: e.to, kind: e.kind, pts: snapped, tip: snapped[snapped.length - 1]!, dir: finish(snapped), width: w }); @@ -1700,7 +1793,8 @@ export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Toke */ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn?: (s: string) => void): Measured { const drawing = fig.querySelector<HTMLElement>(`.${P}-drawing`); - if (!drawing) return { dyn: current, geo: null, ink: "", tokens: null }; + // A figure with no width (inside a closed disclosure or an unselected tab) is not laid out: its resize observer lays it out once it is shown. + if (!drawing || fig.clientWidth === 0) return { dyn: current, geo: null, ink: "", tokens: null }; const tk = readTokens(fig); const measure = ruler(drawing, P); const mins = minimums(m, tk, measure); @@ -1713,7 +1807,7 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin const heightsFor = (d: Dyn): Dyn => { if (m.type !== "flowchart") return d; apply({ ...d, heights: undefined }); - const heights: Record<string, number> = {}; + const heights = record<number>(); drawing.querySelectorAll<HTMLElement>(`.${P}-node[data-shape="decision"]`).forEach((el) => { const words = el.querySelector(`.${P}-words`); if (!words) return; @@ -1727,12 +1821,22 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin return { ...d, heights }; }; const input = (): DrawnInput => ({ m, tk, P, drawing, origin: drawing.getBoundingClientRect(), warn }); + // A list a bare stack opened closes when the figure is laid out again (it opens again if the stack is still bare). + const closed: Dyn = current.autoOpen ? { open: false, autoOpen: undefined } : {}; const names = (geo: Geo, list: number[]) => list.map((k) => lineName(m, geo.lines.find((l) => l.i === k)!)).join(", "); if (W >= mins.least) { - let d = stopOf({ ...current, layout: "drawn", grow: undefined, track: undefined }); - d = heightsFor(d); - apply(d); - const geo = drawnGeometry(input(), measure); + const drawnTry = (pad: boolean) => { + let dd = stopOf({ ...current, ...closed, layout: "drawn", grow: undefined, track: undefined, bare: undefined, pad: pad || undefined }); + dd = heightsFor(dd); + apply(dd); + return { dd, g: drawnGeometry(input(), measure) }; + }; + let { dd: d, g: geo } = drawnTry(false); + // A label refused only because its seats leave the drawing (beside a line in a 40px first or last row) is given space-3 above and below. + if (!geo.through.length && !geo.outside.length && geo.unseated.length && geo.unseated.every((k) => geo.bounded?.includes(k))) { + const padded = drawnTry(true); + if (!padded.g.through.length && !padded.g.unseated.length && !padded.g.outside.length) ({ dd: d, g: geo } = padded); + } if (!geo.through.length && !geo.unseated.length && !geo.outside.length) { if (geo.crossings.length) warn?.(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the drawn layout: ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; @@ -1742,18 +1846,18 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin if (geo.outside.length) warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.outside)} would leave the drawing`); if (geo.unseated.length) warn?.(`the drawn layout does not fit at ${Math.round(W)}px: no clean seat for ${geo.unseated.map((k) => (m.type === "sequence" ? `message ${k}` : `"${m.edges[k]?.label}"`)).join(", ")}`); } - let d = stopOf({ ...current, layout: "stacked", heights: undefined, grow: {}, track: m.type === "schema" ? mins.table : undefined }); + let d = stopOf({ ...current, ...closed, layout: "stacked", heights: undefined, grow: record(), track: m.type === "schema" ? mins.table : undefined, bare: undefined, pad: undefined }); d = heightsFor(d); apply(d); if (m.type === "sequence" || m.type === "schema") return { dyn: d, geo: null, ink: "", tokens: tk }; const plan = stackPlan(m); - let out = stackedGeometry(input(), measure, plan); + let out = stackedGeometry(input(), measure, plan, d.grow); for (let tries = 0; tries < 6 && Object.keys(out.grow).length; tries++) { - const grown = { ...(d.grow ?? {}) }; - for (const [id, n] of Object.entries(out.grow)) grown[id] = (grown[id] ?? 0) + n; + const grown = record(d.grow); + for (const [id, n] of Object.entries(out.grow)) grown[id] = (own(grown, id) ?? 0) + n; d = { ...d, grow: grown }; apply(d); - out = stackedGeometry(input(), measure, plan); + out = stackedGeometry(input(), measure, plan, grown); } const geo = out.geo; // The stack is the last layout there is. If it still holds an overlap (a label with no clean seat after every try, a line through a node or @@ -1765,8 +1869,10 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin if (geo.through.length) warn?.(`in the stacked drawing ${names(geo, geo.through)} would pass through a node, so its lines are not drawn`); if (geo.outside.length) warn?.(`in the stacked drawing ${names(geo, geo.outside)} would leave the drawing, so its lines are not drawn`); if (plan.third) warn?.("the stacked drawing would need a third end lane, so its lines are not drawn"); + // Dressed as where scripting is off (1.13): no line in the key, no key hint, no stops, and the list open when the figure becomes bare. const bare: Geo = { ...geo, lines: [], labels: [], crossings: [] }; - return { dyn: { ...d, grow: {} }, geo: bare, ink: "", tokens: tk }; + const dyn = stopOf({ ...d, grow: record(), bare: true, open: current.bare ? current.open : true, autoOpen: current.bare ? current.autoOpen : current.open ? undefined : true }); + return { dyn, geo: bare, ink: "", tokens: tk }; } if (geo.crossings.length) warn?.(`${geo.crossings.length} crossing${geo.crossings.length === 1 ? "" : "s"} in the stacked drawing (each is cut): ${geo.crossings.map((c) => `${lineName(m, geo.lines[c.top]!)} over ${lineName(m, geo.lines[c.under]!)}`).join("; ")}`); return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk }; @@ -1848,8 +1954,8 @@ export function keyTarget(m: Model, from: string, key: string): string | null { * script, first in the figure) is passed over, never mistaken for the heading. */ const MANAGED = ["data-layout", "data-measured", "role", "aria-roledescription", "aria-labelledby", "aria-describedby", "aria-label", "tabindex", "data-stops", "hidden"]; -const ROOT_MANAGED = ["data-layout", "data-measured"]; -const MANAGED_STYLE = ["--_track", "--_h", "--_gap"]; +const ROOT_MANAGED = ["data-layout", "data-measured", "data-bare"]; +const MANAGED_STYLE = ["--_track", "--_h", "--_gap", "--_ggrow", "--_gpad"]; const absent = (value: VAttrs[string]) => value === undefined || value === null || value === false; function pairs(el: Element, v: VElement): boolean { if (el.tagName.toLowerCase() !== v.t) return false; diff --git a/packages/react/src/diagram-figure.tsx b/packages/react/src/diagram-figure.tsx index e7bc8e4c..91503f87 100644 --- a/packages/react/src/diagram-figure.tsx +++ b/packages/react/src/diagram-figure.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { Kbd } from "./kbd"; +import { useShortcutsVisible } from "./keyboard"; import { usePanelLevel } from "./layers"; import { applyTrace, buildModel, figureTree, hasStops, hintEntries, keyTarget, measureFigure, syncAttributes, @@ -72,6 +73,8 @@ export interface DiagramFigureInternalProps extends DiagramFigureProps { export function DiagramFigure({ spec, component, title: _title, heading: _heading, legend: _legend, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ref: callerRef, ...props }: DiagramFigureInternalProps) { const base = `dg${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; const level = usePanelLevel(); + // The key hint is a data-kbd-hint legend, hidden on touch until a hardware key is pressed: this installs the listener that reveals it. + useShortcutsVisible(); // The development checks (placement, groups, the key's words) cost production nothing: a bundler that sets NODE_ENV drops them. const model = React.useMemo(() => buildModel(spec, { checks: process.env.NODE_ENV !== "production" }), [spec]); const figRef = React.useRef<HTMLElement>(null); @@ -104,6 +107,8 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin dynRef.current = result.dyn; setDyn(result.dyn); setInk(result.ink); + // A layout with no stops traces nothing: a pointer resting on a node as the figure narrows into one leaves no trace behind. + if (!hasStops(model, result.dyn)) setHoverTrace(null); }, [model, base, options, component]); // Measured before the first paint, then whenever the figure's width changes or the real faces arrive. @@ -190,7 +195,7 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin data-size="sm" aria-expanded={Boolean(dyn.open)} aria-controls={`${base}-list`} - onClick={() => { const next = { ...dynRef.current, open: !dynRef.current.open }; dynRef.current = next; setDyn(next); }} + onClick={() => { const next = { ...dynRef.current, open: !dynRef.current.open, autoOpen: undefined }; dynRef.current = next; setDyn(next); }} > <span className="basalt-button-label">{dyn.open ? "Hide the list" : "View as list"}</span> </button> diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css index 2fa0d3da..0824c927 100644 --- a/packages/react/src/styles/components.css +++ b/packages/react/src/styles/components.css @@ -4434,6 +4434,8 @@ margin: 0; font-family: var(--basalt-font-family-sans); } + /* The figure sets its own display, so the attribute's own rule is written out for it. */ + .basalt-diagram[hidden] { display: none; } .basalt-diagram-head { display: flex; flex-direction: column; gap: var(--basalt-space-0-5); min-width: 0; } .basalt-diagram-title { margin: 0; color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-md-tracking); } .basalt-diagram-source { margin: 0; color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } @@ -4514,6 +4516,8 @@ .basalt-diagram-name { color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } .basalt-diagram-detail { margin-block-start: var(--basalt-space-0-5); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } .basalt-diagram-detail[data-mono] { font-family: var(--basalt-font-family-mono); } + /* An identifier breaks only at its spaces: each run is kept whole, and is one word for the track's least width; break-word stays the net. */ + .basalt-diagram-run { display: inline-block; max-width: 100%; } /* The focal node: inverted ink; its quiet lines at opacity-amount, at full strength under more contrast. */ .basalt-diagram-node[data-focal] { background: var(--basalt-diagram-focal); border-color: var(--basalt-diagram-focal); } @@ -4546,7 +4550,7 @@ box-sizing: border-box; display: var(--_d-gd, flex); flex-direction: column; - margin-block-start: var(--basalt-space-12); + margin-block-start: calc(var(--basalt-space-12) + var(--basalt-space-4) * var(--_ggrow, 0)); padding: var(--basalt-space-8) var(--basalt-space-3) var(--basalt-space-3-5); border: var(--basalt-size-hairline) dashed var(--basalt-diagram-structure); border-radius: var(--basalt-radius-lg); @@ -4709,17 +4713,22 @@ .basalt-diagram-swatch[data-shape="focal"] .basalt-diagram-swatch-shape { fill: var(--basalt-diagram-focal); stroke: var(--basalt-diagram-focal); } .basalt-diagram-swatch[data-shape="group"] .basalt-diagram-swatch-shape { fill: none; stroke-dasharray: var(--basalt-space-1) var(--basalt-space-0-5); } .basalt-diagram-fk-mark { color: var(--basalt-text-secondary); font-family: var(--basalt-font-family-mono); } + /* A schema's key seats, set in the key as the seat sets them. */ + .basalt-diagram-key-letters { color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); } .basalt-diagram-hint { display: flex; flex-wrap: wrap; gap: var(--basalt-space-1) var(--basalt-space-4); margin: 0; color: var(--basalt-text-tertiary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); } .basalt-diagram-hint > span { display: inline-flex; align-items: center; gap: var(--basalt-space-1); } .basalt-diagram[data-layout="stacked"]:is([data-type="sequence"], [data-type="schema"]) .basalt-diagram-hint { display: none; } + /* A stack drawn with no lines (1.13) is dressed as where scripting is off: no line in the key and no key hint (the list is open by script). */ + .basalt-diagram[data-bare] :is(.basalt-diagram-entry[data-line], .basalt-diagram-hint) { display: none; } .basalt-diagram-summary { order: 1; max-width: var(--basalt-size-prose-width); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); text-wrap: pretty; } .basalt-diagram-foot { order: 2; display: flex; } /* "View as list": real lists, no box round them. */ .basalt-diagram-list { order: 3; max-width: var(--basalt-size-prose-width); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } .basalt-diagram-list[hidden] { display: none; } .basalt-diagram-list strong { color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-semibold); } - .basalt-diagram-code { color: var(--basalt-text-primary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } + /* Plain text-xs Mono: no box, whatever a page's own code element carries. */ + .basalt-diagram-code { padding: 0; border-radius: 0; background: none; color: var(--basalt-text-primary); font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-mono); } .basalt-diagram-list-head { margin: var(--basalt-space-4) 0 var(--basalt-space-2); color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } .basalt-diagram-list-head:first-child { margin-block-start: 0; } .basalt-diagram-list-group { margin: var(--basalt-space-3) 0 var(--basalt-space-1); color: var(--basalt-text-primary); font-size: inherit; font-weight: var(--basalt-font-weight-medium); line-height: inherit; } @@ -4738,46 +4747,21 @@ /* Before script: the stack, and the author's grid only from the figure's least width (1.11, 1.19): the track minimums and gaps summed from the tokens, never under 640. One rule per least width for two to six columns; a figure of more columns stays stacked until script. */ /* stylelint-disable-next-line basalt/container-length -- size-breakpoint-container-lg (640px), the floor of every least width: architecture and flowchart up to 3 columns, data flow and schema 2, sequence up to 4 */ - @container (width >= 640px) { - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="1"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="3"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="1"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="3"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="1"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="1"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="1"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="3"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } - } + @container (width >= 640px) { .basalt-diagram:not([data-layout]):is(:is([data-type="architecture"], [data-type="flowchart"]):is([data-cols="1"], [data-cols="2"], [data-cols="3"]), :is([data-type="data-flow"], [data-type="schema"]):is([data-cols="1"], [data-cols="2"]), [data-type="sequence"]:is([data-cols="1"], [data-cols="2"], [data-cols="3"], [data-cols="4"])) > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- a data flow of 3 step columns: size-diagram-lane (120) + 3 × (size-diagram-node 144 + space-12 48) = 696px */ @container (width >= 696px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="3"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- 4 columns: 4 × size-diagram-node (144) + 3 × space-16 (64) = 768px; and a schema of 3: 3 × size-diagram-table (224) + 2 × space-12 (48) = 768px */ - @container (width >= 768px) { - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="0"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="4"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="3"] > .basalt-diagram-drawing { --_drawn: ; } - } + @container (width >= 768px) { .basalt-diagram:not([data-layout]):is([data-type="architecture"][data-cols="4"][data-reach="0"], [data-type="flowchart"][data-cols="4"], [data-type="schema"][data-cols="3"]) > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 4 columns whose group reaches one side: 4 × 144 + 3 × 64 + space-4 (16) = 784px */ @container (width >= 784px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 4 columns reaching both sides: 4 × 144 + 3 × 64 + 2 × 16 = 800px; a sequence of 5: 5 × size-diagram-node (144) + 4 × space-5 (20) = 800px */ - @container (width >= 800px) { - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="2"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } - } + @container (width >= 800px) { .basalt-diagram:not([data-layout]):is([data-type="architecture"][data-cols="4"][data-reach="2"], [data-type="sequence"][data-cols="5"]) > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- a data flow of 4 step columns: 120 + 4 × (144 + 48) = 888px */ @container (width >= 888px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- a sequence of 6: 6 × 144 + 5 × 20 = 964px */ @container (width >= 964px) { .basalt-diagram:not([data-layout])[data-type="sequence"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- 5 columns: 5 × 144 + 4 × 64 = 976px */ - @container (width >= 976px) { - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="0"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } - } + @container (width >= 976px) { .basalt-diagram:not([data-layout]):is([data-type="architecture"][data-cols="5"][data-reach="0"], [data-type="flowchart"][data-cols="5"]) > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 5 columns reaching one side: 5 × 144 + 4 × 64 + 16 = 992px */ @container (width >= 992px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 5 columns reaching both sides: 5 × 144 + 4 × 64 + 2 × 16 = 1008px */ @@ -4787,10 +4771,7 @@ /* stylelint-disable-next-line basalt/container-length -- a data flow of 5 step columns: 120 + 5 × (144 + 48) = 1080px */ @container (width >= 1080px) { .basalt-diagram:not([data-layout])[data-type="data-flow"][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- 6 columns: 6 × 144 + 5 × 64 = 1184px */ - @container (width >= 1184px) { - .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="0"] > .basalt-diagram-drawing, - .basalt-diagram:not([data-layout])[data-type="flowchart"][data-cols="6"] > .basalt-diagram-drawing { --_drawn: ; } - } + @container (width >= 1184px) { .basalt-diagram:not([data-layout]):is([data-type="architecture"][data-cols="6"][data-reach="0"], [data-type="flowchart"][data-cols="6"]) > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 6 columns reaching one side: 6 × 144 + 5 × 64 + 16 = 1200px */ @container (width >= 1200px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="1"] > .basalt-diagram-drawing { --_drawn: ; } } /* stylelint-disable-next-line basalt/container-length -- an architecture of 6 columns reaching both sides: 6 × 144 + 5 × 64 + 2 × 16 = 1216px */ @@ -4805,7 +4786,8 @@ @media (scripting: none) { /* An id's weight in a :not(), so this outweighs every least-width rule above. */ .basalt-diagram:not(#basalt-diagram-no-id) > .basalt-diagram-drawing { --_drawn: initial; } - .basalt-diagram-list[hidden] { display: block; } + /* Important, so it also beats a page's own [hidden] rule (the HTML skill's core hides [hidden] with one). */ + .basalt-diagram-list[hidden] { display: block !important; } .basalt-diagram-foot, .basalt-diagram-entry[data-line], .basalt-diagram-hint { display: none; } } @@ -4838,7 +4820,7 @@ .basalt-diagram .basalt-diagram-group, .basalt-diagram .basalt-diagram-gbox { border-color: GrayText; } .basalt-diagram .basalt-diagram-lane + .basalt-diagram-lane::before, .basalt-diagram .basalt-diagram-band::before { border-color: GrayText; } .basalt-diagram .basalt-diagram-hint { color: GrayText; } - .basalt-diagram :is(.basalt-diagram-kind, .basalt-diagram-name, .basalt-diagram-detail, .basalt-diagram-glabel, .basalt-diagram-lane-name, .basalt-diagram-title, .basalt-diagram-source, .basalt-diagram-num, .basalt-diagram-mlabel, .basalt-diagram-route, .basalt-diagram-note, .basalt-diagram-band, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more, .basalt-diagram-legend, .basalt-diagram-fk-mark) { color: CanvasText; } + .basalt-diagram :is(.basalt-diagram-kind, .basalt-diagram-name, .basalt-diagram-detail, .basalt-diagram-glabel, .basalt-diagram-lane-name, .basalt-diagram-title, .basalt-diagram-source, .basalt-diagram-num, .basalt-diagram-mlabel, .basalt-diagram-route, .basalt-diagram-note, .basalt-diagram-band, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-keyseat, .basalt-diagram-ctype, .basalt-diagram-more, .basalt-diagram-legend, .basalt-diagram-fk-mark, .basalt-diagram-key-letters) { color: CanvasText; } .basalt-diagram .basalt-diagram-node:focus-visible { outline-color: Highlight; } /* The focal node is CanvasText under Canvas ink with forced-color-adjust: none, every colour set by hand, so no backplate sits under its words. */ .basalt-diagram .basalt-diagram-node[data-focal], .basalt-diagram .basalt-diagram-node[data-focal][data-near] { forced-color-adjust: none; background: CanvasText; border-color: CanvasText; } diff --git a/packages/react/test/fixtures/cimip-diagrams.json b/packages/react/test/fixtures/cimip-diagrams.json index 42712b52..be36ffd6 100644 --- a/packages/react/test/fixtures/cimip-diagrams.json +++ b/packages/react/test/fixtures/cimip-diagrams.json @@ -68,7 +68,7 @@ "title": "How one message reaches everyone in the room", "source": "\"The log\"", "summary": "Marcus's browser posts a message to cimip task A, which inserts an event row and fires NOTIFY in one Aurora transaction. Every cimip task listens and streams the event over SSE to Priya's browser, while Aurora keeps the newest 300 rows and seals older batches of 200 to S3.", - "legend": { "main": "The message's path", "plain": "Housekeeping", "dashed": "Later, in a batch", "focal": "The one transaction" }, + "legend": { "main": "The message's path", "plain": "Housekeeping", "dashed": "Later, in a batch", "focal": "Where the event is written" }, "lanes": [ { "id": "marcus", "label": "Marcus's browser" }, { "id": "task-a", "label": "cimip task A" }, @@ -130,7 +130,7 @@ "title": "The tables an incident and its runs live in", "source": "server/db/schema.ts; each table shows its keys and a few columns", "summary": "Eight PostgreSQL tables center on incidents: memberships, room_events, log_segments, sandboxes and agent_runs reference incidents.id; memberships and incidents reference users.id; agent_runs references sandboxes.id; and approvals references agent_runs.id.", - "legend": { "plain": "A foreign key, to the key it references", "focal": "The table the others reference" }, + "legend": { "plain": "A foreign key, to the key it references", "focal": "The table most of the others reference" }, "tables": [ { "name": "memberships", "col": 1, "row": 3, "more": 8, "columns": [ { "name": "incident_id", "key": "PK", "references": "incidents.id" }, diff --git a/tools/html-skill/build.mjs b/tools/html-skill/build.mjs index c53846c9..4f792c47 100644 --- a/tools/html-skill/build.mjs +++ b/tools/html-skill/build.mjs @@ -236,7 +236,12 @@ function diagramCss() { const css = react.slice(start, end) .replaceAll("var(--_surface, var(--basalt-surface-1))", "var(--panel-next, var(--basalt-surface-1))") .replaceAll("var(--_surface, var(--basalt-surface-page))", "var(--panel-bg, var(--basalt-surface-page))") - .replaceAll(".basalt-diagram", ".diagram"); + .replaceAll(".basalt-diagram", ".diagram") + // A type role written out in full is the core's own role variable (core.css, "Type roles"), the same value in a third of the bytes. + .replace(/var\(--basalt-text-(xs|sm|md)-size\) \/ var\(--basalt-text-\1-line-height\) var\(--basalt-font-family-(sans|mono)\)/g, (all, size, family) => (family === "mono" && size !== "xs" ? all : `var(--bh-${size}${family === "mono" ? "-mono" : ""})`)) + // The private switch and the properties that read it, shorter (nothing outside this stylesheet names them; a capital never collides with another). + .replaceAll("--_drawn", "--_D") + .replace(/--_d-([a-z])/g, (_, c) => `--_${c.toUpperCase()}`); if (css.includes("--_surface")) throw new Error("html-skill: the diagrams section reads --_surface in a form diagramCss does not rename"); return `@layer basalt {\n${css}\n}\n`; } diff --git a/tools/html-skill/src/modules.json b/tools/html-skill/src/modules.json index 13dc1eaa..2ce034a6 100644 --- a/tools/html-skill/src/modules.json +++ b/tools/html-skill/src/modules.json @@ -722,6 +722,7 @@ "diagram-hint", "diagram-ink", "diagram-key", + "diagram-key-letters", "diagram-keyseat", "diagram-kind", "diagram-label", @@ -748,6 +749,7 @@ "diagram-row", "diagram-rows", "diagram-ruler", + "diagram-run", "diagram-said", "diagram-source", "diagram-steps", diff --git a/tools/html-skill/src/modules/diagram.js b/tools/html-skill/src/modules/diagram.js index 85cee7c5..8580da0d 100644 --- a/tools/html-skill/src/modules/diagram.js +++ b/tools/html-skill/src/modules/diagram.js @@ -35,7 +35,7 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, } // The attributes the figure's markup sets on the figure itself; a redraw clears them before it writes the new ones. - var OWN = ['aria-labelledby', 'data-type', 'data-cols', 'data-reach', 'data-gutter', 'data-layout', 'data-measured']; + var OWN = ['aria-labelledby', 'data-type', 'data-cols', 'data-reach', 'data-gutter', 'data-layout', 'data-measured', 'data-bare']; var OWN_STYLE = ['--_cols', '--_gpad', '--_track']; /** @@ -73,17 +73,26 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, var state = {}; var measured = null; var focusTrace = null, hoverTrace = null; - var warned = {}; + var warned = Object.create(null); var warn = function (m) { if (!warned[m]) { warned[m] = 1; console.warn('Basalt diagram: ' + m); } }; var apply = function (d) { syncAttributes(figure, figureTree(model, d, opts)); }; var ink = figure.querySelector('.diagram-ink'); var toggle = figure.querySelector('.diagram-toggle'); function retrace() { applyTrace(figure, P, measured && measured.geo, measured && measured.tokens, base, focusTrace || hoverTrace); } + // The toggle's words and state follow the list's (a stack drawn with no lines opens it). + function syncToggle() { + if (!toggle) return; + toggle.setAttribute('aria-expanded', String(Boolean(state.open))); + toggle.firstElementChild.textContent = state.open ? 'Hide the list' : 'View as list'; + } function layout() { measured = measureFigure(figure, model, P, base, state, apply, warn); state = measured.dyn; apply(state); + syncToggle(); + // A layout with no stops traces nothing: a pointer resting on a node as the figure narrows into one leaves no trace behind. + if (!hasStops(model, state)) hoverTrace = null; if (ink) ink.innerHTML = measured.ink; retrace(); } @@ -128,10 +137,8 @@ import { applyTrace, buildModel, escapeHtml, figureTree, hasStops, hintEntries, } function onLeave() { if (hoverTrace) { hoverTrace = null; retrace(); } } function onToggle() { - var open = !state.open; - setState(Object.assign({}, state, { open: open })); - toggle.setAttribute('aria-expanded', String(open)); - toggle.firstElementChild.textContent = open ? 'Hide the list' : 'View as list'; + setState(Object.assign({}, state, { open: !state.open, autoOpen: undefined })); + syncToggle(); } figure.addEventListener('keydown', onKey); diff --git a/tools/review/round64.tsx b/tools/review/round64.tsx index fec4bd98..9263740c 100644 --- a/tools/review/round64.tsx +++ b/tools/review/round64.tsx @@ -1,8 +1,9 @@ // Round 64: Basalt's diagrams (DECISIONS 281, revised by 282). A heavy council round decided on one draft (Draft A, Neon's; the second drafter sat out on a // usage limit), checked by Astra and decided by Fable, who revised six objections after the final positions. Built by Opus from the decision; the // implementation has not been reviewed. The content is CIMIP's five diagrams (the owner's prototype, with the decision's corrections). States: at rest -// (`default`), a node traced by the pointer (`hover`), the list open (`list`), forced colours and more contrast. Each is shot at 1440 (drawn), at 672 (a -// 640px figure: the stack, 480 wide), at 390 and at 360. +// (`default`), a node traced by the pointer (`hover`), the list open (`list`), forced colours and more contrast. Each is shot at window widths 1440 +// (drawn), 672, 390 and 360; a shot is labelled by the window's width, and below 1440 the walkthrough's own padding makes the figure 96px narrower +// (576, 294 and 264 wide). import * as React from "react"; @@ -55,7 +56,7 @@ export const ROUND_64: Round = { title: "Diagrams: architecture, flowchart, data flow, sequence and schema (DECISIONS 281, 282)", reviewed: false, summary: - "Five diagram components and the HTML skill's diagram module, built from the council's decision (DECISIONS 281, revised by 282 after the final positions): Draft A's grammar with a measured fit rule, derived routes, a 3:1 contour on flowchart shapes, cut crossings, tracing by ink only, and the words in the page before script. CIMIP's five diagrams are the content. Built by Opus; the implementation has not been reviewed, and the tests were written but not run (DECISIONS 271 paused test runs). Shot at 1440, at a 640px figure, at 390 and at 360, in both themes, with a trace, the list, forced colours and more contrast.", + "Five diagram components and the HTML skill's diagram module, built from the council's decision (DECISIONS 281, revised by 282 after the final positions): Draft A's grammar with a measured fit rule, derived routes, a 3:1 contour on flowchart shapes, cut crossings, tracing by ink only, and the words in the page before script. CIMIP's five diagrams are the content. Built by Opus; the implementation has not been reviewed, and the tests were written but not run (DECISIONS 271 paused test runs). Shot at window widths 1440, 672, 390 and 360 (each shot is labelled by the window; the figures in the three narrow shots are 576, 294 and 264 wide), in both themes, with a trace, the list, forced colours and more contrast.", steps: [ { id: "architecture", @@ -82,7 +83,7 @@ export const ROUND_64: Round = { decisions: [ ...COMMON, "A step is the box, a start or end a capsule, a decision a diamond behind its words (the name at 500, wrapping at 62% of the track). A decision is at least space-16 tall and never flatter than 5:1, drawn or stacked.", - "Built differently from the decision's estimate: the decision measured the flowchart drawing from 880 on Draft A's geometry; here it draws from 946. At a 177px track \"Risk medium or lower?\" wraps to two lines, its diamond (sized exactly as 1.12 says) is 109 tall, and its slope reaches 0.6px into the clean seat of \"responder\", so by \"no seat, no drawn layout\" the stack holds until 946. The options are in the PR's notes; nothing was changed to move it.", + "The decision estimated the flowchart drawing from 880 on Draft A's geometry; measured here it draws from a 960px figure, at every whole width from there to 1,104, and is stacked below it. Under about 960 \"Risk medium or lower?\" wraps to two lines and the slope of \"Who is deciding?\" reaches into the clean seat of \"responder\". Labels are seated against the line's place before its half-pixel snap, so the fit no longer flips between 935 and 951 (the decider accepted the measured width in review round 64).", ], tryIt: TRY_COMMON, states: [...STATES], From 7cd1c77ae75af9325d7e2bd0dca2841bda3827b0 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:23:54 -0600 Subject: [PATCH 4/4] Diagrams: the size table after fix round 2 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/react/test/export-sizes.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index cf70f85e..3297e26f 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -18,7 +18,7 @@ "AppHeader": 1285, "AppShell": 103887, "AppTile": 1112, - "ArchitectureDiagram": 60827, + "ArchitectureDiagram": 67486, "ArrowDownGlyph": 2868, "ArrowLeftGlyph": 2869, "ArrowRightGlyph": 2859, @@ -70,7 +70,7 @@ "CopyGlyph": 2884, "Countdown": 2921, "CoverageStrip": 1570, - "DataFlowDiagram": 60846, + "DataFlowDiagram": 67503, "DateAge": 2527, "DescriptionColumns": 216, "DescriptionItem": 593, @@ -105,7 +105,7 @@ "Fieldset": 6390, "FilterResult": 698, "FilterToolbar": 774, - "FlowchartDiagram": 60833, + "FlowchartDiagram": 67490, "Form": 8730, "FormGrid": 438, "FormGridItem": 628, @@ -224,7 +224,7 @@ "RunsGlyph": 3128, "STATUS_MESSAGE_MS": 26, "SandboxesGlyph": 2963, - "SchemaDiagram": 60785, + "SchemaDiagram": 67438, "SearchDialog": 88271, "SearchField": 18295, "SearchGlyph": 3181, @@ -243,7 +243,7 @@ "SelectableList": 821, "SelectionBar": 25913, "Separator": 4531, - "SequenceDiagram": 60815, + "SequenceDiagram": 67472, "SettingsGlyph": 3100, "ShareBar": 1411, "Sheet": 70793, @@ -412,11 +412,11 @@ "useWaitMark": 303 }, "package": { - "bytes": 862693, - "gzip": 285897 + "bytes": 869454, + "gzip": 288502 }, "styles": { - "bytes": 377648, - "gzip": 49107 + "bytes": 377206, + "gzip": 49222 } }