diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index 75edb2cb..48598df2 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -1,6 +1,6 @@ --- name: basalt-html -description: Generate any standalone HTML page in this project, such as a report, document, mockup, dashboard or small interactive tool, so it looks and behaves like Basalt in both themes and works offline. Use whenever asked to write, draft or mock up an .html file. +description: Generate any standalone HTML page in this project (a report, document, mockup, dashboard or small tool) so it looks and behaves like Basalt in both themes and works offline. Use whenever asked to write or mock up an .html file. --- # Basalt HTML @@ -9,9 +9,9 @@ Standalone HTML that looks and behaves like Basalt: one file, no network, dark a ## Use it -1. Pick modules from the index below and print their usage in one call, always with core: `node .agent/skills/basalt-html/compose.mjs --usage core table status callout`. Core is the layout, type, panel and button classes every page uses. Each usage also names the modules it needs and the classes, attributes and tags that add it. `--usage` alone prints the index. -2. Write the **body** to a file such as `report.body.html`: the HTML inside ``, with the classes the usage names. It may also carry `` (else the first `<h1>` is the title), your own `<style>`, and head tags: `<meta name="description">`, `og:`/`twitter:` meta, `<link rel="icon" href="data:…">` or `canonical` (any other meta or link is refused); the script adds `Basalt.init()` unless your own `<script>` calls it. -3. Run `node .agent/skills/basalt-html/compose.mjs report.body.html` (writes `report.html`; `--out <page.html>` names it). It wraps the body in the doctype, meta and theme bootstrap, inlines Geist and adds the core CSS and script, only the modules your classes, attributes and tags use, and the icons you name in quotes. It prints what it added, and one warning line for each module added. `--no-fonts` skips Geist (only for a file a tool reads, never a file a person opens), `--lang fr` sets the language, `--all` adds every module. +1. Pick modules from the index below and print their usage in one call, always with core: `node .agent/skills/basalt-html/compose.mjs --usage core table status callout`. Core is the classes every page uses. Each usage also names the modules it needs and the markup that adds it. `--usage` alone prints the index. +2. Write the **body** to a file such as `report.body.html`: the HTML inside `<body>`, with the classes the usage names. It may carry `<title>` (else the first `<h1>`), your own `<style>`, and head tags: `<meta name="description">`, `og:`/`twitter:` meta, `<link rel="icon" href="data:…">` or `canonical` (no other meta or link); the script adds `Basalt.init()` unless your `<script>` calls it. +3. Run `node .agent/skills/basalt-html/compose.mjs report.body.html` (writes `report.html`; `--out <page.html>` names it). It adds the doctype, meta and theme bootstrap, Geist inlined, the core, only the modules your markup uses, and the icons you name in quotes. It prints what it added, and one warning line for each module added. `--no-fonts` skips Geist (only for a file a tool reads, never a file a person opens), `--lang fr` sets the language, `--all` adds every module. 4. Open the page in both themes at 1440 and 390 wide before you hand it over. It follows the system theme; the toggle or `Basalt.toggleTheme()` switches it. **Data you did not write** (a file, an API, a user) goes in as `textContent`; a link from it passes `Basalt.safeHref` (relative, http, https, mailto, tel); an option comes from a fixed list. Never into markup, a `<script>`, `style` or an `on…` attribute. @@ -20,7 +20,7 @@ Standalone HTML that looks and behaves like Basalt: one file, no network, dark a ## Modules -Markup built only at run time (a `.row` your script writes) won't be seen: add `<!-- basalt:use rows -->` to the body. +Markup your script builds (a `.row`) isn't seen: add `<!-- basalt:use rows -->` to the body. - **core** `.page`, `.stack`, `.panel`, `.card`, `.btn`: always in; print its usage too. - **glyph** `data-glyph`: Basalt's own glyph by name, never drawn by hand; filled inside `aria-current`. @@ -67,6 +67,9 @@ Markup built only at run time (a `.row` your script writes) won't be seen: add ` - **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`. - **diagram-motion** `"motion": "animated"`: added for you, with `loops`; a flow line needs a label; one mover a figure. +- **diagram-zoom** `.diagram`: added for you, with `dialog`; `"zoom": false` drops Expand. +- **diagram-export** `"export": true`: added for you; SVG and PNG downloads in the foot. +- **diagram-text** `"variant": "text"`: added for you; a sequence in box-drawing art, else its transcript. - **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. @@ -93,7 +96,7 @@ Markup built only at run time (a `.row` your script writes) won't be seen: add ` - **release** `.release`: only from `tools/changelog/skill-body.mjs`; never `hidden` on a fold. - **tab-bar** `.tab-bar`: three to five links, glyph over label; with more, four and a More sheet. -Your own CSS goes in a `<style>` in the body (moved to the head, after Basalt's), using `--basalt-*` tokens only. Element selectors (`a`, `button`, `table`, `h1`) go in `@layer reset { }`, so they never beat a Basalt class; class rules can sit unlayered. Basalt's classes are in `@layer basalt`, so any unlayered rule of yours wins without `!important`. Never restyle a Basalt class from an element rule. +Your CSS goes in a body `<style>` (moved after Basalt's), with `--basalt-*` tokens only. Element selectors (`a`, `button`, `h1`) go in `@layer reset { }`, so they never beat a Basalt class; class rules can sit unlayered. Basalt's classes are in `@layer basalt`, so any unlayered rule of yours wins without `!important`. Never restyle a Basalt class from an element rule. ## Rules @@ -102,10 +105,10 @@ Your own CSS goes in a `<style>` in the body (moved to the head, after Basalt's) - **Levels, rim, nesting.** A panel (`.panel`, `.card`, `.callout`, `.code`, `.table-wrap`) is one level above what holds it, capped at 3, with a 1px rim and no shadow. Level is position, not importance: a hero is level 1. Group with space and dividers first; a panel is for a distinct object; at most one panel deep. Only things that leave the flow (menu, popover, dialog) take `.float` and a shadow. - **Keys.** No single-character shortcuts on the page (WCAG 2.1.4): a shortcut needs ⌘, ⌃ or ⌥. - **Selected** is a shape or weight, never a wash alone: a segment or tab label at 600 (400 at rest) on its pill or underline, a row's filled background, a checked box. No vertical bar; an outline never marks a state. -- **Both themes, always.** WCAG 2.2 AA: 4.5:1 text, 3:1 boundaries, focus and icons (the tokens pass; do not invent colours). -- **Motion** from the tokens only; entries ease out, nothing bounces or overshoots; under reduced motion, opacity only. A press is a colour step; only `.btn` scales (`--usage core`). -- **390px wide** must work: no sideways scroll, touch targets at least 44px (standalone links too: `--usage core`), inputs 16px (the CSS does it on coarse pointers). Don't hide a column to make a table fit. -- **No** CDN, framework, web font request, glow, gradient, dot grid, outer frame around the page, bounce, press scale beyond `.btn`'s .98, red fill, or decorative colour. Danger is red text with a red hairline. -- **Brand SVG file** (from `brand/`): paste it with `data-brand` on its `<svg>`; compose hides it and drops its title. The link round it needs `aria-label`. +- **Both themes, always.** WCAG 2.2 AA: 4.5:1 text, 3:1 boundaries, focus and icons (the tokens pass; add no colours). +- **Motion** from the tokens only; entries ease out, nothing overshoots; under reduced motion, opacity only. A press is a colour step; only `.btn` scales (`--usage core`). +- **390px wide** must work: no sideways scroll, touch targets at least 44px (standalone links too: `--usage core`), inputs 16px on touch (the CSS does it). Never hide a column to make a table fit. +- **No** CDN, framework, web font request, glow, gradient, dot grid, page frame, bounce, press scale beyond `.btn`'s .98, red fill, or decorative colour. Danger is red text with a red hairline. +- **Brand SVG file** (from `brand/`): paste it with `data-brand` on its `<svg>`; compose hides it and drops its title; its link needs `aria-label`. - **A dot between words** is `.dot-sep`, never an `aria-hidden` dot with a hidden comma; a value and its unit need a space (`--usage core`). - Icons: Phosphor Bold via `<i data-icon="Name"></i>`, 16px (`data-size="20"` beside 18 to 24px text). Available: Command, Option, Control, Sun, Moon, Info, Warning, ArrowRight, ArrowLeft, ArrowUp, ArrowDown, CaretUpDown, Trash, Download, ArrowClockwise, CheckCircle, XCircle, MinusCircle, Prohibit, GithubLogo, XLogo, LinkedinLogo, InstagramLogo, YoutubeLogo, EnvelopeSimple, TerminalWindow. Check, close, chevrons, copy, plus, minus, search: core glyphs (`data-glyph`), not icons. A script that names one writes it as a quoted string (`icon: 'Trash'`). Need another icon? Add its name to tools/html-skill/src/icons.json and rebuild. Never draw one, never use an emoji. diff --git a/.agent/skills/basalt-html/compose.mjs b/.agent/skills/basalt-html/compose.mjs index 4def7a29..a1b2acef 100644 --- a/.agent/skills/basalt-html/compose.mjs +++ b/.agent/skills/basalt-html/compose.mjs @@ -33,6 +33,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import vm from "node:vm"; +import { MessageChannel, receiveMessageOnPort, Worker } from "node:worker_threads"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -581,7 +582,12 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = // 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. const code = `${held.restore(markup, true)}\n${styles.map((style) => stripCssComments(style.css)).join("\n")}`; - const chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use, glyphNames: Object.keys(glyphFile) }); + let chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use, glyphNames: Object.keys(glyphFile) }); + // The diagram viewer (DECISIONS 310): a page with a figure has "Expand" and its dialog, unless every figure on it says "zoom": false. A figure drawn from + // script (Basalt.diagram) may want it, so it counts. + if (chosen.modules.includes("diagram") && !chosen.modules.includes("diagram-zoom") && "diagram-zoom" in manifest.modules && zoomWanted(held, code)) { + chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use: [...use, "diagram-zoom"], glyphNames: Object.keys(glyphFile) }); + } // A module the body never triggers, which is in only because another module's script builds its markup (the palette's rows and key chips). const bare = { ...manifest, modules: Object.fromEntries(Object.entries(manifest.modules).map(([n, m]) => [n, { ...m, requires: [] }])) }; const direct = detect(code, bare, [], { all, use }).modules; @@ -630,6 +636,30 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), diagrams: diagramNotes, bytes: Buffer.byteLength(html) }; } +/** + * An automatic diagram's placement for both directions (DECISIONS 306, 1.8), from parts/diagram-place.mjs run in a worker, waited for here: elk answers with + * a promise and compose is synchronous, so this thread sleeps on a shared flag until the worker has posted its answer and woken it. + */ +function placeNow(parts, spec) { + const signal = new SharedArrayBuffer(4); + const { port1, port2 } = new MessageChannel(); + const worker = new Worker(path.join(parts, "diagram-place.mjs"), { workerData: { spec, port: port2, signal }, transferList: [port2] }); + Atomics.wait(new Int32Array(signal), 0, 0, 60_000); + const got = receiveMessageOnPort(port1)?.message; + worker.terminate(); + port1.close(); + if (!got || got.error) throw new Error(got?.error ?? "the placer did not answer"); + return got.placement; +} + +/** Whether any figure on the page keeps its viewer: a `data-diagram` JSON without `"zoom": false`, or a figure drawn from script. */ +function zoomWanted(held, code) { + if (/Basalt\s*\.\s*diagram\b/.test(code)) return true; + const specs = held.saved.filter((item) => item.kind === "script" && item.attrs.some(([k]) => k === "data-diagram")); + if (!specs.length) return true; + return specs.some((item) => { try { return JSON.parse(item.inner).zoom !== false; } catch { return true; } }); +} + /** * 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 @@ -661,11 +691,24 @@ function writeDiagrams(markup, held, parts, notes, marks) { 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; } // Each card's mark: a bundled id is checked and its rule written once; the page's own mark is read into the page and named by an id, so the JSON // the script reads carries the id and never a path. - if (spec && spec.type === "architecture" && Array.isArray(spec.nodes)) { + // An automatic figure (DECISIONS 306, 1.8) is placed here, at build time, for both directions; the page holds the placement and never elkjs. + if (spec && spec.layout === "auto" && !spec.placement && ["architecture", "flowchart", "schema"].includes(spec.type)) { + try { + spec.placement = placeNow(parts, spec); + const inner = `\n${JSON.stringify(spec).replace(/</g, "\\u003c")}\n`; + item.text = item.text.replace(item.inner, () => inner); + item.inner = inner; + } catch (e) { notes.push(`${spec.title ?? "a diagram"} could not be placed (${String(e.message).split("\n")[0]}); it is stacked`); } + } + // An architecture's cards, a data flow's steps and a sequence's participants may carry one (DECISIONS 306, 1.6). + const cards = spec && (spec.type === "architecture" || spec.type === "data-flow") ? spec.nodes : spec && spec.type === "sequence" ? spec.participants : null; + if (Array.isArray(cards)) { let rewrote = false; - for (const n of spec.nodes) { + for (const n of cards) { if (!n || n.mark === undefined || n.mark === null) continue; - if (typeof n.mark === "string") useMark(marks, n.mark, n, notes); + // A data flow's step counts its lane's label as its words, as React's check does (DECISIONS 306, 1.6; Neon's B10 of the code review). + const lane = spec.type === "data-flow" && Array.isArray(spec.lanes) ? spec.lanes.find((l) => l && l.id === n.lane) : null; + if (typeof n.mark === "string") useMark(marks, n.mark, lane ? { ...n, laneLabel: lane.label } : n, notes); else { n.mark = ownMark(marks, n.mark); rewrote = true; } } if (rewrote) { @@ -715,7 +758,7 @@ function useMark(marks, id, node, notes) { } function checkSays(file, id, node, notes) { const says = (Object.hasOwn(file.says, id) ? file.says[id] : undefined) ?? []; - const words = [node.name, node.kind, node.detail].filter(Boolean).join(" ").toLowerCase(); + const words = [node.name, node.kind, node.detail, node.laneLabel].filter(Boolean).join(" ").toLowerCase(); if (says.length && !says.some((w) => words.includes(w.toLowerCase()))) notes.push(`${node.id}'s mark (${id}) stands for ${says.join(" or ")}, and none of its words say so: a mark never carries a fact alone`); } diff --git a/.agent/skills/basalt-html/parts/diagram-export.js b/.agent/skills/basalt-html/parts/diagram-export.js new file mode 100644 index 00000000..e2fb6ce9 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram-export.js @@ -0,0 +1 @@ +(()=>{var G="http://www.w3.org/2000/svg",S=t=>t.replace(/[&<>"']/g,i=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[i]),k=t=>!!t&&t!=="transparent"&&!/rgba\([^)]*,\s*0\)$/.test(t)&&!/\/\s*0\)$/.test(t),h=t=>Math.round(t*100)/100;function z(t){const i=l=>t.querySelector(`:scope > [class$="-${l}"], :scope > [class*="-${l} "]`);return["head","drawing","key"].map(i).filter(l=>!!(l&&l.getClientRects().length))}async function U(t){for(const i of Array.from(document.styleSheets)){let l;try{l=i.cssRules}catch{continue}for(const d of Array.from(l)){if(!(d instanceof CSSFontFaceRule)||d.style.getPropertyValue("font-family").replace(/["']/g,"").trim()!==t)continue;const e=/url\(["']?([^"')]+)["']?\)/.exec(d.style.getPropertyValue("src"))?.[1];if(e){if(e.startsWith("data:"))return e;try{const n=await fetch(new URL(e,i.href??location.href));if(!n.ok)return null;const o=await n.blob();return await new Promise((c,s)=>{const a=new FileReader;a.onload=()=>c(String(a.result)),a.onerror=s,a.readAsDataURL(o)})}catch{return null}}}}return null}function j(t,i,l){const d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(let e=d.nextNode();e;e=d.nextNode()){const n=e.parentElement;if(!n||!e.textContent?.trim()||n.closest("[aria-hidden='true'] .basalt-visually-hidden, .basalt-visually-hidden, .visually-hidden, [class$='-ruler'], [hidden]"))continue;const o=getComputedStyle(n);if(o.visibility==="hidden"||o.display==="none")continue;const c=e.textContent,s=document.createRange();for(const a of c.matchAll(/\S+/g)){s.setStart(e,a.index),s.setEnd(e,a.index+a[0].length);const m=s.getBoundingClientRect();if(!m.width)continue;const f=Number.parseFloat(o.fontSize),b=m.top-i.top+(m.height-f)/2+f*.8;l.push(`<text x="${h(m.left-i.left)}" y="${h(b)}" font-family="${S(o.fontFamily)}" font-size="${f}" font-weight="${o.fontWeight}" fill="${o.color}"${o.textDecorationLine.includes("underline")?' text-decoration="underline"':""}>${S(a[0])}</text>`)}}}function D(t,i,l){if(/-(lane|band|felse)(\s|$)/.test(` ${t.getAttribute("class")??""}`))for(const d of["::before","::after"]){const e=getComputedStyle(t,d);if(!e.content||e.content==="none"||e.content==="normal"||e.display==="none"||e.position!=="absolute")continue;const n=t.getBoundingClientRect(),o=getComputedStyle(t),c=n.left+(Number.parseFloat(o.borderLeftWidth)||0)+(Number.parseFloat(e.left)||0)-i.left,s=n.top+(Number.parseFloat(o.borderTopWidth)||0)+(Number.parseFloat(e.top)||0)-i.top,a=Number.parseFloat(e.width)||0,m=Number.parseFloat(e.height)||0,f=Number.parseFloat(e.borderTopWidth)||0,b=e.maskImage&&e.maskImage!=="none"?` stroke-dasharray="${Number.parseFloat(e.maskSize)/2||4} ${Number.parseFloat(e.maskSize)/2||4}"`:"";k(e.backgroundColor)&&a&&m?l.push(`<line x1="${h(c)}" y1="${h(s+m/2)}" x2="${h(c+a)}" y2="${h(s+m/2)}" stroke="${e.backgroundColor}" stroke-width="${h(m)}"${b}/>`):f&&k(e.borderTopColor)&&l.push(`<line x1="${h(c)}" y1="${h(s+f/2)}" x2="${h(c+a+(Number.parseFloat(e.borderLeftWidth)||0)+(Number.parseFloat(e.borderRightWidth)||0))}" y2="${h(s+f/2)}" stroke="${e.borderTopColor}" stroke-width="${f}"${e.borderTopStyle==="dashed"?' stroke-dasharray="4 4"':""}/>`)}}function O(t,i,l){const d=t.getBoundingClientRect();if(!d.width||!d.height||t.getAttribute("class")?.endsWith("-motion-defs"))return;const e=t.cloneNode(!0),n=[t,...Array.from(t.querySelectorAll("*"))],o=[e,...Array.from(e.querySelectorAll("*"))],c=t.viewBox?.baseVal,s=!!(c&&c.width&&(Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5));n.forEach((a,m)=>{const f=getComputedStyle(a),b=o[m];for(const v of["fill","stroke","stroke-width","stroke-dasharray","stroke-linecap","stroke-linejoin","opacity"])b.setAttribute(v,f.getPropertyValue(v));b.removeAttribute("class"),/-reveal-/.test(b.getAttribute("mask")??"")&&b.removeAttribute("mask"),s&&m>0&&b.setAttribute("vector-effect","non-scaling-stroke"),f.display==="none"&&b.setAttribute("display","none")}),e.setAttribute("x",String(h(d.left-i.left))),e.setAttribute("y",String(h(d.top-i.top))),e.setAttribute("width",String(h(d.width))),e.setAttribute("height",String(h(d.height))),e.removeAttribute("style"),l.push(e.outerHTML)}function I(t,i,l){const d=[t,...Array.from(t.querySelectorAll("*"))],e=d.filter(n=>n instanceof SVGSVGElement&&n.closest("svg")===n&&!!n.closest("[class$='-ink']"));for(const n of e)O(n,i,l);for(const n of d){if(n instanceof SVGElement){if(n.tagName.toLowerCase()!=="svg"||n.closest("svg")!==n||e.includes(n))continue;O(n,i,l);continue}const o=getComputedStyle(n);if(o.display==="none"||o.visibility==="hidden")continue;const c=n.getBoundingClientRect();if(!c.width||!c.height)continue;const s=h(c.left-i.left),a=h(c.top-i.top),m=h(c.width),f=h(c.height),b=Number.parseFloat(o.borderTopLeftRadius)||0,v=k(o.backgroundColor)?o.backgroundColor:"none",A=[o.borderTopWidth,o.borderRightWidth,o.borderBottomWidth,o.borderLeftWidth].map(r=>Number.parseFloat(r)||0),x=A.every(r=>r===A[0]);if(!x){const[r,u,p,w]=A,$=(T,R,F,E,L,M)=>{T&&k(R)&&l.push(`<line x1="${F}" y1="${E}" x2="${L}" y2="${M}" stroke="${R}" stroke-width="${T}"/>`)};$(r,o.borderTopColor,s,a+r/2,s+m,a+r/2),$(p,o.borderBottomColor,s,a+f-p/2,s+m,a+f-p/2),$(w,o.borderLeftColor,s+w/2,a,s+w/2,a+f),$(u,o.borderRightColor,s+m-u/2,a,s+m-u/2,a+f)}const g=x?A[0]:0,N=o.borderLeftColor,C=g&&o.borderTopStyle!=="none"&&k(N)?N:"none";if(v!=="none"||C!=="none"){const r=o.borderTopStyle==="dashed"?' stroke-dasharray="4 2"':"";l.push(`<rect x="${s+g/2}" y="${a+g/2}" width="${Math.max(0,m-g)}" height="${Math.max(0,f-g)}" rx="${b}" fill="${v}" stroke="${C}" stroke-width="${g||0}"${r}/>`),C!=="none"&&!r&&o.borderTopColor!==N&&k(o.borderTopColor)&&l.push(`<line x1="${h(s+b)}" y1="${h(a+g/2)}" x2="${h(s+m-b)}" y2="${h(a+g/2)}" stroke="${o.borderTopColor}" stroke-width="${g}"/>`)}D(n,i,l);const B=/url\(["']?([^"')]+)["']?\)/.exec(o.backgroundImage)?.[1];B&&/-mark$/.test(String(n.getAttribute("class")))&&l.push(`<image href="${S(B)}" x="${s}" y="${a}" width="${m}" height="${f}"/>`)}}var q=t=>t.querySelector("[class$='-title']")?.textContent?.trim()??"",H=t=>t.querySelector("figcaption")?.textContent?.trim()??"",P=(t,i)=>`${q(t).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"diagram"}.${i}`;async function V(t,i,l){const d=i.theme??"page",e=t.getAttribute("data-theme"),n=["data-lit","data-dim","data-near","data-ahead","data-arrival","data-arrival-out"],o=Array.from(t.querySelectorAll(n.map(r=>`[${r}]`).join(", "))),c=o.map(r=>[r,n.map(u=>r.getAttribute(u))]);o.forEach(r=>{for(const u of n)r.removeAttribute(u)});const s=Array.from(t.querySelectorAll("[class*='-flow'], [class*='-bead'], [class*='-packet']"));s.forEach(r=>{r.dataset.exportHidden=r.style.display,r.style.display="none"});const a=t.getAttribute("data-entrance");a&&a!=="done"&&t.setAttribute("data-entrance","done");const m=t.getAnimations({subtree:!0}).map(r=>({a:r,at:r.currentTime,running:r.playState==="running"}));for(const{a:r}of m){const u=r.effect?.getComputedTiming().endTime;r.pause(),typeof u=="number"&&Number.isFinite(u)&&(r.currentTime=u)}const f=t.getAttribute("data-viewer");f!==null&&t.removeAttribute("data-viewer");const b=[];for(let r=t.parentElement;r;r=r.parentElement){const u=getComputedStyle(r).transform,p=/^matrix\(([^,]+),[^,]+,[^,]+,([^,]+),/.exec(u);p&&(Math.abs(Number(p[1])-1)>1e-6||Math.abs(Number(p[2])-1)>1e-6)&&(b.push([r,r.style.transform]),r.style.transform="none")}d!=="page"&&t.setAttribute("data-theme",d),t.classList.add("basalt-exporting");let v;try{t.offsetWidth;const r=Number.parseFloat(getComputedStyle(t).getPropertyValue("--basalt-space-4"))||16,u=z(t),p=u.map(y=>y.getBoundingClientRect()),w=Math.min(...p.map(y=>y.left)),$=Math.min(...p.map(y=>y.top)),T=Math.max(...p.map(y=>y.right)),R=Math.max(...p.map(y=>y.bottom)),F=new DOMRect(w-r,$-r,0,0),E=Math.ceil(T-w+2*r),L=Math.ceil(R-$+2*r),M=getComputedStyle(t).getPropertyValue("--basalt-surface-page").trim()||getComputedStyle(document.body).backgroundColor,W=[];for(const y of u)I(y,F,W);for(const y of u)j(y,F,W);v={body:W,w:E,h:L,ground:M}}finally{t.classList.remove("basalt-exporting"),d!=="page"&&(e===null?t.removeAttribute("data-theme"):t.setAttribute("data-theme",e));for(const[r,u]of b)r.style.transform=u;f!==null&&t.setAttribute("data-viewer",f);for(const{a:r,at:u,running:p}of m)r.currentTime=u,p&&r.play();a&&a!=="done"&&t.setAttribute("data-entrance",a),s.forEach(r=>{r.style.display=r.dataset.exportHidden??"",delete r.dataset.exportHidden});for(const[r,u]of c)n.forEach((p,w)=>{const $=u[w];$!=null&&r.setAttribute(p,$)})}const{body:A,w:x,h:g,ground:N}=v;let C="";if(l){const r=[];for(const u of["Geist","Geist Mono"]){const p=await U(u);p?r.push(`@font-face{font-family:"${u}";src:url(${p});font-weight:100 900}`):console.warn(`Basalt diagramToSvg: the face "${u}" could not be read, so the file names it`)}r.length&&(C=`<style>${r.join("")}</style>`)}return{svg:`<svg xmlns="${G}" width="${x}" height="${g}" viewBox="0 0 ${x} ${g}"><title>${S(q(t))}${S(H(t))}${C}${A.join("")}`,w:x,h:g}}async function _(t,i={}){const{svg:l}=await V(t,i,(i.fonts??"embed")==="embed");return new Blob([l],{type:"image/svg+xml"})}async function X(t,i={}){const{svg:l,w:d,h:e}=await V(t,i,!0),n=i.scale??2,o=new Image;o.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(l)}`,await o.decode();const c=document.createElement("canvas");c.width=Math.round(d*n),c.height=Math.round(e*n);const s=c.getContext("2d");return s.scale(n,n),s.drawImage(o,0,0,d,e),new Promise((a,m)=>c.toBlob(f=>f?a(f):m(new Error("the PNG could not be made")),"image/png"))}(function(t){"use strict";var i=t._;function l(e,n){var o=document.createElement("a");o.href=URL.createObjectURL(e),o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(function(){URL.revokeObjectURL(o.href)},1e3)}function d(e,n){var o=document.createElement("button");o.type="button",o.className="btn diagram-download",o.setAttribute("data-variant","secondary"),o.setAttribute("data-size","sm");var c=document.createElement("span");return c.textContent=e,o.appendChild(c),o.addEventListener("click",n),o}i.diagramExport=function(e,n){var o=d("Download SVG",function(){_(n).then(function(a){l(a,P(n,"svg"))})}),c=d("Download PNG",function(){X(n).then(function(a){l(a,P(n,"png"))})}),s=e.querySelector(".diagram-clear");return e.insertBefore(o,s),e.insertBefore(c,s),[o,c]}})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/diagram-motion.js b/.agent/skills/basalt-html/parts/diagram-motion.js index e30bf5b4..e03f7ada 100644 --- a/.agent/skills/basalt-html/parts/diagram-motion.js +++ b/.agent/skills/basalt-html/parts/diagram-motion.js @@ -1 +1 @@ -(()=>{var T=Object.defineProperty,C=(t,s,e)=>s in t?T(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,c=(t,s,e)=>C(t,typeof s!="symbol"?s+"":s,e);function P(t,s){const e=o=>String(Math.round(o*100)/100);let i=`M${e(t[0].x)} ${e(t[0].y)}`;for(let o=1;o{for(const h of p?.figs??[])h.sync()},e=()=>{for(const h of p?.figs??[])$(h.host.fig);s()},i=new IntersectionObserver(h=>{for(const r of h)for(const a of p?.figs??[])a.drawing===r.target&&a.seen(r)},{threshold:Array.from({length:21},(h,r)=>r/20)}),n=new MutationObserver(h=>{for(const r of h){if(r.target===document.documentElement){for(const a of p?.figs??[])a.holdChanged();continue}for(const a of p?.figs??[])a.host.fig===r.target&&a.traceChanged()}});n.observe(document.documentElement,{attributes:!0,attributeFilter:["data-loops"]});const o=["(prefers-reduced-motion: reduce)","(forced-colors: active)","print"].map(h=>matchMedia(h));for(const h of o)h.addEventListener("change",s);window.addEventListener("beforeprint",e),document.addEventListener("visibilitychange",s),p={figs:new Set,io:i,mo:n,media:o,onChange:s,onPrint:e}}return p.figs.add(t),t.drawing&&p.io.observe(t.drawing),p.mo.observe(t.host.fig,{attributes:!0,attributeFilter:["data-tracing"]}),p}function O(t){if(p&&(p.figs.delete(t),t.drawing&&p.io.unobserve(t.drawing),!p.figs.size)){p.io.disconnect(),p.mo.disconnect();for(const s of p.media)s.removeEventListener("change",p.onChange);window.removeEventListener("beforeprint",p.onPrint),document.removeEventListener("visibilitychange",p.onChange),p=void 0}}function _(t){const s=getComputedStyle(t),e=h=>s.getPropertyValue(`--basalt-${h}`).trim(),i=h=>{const r=e(h),a=parseFloat(r);return/ms$/.test(r)?a:/s$/.test(r)?a*1e3:a||0},n=h=>parseFloat(e(h))||0,o=h=>e(`ease-${h}`)||"ease";return{lineMin:i("duration-diagram-line-min"),lineMax:i("duration-diagram-line-max"),stagger:i("duration-diagram-stagger"),step:i("duration-diagram-step"),arrow:i("duration-diagram-arrow"),limit:i("duration-diagram-limit"),legMin:i("duration-diagram-leg-min"),legMax:i("duration-diagram-leg-max"),rest:i("duration-diagram-rest"),pause:i("duration-diagram-pause"),repeat:i("duration-diagram-repeat"),fast:i("duration-fast"),base:i("duration-base"),slow:i("duration-slow"),slower:i("duration-slower"),trace:n("speed-diagram-trace"),packet:n("speed-diagram-packet"),pulse:n("speed-diagram-pulse"),flow:n("speed-diagram-flow"),bead:n("size-diagram-bead"),flowPeriod:n("size-diagram-flow"),inOut:o("in-out"),out:o("out"),in:o("in")}}var L=(t,s,e)=>Math.max(s,Math.min(e,t)),F="http://www.w3.org/2000/svg",y=(t,s,e)=>{const i=document.createElementNS(F,t);for(const[n,o]of Object.entries(s))i.setAttribute(n,String(o));return e?.appendChild(i),i},S=()=>Number(document.timeline.currentTime??performance.now()),q=t=>t instanceof DOMException&&t.name==="AbortError",R={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function v(t,s){const e=t.pts.map(a=>({...a})),i=R[t.dir],n=e[e.length-1],o=e[e.length-2],h=Math.hypot(n.x-o.x,n.y-o.y),r=Math.min(s,Math.max(0,h-.5));return n.x-=i.x*r,n.y-=i.y*r,e}var E=t=>t.slice(1).reduce((s,e,i)=>s+Math.hypot(e.x-t[i].x,e.y-t[i].y),0),I=(t,s)=>{const e=t.map(n=>n.x),i=t.map(n=>n.y);return{l:Math.floor(Math.min(...e)-s),t:Math.floor(Math.min(...i)-s),r:Math.ceil(Math.max(...e)+s),b:Math.ceil(Math.max(...i)+s)}},V=class{constructor(t){c(this,"host"),c(this,"drawing"),c(this,"page"),c(this,"t"),c(this,"listeners",new Set),c(this,"snapshot",{canLoop:!1,runShown:!1,running:!1}),c(this,"destroyed",!1),c(this,"t0",0),c(this,"factor",1),c(this,"plans",new Map),c(this,"intro",new Set),c(this,"labels",new Set),c(this,"introEnd",null),c(this,"defs",null),c(this,"signature",""),c(this,"inView",!1),c(this,"enough",!1),c(this,"loopGen",0),c(this,"loops",new Set),c(this,"looping",!1),c(this,"flowEls",new Map),c(this,"beadEls",new Map),c(this,"dot",null),c(this,"dotOwner",null),c(this,"resumeAt",0),c(this,"resumeTimer",0),c(this,"runGen",0),c(this,"runAnims",new Set),c(this,"runAt",-1),c(this,"inFlight",!1),c(this,"waiting",!1),c(this,"lastSend",null),c(this,"arrivals",new Map),c(this,"state",()=>this.snapshot),c(this,"subscribe",s=>(this.listeners.add(s),()=>{this.listeners.delete(s)})),c(this,"destroy",()=>{if(!this.destroyed){this.destroyed=!0,this.stopRun(),this.clearLoops(),this.entrance()==="running"&&this.host.fig.setAttribute("data-entrance","done"),this.clearIntro(),this.host.fig.removeEventListener("basalt-diagram-settle",this.onSettle),clearTimeout(this.resumeTimer);for(const s of[...this.flowEls.values(),...this.beadEls.values()])s.remove();this.dot?.remove(),O(this)}}),c(this,"onSettle",()=>{this.clearIntro(),this.sync()}),c(this,"redrawn",()=>{if(this.destroyed)return;if(this.entrance()==="running"){const e=this.host.geo();if(!e?.lines.length)this.clearIntro(),this.host.fig.setAttribute("data-entrance","done");else{const i=this.introEnd?.currentTime,n=i!=null?Number(i):S()-this.t0,o=new Set([...this.plans].filter(([,a])=>a.end<=n).map(([a])=>a)),{plans:h,factor:r}=this.plan(this.ordered(e),this.factor);for(const a of o){const l=this.plans.get(a);l&&h.set(a,l)}this.factor=r,this.plans=h,this.build(o,!1)}}this.looping&&this.clearLoops();for(const e of[...this.flowEls.values(),...this.beadEls.values()])e.remove();this.flowEls.clear(),this.beadEls.clear(),this.runAt>=0&&this.playRun(this.runAt),this.sync()}),c(this,"changed",()=>{const s=this.edgeSignature(),e=JSON.stringify([this.host.model().motion.pulse,this.host.model().motion.packet?.path,this.host.model().edges.map(i=>!!i.flow)]);s!==this.signature&&(this.signature=s,$(this.host.fig),this.stopRun()),e!==this.route&&(this.route=e,this.looping&&this.clearLoops()),this.sync()}),c(this,"route",""),c(this,"repeatGap",null),c(this,"sendValue",s=>{if(!this.lastSend){this.lastSend={v:s};return}s===void 0||s===this.lastSend.v||(this.lastSend={v:s},this.send())}),c(this,"toggleRun",()=>{if(this.runAt>=0){this.stopRun(),this.publish();return}$(this.host.fig),this.playRun(0),this.publish()}),this.host=t,this.drawing=t.fig.querySelector(`.${t.P}-drawing`),this.t=_(t.fig),this.signature=this.edgeSignature(),t.fig.addEventListener("basalt-diagram-settle",this.onSettle),this.page=G(this),this.sync()}publish(){const t=this.hasLines(),s=this.host.model(),e=this.modes(),i=s.edges.some(o=>o.flow)||!!s.motion.pulse||!!s.motion.packet?.repeat,n={canLoop:s.motion.animated&&i&&t&&!e.reduce&&!e.forced,runShown:s.motion.animated&&s.motion.run&&t,running:this.runAt>=0};if(!(n.canLoop===this.snapshot.canLoop&&n.runShown===this.snapshot.runShown&&n.running===this.snapshot.running)){this.snapshot=n;for(const o of this.listeners)o()}}modes(){return{reduce:matchMedia("(prefers-reduced-motion: reduce)").matches,forced:matchMedia("(forced-colors: active)").matches,print:matchMedia("print").matches,held:document.documentElement.getAttribute("data-loops")==="held"}}entrance(){return this.host.fig.getAttribute("data-entrance")}hasLines(){return!!this.host.geo()?.lines.length}traced(){return this.host.fig.hasAttribute("data-tracing")}seen(t){this.inView=t.isIntersecting;const s=Math.min(t.boundingClientRect.height,window.innerHeight)*.4;this.enough=t.isIntersecting&&t.intersectionRect.height>=s-.5,this.sync()}holdChanged(){this.modes().held&&$(this.host.fig),this.sync()}traceChanged(){this.traced()?(this.stopRun(),clearTimeout(this.resumeTimer),this.resumeAt=1/0):this.resumeAt===1/0&&(this.resumeAt=S()+this.t.pause,clearTimeout(this.resumeTimer),this.resumeTimer=window.setTimeout(()=>{this.resumeAt=0,this.sync()},this.t.pause)),this.sync()}sync(){if(this.destroyed)return;const t=this.host.fig,s=this.host.model(),e=this.modes(),i=this.entrance();(i==="pending"||i==="running")&&(e.held||e.print||e.reduce||e.forced)?$(t):i==="pending"&&this.enough&&!document.hidden&&this.hasLines()&&this.play(),!i&&this.enough&&this.hasLines()&&t.setAttribute("data-entrance","done"),this.syncLoops(s,e),this.publish()}ordered(t){const s=this.host.model(),e=[...t.lines];return s.type==="schema"?e.sort((i,n)=>i.pts[0].y-n.pts[0].y||i.pts[0].x-n.pts[0].x||i.i-n.i):e.sort((i,n)=>i.i-n.i),e}plan(t,s){const e=this.t,i=this.host.model().type==="sequence",n=i?e.step:e.stagger,o=t.map(a=>{const l=this.lineEl(a)?.querySelector(`.${this.host.P}-line`),d=l?l.getTotalLength():E(a.pts),m=i?e.arrow:L(d/e.trace*1e3,e.lineMin,e.lineMax),u=i?e.base:0;return{lead:u,dur:m,tail:u+Math.max(m,.85*m+e.slow,i?e.slower:0)}});let h=1;if(n>0)for(let a=1;a{const d=l*n*h;r.set(a.i,{start:d+o[l].lead,dur:o[l].dur,end:d+o[l].tail})}),{plans:r,factor:h}}lineEl(t){return this.host.fig.querySelector(`.${this.host.P}-edge[data-edge="${t.i}"]`)}play(){const t=this.host.geo();if(!t?.lines.length)return;this.host.fig.setAttribute("data-entrance","running"),this.t0=S();const{plans:s,factor:e}=this.plan(this.ordered(t));this.factor=e,this.plans=s,this.build(new Set,!0)}build(t,s){const e=this.host.geo(),i=this.host.fig,{P:n}=this.host,o=this.t;if(!e)return;const h=this.introEnd?.playState==="paused"&&this.introEnd.currentTime!==null?Number(this.introEnd.currentTime):null;for(const u of this.intro)u.cancel();this.intro.clear(),this.defs?.remove();const r=i.querySelector(`.${n}-ink`),a=r?.querySelector(`.${n}-svg`);if(!r||!a)return;this.defs=y("svg",{class:`${n}-motion-defs`,width:0,height:0,"aria-hidden":"true",focusable:"false"}),a.after(this.defs);const l=y("defs",{},this.defs),d=(u,g=this.intro)=>(h===null?u.startTime=this.t0:(u.pause(),u.currentTime=h),g.add(u),u);let m=0;for(const u of e.lines){const g=this.plans.get(u.i),f=this.lineEl(u);if(!g||!f)continue;if(m=Math.max(m,g.end),t.has(u.i)){f.removeAttribute("mask");continue}const M=`${this.host.base}-reveal-${u.i}`,x=y("mask",{id:M,maskUnits:"userSpaceOnUse",x:-e.w,y:-e.h,width:3*e.w,height:3*e.h},l),k=f.querySelector(`.${n}-line`);if(k){const w=k.getTotalLength(),z=y("path",{d:k.getAttribute("d")??"",fill:"none",stroke:"#fff","stroke-width":u.width+6,"stroke-dasharray":`${w} ${w+8}`,"stroke-dashoffset":w},x);d(z.animate([{strokeDashoffset:`${w}px`},{strokeDashoffset:"0px"}],{duration:g.dur,delay:g.start,easing:o.inOut,fill:"both"}))}const A=f.querySelector(`.${n}-tip`);if(A){const w=y("path",{d:A.getAttribute("d")??"",fill:"#fff",stroke:"#fff","stroke-width":3,"stroke-linejoin":"round"},x);d(w.animate([{opacity:0},{opacity:1}],{duration:o.slow,delay:g.start+.85*g.dur,easing:o.out,fill:"both"}))}const b=f.querySelector(`.${n}-dot`);if(b){const w=y("circle",{cx:b.getAttribute("cx")??0,cy:b.getAttribute("cy")??0,r:Number(b.getAttribute("r")??3)+1,fill:"#fff"},x);d(w.animate([{opacity:0},{opacity:1}],{duration:o.fast,delay:g.start,easing:o.out,fill:"both"}))}f.setAttribute("mask",`url(#${M})`)}if(s&&this.host.model().type==="sequence"){const u=getComputedStyle(i),g=u.getPropertyValue("--basalt-text-secondary").trim(),f=u.getPropertyValue("--basalt-text-primary").trim(),M=i.querySelectorAll(`.${n}-msg`);this.ordered(e).forEach((x,k)=>{const A=M[k]?.querySelector(`.${n}-mlabel`),b=this.plans.get(x.i);A&&b&&g&&f&&d(A.animate([{color:g},{color:f}],{duration:o.slower,delay:b.start-o.base,easing:o.out,fill:"both"}),this.labels)})}this.introEnd?.cancel(),this.introEnd=d(i.animate([],{duration:Math.max(1,m)}),new Set),this.introEnd.finished.then(()=>this.finishIntro(),()=>{})}finishIntro(){this.entrance()==="running"&&(this.host.fig.setAttribute("data-entrance","done"),this.clearIntro(),this.sync())}clearIntro(){for(const t of[...this.intro,...this.labels])t.cancel();this.intro.clear(),this.labels.clear(),this.introEnd?.cancel(),this.introEnd=null,this.defs?.remove(),this.defs=null,this.host.fig.querySelectorAll(`.${this.host.P}-edge[mask]`).forEach(t=>t.removeAttribute("mask"))}edgeSignature(){const t=this.host.model();return(t.type==="sequence"?t.steps.flatMap(e=>"n"in e?[`${e.from}>${e.to}:${e.kind}`]:[]):t.edges.map(e=>`${e.from}>${e.to}:${e.kind}`)).join("|")}syncLoops(t,s){const e=this.entrance()==="done";if(!t.motion.animated||!e||!this.hasLines()||s.reduce||s.forced||s.print||s.held||this.traced()||S(){}):t.motion.packet?.repeat&&this.repeat(e,t.motion.packet.path).catch(()=>{})}clearLoops(){this.looping=!1,this.loopGen++;for(const t of this.loops)t.cancel();this.loops.clear();for(const t of[...this.flowEls.values(),...this.beadEls.values()])t.style.display="none";this.dotOwner==="loop"&&this.dot&&(this.dot.style.display="none",this.dotOwner=null),this.runAt<0&&this.dotOwner!=="run"&&this.clearArrivals()}track(t,s){s.add(t);const e=()=>{s.delete(t)};return t.finished.then(e,e),s===this.loops&&(!this.inView||document.hidden)&&t.pause(),t}wait(t,s){return this.track(this.host.fig.animate([],{duration:Math.max(1,t)}),s).finished.then(e=>{e.cancel()})}overlay(t,s,e){const i=this.host.fig.querySelector(`.${this.host.P}-ink`),n=i?.querySelector(`.${this.host.P}-svg`);if(!i||!n)return null;const o=this.host.tokens(),h=v(t,o?.head??8),r=I(h,s),a=y("svg",{class:`${this.host.P}-${e}`,width:r.r-r.l,height:r.b-r.t,viewBox:`${r.l} ${r.t} ${r.r-r.l} ${r.b-r.t}`,"aria-hidden":"true",focusable:"false"});a.style.left=`${r.l}px`,a.style.top=`${r.t}px`;let d=this.defs??n;for(;d.nextElementSibling&&!d.nextElementSibling.classList.contains(`${this.host.P}-label`);)d=d.nextElementSibling;return d.after(a),{svg:a,d:P(h,t.from===t.to?o?.radiusXs??4:o?.radius??8),pts:h}}visible(t,s){const e=this.host.geo();let i=0;for(const n of e?.labels??[])if(n.i===t.i&&n.on){const o=(n.box.t+n.box.b)/2,h=s.some((r,a)=>a>0&&Math.abs(r.y-s[a-1].y)<.5&&Math.abs(o-r.y)<1.5);i+=h?n.box.r-n.box.l:n.box.b-n.box.t}return E(s)-i}flow(t,s){const e=t.lines.find(r=>r.i===s);if(!e)return;const i=this.host.tokens();let n=this.flowEls.get(s);if(n&&!n.isConnected&&(this.flowEls.delete(s),n=void 0),!n){const r=i?.space("1")??4,a=this.overlay({...e,pts:v(e,r)},e.width+2,"flow");if(!a)return;if(this.visible(e,v(e,i?.head??8))<48){a.svg.remove();return}const l=i?.cut??2;y("path",{d:a.d,"stroke-width":e.width+2,"stroke-dasharray":`${l} ${this.t.flowPeriod-l}`},a.svg),n=a.svg,this.flowEls.set(s,n)}n.style.display="";const o=n.firstElementChild,h=this.t.flowPeriod;this.track(o.animate([{strokeDashoffset:"0px"},{strokeDashoffset:`${-h}px`}],{duration:h/this.t.flow*1e3,iterations:1/0,easing:"linear"}),this.loops)}edgeFor(t,s){const i=this.host.model().edges.find(n=>n.from===t&&n.to===s);return i?this.host.geo()?.lines.find(n=>n.i===i.i):void 0}node(t){return this.host.fig.querySelector(`.${this.host.P}-node[data-node="${CSS.escape(t)}"]`)}arrive(t){!t||this.traced()||(clearTimeout(this.arrivals.get(t)),t.removeAttribute("data-arrival-out"),t.setAttribute("data-arrival",""))}depart(t){!t||!t.hasAttribute("data-arrival")||(t.removeAttribute("data-arrival"),t.setAttribute("data-arrival-out",""),this.arrivals.set(t,window.setTimeout(()=>{t.removeAttribute("data-arrival-out"),this.arrivals.delete(t)},this.t.slower*.75)))}clearArrivals(){this.host.fig.querySelectorAll("[data-arrival], [data-arrival-out]").forEach(t=>{t.removeAttribute("data-arrival"),t.removeAttribute("data-arrival-out")});for(const t of this.arrivals.values())clearTimeout(t);this.arrivals.clear()}async pulse(t,s){const e=this.host.tokens();for(;t===this.loopGen;){for(let i=1;it===this.loopGen;try{for(;e();){this.inFlight=!0,this.waiting=!1;try{await this.packetRun(s,this.loops,e)}finally{this.inFlight=!1}if(!e())return;if(this.waiting)continue;const i=this.track(this.host.fig.animate([],{duration:Math.max(1,this.t.repeat)}),this.loops);this.repeatGap=i;try{await i.finished}finally{this.repeatGap===i&&(this.repeatGap=null),i.cancel()}}}finally{!e()&&!this.looping&&(this.waiting=!1)}}send(){const t=this.host.model(),s=t.motion.packet?.path;if(!t.motion.animated||!s||!this.hasLines())return;if(this.inFlight){this.waiting=!0;return}const e=this.modes();if(e.held||e.reduce){const n=this.node(s[s.length-1]);this.arrive(n),this.wait(this.t.rest,this.runAnims).then(()=>this.depart(n),()=>this.depart(n));return}if(this.looping&&t.motion.packet?.repeat){this.waiting=!0,this.repeatGap?.finish();return}this.inFlight=!0;const i=++this.runGen;this.packetRun(s,this.runAnims,()=>i===this.runGen).catch(n=>{if(!q(n))throw n}).finally(()=>{this.inFlight=!1,this.waiting&&i===this.runGen&&(this.waiting=!1,this.send())})}stopRun(){this.runGen++,this.runAt=-1;for(const t of this.runAnims)t.cancel();this.runAnims.clear(),this.dot&&this.dotOwner==="run"&&(this.dot.style.display="none",this.dotOwner=null),this.looping||(this.inFlight=!1),this.looping?this.host.fig.querySelectorAll(`.${this.host.P}-msg[data-arrival]`).forEach(t=>t.removeAttribute("data-arrival")):this.clearArrivals()}playRun(t){const s=this.host.geo();if(!s?.lines.length)return;for(const r of this.runAnims)r.cancel();this.runAnims.clear();const e=++this.runGen,i=()=>e===this.runGen,n=this.ordered(s),o=this.host.fig.querySelectorAll(`.${this.host.P}-msg`);this.runAt=t,(async()=>{for(let r=t;r{if(!q(r))throw r})}};function N(t){const s=[],e=[],{pulse:i,packet:n}=t.motion;i&&n&&s.push("a figure names both a pulse and a packet: it has one mover at most");const o=i??n?.path,h=i?"pulse":"packet",r=new Set;if(o){for(const a of o)t.byId.has(a)||s.push(`the ${h} names ${a}, which is not a node`);for(let a=1;ad.from===o[a-1]&&d.to===o[a]);l?r.add(l.i):s.push(`the ${h} goes from ${o[a-1]} to ${o[a]}, and no line joins them in that direction`)}}for(const a of t.edges)a.flow&&(a.kind==="dashed"&&s.push(`the line from ${a.from} to ${a.to} is dashed and flows: flow is on a main or plain line only`),r.has(a.i)&&s.push(`the line from ${a.from} to ${a.to} flows and is on the ${h}'s route: flow never runs on a line the mover travels`),a.label||e.push(`the line from ${a.from} to ${a.to} flows but has no label: motion never carries a fact alone, so its label says it is a stream`));return{errors:s,warnings:e}}function D(t){return new V(t)}(function(t){"use strict";var s=t._;function e(i,n,o){var h=document.createElement("button");return h.type="button",h.className="btn "+i,h.setAttribute("data-variant","secondary"),h.setAttribute("data-size","sm"),o&&o(h),h.appendChild(document.createTextNode(n)),h}s.diagramMotion=function(i,n,o){var h=N(n.model());h.errors.forEach(function(f){console.error("Basalt diagram: "+f)}),h.warnings.forEach(function(f){console.warn("Basalt diagram: "+f)});var r=D(n),a=i.querySelector(".diagram-foot"),l=null,d=null;a&&(l=e("diagram-play","Play the run"),l.addEventListener("click",function(){r.toggleRun()}),d=e("diagram-pause","Pause animations",function(f){f.setAttribute("data-loops-toggle",""),f.setAttribute("aria-pressed",String(!!(t.loops&&t.loops.held()))),f.insertAdjacentHTML("beforeend",'")}),l.hidden=d.hidden=!0,a.appendChild(l),a.appendChild(d));function m(){var f=r.state();l&&(l.hidden=!f.runShown,l.lastChild.textContent=f.running?"Stop the run":"Play the run"),d&&(d.hidden=!f.canLoop,d.setAttribute("aria-pressed",String(!!(t.loops&&t.loops.held()))))}var u=r.subscribe(m);m();var g=o&&o.packet?o.packet.send:void 0;return r.sendValue("__diagramSend"in i?i.__diagramSend:g),r.sendValue(g),i.__diagramSend=g,{redrawn:r.redrawn,sendValue:function(f){r.sendValue(f),i.__diagramSend=f},destroy:function(){u(),r.destroy(),l&&l.remove(),d&&d.remove()}}}})(window.Basalt)})(); +(()=>{var T=Object.defineProperty,G=(t,i,e)=>i in t?T(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,c=(t,i,e)=>G(t,typeof i!="symbol"?i+"":i,e);function L(t,i,e=0){const s=r=>String(Math.round(r*100)/100);let n=`M${s(t[0].x)} ${s(t[0].y)}`;for(let r=1;r`basalt-diagram-entrance:${location.pathname}#${t.id}`;function A(t){const i=t.getAttribute("data-entrance");i!=="pending"&&i!=="running"||(t.setAttribute("data-entrance","done"),t.dispatchEvent(new Event("basalt-diagram-settle")))}var m;function N(t){if(!m){const i=()=>{for(const r of m?.figs??[])r.sync()},e=()=>{for(const r of m?.figs??[])A(r.host.fig);i()},s=new IntersectionObserver(r=>{for(const h of r)for(const o of m?.figs??[])o.drawing===h.target&&o.seen(h)},{threshold:Array.from({length:21},(r,h)=>h/20)}),n=new MutationObserver(r=>{for(const h of r){if(h.target===document.documentElement){for(const o of m?.figs??[])o.holdChanged();continue}for(const o of m?.figs??[])o.host.fig===h.target&&o.traceChanged()}});n.observe(document.documentElement,{attributes:!0,attributeFilter:["data-loops"]});const a=["(prefers-reduced-motion: reduce)","(forced-colors: active)","print"].map(r=>matchMedia(r));for(const r of a)r.addEventListener("change",i);window.addEventListener("beforeprint",e),document.addEventListener("visibilitychange",i),m={figs:new Set,io:s,mo:n,media:a,onChange:i,onPrint:e}}return m.figs.add(t),t.drawing&&m.io.observe(t.drawing),m.mo.observe(t.host.fig,{attributes:!0,attributeFilter:["data-tracing","data-viewing"]}),m}function V(t){if(m&&(m.figs.delete(t),t.drawing&&m.io.unobserve(t.drawing),!m.figs.size)){m.io.disconnect(),m.mo.disconnect();for(const i of m.media)i.removeEventListener("change",m.onChange);window.removeEventListener("beforeprint",m.onPrint),document.removeEventListener("visibilitychange",m.onChange),m=void 0}}function I(t){const i=getComputedStyle(t),e=r=>i.getPropertyValue(`--basalt-${r}`).trim(),s=r=>{const h=e(r),o=parseFloat(h);return/ms$/.test(h)?o:/s$/.test(h)?o*1e3:o||0},n=r=>parseFloat(e(r))||0,a=r=>e(`ease-${r}`)||"ease";return{lineMin:s("duration-diagram-line-min"),lineMax:s("duration-diagram-line-max"),stagger:s("duration-diagram-stagger"),step:s("duration-diagram-step"),arrow:s("duration-diagram-arrow"),limit:s("duration-diagram-limit"),legMin:s("duration-diagram-leg-min"),legMax:s("duration-diagram-leg-max"),rest:s("duration-diagram-rest"),pause:s("duration-diagram-pause"),repeat:s("duration-diagram-repeat"),fast:s("duration-fast"),base:s("duration-base"),slow:s("duration-slow"),slower:s("duration-slower"),trace:n("speed-diagram-trace"),packet:n("speed-diagram-packet"),pulse:n("speed-diagram-pulse"),flow:n("speed-diagram-flow"),bead:n("size-diagram-bead"),flowPeriod:n("size-diagram-flow"),inOut:a("in-out"),out:a("out"),in:a("in")}}var P=(t,i,e)=>Math.max(i,Math.min(e,t)),R="http://www.w3.org/2000/svg",b=(t,i,e)=>{const s=document.createElementNS(R,t);for(const[n,a]of Object.entries(i))s.setAttribute(n,String(a));return e?.appendChild(s),s},$=()=>Number(document.timeline.currentTime??performance.now()),q=t=>t instanceof DOMException&&t.name==="AbortError",_={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}};function w(t,i){const e=t.pts.map(o=>({...o})),s=_[t.dir],n=e[e.length-1],a=e[e.length-2],r=Math.hypot(n.x-a.x,n.y-a.y),h=Math.min(i,Math.max(0,r-.5));return n.x-=s.x*h,n.y-=s.y*h,e}var E=t=>t.slice(1).reduce((i,e,s)=>i+Math.hypot(e.x-t[s].x,e.y-t[s].y),0),F=(t,i)=>{const e=t.map(n=>n.x),s=t.map(n=>n.y);return{l:Math.floor(Math.min(...e)-i),t:Math.floor(Math.min(...s)-i),r:Math.ceil(Math.max(...e)+i),b:Math.ceil(Math.max(...s)+i)}},D=class{constructor(t){c(this,"host"),c(this,"drawing"),c(this,"page"),c(this,"t"),c(this,"listeners",new Set),c(this,"snapshot",{canLoop:!1,runShown:!1,running:!1}),c(this,"destroyed",!1),c(this,"t0",0),c(this,"factor",1),c(this,"plans",new Map),c(this,"intro",new Set),c(this,"labels",new Set),c(this,"introEnd",null),c(this,"defs",null),c(this,"signature",""),c(this,"inView",!1),c(this,"enough",!1),c(this,"loopGen",0),c(this,"loops",new Set),c(this,"looping",!1),c(this,"flowEls",new Map),c(this,"beadEls",new Map),c(this,"dot",null),c(this,"dotOwner",null),c(this,"resumeAt",0),c(this,"resumeTimer",0),c(this,"runGen",0),c(this,"runAnims",new Set),c(this,"runAt",-1),c(this,"inFlight",!1),c(this,"waiting",!1),c(this,"lastSend",null),c(this,"arrivals",new Map),c(this,"state",()=>this.snapshot),c(this,"subscribe",i=>(this.listeners.add(i),()=>{this.listeners.delete(i)})),c(this,"destroy",()=>{if(!this.destroyed){this.destroyed=!0,this.stopRun(),this.clearLoops(),this.entrance()==="running"&&this.host.fig.setAttribute("data-entrance","done"),this.clearIntro(),this.host.fig.removeEventListener("basalt-diagram-settle",this.onSettle),clearTimeout(this.resumeTimer);for(const i of[...this.flowEls.values(),...this.beadEls.values()])i.remove();this.dot?.remove(),V(this)}}),c(this,"played",!1),c(this,"onSettle",()=>{this.played&&!this.byMode()&&this.markVisit(),this.clearIntro(),this.sync()}),c(this,"redrawn",()=>{if(this.destroyed)return;if(this.entrance()==="running"){const e=this.host.geo();if(!this.textCode())if(!e?.lines.length)this.clearIntro(),this.host.fig.setAttribute("data-entrance","done");else{const s=this.introEnd?.currentTime,n=s!=null?Number(s):$()-this.t0,a=new Set([...this.plans].filter(([,o])=>o.end<=n).map(([o])=>o)),{plans:r,factor:h}=this.plan(this.ordered(e),this.factor);for(const o of a){const l=this.plans.get(o);l&&r.set(o,l)}this.factor=h,this.plans=r,this.build(a,!1)}}this.looping&&this.clearLoops();for(const e of[...this.flowEls.values(),...this.beadEls.values()])e.remove();this.flowEls.clear(),this.beadEls.clear(),this.runAt>=0&&this.playRun(this.runAt),this.sync()}),c(this,"changed",()=>{const i=this.edgeSignature(),e=JSON.stringify([this.host.model().motion.pulse,this.host.model().motion.packet?.path,this.host.model().edges.map(s=>!!s.flow)]);i!==this.signature&&(this.signature=i,A(this.host.fig),this.stopRun()),e!==this.route&&(this.route=e,this.looping&&this.clearLoops()),this.sync()}),c(this,"route",""),c(this,"repeatGap",null),c(this,"sendValue",i=>{if(!this.lastSend){this.lastSend={v:i};return}i===void 0||i===this.lastSend.v||(this.lastSend={v:i},this.send())}),c(this,"toggleRun",()=>{if(this.runAt>=0){this.stopRun(),this.publish();return}A(this.host.fig),this.playRun(0),this.publish()}),this.host=t,this.drawing=t.fig.querySelector(`.${t.P}-drawing`),this.t=I(t.fig),this.signature=this.edgeSignature(),t.fig.addEventListener("basalt-diagram-settle",this.onSettle),this.page=N(this),this.sync()}publish(){const t=this.hasLines(),i=this.host.model(),e=this.modes(),s=i.edges.some(a=>a.flow)||!!i.motion.pulse||!!i.motion.packet?.repeat,n={canLoop:i.motion.animated&&s&&t&&!e.reduce&&!e.forced,runShown:i.motion.animated&&i.motion.run&&t,running:this.runAt>=0};if(!(n.canLoop===this.snapshot.canLoop&&n.runShown===this.snapshot.runShown&&n.running===this.snapshot.running)){this.snapshot=n;for(const a of this.listeners)a()}}modes(){return{reduce:matchMedia("(prefers-reduced-motion: reduce)").matches,forced:matchMedia("(forced-colors: active)").matches,print:matchMedia("print").matches,held:document.documentElement.getAttribute("data-loops")==="held"}}entrance(){return this.host.fig.getAttribute("data-entrance")}byMode(){const t=this.modes();return t.held||t.print||t.reduce||t.forced}markVisit(){const t=this.host.fig;if(!(!t.hasAttribute("data-first-visit")||!t.id))try{localStorage.setItem(O(t),"1")}catch{}}textCode(){return this.host.model().text?this.host.fig.querySelector(`.${this.host.P}-text[data-art] .${this.host.P}-text-ink`):null}hasLines(){return!!this.host.geo()?.lines.length||!!this.textCode()}traced(){return this.host.fig.hasAttribute("data-tracing")||this.host.fig.hasAttribute("data-viewing")}seen(t){this.inView=t.isIntersecting;const i=Math.min(t.boundingClientRect.height,window.innerHeight)*.4;this.enough=t.isIntersecting&&t.intersectionRect.height>=i-.5,this.sync()}holdChanged(){this.modes().held&&A(this.host.fig),this.sync()}traceChanged(){this.traced()?(this.stopRun(),clearTimeout(this.resumeTimer),this.resumeAt=1/0):this.resumeAt===1/0&&(this.resumeAt=$()+this.t.pause,clearTimeout(this.resumeTimer),this.resumeTimer=window.setTimeout(()=>{this.resumeAt=0,this.sync()},this.t.pause)),this.sync()}sync(){if(this.destroyed)return;const t=this.host.fig,i=this.host.model(),e=this.modes(),s=this.entrance();(s==="pending"||s==="running")&&(e.held||e.print||e.reduce||e.forced)?A(t):s==="pending"&&this.enough&&!document.hidden&&this.hasLines()&&this.play(),!s&&this.enough&&this.hasLines()&&t.setAttribute("data-entrance","done"),this.syncLoops(i,e),this.publish()}ordered(t){const i=this.host.model(),e=[...t.lines];return i.type==="schema"?e.sort((s,n)=>s.pts[0].y-n.pts[0].y||s.pts[0].x-n.pts[0].x||s.i-n.i):e.sort((s,n)=>s.i-n.i),e}plan(t,i){const e=this.t,s=this.host.model().type==="sequence",n=s?e.step:e.stagger,a=t.map(o=>{const l=this.lineEl(o)?.querySelector(`.${this.host.P}-line`),d=l?l.getTotalLength():E(o.pts),p=s?e.arrow:P(d/e.trace*1e3,e.lineMin,e.lineMax),u=s?e.base:0;return{lead:u,dur:p,tail:u+Math.max(p,.85*p+e.slow,s?e.slower:0)}});let r=1;if(n>0)for(let o=1;o{const d=l*n*r;h.set(o.i,{start:d+a[l].lead,dur:a[l].dur,end:d+a[l].tail})}),{plans:h,factor:r}}lineEl(t){return this.host.fig.querySelector(`.${this.host.P}-edge[data-edge="${t.i}"]`)}play(){if(this.textCode()){this.playText();return}const t=this.host.geo();if(!t?.lines.length)return;this.host.fig.setAttribute("data-entrance","running"),this.played=!0,this.t0=$();const{plans:i,factor:e}=this.plan(this.ordered(t));this.factor=e,this.plans=i,this.build(new Set,!0)}build(t,i){const e=this.host.geo(),s=this.host.fig,{P:n}=this.host,a=this.t;if(!e)return;const r=this.introEnd?.playState==="paused"&&this.introEnd.currentTime!==null?Number(this.introEnd.currentTime):null;for(const u of this.intro)u.cancel();this.intro.clear(),this.defs?.remove();const h=s.querySelector(`.${n}-ink`),o=h?.querySelector(`.${n}-svg`);if(!h||!o)return;this.defs=b("svg",{class:`${n}-motion-defs`,width:0,height:0,"aria-hidden":"true",focusable:"false"}),o.after(this.defs);const l=b("defs",{},this.defs),d=(u,g=this.intro)=>(r===null?u.startTime=this.t0:(u.pause(),u.currentTime=r),g.add(u),u);let p=0;for(const u of e.lines){const g=this.plans.get(u.i),f=this.lineEl(u);if(!g||!f)continue;if(p=Math.max(p,g.end),t.has(u.i)){f.removeAttribute("mask");continue}const M=`${this.host.base}-reveal-${u.i}`,v=b("mask",{id:M,maskUnits:"userSpaceOnUse",x:-e.w,y:-e.h,width:3*e.w,height:3*e.h},l),S=f.querySelector(`.${n}-line`);if(S){const y=S.getTotalLength(),C=b("path",{d:S.getAttribute("d")??"",fill:"none",stroke:"#fff","stroke-width":u.width+6,"stroke-dasharray":`${y} ${y+8}`,"stroke-dashoffset":y},v);d(C.animate([{strokeDashoffset:`${y}px`},{strokeDashoffset:"0px"}],{duration:g.dur,delay:g.start,easing:a.inOut,fill:"both"}))}const k=f.querySelector(`.${n}-tip`);if(k){const y=b("path",{d:k.getAttribute("d")??"",fill:"#fff",stroke:"#fff","stroke-width":3,"stroke-linejoin":"round"},v);d(y.animate([{opacity:0},{opacity:1}],{duration:a.slow,delay:g.start+.85*g.dur,easing:a.out,fill:"both"}))}const x=f.querySelector(`.${n}-dot`);if(x){const y=b("circle",{cx:x.getAttribute("cx")??0,cy:x.getAttribute("cy")??0,r:Number(x.getAttribute("r")??3)+1,fill:"#fff"},v);d(y.animate([{opacity:0},{opacity:1}],{duration:a.fast,delay:g.start,easing:a.out,fill:"both"}))}f.querySelectorAll(`.${n}-crow, .${n}-ring`).forEach(y=>{const z=y.tagName.toLowerCase()==="circle"?b("circle",{cx:y.getAttribute("cx")??0,cy:y.getAttribute("cy")??0,r:Number(y.getAttribute("r")??3)+1,fill:"#fff"},v):b("path",{d:y.getAttribute("d")??"",fill:"none",stroke:"#fff","stroke-width":3},v),H=y.getAttribute("data-end")==="from";d(z.animate([{opacity:0},{opacity:1}],H?{duration:a.fast,delay:g.start,easing:a.out,fill:"both"}:{duration:a.slow,delay:g.start+.85*g.dur,easing:a.out,fill:"both"}))}),f.setAttribute("mask",`url(#${M})`)}if(i&&this.host.model().type==="sequence"){const u=getComputedStyle(s),g=u.getPropertyValue("--basalt-text-secondary").trim(),f=u.getPropertyValue("--basalt-text-primary").trim(),M=s.querySelectorAll(`.${n}-msg`);this.ordered(e).forEach((v,S)=>{const k=M[S]?.querySelector(`.${n}-mlabel`),x=this.plans.get(v.i);k&&x&&g&&f&&d(k.animate([{color:g},{color:f}],{duration:a.slower,delay:x.start-a.base,easing:a.out,fill:"both"}),this.labels)})}this.introEnd?.cancel(),this.introEnd=d(s.animate([],{duration:Math.max(1,p)}),new Set),this.introEnd.finished.then(()=>this.finishIntro(),()=>{})}finishIntro(){this.entrance()==="running"&&(this.markVisit(),this.host.fig.setAttribute("data-entrance","done"),this.clearIntro(),this.sync())}playText(){const t=this.textCode();if(!t)return;const i=this.host.fig,e=this.t;i.setAttribute("data-entrance","running"),this.played=!0,this.t0=$();const s=[...t.querySelectorAll("[data-n]")],n=Math.max(0,...s.map(l=>Number(l.dataset.n))),a=n>1?Math.min(e.step,(e.limit-e.slower)/(n-1)):0,r=getComputedStyle(i),h=r.getPropertyValue("--basalt-text-secondary").trim(),o=r.getPropertyValue("--basalt-text-tertiary").trim();for(const l of s){const d=Number(l.dataset.n);l.querySelectorAll('[data-ink="label"], [data-ink="main"], [data-ink="plain"]').forEach(p=>{const u=p.dataset.ink==="label"?h:o,g=p.animate([{color:u},{color:u,offset:.001},{color:getComputedStyle(p).color}],{duration:e.slower,delay:(d-1)*a,easing:"ease-out",fill:"backwards"});g.startTime=this.t0,this.intro.add(g)})}this.introEnd?.cancel(),this.introEnd=i.animate([],{duration:Math.max(1,(n-1)*a+e.slower)}),this.introEnd.startTime=this.t0,this.introEnd.finished.then(()=>this.finishIntro(),()=>{})}clearIntro(){for(const t of[...this.intro,...this.labels])t.cancel();this.intro.clear(),this.labels.clear(),this.introEnd?.cancel(),this.introEnd=null,this.defs?.remove(),this.defs=null,this.host.fig.querySelectorAll(`.${this.host.P}-edge[mask]`).forEach(t=>t.removeAttribute("mask"))}edgeSignature(){const t=this.host.model();return(t.type==="sequence"?t.steps.flatMap(e=>"n"in e?[`${e.from}>${e.to}:${e.kind}`]:[]):t.edges.map(e=>`${e.from}>${e.to}:${e.kind}`)).join("|")}syncLoops(t,i){const e=this.entrance()==="done";if(!t.motion.animated||!e||!this.hasLines()||i.reduce||i.forced||i.print||i.held||this.traced()||$(){}):t.motion.packet?.repeat&&this.repeat(e,t.motion.packet.path).catch(()=>{})}clearLoops(){this.looping=!1,this.loopGen++;for(const t of this.loops)t.cancel();this.loops.clear();for(const t of[...this.flowEls.values(),...this.beadEls.values()])t.style.display="none";this.dotOwner==="loop"&&this.dot&&(this.dot.style.display="none",this.dotOwner=null),this.runAt<0&&this.dotOwner!=="run"&&this.clearArrivals()}track(t,i){i.add(t);const e=()=>{i.delete(t)};return t.finished.then(e,e),i===this.loops&&(!this.inView||document.hidden)&&t.pause(),t}wait(t,i){return this.track(this.host.fig.animate([],{duration:Math.max(1,t)}),i).finished.then(e=>{e.cancel()})}overlay(t,i,e){const s=this.host.fig.querySelector(`.${this.host.P}-ink`),n=s?.querySelector(`.${this.host.P}-svg`);if(!s||!n)return null;const a=this.host.tokens(),r=w(t,a?.head??8),h=F(r,i),o=b("svg",{class:`${this.host.P}-${e}`,width:h.r-h.l,height:h.b-h.t,viewBox:`${h.l} ${h.t} ${h.r-h.l} ${h.b-h.t}`,"aria-hidden":"true",focusable:"false"});o.style.left=`${h.l}px`,o.style.top=`${h.t}px`;let d=this.defs??n;for(;d.nextElementSibling&&!d.nextElementSibling.classList.contains(`${this.host.P}-label`);)d=d.nextElementSibling;return d.after(o),{svg:o,d:L(r,t.from===t.to?a?.radiusXs??4:a?.radius??8),pts:r}}visible(t,i){const e=this.host.geo();let s=0;for(const n of e?.labels??[])if(n.i===t.i&&n.on){const a=(n.box.t+n.box.b)/2,r=i.some((h,o)=>o>0&&Math.abs(h.y-i[o-1].y)<.5&&Math.abs(a-h.y)<1.5);s+=r?n.box.r-n.box.l:n.box.b-n.box.t}return E(i)-s}flow(t,i){const e=t.lines.find(h=>h.i===i);if(!e)return;const s=this.host.tokens();if(e.kind==="dashed"){if(this.visible(e,w(e,s?.head??8))<48)return;const h=this.host.fig.querySelector(`.${this.host.P}-edge[data-edge="${i}"] .${this.host.P}-line`);if(!h)return;const o=(s?.dash??6)+(s?.dashGap??4);this.track(h.animate([{strokeDashoffset:"0px"},{strokeDashoffset:`${-o}px`}],{duration:o/this.t.flow*1e3,iterations:1/0,easing:"linear"}),this.loops);return}let n=this.flowEls.get(i);if(n&&!n.isConnected&&(this.flowEls.delete(i),n=void 0),!n){const h=s?.space("1")??4,o=this.overlay({...e,pts:w(e,h)},e.width+2,"flow");if(!o)return;if(this.visible(e,w(e,s?.head??8))<48){o.svg.remove();return}const l=s?.cut??2;b("path",{d:o.d,"stroke-width":e.width+2,"stroke-dasharray":`${l} ${this.t.flowPeriod-l}`},o.svg),n=o.svg,this.flowEls.set(i,n)}n.style.display="";const a=n.firstElementChild,r=this.t.flowPeriod;this.track(a.animate([{strokeDashoffset:"0px"},{strokeDashoffset:`${-r}px`}],{duration:r/this.t.flow*1e3,iterations:1/0,easing:"linear"}),this.loops)}edgeFor(t,i){const s=this.host.model().edges.find(n=>n.from===t&&n.to===i);return s?this.host.geo()?.lines.find(n=>n.i===s.i):void 0}node(t){return this.host.fig.querySelector(`.${this.host.P}-node[data-node="${CSS.escape(t)}"]`)}arrive(t){!t||this.traced()||(clearTimeout(this.arrivals.get(t)),t.removeAttribute("data-arrival-out"),t.setAttribute("data-arrival",""))}depart(t){!t||!t.hasAttribute("data-arrival")||(t.removeAttribute("data-arrival"),t.setAttribute("data-arrival-out",""),this.arrivals.set(t,window.setTimeout(()=>{t.removeAttribute("data-arrival-out"),this.arrivals.delete(t)},this.t.slower*.75)))}clearArrivals(){this.host.fig.querySelectorAll("[data-arrival], [data-arrival-out]").forEach(t=>{t.removeAttribute("data-arrival"),t.removeAttribute("data-arrival-out")});for(const t of this.arrivals.values())clearTimeout(t);this.arrivals.clear()}async pulse(t,i){const e=this.host.tokens();for(;t===this.loopGen;){for(let s=1;st===this.loopGen;try{for(;e();){this.inFlight=!0,this.waiting=!1;try{await this.packetRun(i,this.loops,e)}finally{this.inFlight=!1}if(!e())return;if(this.waiting)continue;const s=this.track(this.host.fig.animate([],{duration:Math.max(1,this.t.repeat)}),this.loops);this.repeatGap=s;try{await s.finished}finally{this.repeatGap===s&&(this.repeatGap=null),s.cancel()}}}finally{!e()&&!this.looping&&(this.waiting=!1)}}send(){const t=this.host.model(),i=t.motion.packet?.path;if(!t.motion.animated||!i||!this.hasLines())return;if(this.inFlight){this.waiting=!0;return}const e=this.modes();if(e.held||e.reduce){const n=this.node(i[i.length-1]);this.arrive(n),this.wait(this.t.rest,this.runAnims).then(()=>this.depart(n),()=>this.depart(n));return}if(this.looping&&t.motion.packet?.repeat){this.waiting=!0,this.repeatGap?.finish();return}this.inFlight=!0;const s=++this.runGen;this.packetRun(i,this.runAnims,()=>s===this.runGen).catch(n=>{if(!q(n))throw n}).finally(()=>{this.inFlight=!1,this.waiting&&s===this.runGen&&(this.waiting=!1,this.send())})}quiet(t,i){const e=this.host.P,s=this.host.fig,n=s.querySelectorAll(`.${e}-msg`);i.forEach((a,r)=>{const h=t>=0&&r>t;n[r]?.toggleAttribute("data-ahead",h),s.querySelector(`.${e}-edge[data-edge="${a.i}"]`)?.toggleAttribute("data-ahead",h)})}stopRun(){this.runGen++,this.runAt=-1,this.host.fig.querySelectorAll("[data-ahead]").forEach(t=>t.removeAttribute("data-ahead"));for(const t of this.runAnims)t.cancel();this.runAnims.clear(),this.dot&&this.dotOwner==="run"&&(this.dot.style.display="none",this.dotOwner=null),this.looping||(this.inFlight=!1),this.looping?this.host.fig.querySelectorAll(`.${this.host.P}-msg[data-arrival]`).forEach(t=>t.removeAttribute("data-arrival")):this.clearArrivals()}playRun(t){if(this.textCode()){this.playTextRun(t);return}const i=this.host.geo();if(!i?.lines.length)return;for(const h of this.runAnims)h.cancel();this.runAnims.clear();const e=++this.runGen,s=()=>e===this.runGen,n=this.ordered(i),a=this.host.fig.querySelectorAll(`.${this.host.P}-msg`);this.runAt=t,(async()=>{for(let h=t;h{if(!q(h))throw h})}playTextRun(t){const i=this.textCode();if(!i)return;for(const o of this.runAnims)o.cancel();this.runAnims.clear();const e=++this.runGen,s=()=>e===this.runGen,n=[...i.querySelectorAll("[data-n]")],a=Math.max(0,...n.map(o=>Number(o.dataset.n))),r=o=>{for(const l of n)l.toggleAttribute("data-ahead",o>=0&&Number(l.dataset.n)>o)};this.runAt=t,(async()=>{for(let o=t;oNumber(d.dataset.n)===o+1);if(await this.wait(this.t.legMin+this.t.base,this.runAnims),!s())return;for(const d of l)d.setAttribute("data-arrival","");await this.wait(this.t.rest,this.runAnims);for(const d of l)d.removeAttribute("data-arrival")}s()&&(this.runAt=-1,r(-1),this.publish())})().catch(o=>{if(!q(o))throw o})}};function B(t){const i=[],e=[],{pulse:s,packet:n}=t.motion;s&&n&&i.push("a figure names both a pulse and a packet: it has one mover at most");const a=s??n?.path,r=s?"pulse":"packet",h=new Set;if(a){for(const o of a)t.byId.has(o)||i.push(`the ${r} names ${o}, which is not a node`);for(let o=1;od.from===a[o-1]&&d.to===a[o]);l?h.add(l.i):i.push(`the ${r} goes from ${a[o-1]} to ${a[o]}, and no line joins them in that direction`)}}for(const o of t.edges)o.flow&&(h.has(o.i)&&i.push(`the line from ${o.from} to ${o.to} flows and is on the ${r}'s route: flow never runs on a line the mover travels`),o.label||e.push(`the line from ${o.from} to ${o.to} flows but has no label: motion never carries a fact alone, so its label says it is a stream`));return{errors:i,warnings:e}}function j(t){return new D(t)}(function(t){"use strict";var i=t._;function e(s,n,a){var r=document.createElement("button");return r.type="button",r.className="btn "+s,r.setAttribute("data-variant","secondary"),r.setAttribute("data-size","sm"),a&&a(r),r.appendChild(document.createTextNode(n)),r}i.diagramMotion=function(s,n,a){var r=B(n.model());r.errors.forEach(function(f){console.error("Basalt diagram: "+f)}),r.warnings.forEach(function(f){console.warn("Basalt diagram: "+f)});var h=j(n),o=s.querySelector(".diagram-foot"),l=null,d=null;o&&(l=e("diagram-play","Play the run"),l.addEventListener("click",function(){h.toggleRun()}),d=e("diagram-pause","Pause animations",function(f){f.setAttribute("data-loops-toggle",""),f.setAttribute("aria-pressed",String(!!(t.loops&&t.loops.held()))),f.insertAdjacentHTML("beforeend",'")}),l.hidden=d.hidden=!0,o.appendChild(l),o.appendChild(d));function p(){var f=h.state();l&&(l.hidden=!f.runShown,l.lastChild.textContent=f.running?"Stop the run":"Play the run"),d&&(d.hidden=!f.canLoop,d.setAttribute("aria-pressed",String(!!(t.loops&&t.loops.held()))))}var u=h.subscribe(p);p();var g=a&&a.packet?a.packet.send:void 0;return h.sendValue("__diagramSend"in s?s.__diagramSend:g),h.sendValue(g),s.__diagramSend=g,{redrawn:h.redrawn,sendValue:function(f){h.sendValue(f),s.__diagramSend=f},destroy:function(){u(),h.destroy(),l&&l.remove(),d&&d.remove()}}}})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/diagram-place.mjs b/.agent/skills/basalt-html/parts/diagram-place.mjs new file mode 100644 index 00000000..392458d8 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram-place.mjs @@ -0,0 +1,211 @@ +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __esm = (fn, res, err) => function __init() { + if (err) throw err[0]; + try { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + } catch (e) { + throw err = [e], e; + } +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// packages/react/src/diagram-elk.ts +var diagram_elk_exports = {}; +__export(diagram_elk_exports, { + default: () => diagram_elk_default +}); +import ELK from "elkjs/lib/elk.bundled.js"; +var Elk, diagram_elk_default; +var init_diagram_elk = __esm({ + "packages/react/src/diagram-elk.ts"() { + "use strict"; + Elk = ELK; + diagram_elk_default = Elk; + } +}); + +// tools/html-skill/src/diagram-place.mjs +import { workerData } from "node:worker_threads"; + +// packages/react/src/diagram-layout-graph.ts +var W = 200; +var H = 80; +var STRAIGHT = "10"; +var options = (direction) => ({ + "elk.algorithm": "layered", + "elk.direction": direction === "right" ? "RIGHT" : "DOWN", + "elk.randomSeed": "1", + "elk.hierarchyHandling": "INCLUDE_CHILDREN", + "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES", + "elk.layered.cycleBreaking.strategy": "MODEL_ORDER", + "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX", + "elk.layered.spacing.nodeNodeBetweenLayers": "64", + "elk.spacing.nodeNode": "48", + "elk.edgeRouting": "ORTHOGONAL" +}); +function partsOf(input) { + const cards = input.type === "schema" ? (input.tables ?? []).map((t) => ({ id: String(t.name) })) : (input.nodes ?? []).map((n) => ({ id: String(n.id), group: n.group })); + const raw = input.type === "schema" ? (input.tables ?? []).flatMap((t) => (t.columns ?? []).filter((c) => c.references).map((c) => ({ from: String(t.name), to: String(c.references).split(".")[0], main: false }))) : (input.edges ?? []).map((e) => ({ from: String(e.from), to: String(e.to), main: e.kind === "main" })); + const ids = new Set(cards.map((c) => c.id)); + const lines = raw.filter((e) => ids.has(e.from) && ids.has(e.to)).map((e, k) => ({ ...e, k })); + return { cards, lines, groups: input.type === "architecture" ? input.groups ?? [] : [] }; +} +function mainInTheMiddle(lines) { + const bySource = /* @__PURE__ */ new Map(); + lines.forEach((e, k) => { + if (!bySource.has(e.from)) bySource.set(e.from, []); + bySource.get(e.from).push(k); + }); + const out = lines.slice(); + for (const slots of bySource.values()) { + const main = slots.filter((k) => lines[k].main); + if (slots.length < 3 || main.length !== 1) continue; + const rest = slots.filter((k) => k !== main[0]); + const order = [...rest.slice(0, Math.floor(rest.length / 2)), main[0], ...rest.slice(Math.floor(rest.length / 2))]; + slots.forEach((slot, j) => { + out[slot] = lines[order[j]]; + }); + } + return out; +} +function graphOf(cards, lines, groups, direction) { + const kids = /* @__PURE__ */ new Map([["", []]]); + for (const g of groups) kids.set(g.id, []); + for (const c of cards) (kids.get(c.group ?? "") ?? kids.get("")).push({ id: c.id, width: W, height: H }); + const children = [...kids.get("")]; + const cycles = (g) => { + const seen = /* @__PURE__ */ new Set([g.id]); + for (let p = g.parent; p; p = groups.find((x) => x.id === p)?.parent) { + if (seen.has(p)) return true; + seen.add(p); + } + return false; + }; + for (const g of groups) { + const box = { id: `group:${g.id}`, children: kids.get(g.id), layoutOptions: { "elk.padding": "[top=32,left=16,bottom=16,right=16]" } }; + (g.parent && kids.has(g.parent) && !cycles(g) ? kids.get(g.parent) : children).push(box); + } + return { id: "root", layoutOptions: options(direction), children, edges: lines.map((e, k) => ({ id: `e${k}`, sources: [e.from], targets: [e.to], ...e.main ? { layoutOptions: { "elk.layered.priority.straightness": STRAIGHT } } : {} })) }; +} + +// packages/react/src/diagram-layout.ts +function absolute(node, ox = 0, oy = 0, out = /* @__PURE__ */ new Map()) { + for (const c of node.children ?? []) { + const x = ox + (c.x ?? 0), y = oy + (c.y ?? 0); + if (c.children) absolute(c, x, y, out); + else out.set(c.id, { x, y, w: c.width ?? W, h: c.height ?? H }); + } + return out; +} +function bands(rects, lo, hi) { + const ids = [...rects.keys()].sort((a, b) => lo(rects.get(a)) - lo(rects.get(b)) || (a < b ? -1 : a > b ? 1 : 0)); + const out = /* @__PURE__ */ new Map(); + let band = 0, end = Infinity; + for (const id of ids) { + const r = rects.get(id); + if (lo(r) >= end - 0.5) { + band++; + end = Infinity; + } + end = Math.min(end, hi(r)); + out.set(id, band + 1); + } + return out; +} +var elkMade; +async function cellsOf(graph) { + if (!elkMade) { + const mod = await Promise.resolve().then(() => (init_diagram_elk(), diagram_elk_exports)); + elkMade = new mod.default(); + } + const rects = absolute(await elkMade.layout(graph)); + const col = bands(rects, (r) => r.x, (r) => r.x + r.w), row = bands(rects, (r) => r.y, (r) => r.y + r.h); + const cells = {}; + for (const id of rects.keys()) cells[id] = { col: col.get(id), row: row.get(id) }; + return cells; +} +function unusable(cards, groups, cells) { + const seen = /* @__PURE__ */ new Set(); + for (const c of cards) { + const at = cells[c.id]; + if (!at) return true; + const key = `${at.col},${at.row}`; + if (seen.has(key)) return true; + seen.add(key); + } + const chain = (id) => { + const out = []; + for (let g = id; g && !out.includes(g); g = groups.find((x) => x.id === g)?.parent) out.push(g); + return out; + }; + for (const g of groups) { + const mine = cards.filter((c) => chain(c.group).includes(g.id)); + if (!mine.length) continue; + const at = mine.map((c) => cells[c.id]); + const box = { c1: Math.min(...at.map((a) => a.col)), c2: Math.max(...at.map((a) => a.col)), r1: Math.min(...at.map((a) => a.row)), r2: Math.max(...at.map((a) => a.row)) }; + if (cards.some((c) => !mine.includes(c) && cells[c.id].col >= box.c1 && cells[c.id].col <= box.c2 && cells[c.id].row >= box.r1 && cells[c.id].row <= box.r2)) return true; + } + return false; +} +async function placeDiagram(input, direction) { + const { cards, lines: authored, groups } = partsOf(input); + const lines = mainInTheMiddle(authored); + const first = await cellsOf(graphOf(cards, lines, groups, direction)); + const layer = (id) => direction === "down" ? first[id].row : first[id].col; + const chain = (id) => { + const out = []; + for (let g = id; g && !out.includes(g); g = groups.find((x) => x.id === g)?.parent) out.push(g); + return out; + }; + const groupOf = new Map(cards.map((c) => [c.id, c.group])); + const all = cards.slice(); + const chained = []; + let ways = 0; + for (const e of lines) { + const a = layer(e.from), b = layer(e.to); + if (!e.main || Math.abs(b - a) < 2) { + chained.push(e); + continue; + } + const inA = chain(groupOf.get(e.from)), inB = chain(groupOf.get(e.to)); + const both = inA.find((g) => inB.includes(g)); + const boxes = []; + let prev = e.from; + for (let l = a + Math.sign(b - a); l !== b; l += Math.sign(b - a)) { + const id = `way:${e.k}:${l}`; + const here = new Set(cards.filter((c) => layer(c.id) === l).flatMap((c) => chain(c.group))); + const group = inB.find((g) => here.has(g)) ?? inA.find((g) => here.has(g)) ?? both; + boxes.push({ id, group, way: true }); + chained.push({ ...e, from: prev, to: id }); + prev = id; + } + chained.push({ ...e, from: prev }); + all.splice(all.findIndex((c) => c.id === e.to), 0, ...boxes); + ways++; + } + const span = (c) => ({ cols: Math.max(1, ...Object.values(c).map((x) => x.col)), rows: Math.max(1, ...Object.values(c).map((x) => x.row)) }); + if (!ways) return { direction, ...span(first), cells: first }; + const second = await cellsOf(graphOf(all, chained, groups, direction)); + const cells = {}; + for (const c of cards) cells[c.id] = second[c.id]; + const layers = (c) => Math.max(1, ...cards.map((x) => direction === "down" ? c[x.id].row : c[x.id].col)); + return unusable(cards, groups, cells) || layers(cells) > layers(first) ? { direction, ...span(first), cells: first } : { direction, ...span(second), cells }; +} + +// tools/html-skill/src/diagram-place.mjs +var { spec, port, signal } = workerData; +var flag = new Int32Array(signal); +try { + const directions = spec.direction ? [spec.direction] : spec.type === "flowchart" ? ["down", "right"] : ["right", "down"]; + const out = []; + for (const d of directions) out.push(await placeDiagram(spec, d)); + port.postMessage({ placement: out }); +} catch (e) { + port.postMessage({ error: String(e && e.message ? e.message : e) }); +} +Atomics.store(flag, 0, 1); +Atomics.notify(flag, 0); diff --git a/.agent/skills/basalt-html/parts/diagram-text.js b/.agent/skills/basalt-html/parts/diagram-text.js new file mode 100644 index 00000000..9af91f49 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram-text.js @@ -0,0 +1,2 @@ +(()=>{var B={"&":"&","<":"<",">":">",'"':""","'":"'"},H=u=>u.replace(/[&<>"']/g,h=>B[h]);function z(u){const h=u.nodes,W=u.steps,d=n=>Array.from(n).length,b=h.map(n=>Math.max(8,d(n.name)+4)),r=h.map(()=>0);let _=0;h.forEach((n,t)=>{r[t]=_+Math.floor(b[t]/2),_+=b[t]+4});const A=(n,t,o)=>{const[s,a]=n0)for(let i=a;i0&&A(t-1,t,s+8):A(t,o,s+4)}const M=h.length-1,x=new Map;{let n=0;const t=[],o=(a,f)=>r[a]-Math.floor(b[a]/2)-1+f,s=(a,f)=>r[a]+Math.ceil(b[a]/2)-f;W.forEach((a,f)=>{if("open"in a){t.push({at:f,a:a.a-1,b:a.b-1,inset:n*2,need:d(`[${a.open}]`)+1+d(` ${a.label} `)+2}),n++;return}if("otherwise"in a){const i=t[t.length-1];i&&(i.need=Math.max(i.need,d("[else]")+1+d(` ${a.otherwise} `)+2));return}if("close"in a){n=Math.max(0,n-1);const i=t.pop();if(!i)return;const k=x.get(i.at)??0,m=i.need-(s(i.b,i.inset)-o(i.a,i.inset))-k;if(m>0){if(i.b"n"in n&&n.from===n.to&&(u.byId.get(n.from)?.i??0)===M?d(`${n.n} ${n.label}`)+8:0)),w=(r[M]??0)+Math.ceil((b[M]??8)/2)+S+2+Math.max(0,...x.values()),T=[],p=()=>{const n={ch:Array(w).fill(" "),ink:Array(w).fill("")};return T.push(n),n},l=(n,t,o,s)=>{Array.from(o).forEach((a,f)=>{const i=t+f;i>=0&&iu.bars.some(o=>o.who===h[n].id&&o.from<=t&&o.to>=t);let j=0;const y=n=>h.forEach((t,o)=>l(n,r[o],R(o,j)?"┃":"│",R(o,j)?"working":"life")),D=p(),q=p(),G=p();h.forEach((n,t)=>{const o=r[t]-Math.floor(b[t]/2),s=b[t],[a,f,i,k,m,$]=n.focal?["╔","═","╗","║","╚","╝"]:["┌","─","┐","│","└","┘"],e=n.focal?"focal":"name";l(D,o,a+f.repeat(s-2)+i,e),l(q,o,k,e),l(q,o+s-1,k,e),l(q,o+Math.floor((s-d(n.name))/2),n.name,e),l(G,o,m+f.repeat(s-2)+$,e)});const C=[],v=n=>{for(const t of C)l(n,t.l,"│","frame"),l(n,t.r,"│","frame")},F=()=>{const n=p();return y(n),v(n),n};F();for(const[n,t]of W.entries()){if("band"in t){const e=p(),c=` ${t.band} `;l(e,0,"─".repeat(w),"band"),l(e,Math.max(0,Math.floor((w-d(c))/2)),c,"band"),F();continue}if("open"in t){const e=t.a-1,c=t.b-1,L=C.length*2,g={l:Math.max(0,r[e]-Math.floor(b[e]/2)-1+L),r:Math.min(w-1,r[c]+Math.ceil(b[c]/2)+(c===M&&W.some(I=>"n"in I&&I.from===I.to)?S:0)-L+(x.get(n)??0))},E=p();y(E),v(E),l(E,g.l,"┌"+"─".repeat(g.r-g.l-1)+"┐","frame"),l(E,g.l+1,`[${t.open}]`,"op"),l(E,g.l+d(t.open)+4,` ${t.label} `,"label"),C.push(g),F();continue}if("otherwise"in t){const e=C[C.length-1];if(!e)continue;const c=p();y(c),v(c),l(c,e.l,"├"+"┄".repeat(e.r-e.l-1)+"┤","frame"),l(c,e.l+1,"[else]","op"),l(c,e.l+8,` ${t.otherwise} `,"label"),F();continue}if("close"in t){const e=C.pop();if(!e)continue;const c=p();y(c),v(c),l(c,e.l,"└"+"─".repeat(e.r-e.l-1)+"┘","frame"),F();continue}j=t.n;const o=u.byId.get(t.from)?.i??0,s=u.byId.get(t.to)?.i??0,a=`${t.n} ${t.label}`,f=e=>e==="main"?"━":e==="dashed"?"┄":"─",i=(e,c)=>e==="dashed"?c?"▷":"◁":c?"▶":"◀",k=t.kind==="main"?"main":"plain",m=p(),$=p();if(m.n=t.n,$.n=t.n,y(m),v(m),y($),v($),o===s){const e=o===M&&h.length>1,c=e?r[o]-4:r[o]+1;l(m,c,e?"┌──":"──┐",k),l($,c,e?"└─"+i(t.kind,!0):i(t.kind,!1)+"─┘",k);const L=e?c-d(a)-1:r[o]+5;if(l(m,L,a.slice(0,d(String(t.n))),"num"),l(m,L+d(String(t.n))+1,t.label,"label"),t.note){const g=p();y(g),v(g),l(g,e?c-d(t.note)-1:r[o]+5,t.note,"note")}}else{const e=Math.min(r[o],r[s]),c=Math.max(r[o],r[s]),L=r[s]>r[o],g=e+Math.max(2,Math.floor((c-e-d(a))/2));l(m,g-1," ",""),l(m,g,String(t.n),"num"),l(m,g+d(String(t.n))," "+t.label+" ","label");const E=f(t.kind).repeat(Math.max(1,c-e-2));if(l($,e+1,L?E+i(t.kind,!0):i(t.kind,!1)+E,k),t.note){const I=p();y(I),v(I);const J=e+Math.max(2,Math.floor((c-e-d(t.note))/2));l(I,J-1,` ${t.note} `,"note")}}}return F(),{html:T.map(n=>{const t=n.ch.join("").trimEnd().length;let o="",s="",a=n.ink[0]??"";for(let f=0;f${H(s)}`:H(s),s=""),a=n.ink[f],s+=n.ch[f];return s&&(o+=a?`${H(s)}`:H(s)),n.n?`${o}`:o}).join(` +`),width:Math.max(...T.map(n=>n.ch.join("").trimEnd().length))}}(function(u){"use strict";u._.diagramText=function(h,W,d,b){var r=h.querySelector(".diagram-text"),_=r&&r.querySelector(".diagram-text-ink");if(_){h.__transcript||(h.__transcript=_.innerHTML);var A=z(W),M=document.createElement("span");M.style.cssText="display:inline-block;white-space:pre",M.textContent="─".repeat(40),r.appendChild(M);var x=M.offsetWidth/40;M.remove();var S=getComputedStyle(r),w=r.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight);b&&b.textWidth&&(b.textWidth(A.width*x+(h.clientWidth-w)+1),w=r.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight));var T=A.width*x<=w+.5,p=T?A.html:h.__transcript;_.innerHTML!==p&&(_.innerHTML=p),r.toggleAttribute("data-art",T)}}})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/diagram-zoom.css b/.agent/skills/basalt-html/parts/diagram-zoom.css new file mode 100644 index 00000000..8c319c02 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram-zoom.css @@ -0,0 +1 @@ +@layer basalt{@media(pointer:coarse){.diagram-expand{min-height:var(--basalt-size-tap-min)}}@media(width>=720px){.dialog[data-form].diagram-viewer,.dialog[data-form][data-held].diagram-viewer{width:calc(100vw - 2 * var(--basalt-space-4));max-width:none;height:calc(100dvh - 2 * var(--basalt-space-4));max-height:none}}.diagram-viewer .sheet-head{flex:none}.diagram-viewer-source{overflow-wrap:break-word}.diagram-stage{--_pad: var(--basalt-space-4);--_travel: var(--basalt-space-1);--_clear: var(--basalt-space-4);--_rest: var(--basalt-duration-slower);position:relative;flex:1 1 auto;display:flex;min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;touch-action:none;outline:none}@media(width>=720px){.diagram-stage{--_pad: var(--basalt-space-6)}}.diagram-stage:focus-visible{outline:var(--basalt-size-focus-width) solid var(--basalt-border-focus);outline-offset:calc(-1 * var(--basalt-size-focus-width))}.diagram-stage[data-pannable]{cursor:grab}.diagram-stage[data-pannable][data-dragging]{cursor:grabbing}.diagram-stage[data-list]{display:block;touch-action:pan-y}.diagram-probe{position:absolute;top:0;left:0;height:0;visibility:hidden;pointer-events:none}.diagram-probe[data-probe=row]{width:calc(var(--basalt-size-page-width) - 2 * var(--basalt-size-gutter))}.diagram-probe[data-probe=contain]{width:var(--basalt-size-breakpoint-container)}.diagram-sizer{position:relative;flex:none;box-sizing:content-box;margin:auto;padding:var(--_pad)}.diagram-sizer[hidden]{display:none}.diagram-layer{position:absolute;top:var(--_pad);inset-inline-start:var(--_pad);transform-origin:0 0;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none}.diagram-layer:dir(rtl){transform-origin:100% 0}.diagram[data-viewer]{gap:0}.diagram[data-viewer]>:is(.diagram-head,.diagram-key,.diagram-hint,.diagram-tap-hint,.diagram-foot,.diagram-list,.diagram-summary){display:none}.diagram-viewer-list{box-sizing:border-box;max-width:calc(var(--basalt-size-page-width) - 2 * var(--basalt-size-gutter) + 2 * var(--_pad));padding:var(--_pad)}.diagram-viewer-foot{display:flex;flex-direction:column;gap:var(--basalt-space-3);padding-block-start:var(--basalt-space-3)}.diagram-viewer-key{--_ground: var(--panel-bg, var(--basalt-surface-overlay))}.diagram-viewer-key .diagram-key{padding-block-start:0;border-top:0}.diagram-viewer-key[data-layout=drawn] .diagram-entry[data-when=stacked],.diagram-viewer-key[data-layout=stacked] .diagram-entry[data-when=drawn],.diagram-viewer-key[data-bare] .diagram-entry[data-line]{display:none}.diagram-viewer-row{display:flex;flex-wrap:wrap;align-items:center;gap:var(--basalt-space-2)}.diagram-zoom{display:flex;align-items:center;gap:var(--basalt-space-1)}.diagram-level{display:inline-grid;justify-items:center;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);font-variant-numeric:tabular-nums}.diagram-level:before{content:attr(data-reserve);grid-area:1 / 1;visibility:hidden}.diagram-level>span{grid-area:1 / 1}.diagram-viewer-hint{flex:1 1 auto;min-width:0}.diagram-viewer-end{display:flex;gap:var(--basalt-space-2);margin-inline-start:auto}@media(pointer:coarse){.diagram-zoom .btn,.diagram-viewer-end .btn{min-height:var(--basalt-size-tap-min);min-width:var(--basalt-size-tap-min)}}@media(forced-colors:active){.diagram-level{color:CanvasText}.diagram-viewer-foot [aria-disabled=true]{color:GrayText}}@media print{.diagram-expand,.diagram-viewer{display:none!important;transition:none!important}}} diff --git a/.agent/skills/basalt-html/parts/diagram-zoom.js b/.agent/skills/basalt-html/parts/diagram-zoom.js new file mode 100644 index 00000000..ed356211 --- /dev/null +++ b/.agent/skills/basalt-html/parts/diagram-zoom.js @@ -0,0 +1 @@ +(()=>{var tt="Plus and minus zoom, zero fits the drawing, Escape closes.";function et(s){return[...s.filter(h=>h.keys[0]!=="Esc"),{keys:["+","−"],words:"zoom"},{keys:["0"],words:"fit"},{keys:["Esc"],words:"close"}]}var G=[25,33,50,67,75,100,125,150,200,300,400],j=4,J=2,at=100,Q=25,U=5e-4;function it(s){const{stage:e,sizer:h,layer:p,status:k}=s;let m=0,M=0,a=1,r=1,c=!1,d=!1,y=null,u="",z=0;const T=()=>Number.parseFloat(getComputedStyle(h).paddingTop)||0,A=()=>Math.min(r,1),q=t=>Math.min(j,Math.max(A(),t));function o(){if(!m||!M)return 1;const t=T(),n=e.clientWidth-2*t,x=e.clientHeight-2*t;if(n<=0||x<=0)return Math.min(1,J);const H=Math.min(n/m,x/M);return Math.min(J,Math.floor(H*100+1e-6)/100)}function l(){const t=A();return{zoom:a,level:Math.round(a*100),fit:r,min:t,max:j,atMin:a<=t+U,atMax:a>=j-U,atFit:Math.abs(a-r)e.clientWidth-2*T()+.5||M*a>e.clientHeight-2*T()+.5)}function S(){clearTimeout(z);const t=`Zoom ${Math.round(a*100)}%`;z=window.setTimeout(()=>{t!==u&&(u=t,k.textContent=t)},s.rest)}function v(){h.style.width=`${m*a}px`,h.style.height=`${M*a}px`,p.style.transform=`scale(${a})`}function K(t){const n=p.getBoundingClientRect();return{x:(t.x-n.left)/a,y:(t.y-n.top)/a}}function E(t,n){const x=p.getBoundingClientRect();e.scrollLeft+=x.left+t.x*a-n.x,e.scrollTop+=x.top+t.y*a-n.y}const g=()=>{const t=e.getBoundingClientRect();return{x:t.left+e.clientWidth/2,y:t.top+e.clientHeight/2}};function W(t,n=g(),x){if(d)return;const H=q(t);if(Math.abs(H-a)<1e-6){w();return}const st=x??K(n);a=H,v(),E(st,n),w(),S()}function L(t){c=!0;const n=a*100,x=t?G.find(H=>H>n+.5):[...G].reverse().find(H=>HNumber.parseFloat(getComputedStyle(e).getPropertyValue("--_travel"))||4,i=()=>{const[t,n]=[...f.values()];return{x:(t.x+n.x)/2,y:(t.y+n.y)/2}},b=()=>{const[t,n]=[...f.values()];return Math.hypot(t.x-n.x,t.y-n.y)};function Y(t){if(!d&&!(t.pointerType==="mouse"&&t.button!==0)&&(f.set(t.pointerId,{x:t.clientX,y:t.clientY}),f.size===1&&(F={x:t.clientX,y:t.clientY},C=F,O=!1,$=!1),f.size===2&&t.pointerType==="touch")){const n=i();B={d0:b()||1,z0:a,c:K(n)},$=!0,O=!1;try{e.setPointerCapture(t.pointerId)}catch{}}}function N(t){if(!f.has(t.pointerId)||d)return;if(f.set(t.pointerId,{x:t.clientX,y:t.clientY}),B&&f.size>=2){c=!0;const x=q(B.z0*(b()/B.d0)),H=i();Math.abs(x-a)>1e-6&&(a=x,v(),w(),S()),E(B.c,H);return}if(f.size!==1||!F||!C)return;const n={x:t.clientX,y:t.clientY};if(!O){if(Math.hypot(n.x-F.x,n.y-F.y)<=V())return;O=!0,$=!0,e.setAttribute("data-dragging","");try{e.setPointerCapture(t.pointerId)}catch{}}e.scrollLeft-=n.x-C.x,e.scrollTop-=n.y-C.y,C=n,t.preventDefault()}function Z(t){if(f.has(t.pointerId)){if(f.delete(t.pointerId),f.size<2&&(B=null),f.size===1){const[n]=[...f.values()];C=n,F=n,O=!0;return}f.size===0&&(O=!1,e.removeAttribute("data-dragging"),F=C=null)}}function P(t){$&&($=!1,t.preventDefault(),t.stopPropagation())}const X=new ResizeObserver(()=>{if(!m||!M)return;const t=c?K(g()):null;r=o(),c?(a=q(a),v(),t&&E(t,g())):(a=r,v()),w()});return X.observe(e),e.addEventListener("wheel",R,{passive:!1}),e.addEventListener("keydown",D),e.addEventListener("pointerdown",Y),e.addEventListener("pointermove",N),e.addEventListener("pointerup",Z),e.addEventListener("pointercancel",Z),e.addEventListener("click",P,!0),{size:I,zoomIn:()=>L(!0),zoomOut:()=>L(!1),fit:_,state:l,list(t){t!==d&&(t?(y={left:e.scrollLeft,top:e.scrollTop},d=!0,e.setAttribute("data-list",""),e.scrollTop=0):(d=!1,e.removeAttribute("data-list"),v(),y&&(e.scrollLeft=y.left,e.scrollTop=y.top),y=null),w())},travelled:()=>$,destroy(){clearTimeout(z),X.disconnect(),e.removeEventListener("wheel",R),e.removeEventListener("keydown",D),e.removeEventListener("pointerdown",Y),e.removeEventListener("pointermove",N),e.removeEventListener("pointerup",Z),e.removeEventListener("pointercancel",Z),e.removeEventListener("click",P,!0)}}}function rt(s,e,h){const p=s.getBoundingClientRect(),k=e.getBoundingClientRect(),m=p.left+h,M=p.left+s.clientWidth-h,a=p.top+h,r=p.top+s.clientHeight-h;k.leftM&&(s.scrollLeft+=Math.min(k.right-M,k.left-m)),k.topr&&(s.scrollTop+=Math.min(k.bottom-r,k.top-a))}function nt(s,e){s.memo.art=Math.ceil(e),s.layer.style.width=`${s.memo.art}px`}function ot(s,e,h,p,k,m,M,a){const{layer:r,memo:c,measureFigure:d}=a;if(c.model!==e&&(c.model=e,c.least=void 0,c.art=void 0),e.text){r.style.width=`${c.art??Math.min(a.avail,a.row)}px`;const w=r.style.transform;r.style.transform="none";const S=d(s,e,h,p,k,m,M);return r.style.transform=w,S}const y=w=>{r.style.width=`${Math.max(c.least||w,Math.min(a.avail,a.row))}px`};r.style.width||(r.style.width=`${Math.min(a.avail,a.row)}px`);const u=r.style.transform;r.style.transform="none";const z=r.offsetWidth?r.getBoundingClientRect().width/r.offsetWidth:1,T=Math.abs(z-1)>1e-4?` scale(${1/z})`:"";r.style.transform=T||"none";const A=(s.querySelector(`.${h}-drawing`)??r).getBoundingClientRect(),q=A.left-Math.round(A.left),o=A.top-Math.round(A.top);(q||o)&&(r.style.transform=`translate(${-q/z}px, ${-o/z}px)${T}`);let l=d(s,e,h,p,k,m,c.least===void 0?void 0:M,y);if(l.dyn.layout==="stacked"&&c.least===void 0&&l.least!==void 0){const w=l.dyn,S=g=>{r.style.width=`${g}px`;const W=d(s,e,h,p,w,m);return W.dyn.layout==="drawn"?d(s,e,h,p,W.dyn,m):W},v=Math.max(l.least,Math.min(a.avail,a.row)),K=Math.max(a.row,v)*1.5;let E;for(let g=v+16;g<=K&&E===void 0;g+=16)S(g).dyn.layout==="drawn"&&(E=g);if(E!==void 0){for(let g=E-15;ga.contain&&(r.style.width=`${a.contain}px`,l=d(s,e,h,p,l.dyn,m,M)),r.style.transform=u,l}(function(s){"use strict";var e=s._,h=0;function p(a){return e.diagramKit.escapeHtml(String(a??""))}function k(a){return''+p(a)+""}function m(a,r){return parseFloat(getComputedStyle(a).getPropertyValue(r))||0}function M(a,r,c,d){var y=e.diagramKit,u=Object.assign({},r,{motion:"still"}),z=y.buildModel(u,{placement:Array.isArray(u.placement)?u.placement[0]:u.placement}),T="dgv"+ ++h,A=y.figureKey("diagram",z),q=et(y.hintEntries(z,!0)).map(function(i){return""+i.keys.map(k).join(" ")+" "+p(i.words)+""}).join(""),o=document.createElement("dialog");o.className="panel float modal dialog diagram-viewer",o.setAttribute("data-form",""),o.setAttribute("aria-describedby",T+"-summary"),o.innerHTML='

'+p(z.title)+"

"+(r.source?'

'+p(r.source)+"

":"")+'

'+p(r.summary)+'

'+(A?'
'+y.toHtml(A)+"
":"")+'
',document.body.appendChild(o);var l=o.querySelector(".diagram-stage"),w=o.querySelector(".diagram-sizer"),S=o.querySelector(".diagram-layer"),v=S.firstChild,K=o.querySelector('[role="status"]'),E=o.querySelector(".diagram-level > span"),g=o.querySelector(".diagram-viewer-key"),W=o.querySelector(".diagram-toggle"),L={out:o.querySelector('[data-zoom="out"]'),in:o.querySelector('[data-zoom="in"]'),fit:o.querySelector('[data-zoom="fit"]')},_=null,I=!1,R=!1,D=function(i,b){b?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled")},f=it({stage:l,sizer:w,layer:S,status:K,rest:m(l,"--_rest")||300,onChange:function(i){E.textContent=i.level+"%",D(L.out,i.listOpen||i.atMin),D(L.in,i.listOpen||i.atMax),D(L.fit,i.listOpen||i.atFit)}}),F={},C={layer:S,avail:0,row:1104,contain:480,memo:F,measureFigure:y.measureFigure,keys:tt,room:function(){var i=parseFloat(getComputedStyle(w).paddingTop)||0;return{w:l.clientWidth-2*i,h:l.clientHeight-2*i}},measure:function(i,b,Y,N,Z,P,X){return ot(i,b,Y,N,Z,P,X,C)},textWidth:function(i){nt(C,i)},onMeasured:function(i,b){l.setAttribute("data-layout",i.dyn.layout||""),g&&(g.setAttribute("data-layout",i.dyn.layout||""),g.toggleAttribute("data-bare",!!i.dyn.bare)),R=!!i.dyn.bare,W.hidden=R,$(I||R),f.size(b.offsetWidth,b.offsetHeight)}};function O(){C.avail=Math.max(0,Math.floor(l.clientWidth-2*(parseFloat(getComputedStyle(w).paddingLeft)||0))),C.row=o.querySelector('[data-probe="row"]').offsetWidth||1104,C.contain=o.querySelector('[data-probe="contain"]').offsetWidth||480}function $(i){i&&!_&&(_=document.createElement("div"),_.className="diagram-list diagram-viewer-list",_.innerHTML=y.figureList("diagram",z).map(function(b){return y.toHtml(b)}).join(""),l.appendChild(_)),i&&f.list(!0),_&&(_.hidden=!i),w.hidden=i,i||f.list(!1)}W.addEventListener("click",function(){I=!I,W.setAttribute("aria-expanded",String(I)),W.firstElementChild.textContent=I?"Hide the list":"View as list",$(I||R)}),L.out.addEventListener("click",function(){L.out.hasAttribute("aria-disabled")||f.zoomOut()}),L.in.addEventListener("click",function(){L.in.hasAttribute("aria-disabled")||f.zoomIn()}),L.fit.addEventListener("click",function(){L.fit.hasAttribute("aria-disabled")||f.fit()}),o.addEventListener("click",function(i){var b=i.target.closest&&i.target.closest("a.diagram-node[href]");!b||!o.contains(b)||i.defaultPrevented||i.button!==0||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||b.target&&b.target!=="_self"||o.open&&o.close()}),l.addEventListener("focusin",function(i){var b=i.target.closest&&i.target.closest(".diagram-node");b&&l.contains(b)&&rt(l,b,m(l,"--_clear")||16)}),r.export===!0&&typeof e.diagramExport=="function"&&e.diagramExport(o.querySelector(".diagram-viewer-end"),v),s.openDialog(o,d),O(),y.draw(v,u,!1,C),setTimeout(function(){l.focus({preventScroll:!0})},0);var B=l.clientWidth,V=new ResizeObserver(function(){Math.abs(l.clientWidth-B)<.5||(B=l.clientWidth,O(),v.__diagram&&v.__diagram.layout())});V.observe(l),o.addEventListener("transitionend",function(i){i.target===o&&i.propertyName==="transform"&&o.open&&v.__diagram&&v.__diagram.layout()}),a.setAttribute("data-viewing",""),c.animated&&c.settle(),o.addEventListener("close",function(){V.disconnect(),f.destroy(),v.__diagram&&v.__diagram.stop(),a.removeAttribute("data-viewing"),setTimeout(function(){o.remove()},m(o,"--_dur")*.75||300)})}e.diagramZoom=function(a,r,c){var d=a.querySelector(":scope > .diagram-foot");if(!d)return null;var y=d.querySelector(".diagram-expand");y&&y.remove();var u=document.createElement("button");u.type="button",u.className="btn diagram-expand",u.setAttribute("data-variant","secondary"),u.setAttribute("data-size","sm"),u.setAttribute("aria-haspopup","dialog"),u.innerHTML="Expand";var z=d.querySelector(".diagram-toggle");z&&z.nextSibling?d.insertBefore(u,z.nextSibling):d.appendChild(u);var T=function(){M(a,r,c,u)};return u.addEventListener("click",T),{destroy:function(){u.removeEventListener("click",T),u.remove()}}}})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/diagram.css b/.agent/skills/basalt-html/parts/diagram.css index 99d58fdc..9258fd20 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;--basalt-size-diagram-bead: 24px;--basalt-size-diagram-flow: 12px}: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);--basalt-diagram-hit: var(--basalt-text-secondary);--basalt-diagram-focal-hit: var(--basalt-action-primary-hover)}[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);--basalt-diagram-hit: var(--basalt-text-secondary);--basalt-diagram-focal-hit: var(--basalt-action-primary-hover)}@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);--basalt-diagram-hit: var(--basalt-text-primary)}}@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%}:root,[data-theme=light],.light{--_dkm: initial}[data-theme=dark],.dark{--_dkm: }@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--_dkm: }}.diagram-mark{--_mf: var(--_dkm) var(--_md);position:absolute;inset-block-start:var(--basalt-space-2-5);inset-inline-end:var(--basalt-space-3);width:var(--basalt-size-icon-sm);height:var(--basalt-size-icon-sm);background:var(--_mf, var(--_ml)) center / contain no-repeat;pointer-events:none}.diagram-node[data-focal]>.diagram-mark{--_mf: var(--_dkm) var(--_ml);background-image:var(--_mf, var(--_md, var(--_ml)))}.diagram-node[data-mark]>.diagram-mark+:is(.diagram-kind,.diagram-name){padding-inline-end:var(--basalt-space-6)}.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:var(--_ww, 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;flex-wrap:wrap;gap:var(--basalt-space-2)}.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}.diagram .diagram-mark{display:none}.diagram .diagram-node[data-mark]>.diagram-mark+:is(.diagram-kind,.diagram-name){padding-inline-end:0}}@media print{.diagram-svg,.diagram-swatch,.diagram-arrow,.diagram-mark,.diagram-node[data-focal]{-webkit-print-color-adjust:exact;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-activation: 8px;--basalt-size-diagram-foot: 14px;--basalt-size-diagram-guide-dash: 4px;--basalt-size-diagram-bead: 24px;--basalt-size-diagram-flow: 12px}: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);--basalt-diagram-hit: var(--basalt-text-secondary);--basalt-diagram-focal-hit: var(--basalt-action-primary-hover)}[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);--basalt-diagram-hit: var(--basalt-text-secondary);--basalt-diagram-focal-hit: var(--basalt-action-primary-hover)}@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);--basalt-diagram-hit: var(--basalt-text-primary)}}@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(--_gw, 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);--_Rows: var(--_D) var(--_rows, none);display:grid;grid-template-columns:var(--_Cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr)));grid-template-rows:var(--_Rows, none);gap:var(--_Gap, var(--basalt-space-4));align-items:start;max-width:none}.diagram[data-type=schema][data-marks]>.diagram-drawing{--_col-gap: calc(var(--basalt-space-12) + var(--basalt-space-3))}.diagram[data-type=sequence]>.diagram-drawing{display:flex;gap:0}.diagram[data-rtl]>.diagram-drawing{direction:ltr}.diagram[data-rtl]>.diagram-drawing :is(.diagram-node>:not(.diagram-mark),.diagram-lane-name,.diagram-said,.diagram-note,.diagram-band,.diagram-fhead,.diagram-felse){direction:rtl}.diagram[data-rtl] .diagram-gbox>.diagram-glabel{inset-inline:auto var(--basalt-space-3)}.diagram[data-rtl] .diagram-group>.diagram-glabel{inset-inline:auto var(--basalt-space-3);margin-inline:0 calc(-1 * var(--basalt-space-1-5))}.diagram[data-rtl] .diagram-runs{direction:ltr;unicode-bidi:isolate}.diagram[data-rtl] .diagram-fhead{inset-inline-start:calc(100% - var(--_fl) - var(--_fw) + var(--basalt-size-hairline))}.diagram[data-rtl] .diagram-felse{padding-inline-start:calc(100% - var(--_fl) - var(--_fw) + var(--basalt-space-3))}.diagram[data-rtl] .diagram-felse:before{inset-inline-start:var(--_Fer, calc(-1 * var(--basalt-space-4)))}.diagram[data-rtl] .diagram-msg[data-self=end] :is(.diagram-said,.diagram-note){--_Sj: var(--_D) left;margin-inline-start:0;margin-inline-end:var(--_Sm, 0)}.diagram[data-rtl] .diagram-msg[data-self=start] :is(.diagram-said,.diagram-note){--_Sj: var(--_D) right;margin-inline-end:0;margin-inline-start:var(--_Sm, 0)}.diagram[data-rtl] :is(.diagram-run,.diagram-mlabel,.diagram-tname,.diagram-cname,.diagram-ctype,.diagram-label,.diagram-glabel,.diagram-kind){unicode-bidi:isolate}.diagram[data-rtl] :is(.diagram-run,.diagram-mlabel,.diagram-cname,.diagram-label){direction:ltr}.diagram[data-rtl] .diagram-arrow{scale:-1 1}.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{--_Mh: var(--_D) var(--_mh, auto);min-height:var(--_Mh, auto)}.diagram-node{--_Jc: var(--_D) normal;justify-content:var(--_Jc, center)}.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%}:root,[data-theme=light],.light{--_dkm: initial}[data-theme=dark],.dark{--_dkm: }@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not(.light){--_dkm: }}.diagram-mark{--_mf: var(--_dkm) var(--_md);position:absolute;inset-block-start:var(--basalt-space-2-5);inset-inline-end:var(--basalt-space-3);width:var(--basalt-size-icon-sm);height:var(--basalt-size-icon-sm);background:var(--_mf, var(--_ml)) center / contain no-repeat;pointer-events:none}.diagram-node[data-focal]>.diagram-mark{--_mf: var(--_dkm) var(--_ml);background-image:var(--_mf, var(--_md, var(--_ml)))}.diagram-node[data-mark]>.diagram-mark+:is(.diagram-kind,.diagram-name){padding-inline-end:var(--basalt-space-6)}.diagram-node[data-shape=participant][data-mark]>.diagram-mark+:is(.diagram-kind,.diagram-name){padding-inline:var(--basalt-space-6)}.diagram-node[data-shape=participant]>.diagram-mark{--_Pmp: var(--_D) absolute;position:var(--_Pmp, static);flex:none;margin-inline-end:var(--_Pmm, var(--basalt-space-1-5));--_Pmm: var(--_D) 0}.diagram-node[data-shape=participant][data-mark]{--_Pfd: var(--_D) column;flex-direction:var(--_Pfd, row)}.diagram-node[data-shape=participant][data-mark]>.diagram-mark+.diagram-name{--_Pnp: var(--_D) var(--basalt-space-6);padding-inline:var(--_Pnp, 0)}.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:var(--_ww, 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-node[data-link]{color:inherit;text-decoration:none;-webkit-tap-highlight-color:transparent}.diagram-name-end{white-space:nowrap}.diagram-node[data-link] .diagram-name-end:after{content:"";display:inline-block;width:var(--basalt-size-icon-sm);height:var(--basalt-size-icon-sm);margin-inline-start:var(--basalt-space-1-5);vertical-align:calc(-1 * var(--basalt-space-0-5));background:var(--basalt-text-secondary);mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M6.5 12L17.5 12M17.5 12L11.5 7M17.5 12L11.5 17' fill='none' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;transition:transform var(--basalt-duration-base) var(--basalt-ease-out),background-color var(--basalt-duration-base) var(--basalt-ease-out)}.diagram-node[data-link=external] .diagram-name-end:after{mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M7 17L17 7M9.5 7L17 7M17 7L17 14.5' fill='none' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")}.diagram-node[data-link][data-focal] .diagram-name-end:after{background:var(--basalt-diagram-focal-ink);opacity:var(--basalt-opacity-amount)}.diagram-node[data-link]:is(:hover,:focus-visible) .diagram-name-end:after{background:var(--basalt-text-primary);transform:translate(var(--basalt-space-0-5))}.diagram-node[data-link][data-focal]:is(:hover,:focus-visible) .diagram-name-end:after{background:var(--basalt-diagram-focal-ink);opacity:1}.diagram-node[data-link]:is(:hover,:focus-visible) :is(.diagram-name,.diagram-tname){text-decoration:underline var(--basalt-size-hairline);text-underline-offset:var(--basalt-size-underline-offset)}.diagram-node[data-link]:active{background:light-dark(color-mix(in srgb,var(--basalt-neutral-0) 4%,var(--panel-next, var(--basalt-surface-1))),color-mix(in srgb,var(--basalt-neutral-100) 6%,var(--panel-next, var(--basalt-surface-1))))}@supports not (color: light-dark(white,black)){.diagram-node[data-link]:active{background:color-mix(in srgb,color-mix(in srgb,var(--basalt-neutral-100) 6%,var(--panel-next, var(--basalt-surface-1))) var(--_dkp),color-mix(in srgb,var(--basalt-neutral-0) 4%,var(--panel-next, var(--basalt-surface-1))))}}.diagram-node[data-link][data-focal]:active{background:var(--basalt-action-primary-press)}.diagram-node[data-link]:dir(rtl) .diagram-name-end:after{scale:-1 1}.diagram-node[data-link]:dir(rtl):is(:hover,:focus-visible) .diagram-name-end:after{transform:translate(calc(-1 * var(--basalt-space-0-5)))}@media(prefers-reduced-motion:reduce){.diagram-node[data-link]:is(:hover,:focus-visible) .diagram-name-end:after,.diagram-node[data-link]:dir(rtl):is(:hover,:focus-visible) .diagram-name-end:after{transform:none}}@media(pointer:coarse){.diagram-node[data-link]{min-height:var(--basalt-size-tap-min)}}@media(forced-colors:active){.diagram .diagram-node[data-link] :is(.diagram-name,.diagram-tname){color:LinkText;text-decoration:underline}.diagram .diagram-node[data-link] .diagram-name-end:after{forced-color-adjust:none;background:LinkText}.diagram .diagram-node[data-link][data-focal] :is(.diagram-name,.diagram-tname){color:Canvas}.diagram .diagram-node[data-link][data-focal] .diagram-name-end:after{background:Canvas}}.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{--_tl: 0}.diagram-group:first-child{margin-block-start:0}.diagram-group[data-turn]{padding-block-start:calc(var(--basalt-space-12) + var(--basalt-space-4) * var(--_tl, 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-group>.diagram-glabel{z-index:1;margin-inline-start:calc(-1 * var(--basalt-space-1-5));padding-inline:var(--basalt-space-1-5);background:var(--_ground)}.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-block:calc(-1 * var(--_gt, 1) * var(--basalt-space-8)) calc(-1 * var(--_gb, 1) * var(--basalt-space-4));margin-inline:calc(-1 * var(--_gs, 1) * var(--basalt-space-4)) calc(-1 * var(--_ge, 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-gbox[data-depth="2"],.diagram-group[data-depth="2"]{border-radius:var(--basalt-radius-md)}.diagram-list-group[data-depth="2"],.diagram-list-items[data-depth="2"]{margin-inline-start:var(--basalt-space-5)}.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[data-type=sequence]>.diagram-drawing>.diagram-ink{z-index:auto}.diagram-lifes{position:absolute;top:0;left:0;z-index:0;overflow:visible}.diagram[data-type=sequence] .diagram-ink>.diagram-svg{z-index:2}.diagram[data-type=sequence] .diagram-steps{z-index:auto}.diagram[data-type=sequence] .diagram-msg :is(.diagram-said,.diagram-note){position:relative;z-index:3}.diagram[data-type=sequence] :is(.diagram-fhead,.diagram-felse){z-index:3}.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-crow{fill:none;stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);stroke-linecap:butt;stroke-linejoin:miter;transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-ring{fill:var(--_ground);stroke:var(--basalt-diagram-edge);stroke-width:var(--basalt-size-hairline);transition:stroke var(--basalt-duration-fast) var(--basalt-ease-out)}.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-edge[data-lit] :is(.diagram-crow,.diagram-ring){stroke:var(--basalt-diagram-edge-main)}.diagram-edge[data-dim] :is(.diagram-crow,.diagram-ring){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-lines="2"]{height:calc(2 * var(--basalt-text-xs-line-height))}.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{--_Ac: var(--_D) var(--_ac, auto);display:flex;min-width:0;grid-column:var(--_Ac, auto);grid-row:1}.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-frame+.diagram-msgs>.diagram-msg:first-child{border-top-color:transparent}.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;column-gap:var(--basalt-space-1);row-gap:0;flex-wrap:wrap;color:var(--basalt-text-secondary)}.diagram-to{display:inline-flex;align-items:center;gap:var(--basalt-space-1);white-space:nowrap}.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-bar{fill:var(--panel-next, var(--basalt-surface-1));stroke:var(--basalt-diagram-structure);stroke-width:var(--basalt-size-hairline);rx:var(--basalt-radius-2xs)}.diagram-frame{--_Fpi: var(--_D) 0;--_cw: calc((100% - (var(--_cols, 1) - 1) * var(--basalt-space-5)) / var(--_cols, 1));--_Fl: var(--_D) calc((var(--_a) - 1) * (var(--_cw) + var(--basalt-space-5)) + var(--_fis, 0) * var(--basalt-space-2));--_Fw: var(--_D) calc((var(--_b) - var(--_a)) * (var(--_cw) + var(--basalt-space-5)) - var(--basalt-space-5) - (var(--_fis, 0) + var(--_fie, 0)) * var(--basalt-space-2));--_fl: var(--_Fl, 0%);--_fw: var(--_Fw, 100%);--_Fel: var(--_D) var(--_fl);--_Few: var(--_D) var(--_fw);--_Fer: var(--_D) calc(100% - var(--_fl) - var(--_fw));position:relative;padding-block:var(--basalt-size-control-lg) var(--basalt-space-2);padding-inline:var(--_Fpi, var(--basalt-space-4))}.diagram-frame+.diagram-frame{margin-block-start:var(--basalt-space-2)}.diagram-frame[data-depth="2"]{--_Fl: var(--_D) calc((var(--_a) - 1) * (var(--_cw) + var(--basalt-space-5)) + var(--_fis, 0) * var(--basalt-space-2))}.diagram-fbox{position:absolute;inset-block:0;inset-inline-start:var(--_fl);z-index:1;box-sizing:border-box;width:var(--_fw);border:var(--basalt-size-hairline) solid var(--basalt-diagram-structure);border-radius:var(--basalt-radius-lg);pointer-events:none}.diagram-frame[data-depth="2"]>.diagram-fbox{border-radius:var(--basalt-radius-xs)}.diagram-fhead{position:absolute;top:var(--basalt-size-hairline);inset-inline-start:calc(var(--_fl) + var(--basalt-size-hairline));display:flex;align-items:flex-start;gap:var(--basalt-space-3);margin:0;white-space:nowrap}.diagram-ftab{padding:var(--basalt-space-1) var(--basalt-space-3);border-inline-end:var(--basalt-size-hairline) solid var(--basalt-diagram-structure);border-block-end:var(--basalt-size-hairline) solid var(--basalt-diagram-structure);border-end-end-radius:var(--basalt-radius-xs);background:var(--_ground);color:var(--basalt-text-primary);font:var(--basalt-font-weight-semibold) var(--bh-xs-mono)}.diagram-flabel{margin-block-start:var(--basalt-space-1);margin-inline-start:calc(-1 * var(--basalt-space-1-5));padding-inline:var(--basalt-space-1-5);background:var(--_ground);color:var(--basalt-text-secondary);font:var(--basalt-font-weight-medium) var(--bh-xs)}.diagram-felse{position:relative;display:flex;align-items:center;gap:var(--basalt-space-1-5);height:var(--basalt-size-control-sm);margin:0;padding-inline-start:calc(var(--_fl) + var(--basalt-space-3));white-space:nowrap}.diagram-felse:before{content:"";position:absolute;top:0;inset-inline-start:var(--_Fel, calc(-1 * var(--basalt-space-4)));width:var(--_Few, calc(100% + 2 * var(--basalt-space-4)));height:var(--basalt-size-hairline);background:var(--basalt-diagram-structure);mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 1' preserveAspectRatio='none'%3E%3Crect width='1' height='1'/%3E%3C/svg%3E") 0 0 / calc(2 * var(--basalt-size-diagram-guide-dash)) var(--basalt-size-hairline) repeat-x}.diagram-felse .diagram-flabel{margin-block-start:0;margin-inline-start:0}.diagram-fword{margin-inline-start:calc(-1 * var(--basalt-space-1-5));padding-inline:var(--basalt-space-1-5);background:var(--_ground);color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs-mono)}.diagram-fword+.diagram-flabel{margin-inline-start:calc(-1 * var(--basalt-space-1-5))}.diagram-key-letters[data-op]{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-text{box-sizing:border-box;margin:0;padding:var(--basalt-space-4);overflow:hidden;border:var(--basalt-size-hairline) solid var(--basalt-border-rim);border-top-color:var(--basalt-border-rim-top);border-radius:var(--basalt-radius-md);background:var(--basalt-surface-sunken);color:var(--basalt-text-secondary);direction:ltr;font:var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-size-code-line-height) var(--basalt-font-family-mono);white-space:pre-wrap;overflow-wrap:break-word}.diagram-text[data-art]{white-space:pre;overflow-wrap:normal}.diagram-drawing:has(>.diagram-text){max-width:none}.diagram-text .diagram-text-ink{font:inherit;padding:0;border:0;border-radius:0;background:none;color:inherit}.diagram-tx-name,.diagram-tx-to{white-space:nowrap;color:var(--basalt-text-primary)}.diagram-tx-line{display:block;padding-inline-start:calc(var(--_in, 0) * 1ch);text-indent:calc(-1 * var(--_hang, 0) * 1ch)}.diagram-text [data-ink=focal],.diagram-text [data-ink=op]{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}.diagram-text :is([data-ink=name],[data-ink=working],[data-ink=plain]){color:var(--basalt-text-secondary)}.diagram-text :is([data-ink=main],[data-ink=label]){color:var(--basalt-text-primary)}.diagram-text :is([data-ink=life],[data-ink=num],[data-ink=note],[data-ink=frame],[data-ink=band]){color:var(--basalt-text-tertiary)}.diagram-key-glyph{font:var(--basalt-font-weight-regular) var(--bh-xs-mono);color:var(--basalt-text-secondary)}.diagram-key-glyph[data-ink=main]{color:var(--basalt-text-primary)}.diagram-key-glyph[data-ink=focal]{color:var(--basalt-text-primary);font-weight:var(--basalt-font-weight-semibold)}@media(forced-colors:active){.diagram-text :is([data-ink]){color:CanvasText}}.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-tap-hint{display:none;margin:0;color:var(--basalt-text-tertiary);font:var(--basalt-font-weight-regular) var(--bh-xs)}.diagram[data-touch][data-layout=drawn]>.diagram-tap-hint,.diagram[data-touch][data-layout=stacked]:not([data-bare],[data-type=sequence],[data-type=schema])>.diagram-tap-hint{display:block}.diagram[data-touch]>.diagram-hint{display:none}.diagram[data-touch] .diagram-node{min-height:var(--basalt-size-tap-min)}@media(pointer:coarse){.diagram-clear{min-height:var(--basalt-size-tap-min)}}.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;flex-wrap:wrap;gap:var(--basalt-space-2)}.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-crow,.diagram-ring,.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"]:not([data-marks]))>.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 >= 816px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="3"]>.diagram-drawing{--_D: }}@container (width >= 832px){.diagram:not([data-layout])[data-type=architecture][data-cols="4"][data-reach="4"]>.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 >= 1024px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="3"]>.diagram-drawing{--_D: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=architecture][data-cols="5"][data-reach="4"]>.diagram-drawing{--_D: }}@container (width >= 1040px){.diagram:not([data-layout])[data-type=schema][data-cols="4"]:not([data-marks])>.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 >= 1232px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="3"]>.diagram-drawing{--_D: }}@container (width >= 1248px){.diagram:not([data-layout])[data-type=architecture][data-cols="6"][data-reach="4"]>.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"]:not([data-marks])>.diagram-drawing{--_D: }}@container (width >= 1584px){.diagram:not([data-layout])[data-type=schema][data-cols="6"]:not([data-marks])>.diagram-drawing{--_D: }}@container (width >= 792px){.diagram:not([data-layout])[data-type=schema][data-marks][data-cols="3"]>.diagram-drawing{--_D: }}@container (width >= 1076px){.diagram:not([data-layout])[data-type=schema][data-marks][data-cols="4"]>.diagram-drawing{--_D: }}@container (width >= 1360px){.diagram:not([data-layout])[data-type=schema][data-marks][data-cols="5"]>.diagram-drawing{--_D: }}@container (width >= 1644px){.diagram:not([data-layout])[data-type=schema][data-marks][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-lifes,.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 :is(.diagram-crow,.diagram-ring){stroke:CanvasText}.diagram .diagram-ring{fill:Canvas}.diagram .diagram-edge[data-dim] :is(.diagram-crow,.diagram-ring){stroke:GrayText}.diagram .diagram-edge[data-lit] :is(.diagram-crow,.diagram-ring){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}.diagram .diagram-bar{fill:Canvas;stroke:CanvasText}.diagram .diagram-fbox,.diagram .diagram-ftab{border-color:GrayText}.diagram .diagram-felse:before{background:GrayText}.diagram :is(.diagram-ftab,.diagram-flabel,.diagram-fword){color:CanvasText;background:Canvas}.diagram .diagram-mark{display:none}.diagram .diagram-node[data-mark]>.diagram-mark+:is(.diagram-kind,.diagram-name){padding-inline-end:0}}@media print{.diagram-svg,.diagram-lifes,.diagram-swatch,.diagram-arrow,.diagram-mark,.diagram-node[data-focal]{-webkit-print-color-adjust:exact;print-color-adjust:exact}.diagram-hint,.diagram-tap-hint,.diagram-clear,.diagram-download{display:none!important}.diagram .diagram-edge :is(.diagram-line,.diagram-tip[data-open]){stroke:var(--basalt-diagram-edge)!important}.diagram .diagram-edge .diagram-line[data-kind=main]{stroke:var(--basalt-diagram-edge-main)!important}.diagram .diagram-edge :is(.diagram-tip:not([data-open]),.diagram-dot){fill:var(--basalt-diagram-edge)!important}.diagram .diagram-edge .diagram-tip[data-kind=main]:not([data-open]){fill:var(--basalt-diagram-edge-main)!important}.diagram .diagram-edge :is(.diagram-crow,.diagram-ring){stroke:var(--basalt-diagram-edge)!important}.diagram .diagram-label{color:var(--basalt-diagram-edge)!important}}.basalt-exporting,.basalt-exporting *{transition:none!important}.diagram-msg[data-ahead] .diagram-mlabel{color:var(--basalt-text-secondary);transition:color var(--basalt-duration-fast) var(--basalt-ease-out)}.diagram-edge[data-ahead] .diagram-line{stroke:var(--basalt-diagram-edge-dim)}.diagram-edge[data-ahead] .diagram-tip:not([data-open]){fill:var(--basalt-diagram-edge-dim)}.diagram-edge[data-ahead] .diagram-tip[data-open]{stroke:var(--basalt-diagram-edge-dim)}.diagram-text [data-n][data-ahead] [data-ink=label],.diagram[data-motion=animated][data-entrance=pending] .diagram-text [data-n] [data-ink=label]{color:var(--basalt-text-secondary)}.diagram-text [data-n][data-ahead] :is([data-ink=main],[data-ink=plain]),.diagram[data-motion=animated][data-entrance=pending] .diagram-text [data-n] :is([data-ink=main],[data-ink=plain]){color:var(--basalt-text-tertiary)}.diagram-text [data-n][data-arrival] [data-ink=num]{color:var(--basalt-text-primary)}@media(prefers-reduced-motion:reduce){.diagram-msg[data-ahead] .diagram-mlabel{transition:none}}@media(forced-colors:active){.diagram .diagram-msg[data-ahead] .diagram-mlabel{color:GrayText}.diagram .diagram-edge[data-ahead] .diagram-line{stroke:GrayText}.diagram .diagram-edge[data-ahead] .diagram-tip:not([data-open]){fill:GrayText}.diagram .diagram-edge[data-ahead] .diagram-tip[data-open]{stroke:GrayText}.diagram .diagram-text [data-n][data-ahead] [data-ink]{color:GrayText}.diagram .diagram-text [data-n][data-arrival] [data-ink=num]{color:Highlight}}@media print{.diagram .diagram-msg[data-ahead] .diagram-mlabel{color:var(--basalt-text-primary)!important}}} diff --git a/.agent/skills/basalt-html/parts/diagram.js b/.agent/skills/basalt-html/parts/diagram.js index fd3c9fce..b4515428 100644 --- a/.agent/skills/basalt-html/parts/diagram.js +++ b/.agent/skills/basalt-html/parts/diagram.js @@ -1,2 +1,6 @@ -(()=>{var ae=["top","right","bottom","left"],re=["main","plain","dashed"],ie=[2,3,4,5,6],at=t=>t==null||t===""?void 0:String(t),ut=t=>Object.assign(Object.create(null),t),ft=(t,e)=>t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;function Et(t,e={}){const s=e.checks!==!1,a=[],o=f=>{a.push(f)},r=t.legend??{},l={};for(const f of["main","plain","dashed","focal","group"]){const m=at(r[f]);m&&(l[f]=m)}const h=t.stepLabel,u=typeof h=="function"?f=>String(h(f)):typeof h=="string"?(f=>h.replace("{n}",String(f))):f=>`Step ${f}`,p=t.shapeLabels??{},g={terminal:at(p.terminal)??"Start or end",step:at(p.step)??"Step",decision:at(p.decision)??"Decision"},c=t.heading===void 0?3:ie.includes(t.heading)?t.heading:(o(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),y=(f,m)=>f==null?"plain":re.includes(f)?f:(o(`"${String(f)}" is not a kind of line (main, plain or dashed): ${m} is drawn plain`),"plain"),b=f=>{if(f!=null){if(ae.includes(f))return f;o(`"${String(f)}" is not a side (top, right, bottom or left): the derived side is used`)}},i=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>=1?f:(o(`${m} is ${JSON.stringify(f)}, not a whole number from 1: it is placed at 1`),1),d=[],w=[];let q=[];const L=[],O=[],F=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(F)||o(`"${String(F)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),F==="architecture"||F==="flowchart"){for(const f of t.nodes??[]){const m=F==="flowchart"&&f.shape==="decision"?"decision":F==="flowchart"&&f.shape==="terminal"?"terminal":"box",A=String(f.id??""),S=i(f.row,`the row of ${A}`);d.push({id:A,i:d.length,name:String(f.name??""),kind:m==="decision"?void 0:at(f.kind),detail:m==="decision"?void 0:at(f.detail),mono:!!f.detailMono,focal:!!f.focal,col:i(f.col,`the column of ${A}`),row:S,row2:S,branch:!!f.branch,shape:m,group:F==="architecture"?at(f.group):void 0,mark:F==="architecture"?le(f.mark,o):void 0})}if(F==="architecture")for(const f of t.groups??[]){const m=String(f.id??"");L.push({id:m,label:String(f.label??""),members:d.filter(A=>A.group===m).map(A=>A.id)})}}else if(F==="data-flow"){q=(t.lanes??[]).map(m=>({id:String(m.id??""),label:String(m.label??"")}));const f=new Map(q.map((m,A)=>[m.id,A+1]));for(const m of t.nodes??[]){const A=String(m.id??""),S=String(m.lane??""),z=f.get(S);z===void 0&&o(`a node (${A}) names the lane "${S}", which is not in lanes`);const C=d.length+1;d.push({id:A,i:d.length,name:String(m.name??""),kind:u(C),detail:at(m.detail),mono:!!m.detailMono,focal:!!m.focal,col:i(m.col,`the column of ${A}`),row:z??1,row2:z??1,branch:!1,shape:"box",lane:z??1,laneLabel:q[(z??1)-1]?.label??S,step:C})}}else if(F==="sequence"){(t.participants??[]).forEach((m,A)=>{const S=String(m.name??"");d.push({id:String(m.id??""),i:A,name:S,kind:at(m.kind),mono:!1,focal:!!m.focal,col:A+1,row:1,row2:1,branch:!1,shape:"participant",short:at(m.short)??S})});let f=0;for(const m of t.steps??[])"band"in m?O.push({band:String(m.band??"")}):(f++,O.push({n:f,from:String(m.from??""),to:String(m.to??""),label:String(m.label??""),note:at(m.note),kind:y(m.kind,`message ${f}`)}))}else if(F==="schema")for(const f of t.tables??[]){const m=String(f.name??""),[A,S]=Array.isArray(f.row)?f.row:[f.row,f.row],z=i(A,`the row of ${m}`),C=Math.max(z,i(S,`the last row of ${m}`)),K=f.more===void 0||f.more===null?void 0:Number.isInteger(f.more)&&f.more>0?f.more:(o(`${m}'s "more" is ${JSON.stringify(f.more)}, not a whole number from 1: it is left out`),void 0);d.push({id:m,i:d.length,name:m,mono:!0,focal:!!f.focal,col:i(f.col,`the column of ${m}`),row:z,row2:C,branch:!1,shape:"table",more:K,columns:(f.columns??[]).map(W=>({name:String(W.name??""),type:at(W.type),key:W.key==="PK"||W.key==="FK"?W.key:(W.key!==void 0&&W.key!==null&&o(`${m}.${String(W.name)}'s key is "${String(W.key)}", not PK or FK: it is left out`),void 0)}))})}const _=new Map;for(const f of d)f.id?_.has(f.id)&&o(`the id "${f.id}" is used twice`):o("a node has no id"),_.set(f.id,f);if(F==="schema")(t.tables??[]).forEach(f=>(f.columns??[]).forEach((m,A)=>{const S=at(m.references);if(!S)return;const[z,C]=S.split("."),K=_.get(z??""),W=K?.columns?.findIndex(T=>T.name===C)??-1;if(!K||W<0){o(`${String(f.name)}.${String(m.name)} references ${S}, which is not a shown column`);return}const M=_.get(String(f.name??""));M.columns[A].ref={table:z,column:C,row:W},w.push({i:w.length,from:M.id,to:z,kind:"plain",fromRow:A,toRow:W,fk:!0})}));else if(F!=="sequence")for(const f of t.edges??[]){const m=String(f.from??""),A=String(f.to??"");if(!_.has(m)||!_.has(A)){o(`a line names ${_.has(m)?A:m}, which is not a node`);continue}const S=at(f.label);S&&S.length>qt&&o(`the label "${S}" is over ${qt} characters: longer words belong in the node or the summary`),w.push({i:w.length,from:m,to:A,kind:y(f.kind,`the line from ${m} to ${A}`),label:S,fromSide:b(f.fromSide),toSide:b(f.toSide),flow:F!=="flowchart"&&f.flow===!0?!0:void 0})}else for(const f of O)"n"in f&&(!_.has(f.from)||!_.has(f.to))&&o(`message ${f.n} names ${_.has(f.from)?f.to:f.from}, which is not a participant`);if(s&&F!=="sequence"){const f=new Map;for(const m of d)for(let A=m.row;A<=m.row2;A++){const S=`${m.col}:${A}`;f.has(S)&&o(`${m.id} and ${f.get(S)} share the cell at column ${m.col}, row ${A}`),f.set(S,m.id)}}if(s){for(const m of L){const A=m.members.map(C=>_.get(C));if(!A.length)continue;const S={c1:Math.min(...A.map(C=>C.col)),c2:Math.max(...A.map(C=>C.col)),r1:Math.min(...A.map(C=>C.row)),r2:Math.max(...A.map(C=>C.row2))};for(const C of d)C.group!==m.id&&C.col>=S.c1&&C.col<=S.c2&&C.row>=S.r1&&C.row<=S.r2&&o(`${C.id} is inside the box of the group "${m.label}" but not a member`);const z=A.map(C=>C.i);Math.max(...z)-Math.min(...z)+1!==z.length&&o(`the members of the group "${m.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const m of d)m.group&&!L.some(A=>A.id===m.group)&&o(`${m.id} names the group "${m.group}", which is not in groups`);d.filter(m=>m.focal).length>1&&o("more than one node is focal: a diagram has one at most");const f=new Set(F==="sequence"?O.flatMap(m=>"n"in m?[m.kind]:[]):w.map(m=>m.kind));f.has("main")&&!l.main&&o("main lines are drawn but the legend has no words for them (legend.main)"),f.has("dashed")&&!l.dashed&&o("dashed lines are drawn but the legend has no words for them (legend.dashed)"),d.some(m=>m.focal)&&!l.focal&&o("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const Z=F==="architecture"||F==="data-flow",E=f=>Array.isArray(f)&&f.length>1?f.map(String):void 0,V=Z&&t.packet&&typeof t.packet=="object"?t.packet:void 0,$=V&&E(V.path),G={animated:t.motion==="animated",pulse:Z?E(t.pulse):void 0,packet:$?{path:$,repeat:V.repeat===!0,send:V.send}:void 0,run:F==="sequence"&&t.run===!0};if(s)for(const f of d){const m=f.mark?.says;if(!m?.length)continue;const A=[f.name,f.kind,f.detail].filter(Boolean).join(" ").toLowerCase();m.some(S=>A.includes(S.toLowerCase()))||o(`${f.id}'s mark stands for ${m.join(" or ")}, and none of its words say so`)}const j=Math.max(1,...d.map(f=>f.col)),v=F==="data-flow"?Math.max(1,q.length):Math.max(1,...d.map(f=>f.row2));return{type:F,title:String(t.title??""),heading:c,legend:l,nodes:d,byId:_,edges:w,groups:L,lanes:q,steps:O,cols:j,rows:v,shapeLabels:g,stepWord:u,warnings:a,motion:G,memo:new Map}}function le(t,e){if(typeof t=="string")return t?{id:t}:void 0;if(!t||typeof t!="object")return;const n=t,s=At(at(n.onLight),e);if(s)return{onLight:s,onDark:At(at(n.onDark),e)??s,says:Array.isArray(n.says)?n.says.map(String):void 0}}function At(t,e){if(t){if(/^data:image\//i.test(t.trim()))return t;try{if(/^https?:$/.test(new URL(t,"https://basalt.invalid/").protocol)&&!/^http:/i.test(t.trim()))return t}catch{}e?.(`a card's mark ${JSON.stringify(t.slice(0,60))} is not a relative path, https or a data: image, so it is not drawn`)}}var Lt=t=>`url("${t.replace(/[\\"\n\r\f;]/g,e=>e===` -`?"\\a ":e==="\r"?"\\d ":e==="\f"?"\\c ":e===";"?"\\3b ":`\\${e}`)}")`;function bt(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var qt=28,pt=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""};function It(t,e){return t.legend[e]}function ce(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function de(t,e){return bt(t,`sentence:${e.i}`,()=>ue(t,e))}function ue(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const s=(e.columns??[]).filter(o=>o.ref).map(o=>`${o.ref.table} (${o.name})`),a=t.edges.filter(o=>o.to===e.id).map(o=>`${o.from} (${t.byId.get(o.from).columns[o.fromRow].name})`);s.length&&n.push(`References ${s.join(", ")}.`),a.length&&n.push(`Referenced by ${a.join(", ")}.`)}else if(t.type==="sequence"){const s=t.steps.filter(o=>"n"in o&&o.from===e.id).length,a=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 ${s} ${s===1?"message":"messages"} and receives ${a}.`)}else{const s=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?ce(t,e):e.kind;if(n.push(pt(s?`${e.name}, ${s}`: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 a=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})`:""}`);a.length&&n.push(`From: ${a.join(", ")}.`),o.length&&n.push(`To: ${o.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(pt(t.legend.focal)),n.join(" ")}function fe(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 s=[];for(const a of n.flat(1/0))a!=null&&a!==!1&&!Array.isArray(a)&&s.push(a);return{t,a:e??{},c:s}}var he={"&":"&","<":"<",">":">",'"':""","'":"'"},it=t=>t.replace(/[&<>"']/g,e=>he[e]),pe=" br img input meta link hr path polygon polyline circle rect line ";function Ot(t,e={}){if(typeof t=="string")return it(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[s,a]of Object.entries(t.a))if(!(a==null||a===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(s))throw new Error(`diagram: "${s}" is not an attribute name`);n+=a===!0?` ${s}`:` ${s}="${it(String(a))}"`}return pe.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(s=>Ot(s,e)).join("")}`}var ge=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function ht(t,e){return!e.layout||e.bare?!1:e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema"}function me(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function _t(t){let e=0;for(const n of t.groups){const s=n.members.map(a=>t.byId.get(a).col);s.length&&(Math.min(...s)===1&&(e|=1),Math.max(...s)===t.cols&&(e|=2))}return(e&1)+(e>>1&1)}function vt(t){return t.type==="sequence"?t.nodes.length:t.cols}function Ct(t){return bt(t,"plan",()=>ye(t))}function ye(t){const e=t.nodes,n=i=>t.type==="data-flow"||!e[i].branch,s=t.edges.map(i=>{const d=t.byId.get(i.from).i,w=t.byId.get(i.to).i,L=e.slice(Math.min(d,w)+1,Math.max(d,w)).every(O=>!n(O.i));return w===d+1&&!(n(d)&&!n(w))?"down":w===d-1?"up":w>d&&n(d)&&!n(w)&&L?"trunk":w>d&&n(d)&&n(w)&&L?"rail":w>d?"end-down":"end-up"}),a=t.edges.map((i,d)=>({e:i,k:d})).filter(({k:i})=>s[i]==="end-down"||s[i]==="end-up"),o=i=>{const d=t.byId.get(i.from).i,w=t.byId.get(i.to).i;return[Math.min(d,w),Math.max(d,w)]},r=(i,d)=>{const[w,q]=o(i),[L,O]=o(d);return w{const d=t.byId.get(i.from).i,[w,q]=o(i);return!n(d)&&e.slice(w+1,q).every(L=>!n(L.i))&&a.every(L=>L.e===i||!r(L.e,i))}),h=a.length>0&&(t.type==="data-flow"||!l),u=i=>{const[d,w]=o(i);return w-d},p=t.edges.map(()=>0);let g=!1;const c=[];for(const i of[...a].sort((d,w)=>u(d.e)-u(w.e)||d.k-w.k)){let d=0;for(const w of c)r(w.e,i.e)&&(d=Math.max(d,p[w.k]+1));p[i.k]=d,d>1&&(g=!0),c.push(i)}const y=t.edges.map(()=>.5);for(const i of e){const d=a.filter(({e:L})=>L.from===i.id);if(d.length<2)continue;const w=d.filter(({k:L})=>s[L]==="end-down").sort((L,O)=>u(O.e)-u(L.e)||L.k-O.k);[...d.filter(({k:L})=>s[L]==="end-up").sort((L,O)=>u(L.e)-u(O.e)||O.k-L.k),...w].forEach(({k:L},O,F)=>{y[L]=F.length===2?O===0?1/3:2/3:(O+1)/(F.length+1)})}const b=ut();for(let i=1;i{const E=s[Z],V=t.byId.get(_.from).i,$=t.byId.get(_.to).i,G=$===i&&(E==="down"||E==="trunk"||E==="rail"||E==="end-down"),j=V===i&&$===i-1&&E==="up",v=$===i-1&&E==="end-up";G&&(E==="trunk"||E==="end-down")&&(O=!0),v&&(F=!0),(G||j||v)&&_.label&&(q++,L=Math.max(L,E==="trunk"?40:48))}),(q>1||O&&F)&&(L=64),b[d.id]=L}return{routes:s,gutter:h,lanes:p,exits:y,gaps:b,third:g}}var gt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function Bt(t,e){const n=e==="fk"?"plain":e,s=n==="main"?8:8.5,a=24,o=n==="dashed"?a-1:a-7;return x("svg",{class:`${t}-swatch`,"data-kind":n,...gt(24,16)},e==="fk"?x("circle",{class:`${t}-dot`,cx:3,cy:s,r:3}):null,x("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${s}H${o}`}),n==="dashed"?x("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${a-8} ${s-4}L${a} ${s}L${a-8} ${s+4}`}):x("path",{class:`${t}-tip`,"data-kind":n,d:`M${a} ${s}L${a-8} ${s-4}L${a-8} ${s+4}Z`}))}function mt(t,e){return e==="decision"?x("svg",{class:`${t}-swatch`,"data-shape":e,...gt(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,...gt(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,...gt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function be(t,e){return bt(e,`key:${t}`,()=>$e(t,e))}function $e(t,e){const n=[],s=(o,r,l={})=>n.push(x("li",{class:`${t}-entry`,...l},o,x("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(x("li",{class:`${t}-entry`},x("span",{class:`${t}-key-letters`,"aria-hidden":"true"},r),x("span",null,l)))}if(e.type==="flowchart"){const o=new Set(e.nodes.map(r=>r.shape));o.has("terminal")&&s(mt(t,"terminal"),e.shapeLabels.terminal),o.has("box")&&s(mt(t,"box"),e.shapeLabels.step),o.has("decision")&&s(mt(t,"decision"),e.shapeLabels.decision)}const a=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];a.has(o)&&r&&s(Bt(t,o),r,{"data-line":""})}return e.type==="schema"&&e.edges.length&&(s(Bt(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,"The table a foreign key references")))),e.nodes.some(o=>o.focal)&&e.legend.focal&&s(mt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&s(mt(t,"group"),e.legend.group),n.length?x("div",{class:`${t}-key`},x("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function we(t,e){const n=e==="main"?6:6.5;return x("svg",{class:`${t}-arrow`,"data-kind":e,...gt(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 xe(t,e,n){if(n.shape==="decision")return[x("span",{class:`${t}-words`},x("span",{class:`${t}-name`},n.name))];const s=[];return e.type==="data-flow"?s.push(x("span",{class:`${t}-kind`},n.kind,x("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&s.push(x("span",{class:`${t}-kind`},n.kind)),s.push(x("span",{class:`${t}-name`},n.name)),n.detail&&s.push(x("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.mono?wt(n.detail).flatMap((a,o)=>[o?" ":"",x("span",{class:`${t}-run`},a)]):n.detail)),s}function ve(t,e){return[x("span",{class:`${t}-th`},x("span",{class:`${t}-tname`},e.name)),x("span",{class:`${t}-rows`},(e.columns??[]).map((n,s)=>x("span",{class:`${t}-row`,"data-row":s,"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 jt=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 Mt(t,e,n,s){const{P:a}=t,o=me(e,s)||s.keep===n.id,r=ht(e,s),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 h=t.plan;if(h&&n.i>0){const c=ft(h.gaps,n.id)??32,y=ft(s.grow,n.id)??0;l.push(`--_gap:${y?`calc(${jt(c)} + var(--basalt-space-4) * ${y})`:jt(c)}`)}const u=ft(s.heights,n.id);u&&l.push(`--_h:${u}px`);const p=ft(s.words,n.id);p&&l.push(`--_ww:${p}px`);const g=r?s.stop===n.id?0:-1:s.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-mark":n.mark?n.mark.id??"":void 0,"data-level":t.level,style:l.join(";"),role:o?"img":void 0,"aria-label":o?de(e,n):void 0,tabindex:g},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.mark?x("span",{class:`${a}-mark`,"aria-hidden":"true",style:n.mark.onLight?`--_ml:${Lt(n.mark.onLight)};--_md:${Lt(n.mark.onDark??n.mark.onLight)}`:void 0}):null,n.shape==="table"?ve(a,n):xe(a,e,n))}function Me(t,e,n){const{P:s}=t,a=[];if(e.type==="data-flow"&&a.push(...e.lanes.map((r,l)=>x("div",{class:`${s}-lane`,style:`--_r:${l+1}`,"aria-hidden":"true"},x("span",{class:`${s}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const l=r.members.map(c=>e.byId.get(c));if(!l.length)continue;const h=Math.min(...l.map(c=>c.col)),u=Math.max(...l.map(c=>c.col)),p=Math.min(...l.map(c=>c.row)),g=Math.max(...l.map(c=>c.row2));a.push(x("div",{class:`${s}-gbox`,"data-group":r.id,style:`--_c:${h};--_c2:${u+1};--_r:${p};--_r2:${g+1}`,"aria-hidden":"true"},x("span",{class:`${s}-glabel`},r.label)))}if(e.type==="sequence")return a.push(x("ul",{class:`${s}-cast`},e.nodes.map(r=>x("li",{class:`${s}-actor`},Mt(t,e,r,n))))),a.push(ke(t,e)),a;let o=0;for(;op.id===r.group):void 0;if(!l){a.push(Mt(t,e,r,n)),o++;continue}const h=[];for(;oMt(t,e,p,n))))}return a}function ke(t,e){const{P:n}=t,s=[];let a=null;for(const o of e.steps){if("band"in o){a=null,s.push(x("p",{class:`${n}-band`},x("span",null,o.band)));continue}a||(a=x("ol",{class:`${n}-msgs`,start:o.n}),s.push(a));const r=e.byId.get(o.from),l=e.byId.get(o.to),h=r?.col??1,u=l?.col??1,p=h===u,g=p&&h===e.nodes.length,c=It(e,o.kind);a.c.push(x("li",{class:`${n}-msg`,"data-kind":o.kind,"data-from":o.from,"data-to":o.to,"data-self":p?g?"start":"end":void 0,style:`--_a:${Math.min(h,u)};--_b:${Math.max(h,u)+1}`},x("span",{class:`${n}-said`},x("span",{class:`${n}-num`},String(o.n)),x("span",{class:`${n}-mlabel`},o.label)),x("span",{class:`${n}-route`},r?.short??o.from," ",we(n,o.kind),x("span",{class:t.hidden}," to ")," ",l?.short??o.to,c?` · ${c}`:""),o.note?x("span",{class:`${n}-note`},o.note):null))}return x("div",{class:`${n}-steps`},s)}function Se(t,e){return bt(e,`list:${t}`,()=>Ee(t,e))}function Ee(t,e){const n=Math.min(6,e.heading+1),s=p=>x(`h${n}`,{class:`${t}-list-head`},p),a=p=>x("strong",null,p),o=p=>x("code",{class:`${t}-code`},p),r=p=>e.byId.get(p)?.name??p,l=p=>{const g=It(e,p);return g?` (${g})`:""},h=p=>p.focal&&e.legend.focal?` ${pt(e.legend.focal)}`:"";if(e.type==="architecture"){const p=y=>x("li",null,a(y.name),y.kind?`, ${y.kind}`:"",y.detail?[". ",y.mono?o(y.detail):y.detail,/[.!?]$/.test(y.detail)?"":"."]:/[.!?]$/.test(y.kind??y.name)?"":".",h(y)),g=[s("Parts")],c=e.nodes.filter(y=>!y.group);c.length&&g.push(x("ul",{class:`${t}-list-items`},c.map(p)));for(const y of e.groups)g.push(x("p",{class:`${t}-list-group`},y.label)),g.push(x("ul",{class:`${t}-list-items`},y.members.map(b=>p(e.byId.get(b)))));return g.push(s("Connections")),g.push(x("ol",{class:`${t}-list-items`},e.edges.map(y=>x("li",null,a(r(y.from))," to ",a(r(y.to)),y.label?[": ",o(y.label)]:"",`${l(y.kind)}.`)))),g}if(e.type==="flowchart"){const p=g=>(e.byId.get(g)?.i??0)+1;return[x("ol",{class:`${t}-list-items`},e.nodes.map(g=>{const c=e.edges.filter(i=>i.from===g.id),y=g.shape==="decision"?"Decision":g.shape==="terminal"?c.length?"Start":"End":"Step",b=!g.detail&&/[.!?]$/.test(g.name)?" ":". ";return x("li",null,a(g.name),g.detail?[", ",g.mono?o(g.detail):g.detail]:"",`${b}${y}.`,h(g),c.length?x("ul",{class:`${t}-list-exits`},c.map(i=>x("li",null,i.label?`If ${i.label}: go to ${p(i.to)}, `:`Then: go to ${p(i.to)}, `,a(r(i.to)),l(i.kind)))):null)}))]}if(e.type==="data-flow")return[x("ol",{class:`${t}-list-items`},e.nodes.map(p=>{const g=e.edges.filter(c=>c.from===p.id);return x("li",null,`${p.laneLabel}: `,a(p.name),p.detail?[", ",p.mono?o(p.detail):p.detail]:"",".",h(p),g.length?[" Then ",...g.flatMap((c,y)=>[y?"; ":"",`to step ${e.byId.get(c.to).step}, `,a(r(c.to)),c.label?[": ",o(c.label)]:"",l(c.kind)]),"."]:"")}))];if(e.type==="sequence"){const p=[s("Participants"),x("ul",{class:`${t}-list-items`},e.nodes.map(c=>x("li",null,a(c.name),c.kind?`, ${c.kind}`:"",".",h(c))))];p.push(s("Messages"));let g=null;for(const c of e.steps){if("band"in c){g=null,p.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`},c.band));continue}g||(g=x("ol",{class:`${t}-list-items`,start:c.n}),p.push(g)),g.c.push(x("li",null,o(c.label),": ",a(r(c.from))," to ",a(r(c.to)),`${l(c.kind)}.`,c.note?` ${pt(c.note)}`:""))}return p}const u=[];for(const p of e.nodes)u.push(x(`h${n}`,{class:`${t}-list-group`},o(p.name),h(p))),u.push(x("ul",{class:`${t}-list-items`},[...(p.columns??[]).map(g=>x("li",null,o(g.name),g.key==="PK"?", primary key":g.key==="FK"?", foreign key":"",g.ref?[", references ",o(`${g.ref.table}.${g.ref.column}`)]:g.type?`, ${g.type}`:"")),...p.more?[x("li",null,`and ${p.more} more ${p.more===1?"column":"columns"}`)]:[]]));return u}function Ae(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 Le(t){return[{keys:["←","→"],words:fe(t)},{keys:["Home","End"],words:"the ends"},{keys:["Esc"],words:"clear"}]}var Tt=t=>t.type==="schema"&&t.cols===1&&t.edges.length>0;function Rt(t,e,n){const s=n.prefix,a=ge(n.base),o=t.type==="sequence"||t.type==="schema"?null:Ct(t),r={P:s,ids:a,level:n.level,plan:o,hidden:n.hiddenClass},l=e.layout==="drawn",h=ht(t,e),u=t.type==="sequence"||t.type==="schema"?l:!0,p=`h${t.heading}`,g=[`--_cols:${vt(t)}`];if(t.type==="architecture"&&t.groups.length||l&&e.pad){const c=t.type==="architecture"?t.groups.flatMap(i=>i.members.map(d=>t.byId.get(d))):[],y=(i,d,w)=>i?`var(--basalt-space-${d})`:w?`var(--basalt-space-${w})`:"0px",b=l&&e.pad?"3":void 0;g.push(`--_gpad:${y(c.some(i=>i.row===1),"8",b)} ${y(c.some(i=>i.col===t.cols),"4")} ${y(c.some(i=>i.row2===t.rows),"4",b)} ${y(c.some(i=>i.col===1),"4")}`)}return Tt(t)&&g.push("--_gpad:0px var(--basalt-space-5) 0px 0px"),t.type==="schema"&&e.track&&g.push(`--_track:${e.track}px`),x("figure",{class:n.className?`${s} ${n.className}`:s,"aria-labelledby":a.title,"data-type":t.type,"data-cols":vt(t),"data-reach":t.type==="architecture"?_t(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,"data-motion":t.motion.animated?"animated":void 0,style:g.join(";")},x("div",{class:`${s}-head`},x(p,{id:a.title,class:`${s}-title`},t.title),n.hasSource?x("p",{class:`${s}-source`},{slot:"source"}):null),x("div",{class:`${s}-drawing`,role:u?"group":void 0,"aria-roledescription":u?"diagram":void 0,"aria-labelledby":u?a.title:void 0,"aria-describedby":u?h?`${a.summary} ${a.keys}`:a.summary:void 0,"data-stops":h?"":void 0},Me(r,t,e),x("div",{class:`${s}-ink`,"aria-hidden":"true"}),x("span",{class:`${s}-ruler`,"aria-hidden":"true"})),be(s,t),x("p",{class:`${s}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),x("div",{class:`${s}-foot`},{slot:"toggle"}),x("div",{id:a.list,class:`${s}-list`,hidden:!e.open},Se(s,t)),x("span",{id:a.keys,class:n.hiddenClass},Ae(t)),x("figcaption",{id:a.summary,class:`${s}-summary`},{slot:"summary"}))}function qe(t){const e=getComputedStyle(t),n=(a,o)=>{const r=parseFloat(e.getPropertyValue(`--basalt-${a}`));return Number.isFinite(r)?r:o},s=new Map;return{space:a=>(s.has(a)||s.set(a,n(`space-${a}`,parseFloat(a.replace("-","."))*4)),s.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 $t=(t,e)=>t==="main"?e.line:e.hair,lt=(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}},ct=(t,e,n=.01)=>t.le.l+n&&t.te.t+n,Ft=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function rt(t,e,n){const{l:s,t:a,r:o,b:r}=t.rect,l=(s+o)/2,h=(a+r)/2,u=(o-s)/2,p=(r-a)/2,g=e==="top"||e==="bottom";if(t.shape==="decision"){if(g){const b=n,i=p*Math.max(0,1-Math.abs(b-l)/u);return{x:b,y:e==="top"?h-i:h+i}}const c=n,y=u*Math.max(0,1-Math.abs(c-h)/p);return{x:e==="left"?l-y:l+y,y:c}}if(t.shape==="terminal"){const c=Math.min(u,p);if(g){const d=n,w=Math.min(Math.max(d,s+c),o-c),q=d-w,L=Math.abs(q)>=c?0:Math.sqrt(c*c-q*q);return{x:d,y:Math.abs(q)<1e-6?e==="top"?a:r:e==="top"?h-L:h+L}}const y=n,b=y-h,i=Math.abs(b)>=c?0:Math.sqrt(c*c-b*b);return{x:e==="left"?s+c-i:o-c+i,y}}return g?{x:n,y:e==="top"?a:r}:{x:e==="left"?s:o,y:n}}function Ie(t,e,n){const{l:s,t:a,r:o,b:r}=e.rect,l=(s+o)/2,h=(a+r)/2,u=(o-s)/2,p=(r-a)/2;if(e.shape==="decision")return Math.abs(t.x-l)/u+Math.abs(t.y-h)/p<1-n/Math.min(u,p);if(e.shape==="terminal"){const g=Math.min(u,p),c=Math.min(Math.max(t.x,s+g),o-g);return Math.hypot(t.x-c,t.y-h)s+n&&t.xa+n&&t.ymatchMedia("(forced-colors: active)").matches;function Ce(t,e){const n=t.querySelector(`.${e}-ruler`),s=new Map;return(a,o)=>{const r=`${o}|${a}`;return s.has(r)||(n.setAttribute("data-f",o),n.textContent=a,s.set(r,n.getBoundingClientRect().width),n.textContent=""),s.get(r)}}var wt=t=>t?t.split(/\s+/).filter(Boolean):[];function Be(t,e,n){const s=e.space;let a=e.node,o=e.table;for(const h of t.nodes){if(h.shape==="table"){for(const y of h.columns??[]){const b=y.ref?`→ ${y.ref.table}`:y.type??"",i=s("6")+n(y.name,"mono")+(b?s("3")+n(b,"mono"):0)+2*s("3")+2*e.hair;o=Math.max(o,Math.ceil(i))}o=Math.max(o,Math.ceil(n(h.name,"table")+2*s("3")+2*e.hair));continue}const u=h.shape==="terminal"?2*s("5"):2*s("3"),p=h.mark&&!_e()?s("6"):0;let g=0;for(const y of wt(h.name))g=Math.max(g,n(y,h.shape==="decision"?"name-500":"name")+(h.kind?0:p));if(t.type!=="data-flow")for(const y of wt(h.kind))g=Math.max(g,n(y,"mono")+p);for(const y of wt(h.detail))g=Math.max(g,n(y,h.mono?"mono":"sans"));const c=h.shape==="decision"?g/.62:g+u+2*e.hair;a=Math.max(a,Math.ceil(c))}const r=vt(t);let l;return t.type==="data-flow"?l=e.lane+r*(a+s("12")):t.type==="schema"?l=r*o+(r-1)*s("12")+(Tt(t)?s("5"):0):t.type==="sequence"?l=r*a+(r-1)*s("5"):l=r*a+(r-1)*s("16")+_t(t)*s("4"),{track:a,table:o,least:Math.max(e.wide,l)}}function Nt(t,e){return{x:(n,s)=>s%2===1?Math.round(n+t-.5)+.5-t:Math.round(n+t)-t,y:(n,s)=>s%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 zt(t,e,n){const s=t.map(o=>({...o}));for(let o=1;o=2){const h=a[a.length-2];if(Math.abs(h.x-l.x)<.01&&Math.abs(l.x-r.x)<.01||Math.abs(h.y-l.y)<.01&&Math.abs(l.y-r.y)<.01){a[a.length-1]=r;continue}}a.push(r)}}return a}var dt=t=>t.slice(1).map((e,n)=>[t[n],e]);function xt(t,e,n){const s=[];for(let o=0;oMath.min(i.x,d.x)+.75&&LMath.min(w.y,q.y)+.75&&Oa.split(/\s+/).map(parseFloat).filter(o=>Number.isFinite(o)),s=(a,o,r)=>{const l=[];let h=o;for(const u of a)l.push([h,h+u]),h+=u+r;return l};return{cols:s(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:s(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0)}}var P=t=>t==="left"||t==="right",Wt={top:"bottom",bottom:"top",left:"right",right:"left"};function Te(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 Re(t,e,n){const s=[];t.edges.forEach((o,r)=>{const l=t.byId.get(o.from),h=t.byId.get(o.to),[u,p]=e[r],g=l.row===h.row&&P(u)&&P(p)&&u===Wt[p]||l.col===h.col&&!P(u)&&!P(p)&&u===Wt[p];s.push({edge:r,end:"from",node:l,side:u,far:h,straight:g,f:.5},{edge:r,end:"to",node:h,side:p,far:l,straight:g,f:.5})});const a=new Map;for(const o of s){const r=`${o.node.id}.${o.side}`;a.has(r)||a.set(r,[]),a.get(r).push(o)}for(const[o,r]of a){if(r[0].node.shape==="decision")continue;const l=i=>P(i.side)?i.far.row-i.node.row:i.far.col-i.node.col,h=r.filter(i=>i.straight),u=r.filter(i=>!i.straight);if(u.sort((i,d)=>l(i)-l(d)||(P(i.side)?i.far.col-d.far.col:i.far.row-d.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`),!h.length){u.length===2?(u[0].f=.25,u[1].f=.75):u.length===3?(u[0].f=.25,u[1].f=.5,u[2].f=.75):u.length>3&&u.forEach((i,d)=>{i.f=(d+1)/(u.length+1)});continue}const p=new Map;for(const i of h)p.has(i.far.id)||p.set(i.far.id,[]),p.get(i.far.id).push(i);for(const i of p.values())i.length>1&&i.sort((d,w)=>d.edge-w.edge).forEach((d,w)=>{d.f=i.length===2?w===0?.25:.75:(w+1)/(i.length+1)});const g=Math.min(...h.map(i=>i.f)),c=Math.max(...h.map(i=>i.f)),y=u.filter(i=>l(i)<0),b=u.filter(i=>l(i)>=0);y.forEach((i,d)=>{i.f=g*(d+1)/(y.length+1)}),b.forEach((i,d)=>{i.f=c+(1-c)*(d+1)/(b.length+1)})}return s}function Dt(t,e,n){const{l:s,t:a,r:o,b:r}=t.rect;return P(e)?rt(t,e,a+(r-a)*n):rt(t,e,s+(o-s)*n)}function Gt(t,e,n,s){const a=new Map;return e.querySelectorAll(`.${s}-node`).forEach(o=>{const r=t.byId.get(o.dataset.node);r&&a.set(r.id,{id:r.id,rect:lt(o,n),shape:r.shape,i:r.i})}),a}function Kt(t,e){const n=e.head,s=e.head/2,{x:a,y:o}=t.tip;return t.dir==="down"?{l:a-s,r:a+s,t:o-n,b:o}:t.dir==="up"?{l:a-s,r:a+s,t:o,b:o+n}:t.dir==="right"?{l:a-n,r:a,t:o-s,b:o+s}:{l:a,r:a+n,t:o-s,b:o+s}}var Vt=(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 Ut(t,e,n,s){const a=(o,r)=>{const l=o+r-Math.floor(o+r);return l<.005||l>.995?[0]:l<=.5?[-l,1-l]:[1-l,-l]};for(const o of a(t.t,n))for(const r of a(t.l,e)){if(!r&&!o)return t;const l={l:t.l+r,r:t.r+r,t:t.t+o,b:t.b+o};if(s(l))return l}return t}function Fe(t,e,n,s,a,o,r,l,h){const u=r.space,p=[],g=[],c=[],y=[],b=u("1"),i=e.filter(d=>t.edges[d.i]?.label).sort((d,w)=>+(t.edges[w.i].kind==="main")-+(t.edges[d.i].kind==="main")||d.i-w.i);for(const d of i){const w=t.edges[d.i].label,q=l(w,"label"),L=16,O=d.pts.length-2,F=[];dt(d.pts).forEach(([$,G],j)=>{const v=Math.abs($.y-G.y)<.01,f=v?$.x:$.y;let m=v?G.x:G.y;const A=Math.sign(m-f)||1;j===O&&(m-=A*r.head);let S=[[f,m]];for(const K of a)for(const W of v?[K.l,K.r]:[K.t,K.b]){const M=v?$.y:$.x;(v?M>K.t&&MK.l&&MW>Math.min(I,k)+1&&W{const M=(K+W)/2,T=v?{x:M,y:$.y}:{x:$.x,y:M};return!a.some(I=>T.x>I.l&&T.xI.t&&T.y1&&z(K,W)?1:0})}),F.sort(($,G)=>G.pri-$.pri||G.len-$.len);let _=null,Z=!1;const E=($,G=!0)=>{const j=Ft($,b);return G&&($.lo.r||$.to.b)||n.some(v=>Ht(j,v))||p.some(v=>ct(j,v))||s.heads.some(v=>ct(j,v))||s.rects.some(v=>ct(j,v))?!1:!e.some(v=>v.i!==d.i&&dt(v.pts).some(([f,m])=>ct(j,Vt(f,m,v.width))))};for(const $ of F){for(const G of[1/2,1/3,2/3]){const j=$.p+($.q-$.p)*G,v=[],f=u("2")+d.width/2;if($.horiz?($.len>=q+2*u("1")+u("3-5")&&v.push({box:{l:j-q/2-u("1"),r:j+q/2+u("1"),t:$.c-L/2,b:$.c+L/2},on:!0}),v.push({box:{l:j-q/2,r:j+q/2,t:$.c-f-L,b:$.c-f},on:!1}),v.push({box:{l:j-q/2,r:j+q/2,t:$.c+f,b:$.c+f+L},on:!1})):($.len>=L+u("3")&&v.push({box:{l:$.c-q/2-u("1"),r:$.c+q/2+u("1"),t:j-L/2,b:j+L/2},on:!0}),v.push({box:{l:$.c+f,r:$.c+f+q,t:j-L/2,b:j+L/2},on:!1}),v.push({box:{l:$.c-f-q,r:$.c-f,t:j-L/2,b:j+L/2},on:!1})),_=v.find(m=>E(m.box))??null,_)break;!Z&&v.some(m=>E(m.box,!1))&&(Z=!0)}if(_)break}if(!_){c.push(d.i),Z&&y.push(d.i);continue}const V=Ut(_.box,h.ox,h.oy,$=>E($));p.push(V),g.push({i:d.i,text:w,box:V,on:_.on})}return{labels:g,unseated:c,bounded:y}}function Zt(t,e,n,s){const a=[],o=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(r=>{if(r.getClientRects().length===0||getComputedStyle(r).display==="contents")return;const l=lt(r,e);o.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 h=r.querySelector(`:scope > .${n}-glabel`);h&&h.getClientRects().length&&a.push(lt(h,e))}),t.querySelectorAll(`.${n}-lane`).forEach((r,l)=>{if(!r.getClientRects().length)return;const h=lt(r,e);l>0&&a.push({l:h.l,r:h.r,t:h.t-s/2-.5,b:h.t-s/2+.5});const u=r.querySelector(`.${n}-lane-name`);u&&a.push(lt(u,e))}),{obstacles:{rects:a,heads:[]},groups:o}}function He(t,e){const{m:s,tk:a,P:o,drawing:r,origin:l,warn:h}=t,u=a.space,p=Gt(s,r,l,o),g=[...p.values()],c=je(r),y=l.left-Math.floor(l.left),b=l.top-Math.floor(l.top),i=Nt(y,b),d=r.clientWidth,w=r.clientHeight,q=M=>s.type==="data-flow"?M.col+1:M.col,L=parseFloat(getComputedStyle(r).rowGap)||0,O={w:d,h:w,nodes:g,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:y,oy:b};if(s.type==="sequence")return ze(t,O,i);let F,_=[];s.type==="schema"?F=s.edges.map(M=>{const T=s.byId.get(M.from),I=s.byId.get(M.to);if(T.col===I.col){const k=T.col===s.cols&&s.cols>1?"left":"right";return[k,k]}return I.col>T.col?["right","left"]:["left","right"]}):(F=s.edges.map(M=>{const T=s.byId.get(M.from),I=s.byId.get(M.to),[k,B]=Te(T,I);return[M.fromSide??k,M.toSide??B]}),_=Re(s,F,h||(()=>{})));const Z=(M,T)=>{const I=r.querySelector(`.${o}-node[data-node="${CSS.escape(M)}"] .${o}-row[data-row="${T}"]`);if(!I)return 0;const k=lt(I,l);return(k.t+k.b)/2},E=s.edges.map((M,T)=>{const[I,k]=F[T],B=p.get(M.from),H=p.get(M.to),U=$t(M.kind,a);if(M.fk){const J=Z(M.from,M.fromRow),nt=Z(M.to,M.toRow),Y=i.y(J,U),R=i.y(nt,U);return{p1:{x:I==="right"?B.rect.r:B.rect.l,y:Y},p2:{x:k==="right"?H.rect.r:H.rect.l,y:R},r1:J,r2:Math.abs(Y-R)<.01?J:nt}}const tt=_.find(J=>J.edge===T&&J.end==="from").f,Q=_.find(J=>J.edge===T&&J.end==="to").f;let N=Dt(B,I,tt),D=Dt(H,k,Q);const et=P(I)?N.y:N.x;let ot=P(k)?D.y:D.x;return P(I)?N={...N,y:i.y(N.y,U)}:N={...N,x:i.x(N.x,U)},P(k)?D={...D,y:i.y(D.y,U)}:D={...D,x:i.x(D.x,U)},P(I)&&P(k)&&Math.abs(N.y-D.y)<1.01&&(D={...D,y:N.y},ot=et),!P(I)&&!P(k)&&Math.abs(N.x-D.x)<1.01&&(D={...D,x:N.x},ot=et),N=P(I)?rt(B,I,N.y):rt(B,I,N.x),D=P(k)?rt(H,k,D.y):rt(H,k,D.x),{p1:N,p2:D,r1:et,r2:ot}}),V=new Set;s.type==="schema"&&s.edges.forEach((M,T)=>{Math.abs(s.byId.get(M.from).col-s.byId.get(M.to).col)>1&&V.add(T)});const $=new Map,G=new Set;s.edges.forEach((M,T)=>{if(V.has(T))return;const[I,k]=F[T],{p1:B,p2:H}=E[T],U=s.byId.get(M.from),tt=s.byId.get(M.to);let Q=null,N=null,D=!1;if(I===k){if(P(I)){const J=I==="right"?Math.max(q(U),q(tt)):Math.min(q(U),q(tt))-1,nt=c.cols[J-1],Y=c.cols[J];nt&&Y&&(Q=`c${J}`,N=[nt[1],Y[0]],D=!0)}else{const J=I==="bottom"?Math.max(U.row2,tt.row2):Math.min(U.row,tt.row)-1,nt=c.rows[J-1],Y=c.rows[J];nt&&Y&&(Q=`r${J}`,N=[nt[1],Y[0]],D=!1)}Q&&G.add(T)}else if(P(I)&&P(k)&&Math.abs(B.y-H.y)>.5){const J=q(tt),nt=k==="left",Y=c.cols[(nt?J-1:J)-1],R=c.cols[(nt?J:J+1)-1];Y&&R&&(Q=`c${nt?J-1:J}`,N=[Y[1],R[0]],D=!0)}else if(!P(I)&&!P(k)&&Math.abs(B.x-H.x)>.5){const nt=k==="top"?tt.row-1:tt.row2,Y=c.rows[nt-1],R=c.rows[nt];Y&&R&&(Q=`r${nt}`,N=[Y[1],R[0]],D=!1)}if(!Q||!N)return;$.has(Q)||$.set(Q,{span:N,vertical:D,members:new Map});const et=`${M.to}.${k}.${Math.round(D?H.y:H.x)}`,ot=$.get(Q);ot.members.has(et)||ot.members.set(et,[]),ot.members.get(et).push(T)});const j=new Map,v=M=>{const[T,I]=F[M],{p1:k,p2:B}=E[M];if(P(T)&&P(I)){if(T===I){const U=j.get(M)??(T==="right"?Math.max(k.x,B.x)+u("4"):Math.min(k.x,B.x)-u("4"));return[k,{x:U,y:k.y},{x:U,y:B.y},B]}if(Math.abs(k.y-B.y)<=.5)return[k,{x:B.x,y:k.y}];const H=j.get(M)??(k.x+B.x)/2;return[k,{x:H,y:k.y},{x:H,y:B.y},B]}if(!P(T)&&!P(I)){if(T===I){const U=j.get(M)??(T==="bottom"?Math.max(k.y,B.y)+u("4"):Math.min(k.y,B.y)-u("4"));return[k,{x:k.x,y:U},{x:B.x,y:U},B]}if(Math.abs(k.x-B.x)<=.5)return[k,{x:k.x,y:B.y}];const H=j.get(M)??(k.y+B.y)/2;return[k,{x:k.x,y:H},{x:B.x,y:H},B]}return P(T)?[k,{x:B.x,y:k.y},B]:[k,{x:k.x,y:B.y},B]},f=M=>{const T=s.edges[M],I=$t(T.kind,a),k=v(M),B=zt(k,I,i);let H;return k.length===B.length&&(H=dt(k).map(([U,tt])=>Math.abs(U.y-tt.y)<.75?(U.y+tt.y)/2:(U.x+tt.x)/2),H[0]=E[M].r1,H.length>1&&(H[H.length-1]=E[M].r2)),{i:M,from:T.from,to:T.to,kind:T.kind,pts:B,tip:B[B.length-1],dir:kt(B),dot:T.fk?B[0]:void 0,width:I,axes:H}},m=()=>s.edges.flatMap((M,T)=>V.has(T)?[]:[f(T)]);let A=null;const S=M=>{A??(A=m());const T=A.map(I=>M.has(I.i)?f(I.i):I);return{lines:T,score:Ne(T,M)*1e5+xt(T,void 0,M).length*1e3+St(T.filter(I=>M.has(I.i)),g,s).length}},z=(M,T)=>{const I=M.flatMap(k=>{const{p1:B,p2:H}=E[k];return T?[B.y,H.y]:[B.x,H.x]});return[Math.min(...I),Math.max(...I)]};for(const[,M]of $){const T=[...M.members.values()].map(k=>({members:k,run:z(k,M.vertical)})).sort((k,B)=>k.run[0]-B.run[0]),I=[];for(const k of T){const B=I[I.length-1];B&&B.some(H=>H.run[0]G.has(et)))continue;const B=k.map(et=>et.members),H=B.length,U=(M.span[1]-M.span[0])/(H+1);UJ.forEach(Y=>j.set(Y,M.span[0]+U*(nt+1))));const ot=S(tt);ot.scoreet.forEach(J=>j.set(J,M.span[0]+U*(ot+1)))),A=D}}O.lines=m();for(const M of V)h?.(`${s.edges[M].from} to ${s.edges[M].to} is two columns apart, so its line is not drawn; its row still writes the target`);O.crossings=xt(O.lines),O.through=St(O.lines,g,s),O.outside=Yt(O.lines,d,w,a);const{obstacles:C,groups:K}=Zt(r,l,o,L);C.heads=O.lines.map(M=>Kt(M,a));const W=Fe(s,O.lines,g,C,K,{l:0,t:0,r:d,b:w},a,e,{ox:y,oy:b});return O.labels=W.labels,O.unseated=W.unseated,O.bounded=W.bounded,O.overlaps=[...new Set(Jt(O.lines,null).flat())],O}function Ne(t,e){return Jt(t,e).length}function Jt(t,e){const n=[];for(let s=0;s=l)continue;const[d,w]=c?[h.x,u.x]:[h.y,u.y],[q,L]=c?[p.x,g.x]:[p.y,g.y];Math.min(Math.max(d,w),Math.max(q,L))-Math.max(Math.min(d,w),Math.min(q,L))>1&&n.push([o.i,r.i])}}return n}function*Xt(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e{const h=l===o.pts.length-1?Math.max(o.width/2,s.head/2):o.width/2;return r.x-h<-.5||r.x+h>e+.5||r.y-h<-.5||r.y+h>n+.5})&&a.push(o.i);return a}function St(t,e,n){const s=[];for(const a of t){const o=dt(a.pts);e.some(r=>o.some(([l,h])=>Oe(l,h,r)))&&s.push(a.i)}return s}function ze(t,e,n){const{m:s,tk:a,P:o,drawing:r,origin:l}=t,h=a.space,u=new Map;r.querySelectorAll(`.${o}-node`).forEach(b=>u.set(b.dataset.node,lt(b,l)));const p=r.querySelector(`.${o}-steps`),g=p?lt(p,l).b:e.h,c=b=>{const i=u.get(b);return i?n.x((i.l+i.r)/2,a.hair):0};for(const b of s.nodes){const i=u.get(b.id);i&&e.lifelines.push({x:c(b.id),y1:i.b,y2:g})}const y=b=>u.get(b.id);return r.querySelectorAll(`.${o}-msg`).forEach(b=>{const i=b.dataset.from,d=b.dataset.to,w=b.dataset.kind??"plain",q=$t(w,a),L=lt(b,l),O=n.y((L.t+L.b)/2,q),F=Number(b.querySelector(`.${o}-num`)?.textContent??0),_=c(i),Z=c(d);let E;if(i===d){const m=b.dataset.self==="start"?-h("6"):h("6"),A=n.y(O-h("2"),q),S=n.y(O+h("2"),q);E=[{x:_,y:A},{x:n.x(_+m,q),y:A},{x:n.x(_+m,q),y:S},{x:_,y:S}]}else E=[{x:_,y:O},{x:Z,y:O}];e.lines.push({i:F,from:i,to:d,kind:w,pts:E,tip:E[E.length-1],dir:kt(E),width:q});const V=b.querySelector(`.${o}-said`),$=b.querySelector(`.${o}-note`),G=s.byId.get(i),j=s.byId.get(d);if(!G||!j)return;const v=i===d?(()=>{const m=s.nodes[G.i+(b.dataset.self==="start"?-1:1)],A=m?c(m.id):b.dataset.self==="start"?0:e.w;return Math.abs(A-_)-h("6")-h("2-5")-h("2")})():Math.abs(Z-_)-2*h("2");Math.max(V?V.getBoundingClientRect().width:0,$?$.getBoundingClientRect().width:0)>v+.5&&e.unseated.push(F)}),e}function Qt(t,e,n,s=ut()){const{m:a,tk:o,P:r,drawing:l,origin:h}=t,u=o.space,p=Gt(a,l,h,r),g=[...p.values()],c=h.left-Math.floor(h.left),y=h.top-Math.floor(h.top),b=Nt(c,y),i=l.clientWidth,d=l.clientHeight,w={w:i,h:d,nodes:g,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:c,oy:y},q=ut();if(a.type==="sequence"||a.type==="schema")return{geo:w,grow:q};const L=i-(parseFloat(getComputedStyle(l).paddingRight)||0),O=(v,f,m)=>{const A=[v];for(let S=1;S<=(ft(s,f)??0);S++)A.push({...v,t:v.t+m*u("4")*S,b:v.b+m*u("4")*S});return A},F=new Map;l.querySelectorAll(`.${r}-node`).forEach(v=>{const f=v.parentElement,m=lt(f,h),A=getComputedStyle(f);F.set(v.dataset.node,m.r-(parseFloat(A.paddingRight)||0)-(parseFloat(A.borderRightWidth)||0))});const _=a.nodes,Z=v=>p.get(_[v].id),E=[],V=v=>$t(a.edges[v].kind,o);a.edges.forEach((v,f)=>{const m=n.routes[f],A=p.get(v.from),S=p.get(v.to),z=V(f);let C=[];const K=v.label,W=K?e(K,"label"):0,M=16,T=u("4");if(m==="down"||m==="up"){const k=Math.max(A.rect.l,S.rect.l),B=Math.min(A.rect.r,S.rect.r),H=a.edges.map((N,D)=>({o:N,j:D})).filter(({o:N,j:D})=>(n.routes[D]==="down"||n.routes[D]==="up")&&(N.from===v.from&&N.to===v.to||N.from===v.to&&N.to===v.from)),U=H.findIndex(N=>N.j===f),tt=H.length<2?.5:H.length===2?U===0?.25:.75:(U+1)/(H.length+1),Q=b.x(k+(B-k)*tt,z);if(C=m==="down"?[rt(A,"bottom",Q),rt(S,"top",Q)]:[rt(A,"top",Q),rt(S,"bottom",Q)],K){let N=Math.min(C[0].y,C[1].y),D=Math.max(C[0].y,C[1].y);m==="down"?D-=o.head:N+=o.head;const et=[...l.querySelectorAll(`.${r}-group`)].map(Y=>lt(Y,h));let ot=[[N,D]];for(const Y of et)for(const R of[Y.t,Y.b])ot=ot.flatMap(([X,st])=>R>X+1&&Ret.some(X=>(Y+R)/2>X.t&&(Y+R)/2X.l&&Q1){const Y=ot.filter(([X,st])=>!J(X,st));[N,D]=(Y.length?Y:ot).reduce((X,st)=>st[1]-st[0]>X[1]-X[0]?st:X)}const nt=[1/2,1/3,2/3].map(Y=>{const R=N+(D-N)*Y;return{l:Q-W/2-u("1"),r:Q+W/2+u("1"),t:R-M/2,b:R+M/2}});E.push({k:f,cands:nt,on:!0,card:m==="down"?v.to:v.from})}}else if(m==="trunk"||m==="rail"){const k=b.x(Math.max(A.rect.l,m==="rail"?S.rect.l:A.rect.l)+u(m==="trunk"?"8":"3"),z),B=rt(A,"bottom",k);if(m==="rail"){if(C=[B,rt(S,"top",k)],K){const H=S.rect.t-u("6");E.push({k:f,cands:O({l:k+u("2-5"),r:k+u("2-5")+W,t:H-M/2,b:H+M/2},v.to,-1),on:!1,card:v.to})}}else{const H=b.x(S.rect.l+u("6"),z),U=b.y(S.rect.t-T,z);C=[B,{x:k,y:U},{x:H,y:U},rt(S,"top",H)],K&&E.push({k:f,cands:O({l:H+u("2-5"),r:H+u("2-5")+W,t:U-M/2,b:U+M/2},v.to,-1),on:!1,card:v.to})}}else{const k=Math.min(F.get(v.from)??i,F.get(v.to)??i),B=b.x(n.gutter?L+(n.lanes[f]?2*u("3-5"):u("3-5")):k-u("2-5"),z),H=b.y(A.rect.t+(A.rect.b-A.rect.t)*n.exits[f],z),U=rt(A,"right",H),tt=b.x(S.rect.r-u("6"),z),Q=m==="end-down",N=b.y(Q?S.rect.t-T:S.rect.b+T,z);C=[U,{x:B,y:U.y},{x:B,y:N},{x:tt,y:N},rt(S,Q?"top":"bottom",tt)];const D=Q?v.to:_[S.i+1]?.id??v.to;K&&E.push({k:f,cands:O({l:tt-u("2-5")-W,r:tt-u("2-5"),t:N-M/2,b:N+M/2},D,Q?-1:1),on:!1,card:D})}const I=zt(C,z,b);w.lines.push({i:f,from:v.from,to:v.to,kind:v.kind,pts:I,tip:I[I.length-1],dir:kt(I),width:z})}),w.crossings=xt(w.lines),w.through=St(w.lines,g,a),w.outside=Yt(w.lines,i,d,o);const{obstacles:$}=Zt(l,h,r,0);$.heads=w.lines.map(v=>Kt(v,o));const G=[],j={l:0,t:0,r:i,b:d};for(const v of E){const f=S=>{const z=Ft(S,u("1"));return S.lj.r+.5||S.tj.b+.5||g.some(C=>Ht(z,C))||G.some(C=>ct(z,C))||$.heads.some(C=>ct(z,C))||$.rects.some(C=>ct(z,C))||w.lines.some(C=>C.i!==v.k&&dt(C.pts).some(([K,W])=>ct(z,Vt(K,W,C.width))))},m=v.cands.find(S=>!f(S));m||(q[v.card]=(q[v.card]??0)+1,w.unseated.push(v.k));const A=m?Ut(m,c,y,S=>!f(S)):v.cands[0];G.push(A),w.labels.push({i:v.k,text:a.edges[v.k].label,box:A,on:v.on})}return{geo:w,grow:q}}function We(t,e){const n=o=>String(Math.round(o*100)/100);let s=`M${n(t[0].x)} ${n(t[0].y)}`;for(let o=1;o({...O})),g=p[p.length-1];g.x-=o.x*u,g.y-=o.y*u;const c=e.tip.x-o.x*l,y=e.tip.y-o.y*l,b=-o.y*h,i=o.x*h,d=O=>Math.round(O*100)/100,w=it(e.kind),q=r?``:``,L=e.dot?``:"";return`${q}${L}`}function Pt(t,e,n,s){const a=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,h]of o){const u=`${s}-cut-${l}`;a.set(l,u);const p=h.map(g=>{const c=e.lines[g.top],y=e.lines[g.under],b=c.width/2+n.cut,i=y.width/2+1;return g.underVertical?``:``}).join("");r+=`${p}`}return{defs:r,ids:a}}function te(t,e,n,s){const{defs:a,ids:o}=Pt(t,e,n,s),r=e.lifelines.map(p=>``).join(""),l=e.lines.map((p,g)=>Ge(t,p,n,o.get(g)??null,p.from===p.to?n.radiusXs:n.radius)).join(""),h=`${a?`${a}`:""}${r}${l}`,u=e.labels.map(p=>`${it(p.text)}`).join("");return h+u}function Ke(t,e,n,s,a,o,r){const h=t.querySelector(`.${n}-drawing`);if(!h||t.clientWidth===0)return{dyn:a,geo:null,ink:"",tokens:null};const u=qe(t),p=Ce(h,n),g=Be(e,u,p),c=t.clientWidth,y=(()=>{const E=document.activeElement;return E&&h.contains(E)&&E.dataset.node?E.dataset.node:void 0})(),b=E=>ht(e,E)?{...E,stop:E.stop&&e.byId.has(E.stop)?E.stop:e.nodes[0]?.id,keep:void 0}:{...E,stop:E.stop??e.nodes[0]?.id,keep:y&&E.layout!=="drawn"?y:void 0},i=E=>{if(e.type!=="flowchart")return E;o({...E,heights:void 0,words:void 0});const V=ut(),$=ut();return h.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(G=>{const j=G.querySelector(`.${n}-words`);if(!j)return;const v=G.getBoundingClientRect(),f=S=>{const z={w:S.width+2*u.space("2-5"),h:S.height+2*u.space("2")},C=1-z.w/v.width,K=C>.05?z.h/2/C:z.h*10;return Math.max(u.space("16"),Math.ceil(v.width/5),Math.ceil(2*K))},m=j.getBoundingClientRect();let A=f(m);if(A>v.width){const S=W=>(G.style.setProperty("--_ww",`${W}px`),j.getBoundingClientRect()),z=Math.floor(G.clientWidth-2*u.space("2-5"));let C=Math.ceil(m.width),K=m.height;for(;C1;){const k=W+M>>1;S(k).height({m:e,tk:u,P:n,drawing:h,origin:h.getBoundingClientRect(),warn:r}),w=a.autoOpen?{open:!1,autoOpen:void 0}:{},q=(E,V)=>V.map($=>yt(e,E.lines.find(G=>G.i===$))).join(", ");if(c>=g.least){const E=j=>{let v=b({...a,...w,layout:"drawn",grow:void 0,track:void 0,bare:void 0,pad:j||void 0});return v=i(v),o(v),{dd:v,g:He(d(),p)}};let{dd:V,g:$}=E(!1);const G=j=>j.through.length>0||j.outside.length>0||(j.overlaps?.length??0)>0;if(!G($)&&$.unseated.length&&$.unseated.every(j=>$.bounded?.includes(j))){const j=E(!0);!G(j.g)&&!j.g.unseated.length&&({dd:V,g:$}=j)}if(!G($)&&!$.unseated.length)return $.crossings.length&&r?.(`${$.crossings.length} crossing${$.crossings.length===1?"":"s"} in the drawn layout: ${$.crossings.map(j=>`${yt(e,$.lines[j.top])} over ${yt(e,$.lines[j.under])}`).join("; ")}`),{dyn:V,geo:$,ink:te(n,$,u,s),tokens:u};$.through.length&&r?.(`the drawn layout does not fit at ${Math.round(c)}px: ${q($,$.through)} would pass through a node`),$.overlaps?.length&&r?.(`the drawn layout does not fit at ${Math.round(c)}px: ${q($,$.overlaps)} would lie on one another`),$.outside.length&&r?.(`the drawn layout does not fit at ${Math.round(c)}px: ${q($,$.outside)} would leave the drawing`),$.unseated.length&&r?.(`the drawn layout does not fit at ${Math.round(c)}px: no clean seat for ${$.unseated.map(j=>e.type==="sequence"?`message ${j}`:`"${e.edges[j]?.label}"`).join(", ")}`)}let L=b({...a,...w,layout:"stacked",heights:void 0,grow:ut(),track:e.type==="schema"?g.table:void 0,bare:void 0,pad:void 0});if(L=i(L),o(L),e.type==="sequence"||e.type==="schema")return{dyn:L,geo:null,ink:"",tokens:u};const O=Ct(e);let F=Qt(d(),p,O,L.grow);for(let E=0;E<6&&Object.keys(F.grow).length;E++){const V=ut(L.grow);for(const[$,G]of Object.entries(F.grow))V[$]=(ft(V,$)??0)+G;L={...L,grow:V},o(L),F=Qt(d(),p,O,V)}const _=F.geo;if(_.unseated.length>0||_.through.length>0||_.outside.length>0||O.third){_.unseated.length&&r?.(`the stacked drawing has no clean seat for ${[...new Set(_.unseated)].map($=>`"${e.edges[$]?.label}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),_.through.length&&r?.(`in the stacked drawing ${q(_,_.through)} would pass through a node, so its lines are not drawn`),_.outside.length&&r?.(`in the stacked drawing ${q(_,_.outside)} would leave the drawing, so its lines are not drawn`),O.third&&r?.("the stacked drawing would need a third end lane, so its lines are not drawn");const E={..._,lines:[],labels:[],crossings:[]};return{dyn:b({...L,grow:ut(),bare:!0,open:a.bare?a.open:!0,autoOpen:a.bare?a.autoOpen:a.open?void 0:!0}),geo:E,ink:"",tokens:u}}return _.crossings.length&&r?.(`${_.crossings.length} crossing${_.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${_.crossings.map(E=>`${yt(e,_.lines[E.top])} over ${yt(e,_.lines[E.under])}`).join("; ")}`),{dyn:L,geo:_,ink:te(n,_,u,s),tokens:u}}function yt(t,e){const n=t.byId.get(e.from)?.name??e.from,s=t.byId.get(e.to)?.name??e.to;return`${n} to ${s}`}function Ve(t,e,n,s,a,o){const r=new Set;if(o){r.add(o);for(const i of n?.lines??[])i.from===o&&r.add(i.to),i.to===o&&r.add(i.from)}if(t.toggleAttribute("data-tracing",!!o),t.querySelectorAll(`.${e}-node`).forEach(i=>i.toggleAttribute("data-near",r.has(i.dataset.node))),!n||!s)return;const l=i=>!!o&&(i.from===o||i.to===o),h=t.querySelector(`.${e}-edges`),u=new Map;t.querySelectorAll(`.${e}-edge`).forEach(i=>u.set(i.getAttribute("data-edge"),i));for(const i of n.lines){const d=u.get(String(i.i));d&&(d.toggleAttribute("data-lit",l(i)),d.toggleAttribute("data-dim",!!o&&!l(i)))}if(t.querySelectorAll(`.${e}-label`).forEach(i=>{const d=n.lines.find(w=>String(w.i)===i.dataset.edge);i.toggleAttribute("data-lit",!!(d&&l(d)))}),h){for(const i of n.lines)if(l(i)){const d=u.get(String(i.i));d&&h.appendChild(d)}}const p=xt(n.lines,l),{defs:g,ids:c}=Pt(e,{...n,crossings:p},s,a),y=t.querySelector(`.${e}-svg`);if(!y)return;let b=y.querySelector("defs");!b&&g&&(b=document.createElementNS("http://www.w3.org/2000/svg","defs"),y.insertBefore(b,y.firstChild)),b&&(b.innerHTML=g),n.lines.forEach((i,d)=>{const w=u.get(String(i.i))?.querySelector(`.${e}-line`);if(!w)return;const q=c.get(d);q?w.setAttribute("mask",`url(#${q})`):w.removeAttribute("mask")})}var Ue=()=>matchMedia("(prefers-reduced-motion: reduce), (forced-colors: active), print").matches||document.documentElement.getAttribute("data-loops")==="held";function Ze(t,e){const n=t.getAttribute("data-entrance");if(!(n==="running"||n==="done")){if(!e){n&&t.removeAttribute("data-entrance");return}n||t.setAttribute("data-entrance",Ue()?"done":"pending")}}function Je(t){const e=t.getAttribute("data-entrance");e!=="pending"&&e!=="running"||(t.setAttribute("data-entrance","done"),t.dispatchEvent(new Event("basalt-diagram-settle")))}function Xe(t,e,n){const s=t.byId.get(e)?.i??0,a=t.nodes.length;let o;if(n==="ArrowRight"||n==="ArrowDown")o=s+1;else if(n==="ArrowLeft"||n==="ArrowUp")o=s-1;else if(n==="Home")o=0;else if(n==="End")o=a-1;else return null;return t.nodes[Math.max(0,Math.min(a-1,o))].id}var Ye=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden"],ee=["data-layout","data-measured","data-bare","data-motion"],Qe=["--_track","--_h","--_ww","--_gap","--_ggrow","--_gpad"],ne=t=>t==null||t===!1;function Pe(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 oe(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const s=n?ee:Ye;for(const r of s)ne(e.a[r])&&t.removeAttribute(r);for(const[r,l]of Object.entries(e.a)){if(r==="class")continue;if(r==="style"){const u=t.style,p=new Map(String(l??"").split(";").map(g=>{const c=g.indexOf(":");return[g.slice(0,c).trim(),g.slice(c+1).trim()]}).filter(([g])=>g));for(const[g,c]of p)u.getPropertyValue(g).trim()!==c&&u.setProperty(g,c);for(const g of Qe)p.has(g)||u.removeProperty(g);continue}if(n&&!ee.includes(r))continue;if(ne(l)){t.removeAttribute(r);continue}const h=l===!0?"":String(l);t.getAttribute(r)!==h&&t.setAttribute(r,h)}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 o=0;for(const r of e.c)if(!(typeof r=="string"||"slot"in r)){for(let l=o;lt.querySelector(`.${e}-node[data-node="${CSS.escape(o)}"]`);n&&a(n)?.setAttribute("tabindex","-1"),a(s)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",s=0;function a(c,y){return{prefix:n,base:c,hasSource:y.source!==void 0&&y.source!==null&&y.source!=="",hiddenClass:"visually-hidden"}}function o(c,y,b,i){var d=function(w){return''+it(w)+""};return{source:it(String(y.source||"")),summary:it(String(y.summary||"")),hint:Le(c).map(function(w){return""+w.keys.map(d).join(" ")+" "+it(w.words)+""}).join(""),toggle:'"}}function r(c,y){var b=Et(c),i=Rt(b,{},a(y,c)),d=Ot(i,o(b,c,y,!1)),w=d.indexOf(">");return{open:d.slice(0,w+1),inner:d.slice(w+1,d.length-9),warnings:b.warnings}}var l=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-layout","data-measured","data-bare"],h=["--_cols","--_gpad","--_track"];function u(c,y,b){c.__diagram&&c.__diagram.stop();var i=(c.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),d=Et(y);if(!b||!i||!c.querySelector(":scope > .diagram-drawing")){if(!i||!c.querySelector("#"+CSS.escape(i+"-title"))){for(;document.getElementById("dg"+ ++s+"-title"););i="dg"+s}var w=r(y,i),q=document.createElement("div");q.innerHTML=w.open+"";var L=q.firstChild;l.forEach(function(R){c.removeAttribute(R)}),h.forEach(function(R){c.style.removeProperty(R)});for(var O=0;O :not(script[data-diagram])").forEach(function(R){R.remove()}),c.insertAdjacentHTML("beforeend",w.inner)}d.warnings.forEach(function(R){console.warn("Basalt diagram: "+R)});var _=a(i,y),Z={},E=null,V=null,$=null,G=Object.create(null),j=function(R){G[R]||(G[R]=1,console.warn("Basalt diagram: "+R))},v=function(R){oe(c,Rt(d,R,_))},f=c.querySelector(".diagram-ink"),m=c.querySelector(".diagram-toggle"),A=d.motion.animated&&typeof e.diagramMotion=="function",S=null,z=null,C=function(){A&&Je(c)};function K(){Ve(c,n,E&&E.geo,E&&E.tokens,i,V||$)}function W(){m&&(m.setAttribute("aria-expanded",String(!!Z.open)),m.firstElementChild.textContent=Z.open?"Hide the list":"View as list")}function M(){E=Ke(c,d,n,i,Z,v,j),Z=E.dyn,v(Z),W(),ht(d,Z)||($=null);var R=f&&E.ink!==z;R&&(f.innerHTML=E.ink,z=E.ink),K(),A&&E.tokens&&(Ze(c,!!(E.geo&&E.geo.lines.length)),R&&S&&S.redrawn())}function T(R){Z=R,v(Z)}function I(R){var X=Z.stop;Z=Object.assign({},Z,{stop:R}),tn(c,n,X,R)}var k=function(R){var X=R&&R.closest?R.closest(".diagram-node"):null;return X&&c.contains(X)?X:null};function B(R){var X=k(R.target);if(!(!X||R.defaultPrevented)){if(C(),R.key==="Escape"){(V||$)&&(R.preventDefault(),V=$=null,K());return}if(ht(d,Z)){var st=Xe(d,X.getAttribute("data-node"),R.key);if(st){R.preventDefault(),I(st);var se=c.querySelector('.diagram-node[data-node="'+CSS.escape(st)+'"]');se&&se.focus()}}}}function H(R){var X=k(R.target);if(X){C();var st=X.getAttribute("data-node");V=X.matches(":focus-visible")?st:null,ht(d,Z)&&Z.stop!==st&&I(st),K()}}function U(R){var X=k(R.target);X&&(k(R.relatedTarget)||(V=null),Z.keep===X.getAttribute("data-node")&&T(Object.assign({},Z,{keep:void 0})),K())}function tt(R){if(!(R.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var X=k(R.target);X&&C();var st=X&&ht(d,Z)?X.getAttribute("data-node"):null;st!==$&&($=st,K())}}function Q(){$&&($=null,K())}function N(){C(),T(Object.assign({},Z,{open:!Z.open,autoOpen:void 0})),W()}c.addEventListener("keydown",B),c.addEventListener("focusin",H),c.addEventListener("focusout",U),c.addEventListener("pointerover",tt),c.addEventListener("pointerleave",Q),m&&m.addEventListener("click",N),M();var D=c.clientWidth,et=0,ot=!0,J=new ResizeObserver(function(){Math.abs(c.clientWidth-D)<.5||(D=c.clientWidth,cancelAnimationFrame(et),et=requestAnimationFrame(M))});J.observe(c),document.fonts&&document.fonts.ready.then(function(){ot&&M()});var nt=matchMedia("(forced-colors: active)"),Y=d.nodes.some(function(R){return R.mark});Y&&nt.addEventListener("change",M),A&&(S=e.diagramMotion(c,{fig:c,P:n,base:i,model:function(){return d},geo:function(){return E&&E.geo},tokens:function(){return E&&E.tokens}},y)),c.__diagram={stop:function(){ot=!1,J.disconnect(),cancelAnimationFrame(et),Y&&nt.removeEventListener("change",M),S&&S.destroy(),c.removeEventListener("keydown",B),c.removeEventListener("focusin",H),c.removeEventListener("focusout",U),c.removeEventListener("pointerover",tt),c.removeEventListener("pointerleave",Q),m&&m.removeEventListener("click",N)},layout:M,key:p(y),send:S&&S.sendValue?S.sendValue:null}}function p(c){try{return JSON.stringify(c,function(y,b){return y==="packet"&&b&&typeof b=="object"?Object.assign({},b,{send:void 0}):b})}catch{return null}}function g(){document.querySelectorAll("figure.diagram").forEach(function(c){if(!c.__diagram){var y=c.querySelector(":scope > script[data-diagram]");if(y)try{u(c,JSON.parse(y.textContent),!0)}catch(b){console.error("Basalt diagram: this figure could not be drawn",b)}}})}e.diagramMarkup=r,t.diagram=function(c,y){var b=c.__diagram,i=b&&b.send?p(y):null;if(i!==null&&i===b.key){b.send(y.packet?y.packet.send:void 0);return}u(c,y)},e.step(62,"wireDiagrams",g)})(window.Basalt)})(); +(()=>{var dn=["top","right","bottom","left"],fn=["main","plain","dashed"],$e=["one","zero-or-one","one-or-many","zero-or-many"],Ft={one:"Exactly one","zero-or-one":"Zero or one","one-or-many":"One or many","zero-or-many":"Zero or many"},un=[2,3,4,5,6],gt=t=>t==null||t===""?void 0:String(t),Lt=t=>Object.assign(Object.create(null),t),Ot=(t,e)=>t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;function Nt(t,e={}){const o=e.checks!==!1,c=[],l=m=>{c.push(m)},a=[],s=m=>{a.push(m)},r=t.legend??{},d={};for(const m of["main","plain","dashed","focal","group","activation"]){const $=gt(r[m]);$&&(d[m]=$)}const p=t.stepLabel,f=typeof p=="function"?m=>String(p(m)):typeof p=="string"?(m=>p.replace("{n}",String(m))):m=>`Step ${m}`,i=t.shapeLabels??{},u={terminal:gt(i.terminal)??"Start or end",step:gt(i.step)??"Step",decision:gt(i.decision)??"Decision"},b=t.heading===void 0?3:un.includes(t.heading)?t.heading:(l(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),h=(m,$)=>m==null?"plain":fn.includes(m)?m:(l(`"${String(m)}" is not a kind of line (main, plain or dashed): ${$} is drawn plain`),"plain"),g=m=>{if(m!=null){if(dn.includes(m))return m;l(`"${String(m)}" is not a side (top, right, bottom or left): the derived side is used`)}},k=(m,$)=>typeof m=="number"&&Number.isInteger(m)&&m>=1?m:(t.layout==="auto"&&m==null||l(`${$} is ${JSON.stringify(m)}, not a whole number from 1: it is placed at 1`),1),M=[],z=[];let w=[];const q=[],O=[],N=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(N)||l(`"${String(N)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),N==="architecture"||N==="flowchart"){for(const m of t.nodes??[]){const $=N==="flowchart"&&m.shape==="decision"?"decision":N==="flowchart"&&m.shape==="terminal"?"terminal":"box",S=String(m.id??""),B=k(m.row,`the row of ${S}`);M.push({id:S,i:M.length,name:String(m.name??""),kind:$==="decision"?void 0:gt(m.kind),detail:$==="decision"?void 0:gt(m.detail),mono:!!m.detailMono,focal:!!m.focal,col:k(m.col,`the column of ${S}`),row:B,row2:B,branch:!!m.branch,shape:$,group:N==="architecture"?gt(m.group):void 0,mark:N==="architecture"?ne(m.mark,l):void 0})}if(N==="architecture"){const m=(t.groups??[]).map(I=>({id:String(I.id??""),label:String(I.label??""),parent:gt(I.parent)})),$=new Map(m.map(I=>[I.id,I])),S=I=>{if(!I.parent)return 1;const j=$.get(I.parent);return j?j.parent===I.id||j.id===I.id?(s(`the groups "${I.label}" and "${j.label}" are each other's parent`),I.parent=void 0,1):j.parent?(s(`the group "${I.label}" is a third level: groups nest two deep`),I.parent=void 0,1):2:(s(`the group "${I.label}" names the parent "${I.parent}", which is not a group`),I.parent=void 0,1)},B=m.map(S);m.forEach((I,j)=>q.push({...I,depth:B[j],members:M.filter(tt=>tt.group===I.id).map(tt=>tt.id),all:[]}));for(const I of q)I.all=[...I.members,...q.filter(j=>j.parent===I.id).flatMap(j=>j.members)];q.sort((I,j)=>I.depth-j.depth)}}else if(N==="data-flow"){w=(t.lanes??[]).map($=>({id:String($.id??""),label:String($.label??"")}));const m=new Map(w.map(($,S)=>[$.id,S+1]));for(const $ of t.nodes??[]){const S=String($.id??""),B=String($.lane??""),I=m.get(B);I===void 0&&l(`a node (${S}) names the lane "${B}", which is not in lanes`);const j=M.length+1;M.push({id:S,i:M.length,name:String($.name??""),kind:f(j),detail:gt($.detail),mono:!!$.detailMono,focal:!!$.focal,col:k($.col,`the column of ${S}`),row:I??1,row2:I??1,branch:!1,shape:"box",lane:I??1,laneLabel:w[(I??1)-1]?.label??B,step:j,mark:ne($.mark)})}}else if(N==="sequence"){(t.participants??[]).forEach((B,I)=>{const j=String(B.name??"");M.push({id:String(B.id??""),i:I,name:j,kind:gt(B.kind),mono:!1,focal:!!B.focal,col:I+1,row:1,row2:1,branch:!1,shape:"participant",short:gt(B.short)??j,mark:ne(B.mark)})});let m=0;const $=new Map(M.map(B=>[B.id,B.col])),S=(B,I)=>{let j=1/0,tt=-1/0;for(const Y of B??[]){if(!Y||typeof Y!="object")continue;if("band"in Y){I>0&&s(`the band "${String(Y.band)}" is inside a frame: a band is the whole figure's`),O.push({band:String(Y.band??"")});continue}if("frame"in Y){if(I>=2){s("a frame is a third level: frames nest two deep");continue}const vt=Y.frame==="alt"||Y.frame==="loop"||Y.frame==="opt"?Y.frame:"opt",St=vt==="alt"?Y.branches??[]:[{label:Y.label,steps:Y.steps}];vt==="alt"&&St.length<2&&s("an alt frame has one branch: it needs two or more");const pt=String(St[0]?.label??"");pt.length>40&&s(`the frame label "${pt}" is over 40 characters`);const ut=O.length;O.push({open:vt,label:pt,depth:I+1,a:0,b:0}),St.forEach((y,A)=>{if(A){const H=String(y.label??"");H.length>40&&s(`the frame label "${H}" is over 40 characters`),O.push({otherwise:H,depth:I+1})}y.steps?.length||s(`a frame or branch ("${String(y.label??"")}") is empty`);const[_,x]=S(y.steps??[],I+1);j=Math.min(j,_),tt=Math.max(tt,x);const L=O[ut];L.a=Math.min(L.a||1/0,_),L.b=Math.max(L.b,x)}),O.push({close:I+1});continue}m++;const mt=String(Y.label??"");mt.includes(` +`)&&s(`message ${m}'s label has a break: a message's second line is its note`);const nt=String(Y.from??""),lt=String(Y.to??"");O.push({n:m,from:nt,to:lt,label:_t(mt),note:gt(Y.note),kind:h(Y.kind,`message ${m}`),activate:Y.activate===!0||void 0,deactivate:Y.deactivate===!0||void 0});const ft=$.get(nt)??1,yt=$.get(lt)??1,wt=ft===yt?ft===M.length?ft-1:ft+1:ft;j=Math.min(j,ft,yt,wt),tt=Math.max(tt,ft,yt,wt)}return[j,tt]};S(t.steps??[],0);for(const B of O)"open"in B&&!Number.isFinite(B.a)&&(B.a=1,B.b=Math.max(1,M.length))}else if(N==="schema")for(const m of t.tables??[]){const $=String(m.name??""),[S,B]=Array.isArray(m.row)?m.row:[m.row,m.row],I=k(S,`the row of ${$}`),j=Math.max(I,k(B,`the last row of ${$}`)),tt=m.more===void 0||m.more===null?void 0:Number.isInteger(m.more)&&m.more>0?m.more:(l(`${$}'s "more" is ${JSON.stringify(m.more)}, not a whole number from 1: it is left out`),void 0);M.push({id:$,i:M.length,name:$,mono:!0,focal:!!m.focal,col:k(m.col,`the column of ${$}`),row:I,row2:j,branch:!1,shape:"table",more:tt,columns:(m.columns??[]).map(Y=>({name:String(Y.name??""),type:gt(Y.type),key:Y.key==="PK"||Y.key==="FK"?Y.key:(Y.key!==void 0&&Y.key!==null&&l(`${$}.${String(Y.name)}'s key is "${String(Y.key)}", not PK or FK: it is left out`),void 0)}))})}let D=!1;if(t.layout==="auto"&&(N==="architecture"||N==="flowchart"||N==="schema")){const m=N==="schema"?t.tables:t.nodes;o&&(m??[]).some(S=>S&&(S.col!==void 0||S.row!==void 0))&&l('a card under layout="auto" has a col or row, which is not read: there are no hints');const $=e.placement?.cells;$||(D=!0);for(const S of M){const B=$?.[S.id];S.col=B?.col??1,S.row=S.row2=B?.row??1}if($){const S=new Map;for(const B of M){const I=Ot($,B.id);if(!I){D=!0,l(`the placement has no cell for ${B.id}, so it is not used`);continue}const j=`${I.col},${I.row}`;S.has(j)&&(D=!0,l(`the placement puts ${S.get(j)} and ${B.id} in one cell, so it is not used`)),S.set(j,B.id)}}if($&&!D)for(const S of q){const B=S.all.map(nt=>M.find(lt=>lt.id===nt)).filter(Boolean);if(!B.length)continue;const I=Math.min(...B.map(nt=>nt.col)),j=Math.max(...B.map(nt=>nt.col)),tt=Math.min(...B.map(nt=>nt.row)),Y=Math.max(...B.map(nt=>nt.row)),mt=M.filter(nt=>!S.all.includes(nt.id)&&nt.col>=I&&nt.col<=j&&nt.row>=tt&&nt.row<=Y);mt.length&&(D=!0,l(`the placement puts ${mt.map(nt=>nt.id).join(", ")} inside the box of the group "${S.label}", so it is not used`))}}else t.layout==="auto"&&s(`layout="auto" is for an architecture, a flowchart or a schema, not a ${N}`);((N==="schema"?t.tables:N==="sequence"?t.participants:t.nodes)??[]).forEach((m,$)=>{if(!m||m.href===void 0||m.href===null)return;const S=String(m.href);if(N==="sequence"){s(`${M[$]?.id}: a participant cannot be a link (href)`);return}if(!S.trim()){s(`${M[$]?.id}'s href is empty`);return}const B=M[$];B&&(B.href=S,B.blank=m.target==="_blank")});const E=new Map;for(const m of M)m.id?E.has(m.id)&&l(`the id "${m.id}" is used twice`):l("a node has no id"),E.set(m.id,m);if(N==="schema"){const m=(S,B)=>{if(S==null)return;const I=S,j=$e.includes(I.from)?I.from:void 0;if(!j){s(`${B}'s cardinality "from" is ${JSON.stringify(I.from)}, not one, zero-or-one, one-or-many or zero-or-many: it is left out`);return}return I.to===void 0||I.to===null?{from:j,to:"one"}:I.to==="one"||I.to==="zero-or-one"?{from:j,to:I.to}:(s(`${B}'s cardinality "to" is ${JSON.stringify(I.to)}: a foreign key references one row at most (one or zero-or-one), so it is drawn as one`),{from:j,to:"one"})};(t.tables??[]).forEach(S=>(S.columns??[]).forEach((B,I)=>{const j=gt(B.references);if(!j&&B.cardinality!==void 0&&B.cardinality!==null&&s(`${String(S.name)}.${String(B.name)} states a cardinality but references nothing`),!j)return;const[tt,Y]=j.split("."),mt=E.get(tt??""),nt=mt?.columns?.findIndex(yt=>yt.name===Y)??-1;if(!mt||nt<0){l(`${String(S.name)}.${String(B.name)} references ${j}, which is not a shown column`);return}const lt=E.get(String(S.name??""));lt.columns[I].ref={table:tt,column:Y,row:nt};const ft=m(B.cardinality,`${String(S.name)}.${String(B.name)}`);ft&&(lt.columns[I].card=ft),z.push({i:z.length,from:lt.id,to:tt,kind:"plain",fromRow:I,toRow:nt,fk:!0,card:ft})}));const $=z.filter(S=>S.card).length;$&&$!S.card).map(S=>`${S.from}.${E.get(S.from).columns[S.fromRow].name}`).join(", ")} ${z.length-$===1?"has":"have"} none)`)}else if(N!=="sequence")for(const m of t.edges??[]){const $=String(m.from??""),S=String(m.to??"");if(!E.has($)||!E.has(S)){l(`a line names ${E.has($)?S:$}, which is not a node`);continue}const B=gt(m.label),I=B?.split(` +`)??[];I.length>2&&s(`the label "${_t(B)}" has more than one break: a label is two lines at most`),I.some(j=>j.length>ve)&&s(`a line of the label "${_t(B)}" is over ${ve} characters: longer words belong in the node or the summary`),z.push({i:z.length,from:$,to:S,kind:h(m.kind,`the line from ${$} to ${S}`),label:B,fromSide:g(m.fromSide),toSide:g(m.toSide),flow:N!=="flowchart"&&m.flow===!0?!0:void 0})}else for(const m of O)"n"in m&&(!E.has(m.from)||!E.has(m.to))&&l(`message ${m.n} names ${E.has(m.from)?m.to:m.from}, which is not a participant`);if(o&&N!=="sequence"&&!D){const m=new Map;for(const $ of M)for(let S=$.row;S<=$.row2;S++){const B=`${$.col}:${S}`;m.has(B)&&l(`${$.id} and ${m.get(B)} share the cell at column ${$.col}, row ${S}`),m.set(B,$.id)}}if(o&&!D){for(const $ of q){const S=$.all.map(j=>E.get(j));if(!S.length)continue;const B={c1:Math.min(...S.map(j=>j.col)),c2:Math.max(...S.map(j=>j.col)),r1:Math.min(...S.map(j=>j.row)),r2:Math.max(...S.map(j=>j.row2))};for(const j of M)!$.all.includes(j.id)&&j.col>=B.c1&&j.col<=B.c2&&j.row>=B.r1&&j.row<=B.r2&&l(`${j.id} is inside the box of the group "${$.label}" but not a member`);const I=S.map(j=>j.i);Math.max(...I)-Math.min(...I)+1!==I.length&&l(`the members of the group "${$.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const $ of M)$.group&&!q.some(S=>S.id===$.group)&&l(`${$.id} names the group "${$.group}", which is not in groups`);M.filter($=>$.focal).length>1&&l("more than one node is focal: a diagram has one at most");const m=new Set(N==="sequence"?O.flatMap($=>"n"in $?[$.kind]:[]):z.map($=>$.kind));m.has("main")&&!d.main&&l("main lines are drawn but the legend has no words for them (legend.main)"),m.has("dashed")&&!d.dashed&&l("dashed lines are drawn but the legend has no words for them (legend.dashed)"),M.some($=>$.focal)&&!d.focal&&l("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const G=N==="architecture"||N==="data-flow",R=m=>Array.isArray(m)&&m.length>1?m.map(String):void 0,C=G&&t.packet&&typeof t.packet=="object"?t.packet:void 0,W=C&&R(C.path),T={animated:t.motion==="animated",pulse:G?R(t.pulse):void 0,packet:W?{path:W,repeat:C.repeat===!0,send:C.send}:void 0,run:N==="sequence"&&t.run===!0,firstVisit:t.entrance==="first-visit"||void 0};if(o)for(const m of M){const $=m.mark?.says;if(!$?.length)continue;const S=[m.name,m.kind,m.detail,m.laneLabel].filter(Boolean).join(" ").toLowerCase();$.some(B=>S.includes(B.toLowerCase()))||l(`${m.id}'s mark stands for ${$.join(" or ")}, and none of its words say so`)}const K=[];if(N==="sequence"){const m=new Map,$=new Map;for(const S of O)"n"in S&&($.set(S.from,S.n),$.set(S.to,S.n));for(const S of O)if("n"in S){if(S.activate){const B=m.get(S.to)??[];if(B.length>=3)s(`message ${S.n} opens a fourth bar on ${S.to}: three deep at most`);else{const I={who:S.to,from:S.n,to:S.n,depth:B.length+1};B.push(I),K.push(I),m.set(S.to,B)}}if(S.deactivate){const I=m.get(S.from)?.pop();I?I.to=S.n:s(`message ${S.n} closes a bar on ${S.from}, which has none open`)}}for(const[S,B]of m)for(const I of B)I.to=Math.max(I.from,$.get(S)??I.from)}const U=t.frameLabels??{},st={opt:gt(U.opt)??"Only if",loop:gt(U.loop)??"Repeats",alt:gt(U.alt)??"One of these",else:gt(U.else)??"Otherwise"},X=t.layout==="auto"&&!D?e.placement:void 0;let J=Math.max(1,X?.cols??1,...M.map(m=>m.col));if(e.rtl){for(const $ of M)$.col=J-$.col+1;const m=$=>$==="left"?"right":$==="right"?"left":$;for(const $ of z)$.fromSide=m($.fromSide),$.toSide=m($.toSide);for(const $ of O)if("open"in $){const[S,B]=[J-$.b+1,J-$.a+1];$.a=S,$.b=B}J=Math.max(1,X?.cols??1,...M.map($=>$.col))}const Z=N==="data-flow"?Math.max(1,w.length):Math.max(1,X?.rows??1,...M.map(m=>m.row2)),Q={type:N,title:String(t.title??""),heading:b,legend:d,nodes:M,byId:E,edges:z,groups:q,lanes:w,steps:O,bars:K,frameWords:st,cols:J,rows:Z,shapeLabels:u,stepWord:f,warnings:c,errors:a,motion:T,memo:new Map,rtl:e.rtl||void 0,unplaced:D||void 0,text:N==="sequence"&&t.variant==="text"||void 0,marks:z.some(m=>m.card)||void 0};if(t.layout==="auto"&&!D&&N!=="schema"&&hn(Q),o)for(const[m,$]of Object.entries(Fe(Q)))$>=48&&l(`${m} grows to ${$}px to hold the lines on one side: use another side`);return o&&M.length>100&&l(`the figure has ${M.length} cards: more than 100, which automatic layout places on the main thread`),o&&M.length>1&&!D&&!Jt(Q)&&l("some part cannot be reached from another by the arrow keys where the figure is drawn, so its arrows keep the author's order"),Q}function hn(t){const e=new Set(t.nodes.map(s=>`${s.col},${s.row}`)),n=(s,r)=>{const d=[];for(let p=Math.min(s,r)+1;p{const r=t.byId.get(s.from),d=t.byId.get(s.to),p=d.col>r.col?"right":"left",f=d.row>r.row?"bottom":"top",i=d.col>r.col?"left":"right",u=d.row>r.row?"top":"bottom",b=(k,M,z,w)=>n(k,M).map(q=>w?[q,z]:[z,q]);let h;const g=k=>(k==="right"?r.col1:k==="bottom"?r.row1)?[{sides:[k,k],cells:[]}]:[];return r.row===d.row?h=[{sides:[p,i],cells:b(r.col,d.col,r.row,!0)},...g("bottom"),...g("top")]:r.col===d.col?h=[{sides:[f,u],cells:b(r.row,d.row,r.col,!1)},...g("right"),...g("left")]:h=[{sides:[p,u],cells:[...b(r.col,d.col,r.row,!0),[d.col,r.row],...b(r.row,d.row,d.col,!1)]},{sides:[f,i],cells:[...b(r.row,d.row,r.col,!1),[r.col,d.row],...b(r.col,d.col,d.row,!0)]},{sides:[p,i],cells:b(r.col,d.col,r.row,!0)},{sides:[f,u],cells:b(r.row,d.row,r.col,!1)}],h.filter(k=>k.cells.every(([M,z])=>!e.has(`${M},${z}`)))},c=new Map,l=new Set;for(const s of t.edges)if(s.fromSide||s.toSide){const[r,d]=de(t.byId.get(s.from),t.byId.get(s.to)),p=s.fromSide??r,f=s.toSide??d;l.add(`${s.from}.${p}`);for(const[i,u]of[[s.from,p],[s.to,f]])c.set(`${i}.${u}`,(c.get(`${i}.${u}`)??0)+1)}const a=t.edges.map((s,r)=>r).sort((s,r)=>o(t.edges[s]).length-o(t.edges[r]).length||+(t.edges[r].kind==="main")-+(t.edges[s].kind==="main")||s-r);for(const s of a){const r=t.edges[s];if(r.fromSide||r.toSide)continue;const d=(f,i,u)=>{const b=`${f}.${i}`;return(c.get(b)??0)>=3?!1:t.byId.get(f).shape!=="decision"?!0:u?!c.has(b):!l.has(b)},p=o(r).find(f=>d(r.from,f.sides[0],!0)&&d(r.to,f.sides[1],!1));if(p){l.add(`${r.from}.${p.sides[0]}`);for(const[f,i]of[[r.from,p.sides[0]],[r.to,p.sides[1]]])c.set(`${f}.${i}`,(c.get(`${f}.${i}`)??0)+1);r.fromSide=p.sides[0],r.toSide=p.sides[1]}}}function ne(t,e){if(typeof t=="string")return t?{id:t}:void 0;if(!t||typeof t!="object")return;const n=t,o=be(gt(n.onLight),e);if(o)return{onLight:o,onDark:be(gt(n.onDark),e)??o,says:Array.isArray(n.says)?n.says.map(String):void 0}}function be(t,e){if(t){if(/^data:image\//i.test(t.trim()))return t;try{if(/^https?:$/.test(new URL(t,"https://basalt.invalid/").protocol)&&!/^http:/i.test(t.trim()))return t}catch{}e?.(`a card's mark ${JSON.stringify(t.slice(0,60))} is not a relative path, https or a data: image, so it is not drawn`)}}var we=t=>`url("${t.replace(/[\\"\n\r\f;]/g,e=>e===` +`?"\\a ":e==="\r"?"\\d ":e==="\f"?"\\c ":e===";"?"\\3b ":`\\${e}`)}")`;function jt(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var ve=28,Vt=t=>t.includes(` +`)?2:1,_t=t=>t.replace(/\n/g," "),Wt=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""};function xe(t,e){return t.legend[e]}function pn(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function gn(t,e){return jt(t,`sentence:${e.i}`,()=>mn(t,e))}function mn(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const o=(e.columns??[]).filter(l=>l.ref).map(l=>`${l.ref.table} (${l.name}${l.card?`: ${ke(e.id,l.ref.table,l.card)}`:""})`),c=t.edges.filter(l=>l.to===e.id).map(l=>`${l.from} (${t.byId.get(l.from).columns[l.fromRow].name}${l.card?`: ${ke(l.from,l.to,l.card)}`:""})`);o.length&&n.push(`References ${o.join(", ")}.`),c.length&&n.push(`Referenced by ${c.join(", ")}.`)}else if(t.type==="sequence"){const o=t.steps.filter(a=>"n"in a&&a.from===e.id).length,c=t.steps.filter(a=>"n"in a&&a.to===e.id).length;n.push(Wt(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${o} ${o===1?"message":"messages"} and receives ${c}.`);const l=Me(t,e);l&&n.push(l.trim())}else{const o=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?pn(t,e):e.kind;if(n.push(Wt(o?`${e.name}, ${o}`:e.name)),e.detail&&n.push(Wt(e.detail)),e.group){const a=t.groups.find(r=>r.id===e.group),s=a?.parent?t.groups.find(r=>r.id===a.parent):void 0;a&&n.push(s?`In ${a.label}, in ${s.label}.`:`In ${a.label}.`)}const c=t.edges.filter(a=>a.to===e.id).map(a=>`${t.byId.get(a.from).name}${a.label?` (${_t(a.label)})`:""}`),l=t.edges.filter(a=>a.from===e.id).map(a=>`${t.byId.get(a.to).name}${a.label?` (${_t(a.label)})`:""}`);c.length&&n.push(`From: ${c.join(", ")}.`),l.length&&n.push(`To: ${l.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(Wt(t.legend.focal)),n.join(" ")}var yn=(t,e,n,o)=>[`${Ft[n.from].toLowerCase()} `,o(t),` to ${Ft[n.to].toLowerCase()} `,o(e)],ke=(t,e,n)=>`${Ft[n.from].toLowerCase()} ${t} to ${Ft[n.to].toLowerCase()} ${e}`;function Me(t,e){const n=t.bars.filter(c=>c.who===e.id&&c.depth===1);return n.length?` ${t.legend.activation??"Working"} during ${n.map(c=>c.from===c.to?`message ${c.from}`:`messages ${c.from} to ${c.to}`).join(" and ")}.`:""}function $n(t,e,n,o){const c=n.pointerType;if(c!=="touch"&&c!=="pen")return;const l=t.querySelector(`.${e}-drawing`),a=n.target;if(!l||!a||!l.contains(a)||!t.querySelector(`.${e}-edge`))return;const s=a.closest(`.${e}-node`);if(!s?.hasAttribute("href"))return s?s.dataset.node===o?null:s.dataset.node??null:o===null?void 0:null}function Se(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function v(t,e,...n){const o=[];for(const c of n.flat(1/0))c!=null&&c!==!1&&!Array.isArray(c)&&o.push(c);return{t,a:e??{},c:o}}var bn={"&":"&","<":"<",">":">",'"':""","'":"'"},bt=t=>t.replace(/[&<>"']/g,e=>bn[e]),wn=" br img input meta link hr path polygon polyline circle rect line ";function oe(t,e={}){if(typeof t=="string")return bt(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,c]of Object.entries(t.a))if(!(c==null||c===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(o))throw new Error(`diagram: "${o}" is not an attribute name`);n+=c===!0?` ${o}`:` ${o}="${bt(String(c))}"`}return wn.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=>oe(o,e)).join("")}`}var vn=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function Rt(t,e){return!e.layout||e.bare?!1:e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema"}function xn(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function Kt(t,e){const n=e.all.map(o=>t.byId.get(o));return n.length?{c1:Math.min(...n.map(o=>o.col)),c2:Math.max(...n.map(o=>o.col)),r1:Math.min(...n.map(o=>o.row)),r2:Math.max(...n.map(o=>o.row2))}:null}function Ee(t){return jt(t,"group-edges",()=>{const e=[0,0,0,0];for(const n of t.groups){const o=Kt(t,n);if(!o)continue;[o.r1===1,o.c2===t.cols,o.r2===t.rows,o.c1===1].forEach((l,a)=>{l&&(e[a]=Math.max(e[a],Ae(t,n,a)))})}return e})}function Ae(t,e,n){const o=Kt(t,e);return t.groups.filter(a=>a.parent===e.id).some(a=>{const s=Kt(t,a);return s&&[s.r1===o.r1,s.c2===o.c2,s.r2===o.r2,s.c1===o.c1][n]})?2:1}function Le(t){const e=Ee(t);return e[1]+e[3]}function ae(t){return t.type==="sequence"?t.nodes.length:t.cols}function _e(t){return jt(t,"plan",()=>kn(t))}function kn(t){const e=t.nodes,n=g=>t.type==="data-flow"||!e[g].branch,o=t.edges.map(g=>{const k=t.byId.get(g.from).i,M=t.byId.get(g.to).i,w=e.slice(Math.min(k,M)+1,Math.max(k,M)).every(q=>!n(q.i));return M===k+1&&!(n(k)&&!n(M))?"down":M===k-1?"up":M>k&&n(k)&&!n(M)&&w?"trunk":M>k&&n(k)&&n(M)&&w?"rail":M>k?"end-down":"end-up"}),c=t.edges.map((g,k)=>({e:g,k})).filter(({k:g})=>o[g]==="end-down"||o[g]==="end-up"),l=g=>{const k=t.byId.get(g.from).i,M=t.byId.get(g.to).i;return[Math.min(k,M),Math.max(k,M)]},a=(g,k)=>{const[M,z]=l(g),[w,q]=l(k);return M{const k=t.byId.get(g.from).i,[M,z]=l(g);return!n(k)&&e.slice(M+1,z).every(w=>!n(w.i))&&c.every(w=>w.e===g||!a(w.e,g))}),r=c.length>0&&(t.type==="data-flow"||!s),d=g=>{const[k,M]=l(g);return M-k},p=t.edges.map(()=>0);let f=!1;const i=[];for(const g of[...c].sort((k,M)=>d(k.e)-d(M.e)||k.k-M.k)){let k=0;for(const M of i)a(M.e,g.e)&&(k=Math.max(k,p[M.k]+1));p[g.k]=k,k>3&&(f=!0),i.push(g)}const u=Math.max(0,...c.map(({k:g})=>p[g]+1)),b=t.edges.map(()=>.5);for(const g of e){const k=c.filter(({e:w})=>w.from===g.id);if(k.length<2)continue;const M=k.filter(({k:w})=>o[w]==="end-down").sort((w,q)=>d(q.e)-d(w.e)||w.k-q.k);[...k.filter(({k:w})=>o[w]==="end-up").sort((w,q)=>d(w.e)-d(q.e)||q.k-w.k),...M].forEach(({k:w},q,O)=>{b[w]=O.length===2?q===0?1/3:2/3:(q+1)/(O.length+1)})}const h=Lt();for(let g=1;g{const G=o[E],R=t.byId.get(dt.from).i,C=t.byId.get(dt.to).i,W=C===g&&(G==="down"||G==="trunk"||G==="rail"||G==="end-down"),T=R===g&&C===g-1&&G==="up",K=C===g-1&&G==="end-up";W&&(G==="trunk"||G==="end-down")&&(q=!0),K&&(O=!0),(W||T||K)&&dt.label&&(z++,w=Math.max(w,G==="trunk"?40:48))}),(z>1||q&&O)&&(w=64);const N=c.filter(({e:dt,k:E})=>o[E]==="end-down"&&t.byId.get(dt.to).i===g).length,D=c.filter(({e:dt,k:E})=>o[E]==="end-up"&&t.byId.get(dt.to).i===g-1).length;w+=20*Math.max(0,N-1)+20*Math.max(0,D-1),h[k.id]=w}return{routes:o,gutter:r,lanes:p,exits:b,gaps:h,third:f,laneCount:u}}var zt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function Ie(t,e){const n=e==="fk"?"plain":e,o=n==="main"?8:8.5,c=24,l=n==="dashed"?c-1:c-7;return v("svg",{class:`${t}-swatch`,"data-kind":n,...zt(24,16)},e==="fk"?v("circle",{class:`${t}-dot`,cx:3,cy:o,r:3}):null,v("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${o}H${l}`}),n==="dashed"?v("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${c-8} ${o-4}L${c} ${o}L${c-8} ${o+4}`}):v("path",{class:`${t}-tip`,"data-kind":n,d:`M${c} ${o}L${c-8} ${o-4}L${c-8} ${o+4}Z`}))}function Mn(t,e){const{crow:n,ring:o}=qe(e,24,8.5,-1);return v("svg",{class:`${t}-swatch`,"data-card":e,...zt(24,16)},v("path",{class:`${t}-line`,"data-kind":"plain",d:"M0 8.5H24"}),v("path",{class:`${t}-crow`,d:n}),o?v("circle",{class:`${t}-ring`,cx:o.x,cy:o.y,r:o.r}):null)}function qe(t,e,n,o,c=8,l=6){const a=u=>String(Math.round(u*100)/100),s=u=>e+o*u,r=c/2,d=u=>`M${a(s(u-.5))} ${a(n-r)}V${a(n+r)}`,p=t==="one-or-many"||t==="zero-or-many",f=t==="zero-or-one"||t==="zero-or-many";let i=p?`M${a(e)} ${a(n-r)}L${a(s(7.5))} ${a(n)}L${a(e)} ${a(n+r)}`:d(4);return f||(i+=d(p?11:8)),{crow:i,ring:f?{x:Math.round(s(10.5)*100)/100,y:n,r:l/2}:void 0}}function Ht(t,e){return e==="decision"?v("svg",{class:`${t}-swatch`,"data-shape":e,...zt(16,16)},v("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?v("svg",{class:`${t}-swatch`,"data-shape":e,...zt(16,16)},v("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):v("svg",{class:`${t}-swatch`,"data-shape":e,...zt(16,16)},v("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function Oe(t,e){return jt(e,`key:${t}`,()=>En(t,e))}var Sn=Oe;function En(t,e){const n=[],o=(a,s,r={})=>n.push(v("li",{class:`${t}-entry`,...r},a,v("span",null,s)));if(e.type==="schema"){const a=new Set(e.nodes.flatMap(s=>(s.columns??[]).map(r=>r.key)));for(const[s,r]of[["PK","Primary key"],["FK","Foreign key"]])a.has(s)&&n.push(v("li",{class:`${t}-entry`},v("span",{class:`${t}-key-letters`,"aria-hidden":"true"},s),v("span",null,r)))}if(e.type==="flowchart"){const a=new Set(e.nodes.map(s=>s.shape));a.has("terminal")&&o(Ht(t,"terminal"),e.shapeLabels.terminal),a.has("box")&&o(Ht(t,"box"),e.shapeLabels.step),a.has("decision")&&o(Ht(t,"decision"),e.shapeLabels.decision)}const c=new Set(e.type==="sequence"?e.steps.flatMap(a=>"n"in a?[a.kind]:[]):e.edges.filter(a=>!a.fk).map(a=>a.kind)),l=(a,s)=>v("span",{class:`${t}-key-glyph`,"data-ink":s,"aria-hidden":"true"},a);for(const a of["main","plain","dashed"]){const s=e.legend[a];c.has(a)&&s&&o(e.text?l(a==="main"?"━━▶":a==="dashed"?"┄┄▷":"──▶",a==="main"?"main":"plain"):Ie(t,a),s,{"data-line":e.text?void 0:""})}if(e.type==="schema"&&e.edges.length){e.edges.some(s=>!s.card)&&o(Ie(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"});const a=new Set(e.edges.flatMap(s=>s.card?[s.card.from,s.card.to]:[]));for(const s of $e)a.has(s)&&o(Mn(t,s),Ft[s],{"data-line":"","data-when":"drawn","data-card":s});n.push(v("li",{class:`${t}-entry`,"data-when":"stacked"},v("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},e.rtl?"←":"→"),v("span",null,"The table a foreign key references")))}if(e.type==="sequence"){e.bars.length&&o(e.text?l("┃","working"):v("svg",{class:`${t}-swatch`,"data-shape":"bar",...zt(16,16)},v("path",{class:`${t}-life`,d:"M8 0V16"}),v("rect",{class:`${t}-bar`,x:4.5,y:2.5,width:7,height:11,rx:1.5})),e.legend.activation??"Working",e.text?{}:{"data-when":"drawn"});const a=new Set(e.steps.flatMap(s=>"open"in s?[s.open]:[]));for(const s of["opt","loop","alt"])a.has(s)&&n.push(v("li",{class:`${t}-entry`},v("span",{class:`${t}-key-letters`,"data-op":"","aria-hidden":"true"},s),v("span",null,e.frameWords[s])))}return e.nodes.some(a=>a.focal)&&e.legend.focal&&o(e.text?l("╔═╗","focal"):Ht(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&o(Ht(t,"group"),e.legend.group),n.length?v("div",{class:`${t}-key`},v("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function An(t,e){const n=e==="main"?6:6.5;return v("svg",{class:`${t}-arrow`,"data-kind":e,...zt(20,12)},v("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?v("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):v("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}function se(t,e){if(!e.href)return e.name;const n=e.name.trimEnd().lastIndexOf(" ");return[n<0?"":e.name.slice(0,n+1),v("span",{class:`${t}-name-end`},n<0?e.name:e.name.slice(n+1))]}function Ln(t,e,n){if(n.shape==="decision")return[v("span",{class:`${t}-words`},v("span",{class:`${t}-name`},se(t,n)))];const o=[];return e.type==="data-flow"?o.push(v("span",{class:`${t}-kind`},n.kind,v("span",{class:`${t}-lane-word`},` · ${n.laneLabel}`))):n.kind&&o.push(v("span",{class:`${t}-kind`},n.kind)),o.push(v("span",{class:`${t}-name`},se(t,n))),n.detail&&o.push(v("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.mono?v("span",{class:`${t}-runs`},Qt(n.detail).flatMap((c,l)=>[l?" ":"",v("span",{class:`${t}-run`},c)])):n.detail)),o}function _n(t,e,n){return[v("span",{class:`${t}-th`},v("span",{class:`${t}-tname`},se(t,e))),v("span",{class:`${t}-rows`},(e.columns??[]).map((o,c)=>v("span",{class:`${t}-row`,"data-row":c,"data-key":o.key},v("span",{class:`${t}-keyseat`},o.key??""),v("span",{class:`${t}-cname`},o.name),o.ref?v("span",{class:`${t}-ctype`,"data-ref":""},`${n.rtl?"←":"→"} ${o.ref.table}`):o.type?v("span",{class:`${t}-ctype`},o.type):null))),e.more?v("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var Ce=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 Zt(t,e,n,o){const{P:c}=t,l=xn(e,o)||o.keep===n.id,a=Rt(e,o),s=o.layout==="drawn"&&o.rows,r=[`--_c:${n.col}`,`--_r:${s?2*n.row:n.row}`,`--_r2:${s?2*n.row2+1:n.row2+1}`];e.type==="data-flow"&&r.push(`--_lc:${n.col+1}`),e.type==="sequence"&&r.push(`--_c2:${n.col+1}`);const d=t.plan;if(d&&n.i>0){const b=Ot(d.gaps,n.id)??32,h=Ot(o.grow,n.id)??0;r.push(`--_gap:${h?`calc(${Ce(b)} + var(--basalt-space-4) * ${h})`:Ce(b)}`)}const p=Ot(o.heights,n.id);p&&r.push(`--_h:${p}px`);const f=Ot(Fe(e),n.id);f&&r.push(`--_mh:${f}px`);const i=Ot(o.words,n.id);i&&r.push(`--_ww:${i}px`);const u=a?o.stop===n.id?0:-1:o.keep===n.id?-1:void 0;return v(n.href?"a":"div",{class:`${c}-node`,href:n.href,target:n.href&&n.blank?"_blank":void 0,rel:n.href&&n.blank?"noopener noreferrer":void 0,"data-link":n.href?n.blank?"external":"":void 0,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-mark":n.mark?n.mark.id??"":void 0,"data-level":t.level,style:r.join(";"),role:l&&!n.href?"img":void 0,"aria-label":l||n.href?gn(e,n):void 0,tabindex:u},n.shape==="decision"?v("svg",{class:`${c}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},v("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.mark?v("span",{class:`${c}-mark`,"aria-hidden":"true",style:n.mark.onLight?`--_ml:${we(n.mark.onLight)};--_md:${we(n.mark.onDark??n.mark.onLight)}`:void 0}):null,n.shape==="table"?_n(c,n,e):Ln(c,e,n))}function In(t,e,n){const{P:o}=t,c=[];if(e.type==="data-flow"&&c.push(...e.lanes.map((r,d)=>v("div",{class:`${o}-lane`,style:`--_r:${d+1}`,"aria-hidden":"true"},v("span",{class:`${o}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const d=Kt(e,r);if(!d)continue;const p=[0,1,2,3].map(f=>Ae(e,r,f));c.push(v("div",{class:`${o}-gbox`,"data-group":r.id,"data-depth":r.depth>1?r.depth:void 0,style:`--_c:${d.c1};--_c2:${d.c2+1};--_r:${d.r1};--_r2:${d.r2+1}${p[0]>1?";--_gt:2":""}${p[1]>1?";--_ge:2":""}${p[2]>1?";--_gb:2":""}${p[3]>1?";--_gs:2":""}`,"aria-hidden":"true"},v("span",{class:`${o}-glabel`},r.label)))}if(e.text)return[v("pre",{class:`${o}-text`,"aria-hidden":"true","data-art":n.art?"":void 0},v("code",{class:`${o}-text-ink`},qn(o,e)))];if(e.type==="sequence")return c.push(v("ul",{class:`${o}-cast`},e.nodes.map(r=>v("li",{class:`${o}-actor`,style:e.rtl?`--_ac:${r.col}`:void 0},Zt(t,e,r,n))))),c.push(On(t,e)),c;const l=r=>{const d=r.group?e.groups.find(p=>p.id===r.group):void 0;return d?.parent?e.groups.find(p=>p.id===d.parent):d},a=(r,d,p)=>{const f=t.plan?Ot(n.grow,d[0].id)??0:0,i=d[0],u=t.plan&&i.group===r.id?e.edges.filter((g,k)=>g.to===i.id&&(t.plan.routes[k]==="trunk"||t.plan.routes[k]==="end-down")):[],b=Math.max(0,...u.map(g=>g.label?Vt(g.label):0)),h=[f?`--_ggrow:${f}`:"",b?`--_tl:${b}`:""].filter(Boolean).join(";");return v("div",{class:`${o}-group`,"data-group":r.id,"data-depth":r.depth>1?r.depth:void 0,"data-turn":u.length?"":void 0,style:h||void 0},v("span",{class:`${o}-glabel`,"aria-hidden":"true"},r.label),p)};let s=0;for(;sh.id===p[i].group):void 0;if(!u){f.push(Zt(t,e,p[i],n)),i++;continue}const b=[];for(;iZt(t,e,h,n))))}c.push(a(d,p,f))}return c}function qn(t,e){const n=[],o=r=>v("span",{class:`${t}-tx-name`},r),c=r=>r==="main"?"━▶":r==="dashed"?"┄▷":"─▶",l=(r,d,p,...f)=>v("span",{class:`${t}-tx-line`,...r,style:p?`--_in:${d+p};--_hang:${p}`:`--_in:${d}`},...f);n.push(l({"data-ink":"names"},0,0,e.nodes.flatMap((r,d)=>[d?" · ":"",o(r.name)])));const a=String(Math.max(1,...e.steps.map(r=>"n"in r?r.n:0))).length;let s=0;for(const r of e.steps){const d=2*s;if("band"in r){n.push(l({"data-ink":"band"},d,0,`── ${r.band} ──`));continue}if("open"in r){n.push(l({"data-ink":"frame"},d,0,v("span",{"data-ink":"op"},`[${r.open}]`),` ${r.label}`)),s++;continue}if("otherwise"in r){n.push(l({"data-ink":"frame"},2*Math.max(0,s-1),0,v("span",{"data-ink":"op"},"[else]"),` ${r.otherwise}`));continue}if("close"in r){s=Math.max(0,s-1),n.push(l({"data-ink":"frame"},2*s,0,"[end]"));continue}const p=e.byId.get(r.from)?.name??r.from,f=e.byId.get(r.to)?.name??r.to,i=a+2;n.push(l({"data-n":r.n},d,i,v("span",{"data-ink":"num"},String(r.n).padStart(a,"0"))," ",o(p)," ",v("span",{class:`${t}-tx-to`},v("span",{"data-ink":r.kind==="main"?"main":"plain"},c(r.kind))," ",f))),n.push(l({"data-n":r.n},d+i,0,v("span",{"data-ink":"label"},r.label))),r.note&&n.push(l({"data-n":r.n},d+i,0,v("span",{"data-ink":"note"},r.note)))}return n}function On(t,e){const{P:n}=t,o=[],c=[],l=()=>c.length?c[c.length-1].el.c:o;let a=null;for(const s of e.steps){if("band"in s){a=null,l().push(v("p",{class:`${n}-band`},v("span",null,s.band)));continue}if("open"in s){a=null;const h=c[c.length-1],g=h?`;--_fis:${s.a===h.a?1:0};--_fie:${s.b===h.b?1:0}`:"",k=v("div",{class:`${n}-frame`,"data-op":s.open,"data-depth":s.depth,style:`--_a:${s.a};--_b:${s.b+1}${g}`},v("span",{class:`${n}-fbox`,"aria-hidden":"true"}),v("p",{class:`${n}-fhead`},v("span",{class:`${n}-ftab`,"aria-hidden":"true"},s.open),v("span",{class:`${n}-flabel`},v("span",{class:t.hidden},`${e.frameWords[s.open]}: `),s.label)));l().push(k),c.push({el:k,a:s.a,b:s.b});continue}if("otherwise"in s){a=null,l().push(v("p",{class:`${n}-felse`},v("span",{class:`${n}-fword`,"aria-hidden":"true"},"else"),v("span",{class:`${n}-flabel`},v("span",{class:t.hidden},`${e.frameWords.else}: `),s.otherwise)));continue}if("close"in s){a=null,c.pop();continue}a||(a=v("ol",{class:`${n}-msgs`,start:s.n}),l().push(a));const r=e.byId.get(s.from),d=e.byId.get(s.to),p=r?.col??1,f=d?.col??1,i=p===f,u=i&&(e.rtl?p!==1:p===e.nodes.length),b=xe(e,s.kind);a.c.push(v("li",{class:`${n}-msg`,"data-kind":s.kind,"data-from":s.from,"data-to":s.to,"data-self":i?u?"start":"end":void 0,style:`--_a:${Math.min(p,f)};--_b:${Math.max(p,f)+1}`},v("span",{class:`${n}-said`},v("span",{class:`${n}-num`},String(s.n)),v("span",{class:`${n}-mlabel`},s.label)),v("span",{class:`${n}-route`},r?.short??s.from," ",v("span",{class:`${n}-to`},An(n,s.kind),v("span",{class:t.hidden}," to ")," ",d?.short??s.to,b?` · ${b}`:"")),s.note?v("span",{class:`${n}-note`},s.note):null))}return v("div",{class:`${n}-steps`},o)}function Be(t,e){return jt(e,`list:${t}`,()=>Bn(t,e))}var Cn=Be;function Bn(t,e){const n=Math.min(6,e.heading+1),o=f=>v(`h${n}`,{class:`${t}-list-head`},f),c=f=>v("strong",null,f),l=f=>f.href?v("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},c(f.name)):c(f.name),a=f=>v("code",{class:`${t}-code`},f),s=f=>e.byId.get(f)?.name??f,r=f=>{const i=xe(e,f);return i?` (${i})`:""},d=f=>f.focal&&e.legend.focal?` ${Wt(e.legend.focal)}`:"";if(e.type==="architecture"){const f=b=>v("li",null,l(b),b.kind?`, ${b.kind}`:"",b.detail?[". ",b.mono?a(b.detail):b.detail,/[.!?]$/.test(b.detail)?"":"."]:/[.!?]$/.test(b.kind??b.name)?"":".",d(b)),i=[o("Parts")],u=e.nodes.filter(b=>!b.group);u.length&&i.push(v("ul",{class:`${t}-list-items`},u.map(f)));for(const b of e.groups.filter(h=>h.depth===1)){i.push(v("p",{class:`${t}-list-group`},b.label)),b.members.length&&i.push(v("ul",{class:`${t}-list-items`},b.members.map(h=>f(e.byId.get(h)))));for(const h of e.groups.filter(g=>g.parent===b.id))i.push(v("p",{class:`${t}-list-group`,"data-depth":2},h.label)),i.push(v("ul",{class:`${t}-list-items`,"data-depth":2},h.members.map(g=>f(e.byId.get(g)))))}return i.push(o("Connections")),i.push(v("ol",{class:`${t}-list-items`},e.edges.map(b=>v("li",null,c(s(b.from))," to ",c(s(b.to)),b.label?[": ",a(_t(b.label))]:"",`${r(b.kind)}.`)))),i}if(e.type==="flowchart"){const f=i=>(e.byId.get(i)?.i??0)+1;return[v("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const u=e.edges.filter(g=>g.from===i.id),b=i.shape==="decision"?"Decision":i.shape==="terminal"?u.length?"Start":"End":"Step",h=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return v("li",null,l(i),i.detail?[", ",i.mono?a(i.detail):i.detail]:"",`${h}${b}.`,d(i),u.length?v("ul",{class:`${t}-list-exits`},u.map(g=>v("li",null,g.label?`If ${_t(g.label)}: go to ${f(g.to)}, `:`Then: go to ${f(g.to)}, `,c(s(g.to)),r(g.kind)))):null)}))]}if(e.type==="data-flow")return[v("ol",{class:`${t}-list-items`},e.nodes.map(f=>{const i=e.edges.filter(u=>u.from===f.id);return v("li",null,`${f.laneLabel}: `,l(f),f.detail?[", ",f.mono?a(f.detail):f.detail]:"",".",d(f),i.length?[" Then ",...i.flatMap((u,b)=>[b?"; ":"",`to step ${e.byId.get(u.to).step}, `,c(s(u.to)),u.label?[": ",a(_t(u.label))]:"",r(u.kind)]),"."]:"")}))];if(e.type==="sequence"){const f=[o("Participants"),v("ul",{class:`${t}-list-items`},e.nodes.map(u=>v("li",null,c(u.name),u.kind?`, ${u.kind}`:"",".",d(u),Me(e,u))))];f.push(o("Messages"));let i=null;for(const u of e.steps){if("band"in u){i=null,f.push(v(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`},u.band));continue}if("open"in u){i=null,f.push(v(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":u.depth>1?u.depth:void 0},`${e.frameWords[u.open]}: ${u.label}`));continue}if("otherwise"in u){i=null,f.push(v(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":u.depth>1?u.depth:void 0},`${e.frameWords.else}: ${u.otherwise}`));continue}if("close"in u){i=null;continue}i||(i=v("ol",{class:`${t}-list-items`,start:u.n}),f.push(i)),i.c.push(v("li",null,a(u.label),": ",c(s(u.from))," to ",c(s(u.to)),`${r(u.kind)}.`,u.note?` ${Wt(u.note)}`:""))}return f}const p=[];for(const f of e.nodes)p.push(v(`h${n}`,{class:`${t}-list-group`},f.href?v("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},a(f.name)):a(f.name),d(f))),p.push(v("ul",{class:`${t}-list-items`},[...(f.columns??[]).map(i=>v("li",null,a(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",a(`${i.ref.table}.${i.ref.column}`),i.card?[" (",yn(f.id,i.ref.table,i.card,a),")"]:""]:i.type?`, ${i.type}`:"")),...f.more?[v("li",null,`and ${f.more} more ${f.more===1?"column":"columns"}`)]:[]]));return p}function je(t,e=!1){const n=t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step";return`${e&&Jt(t)?`Arrow keys move to the nearest ${n} in that direction`:`Arrow keys move to the next or the previous ${n}, in the author's order`}; Home and End go to the ends; Escape clears the trace.${t.nodes.some(c=>c.href)?" Enter opens a part that is a link.":""}`}function re(t,e=!1){const n=e&&t.type!=="sequence"&&Jt(t)&&t.cols>1&&t.rows>1,o=t.nodes.some(c=>c.href)?[{keys:["Enter"],words:"open"}]:[];return[{keys:n?["←","↑","↓","→"]:["←","→"],words:Se(t)},{keys:["Home","End"],words:"the ends"},...o,{keys:["Esc"],words:"clear"}]}var jn=(t,e)=>{for(let n=0;n({col:e.col,rows:[e.row,e.row2]});function Jt(t){return jt(t,"spatial",()=>{const e=t.nodes.map(l=>({id:l.id,...Rn(t,l)})),n=(l,a)=>{const s=a==="right"||a==="left",r=a==="right"||a==="down",d=b=>s?[b.col,b.col]:b.rows,p=b=>s?b.rows:[b.col,b.col],f=d(l),i=p(l);let u=null;return e.forEach((b,h)=>{if(b===l)return;const g=d(b),k=p(b),M=r?g[0]-f[1]:f[0]-g[1];if(M<1)return;const z=Math.max(0,k[0]-i[1],i[0]-k[1]),w=[z===0?0:1,z===0?M:M+2*z,z,Math.abs(k[0]-i[0]),h];(!u||jn(w,u.rank))&&(u={id:b.id,rank:w})}),u?.id??null},o=Lt();for(const l of e)o[l.id]={right:n(l,"right"),left:n(l,"left"),down:n(l,"down"),up:n(l,"up")};const c=l=>{const a=new Set([l]),s=[l];for(;s.length;)for(const r of Object.values(o[s.pop()]))r&&!a.has(r)&&(a.add(r),s.push(r));return a.size};return e.every(l=>c(l.id)===e.length)?o:null})}function Ut(t){return jt(t,"turn-back-lanes",()=>{const e=new Map,n=new Set;if(!ie(t))return{lane:e,dropped:n,lanes:0};const o=(r,d)=>(t.byId.get(r)?.row??0)*1e3+d,c=new Map;t.edges.forEach((r,d)=>{const p=`${r.to}.${r.toRow}.${r.card?.to??""}`,f=o(r.from,r.fromRow??0),i=o(r.to,r.toRow??0),u=c.get(p)??{members:[],lo:1/0,hi:-1/0};u.members.push(d),u.lo=Math.min(u.lo,f,i),u.hi=Math.max(u.hi,f,i),c.set(p,u)});const l=[...c.values()].sort((r,d)=>d.hi-d.lo-(r.hi-r.lo)),a=[];let s=0;for(const r of l.reverse()){const d=new Set(a.filter(f=>f.lo<=r.hi&&r.lo<=f.hi).map(f=>f.lane));let p=0;for(;d.has(p);)p++;if(p>1){for(const f of r.members)n.add(f);continue}a.push({lo:r.lo,hi:r.hi,lane:p});for(const f of r.members)e.set(f,p);s=Math.max(s,p+1)}return{lane:e,dropped:n,lanes:s}})}var ie=t=>t.type==="schema"&&t.cols===1&&t.edges.length>0;function Xt(t,e,n){const o=n.prefix,c=vn(n.base),l=t.type==="sequence"||t.type==="schema"?null:_e(t),a={P:o,ids:c,level:n.level,plan:l,hidden:n.hiddenClass},s=e.layout==="drawn",r=Rt(t,e),d=t.type==="sequence"||t.type==="schema"?s:!0,p=`h${t.heading}`,f=[`--_cols:${ae(t)}`];if(t.type==="architecture"&&t.groups.length||s&&e.pad){const i=t.type==="architecture"?Ee(t):[0,0,0,0],u=(h,g,k)=>h?h>1?`calc(${h} * var(--basalt-space-${g}))`:`var(--basalt-space-${g})`:k?`var(--basalt-space-${k})`:"0px",b=s&&e.pad?"3":void 0;f.push(`--_gpad:${u(i[0],"8",b)} ${u(i[1],"4")} ${u(i[2],"4",b)} ${u(i[3],"4")}`)}if(l?.gutter&&l.laneCount>2&&f.push(`--_gw:calc(${l.laneCount} * var(--basalt-space-3-5) + var(--basalt-space-3))`),ie(t)){const i=t.marks?"var(--basalt-space-6) + var(--basalt-space-1)":"var(--basalt-space-5)";f.push(`--_gpad:0px ${Ut(t).lanes>1?`calc(${i} + var(--basalt-space-3))`:t.marks?`calc(${i})`:i} 0px 0px`)}return t.type==="schema"&&e.track&&f.push(`--_track:${e.track}px`),v("figure",{class:n.className?`${o} ${n.className}`:o,"aria-labelledby":c.title,"data-type":t.type,"data-cols":ae(t),"data-reach":t.type==="architecture"?Le(t):void 0,"data-gutter":l?.gutter?"":void 0,"data-marks":t.marks?"":void 0,"data-layout":e.layout??(t.unplaced?"stacked":void 0),"data-measured":e.layout?"":void 0,"data-bare":e.bare?"":void 0,"data-motion":t.motion.animated?"animated":void 0,"data-first-visit":t.motion.animated&&t.motion.firstVisit?"":void 0,"data-rtl":t.rtl?"":void 0,"data-viewer":n.viewer?"":void 0,style:f.join(";")},v("div",{class:`${o}-head`},v(p,{id:c.title,class:`${o}-title`},t.title),n.hasSource?v("p",{class:`${o}-source`},{slot:"source"}):null),v("div",{class:`${o}-drawing`,style:s&&e.rows?`--_rows:${e.rows};--_row-gap:0px`:void 0,role:d?"group":void 0,"aria-roledescription":d?"diagram":void 0,"aria-labelledby":d?c.title:void 0,"aria-describedby":d?r?`${c.summary} ${c.keys}`:c.summary:void 0,"data-stops":r?"":void 0},In(a,t,e),t.text?null:v("div",{class:`${o}-ink`,"aria-hidden":"true"}),v("span",{class:`${o}-ruler`,"aria-hidden":"true"})),Oe(o,t),v("p",{class:`${o}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),Rt(t,e)&&t.type!=="sequence"||s&&t.type==="sequence"?v("p",{class:`${o}-tap-hint`,"aria-hidden":"true"},`Tap ${Se(t)} to highlight its lines. Tap it again to clear.`):null,v("div",{class:`${o}-foot`},{slot:"toggle"}),v("div",{id:c.list,class:`${o}-list`,hidden:!e.open},Be(o,t)),v("span",{id:c.keys,class:n.hiddenClass},n.viewer?`${je(t,s)} ${n.viewer}`:je(t,s)),v("figcaption",{id:c.summary,class:`${o}-summary`},{slot:"summary"}))}function Tn(t){const e=getComputedStyle(t),n=(c,l)=>{const a=parseFloat(e.getPropertyValue(`--basalt-${c}`));return Number.isFinite(a)?a:l},o=new Map;return{space:c=>(o.has(c)||o.set(c,n(`space-${c}`,parseFloat(c.replace("-","."))*4)),o.get(c)),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),activation:n("size-diagram-activation",8),foot:n("size-diagram-foot",14)}}var Yt=(t,e)=>t==="main"?e.line:e.hair,Mt=(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}},It=(t,e,n=.01)=>t.le.l+n&&t.te.t+n,le=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function xt(t,e,n){const{l:o,t:c,r:l,b:a}=t.rect,s=(o+l)/2,r=(c+a)/2,d=(l-o)/2,p=(a-c)/2,f=e==="top"||e==="bottom";if(t.shape==="decision"){if(f){const b=n,h=p*Math.max(0,1-Math.abs(b-s)/d);return{x:b,y:e==="top"?r-h:r+h}}const i=n,u=d*Math.max(0,1-Math.abs(i-r)/p);return{x:e==="left"?s-u:s+u,y:i}}if(t.shape==="terminal"){const i=Math.min(d,p);if(f){const g=n,k=Math.min(Math.max(g,o+i),l-i),M=g-k,z=Math.abs(M)>=i?0:Math.sqrt(i*i-M*M);return{x:g,y:Math.abs(M)<1e-6?e==="top"?c:a:e==="top"?r-z:r+z}}const u=n,b=u-r,h=Math.abs(b)>=i?0:Math.sqrt(i*i-b*b);return{x:e==="left"?o+i-h:l-i+h,y:u}}return f?{x:n,y:e==="top"?c:a}:{x:e==="left"?o:l,y:n}}function zn(t,e,n){const{l:o,t:c,r:l,b:a}=e.rect,s=(o+l)/2,r=(c+a)/2,d=(l-o)/2,p=(a-c)/2;if(e.shape==="decision")return Math.abs(t.x-s)/d+Math.abs(t.y-r)/p<1-n/Math.min(d,p);if(e.shape==="terminal"){const f=Math.min(d,p),i=Math.min(Math.max(t.x,o+f),l-f);return Math.hypot(t.x-i,t.y-r)o+n&&t.xc+n&&t.ymatchMedia("(forced-colors: active)").matches;function Fn(t,e){const n=t.querySelector(`.${e}-ruler`),o=new Map;return(c,l)=>{const a=`${l}|${c}`;return o.has(a)||(n.setAttribute("data-f",l),n.textContent=c,o.set(a,n.getBoundingClientRect().width),n.textContent=""),o.get(a)}}var Qt=t=>t?t.split(/\s+/).filter(Boolean):[];function Hn(t,e,n){const o=e.space;let c=e.node,l=e.table;for(const r of t.nodes){if(r.shape==="table"){for(const h of r.columns??[]){const g=h.ref?`${t.rtl?"←":"→"} ${h.ref.table}`:h.type??"",k=o("6")+n(h.name,"mono")+(g?o("3")+n(g,"mono"):0)+2*o("3")+2*e.hair;l=Math.max(l,Math.ceil(k))}l=Math.max(l,Math.ceil(n(r.name,"table")+2*o("3")+2*e.hair+(r.href?16+o("1-5"):0)));continue}const d=r.shape==="terminal"?2*o("5"):2*o("3"),p=r.mark&&!Wn()?(r.shape==="participant"?2:1)*o("6"):0;let f=0;const i=r.href?16+o("1-5"):0,u=Qt(r.name);if(u.forEach((h,g)=>{f=Math.max(f,n(h,r.shape==="decision"?"name-500":"name")+(r.kind?0:p)+(g===u.length-1?i:0))}),t.type!=="data-flow")for(const h of Qt(r.kind))f=Math.max(f,n(h,"mono")+p);for(const h of Qt(r.detail))f=Math.max(f,n(h,r.mono?"mono":"sans"));const b=r.shape==="decision"?f/.62:f+d+2*e.hair;c=Math.max(c,Math.ceil(b))}const a=ae(t);let s;return t.type==="data-flow"?s=e.lane+a*(c+o("12")):t.type==="schema"?s=a*l+(a-1)*(o("12")+(t.marks?o("3"):0))+(ie(t)?(t.marks?o("6")+o("1"):o("5"))+(Ut(t).lanes>1?o("3"):0):0):t.type==="sequence"?s=a*c+(a-1)*o("5"):s=a*c+(a-1)*o("16")+Le(t)*o("4"),{track:c,table:l,least:Math.max(e.wide,s)}}function Te(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 ce(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 ze(t,e,n){const o=t.map(l=>({...l}));for(let l=1;l=2){const r=c[c.length-2];if(Math.abs(r.x-s.x)<.01&&Math.abs(s.x-a.x)<.01||Math.abs(r.y-s.y)<.01&&Math.abs(s.y-a.y)<.01){c[c.length-1]=a;continue}}c.push(a)}}return c}var qt=t=>t.slice(1).map((e,n)=>[t[n],e]);function Pt(t,e,n){const o=[];for(let l=0;lMath.min(h.x,g.x)+.75&&zMath.min(k.y,M.y)+.75&&wl.split(/\s+/).map(parseFloat).filter(a=>Number.isFinite(a)),o=(l,a,s)=>{const r=[];let d=a;for(const p of l)r.push([d,d+p]),d+=p+s;return r},c=o(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0);return{cols:o(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:t.style.getPropertyValue("--_rows").trim()?c.filter((l,a)=>a%2===1):c}}var ht=t=>t==="left"||t==="right",Ne={top:"bottom",bottom:"top",left:"right",right:"left"};function de(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 We(t,e,n){const o=[];t.edges.forEach((l,a)=>{const s=t.byId.get(l.from),r=t.byId.get(l.to),[d,p]=e[a],f=s.row===r.row&&ht(d)&&ht(p)&&d===Ne[p]||s.col===r.col&&!ht(d)&&!ht(p)&&d===Ne[p];o.push({edge:a,end:"from",node:s,side:d,far:r,straight:f,f:.5},{edge:a,end:"to",node:r,side:p,far:s,straight:f,f:.5})});const c=new Map;for(const l of o){const a=`${l.node.id}.${l.side}`;c.has(a)||c.set(a,[]),c.get(a).push(l)}for(const[l,a]of c){if(a[0].node.shape==="decision")continue;const s=h=>ht(h.side)?h.far.row-h.node.row:h.far.col-h.node.col,r=a.filter(h=>h.straight),d=a.filter(h=>!h.straight);if(d.sort((h,g)=>s(h)-s(g)||(ht(h.side)?h.far.col-g.far.col:h.far.row-g.far.row)*(s(h)<0?1:-1)),a.length>3&&n(`${l.replace(".","'s ")} side has ${a.length} lines; more than three is an error: use another side`),!r.length){d.length===2?(d[0].f=.25,d[1].f=.75):d.length===3?(d[0].f=.25,d[1].f=.5,d[2].f=.75):d.length>3&&d.forEach((h,g)=>{h.f=(g+1)/(d.length+1)});continue}const p=new Map;for(const h of r)p.has(h.far.id)||p.set(h.far.id,[]),p.get(h.far.id).push(h);for(const h of p.values())h.length>1&&h.sort((g,k)=>g.edge-k.edge).forEach((g,k)=>{g.f=h.length===2?k===0?.25:.75:(k+1)/(h.length+1)});const f=Math.min(...r.map(h=>h.f)),i=Math.max(...r.map(h=>h.f)),u=d.filter(h=>s(h)<0),b=d.filter(h=>s(h)>=0);u.forEach((h,g)=>{h.f=f*(g+1)/(u.length+1)}),b.forEach((h,g)=>{h.f=i+(1-i)*(g+1)/(b.length+1)})}return o}function Fe(t,e=8,n=8){return jt(t,`port-floors:${e}:${n}`,()=>{const o=Lt();if(t.type!=="architecture"&&t.type!=="flowchart"&&t.type!=="data-flow")return o;const c=t.edges.map(a=>{const s=t.byId.get(a.from),r=t.byId.get(a.to),[d,p]=de(s,r);return[a.fromSide??d,a.toSide??p]}),l=new Map;for(const a of We(t,c,()=>{})){if(!ht(a.side)||a.node.shape!=="box")continue;const s=`${a.node.id}.${a.side}`;l.has(s)||l.set(s,[]),l.get(s).push(a.f)}for(const[a,s]of l){if(s.length<2)continue;const r=s.slice().sort((f,i)=>f-i).filter((f,i,u)=>i===0||f-u[i-1]>1e-9);let d=Math.max(e/r[0],e/(1-r[r.length-1]));for(let f=1;f{const a=t.byId.get(l.dataset.node);a&&c.set(a.id,{id:a.id,rect:Mt(l,n),shape:a.shape,i:a.i})}),c}function Ge(t,e){const n=e.head,o=e.head/2,{x:c,y:l}=t.tip;return t.dir==="down"?{l:c-o,r:c+o,t:l-n,b:l}:t.dir==="up"?{l:c-o,r:c+o,t:l,b:l+n}:t.dir==="right"?{l:c-n,r:c,t:l-o,b:l+o}:{l:c,r:c+n,t:l-o,b:l+o}}var Ve=(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 Ke(t,e,n,o){const c=(l,a)=>{const s=l+a-Math.floor(l+a);return s<.005||s>.995?[0]:s<=.5?[-s,1-s]:[1-s,-s]};for(const l of c(t.t,n))for(const a of c(t.l,e)){if(!a&&!l)return t;const s={l:t.l+a,r:t.r+a,t:t.t+l,b:t.b+l};if(o(s))return s}return t}function Gn(t,e,n,o,c,l,a,s,r){const d=a.space,p=[],f=[],i=[],u=[],b=d("1"),h=e.filter(g=>t.edges[g.i]?.label).sort((g,k)=>+(t.edges[k.i].kind==="main")-+(t.edges[g.i].kind==="main")||g.i-k.i);for(const g of h){const k=t.edges[g.i].label,M=s(k,"label"),z=16*Vt(k),w=g.pts.length-2,q=[];qt(g.pts).forEach(([E,G],R)=>{const C=Math.abs(E.y-G.y)<.01,W=C?E.x:E.y;let T=C?G.x:G.y;const K=Math.sign(T-W)||1;R===w&&(T-=K*a.head);let U=[[W,T]];for(const J of c)for(const Z of C?[J.l,J.r]:[J.t,J.b]){const Q=C?E.y:E.x;(C?Q>J.t&&QJ.l&&QZ>Math.min($,S)+1&&Z{const Q=(J+Z)/2,m=C?{x:Q,y:E.y}:{x:E.x,y:Q};return!c.some($=>m.x>$.l&&m.x<$.r&&m.y>$.t&&m.y<$.b)},X=g.axes?.[R]??(C?E.y:E.x);for(const[J,Z]of U)q.push({horiz:C,c:X,p:J,q:Z,len:Math.abs(Z-J),pri:U.length>1&&st(J,Z)?1:0})}),q.sort((E,G)=>G.pri-E.pri||G.len-E.len);let O=null,N=!1;const D=(E,G=!0)=>{const R=le(E,b);return G&&(E.ll.r||E.tl.b)||n.some(C=>Re(R,C))||p.some(C=>It(R,C))||o.heads.some(C=>It(R,C))||o.rects.some(C=>It(R,C))?!1:!e.some(C=>C.i!==g.i&&qt(C.pts).some(([W,T])=>It(R,Ve(W,T,C.width))))};for(const E of q){for(const G of[1/2,1/3,2/3]){const R=E.p+(E.q-E.p)*G,C=[],W=d("2")+g.width/2;if(E.horiz?(E.len>=M+2*d("1")+d("3-5")&&C.push({box:{l:R-M/2-d("1"),r:R+M/2+d("1"),t:E.c-z/2,b:E.c+z/2},on:!0}),C.push({box:{l:R-M/2,r:R+M/2,t:E.c-W-z,b:E.c-W},on:!1}),C.push({box:{l:R-M/2,r:R+M/2,t:E.c+W,b:E.c+W+z},on:!1})):(E.len>=z+d("3")&&C.push({box:{l:E.c-M/2-d("1"),r:E.c+M/2+d("1"),t:R-z/2,b:R+z/2},on:!0}),C.push({box:{l:E.c+W,r:E.c+W+M,t:R-z/2,b:R+z/2},on:!1}),C.push({box:{l:E.c-W-M,r:E.c-W,t:R-z/2,b:R+z/2},on:!1})),O=C.find(T=>D(T.box))??null,O)break;!N&&C.some(T=>D(T.box,!1))&&(N=!0)}if(O)break}if(!O){i.push(g.i),N&&u.push(g.i);continue}const dt=Ke(O.box,r.ox,r.oy,E=>D(E));p.push(dt),f.push({i:g.i,text:k,box:dt,on:O.on})}return{labels:f,unseated:i,bounded:u}}function Ze(t,e,n,o){const c=[],l=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(a=>{if(a.getClientRects().length===0||getComputedStyle(a).display==="contents")return;const s=Mt(a,e);l.push(s),c.push({l:s.l,r:s.r,t:s.t,b:s.t+1},{l:s.l,r:s.r,t:s.b-1,b:s.b},{l:s.l,r:s.l+1,t:s.t,b:s.b},{l:s.r-1,r:s.r,t:s.t,b:s.b});const r=a.querySelector(`:scope > .${n}-glabel`);r&&r.getClientRects().length&&c.push(Mt(r,e))}),t.querySelectorAll(`.${n}-lane`).forEach((a,s)=>{if(!a.getClientRects().length)return;const r=Mt(a,e);s>0&&c.push({l:r.l,r:r.r,t:r.t-o/2-.5,b:r.t-o/2+.5});const d=a.querySelector(`.${n}-lane-name`);d&&c.push(Mt(d,e))}),{obstacles:{rects:c,heads:[]},groups:l}}function Je(t,e){const{m:o,tk:c,P:l,drawing:a,origin:s,warn:r}=t,d=c.space,p=De(o,a,s,l),f=[...p.values()],i=Dn(a),u=s.left-Math.floor(s.left),b=s.top-Math.floor(s.top),h=Te(u,b),g=a.clientWidth,k=a.clientHeight,M=y=>o.type==="data-flow"?y.col+1:y.col,z=parseFloat(getComputedStyle(a).rowGap)||0,w={w:g,h:k,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:u,oy:b};if(o.type==="sequence")return Kn(t,w,h);let q,O=[];o.type==="schema"?q=o.edges.map(y=>{const A=o.byId.get(y.from),_=o.byId.get(y.to);if(A.col===_.col){const x=A.col===o.cols&&o.cols>1?"left":"right";return[x,x]}return _.col>A.col?["right","left"]:["left","right"]}):(q=o.edges.map(y=>{const A=o.byId.get(y.from),_=o.byId.get(y.to),[x,L]=de(A,_);return[y.fromSide??x,y.toSide??L]}),O=We(o,q,r||(()=>{})));const N=(y,A)=>{const _=a.querySelector(`.${l}-node[data-node="${CSS.escape(y)}"] .${l}-row[data-row="${A}"]`);if(!_)return 0;const x=Mt(_,s);return(x.t+x.b)/2},D=new Map;if(o.type==="schema"){const y=new Map;o.edges.forEach((_,x)=>{const L=`${_.to}.${_.toRow}.${q[x][1]}`;y.set(L,[...y.get(L)??[],x])});const A=_=>{const x=o.edges[_].card?.to;return x==="one"?0:x==="zero-or-one"?1:2};for(const _ of y.values()){const x=[...new Set(_.map(A))].sort((L,H)=>L-H);if(x.length>1)for(const L of _)D.set(L,(x.indexOf(A(L))-(x.length-1)/2)*d("2"))}}const dt=y=>Math.round(y+u)-u,E=o.edges.map((y,A)=>{const[_,x]=q[A],L=p.get(y.from),H=p.get(y.to),P=Yt(y.kind,c);if(y.fk){const et=N(y.from,y.fromRow),at=N(y.to,y.toRow)+(D.get(A)??0),$t=h.y(et,P),Ct=h.y(at,P),Et=_==="right"?L.rect.r:L.rect.l,kt=x==="right"?H.rect.r:H.rect.l;return{p1:{x:y.card?dt(Et):Et,y:$t},p2:{x:y.card?dt(kt):kt,y:Ct},r1:et,r2:Math.abs($t-Ct)<.01?et:at}}const ot=O.find(et=>et.edge===A&&et.end==="from").f,ct=O.find(et=>et.edge===A&&et.end==="to").f;let it=He(L,_,ot),rt=He(H,x,ct);const F=ht(_)?it.y:it.x;let V=ht(x)?rt.y:rt.x;return ht(_)?it={...it,y:h.y(it.y,P)}:it={...it,x:h.x(it.x,P)},ht(x)?rt={...rt,y:h.y(rt.y,P)}:rt={...rt,x:h.x(rt.x,P)},ht(_)&&ht(x)&&Math.abs(it.y-rt.y)<1.01&&(rt={...rt,y:it.y},V=F),!ht(_)&&!ht(x)&&Math.abs(it.x-rt.x)<1.01&&(rt={...rt,x:it.x},V=F),it=ht(_)?xt(L,_,it.y):xt(L,_,it.x),rt=ht(x)?xt(H,x,rt.y):xt(H,x,rt.x),{p1:it,p2:rt,r1:F,r2:V}}),G=new Set,R=(y,A)=>{G.has(y)||(G.add(y),r?.(`${o.edges[y].from} to ${o.edges[y].to} ${A}, so its line is not drawn; its row still writes the target`))};for(const y of Ut(o).dropped)R(y,"would need a third lane of turn-backs");const C=new Map,W=Lt();o.type==="schema"&&o.edges.forEach((y,A)=>{const _=o.byId.get(y.from),x=o.byId.get(y.to);if(Math.abs(_.col-x.col)<2)return;const L=Math.min(_.col,x.col),H=Math.max(_.col,x.col),P=o.nodes.filter(at=>at.col>L&&at.col$t.row<=at&&$t.row2>=at+1)||ct.push({key:`g${at}`,y:(ot[at-1][1]+ot[at][0])/2,inner:!0});ct.push({key:"top",y:ot[0][0]-d("4"),inner:!1},{key:"bottom",y:ot[ot.length-1][1]+d("4"),inner:!1});const it=(E[A].r1+E[A].r2)/2,rt=t.pick?.[A]??ct.slice().sort((at,$t)=>Math.abs(at.y-it)-Math.abs($t.y-it)||Number($t.inner)-Number(at.inner)||at.y-$t.y)[0].key;W[A]=rt;const F=q[A][0]==="right"?_.col:_.col-1,V=i.cols[F-1],et=i.cols[F];C.set(A,{corridor:rt,first:V&&et?{key:`c${F}`,span:[V[1],et[0]]}:null,y:0})});const T=new Map;for(const[y,A]of C){const _=o.edges[y],x=T.get(A.corridor)??[],L=x.find(H=>{const P=o.edges[H[0]];return P.to===_.to&&P.toRow===_.toRow&&q[H[0]][1]===q[y][1]&&Math.abs(E[H[0]].p2.y-E[y].p2.y)<.5});L?L.push(y):x.length>=2?R(y,"would need a third lane in its corridor"):x.push([y]),T.set(A.corridor,x)}for(const y of[...C.keys()])G.has(y)&&C.delete(y);const K=y=>{const A=o.edges[y[0]];return Math.abs(o.byId.get(A.from).col-o.byId.get(A.to).col)*1e4+Math.abs(E[y[0]].p1.x-E[y[0]].p2.x)},U=(y,A,_)=>{const x=i.rows;if(y==="top")return x[0][0]-d("4")-A*d("3");if(y==="bottom")return x[x.length-1][1]+d("4")+A*d("3");const L=Number(y.slice(1));return(x[L-1][1]+x[L][0])/2+(A-(_-1)/2)*d("3")},st=(y,A)=>A.forEach((_,x)=>_.forEach(L=>{C.get(L).y=U(y,x,A.length)})),X=()=>{for(const[y,A]of T){const _=A.map(x=>x.filter(L=>C.has(L))).filter(x=>x.length);T.set(y,_),st(y,y==="top"||y==="bottom"?_.slice().sort((x,L)=>K(x)-K(L)):_.slice().sort((x,L)=>K(L)-K(x)))}};X();const J=new Map,Z=new Set,Q=new Map,m=(y,A,_,x,L)=>{J.has(y)||J.set(y,{span:A,vertical:_,members:new Map});const H=J.get(y);H.members.has(x)||H.members.set(x,[]),H.members.get(x).push(L)},$=()=>{J.clear(),Z.clear(),Q.clear(),o.edges.forEach((y,A)=>{if(G.has(A))return;const _=C.get(A);_?.first&&m(_.first.key,_.first.span,!0,`far:${A}`,-(A+1));const[x,L]=q[A],{p1:H,p2:P}=E[A],ot=o.byId.get(y.from),ct=o.byId.get(y.to);let it=null,rt=null,F=!1;if(x===L){if(ht(x)){const V=x==="right"?Math.max(M(ot),M(ct)):Math.min(M(ot),M(ct))-1,et=i.cols[V-1],at=i.cols[V];et&&at&&(it=`c${V}`,rt=[et[1],at[0]],F=!0)}else{const V=x==="bottom"?Math.max(ot.row2,ct.row2):Math.min(ot.row,ct.row)-1,et=i.rows[V-1],at=i.rows[V];et&&at&&(it=`r${V}`,rt=[et[1],at[0]],F=!1)}it&&Z.add(A)}else if(ht(x)&&ht(L)&&(_||Math.abs(H.y-P.y)>.5)){const V=M(ct),et=L==="left",at=i.cols[(et?V-1:V)-1],$t=i.cols[(et?V:V+1)-1];at&&$t&&(it=`c${et?V-1:V}`,rt=[at[1],$t[0]],F=!0)}else if(!ht(x)&&!ht(L)&&Math.abs(H.x-P.x)>.5){const et=L==="top"?ct.row-1:ct.row2,at=i.rows[et-1],$t=i.rows[et];at&&$t&&(it=`r${et}`,rt=[at[1],$t[0]],F=!1)}!it||!rt||(_&&Q.set(A,rt),m(it,rt,F,`${y.to}.${L}.${Math.round(F?P.y:P.x)}`,A))})};$();const S=new Map,B=y=>{const[A,_]=q[y],{p1:x,p2:L}=E[y],H=C.get(y);if(H){const P=Q.get(y),ot=S.get(-(y+1))??(H.first?(H.first.span[0]+H.first.span[1])/2:x.x),ct=S.get(y)??(P?(P[0]+P[1])/2:L.x);return[x,{x:ot,y:x.y},{x:ot,y:H.y},{x:ct,y:H.y},{x:ct,y:L.y},L]}if(ht(A)&&ht(_)){if(A===_){const ot=d(o.marks?"6":"4")+(o.type==="schema"&&o.cols===1?(Ut(o).lane.get(y)??0)*d("3"):0),ct=S.get(y)??(A==="right"?Math.max(x.x,L.x)+ot:Math.min(x.x,L.x)-ot);return[x,{x:ct,y:x.y},{x:ct,y:L.y},L]}if(Math.abs(x.y-L.y)<=.5)return[x,{x:L.x,y:x.y}];const P=S.get(y)??(x.x+L.x)/2;return[x,{x:P,y:x.y},{x:P,y:L.y},L]}if(!ht(A)&&!ht(_)){if(A===_){const ot=S.get(y)??(A==="bottom"?Math.max(x.y,L.y)+d("4"):Math.min(x.y,L.y)-d("4"));return[x,{x:x.x,y:ot},{x:L.x,y:ot},L]}if(Math.abs(x.x-L.x)<=.5)return[x,{x:x.x,y:L.y}];const P=S.get(y)??(x.y+L.y)/2;return[x,{x:x.x,y:P},{x:L.x,y:P},L]}return ht(A)?[x,{x:L.x,y:x.y},L]:[x,{x:x.x,y:L.y},L]},I=y=>{const A=o.edges[y],_=Yt(A.kind,c),x=B(y),L=ze(x,_,h);let H;return x.length===L.length&&(H=qt(x).map(([P,ot])=>Math.abs(P.y-ot.y)<.75?(P.y+ot.y)/2:(P.x+ot.x)/2),H[0]=E[y].r1,H.length>1&&(H[H.length-1]=E[y].r2)),{i:y,from:A.from,to:A.to,kind:A.kind,pts:L,tip:L[L.length-1],dir:ce(L),dot:A.fk&&!A.card?L[0]:void 0,card:A.card,width:_,axes:H}},j=()=>o.edges.flatMap((y,A)=>G.has(A)?[]:[I(A)]);let tt=null;const Y=y=>{tt??(tt=j());const A=tt.map(_=>y.has(_.i)?I(_.i):_);return{lines:A,score:Vn(A,y)*1e5+Pt(A,void 0,y).length*1e3+ue(A.filter(_=>y.has(_.i)),f,o).length}},mt=(y,A)=>{const _=y.flatMap(x=>{const L=x<0?-x-1:x,{p1:H,p2:P}=E[L],ot=C.get(L);return ot?x<0?[H.y,ot.y]:[ot.y,P.y]:A?[H.y,P.y]:[H.x,P.x]});return[Math.min(..._),Math.max(..._)]},nt=y=>y<0?-y-1:y,lt=y=>{const A=[...y.members.values()].map(x=>({members:x,run:mt(x,y.vertical)})).sort((x,L)=>x.run[0]-L.run[0]),_=[];for(const x of A){const L=_[_.length-1];L&&L.some(H=>H.run[0]!(x.length===1&&x[0].members.every(L=>Z.has(L))))},ft=y=>(A,_)=>y[A].run[0]{const A=ft(y),_=[];return y.forEach((x,L)=>{let H=0;for(;_.some((P,ot)=>P===H&&A(L,ot));)H++;_.push(H)}),_},wt=y=>Math.max(0,...yt(y))+1;if(o.marks)for(let y=0;y3){A=H.map(P=>P.members.map(nt));break}if(!A)break;const _=L=>Math.max(...L),x=A.filter(L=>L.some(H=>C.has(H))).sort((L,H)=>_(H)-_(L))[0]??A.slice().sort((L,H)=>_(H)-_(L))[0];for(const L of x)R(L,"would need a fourth lane in a marked gutter"),C.delete(L);$()}const vt=(y,A,_)=>{const x=y[1]-y[0];if(!o.marks)return y[0]+x/(_+1)*(A+1);const L=c.foot+c.radiusXs,H=_>1?Math.min(x/(_+1),(x-2*L)/(_-1)):0;return(y[0]+y[1])/2+(A-(_-1)/2)*H};X();for(const[y,A]of T){if(y==="top"||y==="bottom"||A.length<2)continue;const _=new Set(A.flat());let x=A,L=1/0;for(const H of fe(A.slice().sort((P,ot)=>K(ot)-K(P)))){st(y,H),tt=null;const P=Y(_);P.scorect.members);if(o.marks){const ct=wt(A),it=ft(A),rt=A.length,F=new Set(_.flat().map(nt)),V=Et=>Et.forEach((kt,Tt)=>_[Tt].forEach(Bt=>S.set(Bt,vt(y.span,kt,ct))));let et=yt(A),at=1/0,$t=null;const Ct=[et];if(ct**rt<=729)for(let Et=0;EtMath.floor(Et/ct**Bt)%ct);kt.every((Tt,Bt)=>kt.every((ee,Gt)=>Gt<=Bt||Tt!==ee||!it(Bt,Gt)))&&Ct.push(kt)}for(const Et of Ct){V(Et);const kt=Y(F);kt.scorert.forEach(V=>S.set(V,vt(y.span,F,x))));const it=Y(L);it.scorect.forEach(rt=>S.set(rt,vt(y.span,it,x)))),tt=ot}if(w.lines=j(),o.marks&&(w.lines=w.lines.filter(y=>{if(!y.card)return!0;const A=qt(y.pts),_=([L,H])=>Math.hypot(H.x-L.x,H.y-L.y),x=A.length===1?2*c.foot:c.foot+c.radiusXs-.5;return _(A[0])>=x&&_(A[A.length-1])>=x?!0:(R(y.i,"has no room for its marks at an end"),C.delete(y.i),!1)})),C.size){const y=new Set([...C.values()].map(_=>_.corridor)),A=[y.has("top")?"var(--basalt-space-8)":"0px"];for(let _=1;_<=o.rows;_++)A.push("auto",_Ge(y,c));const ut=Gn(o,w.lines,f,St,pt,{l:0,t:0,r:g,b:k},c,e,{ox:u,oy:b});return w.labels=ut.labels,w.unseated=ut.unseated,w.bounded=ut.bounded,w.overlaps=[...new Set(Ue(w.lines,null).flat())],w}function Vn(t,e){return Ue(t,e).length}function Ue(t,e){const n=[];for(let o=0;o=s)continue;const[g,k]=i?[r.x,d.x]:[r.y,d.y],[M,z]=i?[p.x,f.x]:[p.y,f.y];Math.min(Math.max(g,k),Math.max(M,z))-Math.max(Math.min(g,k),Math.min(M,z))>1&&n.push([l.i,a.i])}}return n}function*fe(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e{const r=s===l.pts.length-1?Math.max(l.width/2,o.head/2):l.width/2;return a.x-r<-.5||a.x+r>e+.5||a.y-r<-.5||a.y+r>n+.5})&&c.push(l.i);return c}function ue(t,e,n){const o=[];for(const c of t){const l=qt(c.pts);e.some(a=>l.some(([s,r])=>Nn(s,r,a)))&&o.push(c.i)}return o}function Kn(t,e,n){const{m:o,tk:c,P:l,drawing:a,origin:s}=t,r=c.space,d=new Map;a.querySelectorAll(`.${l}-node`).forEach(w=>d.set(w.dataset.node,Mt(w,s)));const p=a.querySelector(`.${l}-steps`),f=p?Mt(p,s).b:e.h,i=w=>{const q=d.get(w);return q?n.x((q.l+q.r)/2,c.hair):0};for(const w of o.nodes){const q=d.get(w.id);q&&e.lifelines.push({x:i(w.id),y1:q.b,y2:f})}const u=w=>d.get(w.id),b=new Map;a.querySelectorAll(`.${l}-msg`).forEach(w=>{const q=Mt(w,s);b.set(Number(w.querySelector(`.${l}-num`)?.textContent??0),(q.t+q.b)/2)});const h=c.activation,g=h/2,k=w=>{const q=o.byId.get(w.who);if(!q)return null;const O=i(w.who),D=(q.i===o.nodes.length-1&&o.nodes.length>1?-1:1)*(o.rtl?-1:1),dt=(w.depth-1)*r("1")*D,E=b.get(w.from)??0,G=b.get(w.to)??E,R=w.from===w.to;return{l:n.x(O-g+dt,c.hair),r:n.x(O+g+dt,c.hair),t:n.y(R?E-r("2")-r("1"):E,c.hair),b:n.y(R?E+r("2")+r("1"):G,c.hair)}},M=o.bars.map(w=>({bar:w,rect:k(w)})).filter(w=>w.rect);e.bars=M.map(w=>w.rect);const z=(w,q,O)=>M.filter(({bar:N})=>N.who===w&&N.to>=q&&(O?N.from<=q:N.fromD.bar.depth-N.bar.depth)[0]?.rect;a.querySelectorAll(`.${l}-msg`).forEach(w=>{const q=w.dataset.from,O=w.dataset.to,N=w.dataset.kind??"plain",D=Yt(N,c),dt=Mt(w,s),E=n.y((dt.t+dt.b)/2,D),G=Number(w.querySelector(`.${l}-num`)?.textContent??0);let R=i(q),C=i(O),W;if(q===O){const Z=w.dataset.self==="start"?-r("6"):r("6"),Q=z(q,G,!0),m=Q?Z>0?Q.r:Q.l:R,$=n.y(E-r("2"),D),S=n.y(E+r("2"),D);W=[{x:m,y:$},{x:n.x(R+Z,D),y:$},{x:n.x(R+Z,D),y:S},{x:m,y:S}]}else{const Z=C>R?1:-1,Q=z(q,G,!1),m=z(O,G,!0);Q&&(R=Z>0?Q.r:Q.l),m&&(C=Z>0?m.l:m.r),W=[{x:R,y:E},{x:C,y:E}]}e.lines.push({i:G,from:q,to:O,kind:N,pts:W,tip:W[W.length-1],dir:ce(W),width:D});const T=w.querySelector(`.${l}-said`),K=w.querySelector(`.${l}-note`),U=o.byId.get(q),st=o.byId.get(O);if(!U||!st)return;const X=q===O?(()=>{const Z=o.nodes.find(m=>m.col===U.col+(w.dataset.self==="start"?-1:1)),Q=Z?i(Z.id):w.dataset.self==="start"?0:e.w;return Math.abs(Q-R)-r("6")-r("2-5")-r("2")})():Math.abs(C-R)-2*r("2");Math.max(T?T.getBoundingClientRect().width:0,K?K.getBoundingClientRect().width:0)>X+.5&&e.unseated.push(G)}),a.querySelectorAll(`.${l}-fhead`).forEach(w=>{const q=w.parentElement?.querySelector(`:scope > .${l}-fbox`);if(!q)return;[...w.children].reduce((N,D)=>N+D.getBoundingClientRect().width,0)+r("3")>q.getBoundingClientRect().width+.5&&(e.misfit??(e.misfit=[])).push(`the frame "${w.querySelector(`.${l}-flabel`)?.textContent??""}" is wider than its participants`)});{const w=[...a.querySelectorAll(`.${l}-fbox`)].flatMap(q=>{const O=Mt(q,s);return[{x:O.l+.5,t:O.t,b:O.b},{x:O.r-.5,t:O.t,b:O.b}]});w.length&&a.querySelectorAll(`.${l}-said, .${l}-note, .${l}-band > span`).forEach(q=>{if(!q.getClientRects().length)return;const O=le(Mt(q,s),r("1"));w.some(N=>O.lN.x&&O.tN.t)&&(e.misfit??(e.misfit=[])).push(`"${q.textContent?.trim()??""}" would lie on a frame's side`)})}return e}function Ye(t,e,n,o=Lt()){const{m:c,tk:l,P:a,drawing:s,origin:r}=t,d=l.space,p=De(c,s,r,a),f=[...p.values()],i=r.left-Math.floor(r.left),u=r.top-Math.floor(r.top),b=Te(i,u),h=s.clientWidth,g=s.clientHeight,k={w:h,h:g,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:i,oy:u},M=Lt();if(c.type==="sequence"||c.type==="schema")return{geo:k,grow:M};const z=h-(parseFloat(getComputedStyle(s).paddingRight)||0),w=(T,K,U)=>{const st=[T];for(let X=1;X<=(Ot(o,K)??0);X++)st.push({...T,t:T.t+U*d("4")*X,b:T.b+U*d("4")*X});return st},q=new Map;s.querySelectorAll(`.${a}-node`).forEach(T=>{const K=T.parentElement,U=Mt(K,r),st=getComputedStyle(K);q.set(T.dataset.node,U.r-(parseFloat(st.paddingRight)||0)-(parseFloat(st.borderRightWidth)||0))});const O=c.nodes,N=T=>p.get(O[T].id),D=T=>{const K=s.querySelector(`.${a}-node[data-node="${CSS.escape(T)}"]`),U=K?.parentElement;return!!(U?.matches(`.${a}-group[data-turn]`)&&U.querySelector(`:scope > .${a}-node`)===K)},dt=(T,K,U)=>D(K)?Array.from({length:Math.round(U/16)+1},(st,X)=>({...T,t:T.t-X*d("4"),b:T.b-X*d("4")})):[T],E=[],G=T=>Yt(c.edges[T].kind,l);c.edges.forEach((T,K)=>{const U=n.routes[K],st=p.get(T.from),X=p.get(T.to),J=G(K);let Z=[];const Q=T.label,m=Q?e(Q,"label"):0,$=Q?16*Vt(Q):16,S=d("4");if(U==="down"||U==="up"){const I=Math.max(st.rect.l,X.rect.l),j=Math.min(st.rect.r,X.rect.r),tt=c.edges.map((lt,ft)=>({o:lt,j:ft})).filter(({o:lt,j:ft})=>(n.routes[ft]==="down"||n.routes[ft]==="up")&&(lt.from===T.from&<.to===T.to||lt.from===T.to&<.to===T.from)),Y=tt.findIndex(lt=>lt.j===K),mt=tt.length<2?.5:tt.length===2?Y===0?.25:.75:(Y+1)/(tt.length+1),nt=b.x(I+(j-I)*mt,J);if(Z=U==="down"?[xt(st,"bottom",nt),xt(X,"top",nt)]:[xt(st,"top",nt),xt(X,"bottom",nt)],Q){let lt=Math.min(Z[0].y,Z[1].y),ft=Math.max(Z[0].y,Z[1].y);U==="down"?ft-=l.head:lt+=l.head;const yt=[...s.querySelectorAll(`.${a}-group`)].map(pt=>Mt(pt,r));let wt=[[lt,ft]];for(const pt of yt)for(const ut of[pt.t,pt.b])wt=wt.flatMap(([y,A])=>ut>y+1&&utyt.some(y=>(pt+ut)/2>y.t&&(pt+ut)/2y.l&&nt1){const pt=wt.filter(([y,A])=>!vt(y,A));[lt,ft]=(pt.length?pt:wt).reduce((y,A)=>A[1]-A[0]>y[1]-y[0]?A:y)}const St=[1/2,1/3,2/3].map(pt=>{const ut=lt+(ft-lt)*pt;return{l:nt-m/2-d("1"),r:nt+m/2+d("1"),t:ut-$/2,b:ut+$/2}});E.push({k:K,cands:St,on:!0,card:U==="down"?T.to:T.from})}}else if(U==="trunk"||U==="rail"){const I=b.x(Math.max(st.rect.l,U==="rail"?X.rect.l:st.rect.l)+d(U==="trunk"?"8":"3"),J),j=xt(st,"bottom",I);if(U==="rail"){if(Z=[j,xt(X,"top",I)],Q){const tt=X.rect.t-d("6");E.push({k:K,cands:w({l:I+d("2-5"),r:I+d("2-5")+m,t:tt-$/2,b:tt+$/2},T.to,-1),on:!1,card:T.to})}}else{const tt=b.x(X.rect.l+d("6"),J),Y=b.y(X.rect.t-S,J);Z=[j,{x:I,y:Y},{x:tt,y:Y},xt(X,"top",tt)],Q&&E.push({k:K,cands:[...dt({l:tt+d("2-5"),r:tt+d("2-5")+m,t:Y-$/2,b:Y+$/2},T.to,$),...w({l:tt+d("2-5"),r:tt+d("2-5")+m,t:Y-$/2,b:Y+$/2},T.to,-1).slice(1)],on:!1,card:T.to})}}else{const I=Math.min(q.get(T.from)??h,q.get(T.to)??h),j=b.x(n.gutter?z+(n.lanes[K]+1)*d("3-5"):I-d("2-5"),J),tt=b.y(st.rect.t+(st.rect.b-st.rect.t)*n.exits[K],J),Y=xt(st,"right",tt),mt=U==="end-down",nt=c.edges.map((ut,y)=>({o:ut,j:y})).filter(({o:ut,j:y})=>n.routes[y]===U&&ut.to===T.to).sort((ut,y)=>n.lanes[y.j]-n.lanes[ut.j]||ut.j-y.j),lt=Math.max(0,nt.findIndex(({j:ut})=>ut===K)),ft=X.rect.r-d("6")-lt*d("3"),yt=X.rect.r-d("6")-(nt.length-1)*d("3"),wt=b.x(ft,J),vt=mt?X.rect.t-S-lt*d("5"):X.rect.b+S+lt*d("5"),St=b.y(vt,J);Z=[Y,{x:j,y:Y.y},{x:j,y:St},{x:wt,y:St},xt(X,mt?"top":"bottom",wt)];const pt=mt?T.to:O[X.i+1]?.id??T.to;Q&&E.push({k:K,cands:[...mt?dt({l:yt-d("2-5")-m,r:yt-d("2-5"),t:vt-$/2,b:vt+$/2},pt,$):[{l:yt-d("2-5")-m,r:yt-d("2-5"),t:vt-$/2,b:vt+$/2}],...w({l:yt-d("2-5")-m,r:yt-d("2-5"),t:vt-$/2,b:vt+$/2},pt,mt?-1:1).slice(1)],on:!1,card:pt})}const B=ze(Z,J,b);k.lines.push({i:K,from:T.from,to:T.to,kind:T.kind,pts:B,tip:B[B.length-1],dir:ce(B),width:J})}),k.crossings=Pt(k.lines),k.through=ue(k.lines,f,c),k.outside=Xe(k.lines,h,g,l);const{obstacles:R}=Ze(s,r,a,0);R.heads=k.lines.map(T=>Ge(T,l));const C=[],W={l:0,t:0,r:h,b:g};for(const T of E){const K=X=>{const J=le(X,d("1"));return X.lW.r+.5||X.tW.b+.5||f.some(Z=>Re(J,Z))||C.some(Z=>It(J,Z))||R.heads.some(Z=>It(J,Z))||R.rects.some(Z=>It(J,Z))||k.lines.some(Z=>Z.i!==T.k&&qt(Z.pts).some(([Q,m])=>It(J,Ve(Q,m,Z.width))))},U=T.cands.find(X=>!K(X));U||(M[T.card]=(M[T.card]??0)+1,k.unseated.push(T.k));const st=U?Ke(U,i,u,X=>!K(X)):T.cands[0];C.push(st),k.labels.push({i:T.k,text:c.edges[T.k].label,box:st,on:T.on})}return{geo:k,grow:M}}function Qe(t,e,n=0){const o=a=>String(Math.round(a*100)/100);let c=`M${o(t[0].x)} ${o(t[0].y)}`;for(let a=1;a{const{crow:G,ring:R}=qe(N,D.x,D.y,dt,n.head,n.dot);return`${R?``:""}`};return`${O(e.card.from,w,Math.sign(q.x-w.x)||1,"from")}${O(e.card.to,e.tip,-l.x||1,"to")}`}const a=e.kind==="dashed",s=n.head,r=n.head/2,d=a?1:s-1,p=e.pts.map(w=>({...w})),f=p[p.length-1];f.x-=l.x*d,f.y-=l.y*d;const i=e.tip.x-l.x*s,u=e.tip.y-l.y*s,b=-l.y*r,h=l.x*r,g=w=>Math.round(w*100)/100,k=bt(e.kind),M=a?``:``,z=e.dot?``:"";return`${M}${z}`}function Pe(t,e,n,o){const c=new Map,l=new Map;for(const s of e.crossings)l.has(s.under)||l.set(s.under,[]),l.get(s.under).push(s);let a="";for(const[s,r]of l){const d=`${o}-cut-${s}`;c.set(s,d);const p=r.map(f=>{const i=e.lines[f.top],u=e.lines[f.under],b=i.width/2+n.cut,h=u.width/2+1;return f.underVertical?``:``}).join("");a+=`${p}`}return{defs:a,ids:c}}function tn(t,e,n,o){const{defs:c,ids:l}=Pe(t,e,n,o),a=e.lifelines.map(i=>``).join(""),s=(e.bars??[]).map(i=>``).join(""),r=e.lines.map((i,u)=>Jn(t,i,n,l.get(u)??null,i.from===i.to?n.radiusXs:n.radius)).join(""),p=`${a?`${a}`:""}${c?`${c}`:""}${s}${r}`,f=e.labels.map(i=>`1?' data-lines="2"':""} style="left:${Math.round(i.box.l*100)/100}px;top:${Math.round(i.box.t*100)/100}px;width:${Math.round((i.box.r-i.box.l)*100)/100}px">${i.text.split(` +`).map(bt).join("
")}
`).join("");return p+f}function he(t,e,n,o,c,l,a,s){const d=t.querySelector(`.${n}-drawing`);if(!d||t.clientWidth===0)return{dyn:c,geo:null,ink:"",tokens:null};const p=Tn(t),f=Fn(d,n),i=Hn(e,p,f);s?.(i.least);const u=t.clientWidth,b=(()=>{const E=document.activeElement;return E&&d.contains(E)&&E.dataset.node?E.dataset.node:void 0})(),h=E=>Rt(e,E)?{...E,stop:E.stop&&e.byId.has(E.stop)?E.stop:e.nodes[0]?.id,keep:void 0}:{...E,stop:E.stop??e.nodes[0]?.id,keep:b&&E.layout!=="drawn"?b:void 0};let g=!1;const k=E=>{if(g=!1,e.type!=="flowchart")return E;l({...E,heights:void 0,words:void 0});const G=Lt(),R=Lt();return d.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(C=>{const W=C.querySelector(`.${n}-words`);if(!W)return;const T=C.getBoundingClientRect(),K=X=>{const J={w:X.width+2*p.space("2-5"),h:X.height+2*p.space("2")},Z=1-J.w/T.width,Q=Z>.05?J.h/2/Z:J.h*10;return Math.max(p.space("16"),Math.ceil(T.width/5),Math.ceil(2*Q))},U=W.getBoundingClientRect();let st=K(U);if(st>T.width){const X=m=>(C.style.setProperty("--_ww",`${m}px`),W.getBoundingClientRect()),J=Math.floor(C.clientWidth-2*p.space("2-5"));let Z=Math.ceil(U.width),Q=U.height;for(;Z1;){const I=m+$>>1;X(I).heightT.width&&(g=!0)}),{...E,heights:G,words:Object.keys(R).length?R:void 0}},M=()=>({m:e,tk:p,P:n,drawing:d,origin:d.getBoundingClientRect(),warn:a}),z=c.autoOpen?{open:!1,autoOpen:void 0}:{},w=(E,G)=>G.map(R=>Dt(e,E.lines.find(C=>C.i===R))).join(", ");if(e.text)return{dyn:{...c,layout:"stacked",bare:void 0},geo:null,ink:"",tokens:p,least:i.least};if(u>=i.least&&!e.unplaced){const E=W=>{let T=h({...c,...z,layout:"drawn",grow:void 0,track:void 0,bare:void 0,pad:W||void 0,rows:void 0});T=k(T),l(T);let K=Je(M(),f);return K.corridors&&(T={...T,rows:K.corridors.rows},l(T),K=Je({...M(),pick:K.corridors.pick},f)),{dd:T,g:K}};let{dd:G,g:R}=E(!1);const C=W=>W.through.length>0||W.outside.length>0||(W.overlaps?.length??0)>0||(W.misfit?.length??0)>0||g;if(!C(R)&&R.unseated.length&&R.unseated.every(W=>R.bounded?.includes(W))){const W=E(!0);!C(W.g)&&!W.g.unseated.length&&({dd:G,g:R}=W)}if(!C(R)&&!R.unseated.length)return R.crossings.length&&a?.(`${R.crossings.length} crossing${R.crossings.length===1?"":"s"} in the drawn layout: ${R.crossings.map(W=>`${Dt(e,R.lines[W.top])} over ${Dt(e,R.lines[W.under])}`).join("; ")}`),{dyn:G,geo:R,ink:tn(n,R,p,o),tokens:p,least:i.least};g&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: a decision would be taller than it is wide`),R.misfit?.length&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: ${R.misfit.join("; ")}`),R.through.length&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: ${w(R,R.through)} would pass through a node`),R.overlaps?.length&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: ${w(R,R.overlaps)} would lie on one another`),R.outside.length&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: ${w(R,R.outside)} would leave the drawing`),R.unseated.length&&a?.(`the drawn layout does not fit at ${Math.round(u)}px: no clean seat for ${R.unseated.map(W=>e.type==="sequence"?`message ${W}`:`"${_t(e.edges[W]?.label??"")}"`).join(", ")}`)}let q=h({...c,...z,layout:"stacked",heights:void 0,grow:Lt(),track:e.type==="schema"?i.table:void 0,bare:void 0,pad:void 0,rows:void 0});if(q=k(q),l(q),e.type==="sequence"||e.type==="schema")return{dyn:q,geo:null,ink:"",tokens:p,least:i.least};const O=_e(e);let N=Ye(M(),f,O,q.grow);for(let E=0;E<6&&Object.keys(N.grow).length;E++){const G=Lt(q.grow);for(const[R,C]of Object.entries(N.grow))G[R]=(Ot(G,R)??0)+C;q={...q,grow:G},l(q),N=Ye(M(),f,O,G)}const D=N.geo;if(!O.third&&O.laneCount>2&&a?.(`the stacked drawing uses ${O.laneCount} end lanes (four at most)`),D.unseated.length>0||D.through.length>0||D.outside.length>0||O.third){D.unseated.length&&a?.(`the stacked drawing has no clean seat for ${[...new Set(D.unseated)].map(R=>`"${_t(e.edges[R]?.label??"")}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),D.through.length&&a?.(`in the stacked drawing ${w(D,D.through)} would pass through a node, so its lines are not drawn`),D.outside.length&&a?.(`in the stacked drawing ${w(D,D.outside)} would leave the drawing, so its lines are not drawn`),O.third&&a?.("the stacked drawing would need a fifth end lane, so its lines are not drawn","error");const E={...D,lines:[],labels:[],crossings:[]},G=h({...q,grow:Lt(),bare:!0,open:c.bare?c.open:!0,autoOpen:c.bare?c.autoOpen:c.open?void 0:!0});return l(G),{dyn:G,geo:E,ink:"",tokens:p,least:i.least}}return D.crossings.length&&a?.(`${D.crossings.length} crossing${D.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${D.crossings.map(E=>`${Dt(e,D.lines[E.top])} over ${Dt(e,D.lines[E.under])}`).join("; ")}`),{dyn:q,geo:D,ink:tn(n,D,p,o),tokens:p,least:i.least}}function Dt(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 Un(t,e,n,o,c,l){const a=new Set;if(l){a.add(l);for(const h of n?.lines??[])h.from===l&&a.add(h.to),h.to===l&&a.add(h.from)}if(t.toggleAttribute("data-tracing",!!l),t.querySelectorAll(`.${e}-node`).forEach(h=>h.toggleAttribute("data-near",a.has(h.dataset.node))),!n||!o)return;const s=h=>!!l&&(h.from===l||h.to===l),r=t.querySelector(`.${e}-edges`),d=new Map;t.querySelectorAll(`.${e}-edge`).forEach(h=>d.set(h.getAttribute("data-edge"),h));for(const h of n.lines){const g=d.get(String(h.i));g&&(g.toggleAttribute("data-lit",s(h)),g.toggleAttribute("data-dim",!!l&&!s(h)))}if(t.querySelectorAll(`.${e}-label`).forEach(h=>{const g=n.lines.find(k=>String(k.i)===h.dataset.edge);h.toggleAttribute("data-lit",!!(g&&s(g)))}),r){for(const h of n.lines)if(s(h)){const g=d.get(String(h.i));g&&r.appendChild(g)}}const p=Pt(n.lines,s),{defs:f,ids:i}=Pe(e,{...n,crossings:p},o,c),u=t.querySelector(`.${e}-svg`);if(!u)return;let b=u.querySelector("defs");!b&&f&&(b=document.createElementNS("http://www.w3.org/2000/svg","defs"),u.insertBefore(b,u.firstChild)),b&&(b.innerHTML=f),n.lines.forEach((h,g)=>{const k=d.get(String(h.i))?.querySelector(`.${e}-line`);if(!k)return;const M=i.get(g);M?k.setAttribute("mask",`url(#${M})`):k.removeAttribute("mask")})}var Xn=()=>matchMedia("(prefers-reduced-motion: reduce), (forced-colors: active), print").matches||document.documentElement.getAttribute("data-loops")==="held";function Yn(t,e){const n=t.getAttribute("data-entrance");if(!(n==="running"||n==="done")){if(!e){n&&t.removeAttribute("data-entrance");return}n||t.setAttribute("data-entrance",Xn()||Pn(t)?"done":"pending")}}var Qn=t=>`basalt-diagram-entrance:${location.pathname}#${t.id}`;function Pn(t){if(!t.hasAttribute("data-first-visit")||!t.id)return!1;try{return localStorage.getItem(Qn(t))!==null}catch{return!1}}function en(t){const e=t.getAttribute("data-entrance");e!=="pending"&&e!=="running"||(t.setAttribute("data-entrance","done"),t.dispatchEvent(new Event("basalt-diagram-settle")))}function to(t,e,n,o=!1,c=!1){const l=o?Jt(t):null;if(l&&n.startsWith("Arrow")){const d={ArrowRight:c?"left":"right",ArrowLeft:c?"right":"left",ArrowDown:"down",ArrowUp:"up"}[n];return d?l[e]?.[d]??null:null}const a=t.byId.get(e)?.i??0,s=t.nodes.length;let r;if(n==="ArrowRight"||n==="ArrowDown")r=a+1;else if(n==="ArrowLeft"||n==="ArrowUp")r=a-1;else if(n==="Home")r=0;else if(n==="End")r=s-1;else return null;return t.nodes[Math.max(0,Math.min(s-1,r))].id}var eo=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden","data-art"],nn=["data-layout","data-measured","data-bare","data-motion","data-first-visit","data-rtl","data-cols","data-reach","data-gutter","data-marks"],no=["--_track","--_h","--_ww","--_gap","--_ggrow","--_tl","--_gpad","--_gw","--_mh","--_rows","--_row-gap"],on=t=>t==null||t===!1;function oo(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 te(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const o=n?nn:eo;for(const a of o)on(e.a[a])&&t.removeAttribute(a);for(const[a,s]of Object.entries(e.a)){if(a==="class")continue;if(a==="style"){const d=t.style,p=new Map(String(s??"").split(";").map(f=>{const i=f.indexOf(":");return[f.slice(0,i).trim(),f.slice(i+1).trim()]}).filter(([f])=>f));for(const[f,i]of p)d.getPropertyValue(f).trim()!==i&&d.setProperty(f,i);for(const f of no)p.has(f)||d.removeProperty(f);continue}if(n&&!nn.includes(a))continue;if(on(s)){t.removeAttribute(a);continue}const r=s===!0?"":String(s);t.getAttribute(a)!==r&&t.setAttribute(a,r)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class)||e.c.some(a=>typeof a!="string"&&"slot"in a))return;const c=[...t.children];let l=0;for(const a of e.c)if(!(typeof a=="string"||"slot"in a)){for(let s=l;st.querySelector(`.${e}-node[data-node="${CSS.escape(l)}"]`);n&&c(n)?.setAttribute("tabindex","-1"),c(o)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",o=0;function c(i,u,b){return{prefix:n,base:i,hasSource:u.source!==void 0&&u.source!==null&&u.source!=="",hiddenClass:"visually-hidden",viewer:b?b.keys:void 0}}function l(i,u,b,h){var g=function(k){return''+bt(k)+""};return{source:bt(String(u.source||"")),summary:bt(String(u.summary||"")),hint:re(i).map(function(k){return""+k.keys.map(g).join(" ")+" "+bt(k.words)+""}).join(""),toggle:'"}}function a(i,u,b){for(var h=i.layout==="auto"&&(i.type==="architecture"||i.type==="flowchart"||i.type==="schema"),g=h?Array.isArray(i.placement)?i.placement:i.placement?[i.placement]:[]:[],k=i.direction||(i.type==="flowchart"?"down":"right"),M=null,z=0;z");return{open:O.slice(0,N+1),inner:O.slice(N+1,O.length-9),warnings:w.errors.map(function(D){return"error: "+D}).concat(w.warnings)}}var s=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-marks","data-layout","data-measured","data-bare"],r=["--_cols","--_gpad","--_track"];function d(i,u,b,h){i.__diagram&&i.__diagram.stop();var g=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),k=getComputedStyle(i).direction==="rtl",M=u.layout==="auto"&&(u.type==="architecture"||u.type==="flowchart"||u.type==="schema"),z=M?Array.isArray(u.placement)?u.placement:u.placement?[u.placement]:[]:[];M&&!z.length&&console.warn('Basalt diagram: "layout": "auto" needs a placement, which compose.mjs writes at build time; drawn from script, place it with placeDiagram (@srasyndicate/basalt/diagram-layout) and pass "placement". The figure is stacked');var w=u.direction?[u.direction]:u.type==="flowchart"?["down","right"]:["right","down"],q=function(F){for(var V=0;V .diagram-drawing")){if(!g||!i.querySelector("#"+CSS.escape(g+"-title"))){for(;document.getElementById("dg"+ ++o+"-title"););g="dg"+o}var N=a(u,g,h),D=document.createElement("div");D.innerHTML=N.open+"";var dt=D.firstChild;s.forEach(function(F){i.removeAttribute(F)}),r.forEach(function(F){i.style.removeProperty(F)});for(var E=0;E :not(script[data-diagram])").forEach(function(F){F.remove()}),i.insertAdjacentHTML("beforeend",N.inner)}O.warnings.forEach(function(F){console.warn("Basalt diagram: "+F)}),O.errors.forEach(function(F){console.error("Basalt diagram: "+F)}),O.motion.animated&&O.motion.firstVisit&&!i.id&&console.error('Basalt diagram: "entrance": "first-visit" needs an id on the figure: without one the entrance plays on every visit');var R=c(g,u,h),C={},W=null,T=null,K=null,U=null,st=Object.create(null),X=function(F,V){st[F]||(st[F]=1,(V==="error"?console.error:console.warn)("Basalt diagram: "+F))},J=function(F){te(i,Xt(O,F,R))},Z=i.querySelector(".diagram-ink"),Q=i.querySelector(".diagram-toggle"),m=!h&&O.motion.animated&&typeof e.diagramMotion=="function",$=null,S=null,B=function(){m&&en(i)};function I(){Un(i,n,W&&W.geo,W&&W.tokens,g,T||U||K),Y()}var j=null,tt=!h&&matchMedia("(hover: none), (pointer: coarse)").matches;function Y(){var F=tt&&!h&&Z&&Z.innerHTML!=="";if(i.toggleAttribute("data-touch",!!(tt&&!h)),F&&!j){var V=i.querySelector(":scope > .diagram-foot");if(!V)return;j=document.createElement("button"),j.type="button",j.className="btn diagram-clear",j.setAttribute("data-variant","secondary"),j.setAttribute("data-size","sm"),j.innerHTML="Clear highlight",j.addEventListener("click",function(){U&&(U=null,I())}),V.appendChild(j)}else!F&&j&&(j.remove(),j=null);j&&j!==j.parentNode.lastElementChild&&document.activeElement!==j&&j.parentNode.appendChild(j),j&&(U?j.removeAttribute("aria-disabled"):j.setAttribute("aria-disabled","true"))}function mt(F){if(!F.defaultPrevented){var V=$n(i,n,F,U);V!==void 0&&(B(),tt=!0,U=V,I())}}function nt(){Q&&(Q.setAttribute("aria-expanded",String(!!C.open)),Q.firstElementChild.textContent=C.open?"Hide the list":"View as list")}function lt(){if(M&&z.length>1&&!h){for(var F=null,V=[],et=!1,at=0;at1&&h&&!u.direction&&h.room){for(var ee=h.room(),Gt=-1,pe=null,ge=0;geGt+1e-6&&(Gt=sn,pe=me)}}}pe&&(O=pe)}W=(h?h.measure:he)(i,O,n,g,C,J,X),C=W.dyn,J(C),nt();var ye=i.querySelector(":scope > .diagram-hint");if(ye){var rn=re(O,C.layout==="drawn").map(function(At){return""+At.keys.map(function(io){return''+bt(io)+""}).join(" ")+" "+bt(At.words)+""}).join("");ye.innerHTML!==rn&&(ye.innerHTML=rn)}Rt(O,C)||(K=U=null);var ln=Z&&W.ink!==S;ln&&(Z.innerHTML=W.ink,S=W.ink),I();var ro=O.text?i.querySelector(".diagram-text[data-art]"):null;O.text&&typeof e.diagramText=="function"&&e.diagramText(i,O,u,h);var cn=O.text?i.querySelector(".diagram-text[data-art]"):null;m&&W.tokens&&(Yn(i,!!(W.geo&&W.geo.lines.length)||!!cn),(ln||cn!==ro)&&$&&$.redrawn()),h&&h.onMeasured&&W.tokens&&h.onMeasured(W,i)}function ft(F){C=F,J(C)}function yt(F){var V=C.stop;C=Object.assign({},C,{stop:F}),ao(i,n,V,F)}var wt=function(F){var V=F&&F.closest?F.closest(".diagram-node"):null;return V&&i.contains(V)?V:null};function vt(F){var V=wt(F.target);if(!(!V||F.defaultPrevented)){if(B(),F.key==="Escape"){!h&&(T||K||U)&&(F.preventDefault(),T=K=U=null,I());return}if(Rt(O,C)){var et=to(O,V.getAttribute("data-node"),F.key,C.layout==="drawn");if(et){F.preventDefault(),yt(et);var at=i.querySelector('.diagram-node[data-node="'+CSS.escape(et)+'"]');at&&at.focus()}}}}function St(F){var V=wt(F.target);if(V){B();var et=V.getAttribute("data-node");T=V.matches(":focus-visible")?et:null,Rt(O,C)&&C.stop!==et&&yt(et),I()}}function pt(F){var V=wt(F.target);V&&(wt(F.relatedTarget)||(T=null),C.keep===V.getAttribute("data-node")&&ft(Object.assign({},C,{keep:void 0})),I())}function ut(F){if(!(F.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var V=wt(F.target);V&&B();var et=V&&Rt(O,C)?V.getAttribute("data-node"):null;et!==K&&(K=et,I())}}function y(){K&&(K=null,I())}function A(){B(),ft(Object.assign({},C,{open:!C.open,autoOpen:void 0})),nt()}i.addEventListener("keydown",vt),i.addEventListener("focusin",St),i.addEventListener("focusout",pt),i.addEventListener("pointerover",ut),i.addEventListener("pointerleave",y),i.addEventListener("click",mt),Q&&Q.addEventListener("click",A),lt();var _=i.clientWidth,x=0,L=!0,H=new ResizeObserver(function(){Math.abs(i.clientWidth-_)<.5||(_=i.clientWidth,cancelAnimationFrame(x),x=requestAnimationFrame(lt))});H.observe(i),document.fonts&&document.fonts.ready.then(function(){L&<()});var P=matchMedia("(forced-colors: active)"),ot=O.nodes.some(function(F){return F.mark});ot&&P.addEventListener("change",lt),m&&($=e.diagramMotion(i,{fig:i,P:n,base:g,model:function(){return O},geo:function(){return W&&W.geo},tokens:function(){return W&&W.tokens}},u));var ct=!h&&u.zoom!==!1&&typeof e.diagramZoom=="function"?e.diagramZoom(i,u,{model:O,settle:B,animated:m}):null,it=i.querySelector(":scope > .diagram-foot"),rt=!h&&u.export===!0&&it&&typeof e.diagramExport=="function"?e.diagramExport(it,i):[];i.__diagram={stop:function(){ct&&ct.destroy(),rt.forEach(function(F){F.remove()}),L=!1,H.disconnect(),cancelAnimationFrame(x),ot&&P.removeEventListener("change",lt),$&&$.destroy(),i.removeEventListener("keydown",vt),i.removeEventListener("focusin",St),i.removeEventListener("focusout",pt),i.removeEventListener("pointerover",ut),i.removeEventListener("pointerleave",y),i.removeEventListener("click",mt),j&&j.remove(),Q&&Q.removeEventListener("click",A)},layout:lt,key:p(u),send:$&&$.sendValue?$.sendValue:null}}function p(i){try{return JSON.stringify(i,function(u,b){return u==="packet"&&b&&typeof b=="object"?Object.assign({},b,{send:void 0}):b})}catch{return null}}function f(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var u=i.querySelector(":scope > script[data-diagram]");if(u)try{d(i,JSON.parse(u.textContent),!0)}catch(b){console.error("Basalt diagram: this figure could not be drawn",b)}}})}e.diagramMarkup=a,e.diagramKit={draw:d,buildModel:Nt,figureKey:Sn,figureList:Cn,hintEntries:re,toHtml:oe,escapeHtml:bt,settleEntrance:en,measureFigure:he},t.diagram=function(i,u){var b=i.__diagram,h=b&&b.send?p(u):null;if(h!==null&&h===b.key){b.send(u.packet?u.packet.send:void 0);return}d(i,u)},e.step(62,"wireDiagrams",f)})(window.Basalt)})(); diff --git a/.agent/skills/basalt-html/parts/manifest.json b/.agent/skills/basalt-html/parts/manifest.json index 79d89147..e37b5a8b 100644 --- a/.agent/skills/basalt-html/parts/manifest.json +++ b/.agent/skills/basalt-html/parts/manifest.json @@ -1,5 +1,5 @@ { - "$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 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). Raised in cimip-gaps-2 batch B5 (the touch sizes under 720 whatever the pointer: each coarse-pointer target rule also answers a window under 720, about 20 bytes a rule; forms merged its three into one and stays under 3500): select 9000 to 9100 (measured 9064), selection 1480 to 1500 (1486), filter 17450 to 17500 (17473), option-chips 6850 to 6900 (6853), menu 8900 to 8950 (8902). B5 fix pass 1 (Astra): core 34550 to 34950 (measured 34911: 30762 CSS and 4149 JS) for stacked links in a column, each giving up the side of its 44px box that meets a neighbour, so a tap on a link's words is always that link's; core had 12 bytes free. DECISIONS 274 (the owner's pick: under 720 the toast stack hangs from the bar): toast 15700 to 16050 (measured 16035; 8 bytes were free; the stack's direction became one sign variable, trimming 585 of the 920 bytes the phone form first took). B5 merged with main (5ad5345a): main's own core measured 34930 against its 34550 cap before B5; with B5 (the touch sizes under 720 and stacked links in a column) it is 35331, so core is 35350; nav 5350 to 5400 (measured 5364: B4's nav plus the touch size under 720). The full run after the stream (DECISIONS 246): the site footer's links keep their own flex column under 720, as React's, out of the bare-link touch rule (26 bytes), so core is 35400 (measured 35357); sheet 5250 to 5400 (measured 5368: React's B5 ring room, ported: the held actions reach space-1-5 above their band, clipped, and the body keeps space-1-5 at each end). Raised for diagram motion and service marks (DECISIONS 292): skillMd 12550 to 12650 for the diagram-motion module's one line; diagram 87200 to 91000 for what a still diagram now carries (a card's mark and its seat, the pending frame, the comparison that writes a drawing only when it changed, and the print rule), and its usage 2600 to 4300 for the decision's four lines and the list of mark ids; the new diagram-motion module (the motion engine, its stylesheet and the motion tokens, in a page only when a diagram is animated) at 26200. Raised when the diagram tests were first run (DECISIONS 298): diagram 91000 to 91250 and diagram-motion 26200 to 26850. Raised in batch A of the diagrams backlog (DECISIONS 301): diagram 91250 to 92400, for the engine fixes it bundles (a decision kept no taller than it is wide, labels on whole pixels, slots beside a straight line, a one-column schema's turn-back); the skill keeps the development checks a production React build now drops. Raised again in that batch's review fixes: diagram 92400 to 92650, for the drawn layout refusing two lines laid on one another (Neon's blocking finding 1 on #126). Fix round 1 of #124 had already taken them to 91205 and 26621 with the tests unrun; this round added 1 byte (every focal node prints its fill; a one-form mark's dark form falls back to its light one) and 180 (the entrance keeps its own clock when it is drawn again while paused). DECISIONS 320 (versions and release notes): the release module is new (budget 15900 at first, usage 2400); topbar, app-shell and tab-bar gain the version link's classes (budgets: topbar 17700 to 19900, app-shell 4300 to 5200 with the rail's tooltip for it, tab-bar 4850 to 5200), their usage caps rising 2900 to 3100, 2600 to 2850 and 2250 to 2400 for its one line each; skillMd rose 12650 to 12800 for the release module's line and .version-link in topbar's. The code review of round 68 adds data-focus-self to the popover module (its Tab walk; budget 4950 to 5600, usage cap 950 to 1100) and logical start and end for its alignment; the release module's header grid and the Sources panel's touch rows take it to 16900. The spacing sweep of round 68 (DECISIONS 326: Copy link's words on the edge, the callout's last change, its reference column, the last release, the touch rows' end and the whole code chip) takes the release module to 17400. The ruling on where a release ends (DECISIONS 331: no padding under the last change in a release, a release-ending fold's hang, an arrived change keeping its padding, the panel holding its first margin, Build details 44 on touch and a closed Fixed panel taking no room) takes it to 19000. The code recheck of round 68 (recheck 5) has the popover's Tab walk follow Safari's own rule (Tab skips links on Apple's WebKit, Option-Tab reaches them): popover 5600 to 5900. The pixel recheck of round 68 has the Sources panel's touch rows keep their 20px lines with the link's box as hit area, space-3 rows and space-6 between two linked values (recheck-pixels 4), and the release's whole header take the arrival's plate: release 19000 to 19600. Merging #127 (stages, DECISIONS 316 and 328) into the versioning branch: both had raised skillMd from 12650 to 12800 for their own module's line, and together they came to 12886; SKILL.md was tightened in its wording (no rule dropped) to stay within 12800.Raised in the repo review (23 Nov 2026; budgets are soft, the owner's word): notifications 12450 to 12700 (a link is written only when relative, http, https or mailto, and side and align are checked before they reach the markup), combobox 11200 to 11350 (a disabled field's hidden input is disabled too, now and later), tooltip 3200 to 3550 (the gap to the opener is the tooltip's own, and hover and keyboard focus each hold it open; WCAG 1.4.13), chart 34750 to 34800 (the scale's step search and gridlines are bounded, so extreme values cannot hang the page), spinner 650 to 720 (its held rule moved in from loops, so a ring-only page keeps a stored hold), kbd 2900 to 2950, palette 11400 to 11500 (and its usage text 1350 to 1400, for the Mod line) and toast 16050 to 16200 (Mod in a palette item's keys is bound as it is drawn, and a toast action's aria-keyshortcuts resolves Mod). The safe-sinks rule (decided by the owner, Fable, Astra and Muse, 23 Nov 2026): skillMd 12650 to 12900, and 13050 with main's own raise merged in (one line: data goes in as textContent, a link passes Basalt.safeHref, an option comes from a fixed list), core 35400 to 35650, and 35800 with main's own raise merged in, and its usage 2950 to 3200 (one safeHref, published as Basalt.safeHref, and _.pick, in place of a copy in each module; esc escapes the apostrophe), link-tabs 5750 to 5900 (a refused link dispatches no event), diagram 92650 to 93000 (a card's mark is a relative path, https or a data: image).", + "$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 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). Raised in cimip-gaps-2 batch B5 (the touch sizes under 720 whatever the pointer: each coarse-pointer target rule also answers a window under 720, about 20 bytes a rule; forms merged its three into one and stays under 3500): select 9000 to 9100 (measured 9064), selection 1480 to 1500 (1486), filter 17450 to 17500 (17473), option-chips 6850 to 6900 (6853), menu 8900 to 8950 (8902). B5 fix pass 1 (Astra): core 34550 to 34950 (measured 34911: 30762 CSS and 4149 JS) for stacked links in a column, each giving up the side of its 44px box that meets a neighbour, so a tap on a link's words is always that link's; core had 12 bytes free. DECISIONS 274 (the owner's pick: under 720 the toast stack hangs from the bar): toast 15700 to 16050 (measured 16035; 8 bytes were free; the stack's direction became one sign variable, trimming 585 of the 920 bytes the phone form first took). B5 merged with main (5ad5345a): main's own core measured 34930 against its 34550 cap before B5; with B5 (the touch sizes under 720 and stacked links in a column) it is 35331, so core is 35350; nav 5350 to 5400 (measured 5364: B4's nav plus the touch size under 720). The full run after the stream (DECISIONS 246): the site footer's links keep their own flex column under 720, as React's, out of the bare-link touch rule (26 bytes), so core is 35400 (measured 35357); sheet 5250 to 5400 (measured 5368: React's B5 ring room, ported: the held actions reach space-1-5 above their band, clipped, and the body keeps space-1-5 at each end). Raised for diagram motion and service marks (DECISIONS 292): skillMd 12550 to 12650 for the diagram-motion module's one line; diagram 87200 to 91000 for what a still diagram now carries (a card's mark and its seat, the pending frame, the comparison that writes a drawing only when it changed, and the print rule), and its usage 2600 to 4300 for the decision's four lines and the list of mark ids; the new diagram-motion module (the motion engine, its stylesheet and the motion tokens, in a page only when a diagram is animated) at 26200. Raised when the diagram tests were first run (DECISIONS 298): diagram 91000 to 91250 and diagram-motion 26200 to 26850. Raised in batch A of the diagrams backlog (DECISIONS 301): diagram 91250 to 92400, for the engine fixes it bundles (a decision kept no taller than it is wide, labels on whole pixels, slots beside a straight line, a one-column schema's turn-back); the skill keeps the development checks a production React build now drops. Raised again in that batch's review fixes: diagram 92400 to 92650, for the drawn layout refusing two lines laid on one another (Neon's blocking finding 1 on #126). Fix round 1 of #124 had already taken them to 91205 and 26621 with the tests unrun; this round added 1 byte (every focal node prints its fill; a one-form mark's dark form falls back to its light one) and 180 (the entrance keeps its own clock when it is drawn again while paused). DECISIONS 320 (versions and release notes): the release module is new (budget 15900 at first, usage 2400); topbar, app-shell and tab-bar gain the version link's classes (budgets: topbar 17700 to 19900, app-shell 4300 to 5200 with the rail's tooltip for it, tab-bar 4850 to 5200), their usage caps rising 2900 to 3100, 2600 to 2850 and 2250 to 2400 for its one line each; skillMd rose 12650 to 12800 for the release module's line and .version-link in topbar's. The code review of round 68 adds data-focus-self to the popover module (its Tab walk; budget 4950 to 5600, usage cap 950 to 1100) and logical start and end for its alignment; the release module's header grid and the Sources panel's touch rows take it to 16900. The spacing sweep of round 68 (DECISIONS 326: Copy link's words on the edge, the callout's last change, its reference column, the last release, the touch rows' end and the whole code chip) takes the release module to 17400. The ruling on where a release ends (DECISIONS 331: no padding under the last change in a release, a release-ending fold's hang, an arrived change keeping its padding, the panel holding its first margin, Build details 44 on touch and a closed Fixed panel taking no room) takes it to 19000. The code recheck of round 68 (recheck 5) has the popover's Tab walk follow Safari's own rule (Tab skips links on Apple's WebKit, Option-Tab reaches them): popover 5600 to 5900. The pixel recheck of round 68 has the Sources panel's touch rows keep their 20px lines with the link's box as hit area, space-3 rows and space-6 between two linked values (recheck-pixels 4), and the release's whole header take the arrival's plate: release 19000 to 19600. Merging #127 (stages, DECISIONS 316 and 328) into the versioning branch: both had raised skillMd from 12650 to 12800 for their own module's line, and together they came to 12886; SKILL.md was tightened in its wording (no rule dropped) to stay within 12800. Raised in diagram batch B's fix round (DECISIONS 318, the owner's diagram raise; and 326's sweep), each to its measured size: diagram 137700 to 144100 (the two reviews' fixes in the shared engine: right to left frames and self-calls, the corridors' and lanes' development words, the unusable-placement check, the transcript's hanging lines, the text art's frame widening, the frame-side fit check, the sequence's layers, the stacked group's turn room), diagram-motion 28450 to 30450 (the text sequence's build by ink and its colour-only run, moved into the motion module), diagram-zoom 17000 to 17600 (a linked card closes the viewer; the text art's own width; a placed model for the key hint), diagram-export 7850 to 10450 (an export at rest: sized drawing SVGs, no reveal masks, the pseudo-element rules, the lines under the cards, a viewer's figure read at 100% with its head and key, the rim's lit top). Raised at the batch B re-check (the decider's four rulings): diagram 144100 to 145100 (5.1's first list reported as errors apart from the warnings, a turn's label lines on the group entered by it and the seats beside its turn, the bare stack applied, the text art's reset of the core's inline code chip). Merging main (#127 and #128) into diagram batch B: skillMd keeps main's 12800 (batch B had raised it to 12950 for its diagram lines); SKILL.md was tightened in its wording to stay within it, no rule dropped; core takes main's 35550.Raised in the repo review (23 Nov 2026; budgets are soft, the owner's word): notifications 12450 to 12700 (a link is written only when relative, http, https or mailto, and side and align are checked before they reach the markup), combobox 11200 to 11350 (a disabled field's hidden input is disabled too, now and later), tooltip 3200 to 3550 (the gap to the opener is the tooltip's own, and hover and keyboard focus each hold it open; WCAG 1.4.13), chart 34750 to 34800 (the scale's step search and gridlines are bounded, so extreme values cannot hang the page), spinner 650 to 720 (its held rule moved in from loops, so a ring-only page keeps a stored hold), kbd 2900 to 2950, palette 11400 to 11500 (and its usage text 1350 to 1400, for the Mod line) and toast 16050 to 16200 (Mod in a palette item's keys is bound as it is drawn, and a toast action's aria-keyshortcuts resolves Mod). The safe-sinks rule (decided by the owner, Fable, Astra and Muse, 23 Nov 2026): skillMd 12650 to 12900, and 13050 with main's own raise merged in (one line: data goes in as textContent, a link passes Basalt.safeHref, an option comes from a fixed list), core 35400 to 35650, and 35800 with main's own raise merged in, and its usage 2950 to 3200 (one safeHref, published as Basalt.safeHref, and _.pick, in place of a copy in each module; esc escapes the apostrophe), link-tabs 5750 to 5900 (a refused link dispatches no event), diagram 92650 to 93000 (a card's mark is a relative path, https or a data: image). Merging #129 into diagram batch B: diagram keeps batch B's 145100 plus #129's mark check, set to its measure, and batch B's usage 4600.", "budgets": { "skillMd": 13050, "core": 35800 @@ -820,8 +820,8 @@ "art", "kbd" ], - "budget": 93000, - "usage": 4300, + "budget": 145450, + "usage": 4600, "builds": [ "kbd" ] @@ -847,8 +847,8 @@ "toggle", "glyph" ], - "budget": 26850, - "usage": 1300, + "budget": 30450, + "usage": 1450, "builds": [ "loops", "toggle", @@ -858,6 +858,64 @@ "pause" ] }, + "diagram-zoom": { + "classes": [ + "diagram-expand", + "diagram-viewer", + "diagram-stage", + "diagram-sizer", + "diagram-layer", + "diagram-zoom", + "diagram-level", + "diagram-probe", + "diagram-viewer-foot", + "diagram-viewer-key", + "diagram-viewer-row", + "diagram-viewer-hint", + "diagram-viewer-end", + "diagram-viewer-list", + "diagram-viewer-source" + ], + "requires": [ + "diagram", + "dialog", + "dialog-form", + "sheet" + ], + "budget": 17600, + "usage": 900, + "builds": [ + "dialog", + "dialog-form", + "sheet" + ] + }, + "diagram-export": { + "text": [ + "\"export\"\\s*:\\s*true" + ], + "textWords": [ + "a diagram's \"export\": true" + ], + "requires": [ + "diagram" + ], + "budget": 10450, + "usage": 700 + }, + "diagram-text": { + "text": [ + "\"variant\"\\s*:\\s*\"text\"" + ], + "textWords": [ + "a sequence's \"variant\": \"text\"" + ], + "requires": [ + "diagram" + ], + "budget": 5450, + "usage": 700 + }, "sparkline": { "classes": [ "sparkline", diff --git a/.agent/skills/basalt-html/parts/usage/diagram-export.md b/.agent/skills/basalt-html/parts/usage/diagram-export.md new file mode 100644 index 00000000..511d845a --- /dev/null +++ b/.agent/skills/basalt-html/parts/usage/diagram-export.md @@ -0,0 +1,6 @@ +# diagram-export + +Added for you when a diagram's JSON says `"export": true`. + +- The figure's foot gets "Download SVG" and "Download PNG", and so does its viewer's (the drawn layout at 100%, whatever the zoom). Each writes the figure in the theme shown: the title and source, the drawing and the key, at rest; native SVG with its words as text and the faces embedded; the PNG at 2x. +- Without `"export": true` there are no buttons and no module. Don't add your own. diff --git a/.agent/skills/basalt-html/parts/usage/diagram-motion.md b/.agent/skills/basalt-html/parts/usage/diagram-motion.md index 479364ef..efba91b7 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram-motion.md +++ b/.agent/skills/basalt-html/parts/usage/diagram-motion.md @@ -5,5 +5,6 @@ Added for you when a diagram's JSON says `"motion": "animated"` (with `loops`); - **Entrance:** in view (two fifths of it), each line draws once in the author's order, inside five seconds; a sequence's arrows go in message order and each label lifts from secondary to primary. Every word is at rest from the first frame. It never plays under reduced motion, in forced colours, under the hold or in print, and settles at once on a hover, a focus, a key or a control. - **Loops:** a flow line's cuts, a pulse's bead, a repeating packet. They run only in view, never while a node is traced, and stop under the page's hold. The figure's foot then has "Pause animations" (the hold's own button, built for you) after "View as list". Don't add a second one for the diagram. - **One mover a figure:** a pulse or a packet, never both. Flow is a state of a line and never runs on a line the mover travels. +- **First visit:** `"entrance": "first-visit"` with an `id` on the figure plays the entrance once; later visits are at rest. A text sequence builds by ink instead, in view. - **Run:** "Play the run" sends one dot through a sequence's messages; it reads "Stop the run" while it runs. It works under the hold and under reduced motion (by colour alone). - `Basalt.diagram(figure, spec)` with a new `packet.send` value sends one message. diff --git a/.agent/skills/basalt-html/parts/usage/diagram-text.md b/.agent/skills/basalt-html/parts/usage/diagram-text.md new file mode 100644 index 00000000..fdc9beb4 --- /dev/null +++ b/.agent/skills/basalt-html/parts/usage/diagram-text.md @@ -0,0 +1,6 @@ +# diagram-text + +Added for you when a sequence's JSON says `"variant": "text"`. + +- The same data as box-drawing characters in a code block, where its widest line fits; elsewhere the transcript (one line a message), which the page holds before script. Nothing scrolls sideways, and the block is hidden from assistive technology: the title, the summary and "View as list" carry it. +- With `"motion": "animated"` it builds by ink: labels and arrows lift in message order, no line hidden, no caret. diff --git a/.agent/skills/basalt-html/parts/usage/diagram-zoom.md b/.agent/skills/basalt-html/parts/usage/diagram-zoom.md new file mode 100644 index 00000000..a6355aee --- /dev/null +++ b/.agent/skills/basalt-html/parts/usage/diagram-zoom.md @@ -0,0 +1,8 @@ +# diagram-zoom + +Added for you on a page with a diagram (with `dialog`, `dialog-form` and `sheet`), unless every figure's JSON says `"zoom": false`. + +- **Expand:** in the figure's foot after "View as list", once script runs. It opens the viewer: the drawn layout in a dialog (the window less 16px from 720, the whole window under it), even where the page shows the stack. +- **Zoom:** it opens at Fit (the whole drawing, 200% at most). "Zoom out", "Zoom in" and "Fit" in the foot; `+`, `-` and `0` with focus in the stage; Ctrl or Command with the wheel, a trackpad pinch and two fingers zoom about the pointer. From Fit or 100% to 400%. +- **Pan:** the stage scrolls both ways; a drag, one finger, the wheel or the arrow keys. A trace works; nothing animates. Esc closes it. +- Don't build a viewer of your own, and don't scale a figure on the page. diff --git a/.agent/skills/basalt-html/parts/usage/diagram.md b/.agent/skills/basalt-html/parts/usage/diagram.md index e50d6a93..eb31b43e 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram.md +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -16,14 +16,15 @@ 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`). +- **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`; `cardinality: { "from", "to" }` on every foreign key or none draws crow's feet: `from` is `one`, `zero-or-one`, `one-or-many` or `zero-or-many`, `to` is `one` or `zero-or-one`). - **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 but a card's service mark. The drawn layout is used only where it fits; otherwise the figure is stacked, one column at most 480 wide. - **Motion:** `"motion": "animated"` (default still) draws each line once in view, every word at rest; it brings in `diagram-motion` (its usage says the rest). Motion never carries a fact alone. -- **Flow, pulse, packet:** `"flow": true` on a `main` or `plain` edge marches it (give it a label). `"pulse": ["a", "b", "c"]` runs a bead along a route; `"packet": { "path": [...], "repeat": true }` sends a dot. One of pulse and packet; never flow on the mover's route. Architecture and data flow only. +- **Flow, pulse, packet:** `"flow": true` on an edge marches it (a dashed line's own dashes) (give it a label). `"pulse": ["a", "b", "c"]` runs a bead along a route; `"packet": { "path": [...], "repeat": true }` sends a dot. One of pulse and packet; never flow on the mover's route. Architecture and data flow only. - **Run:** `"run": true` on a sequence adds "Play the run", a dot through every message. -- **Mark:** `"mark": "aws-ecs-service"` on an architecture node, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: ``. +- **Parts:** a group's `parent` (two levels); `href` (and `"target": "_blank"`) makes a card a link; a label's `"\n"` is its one break; a sequence's message `activate`/`deactivate` (a bar) and steps `{ "frame": "opt" | "loop", "label", "steps" }` or `{ "frame": "alt", "branches": [...] }`; `"variant": "text"` draws it as text art; `"layout": "auto"` places the cards for you (compose.mjs, at build time); `"entrance": "first-visit"` with an `id` plays the entrance once. +- **Mark:** `"mark": "aws-ecs-service"` on an architecture node, a data flow's step or a sequence's participant, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: ``. - **Marks:** `aws-*`, `azure-*`, `gcp-*`, `kubernetes`, `temporal`, `sonarqube`, `github`, `coderabbit`, `greptile`, `blacksmith`, `jenkins`, `servicenow`, `blazemeter`. `node .agent/skills/basalt-html/compose.mjs --marks [aws azure gcp ...]` prints each id with the words its card must say and which are unofficial; a database card (Aurora, RDS) takes `aws-database`. diff --git a/AGENTS.md b/AGENTS.md index ffb88b86..472c943e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,7 +124,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, the edges between a `NumberField`'s value and its steppers, a diagram's connector and a sequence diagram's lifeline, and a stage list's or run timeline's connector (1px between two marks, never + `Separator` between groups of controls, the edges between a `NumberField`'s value and its steppers, a diagram's connector, a sequence diagram's lifeline with its activation bar, a frame's sides, and a stage list's or run timeline's connector (1px between two marks, never filled and never a state). 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 @@ -184,7 +184,7 @@ Basalt has one owner (Bailey) and a design panel of two independent design revie and holds no version. The entry or release a link opens is the stream's arrival (the plate and "Linked"). Build details is on the running release alone, from the running build. No area filter. - **Density and touch:** compact moves controls one step down, with a floor of 24px. Touch - targets stay at least 44px whatever the density, on touch and in any window under 720 whatever the pointer (16px text entry stays touch-only), except a chart's day, reached by drag and by the keys (the phase lane's marks keep 44px). Text entry is 16px on touch. A one-line notification entry is at least 44 tall on + targets stay at least 44px whatever the density, on touch and in any window under 720 whatever the pointer (16px text entry stays touch-only), except a chart's day, reached by drag and by the keys (the phase lane's marks keep 44px); a diagram's card that answers a tap is 44px tall. Text entry is 16px on touch. A one-line notification entry is at least 44 tall on touch, and a `Link` on a line of its own has a 44px hit box with no change to layout, its words raised over a stacked neighbour's box; a link in a sentence keeps its line. - **The phone and what is pinned:** while an on-screen keyboard is up (`data-screen-keyboard`) the tab bar and the phone's status bar are covered, and the foot, sheets, dialogs, the command menu and the toasts are laid out on what is seen. A page that pins more than the bar opts into measured sizes @@ -219,7 +219,15 @@ Basalt has one owner (Bailey) and a design panel of two independent design revie (the faces arriving, a resize) never restarts, hides or cuts short an entrance. An architecture card may carry its service's own mark, 16px in the top end corner: the owner's file, never recoloured, a form for each ground, decoration beside the name, recorded in `packages/react/marks/manifest.json`; a service without one is its name alone. In print a mark prints, and so does the fill of a - focal node that carries one (`print-color-adjust: exact`). + focal node that carries one (`print-color-adjust: exact`). A schema may state how many (crow's foot in the line's ink, on every key or none) and + draws far keys along a corridor. A sequence may show a participant working (a bar) and frame a run of messages + (`opt`, `loop`, `alt`: structure, never a panel, every word plated), and may be written as text art, which never hides a line and has no caret. + Groups nest two deep; four end lanes at most. A card may be a link (the card is the stop; the arrow is the cue). A label breaks only where its + author breaks it. Arrow keys are spatial, on tracks. On touch a tap traces and "Clear highlight" clears. In print a figure is untraced and light. + Right to left mirrors the figure, not the words. Automatic layout asks elkjs for a column and a row and nothing else; Basalt routes, and a figure + is never scaled. elkjs loads on demand or not at all: place at build time. "Expand" opens the viewer: the drawn layout in a dialog (full screen under + 720), laid out at 100% and zoomed by the reader with one transform, from Fit or 100% to 400%, in steps that land at once; it pans by scrolling; it + is never a picture, a `viewBox` or CSS `zoom`; it is still, and it does not print. - **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 05938a86..dd2e8c33 100644 --- a/Sources/BasaltTokens/Tokens.swift +++ b/Sources/BasaltTokens/Tokens.swift @@ -702,6 +702,10 @@ extension Basalt { public static let diagramStep: Double = 56 /// A diagram's arrowhead, its length and its width, for every kind of line (DECISIONS 281). public static let diagramHead: Double = 8 + /// The width of an activation bar on a sequence diagram's lifeline (DECISIONS 306, 1.0). + public static let diagramActivation: Double = 8 + /// The room a cardinality mark takes at a foreign key line's end; no elbow starts inside it (DECISIONS 306, 1.0). + public static let diagramFoot: Double = 14 /// A sequence diagram's lifeline dash, on and off (4 on 4 off), unlike a message's 6 on 4 off (DECISIONS 281). public static let diagramGuideDash: Double = 4 /// A diagram pulse's bead, along the line (DECISIONS 292); never more than two fifths of the line's visible length. diff --git a/dependencies.allowed.json b/dependencies.allowed.json index ba067917..b0a0ed36 100644 --- a/dependencies.allowed.json +++ b/dependencies.allowed.json @@ -6,6 +6,7 @@ "@phosphor-icons/react": "The web icon set (foundations: Icons).", "@srasyndicate/basalt-tokens": "Basalt's own tokens.", "shiki": "CodeBlock syntax highlighting; loaded on demand, one grammar at a time.", + "elkjs": "Automatic diagram layout (`layout=\"auto\"`), loaded on demand through `diagram-layout` and never from the index. EPL-2.0 OR GPL-3.0-or-later; used under EPL-2.0, unmodified. The owner approved it (DECISIONS 301). A build input, not a dependency: its file is copied, unchanged, into dist/diagram-elk.js with its licence (dist/elkjs/LICENSE.md), the one copy the package ships (the decider's ruling 2 on the batch B re-check); it is listed in $copied, pinned.", "react": "Peer: the host app's React.", "react-dom": "Peer: the host app's React DOM." }, @@ -16,5 +17,9 @@ } }, "packages/tokens": {}, - "Package.swift": {} + "Package.swift": {}, + "$copied": { + "$comment": "Approved packages whose file is copied into a package's dist (they are devDependencies, so the lint would call their entry stale): each pinned to the exact version the copy was made from. scripts/check-deps.mjs fails when the devDependency is gone or drifts.", + "packages/react": { "elkjs": "0.12.1" } + } } diff --git a/docs/foundations.md b/docs/foundations.md index a8cc09a3..46fde4e2 100644 --- a/docs/foundations.md +++ b/docs/foundations.md @@ -70,7 +70,8 @@ levels changed no pixel. Dark steps up from true black in small increments, as Linear does. Nothing above the page is pure black, so large moving surfaces never smear on OLED (pixels at `#000` switch fully off and lag when they turn back on). Light sits the page just below white, as Vercel does, -so white cards lift without a shadow. +so white cards lift without a shadow. In print the tokens are the light set, whatever theme the screen shows: the tokens build writes +it, and an app that prints dark on purpose overrides it. **Depth is by level, and the level is not a prop.** It is a private context, rendered as `data-level`, that crosses portals as the modal depth does: @@ -1486,8 +1487,8 @@ Basalt allows a short list of vertical lines. Each is structure, and none is a 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), 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) a -sequence diagram's lifeline, and a stage list's or a run timeline's connector: a 1px line in `border-input` that joins one stage's +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), a +sequence diagram's lifeline and the activation bar on it, a frame's sides, and a stage list's or a run timeline's connector: a 1px line in `border-input` that joins one stage's mark to the next. It is drawn between every two consecutive marks, beside an open detail too, and it never fills, breaks, moves or changes colour with a stage's state: the mark and its word carry the state. A rail's links are horizontal and are not on this list; they fill as their stage passes, repeating the check before them. A connector is never drawn without both its nodes and its head, and neither is ever a mark of state. @@ -1711,6 +1712,12 @@ owner's prototype, one draft, a check and a decision, revised after the final po **Status:** decided by the council (DECISIONS 281, a handoff); the implementation has not been reviewed. +The parts of DECISIONS 301 (cardinality and far keys, activations and frames, the text art, nested groups, four end lanes, link cards, +two-line labels, spatial keys, a trace on touch, marks on steps and participants, right to left, export and automatic layout) were +decided by the council from two drafts and a check (DECISIONS 306, revised by 313). **Status:** the implementation has not been reviewed. +Automatic layout leads with build time: place with `placeDiagram` and pass `placement`, and +elkjs (EPL-2.0 OR GPL-3.0-or-later, used under EPL-2.0) never reaches the browser. + **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, with one exception: a service's own mark on an architecture card keeps its owner's colours ([Service marks](#service-marks)). One node may be focal, and it is inverted ink. @@ -1718,9 +1725,10 @@ card keeps its owner's colours ([Service marks](#service-marks)). One node may b ### 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. + "View as list" and the list, with "Expand" beside "View as 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. + scaled through a `viewBox`, and nothing scrolls sideways. The one place a reader may scale and scroll it is its viewer (below), where the + scale is theirs, as a browser's zoom is. - 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). 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). @@ -1734,12 +1742,15 @@ card keeps its owner's colours ([Service marks](#service-marks)). One node may b - 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. + A side's one line is at its middle. A straight line keeps the middle; one other takes the quarter point toward its far end, and + two or more share that half evenly. A port is on the flat part of its side, never nearer a corner than the corner's radius, and + two ports on a side are at least `size-diagram-head` apart: a card whose side holds more than its height allows grows to the least + height at which both hold (48 for a straight line and two others), and its row takes that height. A side never stacks a figure. 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 +- **A label** is `text-xs` Mono in secondary ink, one line, or two where the author writes a break (never a break of the engine's), 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. 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 @@ -1752,9 +1763,20 @@ card keeps its owner's colours ([Service marks](#service-marks)). One node may b 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 line that leaves or passes a spine card runs in an end gutter outside the cards (lanes `space-3-5` apart, four at most; the gutter is + its lanes and `space-3`), 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 stacked + group whose first card is entered by a turn has `space-12` above; its label stays in the first `space-8`. +- **Several end lines into one card nest:** the line from the outermost lane turns lowest and enters nearest the end edge; each + line from a lane further in turns `space-5` higher and enters `space-3` further in. Their labels are seated `space-2-5` clear of + the innermost entry, each on its own turn's height, taken before the half-pixel snap. +- **Automatic layout** (`layout: "auto"`): the author leaves placement out and elkjs gives each card a column and a row. Nothing + else of elk's is read. Basalt sizes, routes, seats and stacks the figure as it does an authored one, and chooses each line's sides + from its router's four shapes, the line with the fewest clean shapes first. A main line that passes a layer keeps a way there: + cells no card takes. A decision's point that a line leaves takes no other line, and a line turns back only where there is a gutter + (DECISIONS 322). It tries the type's direction, then the other, then + stacks; a figure is never scaled. A `col` or `row` left on a card is not read: there are no hints. elkjs is loaded on demand, or + not at all where `placement` is given; the HTML skill places at build time. - **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 @@ -1763,23 +1785,38 @@ card keeps its owner's colours ([Service marks](#service-marks)). One node may b ### 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. +- **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'. A group may hold groups, two levels in all; an inner group is `space-4` inside the outer and radius 8. - **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. + at least `space-16` tall and never flatter than 5:1. A decision is never taller than it is wide: a width at which one would be is not + a width the flowchart is drawn at. - **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. + a band is a ruled line of words. **A bar** on a lifeline (`size-diagram-activation`, the head's fill, a 1px `diagram-structure` + edge) shows a participant working, from the message that starts it to the one that ends it. **A frame** (`opt`, `loop`, `alt`) is a + transparent box round a run of messages, 1px solid `diagram-structure`, radius 12, as wide as the participants inside it: structure, + never a panel. Its operator is in a tab at its top start, its condition beside it, and an `alt`'s later branches start under a + dashed rule and the word `else`. Every word of a frame is plated. Frames nest two deep. In a run, messages not yet reached are + quiet: label `text-secondary`, line `diagram-edge-dim`. **As text** (`variant: "text"`) the same data is box-drawing characters in a + code block, and a transcript where the art does not fit; it never scrolls sideways, no character is written over a word, and no + line is ever hidden. - **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. + plain line from a dot on its row to a head on the referenced row. It comes from the column's own record. Where the author states + how many (`cardinality`, on every foreign key or none), the dot and the head give way to crow's-foot marks in the line's ink, inside + `size-diagram-foot` at each end, and the column gap is `space-12` plus `space-3`: three lanes at most, none nearer a table than the + zone plus `radius-xs`. A lane is shared by runs that are never beside each other (their spans overlap or come within `space-8`). A + bar's ink is the pixel that ends at its distance. A key two or more columns away is drawn along a corridor: a row gap clear of the + tables between, or the margin above or below. A line that cannot be drawn clean is left out alone, and its row still writes the target. ### 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. 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). + seat sets them, then "Primary key" and "Foreign key" (built in; the decider's answers, review round 64). A schema that draws + cardinality shows each form drawn ("Exactly one", "Zero or one", "One or many", "Zero or many"), and a sequence each frame operator + drawn, the letters set as the tab sets them ("Only if", "Repeats", "One of these"): built in, because they are notation. - 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 @@ -1790,13 +1827,49 @@ card keeps its owner's colours ([Service marks](#service-marks)). One node may b - 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. + is, where it sits, and what it connects from and to. → ↓ ← ↑ move to the nearest part in that direction: first a part in the same row + or column, then the lowest of tracks along the arrow plus twice the tracks across it. The rule runs on a part's column and rows, + never on its measured centre, and a figure whose parts cannot all be reached that way keeps the author's order. Stacked, the keys + are the author's order. 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. + and never weight, dash or head, so the key stays true. +- **A card may be a link** (`href`): the card is the link and the figure's roving stop, Enter follows it, and its cue is the arrow + after its name ([Links and rows](#links-and-rows)); a press is a colour step. +- **On touch a tap traces,** where lines are drawn. It clears by a tap on the same card, a tap on the ground or "Clear highlight", a + button that stays in the foot and is `aria-disabled` until a trace is up. A hint line says so. A card that answers a tap is at + least 44px tall. A linked card follows its link and is never traced by a tap. Nothing is announced. - A diagram is still unless its author asks for motion (`motion="animated"`); see [Motion in a diagram](#motion-in-a-diagram). A trace's ink changes over `duration-fast`, at once under reduced motion. + +### The viewer + +"Expand", in the figure's foot beside "View as list", opens the figure in a dialog: the window less `space-4` from 720, the whole +window under it, in the form dialog's box, on a native modal `` in the viewer's own chunk, drawing and behaving as `Dialog` does, the +rim included, with the sheet's head, body and foot. "Expand" is words only. Decided by the council's decider alone as part 9 of DECISIONS 301 +(DECISIONS 310, the owner's ask), revised after the pixel review; no draft and no check. **Status:** the implementation has not been reviewed. + +- **What it holds** is the drawn layout, drawn again from the same data at the stage's inner width, never under the figure's least + drawn width and never over the page row unless that is more. The least drawn width is the first width the engine draws the figure + at, found once for its data. The stack is held only when nothing is drawn. A text sequence holds the art at its own width, never the + transcript. A linked card is followed on a click, a tap or Enter, and a link that stays in this tab closes the viewer first. +- **Laid out at 100%, zoomed by the reader.** The layout is made in real CSS pixels and never measured while zoomed. The zoom is + one `transform: scale()` on that layer: never a `viewBox`, CSS `zoom`, a canvas or a picture, and no layer is held at an old + size. Under `scale(3)` the figure is the pixels a 3x screen draws. +- **Fit** is the whole drawing in the stage (padding `space-6`, `space-4` under 720), 200% at most, and is how it opens. The limits + are Fit or 100%, whichever is less, and 400%. Buttons and keys step through 25, 33, 50, 67, 75, 100, 125, 150, 200, 300 and 400, + and a step lands at once. The level is written between the buttons and spoken once it rests. +- **Zoom:** "Zoom out", "Zoom in" and "Fit"; `+`, `−` and `0` while focus is in the stage; Ctrl or Command with the wheel and a + trackpad pinch, about the pointer; two fingers on touch, about their midpoint. +- **Pan is a scroll:** the stage scrolls both ways. A drag past `space-1`, one finger on touch, the wheel, and the scrolling keys + with the stage focused. No momentum and no rubber band. A drag does not select. +- **The foot** holds the figure's key at its real size, the key hint, and "View as list", which puts the list in the stage in + place of the drawing. +- **Focus** opens on the stage (the flush field's inset ring). Esc always closes, and focus returns to "Expand". +- **A trace works. Nothing else moves:** no entrance, flow, mover or run plays in the viewer, and the page's figure holds its + loops while it is open. +- **Under 100%** the words are under 12px and a hairline may be thinner than a device pixel: an overview, with no size or + contrast claim. It does not print: the page prints as always. ### Motion in a diagram Decided by the council for the owner's handoff (DECISIONS 287 to 291 and 292). **Status:** the implementation has not been reviewed. @@ -1805,7 +1878,9 @@ Still is the default and is the drawing above, unchanged. Animated adds an entra or a packet. Motion never carries a fact alone, and it runs only where lines are drawn. - **The entrance plays when the figure comes into view** (two fifths of the drawing, or of the window for a taller one), once a figure - a page load, on every figure that asks for it. It is not the page's one entrance and is not stored between visits. + a page load, on every figure that asks for it. It is not the page's one entrance and is not stored between visits, unless the figure + asks for `entrance: "first-visit"`: then a mark is stored when an entrance that played finishes or gives way to the reader, and later + visits are at rest. A visit at rest by mode stores nothing. - **Trace:** each line draws along its length at `speed-diagram-trace`, between `duration-diagram-line-min` and `-line-max`, on `ease-in-out`, in the author's order (a schema's by where each starts), `duration-diagram-stagger` apart. A head fades in over `duration-slow` as its line is 85% drawn. Each line is revealed on its own. @@ -1819,9 +1894,10 @@ or a packet. Motion never carries a fact alone, and it runs only where lines are - **Measured again** (the faces arriving, a change of width, a parent's render), a figure whose lines are the same is not written to; a pending figure stays pending on its new lines; a running entrance carries on, on the new lines, from the clock it started on, with every line that was whole still whole; a layout with no lines is at rest. A loop starts again on the new lines. -- **Flow** (`flow` on a main or plain edge): cuts of `size-cut` in the ground colour every `size-diagram-flow` march toward the head at +- **Flow** (`flow` on an edge): cuts of `size-cut` in the ground colour every `size-diagram-flow` march toward the head at `speed-diagram-flow`. Cuts exist only while they move: held, traced, still and printed, the line is solid, so the key stays true. A line - with under 48px showing does not flow. + with under 48px showing does not flow. A dashed line's own dashes march, one period every 625ms, and sit where the key draws them + whenever they are not moving. - **Pulse** (`pulse`, a route of nodes): a solid bead of `size-diagram-bead`, at most two fifths of the line showing, one hairline proud of its line on each side, at `speed-diagram-pulse`. It leaves from a card's edge and is taken in at the line's end, rests `duration-diagram-rest` at each card, and starts again `duration-diagram-pause` after the route. @@ -1836,6 +1912,8 @@ or a packet. Motion never carries a fact alone, and it runs only where lines are `data-loops="held"` clears them to rest. A figure that can loop draws "Pause animations", the hold's own button (`LoopsToggle`'s Button form at `size="sm"`), in its foot after "View as list" (WCAG 2.2.2). A trace stops them; they start again `duration-diagram-pause` after it ends. Neither motion button prints. +- **A text sequence** builds by ink: a message's label and arrow lift to their resting ink at its turn. No line is hidden and there is + no caret. - **A sequence's run** (`run`): "Play the run" sends one packet through every message in order. It may pass five seconds; while it runs the button reads "Stop the run" and stops it. The hold does not stop it. - **Reduced motion:** the figure is still; a run steps through its messages by colour alone. **Forced colours:** the figure is still; a @@ -1846,8 +1924,9 @@ or a packet. Motion never carries a fact alone, and it runs only where lines are Decided by the council for the owner's handoff (DECISIONS 287 to 291 and 292). **Status:** the implementation has not been reviewed. -An architecture card may carry its service's own mark: 16px (`size-icon-sm`), in the top end corner inside the padding, with nothing -behind it. The card's first line keeps `space-6` clear of it. +An architecture card, a data flow's step and a sequence's participant may carry its service's own mark: 16px (`size-icon-sm`), in the top end corner inside the padding, with nothing +behind it. The card's first line keeps `space-6` clear of it. A participant's head keeps `space-6` clear on both sides, so its name stays +over its lifeline; a stacked chip draws the mark before the name. - **A mark is its owner's file and Basalt never recolours it.** It has a form for light grounds and a form for dark grounds; a card takes the form for its ground, and the focal card the other theme's. A one-colour mark with one published file and no rule against it gets its @@ -1876,6 +1955,13 @@ behind it. The card's first line keeps `space-6` clear of it. the input boundary and do not step. - Print: the lines, the key's swatches, a card's mark and every focal node's fill (with a mark or without, DECISIONS 298) print whatever the reader's "Background graphics" setting (`print-color-adjust: exact`, with the `-webkit-` form). +- Forced colours: cardinality marks follow their line; an activation's edge is `CanvasText`; a frame's edges are `GrayText`; a + linked name is `LinkText`, underlined. +- Print: a figure prints untraced, in its resting ink, and in the light theme whatever the screen shows. +- Right to left: drawn, the figure mirrors and its words do not; stacked, not yet (the rail, the trunk and the end gutter stay on their + left-to-right sides: a named gap, on the backlog). Identifiers are isolated left to right as runs; named sides swap; the arrow keys + stay physical; the text art stays left to right. +- Export: a linked card's arrow is not drawn in a file. ### Diagram tokens @@ -1897,6 +1983,8 @@ behind it. The card's first line keeps `space-6` clear of it. | `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 | +| `size-diagram-activation` | 8px | An activation bar's width | +| `size-diagram-foot` | 14px | The room of a cardinality mark at a line's end | The motion tokens (DECISIONS 292). The motion tokens do not collapse under reduced motion: nothing they time runs there. @@ -1926,7 +2014,9 @@ Under more contrast `diagram-focal-rule` is drawn as `diagram-focal-rule-contras 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. +(`space-6`), the end gutter (lanes at `space-3-5`, four at most), the turn stagger (`space-5`), the schema's gap where marks are drawn +(`space-12` plus `space-3`), a corridor's lanes (`space-3`), the viewer's zoom steps and limits (ratios, the reader's) and the +quarter-point slots are rules made of the space scale. ## Layout @@ -2418,6 +2508,9 @@ form of a column the page docks when it is wide enough, and it opens from the si from the bottom of the screen. The top `Sheet` stays the site's narrow menu. (The owner's DECISIONS 222: lists are paginated with a choice of how many to show, and can be filtered; a form or task opens as a centered modal over a darkened page, not a side panel.) +A diagram's viewer is not a task: it is a figure at the window's size ([Diagrams](#the-viewer)). It uses the dialog's box and the +full-screen modal under 720, and the scrim always closes it. + ### Everything that changes a list sits above it The filters come first (`FilterToolbar`), then one band (`ListBand`) with the count, the pager and the page size. Only the rows below change, so nothing above can be pushed. A bar diff --git a/docs/motion.md b/docs/motion.md index 7d4e8f48..ac4d76bd 100644 --- a/docs/motion.md +++ b/docs/motion.md @@ -85,6 +85,12 @@ only where lines are drawn. The entrance plays when the figure comes into view a The rules and the tokens are in [Motion in a diagram](foundations.md#motion-in-a-diagram). Status: decided by the council (DECISIONS 287 to 291 and 292); the implementation hasn't been reviewed. +DECISIONS 306 adds three things. An entrance is not stored between visits unless the figure asks for `entrance: "first-visit"`: then a +mark is stored when an entrance that played finishes or gives way to the reader, and later visits are at rest; a visit at rest by mode stores +nothing. Flow is on any edge: a dashed line's own dashes march, one period every 625ms, and sit where the key draws them whenever they are not +moving. A text sequence builds by ink: a message's label and arrow lift to their resting ink at its turn. No line is hidden and there is no caret. +There is no blinking caret. The diagram's viewer (DECISIONS 310) is still: no entrance, flow, mover or run plays in it, and a zoom lands at once. + ## The hover glide Menu, Select, Combobox and CommandMenu draw one plate per popup, and navigation draws one pill per list, which follows the pointer between rows on `duration-base` and `ease-out`, whatever the distance. Each row's own plate is the fallback and stays correct with no script. Base UI's `data-highlighted` (and cmdk's `data-selected`) stays the authority for which row is active; the glide only paints it, and an input-modality check decides whether the plate travels (pointer) or snaps (keyboard). diff --git a/package-lock.json b/package-lock.json index 89e85132..93fc9dec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4330,6 +4330,13 @@ "node": ">= 0.4" } }, + "node_modules/elkjs": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.12.1.tgz", + "integrity": "sha512-IhMYKHE4S2vtx0QrhBP3lYOIKDeIiJXBrdq9MGYkuB8ZHqhrBnHNfSUndjXFewrX1CPK8chwq+2NA0K0hliYuw==", + "dev": true, + "license": "EPL-2.0 OR GPL-3.0-or-later" + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -7239,6 +7246,7 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "axe-core": "4.14.0", + "elkjs": "0.12.1", "esbuild": "0.28.2", "geist": "1.9.0", "playwright": "1.63.0", diff --git a/packages/react/THIRD-PARTY-NOTICES.md b/packages/react/THIRD-PARTY-NOTICES.md new file mode 100644 index 00000000..f7ef38c1 --- /dev/null +++ b/packages/react/THIRD-PARTY-NOTICES.md @@ -0,0 +1,13 @@ +# Third-party code + +## elkjs + +`@srasyndicate/basalt/diagram-layout` (automatic diagram layout, DECISIONS 306, 1.8) imports [elkjs](https://github.com/kieler/elkjs) 0.12.1, +the Eclipse Layout Kernel compiled to JavaScript, unmodified. Its file, `lib/elk.bundled.js`, is copied unchanged into this package as +`dist/diagram-elk.js` (inside a small module wrapper), and its licence is beside it in `dist/elkjs/LICENSE.md`. That file is the one copy +the package ships: elkjs is a build input of the package (a development dependency), not a dependency an app installs. + +- Licence: EPL-2.0 OR GPL-3.0-or-later. Basalt uses it under the Eclipse Public License 2.0 (https://www.eclipse.org/legal/epl-2.0/). +- Source: https://github.com/kieler/elkjs (the Eclipse Layout Kernel's own source: https://github.com/eclipse/elk). +- It is loaded only when an automatic figure has no `placement`. An app or page that places at build time with `placeDiagram` and passes `placement` + ships none of it. An app whose browser bundle holds elkjs distributes it, and owes its notice and a pointer to its source. diff --git a/packages/react/build.mjs b/packages/react/build.mjs index 2d890c6f..5073bdf0 100644 --- a/packages/react/build.mjs +++ b/packages/react/build.mjs @@ -37,7 +37,7 @@ const packageDir = (name) => { // every file that entry shares with an ordinary import (utils, icon, kbd, Phosphor's icon base) is merged into one chunk // that the ordinary import then loads, whatever it needs: Spinner paid 12.7 KB for a 1 KB component, Skeleton 12 KB. // The panel is loaded on demand, so a second copy of those few files costs nothing until a menu opens. -const external = ["react", "react/*", "react-dom", "react-dom/*", "@base-ui/react", "@base-ui/react/*", "@phosphor-icons/react", "@phosphor-icons/react/*", "cmdk", "shiki", "shiki/*"]; +const external = ["react", "react/*", "react-dom", "react-dom/*", "@base-ui/react", "@base-ui/react/*", "@phosphor-icons/react", "@phosphor-icons/react/*", "cmdk", "shiki", "shiki/*", "elkjs", "elkjs/*"]; // The notice (without its comment marks) that the panel's banner carries and that the opt-in Phosphor plugin (src/tooling/phosphor.ts) puts // in front of the icons it trims. It is one string, so the two comments are identical and a bundler that holds both keeps one copy. const phosphorNotice = `Bundles four icons from @phosphor-icons/react.\n${fs.readFileSync(path.join(packageDir("@phosphor-icons/react"), "LICENSE"), "utf8").trim().replaceAll("*/", "* /")}`; @@ -95,6 +95,41 @@ await esbuild.build({ banner: { js: `"use client";` }, }); +// elkjs as an ES module of its own (DECISIONS 306, 1.8): elkjs's own file, verbatim and unmodified, inside a wrapper that gives it a module and no global +// require, written to dist/diagram-elk.js with its notice. Imported only by diagram-layout, on demand: bundled as CommonJS by an app, elkjs put the +// bundler's CommonJS helpers in the chunk every component's bundle shares. +fs.mkdirSync(dist, { recursive: true }); +{ + const elk = fs.readFileSync(path.join(packageDir("elkjs"), "lib", "elk.bundled.js"), "utf8"); + fs.writeFileSync(path.join(dist, "diagram-elk.js"), `/*! elkjs 0.12.1 (https://github.com/kieler/elkjs), the Eclipse Layout Kernel: EPL-2.0 OR GPL-3.0-or-later, used under EPL-2.0, unmodified. */ +const elkModule = { exports: {} }; +(function (module, exports, require, define) { +${elk} +}).call(globalThis, elkModule, elkModule.exports, undefined, undefined); +export default elkModule.exports; +`); + // Its licence goes with the copy (Neon's B11 of the code review): the package redistributes the file, so it carries the text it is distributed under. + fs.mkdirSync(path.join(dist, "elkjs"), { recursive: true }); + fs.copyFileSync(path.join(packageDir("elkjs"), "LICENSE.md"), path.join(dist, "elkjs", "LICENSE.md")); +} + +// The diagram viewer is the fourth (DECISIONS 310, 9.13): "Expand" loads it at its first hover, focus or touch, and it brings the form dialog's box (on a native +// , no Base UI dialog), the sheet's parts and the buttons with it, inlined for the same reason as the motion's. It imports the figure and the engine only as types: the figure hands them over when it opens +// the viewer (ViewerKit), so this chunk never holds a second copy of the engine. +await esbuild.build({ + bundle: true, + format: "esm", + platform: "neutral", + target: "es2022", + jsx: "automatic", + logLevel: "warning", + entryPoints: [path.join(here, "src/diagram-viewer.tsx")], + outdir: dist, + external: external.filter((name) => !name.startsWith("@phosphor-icons")), + plugins: [{ name: "lazy-flight", setup(build) { build.onResolve({ filter: /^\.\/glyph-flight$/ }, (args) => (args.kind === "dynamic-import" ? { path: "./glyph-flight.js", external: true } : undefined)); } }], + banner: { js: `"use client";` }, +}); + // The root's map for the imports plugin (src/tooling/imports.ts): every name the root exports at run time, and the module that holds it, read from the barrel's source. // `export * from "./glyph-set"` is the one star, and glyph-set is itself a list of `export { X } from "./glyphs/x"`: each glyph maps to its own module. Every // `export` statement in the barrel must be one of the three forms below (`export { … } from "./x";`, `export type { … } from "./x";`, `export * from "./x";`, double @@ -187,7 +222,7 @@ await esbuild.build({ // The core glyphs are modules of their own (src/glyphs), so an app that imports HomeGlyph bundles only HomeGlyph. entryPoints: [ // index.ts is not bundled: it is a barrel of `export { … } from "./module"` and is written as one, below, so each export comes from the module that holds it. - ...fs.readdirSync(path.join(here, "src")).filter((f) => /\.tsx?$/.test(f) && !f.endsWith(".d.ts") && !["command-panel.tsx", "glyph-flight.tsx", "diagram-motion.tsx", "diagram-motion-core.ts", "release-sources.tsx", "rail-tooltip.tsx", "index.ts"].includes(f)).map((f) => path.join(here, "src", f)), + ...fs.readdirSync(path.join(here, "src")).filter((f) => /\.tsx?$/.test(f) && !f.endsWith(".d.ts") && !["command-panel.tsx", "glyph-flight.tsx", "diagram-motion.tsx", "diagram-motion-core.ts", "diagram-viewer.tsx", "diagram-zoom-core.ts", "diagram-elk.ts", "release-sources.tsx", "rail-tooltip.tsx", "index.ts"].includes(f)).map((f) => path.join(here, "src", f)), ...fs.readdirSync(path.join(here, "src", "glyphs")).filter((f) => /\.ts$/.test(f)).map((f) => path.join(here, "src", "glyphs", f)), // The service marks (DECISIONS 292, 2.6): one module a mark under dist/marks, at @srasyndicate/basalt/marks/, never imported by the index, so an // app pays for the marks it imports and no others. Generated by marks/generate.mjs. @@ -198,7 +233,7 @@ await esbuild.build({ ...fs.readdirSync(path.join(here, "src", "tooling")).filter((f) => /\.ts$/.test(f)).map((f) => path.join(here, "src", "tooling", f)), ], define: { __PHOSPHOR_NOTICE__: JSON.stringify(phosphorNotice), __BASALT_ROOT_MAP__: JSON.stringify(JSON.stringify(rootMap)) }, - plugins: [{ name: "lazy-modules", setup(build) { build.onResolve({ filter: /^\.\/(command-panel|glyph-flight|diagram-motion|release-sources|rail-tooltip)$/ }, (args) => (args.kind === "dynamic-import" ? { path: `${args.path}.js`, external: true } : undefined)); } }], + plugins: [{ name: "lazy-modules", setup(build) { build.onResolve({ filter: /^\.\/(command-panel|glyph-flight|diagram-motion|diagram-viewer|diagram-layout|diagram-text|diagram-elk|release-sources|rail-tooltip)$/ }, (args) => (args.kind === "dynamic-import" ? { path: `${args.path}.js`, external: true } : undefined)); } }], outdir: dist, bundle: true, splitting: true, @@ -251,7 +286,7 @@ const needsClient = (file, seen = new Set()) => { seen.add(file); return staticImports(fs.readFileSync(path.join(dist, file), "utf8")).some((specifier) => clientImport.test(specifier) || (/^\.\/chunk-/.test(specifier) && needsClient(specifier.slice(2), seen))); }; -for (const file of fs.readdirSync(dist, { recursive: true }).filter((f) => f.endsWith(".js") && !path.basename(f).startsWith("chunk-") && !["command-panel.js", "glyph-flight.js", "diagram-motion.js", "release-sources.js", "rail-tooltip.js"].includes(f))) { +for (const file of fs.readdirSync(dist, { recursive: true }).filter((f) => f.endsWith(".js") && !path.basename(f).startsWith("chunk-") && !["command-panel.js", "glyph-flight.js", "diagram-motion.js", "diagram-viewer.js", "diagram-elk.js", "release-sources.js", "rail-tooltip.js"].includes(f))) { const code = fs.readFileSync(path.join(dist, file), "utf8"); if (needsClient(file)) fs.writeFileSync(path.join(dist, file), `"use client";\n${code}`); } @@ -269,7 +304,9 @@ fs.writeFileSync(path.join(dist, "head", "loops.js"), loopsBootstrap); // The accent classes are generated with the tokens and ship with the components, whose Badge is the one reader of them. const accents = fs.readFileSync(require.resolve("@srasyndicate/basalt-tokens/accents.css"), "utf8"); -const components = `${fs.readFileSync(path.join(here, "src/styles/components.css"), "utf8")}\n${accents}`; +// `%glyph-mask:name%` in the stylesheet is a core glyph's drawing as a mask (glyph-mask.mjs). +const { withGlyphMasks } = await import(pathToFileURL(path.join(here, "glyph-mask.mjs")).href); +const components = `${withGlyphMasks(fs.readFileSync(path.join(here, "src/styles/components.css"), "utf8"))}\n${accents}`; // Geist Sans and Mono, variable (SIL OFL 1.1, licence shipped beside the files). const geist = path.join(packageDir("geist"), "dist", "fonts"); diff --git a/packages/react/glyph-mask.mjs b/packages/react/glyph-mask.mjs new file mode 100644 index 00000000..a6129709 --- /dev/null +++ b/packages/react/glyph-mask.mjs @@ -0,0 +1,19 @@ +// `%glyph-mask:name%` in a stylesheet is a data URI of that core glyph, drawn with the set's 2.25 round stroke on the 24 grid, for a CSS mask (a diagram's +// link cue, DECISIONS 306, 1.4): the same drawing as the HTML skill's (tools/html-skill/build.mjs), from the same source, never redrawn by hand. The package's +// build and the review walkthrough (which reads the source stylesheet) both write it in. +import { GLYPHS, slots } from "./glyphs/source.mjs"; + +export function glyphMaskUri(name) { + const glyph = GLYPHS[name]; + if (!glyph || !(glyph.s || glyph.of)) throw new Error(`glyph-mask: "${name}" is not a core glyph with a drawing`); + const near = (a, b) => Math.abs(a - b) < 1e-6; + const d = (glyph.s ?? slots(name)).filter((slot) => slot[8]).map(([x0, y0, x1, y1, x2, y2, x3, y3]) => { + const straight = near(x1, x0 + (x3 - x0) / 3) && near(y1, y0 + (y3 - y0) / 3) && near(x2, x0 + (2 * (x3 - x0)) / 3) && near(y2, y0 + (2 * (y3 - y0)) / 3); + return straight ? `M${x0} ${y0}L${x3} ${y3}` : `M${x0} ${y0}C${x1} ${y1} ${x2} ${y2} ${x3} ${y3}`; + }).join(""); + const svg = ``; + return `data:image/svg+xml,${svg.replace(//g, "%3E")}`; +} + +/** The stylesheet with every `%glyph-mask:name%` written in. */ +export const withGlyphMasks = (css) => css.replace(/%glyph-mask:([\w-]+)%/g, (_, name) => glyphMaskUri(name)); diff --git a/packages/react/package.json b/packages/react/package.json index 471bf516..647c7cb7 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -25,6 +25,14 @@ "types": "./dist/tooling/imports.d.ts", "default": "./dist/tooling/imports.js" }, + "./diagram-export": { + "types": "./dist/diagram-export.d.ts", + "default": "./dist/diagram-export.js" + }, + "./diagram-layout": { + "types": "./dist/diagram-layout.d.ts", + "default": "./dist/diagram-layout.js" + }, "./marks/*": { "types": "./dist/marks/*.d.ts", "default": "./dist/marks/*.js" @@ -37,7 +45,8 @@ }, "files": [ "dist", - "THIRD-PARTY-MARKS.md" + "THIRD-PARTY-MARKS.md", + "THIRD-PARTY-NOTICES.md" ], "scripts": { "build": "node build.mjs", @@ -60,6 +69,7 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "axe-core": "4.14.0", + "elkjs": "0.12.1", "esbuild": "0.28.2", "geist": "1.9.0", "playwright": "1.63.0", diff --git a/packages/react/src/architecture-diagram.tsx b/packages/react/src/architecture-diagram.tsx index 779c3b91..b6d0eec4 100644 --- a/packages/react/src/architecture-diagram.tsx +++ b/packages/react/src/architecture-diagram.tsx @@ -2,12 +2,12 @@ import * as React from "react"; import { DiagramFigure } from "./diagram-figure"; import type { DiagramFigureProps } from "./diagram-figure"; -import type { ArchitectureNode, DiagramFlowEdge, DiagramGroup, DiagramPacket } from "./diagram-core"; +import type { ArchitectureNode, DiagramFlowEdge, DiagramGroup, DiagramPacket, DiagramPlacement, DiagramUnplaced } from "./diagram-core"; -export type { ArchitectureNode, DiagramEdge, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramSide } from "./diagram-core"; +export type { ArchitectureNode, DiagramEdge, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./diagram-core"; export type { DiagramFigureProps } from "./diagram-figure"; -export interface ArchitectureDiagramProps extends DiagramFigureProps { +interface ArchitectureDiagramBase 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. */ @@ -20,8 +20,28 @@ export interface ArchitectureDiagramProps extends DiagramFigureProps { packet?: DiagramPacket; } +/** + * Authored (the default): every card carries its `col` and `row`. Automatic (`layout: "auto"`, DECISIONS 306, 1.8): no card needs them, and none are read. + */ +export type ArchitectureDiagramProps = Omit & ( + | { layout?: "authored"; direction?: never; placement?: never; nodes: ArchitectureNode[] } + | { + /** + * `"auto"` (DECISIONS 306, 1.8): elkjs gives each card a column and a row, and Basalt sizes, routes and seats the figure as it does an authored one; a + * card's `col` and `row` are left out (and not read). Place at build time with `placeDiagram` from `@srasyndicate/basalt/diagram-layout` and pass + * `placement`: then elkjs never loads in the browser. Without it the layout module loads on demand at 640 or wider. + */ + layout: "auto"; + /** Under `"auto"`: the one direction tried. Left out, the type's own (right for an architecture and a schema, down for a flowchart), then the other. */ + direction?: "right" | "down"; + /** Under `"auto"`: `placeDiagram`'s answer for one direction or both. */ + placement?: DiagramPlacement | DiagramPlacement[]; + nodes: Array>; + } +); + /** An architecture diagram (DECISIONS 281): nodes with a kind, a name and a detail, groups, and three kinds of line. */ -export function ArchitectureDiagram({ nodes, groups, edges, pulse, packet, motion, title, heading, legend, ...props }: ArchitectureDiagramProps) { - const spec = React.useMemo(() => ({ type: "architecture" as const, title, heading, legend, nodes, groups, edges, motion, pulse, packet }), [title, heading, legend, nodes, groups, edges, motion, pulse, packet]); - return ; +export function ArchitectureDiagram({ nodes, groups, edges, pulse, packet, motion, entrance, layout, direction, placement, title, heading, legend, ...props }: ArchitectureDiagramProps) { + const spec = React.useMemo(() => ({ type: "architecture" as const, title, heading, legend, nodes: nodes as ArchitectureNode[], groups, edges, motion, entrance, layout, direction, placement, pulse, packet }), [title, heading, legend, nodes, groups, edges, motion, entrance, layout, direction, placement, pulse, packet]); + return ; } diff --git a/packages/react/src/data-flow-diagram.tsx b/packages/react/src/data-flow-diagram.tsx index 707c7039..166d9ecd 100644 --- a/packages/react/src/data-flow-diagram.tsx +++ b/packages/react/src/data-flow-diagram.tsx @@ -22,7 +22,7 @@ export interface DataFlowDiagramProps extends DiagramFigureProps { } /** A data flow (DECISIONS 281): lanes as bands, steps numbered in order; stacked, a step says its lane. */ -export function DataFlowDiagram({ lanes, nodes, edges, stepLabel, pulse, packet, motion, title, heading, legend, ...props }: DataFlowDiagramProps) { - const spec = React.useMemo(() => ({ type: "data-flow" as const, title, heading, legend, lanes, nodes, edges, stepLabel, motion, pulse, packet }), [title, heading, legend, lanes, nodes, edges, stepLabel, motion, pulse, packet]); - return ; +export function DataFlowDiagram({ lanes, nodes, edges, stepLabel, pulse, packet, motion, entrance, title, heading, legend, ...props }: DataFlowDiagramProps) { + const spec = React.useMemo(() => ({ type: "data-flow" as const, title, heading, legend, lanes, nodes, edges, stepLabel, motion, entrance, pulse, packet }), [title, heading, legend, lanes, nodes, edges, stepLabel, motion, entrance, pulse, packet]); + return ; } diff --git a/packages/react/src/diagram-core.ts b/packages/react/src/diagram-core.ts index a9a60ddb..396f50b1 100644 --- a/packages/react/src/diagram-core.ts +++ b/packages/react/src/diagram-core.ts @@ -22,7 +22,7 @@ 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 DiagramLegend { main?: string; plain?: string; dashed?: string; focal?: string; group?: string; activation?: string } export interface DiagramNode { id: string; @@ -38,6 +38,10 @@ export interface DiagramNode { row: number; /** Indented in the stacked drawing; a node is on the spine unless it is a branch. */ branch?: boolean; + /** The card is a link (DECISIONS 306, 1.4): the card itself is an ``, the figure's roving stop, and Enter follows it. */ + href?: string; + /** `"_blank"` opens a new tab (with `rel="noopener noreferrer"`); the cue is then the external arrow. */ + target?: "_blank"; } export interface DiagramEdge { @@ -52,7 +56,8 @@ export interface DiagramEdge { toSide?: DiagramSide; } -export interface DiagramGroup { id: string; label: string } +/** A group of an architecture. `parent` names the group it is in (DECISIONS 306, 1.3): two levels at most, a node naming its innermost group. */ +export interface DiagramGroup { id: string; label: string; parent?: string } /** * A service's own mark for an architecture card (DECISIONS 292, 2.7): its owner's file for light grounds and, if it has one, for dark grounds, each * a URL the app has the right to show: a relative path, an `https` URL or a `data:image/` URI, from files the app ships, never from user input (anything else @@ -78,11 +83,22 @@ export interface DiagramPacket { export type DiagramMotion = "still" | "animated"; export type FlowchartNode = DiagramNode & { shape?: "step" | "decision" | "terminal" }; export interface DataFlowLane { id: string; label: string } -export type DataFlowNode = Omit & { 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 type DataFlowNode = Omit & { lane: string; mark?: DiagramMark }; +/** A participant may carry its service's mark (DECISIONS 306, 1.6), never a person. */ +export interface SequenceParticipant { id: string; name: string; kind?: string; short?: string; focal?: boolean; mark?: DiagramMark } +/** A message. `activate` starts its receiver working; `deactivate` stops its sender after it (DECISIONS 306, 1.2). */ +export type SequenceMessage = { from: string; to: string; label: string; note?: string; kind?: DiagramLineKind; activate?: boolean; deactivate?: boolean }; +/** A step: a message, a band, or a frame round a run of steps (`opt`, `loop`, or `alt` with two or more branches). Frames nest two deep. */ +export type SequenceStep = SequenceMessage | { band: string } + | { frame: "opt" | "loop"; label: string; steps: SequenceStep[] } + | { frame: "alt"; branches: Array<{ label: string; steps: SequenceStep[] }> }; +/** The words the key and the list say for each frame operator, and for an alt's later branches. */ +export interface DiagramFrameLabels { opt?: string; loop?: string; alt?: string; else?: string } +/** How many rows each end of a foreign key allows (DECISIONS 306, 1.1): `from` is the column's own table, `to` the referenced one, which is one row at most. */ +export type DiagramCardinality = "one" | "zero-or-one" | "one-or-many" | "zero-or-many"; +export interface DiagramCardinalityPair { from: DiagramCardinality; to?: "one" | "zero-or-one" } +export interface SchemaColumn { name: string; type?: string; key?: "PK" | "FK"; references?: string; cardinality?: DiagramCardinalityPair } +export interface SchemaTable { name: string; col: number; row: number | [number, number]; focal?: boolean; more?: number; columns: SchemaColumn[]; href?: string; target?: "_blank" } 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. */ @@ -105,6 +121,28 @@ export interface DiagramSpec { pulse?: string[]; packet?: DiagramPacket; run?: boolean; + /** A sequence's frame words (DECISIONS 306, 1.2): "Only if", "Repeats", "One of these", "Otherwise". */ + frameLabels?: DiagramFrameLabels; + /** `"first-visit"` (DECISIONS 306, 1.5): an animated figure's entrance plays until it has played once on this page, then is at rest. Needs an `id`. */ + entrance?: "always" | "first-visit"; + /** A sequence drawn as text art (DECISIONS 306, 1.2). */ + variant?: "drawn" | "text"; + /** Automatic layout (1.8): `"auto"` takes each card's column and row from `placement` (elkjs's, from `placeDiagram`), and a card's own are not read. */ + layout?: "authored" | "auto"; + direction?: "right" | "down"; + placement?: DiagramPlacement | DiagramPlacement[]; +} + +/** A card of an automatic figure (1.8): its `col` and `row` may be left out (and are not read). */ +export type DiagramUnplaced = Omit & { col?: number; row?: number | [number, number] }; + +/** Where an automatic figure's cards go in one direction (1.8): `placeDiagram`'s answer. */ +export interface DiagramPlacement { + direction: "right" | "down"; + cells: Record; + /** The grid's tracks (DECISIONS 322, rule 1): at least the cards' own, and more where a track holds only a main line's way. */ + cols?: number; + rows?: number; } // ============================================================================================================================================ @@ -113,7 +151,7 @@ export interface DiagramSpec { 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 MColumn { name: string; type?: string; key?: "PK" | "FK"; ref?: { table: string; column: string; row: number }; card?: { from: DiagramCardinality; to: "one" | "zero-or-one" } } export interface MNode { id: string; i: number; @@ -136,6 +174,9 @@ export interface MNode { short?: string; /** A card's mark: a bundled id (the HTML skill's page holds its rule) or the two URLs. */ mark?: { id?: string; onLight?: string; onDark?: string; says?: string[] }; + /** A link card (1.4). */ + href?: string; + blank?: boolean; } export interface MEdge { i: number; @@ -149,10 +190,18 @@ export interface MEdge { fromRow?: number; toRow?: number; fk?: boolean; - /** A live stream (DECISIONS 292, 1.6). */ + /** A foreign key's stated cardinality (1.1): its ends are crow's-foot marks in place of the dot and the head. */ + card?: { from: DiagramCardinality; to: "one" | "zero-or-one" }; + /** A live stream (DECISIONS 292, 1.6); on a dashed line its own dashes march (DECISIONS 306, 1.5). */ flow?: boolean; } -export type MStep = { band: string } | { n: number; from: string; to: string; label: string; note?: string; kind: DiagramLineKind }; +export type MStep = { band: string } | { n: number; from: string; to: string; label: string; note?: string; kind: DiagramLineKind; activate?: boolean; deactivate?: boolean } + /** A frame opens (its operator, label and depth, and the participants' columns it spans), an alt's later branch starts, or a frame closes (1.2). */ + | { open: "opt" | "loop" | "alt"; label: string; depth: number; a: number; b: number } + | { otherwise: string; depth: number } + | { close: number }; +/** A participant working: a bar from the message that starts it to the one that ends it, at a depth from 1 to 3 (1.2). */ +export interface MBar { who: string; from: number; to: number; depth: number } export interface Model { type: DiagramType; title: string; @@ -161,22 +210,40 @@ export interface Model { nodes: MNode[]; byId: Map; edges: MEdge[]; - groups: Array; + /** `members` are a group's own nodes; `all` adds its child groups' (its box's extent); `depth` is 1 or 2. Outer groups come first. */ + groups: Array; lanes: DataFlowLane[]; steps: MStep[]; + /** A sequence's activation bars (1.2). */ + bars: MBar[]; + /** A sequence's frame words. */ + frameWords: { opt: string; loop: string; alt: string; else: string }; cols: number; rows: number; shapeLabels: Required; stepWord: (n: number) => string; warnings: string[]; /** Motion (DECISIONS 292). Read and ignored when still. */ - motion: { animated: boolean; pulse?: string[]; packet?: { path: string[]; repeat: boolean; send?: number | string }; run: boolean }; + motion: { animated: boolean; pulse?: string[]; packet?: { path: string[]; repeat: boolean; send?: number | string }; run: boolean; firstVisit?: boolean }; /** Work that depends on the model alone, done once (see `memo`). */ memo: Map; + /** Mirrored for a right-to-left figure (1.7). */ + rtl?: boolean; + /** An automatic figure with no placement yet (1.8): it is stacked, every word present, until one arrives. */ + unplaced?: boolean; + /** A sequence drawn as text art (1.2): a code block holding the art where it fits and the transcript where it does not. */ + text?: boolean; + /** A schema that draws cardinality marks (1.1): its column gap is space-12 plus space-3. */ + marks?: boolean; + /** 5.1's first list, in a development build: reported as errors (console.error), the figure drawn as production draws it. */ + errors: string[]; } const SIDES: DiagramSide[] = ["top", "right", "bottom", "left"]; const LINE_KINDS: DiagramLineKind[] = ["main", "plain", "dashed"]; +const CARDS: DiagramCardinality[] = ["one", "zero-or-one", "one-or-many", "zero-or-many"]; +/** A form's words: the key's ("Exactly one") and the list's ("exactly one"). */ +const CARD_WORDS: Record = { one: "Exactly one", "zero-or-one": "Zero or one", "one-or-many": "One or many", "zero-or-many": "Zero or many" }; 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. */ @@ -187,6 +254,11 @@ const record = (from?: Record): Record => Object.assign const own = (r: Record | undefined, id: string): T | undefined => (r && Object.prototype.hasOwnProperty.call(r, id) ? r[id] : undefined); export interface BuildOptions { + /** The placement an automatic figure is drawn from (1.8), chosen by the figure from those it has. */ + placement?: DiagramPlacement; + /** The figure's computed direction is right to left (DECISIONS 306, 1.7): the model is mirrored, so column 1 is drawn at the right and a named left or + * right side swaps. The engine then lays out and routes as it does any figure; the words do not mirror. */ + rtl?: boolean; /** 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; } @@ -202,9 +274,12 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model const checks = dev && options.checks !== false; const warnings: string[] = []; const warn = (message: string) => { warnings.push(message); }; + // 5.1's first list (the decider's ruling 1 on the re-check): reported as an error, once for a figure, and the figure is drawn as production draws it. + const errors: string[] = []; + const error = (message: string) => { errors.push(message); }; const legendIn = (spec.legend ?? {}) as Record; const legend: DiagramLegend = {}; - for (const k of ["main", "plain", "dashed", "focal", "group"] as const) { const w = txt(legendIn[k]); if (w) legend[k] = w; } + for (const k of ["main", "plain", "dashed", "focal", "group", "activation"] 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; @@ -224,6 +299,8 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model }; const trackOf = (v: unknown, what: string): number => { if (typeof v === "number" && Number.isInteger(v) && v >= 1) return v; + // An automatic figure's cards take the placement's tracks (1.8). + if (spec.layout === "auto" && (v === undefined || v === null)) return 1; dev && warn(`${what} is ${JSON.stringify(v)}, not a whole number from 1: it is placed at 1`); return 1; }; @@ -246,7 +323,23 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model mark: type === "architecture" ? markOf((raw as { mark?: unknown }).mark, dev ? warn : undefined) : undefined, }); } - 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) }); } + if (type === "architecture") { + const raw = (spec.groups ?? []).map((g) => ({ id: String(g.id ?? ""), label: String(g.label ?? ""), parent: txt(g.parent) })); + const byGroup = new Map(raw.map((g) => [g.id, g])); + // Depth by the parent chain: an unknown parent or a cycle is an error, and the group is drawn at the top level. + const depthOf = (g: (typeof raw)[number]): number => { + if (!g.parent) return 1; + const p = byGroup.get(g.parent); + if (!p) { dev && error(`the group "${g.label}" names the parent "${g.parent}", which is not a group`); g.parent = undefined; return 1; } + if (p.parent === g.id || p.id === g.id) { dev && error(`the groups "${g.label}" and "${p.label}" are each other's parent`); g.parent = undefined; return 1; } + if (p.parent) { dev && error(`the group "${g.label}" is a third level: groups nest two deep`); g.parent = undefined; return 1; } + return 2; + }; + const depths = raw.map(depthOf); + raw.forEach((g, k) => groups.push({ ...g, depth: depths[k]!, members: nodes.filter((n) => n.group === g.id).map((n) => n.id), all: [] })); + for (const g of groups) g.all = [...g.members, ...groups.filter((c) => c.parent === g.id).flatMap((c) => c.members)]; + groups.sort((a, b) => a.depth - b.depth); + } } else if (type === "data-flow") { 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])); @@ -259,15 +352,59 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model nodes.push({ 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, + mark: markOf((raw as { mark?: unknown }).mark), }); } } else if (type === "sequence") { - (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 }); }); + (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, mark: markOf((p as { mark?: unknown }).mark) }); }); let n = 0; - for (const s of spec.steps ?? []) { - 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}`) }); } - } + const colOf = new Map(nodes.map((p) => [p.id, p.col])); + // Messages number straight through frames. A frame spans the columns of the participants that send or receive inside it, and the column a + // self-call's words run into (1.2). + const walk = (list: SequenceStep[], depth: number): [number, number] => { + let a = Infinity, b = -Infinity; + for (const s of list ?? []) { + if (!s || typeof s !== "object") continue; + if ("band" in s) { + if (depth > 0) dev && error(`the band "${String(s.band)}" is inside a frame: a band is the whole figure's`); + steps.push({ band: String(s.band ?? "") }); + continue; + } + if ("frame" in s) { + if (depth >= 2) { dev && error("a frame is a third level: frames nest two deep"); continue; } + const op = s.frame === "alt" || s.frame === "loop" || s.frame === "opt" ? s.frame : "opt"; + const branches = op === "alt" ? ((s as { branches?: Array<{ label: string; steps: SequenceStep[] }> }).branches ?? []) : [{ label: (s as { label: string }).label, steps: (s as { steps: SequenceStep[] }).steps }]; + if (op === "alt" && branches.length < 2) dev && error("an alt frame has one branch: it needs two or more"); + const label = String(branches[0]?.label ?? ""); + if (label.length > 40) dev && error(`the frame label "${label}" is over 40 characters`); + const at = steps.length; + steps.push({ open: op, label, depth: depth + 1, a: 0, b: 0 }); + branches.forEach((br, k) => { + if (k) { const l = String(br.label ?? ""); if (l.length > 40) dev && error(`the frame label "${l}" is over 40 characters`); steps.push({ otherwise: l, depth: depth + 1 }); } + if (!br.steps?.length) dev && error(`a frame or branch ("${String(br.label ?? "")}") is empty`); + const [x, y] = walk(br.steps ?? [], depth + 1); + a = Math.min(a, x); b = Math.max(b, y); + const open = steps[at] as { a: number; b: number }; + open.a = Math.min(open.a || Infinity, x); open.b = Math.max(open.b, y); + }); + steps.push({ close: depth + 1 }); + continue; + } + n++; + const label = String(s.label ?? ""); + // A message's second line is its note (1.4): a break in its label is an error, and it is drawn on one line. + if (label.includes("\n")) dev && error(`message ${n}'s label has a break: a message's second line is its note`); + const from = String(s.from ?? ""), to = String(s.to ?? ""); + steps.push({ n, from, to, label: said(label), note: txt(s.note), kind: kindOf(s.kind, `message ${n}`), activate: s.activate === true || undefined, deactivate: s.deactivate === true || undefined }); + const ca = colOf.get(from) ?? 1, cb = colOf.get(to) ?? 1; + // A self-call's words run into the next column (the one before it on the last participant). + const run = ca === cb ? (ca === nodes.length ? ca - 1 : ca + 1) : ca; + a = Math.min(a, ca, cb, run); b = Math.max(b, ca, cb, run); + } + return [a, b]; + }; + walk(spec.steps ?? [], 0); + for (const st of steps) if ("open" in st && !Number.isFinite(st.a)) { st.a = 1; st.b = Math.max(1, nodes.length); } } else if (type === "schema") { for (const t of spec.tables ?? []) { const name = String(t.name ?? ""); @@ -282,6 +419,44 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model } } + // Automatic layout (1.8): each card's column and row are the placement's; a card's own are not read (a development build says so once). + let unplaced = false; + if (spec.layout === "auto" && (type === "architecture" || type === "flowchart" || type === "schema")) { + const raw = (type === "schema" ? spec.tables : spec.nodes) as Array<{ col?: unknown; row?: unknown }> | undefined; + if (checks && (raw ?? []).some((n) => n && (n.col !== undefined || n.row !== undefined))) warn('a card under layout="auto" has a col or row, which is not read: there are no hints'); + const cells = options.placement?.cells; + if (!cells) unplaced = true; + for (const n of nodes) { const c = cells?.[n.id]; n.col = c?.col ?? 1; n.row = n.row2 = c?.row ?? 1; } + // A placement that puts two cards in one cell, or leaves a card out, is not used (8.5; Neon's B8 of the code review): the figure tries its other + // direction, then stacks, and a development build names the cards. (A card inside a group's box it is not in is checked below, with the groups.) + if (cells) { + const seen = new Map(); + for (const n of nodes) { + const c = own(cells, n.id); + if (!c) { unplaced = true; dev && warn(`the placement has no cell for ${n.id}, so it is not used`); continue; } + const key = `${c.col},${c.row}`; + if (seen.has(key)) { unplaced = true; dev && warn(`the placement puts ${seen.get(key)} and ${n.id} in one cell, so it is not used`); } + seen.set(key, n.id); + } + } + if (cells && !unplaced) for (const g of groups) { + const mem = g.all.map((id) => nodes.find((n) => n.id === id)!).filter(Boolean); + 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.row)); + const inside = nodes.filter((n) => !g.all.includes(n.id) && n.col >= c1 && n.col <= c2 && n.row >= r1 && n.row <= r2); + if (inside.length) { unplaced = true; dev && warn(`the placement puts ${inside.map((n) => n.id).join(", ")} inside the box of the group "${g.label}", so it is not used`); } + } + } else if (spec.layout === "auto") dev && error(`layout="auto" is for an architecture, a flowchart or a schema, not a ${type}`); + // Link cards (1.4): any card but a sequence's participant (its stacked chip has no room for a 44px target). + const rawCards = (type === "schema" ? spec.tables : type === "sequence" ? spec.participants : spec.nodes) as Array<{ href?: unknown; target?: unknown }> | undefined; + (rawCards ?? []).forEach((raw, k) => { + if (!raw || raw.href === undefined || raw.href === null) return; + const href = String(raw.href); + if (type === "sequence") { dev && error(`${nodes[k]?.id}: a participant cannot be a link (href)`); return; } + if (!href.trim()) { dev && error(`${nodes[k]?.id}'s href is empty`); return; } + const n = nodes[k]; + if (n) { n.href = href; n.blank = raw.target === "_blank"; } + }); const byId = new Map(); for (const n of nodes) { if (dev && !n.id) warn("a node has no id"); @@ -291,8 +466,20 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): 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") { + const cardOf = (v: unknown, where: string): MEdge["card"] => { + if (v === undefined || v === null) return undefined; + const o = v as { from?: unknown; to?: unknown }; + const from = CARDS.includes(o.from as DiagramCardinality) ? (o.from as DiagramCardinality) : undefined; + if (!from) { dev && error(`${where}'s cardinality "from" is ${JSON.stringify(o.from)}, not one, zero-or-one, one-or-many or zero-or-many: it is left out`); return undefined; } + if (o.to === undefined || o.to === null) return { from, to: "one" }; + if (o.to === "one" || o.to === "zero-or-one") return { from, to: o.to }; + // A foreign key points at one row at most. + dev && error(`${where}'s cardinality "to" is ${JSON.stringify(o.to)}: a foreign key references one row at most (one or zero-or-one), so it is drawn as one`); + return { from, to: "one" }; + }; (spec.tables ?? []).forEach((t) => (t.columns ?? []).forEach((c, k) => { const ref = txt(c.references); + if (!ref && c.cardinality !== undefined && c.cardinality !== null) dev && error(`${String(t.name)}.${String(c.name)} states a cardinality but references nothing`); if (!ref) return; const [table, column] = ref.split("."); const target = byId.get(table ?? ""); @@ -300,14 +487,21 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model if (!target || row < 0) { dev && 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: source.id, to: table!, kind: "plain", fromRow: k, toRow: row, fk: true }); + const card = cardOf(c.cardinality, `${String(t.name)}.${String(c.name)}`); + if (card) source.columns![k]!.card = card; + edges.push({ i: edges.length, from: source.id, to: table!, kind: "plain", fromRow: k, toRow: row, fk: true, card }); })); + // All of a figure's foreign keys state how many, or none (1.1). In production an unstated line draws as today, and the key shows both. + const stated = edges.filter((e) => e.card).length; + if (stated && stated < edges.length) dev && error(`cardinality is stated on ${stated} of ${edges.length} foreign keys: state it on every one or none (${edges.filter((e) => !e.card).map((e) => `${e.from}.${byId.get(e.from)!.columns![e.fromRow!]!.name}`).join(", ")} ${edges.length - stated === 1 ? "has" : "have"} none)`); } else if (type !== "sequence") { for (const e of spec.edges ?? []) { const from = String(e.from ?? ""), to = String(e.to ?? ""); if (!byId.has(from) || !byId.has(to)) { dev && 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) dev && warn(`the label "${label}" is over ${MAX_LABEL} characters: longer words belong in the node or the summary`); + const lines = label?.split("\n") ?? []; + if (lines.length > 2) dev && error(`the label "${said(label!)}" has more than one break: a label is two lines at most`); + if (lines.some((l) => l.length > MAX_LABEL)) dev && error(`a line of the label "${said(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), flow: type !== "flowchart" && (e as DiagramFlowEdge).flow === true ? true : undefined }); } } else if (dev) { @@ -317,7 +511,7 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model } // 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") { + if (checks && type !== "sequence" && !unplaced) { const cells = new Map(); for (const n of nodes) for (let r = n.row; r <= n.row2; r++) { const key = `${n.col}:${r}`; @@ -325,12 +519,12 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model cells.set(key, n.id); } } - if (checks) { + if (checks && !unplaced) { for (const g of groups) { - const m = g.members.map((id) => byId.get(id)!); + const m = g.all.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`); + for (const n of nodes) if (!g.all.includes(n.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`); } @@ -354,16 +548,119 @@ export function buildModel(spec: DiagramSpec, options: BuildOptions = {}): Model pulse: movers ? route(spec.pulse) : undefined, packet: packetPath ? { path: packetPath, repeat: packetIn!.repeat === true, send: packetIn!.send } : undefined, run: type === "sequence" && spec.run === true, + firstVisit: spec.entrance === "first-visit" || undefined, }; if (checks) for (const n of nodes) { const says = n.mark?.says; if (!says?.length) continue; - const words = [n.name, n.kind, n.detail].filter(Boolean).join(" ").toLowerCase(); + // A step's lane label counts as its words (DECISIONS 306, 1.6). + const words = [n.name, n.kind, n.detail, n.laneLabel].filter(Boolean).join(" ").toLowerCase(); if (!says.some((w) => words.includes(w.toLowerCase()))) warn(`${n.id}'s mark stands for ${says.join(" or ")}, and none of its words say so`); } - 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: String(spec.title ?? ""), heading: heading as Model["heading"], legend, nodes, byId, edges, groups, lanes, steps, cols, rows, shapeLabels, stepWord, warnings, motion, memo: new Map() }; + // Activation bars (1.2): a stack on each participant. `activate` opens one on the receiver, `deactivate` closes the sender's top one after its message; + // a bar left open closes at that participant's last message. Three deep at most. + const bars: MBar[] = []; + if (type === "sequence") { + const open = new Map(); + const last = new Map(); + for (const st of steps) if ("n" in st) { last.set(st.from, st.n); last.set(st.to, st.n); } + for (const st of steps) { + if (!("n" in st)) continue; + if (st.activate) { + const stack = open.get(st.to) ?? []; + if (stack.length >= 3) dev && error(`message ${st.n} opens a fourth bar on ${st.to}: three deep at most`); + else { const bar = { who: st.to, from: st.n, to: st.n, depth: stack.length + 1 }; stack.push(bar); bars.push(bar); open.set(st.to, stack); } + } + if (st.deactivate) { + const stack = open.get(st.from); + const top = stack?.pop(); + if (!top) dev && error(`message ${st.n} closes a bar on ${st.from}, which has none open`); + else top.to = st.n; + } + } + for (const [who, stack] of open) for (const bar of stack) bar.to = Math.max(bar.from, last.get(who) ?? bar.from); + } + const fl = (spec.frameLabels ?? {}) as Record; + const frameWords = { opt: txt(fl.opt) ?? "Only if", loop: txt(fl.loop) ?? "Repeats", alt: txt(fl.alt) ?? "One of these", else: txt(fl.else) ?? "Otherwise" }; + // An automatic figure's tracks include those that hold only a main line's way (DECISIONS 322, rule 1). + const placed = spec.layout === "auto" && !unplaced ? options.placement : undefined; + let cols = Math.max(1, placed?.cols ?? 1, ...nodes.map((n) => n.col)); + // Right to left (1.7): column 1 at the right. Columns are mirrored, a frame's span with them, and a named left or right side swaps. + if (options.rtl) { + for (const n of nodes) n.col = cols - n.col + 1; + const swap = (side?: DiagramSide) => (side === "left" ? "right" : side === "right" ? "left" : side); + for (const e of edges) { e.fromSide = swap(e.fromSide); e.toSide = swap(e.toSide); } + for (const st of steps) if ("open" in st) { const [a, b] = [cols - st.b + 1, cols - st.a + 1]; st.a = a; st.b = b; } + // A way-only track (DECISIONS 322) is a track right to left too (Neon's P3 of the code review). + cols = Math.max(1, placed?.cols ?? 1, ...nodes.map((n) => n.col)); + } + const rows = type === "data-flow" ? Math.max(1, lanes.length) : Math.max(1, placed?.rows ?? 1, ...nodes.map((n) => n.row2)); + const model: Model = { type, title: String(spec.title ?? ""), heading: heading as Model["heading"], legend, nodes, byId, edges, groups, lanes, steps, bars, frameWords, cols, rows, shapeLabels, stepWord, warnings, errors, motion, memo: new Map(), rtl: options.rtl || undefined, unplaced: unplaced || undefined, text: (type === "sequence" && spec.variant === "text") || undefined, marks: edges.some((e) => e.card) || undefined }; + if (spec.layout === "auto" && !unplaced && type !== "schema") chooseSides(model); + if (checks) for (const [id, h0] of Object.entries(portFloors(model))) if (h0 >= 48) warn(`${id} grows to ${h0}px to hold the lines on one side: use another side`); + // A figure with no cells yet (an automatic one before its placement) has no spatial keys to check. + if (checks && nodes.length > 100) warn(`the figure has ${nodes.length} cards: more than 100, which automatic layout places on the main thread`); + if (checks && nodes.length > 1 && !unplaced && !spatialTable(model)) warn("some part cannot be reached from another by the arrow keys where the figure is drawn, so its arrows keep the author's order"); + return model; +} + +/** + * An automatic figure's sides (1.8): nobody names one, so each line tries the router's shapes in order (sideways out and up or down in, up or down out + * and sideways in, then the two straight-on shapes; in one row or column the straight line, then a turn-back either side) and takes the first that + * passes through no card and puts no fourth line on a side. The line with the fewest clean shapes chooses first, then main lines, then the author's + * order. A side the author named is kept. + */ +function chooseSides(m: Model) { + const taken = new Set(m.nodes.map((n) => `${n.col},${n.row}`)); + const between = (p: number, q: number) => { const out: number[] = []; for (let k = Math.min(p, q) + 1; k < Math.max(p, q); k++) out.push(k); return out; }; + type Shape = { sides: [DiagramSide, DiagramSide]; cells: Array<[number, number]> }; + const shapes = (e: MEdge): Shape[] => { + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + const sx: DiagramSide = b.col > a.col ? "right" : "left", sy: DiagramSide = b.row > a.row ? "bottom" : "top"; + const ex: DiagramSide = b.col > a.col ? "left" : "right", ey: DiagramSide = b.row > a.row ? "top" : "bottom"; + const along = (lo: number, hi: number, at: number, horizontal: boolean) => between(lo, hi).map((k) => (horizontal ? [k, at] : [at, k]) as [number, number]); + let list: Shape[]; + // A turn-back runs in the gutter beside its side (DECISIONS 322, rule 4): it is a shape only where a track lies beyond that side, so none is chosen on + // the drawing's own edge, where it would leave the drawing. + const turn = (side: DiagramSide): Shape[] => ((side === "right" ? a.col < m.cols : side === "left" ? a.col > 1 : side === "bottom" ? a.row < m.rows : a.row > 1) ? [{ sides: [side, side], cells: [] }] : []); + if (a.row === b.row) list = [{ sides: [sx, ex], cells: along(a.col, b.col, a.row, true) }, ...turn("bottom"), ...turn("top")]; + else if (a.col === b.col) list = [{ sides: [sy, ey], cells: along(a.row, b.row, a.col, false) }, ...turn("right"), ...turn("left")]; + else list = [ + { sides: [sx, ey], cells: [...along(a.col, b.col, a.row, true), [b.col, a.row], ...along(a.row, b.row, b.col, false)] }, + { sides: [sy, ex], cells: [...along(a.row, b.row, a.col, false), [a.col, b.row], ...along(a.col, b.col, b.row, true)] }, + { sides: [sx, ex], cells: along(a.col, b.col, a.row, true) }, + { sides: [sy, ey], cells: along(a.row, b.row, a.col, false) }, + ]; + return list.filter((c) => c.cells.every(([x, y]) => !taken.has(`${x},${y}`))); + }; + const load = new Map(); + const left = new Set(); + // Sides the author named count before any line chooses (DECISIONS 322, rule 3). + for (const e of m.edges) if (e.fromSide || e.toSide) { + const [d1, d2] = defaultSides(m.byId.get(e.from)!, m.byId.get(e.to)!); + const s1 = e.fromSide ?? d1, s2 = e.toSide ?? d2; + left.add(`${e.from}.${s1}`); + for (const [id, side] of [[e.from, s1], [e.to, s2]] as const) load.set(`${id}.${side}`, (load.get(`${id}.${side}`) ?? 0) + 1); + } + const order = m.edges.map((_, k) => k).sort((p, q) => shapes(m.edges[p]!).length - shapes(m.edges[q]!).length || Number(m.edges[q]!.kind === "main") - Number(m.edges[p]!.kind === "main") || p - q); + for (const k of order) { + const e = m.edges[k]!; + if (e.fromSide || e.toSide) continue; + // A decision's lines meet at its four points (DECISIONS 322, rule 3): a point a line leaves takes no other line, so two lines never leave one point on + // one another and a line never arrives where one leaves. Lines that arrive at one point join, three at most, as on any side. + const room = (id: string, side: DiagramSide, leaving: boolean) => { + const key = `${id}.${side}`; + if ((load.get(key) ?? 0) >= 3) return false; + if (m.byId.get(id)!.shape !== "decision") return true; + return leaving ? !load.has(key) : !left.has(key); + }; + const ok = shapes(e).find((c) => room(e.from, c.sides[0], true) && room(e.to, c.sides[1], false)); + if (!ok) continue; + left.add(`${e.from}.${ok.sides[0]}`); + for (const [id, side] of [[e.from, ok.sides[0]], [e.to, ok.sides[1]]] as const) load.set(`${id}.${side}`, (load.get(`${id}.${side}`) ?? 0) + 1); + e.fromSide = ok.sides[0]; + e.toSide = ok.sides[1]; + } } /** A card's mark from the author's data: a bundled id (a string), or `{ onLight, onDark }` (with the words a bundled one stands for, `says`). */ @@ -395,6 +692,10 @@ function memo(m: Model, key: string, make: () => T): T { } const MAX_LABEL = 28; +/** How many lines a label is drawn on: one, or two where its author wrote a break (DECISIONS 306, 1.4). The engine never breaks one. */ +const labelLines = (text: string) => (text.includes("\n") ? 2 : 1); +/** A label as words: its lines joined with a space (the list and the sentences). */ +const said = (text: string) => text.replace(/\n/g, " "); // ============================================================================================================================================ // Words: sentences, the key, the list @@ -420,8 +721,9 @@ function writeSentence(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})`); + // A stated cardinality adds its clause (1.1): "users (decided_by: zero or many approvals to zero or one users)". + const refs = (n.columns ?? []).filter((c) => c.ref).map((c) => `${c.ref!.table} (${c.name}${c.card ? `: ${cardClause(n.id, c.ref!.table, c.card)}` : ""})`); + const by = m.edges.filter((e) => e.to === n.id).map((e) => `${e.from} (${m.byId.get(e.from)!.columns![e.fromRow!]!.name}${e.card ? `: ${cardClause(e.from, e.to, e.card)}` : ""})`); if (refs.length) parts.push(`References ${refs.join(", ")}.`); if (by.length) parts.push(`Referenced by ${by.join(", ")}.`); } else if (m.type === "sequence") { @@ -429,13 +731,16 @@ function writeSentence(m: Model, n: MNode): string { 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}.`); + const w = working(m, n); + if (w) parts.push(w.trim()); } 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})` : ""}`); + // The chain, innermost first: "In Data & logs, in AWS · your account." (1.3) + if (n.group) { const g = m.groups.find((x) => x.id === n.group); const outer = g?.parent ? m.groups.find((x) => x.id === g.parent) : undefined; if (g) parts.push(outer ? `In ${g.label}, in ${outer.label}.` : `In ${g.label}.`); } + const from = m.edges.filter((e) => e.to === n.id).map((e) => `${m.byId.get(e.from)!.name}${e.label ? ` (${said(e.label)})` : ""}`); + const to = m.edges.filter((e) => e.from === n.id).map((e) => `${m.byId.get(e.to)!.name}${e.label ? ` (${said(e.label)})` : ""}`); if (from.length) parts.push(`From: ${from.join(", ")}.`); if (to.length) parts.push(`To: ${to.join(", ")}.`); } @@ -443,6 +748,36 @@ function writeSentence(m: Model, n: MNode): string { return parts.join(" "); } +/** A foreign key's cardinality in words (1.1): "zero or many approvals to zero or one users". Table names are written as given. */ +/** The same clause in the list, its table names as code. */ +const cardClauseCode = (from: string, to: string, card: { from: DiagramCardinality; to: DiagramCardinality }, code: (s: string) => VElement): VChild[] => [`${CARD_WORDS[card.from].toLowerCase()} `, code(from), ` to ${CARD_WORDS[card.to].toLowerCase()} `, code(to)]; +const cardClause = (from: string, to: string, card: { from: DiagramCardinality; to: DiagramCardinality }) => `${CARD_WORDS[card.from].toLowerCase()} ${from} to ${CARD_WORDS[card.to].toLowerCase()} ${to}`; + +/** A participant's working stretches in words (1.2): " Working during messages 6 to 12." (and "message 3" for one). */ +function working(m: Model, n: MNode): string { + const bars = m.bars.filter((b) => b.who === n.id && b.depth === 1); + if (!bars.length) return ""; + const word = m.legend.activation ?? "Working"; + return ` ${word} during ${bars.map((b) => (b.from === b.to ? `message ${b.from}` : `messages ${b.from} to ${b.to}`)).join(" and ")}.`; +} + +/** + * What a tap does (DECISIONS 306, 1.5): a `click` from a touch or a pen pointer on a card traces it, on the same card or the drawing's ground clears it. + * A linked card follows its link and is never traced. Returns the trace to show, or undefined where the tap changes nothing. + */ +export function tapTrace(fig: HTMLElement, P: string, event: MouseEvent, current: string | null): string | null | undefined { + const type = (event as PointerEvent).pointerType; + if (type !== "touch" && type !== "pen") return undefined; + const drawing = fig.querySelector(`.${P}-drawing`); + const target = event.target as Element | null; + if (!drawing || !target || !drawing.contains(target) || !fig.querySelector(`.${P}-edge`)) return undefined; + const node = target.closest(`.${P}-node`); + if (node?.hasAttribute("href")) return undefined; + // A tap on the ground clears a trace; with none up it is nothing, so it never makes a figure "on touch" (Neon's P7 of the code review). + if (!node) return current === null ? undefined : null; + return node.dataset.node === current ? null : node.dataset.node ?? null; +} + /** 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"; @@ -507,8 +842,12 @@ export interface Dyn { 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 text variant shows its art (1.2): its widest line fits the block. */ + art?: 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; + /** A schema's rows with its corridors (DECISIONS 306, 1.1): a grid-template-rows of spacer tracks round the author's rows, set only where a far key is drawn. */ + rows?: string; } export interface TreeIds { base: string } @@ -526,16 +865,40 @@ function nodesAreImages(m: Model, dyn: Dyn): boolean { return true; } -/** How many sides a group reaches (the start or the end column): each adds space-4 to the least width. */ +/** A group's cells, its own members' and its child groups'. */ +function groupCells(m: Model, g: Model["groups"][number]) { + const mem = g.all.map((id) => m.byId.get(id)!); + if (!mem.length) return null; + return { 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)) }; +} +/** + * How many group levels reach each edge of the grid (DECISIONS 306, 1.3): the top row, the end column, the bottom row and the start column. A nested + * group's box is space-4 inside its parent's at the sides and below and space-8 below its top, so each level that reaches an edge takes that room again. + */ +export function groupEdges(m: Model): [number, number, number, number] { + return memo(m, "group-edges", () => { + const out: [number, number, number, number] = [0, 0, 0, 0]; + for (const g of m.groups) { + const c = groupCells(m, g); + if (!c) continue; + const at = [c.r1 === 1, c.c2 === m.cols, c.r2 === m.rows, c.c1 === 1]; + // A group reaches an edge with its own depth when its child does too, or alone at depth 1. + at.forEach((on, k) => { if (on) out[k] = Math.max(out[k]!, groupLevels(m, g, k)); }); + } + return out; + }); +} +/** How many boxes a group draws past its cells on one side: 1, and 1 more for a child group that reaches that side of it. */ +function groupLevels(m: Model, g: Model["groups"][number], side: number): number { + const c = groupCells(m, g)!; + const kids = m.groups.filter((k) => k.parent === g.id); + const reaches = kids.some((k) => { const kc = groupCells(m, k); return kc && [kc.r1 === c.r1, kc.c2 === c.c2, kc.r2 === c.r2, kc.c1 === c.c1][side]; }); + return reaches ? 2 : 1; +} +/** How many group levels reach the start and the end columns: 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); + const e = groupEdges(m); + return e[1] + e[3]; } /** 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. */ @@ -544,7 +907,7 @@ export function columnCount(m: Model): number { return m.type === "sequence" ? m // ---- 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; third: boolean } +export interface StackPlan { routes: StackRoute[]; gutter: boolean; lanes: number[]; exits: number[]; gaps: Record; third: boolean; laneCount: number } /** 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 { @@ -575,7 +938,7 @@ function planStack(m: Model): StackPlan { 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. 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`). + // so no two overlapping lines share a lane. A line that would need a fifth 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; @@ -584,9 +947,11 @@ function planStack(m: Model): StackPlan { 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; + // Four lanes at most (DECISIONS 306, 1.3): a fifth is the last resort, no lines and the list open. + if (lane > 3) third = true; placed.push(it); } + const laneCount = Math.max(0, ...ends.map(({ k }) => lanes[k]! + 1)); // 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) { @@ -618,10 +983,15 @@ function planStack(m: Model): StackPlan { } }); if (labelled > 1 || (turnInto && turnFrom)) gap = 64; + // Several end lines into one card (1.3) turn space-5 apart: the gap above it grows space-5 for each entry past the first (and below a card for lines + // that enter it from below). + const downInto = ends.filter(({ e, k }) => routes[k] === "end-down" && m.byId.get(e.to)!.i === b).length; + const upInto = ends.filter(({ e, k }) => routes[k] === "end-up" && m.byId.get(e.to)!.i === b - 1).length; + gap += 20 * Math.max(0, downInto - 1) + 20 * Math.max(0, upInto - 1); gaps[card.id] = gap; void above; } - return { routes, gutter, lanes, exits, gaps, third }; + return { routes, gutter, lanes, exits, gaps, third, laneCount }; } // ---- Swatches: each drawn exactly as its mark ---- @@ -641,6 +1011,31 @@ function lineSwatch(P: string, kind: DiagramLineKind | "fk"): VElement { ? 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` })); } +/** A cardinality swatch (1.1): a 24px line carrying the form, its table's edge at the end. */ +function cardSwatch(P: string, form: DiagramCardinality): VElement { + const { crow, ring } = cardMarks(form, 24, 8.5, -1); + return h("svg", { class: `${P}-swatch`, "data-card": form, ...svgA(24, 16) }, + h("path", { class: `${P}-line`, "data-kind": "plain", d: "M0 8.5H24" }), + h("path", { class: `${P}-crow`, d: crow }), + ring ? h("circle", { class: `${P}-ring`, cx: ring.x, cy: ring.y, r: ring.r }) : null); +} + +/** + * A form's marks at one end of a line (1.1), Information Engineering's, from the table's edge `edge` along the line at `y`, `out` the way away from + * the table (+1 or -1). Each bar is a 1px tick size-diagram-head across, its ink the pixel that ends at its distance; a foot is three spokes from a + * point at 7.5 to the edge, space-1 either side of the line; a ring is size-dot across its stroke's middle, centred at 10.5, so its ink runs 7 to 14. + */ +export function cardMarks(form: DiagramCardinality, edge: number, y: number, out: number, head = 8, dot = 6): { crow: string; ring?: { x: number; y: number; r: number } } { + const r2 = (n: number) => String(Math.round(n * 100) / 100); + const at = (d: number) => edge + out * d; + const half = head / 2; + const bar = (d: number) => `M${r2(at(d - 0.5))} ${r2(y - half)}V${r2(y + half)}`; + const many = form === "one-or-many" || form === "zero-or-many"; + const zero = form === "zero-or-one" || form === "zero-or-many"; + let crow = many ? `M${r2(edge)} ${r2(y - half)}L${r2(at(7.5))} ${r2(y)}L${r2(edge)} ${r2(y + half)}` : bar(4); + if (!zero) crow += bar(many ? 11 : 8); + return { crow, ring: zero ? { x: Math.round(at(10.5) * 100) / 100, y, r: dot / 2 } : undefined }; +} 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 })); @@ -651,6 +1046,8 @@ function boxSwatch(P: string, shape: "box" | "terminal" | "decision" | "focal" | function keyTree(P: string, m: Model): VElement | null { return memo(m, `key:${P}`, () => buildKey(P, m)); } +/** The key alone, for the viewer's foot (DECISIONS 310, 9.2): the same entries the figure draws under its drawing. */ +export const figureKey = keyTree; 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))); @@ -668,16 +1065,28 @@ function buildKey(P: string, m: Model): VElement | null { if (used.has("decision")) entry(boxSwatch(P, "decision"), m.shapeLabels.decision); } const kinds = new Set(m.type === "sequence" ? m.steps.flatMap((s) => ("n" in s ? [s.kind] : [])) : m.edges.filter((e) => !e.fk).map((e) => e.kind)); + // The text art's key is its own glyphs (1.2): the key is built from what is drawn. + const glyph = (g: string, ink: string) => h("span", { class: `${P}-key-glyph`, "data-ink": ink, "aria-hidden": "true" }, g); 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 (kinds.has(k) && words) entry(m.text ? glyph(k === "main" ? "━━▶" : k === "dashed" ? "┄┄▷" : "──▶", k === "main" ? "main" : "plain") : lineSwatch(P, k), words, { "data-line": m.text ? undefined : "" }); } 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, "The table a foreign key references"))); + // The foreign-key line where it is drawn; where it is not, the row says it, and so does the key. A schema that states how many shows each form + // drawn in its place (1.1), built in because the forms are notation; an unstated line (production, a figure that states some) keeps its entry. + if (m.edges.some((e) => !e.card)) entry(lineSwatch(P, "fk"), m.legend.plain ?? "A foreign key, to the key it references", { "data-line": "", "data-when": "drawn" }); + const forms = new Set(m.edges.flatMap((e) => (e.card ? [e.card.from, e.card.to] : []))); + for (const f of CARDS) if (forms.has(f)) entry(cardSwatch(P, f), CARD_WORDS[f], { "data-line": "", "data-when": "drawn", "data-card": f }); + entries.push(h("li", { class: `${P}-entry`, "data-when": "stacked" }, h("span", { class: `${P}-fk-mark`, "aria-hidden": "true" }, m.rtl ? "←" : "→"), 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.type === "sequence") { + // A bar on a dashed lifeline, where one is drawn (1.2); then each frame operator drawn, its letters set as the tab sets them, and its words. + if (m.bars.length) entry(m.text ? glyph("┃", "working") : h("svg", { class: `${P}-swatch`, "data-shape": "bar", ...svgA(16, 16) }, h("path", { class: `${P}-life`, d: "M8 0V16" }), h("rect", { class: `${P}-bar`, x: 4.5, y: 2.5, width: 7, height: 11, rx: 1.5 })), m.legend.activation ?? "Working", m.text ? {} : { "data-when": "drawn" }); + const ops = new Set(m.steps.flatMap((st) => ("open" in st ? [st.open] : []))); + for (const op of ["opt", "loop", "alt"] as const) if (ops.has(op)) entries.push(h("li", { class: `${P}-entry` }, h("span", { class: `${P}-key-letters`, "data-op": "" , "aria-hidden": "true" }, op), h("span", null, m.frameWords[op]))); + } + // The text art draws the focal participant in a double-line box: its key shows that glyph (P4 of the pixel review). + if (m.nodes.some((n) => n.focal) && m.legend.focal) entry(m.text ? glyph("╔═╗", "focal") : 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)); @@ -695,24 +1104,32 @@ function inlineArrow(P: string, kind: DiagramLineKind): VElement { // ---- Nodes ---- +/** A card's name; a link card's last word is held with its cue (the stylesheet's arrow after it), so the arrow never leaves the name's last word (1.4). */ +function linkName(P: string, n: MNode): VChild { + if (!n.href) return n.name; + const at = n.name.trimEnd().lastIndexOf(" "); + return [at < 0 ? "" : n.name.slice(0, at + 1), h("span", { class: `${P}-name-end` }, at < 0 ? n.name : n.name.slice(at + 1))]; +} + 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))]; + if (n.shape === "decision") return [h("span", { class: `${P}-words` }, h("span", { class: `${P}-name` }, linkName(P, n)))]; 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)); + kids.push(h("span", { class: `${P}-name` }, linkName(P, n))); // 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)); + // The runs are held in one span, a single left-to-right run right to left (1.7). + if (n.detail) kids.push(h("span", { class: `${P}-detail`, "data-mono": n.mono ? "" : undefined }, n.mono ? h("span", { class: `${P}-runs` }, words(n.detail).flatMap((w, j) => [j ? " " : "", h("span", { class: `${P}-run` }, w)])) : n.detail)); return kids; } -function tableText(P: string, n: MNode): VChild[] { +function tableText(P: string, n: MNode, m: Model): VChild[] { return [ - h("span", { class: `${P}-th` }, h("span", { class: `${P}-tname` }, n.name)), + h("span", { class: `${P}-th` }, h("span", { class: `${P}-tname` }, linkName(P, n))), 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))), + c.ref ? h("span", { class: `${P}-ctype`, "data-ref": "" }, `${m.rtl ? "←" : "→"} ${c.ref.table}`) : c.type ? h("span", { class: `${P}-ctype` }, c.type) : null))), n.more ? h("span", { class: `${P}-more` }, `+ ${n.more} more`) : null, ]; } @@ -728,7 +1145,9 @@ 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}`]; + // Where a schema's corridors are spacer tracks (1.1), the author's row r is track 2r. + const spaced = dyn.layout === "drawn" && dyn.rows; + const style: string[] = [`--_c:${n.col}`, `--_r:${spaced ? 2 * n.row : n.row}`, `--_r2:${spaced ? 2 * n.row2 + 1 : 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; @@ -739,11 +1158,19 @@ function nodeTree(ctx: TreeContext, m: Model, n: MNode, dyn: Dyn): VElement { } const height = own(dyn.heights, n.id); if (height) style.push(`--_h:${height}px`); + // The least height its ports need (call 3); the stylesheet applies it to the drawn layout alone. + const floor = own(portFloors(m), n.id); + if (floor) style.push(`--_mh:${floor}px`); const wordsWidth = own(dyn.words, n.id); if (wordsWidth) style.push(`--_ww:${wordsWidth}px`); const tabbable = stops ? (dyn.stop === n.id ? 0 : -1) : dyn.keep === n.id ? -1 : undefined; - return h("div", { + // A link card is the link itself (1.4): its name is its sentence, read with the link role, and it begins with the card's visible name. + return h(n.href ? "a" : "div", { class: `${P}-node`, + href: n.href, + target: n.href && n.blank ? "_blank" : undefined, + rel: n.href && n.blank ? "noopener noreferrer" : undefined, + "data-link": n.href ? (n.blank ? "external" : "") : undefined, "data-node": n.id, "data-shape": n.shape, "data-focal": n.focal ? "" : undefined, @@ -751,14 +1178,14 @@ function nodeTree(ctx: TreeContext, m: Model, n: MNode, dyn: Dyn): VElement { "data-mark": n.mark ? n.mark.id ?? "" : undefined, "data-level": ctx.level, style: style.join(";"), - role: images ? "img" : undefined, - "aria-label": images ? nodeSentence(m, n) : undefined, + role: images && !n.href ? "img" : undefined, + "aria-label": images || n.href ? 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, // A mark (DECISIONS 292, 2.6): an empty span, the form a background image, so its colours cannot be restyled and nothing of the file reaches the page. n.mark ? h("span", { class: `${P}-mark`, "aria-hidden": "true", style: n.mark.onLight ? `--_ml:${cssUrl(n.mark.onLight)};--_md:${cssUrl(n.mark.onDark ?? n.mark.onLight)}` : undefined }) : null, - n.shape === "table" ? tableText(P, n) : nodeText(P, m, n)); + n.shape === "table" ? tableText(P, n, m) : nodeText(P, m, n)); } function drawingChildren(ctx: TreeContext, m: Model, dyn: Dyn): VNode[] { @@ -769,50 +1196,129 @@ function drawingChildren(ctx: TreeContext, m: Model, dyn: Dyn): VNode[] { } 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))); + const c = groupCells(m, g); + if (!c) continue; + // A box grown past its cells by one level on each side, and by two where a child group reaches that side of it (1.3). + const lv = [0, 1, 2, 3].map((k) => groupLevels(m, g, k)); + out.push(h("div", { class: `${P}-gbox`, "data-group": g.id, "data-depth": g.depth > 1 ? g.depth : undefined, style: `--_c:${c.c1};--_c2:${c.c2 + 1};--_r:${c.r1};--_r2:${c.r2 + 1}${lv[0]! > 1 ? ";--_gt:2" : ""}${lv[1]! > 1 ? ";--_ge:2" : ""}${lv[2]! > 1 ? ";--_gb:2" : ""}${lv[3]! > 1 ? ";--_gs:2" : ""}`, "aria-hidden": "true" }, h("span", { class: `${P}-glabel` }, g.label))); } } + // The text variant (1.2): one code block, aria-hidden (the title, the summary and the list carry the figure). Before script it holds the transcript; + // script writes the art where its widest line fits (the diagram-text module). + if (m.text) return [h("pre", { class: `${P}-text`, "aria-hidden": "true", "data-art": dyn.art ? "" : undefined }, h("code", { class: `${P}-text-ink` }, transcript(P, m)))]; 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))))); + // Drawn, each head is in its column (mirrored right to left, 1.7). + out.push(h("ul", { class: `${P}-cast` }, m.nodes.map((n) => h("li", { class: `${P}-actor`, style: m.rtl ? `--_ac:${n.col}` : undefined }, 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. + // Nodes in the author's order; a group's members are wrapped once, so the stacked drawing can draw its box around them. A nested group is a wrapper + // inside its parent's (1.3). + const outerOf = (n: MNode) => { const g = n.group ? m.groups.find((x) => x.id === n.group) : undefined; return g?.parent ? m.groups.find((x) => x.id === g.parent) : g; }; + const wrap = (g: Model["groups"][number], run: MNode[], kids: VNode[]) => { + // 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; + // A group whose first card is entered by a turn (a trunk or an end line) has space-12 above it, so the turn runs under its label, not behind it + // (DECISIONS 306, 1.3, the decider's answer 1 to the pixel review). The label keeps its place in the first space-8. + const first = run[0]!; + const turns = ctx.plan && first.group === g.id ? m.edges.filter((e, k) => e.to === first.id && (ctx.plan!.routes[k] === "trunk" || ctx.plan!.routes[k] === "end-down")) : []; + // A labelled turn's label is seated beside its turn, inside the group (the decider's ruling 4 on the re-check): the group has space-4 more above for each + // line of the longest such label, so nothing grows above the group for it. + const lines = Math.max(0, ...turns.map((e) => (e.label ? labelLines(e.label) : 0))); + const style = [grow ? `--_ggrow:${grow}` : "", lines ? `--_tl:${lines}` : ""].filter(Boolean).join(";"); + return h("div", { class: `${P}-group`, "data-group": g.id, "data-depth": g.depth > 1 ? g.depth : undefined, "data-turn": turns.length ? "" : undefined, style: style || undefined }, h("span", { class: `${P}-glabel`, "aria-hidden": "true" }, g.label), kids); + }; 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; + const g = outerOf(n); 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++]!); - // 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)))); + while (k < m.nodes.length && outerOf(m.nodes[k]!)?.id === g.id) run.push(m.nodes[k++]!); + const kids: VNode[] = []; + for (let j = 0; j < run.length;) { + const inner = run[j]!.group !== g.id ? m.groups.find((x) => x.id === run[j]!.group) : undefined; + if (!inner) { kids.push(nodeTree(ctx, m, run[j]!, dyn)); j++; continue; } + const sub: MNode[] = []; + while (j < run.length && run[j]!.group === inner.id) sub.push(run[j++]!); + kids.push(wrap(inner, sub, sub.map((x) => nodeTree(ctx, m, x, dyn)))); + } + out.push(wrap(g, run, kids)); + } + return out; +} + +/** + * The text variant's transcript (1.2), where the art does not fit, as Draft B's reference (B6 of the pixel review): the participants on a line; then each + * message as its number, sender, arrow and receiver, its label on a line of its own and its note on another, every line of it hanging under the sender + * inside its frame's indent; frames as indented brackets. A line breaks between participants and between words, never inside a name (each name is held + * whole). Each line is a block: `--_in` is its indent in characters, `--_hang` how far its first line starts before it. + */ +export function transcript(P: string, m: Model): VNode[] { + const out: VNode[] = []; + const held = (s: string) => h("span", { class: `${P}-tx-name` }, s); + const arrow = (k: DiagramLineKind) => (k === "main" ? "━▶" : k === "dashed" ? "┄▷" : "─▶"); + const line = (attrs: VAttrs, indent: number, hang: number, ...kids: VChild[]) => h("span", { class: `${P}-tx-line`, ...attrs, style: hang ? `--_in:${indent + hang};--_hang:${hang}` : `--_in:${indent}` }, ...kids); + out.push(line({ "data-ink": "names" }, 0, 0, m.nodes.flatMap((n, k) => [k ? " · " : "", held(n.name)]))); + const digits = String(Math.max(1, ...m.steps.map((s) => ("n" in s ? s.n : 0)))).length; + let indent = 0; + for (const s of m.steps) { + const pad = 2 * indent; + if ("band" in s) { out.push(line({ "data-ink": "band" }, pad, 0, `── ${s.band} ──`)); continue; } + if ("open" in s) { out.push(line({ "data-ink": "frame" }, pad, 0, h("span", { "data-ink": "op" }, `[${s.open}]`), ` ${s.label}`)); indent++; continue; } + if ("otherwise" in s) { out.push(line({ "data-ink": "frame" }, 2 * Math.max(0, indent - 1), 0, h("span", { "data-ink": "op" }, "[else]"), ` ${s.otherwise}`)); continue; } + if ("close" in s) { indent = Math.max(0, indent - 1); out.push(line({ "data-ink": "frame" }, 2 * indent, 0, "[end]")); continue; } + const a = m.byId.get(s.from)?.name ?? s.from, b = m.byId.get(s.to)?.name ?? s.to; + const hang = digits + 2; + // The arrow and the receiver are one unbreakable run: a route that does not fit breaks before its arrow, and the second line starts with the arrow under + // the sender (the decider's ruling 3 on the re-check), as the stacked list's route does (66-2). + out.push(line({ "data-n": s.n }, pad, hang, h("span", { "data-ink": "num" }, String(s.n).padStart(digits, "0")), " ", held(a), " ", h("span", { class: `${P}-tx-to` }, h("span", { "data-ink": s.kind === "main" ? "main" : "plain" }, arrow(s.kind)), " ", b))); + out.push(line({ "data-n": s.n }, pad + hang, 0, h("span", { "data-ink": "label" }, s.label))); + if (s.note) out.push(line({ "data-n": s.n }, pad + hang, 0, h("span", { "data-ink": "note" }, s.note))); } return out; } function sequenceSteps(ctx: TreeContext, m: Model): VElement { const { P } = ctx; - const blocks: VNode[] = []; + const root: VNode[] = []; + // Frames (DECISIONS 306, 1.2) are boxes round their rows: each one a block holding its header, its rows and the frames inside it. + const stack: Array<{ el: VElement; a: number; b: number }> = []; + const into = () => (stack.length ? stack[stack.length - 1]!.el.c : root); 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); } + if ("band" in s) { list = null; into().push(h("p", { class: `${P}-band` }, h("span", null, s.band))); continue; } + if ("open" in s) { + list = null; + const parent = stack[stack.length - 1]; + // A frame inside a frame is space-2 inside it on every side they share. + const inset = parent ? `;--_fis:${s.a === parent.a ? 1 : 0};--_fie:${s.b === parent.b ? 1 : 0}` : ""; + const el = h("div", { class: `${P}-frame`, "data-op": s.open, "data-depth": s.depth, style: `--_a:${s.a};--_b:${s.b + 1}${inset}` }, + h("span", { class: `${P}-fbox`, "aria-hidden": "true" }), + h("p", { class: `${P}-fhead` }, h("span", { class: `${P}-ftab`, "aria-hidden": "true" }, s.open), h("span", { class: `${P}-flabel` }, h("span", { class: ctx.hidden }, `${m.frameWords[s.open]}: `), s.label))); + into().push(el); + stack.push({ el, a: s.a, b: s.b }); + continue; + } + if ("otherwise" in s) { + list = null; + into().push(h("p", { class: `${P}-felse` }, h("span", { class: `${P}-fword`, "aria-hidden": "true" }, "else"), h("span", { class: `${P}-flabel` }, h("span", { class: ctx.hidden }, `${m.frameWords.else}: `), s.otherwise))); + continue; + } + if ("close" in s) { list = null; stack.pop(); continue; } + if (!list) { list = h("ol", { class: `${P}-msgs`, start: s.n }); into().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; + // A self-call goes to the end side, the start side on the last participant: logical, so mirrored right to left (1.7). + const last = self && (m.rtl ? ca !== 1 : 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}` : ""), + h("span", { class: `${P}-route` }, a?.short ?? s.from, " ", h("span", { class: `${P}-to` }, 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); + return h("div", { class: `${P}-steps` }, root); } // ---- The list ("View as list") ---- @@ -820,25 +1326,34 @@ function sequenceSteps(ctx: TreeContext, m: Model): VElement { function listTree(P: string, m: Model): VNode[] { return memo(m, `list:${P}`, () => buildList(P, m)); } +/** The list alone, for the viewer's stage (DECISIONS 310, 9.9): the page's own list, in place of the drawing. */ +export const figureList = listTree; 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); + // A link card's name in the list is the same link (1.4). + const named = (n: MNode) => (n.href ? h("a", { href: n.href, target: n.blank ? "_blank" : undefined, rel: n.blank ? "noopener noreferrer" : undefined }, strong(n.name)) : strong(n.name)); 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 part = (n: MNode) => h("li", null, named(n), 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) { + // Direct members, then each child group under its label (1.3). + for (const g of m.groups.filter((x) => x.depth === 1)) { 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)!)))); + if (g.members.length) out.push(h("ul", { class: `${P}-list-items` }, g.members.map((id) => part(m.byId.get(id)!)))); + for (const c of m.groups.filter((x) => x.parent === g.id)) { + out.push(h("p", { class: `${P}-list-group`, "data-depth": 2 }, c.label)); + out.push(h("ul", { class: `${P}-list-items`, "data-depth": 2 }, c.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)}.`)))); + 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(said(e.label))] : "", `${kw(e.kind)}.`)))); return out; } if (m.type === "flowchart") { @@ -847,24 +1362,28 @@ function buildList(P: string, m: Model): VNode[] { 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)), kw(e.kind)))) : null); + return h("li", null, named(n), 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 ${said(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") { 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)]), "."] : ""); + return h("li", null, `${n.laneLabel}: `, named(n), 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(said(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))))]; + 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), working(m, n))))]; 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 "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; } + // A frame is a sub-heading as a band is (1.2): "Only if: First run on an incident only", "Otherwise: Rejected". Messages keep their numbers. + if ("open" in s) { list = null; out.push(h(`h${Math.min(6, sub + 1)}`, { class: `${P}-list-group`, "data-depth": s.depth > 1 ? s.depth : undefined }, `${m.frameWords[s.open]}: ${s.label}`)); continue; } + if ("otherwise" in s) { list = null; out.push(h(`h${Math.min(6, sub + 1)}`, { class: `${P}-list-group`, "data-depth": s.depth > 1 ? s.depth : undefined }, `${m.frameWords.else}: ${s.otherwise}`)); continue; } + if ("close" in s) { list = null; 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(s.note)}` : "")); } @@ -874,24 +1393,66 @@ function buildList(P: string, m: Model): VNode[] { const out: VNode[] = []; for (const n of m.nodes) { // 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(`h${sub}`, { class: `${P}-list-group` }, n.href ? h("a", { href: n.href, target: n.blank ? "_blank" : undefined, rel: n.blank ? "noopener noreferrer" : undefined }, code(n.name)) : 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.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.card ? [" (", cardClauseCode(n.id, c.ref.table, c.card, code), ")"] : ""] : 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 { +/** The keys sentence (hidden), which describes the drawing to a screen reader. Drawn, the arrows are spatial (DECISIONS 306, 1.5), unless they fall back. */ +function keysSentence(m: Model, drawn = false): 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.`; + const arrows = drawn && spatialTable(m) ? `Arrow keys move to the nearest ${noun} in that direction` : `Arrow keys move to the next or the previous ${noun}, in the author's order`; + // Where a card is a link (1.4), Enter follows it. + return `${arrows}; Home and End go to the ends; Escape clears the trace.${m.nodes.some((n) => n.href) ? " Enter opens a part that is a link." : ""}`; } -/** 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" }]; +/** The key hint's entries: the keys and their words. Four arrows where a drawn figure has more than one row and more than one column (1.5). */ +export function hintEntries(m: Model, drawn = false): Array<{ keys: string[]; words: string }> { + const four = drawn && m.type !== "sequence" && spatialTable(m) && m.cols > 1 && m.rows > 1; + const open = m.nodes.some((n) => n.href) ? [{ keys: ["Enter"], words: "open" }] : []; + return [{ keys: four ? ["←", "↑", "↓", "→"] : ["←", "→"], words: stopNoun(m) }, { keys: ["Home", "End"], words: "the ends" }, ...open, { keys: ["Esc"], words: "clear" }]; +} + +// ---- The spatial arrow keys (DECISIONS 306, 1.5): on a card's column and rows, never on its measured centre ---- + +type Way = "right" | "left" | "down" | "up"; +/** Lexicographic order of two ranks. */ +const less = (a: number[], b: number[]) => { for (let k = 0; k < a.length; k++) if (a[k] !== b[k]) return a[k]! < b[k]!; return false; }; +/** A card's tracks: its column and its rows (a data flow's row is its lane, a sequence's heads are one row). */ +const tracksOf = (_m: Model, n: MNode) => ({ col: n.col, rows: [n.row, n.row2] as [number, number] }); +/** + * Where each arrow goes from each card, or null when some card cannot be reached from another by the arrows: then the arrows are the author's order. + * A card is "that way" when it starts past the focused card's last track on the arrow's axis. Among those sharing a track across the arrow, the nearest; + * otherwise the lowest of tracks along the arrow plus twice the tracks across; ties go to fewer across, then the nearer first row, then the author's order. + */ +export function spatialTable(m: Model): Record> | null { + return memo(m, "spatial", () => { + const cards = m.nodes.map((n) => ({ id: n.id, ...tracksOf(m, n) })); + const target = (from: (typeof cards)[number], way: Way) => { + const horizontal = way === "right" || way === "left", forward = way === "right" || way === "down"; + const along = (c: (typeof cards)[number]) => (horizontal ? [c.col, c.col] : c.rows), across = (c: (typeof cards)[number]) => (horizontal ? c.rows : [c.col, c.col]); + const a = along(from), x = across(from); + let best: { id: string; rank: number[] } | null = null; + cards.forEach((c, order) => { + if (c === from) return; + const b = along(c), y = across(c); + const d = forward ? b[0]! - a[1]! : a[0]! - b[1]!; + if (d < 1) return; + const off = Math.max(0, y[0]! - x[1]!, x[0]! - y[1]!); + const rank = [off === 0 ? 0 : 1, off === 0 ? d : d + 2 * off, off, Math.abs(y[0]! - x[0]!), order]; + if (!best || less(rank, best.rank)) best = { id: c.id, rank }; + }); + return (best as { id: string } | null)?.id ?? null; + }; + const table: Record> = record(); + for (const c of cards) table[c.id] = { right: target(c, "right"), left: target(c, "left"), down: target(c, "down"), up: target(c, "up") }; + const reach = (start: string) => { const seen = new Set([start]); const todo = [start]; while (todo.length) for (const t of Object.values(table[todo.pop()!]!)) if (t && !seen.has(t)) { seen.add(t); todo.push(t); } return seen.size; }; + return cards.every((c) => reach(c.id) === cards.length) ? table : null; + }); } export interface FigureOptions { @@ -906,9 +1467,48 @@ export interface FigureOptions { hasSource?: boolean; /** The class of the hidden text. */ hiddenClass: string; + /** The figure is the viewer's (DECISIONS 310): only its drawing shows, and its keys sentence ends with these words (the zoom keys). */ + viewer?: string; } /** The whole figure. Before script runs `dyn` is empty; the same tree, with the measured `dyn`, is what script settles on. */ +/** + * A one-column schema's turn-backs (DECISIONS 306, section 4, call 2): turn-backs that run beside each other take lanes space-3 apart, nested (the + * farther-going outermost), lines to one key sharing one; two lanes at most in the padding, and a third line is not drawn. Worked out from the data alone + * (a line's place down the column is its table's row and its key's row), so the padding is known before anything is measured. + */ +export function turnBackLanes(m: Model): { lane: Map; dropped: Set; lanes: number } { + return memo(m, "turn-back-lanes", () => { + const lane = new Map(), dropped = new Set(); + if (!oneColumnTurnBacks(m)) return { lane, dropped, lanes: 0 }; + const at = (id: string, row: number) => (m.byId.get(id)?.row ?? 0) * 1000 + row; + // One group a key; its run from its highest to its lowest end. + const groups = new Map(); + m.edges.forEach((e, k) => { + // Lines to one key share a lane only when they state the same thing there (1.1; Neon's B9 of the code review). + const key = `${e.to}.${e.toRow}.${e.card?.to ?? ""}`; + const a = at(e.from, e.fromRow ?? 0), b = at(e.to, e.toRow ?? 0); + const g = groups.get(key) ?? { members: [], lo: Infinity, hi: -Infinity }; + g.members.push(k); g.lo = Math.min(g.lo, a, b); g.hi = Math.max(g.hi, a, b); + groups.set(key, g); + }); + // Longest first, so the farther-going is outermost; each takes the innermost lane no group beside it holds. + const order = [...groups.values()].sort((x, y) => (y.hi - y.lo) - (x.hi - x.lo)); + const placed: Array<{ lo: number; hi: number; lane: number }> = []; + let most = 0; + for (const g of order.reverse()) { + const used = new Set(placed.filter((p) => p.lo <= g.hi && g.lo <= p.hi).map((p) => p.lane)); + let l = 0; + while (used.has(l)) l++; + if (l > 1) { for (const k of g.members) dropped.add(k); continue; } + placed.push({ lo: g.lo, hi: g.hi, lane: l }); + for (const k of g.members) lane.set(k, l); + most = Math.max(most, l + 1); + } + return { lane, dropped, lanes: most }; + }); +} + /** A schema of one column whose foreign keys are drawn as turn-backs on its end side, where it has no gutter. */ const oneColumnTurnBacks = (m: Model) => m.type === "schema" && m.cols === 1 && m.edges.length > 0; @@ -925,14 +1525,22 @@ export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { 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"); + // Each group level that reaches an edge takes its room again (1.3): space-8 above, space-4 at a side and below. + const e: [number, number, number, number] = m.type === "architecture" ? groupEdges(m) : [0, 0, 0, 0]; + const pad = (levels: number, step: string, least?: string) => (levels ? (levels > 1 ? `calc(${levels} * var(--basalt-space-${step}))` : `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")}`); + style.push(`--_gpad:${pad(e[0], "8", block)} ${pad(e[1], "4")} ${pad(e[2], "4", block)} ${pad(e[3], "4")}`); } // A schema of one column with a foreign key: its turn-backs run space-4 out on the end side, past the cards, so the drawn layout keeps space-5 there // (the turn-back and its stroke on the pixel grid); the fit rule counts it (minimums). - if (oneColumnTurnBacks(m)) style.push("--_gpad:0px var(--basalt-space-5) 0px 0px"); + // Two lanes of turn-backs take space-3 more (call 2). + // The end gutter grows by lanes (1.3): lanes × space-3-5 + space-3 (40, 54, 68). + if (plan?.gutter && plan.laneCount > 2) style.push(`--_gw:calc(${plan.laneCount} * var(--basalt-space-3-5) + var(--basalt-space-3))`); + if (oneColumnTurnBacks(m)) { + // Where marks are drawn the first lane is space-6 out, so the padding is space-6 plus space-1 (1.1). + const first = m.marks ? "var(--basalt-space-6) + var(--basalt-space-1)" : "var(--basalt-space-5)"; + style.push(`--_gpad:0px ${turnBackLanes(m).lanes > 1 ? `calc(${first} + var(--basalt-space-3))` : m.marks ? `calc(${first})` : first} 0px 0px`); + } if (m.type === "schema" && dyn.track) style.push(`--_track:${dyn.track}px`); return h("figure", { class: o.className ? `${P} ${o.className}` : P, @@ -941,27 +1549,36 @@ export function figureTree(m: Model, dyn: Dyn, o: FigureOptions): VElement { "data-cols": columnCount(m), "data-reach": m.type === "architecture" ? groupReach(m) : undefined, "data-gutter": plan?.gutter ? "" : undefined, - "data-layout": dyn.layout, + "data-marks": m.marks ? "" : undefined, + // An automatic figure with no placement is stacked before script too: its cards have no cells yet. + "data-layout": dyn.layout ?? (m.unplaced ? "stacked" : undefined), "data-measured": dyn.layout ? "" : undefined, "data-bare": dyn.bare ? "" : undefined, "data-motion": m.motion.animated ? "animated" : undefined, + "data-first-visit": m.motion.animated && m.motion.firstVisit ? "" : undefined, + "data-rtl": m.rtl ? "" : undefined, + "data-viewer": o.viewer ? "" : 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`, + // A schema's far keys run in corridors (1.1): its rows are spacer tracks round the author's, and the grid's own row gap is none. + style: drawn && dyn.rows ? `--_rows:${dyn.rows};--_row-gap:0px` : undefined, role: group ? "group" : undefined, "aria-roledescription": group ? "diagram" : undefined, "aria-labelledby": group ? ids.title : 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" })), + }, drawingChildren(ctx, m, dyn), m.text ? null : 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" }), + // On touch, where lines are drawn, a line in the hint's seat and type says how to trace (DECISIONS 306, 1.5); the stylesheet shows it only then. + hasStops(m, dyn) && m.type !== "sequence" || (drawn && m.type === "sequence") ? h("p", { class: `${P}-tap-hint`, "aria-hidden": "true" }, `Tap ${stopNoun(m)} to highlight its lines. Tap it again to clear.`) : null, 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("span", { id: ids.keys, class: o.hiddenClass }, o.viewer ? `${keysSentence(m, drawn)} ${o.viewer}` : keysSentence(m, drawn)), h("figcaption", { id: ids.summary, class: `${P}-summary` }, { slot: "summary" })); } @@ -987,6 +1604,8 @@ export interface GLine { dir: Dir; /** A foreign key's dot, on the row it leaves. */ dot?: Pt; + /** A foreign key's stated cardinality (1.1): marks at both ends in place of the dot and the head. */ + card?: { from: DiagramCardinality; to: DiagramCardinality }; 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. */ @@ -1002,6 +1621,10 @@ export interface Geo { nodes: GNode[]; lines: GLine[]; lifelines: Array<{ x: number; y1: number; y2: number }>; + /** A sequence's activation bars (DECISIONS 306, 1.2): structure, drawn over the lifelines and under the lines. */ + bars?: Array<{ l: number; r: number; t: number; b: number }>; + /** What does not fit and is not a line or a label (a frame's header wider than its frame): the drawn layout is refused. */ + misfit?: string[]; 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. */ @@ -1014,6 +1637,8 @@ export interface Geo { /** The offset of the drawing's origin from the device pixel grid, so lines can be snapped to it. */ ox: number; oy: number; + /** A schema's far keys (1.1): the rows their corridors need, and each far line's corridor, chosen once on the grid without them. */ + corridors?: { rows: string; pick: Record }; } export interface Tokens { @@ -1021,6 +1646,8 @@ export interface Tokens { 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; + /** An activation bar's width and a cardinality mark's room (DECISIONS 306, 1.0). */ + activation: number; foot: number; } export function readTokens(el: Element): Tokens { @@ -1033,6 +1660,7 @@ export function readTokens(el: Element): Tokens { 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), + activation: px("size-diagram-activation", 8), foot: px("size-diagram-foot", 14), }; } @@ -1131,18 +1759,22 @@ function minimums(m: Model, tk: Tokens, measure: ReturnType) { 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 type = c.ref ? `${m.rtl ? "←" : "→"} ${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)); + table = Math.max(table, Math.ceil(measure(n.name, "table") + 2 * s("3") + 2 * tk.hair + (n.href ? 16 + s("1-5") : 0))); continue; } const pad = n.shape === "terminal" ? 2 * s("5") : 2 * s("3"); // The first line (the kind, or the name on a card with no kind) keeps space-6 clear of a mark, except in forced colours, where none is drawn. - const seat = n.mark && !forced() ? s("6") : 0; + // A participant's head centres its words, so its first line keeps space-6 clear on both sides (1.6). + const seat = n.mark && !forced() ? (n.shape === "participant" ? 2 : 1) * s("6") : 0; let widest = 0; - for (const w of words(n.name)) widest = Math.max(widest, measure(w, n.shape === "decision" ? "name-500" : "name") + (n.kind ? 0 : seat)); + // A link card's last word carries its cue, 16 and space-1-5 before it (1.4). + const cue = n.href ? 16 + s("1-5") : 0; + const nameWords = words(n.name); + nameWords.forEach((w, j) => { widest = Math.max(widest, measure(w, n.shape === "decision" ? "name-500" : "name") + (n.kind ? 0 : seat) + (j === nameWords.length - 1 ? cue : 0)); }); if (m.type !== "data-flow") for (const w of words(n.kind)) widest = Math.max(widest, measure(w, "mono") + seat); 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; @@ -1151,7 +1783,8 @@ function minimums(m: Model, tk: Tokens, measure: ReturnType) { 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") + (oneColumnTurnBacks(m) ? s("5") : 0); + // Where marks are drawn the gap is space-12 plus space-3, and a one-column schema's first turn-back is space-6 out (1.1). + else if (m.type === "schema") least = n * table + (n - 1) * (s("12") + (m.marks ? s("3") : 0)) + (oneColumnTurnBacks(m) ? (m.marks ? s("6") + s("1") : s("5")) + (turnBackLanes(m).lanes > 1 ? s("3") : 0) : 0); // 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"); @@ -1229,9 +1862,11 @@ 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; }; + const rows = tracks(list(cs.gridTemplateRows), parseFloat(cs.paddingTop) || 0, parseFloat(cs.rowGap) || 0); 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), + // A schema's corridors (1.1) are spacer tracks round the author's rows: its rows are every other track. + rows: drawing.style.getPropertyValue("--_rows").trim() ? rows.filter((_, j) => j % 2 === 1) : rows, }; } @@ -1285,6 +1920,37 @@ function assignSlots(m: Model, sides: Array<[DiagramSide, DiagramSide]>, warn: ( return ports; } +/** + * A card's least height for its ports (DECISIONS 306, section 4, call 3): a port sits on the flat part of its side, never nearer a corner than the corner's + * radius, and two ports on a side are at least size-diagram-head apart. A card whose start or end side holds more than its height allows grows to the least + * height at which both hold (48 for a straight line and two others, 64 for an extra beside a straight pair), and its row takes it. From the data alone, so + * it is the same at every width: a side never stacks a figure. By node id; only cards that need more than nothing are named. + */ +export function portFloors(m: Model, radius = 8, head = 8): Record { + return memo(m, `port-floors:${radius}:${head}`, () => { + const out: Record = record(); + if (m.type !== "architecture" && m.type !== "flowchart" && m.type !== "data-flow") return out; + 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 bySide = new Map(); + for (const p of assignSlots(m, sides, () => {})) { + if (!isH(p.side) || p.node.shape !== "box") continue; + const key = `${p.node.id}.${p.side}`; + if (!bySide.has(key)) bySide.set(key, []); + bySide.get(key)!.push(p.f); + } + for (const [key, fs] of bySide) { + if (fs.length < 2) continue; + // Slots that share a point are one (a bus); the fractions are kept unrounded, so 48 is 48 and not 49 (Neon's P1 of the code review). + const f = fs.slice().sort((a, b) => a - b).filter((x, j, all) => j === 0 || x - all[j - 1]! > 1e-9); + let need = Math.max(radius / f[0]!, radius / (1 - f[f.length - 1]!)); + for (let j = 1; j < f.length; j++) need = Math.max(need, head / (f[j]! - f[j - 1]!)); + const id = key.slice(0, key.lastIndexOf(".")); + out[id] = Math.max(out[id] ?? 0, Math.ceil(need - 1e-6)); + } + return out; + }); +} + /** 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]; }); @@ -1297,7 +1963,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; pick?: Record } function gNodes(m: Model, drawing: HTMLElement, origin: DOMRect, P: string): Map { const out = new Map(); @@ -1346,7 +2012,8 @@ function seatLabels(m: Model, lines: GLine[], nodes: GNode[], obstacles: Obstacl 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; + // A label may hold one break of its author's (DECISIONS 306, 1.4): its box is its widest line, and 16 a line tall. + const w = measure(text, "label"), hgt = 16 * labelLines(text); 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) => { @@ -1466,15 +2133,30 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge const r = rectOf(el, origin); return (r.t + r.b) / 2; }; + // One key, two statements (1.1): lines that state different things at one key arrive space-2 apart, centred on the row, each in its own lane; + // lines that state the same thing share a bus. + const arrivals = new Map(); + if (m.type === "schema") { + const at = new Map(); + m.edges.forEach((e, k) => { const key = `${e.to}.${e.toRow}.${sides[k]![1]}`; at.set(key, [...(at.get(key) ?? []), k]); }); + const rank = (k: number) => { const t = m.edges[k]!.card?.to; return t === "one" ? 0 : t === "zero-or-one" ? 1 : 2; }; + for (const list of at.values()) { + const says = [...new Set(list.map(rank))].sort((x, y) => x - y); + if (says.length > 1) for (const k of list) arrivals.set(k, (says.indexOf(rank(k)) - (says.length - 1) / 2) * s("2")); + } + } + // A marked line's ends are on whole pixels of the table's edge, so its marks are measured from it (1.1). + const whole = (x: number) => Math.round(x + ox) - ox; // 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 r1 = rowY(e.from, e.fromRow!), r2 = rowY(e.to, e.toRow!); + const r1 = rowY(e.from, e.fromRow!), r2 = rowY(e.to, e.toRow!) + (arrivals.get(k) ?? 0); 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 x1 = s1 === "right" ? a.rect.r : a.rect.l, x2 = s2 === "right" ? b.rect.r : b.rect.l; + return { p1: { x: e.card ? whole(x1) : x1, y: y1 }, p2: { x: e.card ? whole(x2) : x2, 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); @@ -1490,16 +2172,86 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge p2 = isH(s2) ? contour(b, s2, p2.y) : contour(b, s2, p2.x); 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(); - 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); }); + // A line that is not drawn: its row still writes the target, and a development build names it. One tight line never stacks the figure. + const drop = (k: number, why: string) => { if (dropped.has(k)) return; dropped.add(k); if (dev) warn?.(`${m.edges[k]!.from} to ${m.edges[k]!.to} ${why}, so its line is not drawn; its row still writes the target`); }; + // A one-column schema's third lane of turn-backs is not drawn (call 2). + for (const k of turnBackLanes(m).dropped) drop(k, dev ? "would need a third lane of turn-backs" : ""); + + // Foreign keys two or more columns away (1.1): out of the row's facing side, a turn in the gutter beside its own table, a run along a corridor (a + // row gap no table of the columns between stands in, or the margin above or below), a turn in the gutter beside the referenced table into the key. + const far = new Map(); + const pick: Record = record(); + if (m.type === "schema") m.edges.forEach((e, k) => { + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + if (Math.abs(a.col - b.col) < 2) return; + const lo = Math.min(a.col, b.col), hi = Math.max(a.col, b.col); + const between = m.nodes.filter((n) => n.col > lo && n.col < hi); + const rows = grid.rows; + if (!rows.length) return; + // Each corridor's height: an interior gap's middle; a margin's first lane, space-4 out. + const cands: Array<{ key: string; y: number; inner: boolean }> = []; + for (let g = 1; g < rows.length; g++) if (!between.some((n) => n.row <= g && n.row2 >= g + 1)) cands.push({ key: `g${g}`, y: (rows[g - 1]![1] + rows[g]![0]) / 2, inner: true }); + cands.push({ key: "top", y: rows[0]![0] - s("4"), inner: false }, { key: "bottom", y: rows[rows.length - 1]![1] + s("4"), inner: false }); + // The one nearest the middle of the two rows' heights; an interior gap wins a tie with a margin, then the upper. Chosen once, on the grid + // without corridors (the second measure, with them, keeps it). + const mid = (ends[k]!.r1 + ends[k]!.r2) / 2; + const chosen = input.pick?.[k] ?? cands.slice().sort((p, q) => Math.abs(p.y - mid) - Math.abs(q.y - mid) || Number(q.inner) - Number(p.inner) || p.y - q.y)[0]!.key; + pick[k] = chosen; + const ti = sides[k]![0] === "right" ? a.col : a.col - 1; + const t1 = grid.cols[ti - 1], t2 = grid.cols[ti]; + far.set(k, { corridor: chosen, first: t1 && t2 ? { key: `c${ti}`, span: [t1[1], t2[0]] } : null, y: 0 }); + }); + // A corridor's lanes (1.1): two at most, space-3 apart, lines to one key sharing one; a third line is not drawn, the later in the author's order. + // An interior gap's lanes are centred in it (space-3-5 clear of the tables in its space-10); a margin's are space-4 and space-4 plus space-3 out. + const corridorGroups = new Map(); + for (const [k, f] of far) { + const e = m.edges[k]!; + const groups = corridorGroups.get(f.corridor) ?? []; + const bus = groups.find((g) => { const o = m.edges[g[0]!]!; return o.to === e.to && o.toRow === e.toRow && sides[g[0]!]![1] === sides[k]![1] && Math.abs(ends[g[0]!]!.p2.y - ends[k]!.p2.y) < 0.5; }); + if (bus) bus.push(k); + else if (groups.length >= 2) drop(k, dev ? "would need a third lane in its corridor" : ""); + else groups.push([k]); + corridorGroups.set(f.corridor, groups); + } + for (const k of [...far.keys()]) if (dropped.has(k)) far.delete(k); + // How far a line goes: its columns, then its run across. + const reach = (g: number[]) => { const e = m.edges[g[0]!]!; return Math.abs(m.byId.get(e.from)!.col - m.byId.get(e.to)!.col) * 1e4 + Math.abs(ends[g[0]!]!.p1.x - ends[g[0]!]!.p2.x); }; + const corridorY = (key: string, j: number, count: number) => { + const rows = grid.rows; + if (key === "top") return rows[0]![0] - s("4") - j * s("3"); + if (key === "bottom") return rows[rows.length - 1]![1] + s("4") + j * s("3"); + const g = Number(key.slice(1)); + return (rows[g - 1]![1] + rows[g]![0]) / 2 + (j - (count - 1) / 2) * s("3"); + }; + // A margin's lanes nest by the merged rule: the farther-going outermost. An interior gap's take the order that crosses least (below). + const setCorridor = (key: string, order: number[][]) => order.forEach((g, j) => g.forEach((k) => { far.get(k)!.y = corridorY(key, j, order.length); })); + const nestCorridors = () => { + for (const [key, groups] of corridorGroups) { + const live = groups.map((g) => g.filter((k) => far.has(k))).filter((g) => g.length); + corridorGroups.set(key, live); + setCorridor(key, key === "top" || key === "bottom" ? live.slice().sort((p, q) => reach(p) - reach(q)) : live.slice().sort((p, q) => reach(q) - reach(p))); + } + }; + nestCorridors(); // 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 }>(); const turnBacks = new Set(); - m.edges.forEach((e, k) => { + // A far line's last gutter (its bus's), by edge. + const farLast = new Map(); + const join = (key: string, span: [number, number], vertical: boolean, port: string, id: number) => { + if (!jogs.has(key)) jogs.set(key, { span, vertical, members: new Map() }); + const g = jogs.get(key)!; + if (!g.members.has(port)) g.members.set(port, []); + g.members.get(port)!.push(id); + }; + const gather = () => { jogs.clear(); turnBacks.clear(); farLast.clear(); m.edges.forEach((e, k) => { if (dropped.has(k)) return; + // A far line turns in two gutters: its own (a lane of its own, keyed by -(k + 1)) and the referenced table's, where it joins the key's bus. + const f = far.get(k); + if (f?.first) join(f.first.key, f.first.span, true, `far:${k}`, -(k + 1)); const [s1, s2] = sides[k]!; const { p1, p2 } = ends[k]!; const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; @@ -1515,7 +2267,7 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge 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) { + } else if (isH(s1) && isH(s2) && (f || 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]; @@ -1528,19 +2280,30 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge 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); - }); + if (f) farLast.set(k, span); + join(key, span, vertical, `${e.to}.${s2}.${Math.round(vertical ? p2.y : p2.x)}`, k); + }); }; + gather(); const lanes = new Map(); const route = (k: number): Pt[] => { const [s1, s2] = sides[k]!; const { p1, p2 } = ends[k]!; + const f = far.get(k); + if (f) { + // Out to its own gutter's lane, along its corridor, into the referenced table's gutter (the bus there) and the key. + const last = farLast.get(k); + const x1 = lanes.get(-(k + 1)) ?? (f.first ? (f.first.span[0] + f.first.span[1]) / 2 : p1.x); + const x2 = lanes.get(k) ?? (last ? (last[0] + last[1]) / 2 : p2.x); + return [p1, { x: x1, y: p1.y }, { x: x1, y: f.y }, { x: x2, y: f.y }, { x: x2, y: p2.y }, p2]; + } if (isH(s1) && isH(s2)) { - 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 (s1 === s2) { + // A one-column schema's turn-back takes its lane: space-4 out, the second space-3 further (call 2); space-6 out where marks are drawn (1.1). + const out = s(m.marks ? "6" : "4") + (m.type === "schema" && m.cols === 1 ? (turnBackLanes(m).lane.get(k) ?? 0) * s("3") : 0); + const x = lanes.get(k) ?? (s1 === "right" ? Math.max(p1.x, p2.x) + out : Math.min(p1.x, p2.x) - out); + 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]; @@ -1566,7 +2329,7 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge 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 }; + return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: finish(pts), dot: e.fk && !e.card ? pts[0] : undefined, card: e.card, width: w, axes }; }; 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 @@ -1580,11 +2343,19 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge }; // 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. + // A member's run along its gutter: a line's from end to end; a far line's from its row to its corridor (its own gutter) or on to its key. 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]; }); + const ys = members.flatMap((id) => { + const k = id < 0 ? -id - 1 : id; + const { p1, p2 } = ends[k]!; + const f = far.get(k); + if (f) return id < 0 ? [p1.y, f.y] : [f.y, p2.y]; + return vertical ? [p1.y, p2.y] : [p1.x, p2.x]; + }); return [Math.min(...ys), Math.max(...ys)]; }; - for (const [, g] of jogs) { + const edgeOf = (id: number) => (id < 0 ? -id - 1 : id); + const clustersOf = (g: { span: [number, number]; vertical: boolean; members: Map }) => { 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 = []; for (const p of ports) { @@ -1592,26 +2363,112 @@ function drawnGeometry(input: DrawnInput, measure: ReturnType): Ge // 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) { - // A turn-back alone keeps its own place, space-4 out from the side; beside a jog or another turn-back, they share the gutter's lanes. - if (cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k))) continue; + // A turn-back alone keeps its own place, space-4 out from the side (space-6 where marks are drawn); beside a jog or another turn-back, they share the gutter's lanes. + return clusters.filter((cluster) => !(cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k)))); + }; + // A marked gutter's lanes are counted by what runs beside what (1.1): a line needs a lane apart only from the lines its run is beside (closer than + // space-8, the merged rule for sharing the middle), so the lanes a cluster needs are the most runs beside each other at one height. Each run takes the first lane + // free of the runs beside it, in the order the runs start: as few lanes as the most beside one another. + type Cluster = ReturnType[number]; + const besideIn = (cluster: Cluster) => (i: number, j: number) => cluster[i]!.run[0] < cluster[j]!.run[1] + s("8") && cluster[j]!.run[0] < cluster[i]!.run[1] + s("8"); + const firstFit = (cluster: Cluster) => { + const beside = besideIn(cluster); + const slot: number[] = []; + cluster.forEach((_, i) => { let l = 0; while (slot.some((x, j) => x === l && beside(i, j))) l++; slot.push(l); }); + return slot; + }; + const needOf = (cluster: Cluster) => Math.max(0, ...firstFit(cluster)) + 1; + // A marked gutter (1.1) holds three lanes at most: a line that would need a fourth is not drawn, a far line first and then the later in the + // author's order (its lane and its bus go with it). + if (m.marks) for (let guard = 0; guard < m.edges.length; guard++) { + let over: number[][] | null = null; + for (const [, g] of jogs) for (const cluster of clustersOf(g)) if (needOf(cluster) > 3) { over = cluster.map((c) => c.members.map(edgeOf)); break; } + if (!over) break; + const latest = (group: number[]) => Math.max(...group); + const victim = over.filter((group) => group.some((k) => far.has(k))).sort((p, q) => latest(q) - latest(p))[0] ?? over.slice().sort((p, q) => latest(q) - latest(p))[0]!; + for (const k of victim) { drop(k, dev ? "would need a fourth lane in a marked gutter" : ""); far.delete(k); } + gather(); + } + // Lanes in a marked gutter (1.1): none nearer a table than the zone plus radius-xs (18), centred and evenly spaced at the merged pitch or the pitch + // that puts the outer lanes 18 from the tables, whichever is less: one at 30, two at 20 and 40, three at 18, 30 and 42 in the 60 gap. + const laneAt = (span: [number, number], j: number, count: number) => { + const width = span[1] - span[0]; + if (!m.marks) return span[0] + (width / (count + 1)) * (j + 1); + const room = tk.foot + tk.radiusXs; + const step = count > 1 ? Math.min(width / (count + 1), (width - 2 * room) / (count - 1)) : 0; + return (span[0] + span[1]) / 2 + (j - (count - 1) / 2) * step; + }; + // An interior corridor's two lanes: the order that crosses least. + nestCorridors(); + for (const [key, groups] of corridorGroups) { + if (key === "top" || key === "bottom" || groups.length < 2) continue; + const members = new Set(groups.flat()); + let best = groups, bestScore = Infinity; + for (const perm of permutations(groups.slice().sort((p, q) => reach(q) - reach(p)))) { + setCorridor(key, perm); + current = null; + const tried = score(members); + if (tried.score < bestScore) { bestScore = tried.score; best = perm; } + } + setCorridor(key, best); + current = null; + } + for (const [, g] of jogs) { + for (const cluster of clustersOf(g)) { const groupsOf = cluster.map((c) => c.members); + if (m.marks) { + // A marked gutter: its lanes by what runs beside what, each assignment that keeps runs beside each other apart tried, the one that crosses + // least kept (the first-fit one wins a tie). + const need = needOf(cluster), beside = besideIn(cluster), n = cluster.length; + const inGutter = new Set(groupsOf.flat().map(edgeOf)); + const set = (slots: number[]) => slots.forEach((l, i) => groupsOf[i]!.forEach((k) => lanes.set(k, laneAt(g.span, l, need)))); + let best = firstFit(cluster), bestScore = Infinity, bestLines: GLine[] | null = null; + const tries: number[][] = [best]; + if (need ** n <= 729) for (let code = 0; code < need ** n; code++) { + const slots = Array.from({ length: n }, (_, i) => Math.floor(code / need ** i) % need); + if (slots.every((x, i) => slots.every((y, j) => j <= i || x !== y || !beside(i, j)))) tries.push(slots); + } + for (const slots of tries) { + set(slots); + const tried = score(inGutter); + if (tried.score < bestScore) { bestScore = tried.score; best = slots; bestLines = tried.lines; } + } + set(best); + current = bestLines; + continue; + } const count = groupsOf.length; - const step = (g.span[1] - g.span[0]) / (count + 1); - if (dev && step < s("3")) warn?.(`a gutter holds ${count} lanes side by side, closer than space-3`); - const inGutter = new Set(groupsOf.flat()); + if (dev && !m.marks && (g.span[1] - g.span[0]) / (count + 1) < s("3")) warn?.(`a gutter holds ${count} lanes side by side, closer than space-3`); + const inGutter = new Set(groupsOf.flat().map(edgeOf)); 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)))); + perm.forEach((members, j) => members.forEach((k) => lanes.set(k, laneAt(g.span, j, count)))); 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)))); + best.forEach((members, j) => members.forEach((k) => lanes.set(k, laneAt(g.span, j, count)))); current = bestLines; } } geo.lines = build(); - if (dev) 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`); + // A marked line whose end run cannot hold its zone (1.1): the marks and an elbow's room past them, or both zones on a straight line. + if (m.marks) geo.lines = geo.lines.filter((l) => { + if (!l.card) return true; + const segs = segmentsOf(l.pts); + const len = ([a, b]: readonly [Pt, Pt]) => Math.hypot(b.x - a.x, b.y - a.y); + const need = segs.length === 1 ? 2 * tk.foot : tk.foot + tk.radiusXs - 0.5; + if (len(segs[0]!) >= need && len(segs[segs.length - 1]!) >= need) return true; + drop(l.i, dev ? "has no room for its marks at an end" : ""); + far.delete(l.i); + return false; + }); + // The rows a far line's corridor needs (1.1): a row gap that carries one is space-10 (space-8 otherwise); a margin corridor adds space-8. + if (far.size) { + const used = new Set([...far.values()].map((f) => f.corridor)); + const tracks = [used.has("top") ? "var(--basalt-space-8)" : "0px"]; + for (let r = 1; r <= m.rows; r++) tracks.push("auto", r < m.rows ? (used.has(`g${r}`) ? "var(--basalt-space-10)" : "var(--basalt-space-8)") : used.has("bottom") ? "var(--basalt-space-8)" : "0px"); + geo.corridors = { rows: tracks.join(" "), pick }; + } geo.crossings = findCrossings(geo.lines); geo.through = throughOf(geo.lines, nodes, m); geo.outside = outsideOf(geo.lines, W, H, tk); @@ -1691,6 +2548,30 @@ function sequenceGeometry(input: DrawnInput, geo: Geo, sn: ReturnType { 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; }; + // Each message's line height, by its number, for the bars. + const rowY = new Map(); + drawing.querySelectorAll(`.${P}-msg`).forEach((li) => { + const r = rectOf(li, origin); + rowY.set(Number(li.querySelector(`.${P}-num`)?.textContent ?? 0), (r.t + r.b) / 2); + }); + // Activation bars (1.2): size-diagram-activation wide, centred on the lifeline, from the opening message's line to the closing one's; a nested bar + // space-1 toward the end side (the start side on the last participant). A one-row bar (a self-call that opens and closes it) spans its loop. + const W = tk.activation, half = W / 2; + const barRect = (bar: MBar) => { + const who = m.byId.get(bar.who); + if (!who) return null; + const lx = xOf(bar.who); + const lastOne = who.i === m.nodes.length - 1 && m.nodes.length > 1; + const dir = (lastOne ? -1 : 1) * (m.rtl ? -1 : 1); + const off = (bar.depth - 1) * s("1") * dir; + const y1 = rowY.get(bar.from) ?? 0, y2 = rowY.get(bar.to) ?? y1; + const one = bar.from === bar.to; + return { l: sn.x(lx - half + off, tk.hair), r: sn.x(lx + half + off, tk.hair), t: sn.y(one ? y1 - s("2") - s("1") : y1, tk.hair), b: sn.y(one ? y1 + s("2") + s("1") : y2, tk.hair) }; + }; + const placedBars = m.bars.map((bar) => ({ bar, rect: barRect(bar) })).filter((x) => x.rect) as Array<{ bar: MBar; rect: Rect }>; + geo.bars = placedBars.map((x) => x.rect); + /** The deepest bar a participant has at a message (the one a line ends on), and whether one it opens counts. */ + const barAt = (who: string, n: number, opening: boolean) => placedBars.filter(({ bar }) => bar.who === who && bar.to >= n && (opening ? bar.from <= n : bar.from < n || (bar.from === n && bar.to === n))).sort((x, y) => y.bar.depth - x.bar.depth)[0]?.rect; drawing.querySelectorAll(`.${P}-msg`).forEach((li) => { const from = li.dataset.from!, to = li.dataset.to!; const kind = (li.dataset.kind ?? "plain") as DiagramLineKind; @@ -1698,25 +2579,52 @@ function sequenceGeometry(input: DrawnInput, geo: Geo, sn: ReturnType 0 ? bar.r : bar.l) : x1; 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 }]; + pts = [{ x: edge, y: yt }, { x: sn.x(x1 + out, w), y: yt }, { x: sn.x(x1 + out, w), y: yb }, { x: edge, y: yb }]; + } else { + // A line ends on a bar's edge, as a line ends on the shape drawn (1.2): the receiver's bar (one this message opens included), the sender's. + const toward = x2 > x1 ? 1 : -1; + const sb = barAt(from, num, false), rb = barAt(to, num, true); + if (sb) x1 = toward > 0 ? sb.r : sb.l; + if (rb) x2 = toward > 0 ? rb.l : rb.r; + 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"); })() + // The neighbour on the loop's side, by column (right to left the author's order runs the other way). + ? (() => { const next = m.nodes.find((n) => n.col === a.col + (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; }); + // A frame's header (its tab, then its label) must fit inside its frame (1.2): a header that does not stacks the figure. + drawing.querySelectorAll(`.${P}-fhead`).forEach((head) => { + const box = head.parentElement?.querySelector(`:scope > .${P}-fbox`); + if (!box) return; + const need = [...head.children].reduce((sum, c) => sum + c.getBoundingClientRect().width, 0) + s("3"); + if (need > box.getBoundingClientRect().width + 0.5) (geo.misfit ??= []).push(`the frame "${head.querySelector(`.${P}-flabel`)?.textContent ?? ""}" is wider than its participants`); + }); + // Any text box, grown space-1, that would lie on a frame's side fails the fit rule too (1.2; Neon's B7 of the code review): the figure stacks. + { + const sides = [...drawing.querySelectorAll(`.${P}-fbox`)].flatMap((el) => { const r = rectOf(el, origin); return [{ x: r.l + 0.5, t: r.t, b: r.b }, { x: r.r - 0.5, t: r.t, b: r.b }]; }); + if (sides.length) drawing.querySelectorAll(`.${P}-said, .${P}-note, .${P}-band > span`).forEach((el) => { + if (!el.getClientRects().length) return; + const r = grow(rectOf(el, origin), s("1")); + if (sides.some((f) => r.l < f.x && r.r > f.x && r.t < f.b && r.b > f.t)) (geo.misfit ??= []).push(`"${el.textContent?.trim() ?? ""}" would lie on a frame's side`); + }); + } return geo; } @@ -1752,6 +2660,10 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType, p }); const order = m.nodes; const card = (i: number) => map.get(order[i]!.id)!; + // The first card of a group entered by a turn (ruling 4 on the re-check): its turn's label takes the first seat beside the turn that clears the card, a + // line at a time up into the room the group keeps for it, never above the group's edge (the group's edge and label are obstacles). + const turnInto = (id: string) => { const el = drawing.querySelector(`.${P}-node[data-node="${CSS.escape(id)}"]`); const g = el?.parentElement; return Boolean(g?.matches(`.${P}-group[data-turn]`) && g.querySelector(`:scope > .${P}-node`) === el); }; + const beside = (box: Rect, id: string, lh: number) => (turnInto(id) ? Array.from({ length: Math.round(lh / 16) + 1 }, (_, j) => ({ ...box, t: box.t - j * s("4"), b: box.b - j * s("4") })) : [box]); // 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 }> = []; @@ -1763,7 +2675,7 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType, p let pts: Pt[] = []; const label = e.label; const lw = label ? measure(label, "label") : 0; - const lh = 16; + const lh = label ? 16 * labelLines(label) : 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); @@ -1800,20 +2712,28 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType, p 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: 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 }); + if (label) labelSeats.push({ k, cands: [...beside({ l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }, e.to, lh), ...lineSeats({ l: ex + s("2-5"), r: ex + s("2-5") + lw, t: ty - lh / 2, b: ty + lh / 2 }, e.to, -1).slice(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 ? spineEnd + (plan.lanes[k] ? 2 * s("3-5") : s("3-5")) : right - s("2-5"), w); + // Lanes space-3-5 apart, one pitch (DECISIONS 306, 1.3). + const laneX = sn.x(plan.gutter ? spineEnd + (plan.lanes[k]! + 1) * 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); + // Several end lines into one card nest (1.3): the line from the outermost lane turns lowest (the merged turn) and enters nearest the end edge + // (space-6 in); each from a lane further in turns space-5 higher and enters space-3 further in. Their labels are seated space-2-5 clear of the + // innermost entry, each centred on its own turn's height, taken before the half-pixel snap. + const mates = m.edges.map((o, j) => ({ o, j })).filter(({ o, j }) => (plan.routes[j] === r) && o.to === e.to).sort((x, y) => plan.lanes[y.j]! - plan.lanes[x.j]! || x.j - y.j); + const at = Math.max(0, mates.findIndex(({ j }) => j === k)); + const exRaw = b.rect.r - s("6") - at * s("3"), innerEx = b.rect.r - s("6") - (mates.length - 1) * s("3"); + const ex = sn.x(exRaw, w); + const tyRaw = down ? b.rect.t - turn - at * s("5") : b.rect.b + turn + at * s("5"); + const ty = sn.y(tyRaw, w); pts = [exit, { x: laneX, y: exit.y }, { x: laneX, y: ty }, { x: ex, y: ty }, contour(b, down ? "top" : "bottom", ex)]; 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 }); + if (label) labelSeats.push({ k, cands: [...(down ? beside({ l: innerEx - s("2-5") - lw, r: innerEx - s("2-5"), t: tyRaw - lh / 2, b: tyRaw + lh / 2 }, into, lh) : [{ l: innerEx - s("2-5") - lw, r: innerEx - s("2-5"), t: tyRaw - lh / 2, b: tyRaw + lh / 2 }]), ...lineSeats({ l: innerEx - s("2-5") - lw, r: innerEx - s("2-5"), t: tyRaw - lh / 2, b: tyRaw + lh / 2 }, into, down ? -1 : 1).slice(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 }); @@ -1848,13 +2768,16 @@ function stackedGeometry(input: DrawnInput, measure: ReturnType, p // ---- The ink: one string of SVG and labels, the same in React and in the skill ---- -export function pathD(pts: Pt[], radius: number): string { +/** A route as a path, its corners rounded. `zone` (a marked line's, 1.1): no elbow starts within it of either end. */ +export function pathD(pts: Pt[], radius: number, zone = 0): 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); + let r = Math.min(radius, d1 / 2, d2 / 2); + if (zone && k === 1) r = Math.min(r, Math.max(0, d1 - zone)); + if (zone && k === pts.length - 2) r = Math.min(r, Math.max(0, d2 - zone)); 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 }; @@ -1868,6 +2791,15 @@ const unit: Record = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: function lineMarkup(P: string, l: GLine, tk: Tokens, maskId: string | null, radius: number): string { const u = unit[l.dir]; + // A line that states how many (1.1): its shaft runs to both tables' edges, through crow's-foot marks in its own ink, with no dot and no head. + if (l.card) { + const a = l.pts[0]!, b = l.pts[1]!; + const end = (form: DiagramCardinality, at: Pt, out: number, which: string) => { + const { crow, ring } = cardMarks(form, at.x, at.y, out, tk.head, tk.dot); + return `${ring ? `` : ""}`; + }; + return `${end(l.card.from, a, Math.sign(b.x - a.x) || 1, "from")}${end(l.card.to, l.tip, -u.x || 1, "to")}`; + } 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). @@ -1911,23 +2843,27 @@ function masksMarkup(P: string, geo: Geo, tk: Tokens, base: string): { defs: str /** 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); + // A sequence's lifelines are their own layer, under its frames; the bars, lines and heads are over them (1.2's order: lifelines, frames, bars, lines, + // plates and labels; Neon's P8 of the code review). const lifelines = geo.lifelines.map((l) => ``).join(""); + const bars = (geo.bars ?? []).map((b) => ``).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 = `${defs ? `${defs}` : ""}${lifelines}${lines}`; - const labels = geo.labels.map((l) => `${escapeHtml(l.text)}`).join(""); + const under = lifelines ? `${lifelines}` : ""; + const svg = `${under}${defs ? `${defs}` : ""}${bars}${lines}`; + const labels = geo.labels.map((l) => ` 1 ? ' data-lines="2"' : ""} 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">${l.text.split("\n").map(escapeHtml).join("
")}
`).join(""); return svg + labels; } // ---- Laying a figure out ---- -export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Tokens | null } +export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Tokens | null; least?: number } /** * 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 { +export function measureFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn?: (s: string, level?: "error") => void, sizeTo?: (least: number) => void): Measured { // Development only (the warnings): first, so a minifier sees it is a constant and drops what it guards. const dev = process.env.NODE_ENV !== "production"; const drawing = fig.querySelector(`.${P}-drawing`); @@ -1936,13 +2872,18 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin const tk = readTokens(fig); const measure = ruler(drawing, P); const mins = minimums(m, tk, measure); + // The viewer (DECISIONS 310, 9.3) sizes its figure from the least drawn width before it is measured: never under it, so the drawn layout is tried. + sizeTo?.(mins.least); 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 }; }; + // A decision that is taller than it is wide at this width (call 1 of DECISIONS 306, section 4): the drawn layout is refused, as any fit failure is. + let tall = false; const heightsFor = (d: Dyn): Dyn => { + tall = false; if (m.type !== "flowchart") return d; apply({ ...d, heights: undefined, words: undefined }); const heights = record(); @@ -1980,6 +2921,8 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin el.style.removeProperty("--_ww"); } heights[el.dataset.node!] = height; + // Taller than wide after every width its words can take (DECISIONS 306, section 4, call 1): a width the flowchart is not drawn at. + if (height > nr.width) tall = true; }); return { ...d, heights, words: Object.keys(widened).length ? widened : undefined }; }; @@ -1987,35 +2930,46 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin // 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) { + // The text variant is one code block: no drawn layout and no lines; the art module chooses art or transcript by width (1.2). + if (m.text) return { dyn: { ...current, layout: "stacked", bare: undefined }, geo: null, ink: "", tokens: tk, least: mins.least }; + if (W >= mins.least && !m.unplaced) { const drawnTry = (pad: boolean) => { - let dd = stopOf({ ...current, ...closed, layout: "drawn", grow: undefined, track: undefined, bare: undefined, pad: pad || undefined }); + let dd = stopOf({ ...current, ...closed, layout: "drawn", grow: undefined, track: undefined, bare: undefined, pad: pad || undefined, rows: undefined }); dd = heightsFor(dd); apply(dd); - return { dd, g: drawnGeometry(input(), measure) }; + let g = drawnGeometry(input(), measure); + // A schema's far keys (1.1): their corridors are chosen on the grid without them, then the rows grow to hold them and the figure is measured again. + if (g.corridors) { + dd = { ...dd, rows: g.corridors.rows }; + apply(dd); + g = drawnGeometry({ ...input(), pick: g.corridors.pick }, measure); + } + return { dd, g }; }; 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. // A route the drawn layout refuses: through a node, off the drawing, or laid on another line. - const refused = (g: Geo) => g.through.length > 0 || g.outside.length > 0 || (g.overlaps?.length ?? 0) > 0; + const refused = (g: Geo) => g.through.length > 0 || g.outside.length > 0 || (g.overlaps?.length ?? 0) > 0 || (g.misfit?.length ?? 0) > 0 || tall; if (!refused(geo) && geo.unseated.length && geo.unseated.every((k) => geo.bounded?.includes(k))) { const padded = drawnTry(true); if (!refused(padded.g) && !padded.g.unseated.length) ({ dd: d, g: geo } = padded); } if (!refused(geo) && !geo.unseated.length) { if (geo.crossings.length) dev && 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 }; + return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk, least: mins.least }; } // At a width the figure should fit by its tokens and words, a failure is the author's to fix. + if (tall) dev && warn?.(`the drawn layout does not fit at ${Math.round(W)}px: a decision would be taller than it is wide`); + if (geo.misfit?.length) dev && warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${geo.misfit.join("; ")}`); if (geo.through.length) dev && warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.through)} would pass through a node`); if (geo.overlaps?.length) dev && warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.overlaps)} would lie on one another`); if (geo.outside.length) dev && warn?.(`the drawn layout does not fit at ${Math.round(W)}px: ${names(geo, geo.outside)} would leave the drawing`); - if (geo.unseated.length) dev && 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.unseated.length) dev && 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}` : `"${said(m.edges[k]?.label ?? "")}"`)).join(", ")}`); } - let d = stopOf({ ...current, ...closed, layout: "stacked", heights: undefined, grow: record(), track: m.type === "schema" ? mins.table : undefined, bare: undefined, pad: undefined }); + let d = stopOf({ ...current, ...closed, layout: "stacked", heights: undefined, grow: record(), track: m.type === "schema" ? mins.table : undefined, bare: undefined, pad: undefined, rows: undefined }); d = heightsFor(d); apply(d); - if (m.type === "sequence" || m.type === "schema") return { dyn: d, geo: null, ink: "", tokens: tk }; + if (m.type === "sequence" || m.type === "schema") return { dyn: d, geo: null, ink: "", tokens: tk, least: mins.least }; const plan = stackPlan(m); let out = stackedGeometry(input(), measure, plan, d.grow); for (let tries = 0; tries < 6 && Object.keys(out.grow).length; tries++) { @@ -2029,19 +2983,23 @@ export function measureFigure(fig: HTMLElement, m: Model, P: string, base: strin // 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. + if (dev && !plan.third && plan.laneCount > 2) warn?.(`the stacked drawing uses ${plan.laneCount} end lanes (four at most)`); const failed = geo.unseated.length > 0 || geo.through.length > 0 || geo.outside.length > 0 || plan.third; if (failed) { - if (geo.unseated.length) dev && 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.unseated.length) dev && warn?.(`the stacked drawing has no clean seat for ${[...new Set(geo.unseated)].map((k) => `"${said(m.edges[k]?.label ?? "")}"`).join(", ")}, so its lines are not drawn; the list holds every connection`); if (geo.through.length) dev && warn?.(`in the stacked drawing ${names(geo, geo.through)} would pass through a node, so its lines are not drawn`); if (geo.outside.length) dev && warn?.(`in the stacked drawing ${names(geo, geo.outside)} would leave the drawing, so its lines are not drawn`); - if (dev && plan.third) warn?.("the stacked drawing would need a third end lane, so its lines are not drawn"); + if (dev && plan.third) warn?.("the stacked drawing would need a fifth end lane, so its lines are not drawn", "error"); // 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: [] }; 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 }; + // Written as it is returned: the tries above wrote a state that is not bare, and a host that sees the same state as before renders nothing, so the + // figure would keep their markup (a stack with no lines, not dressed bare, its list closed: P-R3 of the code re-check). + apply(dyn); + return { dyn, geo: bare, ink: "", tokens: tk, least: mins.least }; } if (geo.crossings.length) dev && 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 }; + return { dyn: d, geo, ink: inkHtml(P, geo, tk, base), tokens: tk, least: mins.least }; } function lineName(m: Model, l: GLine): string { @@ -2114,7 +3072,14 @@ export function entranceDrawn(fig: HTMLElement, lines: boolean): void { const state = fig.getAttribute("data-entrance"); if (state === "running" || state === "done") return; if (!lines) { if (state) fig.removeAttribute("data-entrance"); return; } - if (!state) fig.setAttribute("data-entrance", entranceBlocked() ? "done" : "pending"); + if (!state) fig.setAttribute("data-entrance", entranceBlocked() || seenBefore(fig) ? "done" : "pending"); +} +/** The first visit's mark (DECISIONS 306, 1.5): where a figure's entrance has played on this page before. */ +export const visitKey = (fig: HTMLElement) => `basalt-diagram-entrance:${location.pathname}#${fig.id}`; +function seenBefore(fig: HTMLElement): boolean { + if (!fig.hasAttribute("data-first-visit") || !fig.id) return false; + // Storage that throws: it plays again. + try { return localStorage.getItem(visitKey(fig)) !== null; } catch { return false; } } /** Settles a pending or running entrance at once (a node hovered or focused, a key, a control used): every line whole, and the module told. */ @@ -2126,7 +3091,13 @@ export function settleEntrance(fig: HTMLElement): void { } /** 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 { +export function keyTarget(m: Model, from: string, key: string, drawn = false, rtl = false): string | null { + // Drawn, the arrows are spatial and physical: in a right-to-left figure column 1 is at the right (1.5). + const table = drawn ? spatialTable(m) : null; + if (table && key.startsWith("Arrow")) { + const way = ({ ArrowRight: rtl ? "left" : "right", ArrowLeft: rtl ? "right" : "left", ArrowDown: "down", ArrowUp: "up" } as Record)[key]; + return way ? table[from]?.[way] ?? null : null; + } const i = m.byId.get(from)?.i ?? 0; const n = m.nodes.length; let to: number; @@ -2147,9 +3118,10 @@ export function keyTarget(m: Model, from: string, key: string): string | null { * 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", "data-bare", "data-motion"]; -const MANAGED_STYLE = ["--_track", "--_h", "--_ww", "--_gap", "--_ggrow", "--_gpad"]; +const MANAGED = ["data-layout", "data-measured", "role", "aria-roledescription", "aria-labelledby", "aria-describedby", "aria-label", "tabindex", "data-stops", "hidden", "data-art"]; +// The figure's grid attributes follow the model too: an automatic figure's direction can change its columns after script (Neon's B8 of the code review). +const ROOT_MANAGED = ["data-layout", "data-measured", "data-bare", "data-motion", "data-first-visit", "data-rtl", "data-cols", "data-reach", "data-gutter", "data-marks"]; +const MANAGED_STYLE = ["--_track", "--_h", "--_ww", "--_gap", "--_ggrow", "--_tl", "--_gpad", "--_gw", "--_mh", "--_rows", "--_row-gap"]; 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-elk.ts b/packages/react/src/diagram-elk.ts new file mode 100644 index 00000000..b0f1ea11 --- /dev/null +++ b/packages/react/src/diagram-elk.ts @@ -0,0 +1,8 @@ +// elkjs (EPL-2.0 OR GPL-3.0-or-later, used under EPL-2.0, unmodified), as an ES module of its own: build.mjs copies elkjs's own file into +// dist/diagram-elk.js, with its licence beside it (dist/elkjs/LICENSE.md), so its CommonJS wrapper lives in this one file and never in an app's shared +// chunk. Only diagram-layout imports it, on demand. Its type here is Basalt's own: no elkjs type is in any declaration (AGENTS.md). +import ELK from "elkjs/lib/elk.bundled.js"; + +/** The layout class, as diagram-layout calls it. */ +const Elk = ELK as unknown as new () => { layout: (graph: object) => Promise }; +export default Elk; diff --git a/packages/react/src/diagram-export.ts b/packages/react/src/diagram-export.ts new file mode 100644 index 00000000..bd5bc9ed --- /dev/null +++ b/packages/react/src/diagram-export.ts @@ -0,0 +1,266 @@ +// A diagram to a file (DECISIONS 306, 1.7): `@srasyndicate/basalt/diagram-export`, a module of its own that an app loads on demand and wires to its own +// button. Never imported by the index or by a figure. The file holds the title and source, the drawing as it is laid out now (drawn or stacked) and the +// key, on surface-page with space-4 round it, at rest: every line whole, no mover, no trace. Native SVG only, never foreignObject: boxes are rects, lines +// and marks are the drawing's own SVG and images, and words are SVG text set from the live figure's measured line boxes. Nothing here runs at load. +// The implementation hasn't been reviewed. + +/** The theme of the file: the page's (the default), or light or dark. */ +export interface DiagramExportOptions { + theme?: "page" | "light" | "dark"; + /** SVG only: "embed" (the default) writes the faces into the file, so it measures the same anywhere; "name" writes the font stack, for design tools. */ + fonts?: "embed" | "name"; + /** PNG only: device pixels per CSS pixel (default 2). */ + scale?: number; +} + +const NS = "http://www.w3.org/2000/svg"; +const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); +const visible = (c: string) => Boolean(c) && c !== "transparent" && !/rgba\([^)]*,\s*0\)$/.test(c) && !/\/\s*0\)$/.test(c); +const r2 = (n: number) => Math.round(n * 100) / 100; + +/** The parts of a figure a file holds: its head, its drawing and its key (no control, hint or list). */ +function partsOf(fig: HTMLElement): HTMLElement[] { + const pick = (cls: string) => fig.querySelector(`:scope > [class$="-${cls}"], :scope > [class*="-${cls} "]`); + return ["head", "drawing", "key"].map(pick).filter((el): el is HTMLElement => Boolean(el && el.getClientRects().length)); +} + +/** A face's file as a data URI, from the page's own @font-face rules; null where it cannot be read. */ +async function faceData(family: string): Promise { + for (const sheet of Array.from(document.styleSheets)) { + let rules: CSSRuleList; + try { rules = sheet.cssRules; } catch { continue; } + for (const rule of Array.from(rules)) { + if (!(rule instanceof CSSFontFaceRule)) continue; + if (rule.style.getPropertyValue("font-family").replace(/["']/g, "").trim() !== family) continue; + const url = /url\(["']?([^"')]+)["']?\)/.exec(rule.style.getPropertyValue("src"))?.[1]; + if (!url) continue; + if (url.startsWith("data:")) return url; + try { + const res = await fetch(new URL(url, sheet.href ?? location.href)); + // A face that is not there (a 404's page) is not embedded: the file names the face instead. + if (!res.ok) return null; + const blob = await res.blob(); + return await new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(String(r.result)); r.onerror = reject; r.readAsDataURL(blob); }); + } catch { return null; } + } + } + return null; +} + +/** Text as SVG text, one element per word, each at its own measured box, so the file is the figure's words where the figure set them. */ +function textOf(root: Element, origin: DOMRect, out: string[]) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + const el = node.parentElement; + if (!el || !node.textContent?.trim()) continue; + if (el.closest("[aria-hidden='true'] .basalt-visually-hidden, .basalt-visually-hidden, .visually-hidden, [class$='-ruler'], [hidden]")) continue; + const cs = getComputedStyle(el); + if (cs.visibility === "hidden" || cs.display === "none") continue; + const text = node.textContent; + const range = document.createRange(); + for (const m of text.matchAll(/\S+/g)) { + range.setStart(node, m.index!); + range.setEnd(node, m.index! + m[0].length); + const r = range.getBoundingClientRect(); + if (!r.width) continue; + const size = Number.parseFloat(cs.fontSize); + // The baseline: the line box's top plus the face's ascent, about four fifths of the size for Geist and Geist Mono. + const y = r.top - origin.top + (r.height - size) / 2 + size * 0.8; + out.push(`${esc(m[0])}`); + } + } +} + +/** A rule drawn by a ::before or ::after (a lane's rule, a band's, a frame's else rule): its box from its own computed place, as a line or a rect. */ +function pseudoOf(el: Element, origin: DOMRect, out: string[]) { + // The structural rules only: a linked card's arrow (its name's ::after) is not drawn in a file (1.7, the decider's text edit). + if (!/-(lane|band|felse)(\s|$)/.test(` ${el.getAttribute("class") ?? ""}`)) return; + for (const which of ["::before", "::after"] as const) { + const cs = getComputedStyle(el, which); + if (!cs.content || cs.content === "none" || cs.content === "normal" || cs.display === "none") continue; + if (cs.position !== "absolute") continue; + const host = el.getBoundingClientRect(), hs = getComputedStyle(el); + const x = host.left + (Number.parseFloat(hs.borderLeftWidth) || 0) + (Number.parseFloat(cs.left) || 0) - origin.left; + const y = host.top + (Number.parseFloat(hs.borderTopWidth) || 0) + (Number.parseFloat(cs.top) || 0) - origin.top; + const w = Number.parseFloat(cs.width) || 0, h = Number.parseFloat(cs.height) || 0; + const bt = Number.parseFloat(cs.borderTopWidth) || 0; + // A dashed rule is drawn as its mask draws it: on and off at the rule's own height times its dash. + const dashed = cs.maskImage && cs.maskImage !== "none" ? ` stroke-dasharray="${Number.parseFloat(cs.maskSize) / 2 || 4} ${Number.parseFloat(cs.maskSize) / 2 || 4}"` : ""; + if (visible(cs.backgroundColor) && w && h) out.push(``); + else if (bt && visible(cs.borderTopColor)) out.push(``); + } +} + +/** An SVG of the figure as it is drawn: every painted part with its computed paint, sized and placed, and no motion's mask left on it. */ +function svgOf(el: SVGSVGElement, origin: DOMRect, out: string[]) { + const r = el.getBoundingClientRect(); + if (!r.width || !r.height) return; + if (el.getAttribute("class")?.endsWith("-motion-defs")) return; + const clone = el.cloneNode(true) as SVGSVGElement; + const src = [el, ...Array.from(el.querySelectorAll("*"))]; + const dst = [clone, ...Array.from(clone.querySelectorAll("*"))]; + // A viewBox drawn at another size (the flowchart's diamond): its strokes keep their width. + const vb = el.viewBox?.baseVal; + const stretched = Boolean(vb && vb.width && (Math.abs(vb.width - r.width) > 0.5 || Math.abs(vb.height - r.height) > 0.5)); + src.forEach((s, k) => { + const cs = getComputedStyle(s); + const d = dst[k] as Element; + for (const p of ["fill", "stroke", "stroke-width", "stroke-dasharray", "stroke-linecap", "stroke-linejoin", "opacity"]) d.setAttribute(p, cs.getPropertyValue(p)); + d.removeAttribute("class"); + // An entrance's reveal is its own mask: a file is at rest, every line whole. + if (/-reveal-/.test(d.getAttribute("mask") ?? "")) d.removeAttribute("mask"); + if (stretched && k > 0) d.setAttribute("vector-effect", "non-scaling-stroke"); + if (cs.display === "none") d.setAttribute("display", "none"); + }); + clone.setAttribute("x", String(r2(r.left - origin.left))); + clone.setAttribute("y", String(r2(r.top - origin.top))); + clone.setAttribute("width", String(r2(r.width))); + clone.setAttribute("height", String(r2(r.height))); + clone.removeAttribute("style"); + out.push(clone.outerHTML); +} + +/** + * Every box with a fill or an edge as a rect, the drawing's SVG as it is, the rules drawn by pseudo-elements, and the marks as images. The drawing's + * lines go first, under its cards and plates, as the page paints them (the ink is behind the nodes). + */ +function boxesOf(root: Element, origin: DOMRect, out: string[]) { + const all = [root, ...Array.from(root.querySelectorAll("*"))]; + const inks = all.filter((el): el is SVGSVGElement => el instanceof SVGSVGElement && el.closest("svg") === el && Boolean(el.closest("[class$='-ink']"))); + for (const svg of inks) svgOf(svg, origin, out); + for (const el of all) { + if (el instanceof SVGElement) { + if (el.tagName.toLowerCase() !== "svg" || el.closest("svg") !== el || inks.includes(el as SVGSVGElement)) continue; + svgOf(el as SVGSVGElement, origin, out); + continue; + } + const cs = getComputedStyle(el); + if (cs.display === "none" || cs.visibility === "hidden") continue; + const r = el.getBoundingClientRect(); + if (!r.width || !r.height) continue; + const x = r2(r.left - origin.left), y = r2(r.top - origin.top), w = r2(r.width), h = r2(r.height); + const radius = Number.parseFloat(cs.borderTopLeftRadius) || 0; + const fill = visible(cs.backgroundColor) ? cs.backgroundColor : "none"; + const sidesW = [cs.borderTopWidth, cs.borderRightWidth, cs.borderBottomWidth, cs.borderLeftWidth].map((v) => Number.parseFloat(v) || 0); + const uniform = sidesW.every((v) => v === sidesW[0]); + // An edge on some sides only (the key's divider) is drawn as those lines, not a box. + if (!uniform) { + const [t, r, b, l] = sidesW; + const edge = (on: number, color: string, x1: number, y1: number, x2: number, y2: number) => { if (on && visible(color)) out.push(``); }; + edge(t!, cs.borderTopColor, x, y + t! / 2, x + w, y + t! / 2); + edge(b!, cs.borderBottomColor, x, y + h - b! / 2, x + w, y + h - b! / 2); + edge(l!, cs.borderLeftColor, x + l! / 2, y, x + l! / 2, y + h); + edge(r!, cs.borderRightColor, x + w - r! / 2, y, x + w - r! / 2, y + h); + } + const bw = uniform ? sidesW[0]! : 0; + // A panel's rim is the sides' colour with its top lit (Neon's P8 of the code review): the box in the sides' colour, then the top edge in its own. + const sideColor = cs.borderLeftColor; + const stroke = bw && cs.borderTopStyle !== "none" && visible(sideColor) ? sideColor : "none"; + if (fill !== "none" || stroke !== "none") { + const dash = cs.borderTopStyle === "dashed" ? ` stroke-dasharray="4 2"` : ""; + out.push(``); + if (stroke !== "none" && !dash && cs.borderTopColor !== sideColor && visible(cs.borderTopColor)) out.push(``); + } + pseudoOf(el, origin, out); + // A mark is its owner's file in the export theme's form. + const image = /url\(["']?([^"')]+)["']?\)/.exec(cs.backgroundImage)?.[1]; + if (image && /-mark$/.test(String(el.getAttribute("class")))) out.push(``); + } +} + +/** The figure's title and summary, for the SVG's own title and desc. */ +const titleOf = (fig: HTMLElement) => fig.querySelector("[class$='-title']")?.textContent?.trim() ?? ""; +const summaryOf = (fig: HTMLElement) => fig.querySelector("figcaption")?.textContent?.trim() ?? ""; +/** The file's name: the title's slug. */ +export const exportName = (fig: HTMLElement, ext: string) => `${(titleOf(fig).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "diagram")}.${ext}`; + +async function svgText(fig: HTMLElement, options: DiagramExportOptions, embed: boolean): Promise<{ svg: string; w: number; h: number }> { + const theme = options.theme ?? "page"; + const had = fig.getAttribute("data-theme"); + // A file is at rest: no trace, no pending or running entrance, no mover, no quiet run (Neon's B5 of the code review). The figure is shown so for the read + // and put back at once, before anything waits. + const states = ["data-lit", "data-dim", "data-near", "data-ahead", "data-arrival", "data-arrival-out"]; + const marked = Array.from(fig.querySelectorAll(states.map((a) => `[${a}]`).join(", "))); + const marks = marked.map((el) => [el, states.map((a) => el.getAttribute(a))] as const); + marked.forEach((el) => { for (const a of states) el.removeAttribute(a); }); + const hidden = Array.from(fig.querySelectorAll("[class*='-flow'], [class*='-bead'], [class*='-packet']")); + hidden.forEach((el) => { el.dataset.exportHidden = el.style.display; el.style.display = "none"; }); + const entrance = fig.getAttribute("data-entrance"); + if (entrance && entrance !== "done") fig.setAttribute("data-entrance", "done"); + // An entrance's or a run's colour animations are read at their end, and put back where they were. + const anims = fig.getAnimations({ subtree: true }).map((a) => ({ a, at: a.currentTime, running: a.playState === "running" })); + for (const { a } of anims) { const end = a.effect?.getComputedTiming().endTime; a.pause(); if (typeof end === "number" && Number.isFinite(end)) a.currentTime = end; } + // The viewer's figure (the skill's 9.11): its head and key, which the stage hides, are in the file, and it is read at 100% whatever the zoom. + const viewer = fig.getAttribute("data-viewer"); + if (viewer !== null) fig.removeAttribute("data-viewer"); + const scaled: Array<[HTMLElement, string]> = []; + for (let el = fig.parentElement; el; el = el.parentElement) { + const t = getComputedStyle(el).transform; + const m = /^matrix\(([^,]+),[^,]+,[^,]+,([^,]+),/.exec(t); + if (m && (Math.abs(Number(m[1]) - 1) > 1e-6 || Math.abs(Number(m[2]) - 1) > 1e-6)) { scaled.push([el, el.style.transform]); el.style.transform = "none"; } + } + if (theme !== "page") fig.setAttribute("data-theme", theme); + fig.classList.add("basalt-exporting"); + let read: { body: string[]; w: number; h: number; ground: string }; + try { + void fig.offsetWidth; + const pad = Number.parseFloat(getComputedStyle(fig).getPropertyValue("--basalt-space-4")) || 16; + const parts = partsOf(fig); + const rects = parts.map((p) => p.getBoundingClientRect()); + const left = Math.min(...rects.map((r) => r.left)), top = Math.min(...rects.map((r) => r.top)); + const right = Math.max(...rects.map((r) => r.right)), bottom = Math.max(...rects.map((r) => r.bottom)); + const origin = new DOMRect(left - pad, top - pad, 0, 0); + const w = Math.ceil(right - left + 2 * pad), h = Math.ceil(bottom - top + 2 * pad); + const ground = getComputedStyle(fig).getPropertyValue("--basalt-surface-page").trim() || getComputedStyle(document.body).backgroundColor; + const body: string[] = []; + for (const p of parts) boxesOf(p, origin, body); + for (const p of parts) textOf(p, origin, body); + read = { body, w, h, ground }; + } finally { + fig.classList.remove("basalt-exporting"); + if (theme !== "page") { if (had === null) fig.removeAttribute("data-theme"); else fig.setAttribute("data-theme", had); } + for (const [el, t] of scaled) el.style.transform = t; + if (viewer !== null) fig.setAttribute("data-viewer", viewer); + for (const { a, at, running } of anims) { a.currentTime = at; if (running) a.play(); } + if (entrance && entrance !== "done") fig.setAttribute("data-entrance", entrance); + hidden.forEach((el) => { el.style.display = el.dataset.exportHidden ?? ""; delete el.dataset.exportHidden; }); + for (const [el, values] of marks) states.forEach((a, k) => { const v = values[k]; if (v !== null && v !== undefined) el.setAttribute(a, v); }); + } + const { body, w, h, ground } = read; + let style = ""; + if (embed) { + const faces: string[] = []; + for (const family of ["Geist", "Geist Mono"]) { + const data = await faceData(family); + if (data) faces.push(`@font-face{font-family:"${family}";src:url(${data});font-weight:100 900}`); + else if (process.env.NODE_ENV !== "production") console.warn(`Basalt diagramToSvg: the face "${family}" could not be read, so the file names it`); + } + if (faces.length) style = ``; + } + const svg = `${esc(titleOf(fig))}${esc(summaryOf(fig))}${style}${body.join("")}`; + return { svg, w, h }; +} + +declare const process: { env: { NODE_ENV?: string } }; + +/** The figure as an SVG file: native SVG, its words as text, the faces embedded by default. */ +export async function diagramToSvg(figure: HTMLElement, options: DiagramExportOptions = {}): Promise { + const { svg } = await svgText(figure, options, (options.fonts ?? "embed") === "embed"); + return new Blob([svg], { type: "image/svg+xml" }); +} + +/** The figure as a PNG file, at `scale` (2 by default), always drawn with the faces embedded. */ +export async function diagramToPng(figure: HTMLElement, options: DiagramExportOptions = {}): Promise { + const { svg, w, h } = await svgText(figure, options, true); + const scale = options.scale ?? 2; + const img = new Image(); + img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; + await img.decode(); + const canvas = document.createElement("canvas"); + canvas.width = Math.round(w * scale); + canvas.height = Math.round(h * scale); + const ctx = canvas.getContext("2d")!; + ctx.scale(scale, scale); + ctx.drawImage(img, 0, 0, w, h); + return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("the PNG could not be made"))), "image/png")); +} diff --git a/packages/react/src/diagram-figure.tsx b/packages/react/src/diagram-figure.tsx index 4d2e4ab2..3e406367 100644 --- a/packages/react/src/diagram-figure.tsx +++ b/packages/react/src/diagram-figure.tsx @@ -2,11 +2,11 @@ import * as React from "react"; import { Kbd } from "./kbd"; import { useShortcutsVisible } from "./keyboard"; -import { usePanelLevel } from "./layers"; +import { inLevel, usePanelLevel } from "./layers"; import { - applyTrace, buildModel, entranceDrawn, figureTree, hasStops, hintEntries, keyTarget, measureFigure, settleEntrance, syncAttributes, + applyTrace, buildModel, tapTrace, transcript, entranceDrawn, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, settleEntrance, syncAttributes, toHtml, } from "./diagram-core"; -import type { DiagramLegend, DiagramMotion, DiagramSpec, Dyn, Measured, VNode } from "./diagram-core"; +import type { DiagramLegend, DiagramMotion, DiagramPlacement, DiagramSpec, Dyn, Measured, Model, VNode } from "./diagram-core"; import type { MotionController } from "./diagram-motion-core"; type MotionModule = typeof import("./diagram-motion"); @@ -14,6 +14,21 @@ let motionLoading: Promise | undefined; /** The motion code (DECISIONS 292, 2.6): a module of its own, loaded the first time a figure is animated, so a still figure never pays for it. */ const loadMotion = () => (motionLoading ??= import("./diagram-motion").catch((error) => { motionLoading = undefined; throw error; })); +type TextModule = typeof import("./diagram-text"); +let textLoading: Promise | undefined; +/** The text art (DECISIONS 306, 1.2): generated by a module of its own, loaded by a figure with variant="text". */ +const loadText = () => (textLoading ??= import("./diagram-text").catch((error) => { textLoading = undefined; throw error; })); + +type LayoutModule = typeof import("./diagram-layout"); +let layoutLoading: Promise | undefined; +/** Automatic layout (DECISIONS 306, 1.8): elkjs's module, loaded the first time an automatic figure with no placement is measured at 640 or wider. */ +const loadLayout = () => (layoutLoading ??= import("./diagram-layout").catch((error) => { layoutLoading = undefined; throw error; })); + +type ViewerModule = typeof import("./diagram-viewer"); +let viewerLoading: Promise | undefined; +/** The viewer (DECISIONS 310, 9.13): a module of its own, with the Dialog it needs, loaded at the Expand button's first hover, focus or touch. */ +const loadViewer = () => (viewerLoading ??= import("./diagram-viewer").catch((error) => { viewerLoading = undefined; throw error; })); + // The figure every diagram shares (DECISIONS 281): 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. @@ -35,9 +50,19 @@ export interface DiagramFigureProps extends Omit, * reduced-motion or forced-colours figure is still. Motion never carries a fact alone: the words say what moves. */ motion?: DiagramMotion; + /** + * `true` (the default) puts "Expand" in the foot, after "View as list" (DECISIONS 310): it opens the viewer, a dialog that holds the drawn layout, + * where the reader zooms (from Fit or 100% to 400%) and pans it. `false` leaves both out. Before script there is no button: it does nothing without it. + */ + zoom?: boolean; + /** `"first-visit"` (DECISIONS 306, 1.5): an animated figure's entrance plays until it has played once on this page; later visits are at rest. Needs an `id`. */ + entrance?: "always" | "first-visit"; } const P = "basalt-diagram"; +/** What the viewer is handed (diagram-viewer.tsx): this component and the engine, so its chunk holds no second copy of either. Built at the first open. */ +let kitMade: import("./diagram-viewer").ViewerKit | undefined; +const kitOf = () => (kitMade ??= { Figure: DiagramFigure, Kbd, buildModel, figureKey, figureList, hintEntries, toHtml, inLevel, measureFigure }); declare const process: { env: { NODE_ENV?: string } }; const CAMEL: Record = { class: "className", tabindex: "tabIndex", for: "htmlFor", viewbox: "viewBox" }; @@ -82,18 +107,64 @@ function warnOnce(component: string, message: string) { console.warn(`Basalt ${key}`); } +/** The viewer's own figure (DECISIONS 310, 9.3): laid out and measured by the viewer, its drawing alone shown. */ +export interface DiagramViewerMode { + /** Lays the figure out (diagram-zoom-core's measureViewerFigure, with this module's engine). */ + measure: (fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn?: (s: string) => void) => Measured; + /** The words the keys sentence ends with. */ + keys: string; + /** The stage's inner size: an automatic figure takes the direction with the larger Fit in it (9.3). */ + room: () => { w: number; h: number }; + /** After every layout: what was measured, and the figure. */ + onMeasured: (measured: Measured, fig: HTMLElement) => void; + /** A text sequence (9.3): the figure's width at which the art's widest line just fits; the viewer lays it out at that width. */ + textWidth?: (need: number) => void; +} + export interface DiagramFigureInternalProps extends DiagramFigureProps { spec: DiagramSpec; component: string; + /** Internal: the figure is the viewer's (diagram-viewer.tsx). */ + viewer?: DiagramViewerMode; } -export function DiagramFigure({ spec, component, title: _title, heading: _heading, legend: _legend, motion: _motion, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ref: callerRef, ...props }: DiagramFigureInternalProps) { +export function DiagramFigure({ spec, component, viewer, zoom = true, entrance: _entrance, title: _title, heading: _heading, legend: _legend, motion: _motion, 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]); + // Right to left (DECISIONS 306, 1.7): no prop; the figure follows its computed direction, read as it is measured, and the model is mirrored. + const [rtl, setRtl] = React.useState(false); + // Automatic layout (1.8): the placements given or loaded, and the direction tried (the type's own, then the other, unless the author named one). + const auto = spec.layout === "auto" && (spec.type === "architecture" || spec.type === "flowchart" || spec.type === "schema"); + const given = React.useMemo(() => (spec.placement ? (Array.isArray(spec.placement) ? spec.placement : [spec.placement]) : []), [spec.placement]); + const [loaded, setLoaded] = React.useState(null); + // What placement reads (the cards, their groups and the lines, by id): new cards are placed afresh. The answer for the old ones, loaded or still in + // flight, is dropped (P-R1 of the code re-check), so a card added while elk runs is never left without a cell. Other props (words, a legend) do not count. + const placedFrom = React.useMemo(() => (auto ? JSON.stringify([spec.type, (spec.type === "schema" ? spec.tables?.map((t) => [t.name, t.columns?.map((c) => c.references ?? "")]) : spec.nodes?.map((n) => [n.id, (n as { group?: string }).group])), spec.edges?.map((e) => [e.from, e.to, e.kind]), spec.groups?.map((g) => [g.id, g.parent])]) : ""), [auto, spec.type, spec.tables, spec.nodes, spec.edges, spec.groups]); + const placing = React.useRef(null); + const placedFor = React.useRef(placedFrom); + if (placedFor.current !== placedFrom) { placedFor.current = placedFrom; placing.current = null; if (loaded) setLoaded(null); } + // A figure that unmounts drops an answer still in flight. + React.useEffect(() => () => { placing.current = null; }, []); + const placements = React.useMemo(() => (given.length ? given : loaded ?? []), [given, loaded]); + const order = React.useMemo>(() => (spec.direction ? [spec.direction] : spec.type === "flowchart" ? ["down", "right"] : ["right", "down"]), [spec.direction, spec.type]); + const [dirAt, setDirAt] = React.useState(0); + // The reasons last warned when no direction draws (DECISIONS 322, rule 5): a new width with the same reasons is not a new warning. + const autoWarned = React.useRef(null); + // The errors this figure has reported, so each is said once for it. + const errored = React.useRef | null>(null); + const errorOnce = React.useCallback((message: string) => { + errored.current ??= new Set(); + if (errored.current.has(message)) return; + errored.current.add(message); + console.error(`Basalt ${component}: ${message}`); + }, [component]); + // The viewer's figure takes the placements this figure has (DECISIONS 306, 8.4: elk runs once a direction), loaded ones included (DECISIONS 322). + const viewerSpec = React.useMemo(() => (auto && !given.length && loaded ? { ...spec, placement: loaded } : spec), [auto, given, loaded, spec]); + const placementFor = React.useCallback((k: number) => placements.find((p) => p.direction === order[k]), [placements, order]); + const model = React.useMemo(() => buildModel(spec, { checks: process.env.NODE_ENV !== "production", rtl, placement: auto ? placementFor(dirAt) : undefined }), [spec, rtl, auto, placementFor, dirAt]); const animated = model.motion.animated; const figRef = React.useRef(null); // The figure's own ref, which measuring reads, and the caller's, both set: a caller's ref never replaces the figure's. @@ -103,7 +174,10 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin else if (callerRef) callerRef.current = el; }, [callerRef]); const [dyn, setDyn] = React.useState({}); - const [ink, setInk] = React.useState(""); + // A text figure's block holds its transcript before script (and on the server), its art once script finds it fits (1.2). + const transcriptHtml = React.useMemo(() => (model.text ? transcript(P, model).map((v) => toHtml(v)).join("") : ""), [model]); + const [ink, setInk] = React.useState(() => transcriptHtml); + const [textModule, setTextModule] = React.useState(null); const inkHtml = React.useMemo(() => ({ __html: ink }), [ink]); const measured = React.useRef(null); const dynRef = React.useRef(dyn); @@ -121,28 +195,132 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin modelRef.current = model; const [focusTrace, setFocusTrace] = React.useState(null); const [hoverTrace, setHoverTrace] = React.useState(null); + // A trace on touch (DECISIONS 306, 1.5), the third source after keyboard focus. "On touch" is the media's, or a figure that has taken a touch tap. + const [touchTrace, setTouchTrace] = React.useState(null); + const [touched, setTouched] = React.useState(false); // On whether there is a source, not the node itself: a parent's render makes a new node each time, which would measure the figure again on every render. + // The viewer's keys likewise, by the value the tree reads. const hasSource = source !== undefined && source !== null; - const options = React.useMemo(() => ({ prefix: P, base, level, hasSource, hiddenClass: "basalt-visually-hidden" }), [base, level, hasSource]); + const viewerKeys = viewer?.keys; + const options = React.useMemo(() => ({ prefix: P, base, level, hasSource, hiddenClass: "basalt-visually-hidden", viewer: viewerKeys }), [base, level, hasSource, viewerKeys]); // 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]); + // 5.1's first list is an error (the decider's ruling 1): console.error, once for this figure and the message; the figure is drawn as production draws it. + if (process.env.NODE_ENV !== "production") for (const e of model.errors) errorOnce(e); + if (process.env.NODE_ENV !== "production" && model.motion.firstVisit && !props.id) errorOnce('entrance="first-visit" needs an id: without one the entrance plays on every visit'); + }, [model, component, props.id]); const measure = React.useCallback(() => { const fig = figRef.current; if (!fig) return; - 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); + const dirRtl = getComputedStyle(fig).direction === "rtl"; + if (dirRtl !== rtl) { setRtl(dirRtl); return; } + // An automatic figure with no placement loads the layout module once it is measured at 640 or wider (never at a phone's width); until it answers, and + // if it fails, the figure is stacked with every word present. elk runs once a direction: a resize or the faces arriving never run it again. + // The viewer's figure is laid out at its least drawn width whatever the window (9.3), so on a phone it loads the module the page's stacked figure did not. + // One placement in flight a figure (P5 of the code review): a resize or the faces arriving while it runs do not start another, and an answer for a figure + // that has gone is dropped. + if (auto && !given.length && !loaded && !placing.current && (viewer || fig.clientWidth >= 640)) { + const input = { type: spec.type as "architecture" | "flowchart" | "schema", nodes: spec.nodes as Array<{ id: string; group?: string }>, tables: spec.tables, edges: spec.edges, groups: spec.groups }; + const ask = placedFrom; + placing.current = ask; + loadLayout().then((mod) => Promise.all(order.map((d) => mod.placeDiagram(input, d)))).then((all) => { if (placing.current === ask) { placing.current = null; setLoaded(all); } }, (error: unknown) => { + if (placing.current === ask) placing.current = null; + if (process.env.NODE_ENV !== "production") warnOnce(component, `the automatic layout could not load (${String(error)}), so the figure is stacked`); + }); + } + // The direction: the first, in order, whose drawn layout fits at this width (each placement measured as it would be drawn); none fits, the first, stacked. + if (auto && placements.length > 1 && !viewer) { + let pick = 0, drew = false, fitsByWidth = false; + // What an author sees when no direction draws (DECISIONS 322, rule 5): one warning that gives each direction's reason, where at least one direction + // had the width it needs. A figure that is only too narrow for both says nothing, as an authored figure does. + const why: string[] = []; + for (let k = 0; k < order.length; k++) { + const place = placementFor(k); + if (!place) continue; + const trial = buildModel(spec, { rtl, placement: place }); + const said: string[] = []; + const t = measureFigure(fig, trial, P, base, {}, (d) => syncAttributes(fig, figureTree(trial, d, options)), process.env.NODE_ENV !== "production" ? (w) => said.push(w) : undefined); + if (t.dyn.layout === "drawn") { pick = k; drew = true; break; } + if (process.env.NODE_ENV !== "production") { + const reasons = said.filter((w) => w.startsWith("the drawn layout does not fit")).map((w) => w.replace(/^the drawn layout does not fit at \d+px: /, "")); + if (reasons.length) fitsByWidth = true; + why.push(`laid ${order[k]} ${reasons.length ? reasons.join("; ") : `it needs ${Math.ceil(t.least ?? 0)}px`}`); + } + } + if (process.env.NODE_ENV !== "production" && !drew && fitsByWidth) { + const reasons = why.join("; ").replace(/\d+px/g, ""); + if (autoWarned.current !== reasons) { + autoWarned.current = reasons; + console.warn(`Basalt ${component}: layout="auto" draws in neither direction at ${Math.round(fig.clientWidth)}px, so the figure is stacked: ${why.join("; ")}. Name a side on a line named here (fromSide, toSide), shorten a label named here, or write the figure authored: placeDiagram returns every cell to start from`); + } + } + if (pick !== dirAt) { setDirAt(pick); return; } + } + // In the viewer, an automatic figure with no named direction takes the direction with the larger Fit in this stage; a tie keeps the type's own (9.3). + if (auto && placements.length > 1 && viewer && !spec.direction) { + const room = viewer.room(); + let pick = 0, best = -1; + for (let k = 0; k < order.length; k++) { + const place = placementFor(k); + if (!place) continue; + const trial = buildModel(spec, { rtl, placement: place }); + const t = viewer.measure(fig, trial, P, base, {}, (d) => syncAttributes(fig, figureTree(trial, d, options))); + if (t.dyn.layout !== "drawn") continue; + // Fit as the viewer takes it (whole per cents, 200% at most), so two directions that both fit at 200% tie and the type's own stays. + const fit = Math.min(2, Math.floor(Math.min(room.w / fig.offsetWidth, room.h / fig.offsetHeight) * 100 + 1e-6) / 100); + if (fit > best + 1e-6) { best = fit; pick = k; } + } + if (pick !== dirAt) { setDirAt(pick); return; } + } + const warn = process.env.NODE_ENV !== "production" ? (message: string, level?: "error") => (level === "error" ? errorOnce(message) : warnOnce(component, message)) : undefined; + const apply = (d: Dyn) => syncAttributes(fig, figureTree(model, d, options)); + const result = (viewer ? viewer.measure : measureFigure)(fig, model, P, base, dynRef.current, apply, warn); + // The text variant (1.2): the art where its widest line fits the block, the transcript otherwise; the art's module loads the first time. + if (model.text) { + const pre = fig.querySelector(`.${P}-text`); + if (!textModule) { void loadText().then((mod) => setTextModule(() => mod), () => {}); } + let html = transcriptHtml, art = false; + if (pre && textModule) { + const made = textModule.textArt(model); + // A glyph's width at 100%: offsetWidth, which no transform scales (the viewer's layer is zoomed when this runs), on one unbreakable run. + const probe = document.createElement("span"); + probe.style.cssText = "display:inline-block;white-space:pre"; + probe.textContent = "─".repeat(40); + pre.append(probe); + const cw = probe.offsetWidth / 40; + probe.remove(); + const cs = getComputedStyle(pre); + let room = pre.clientWidth - Number.parseFloat(cs.paddingLeft) - Number.parseFloat(cs.paddingRight); + // In the viewer the art is held at its own width, never the transcript (9.3): the layer takes the width the widest line needs. + if (viewer?.textWidth) { + viewer.textWidth(made.width * cw + (fig.clientWidth - room) + 1); + room = pre.clientWidth - Number.parseFloat(cs.paddingLeft) - Number.parseFloat(cs.paddingRight); + } + if (made.width * cw <= room + 0.5) { html = made.html; art = true; } + } + result.dyn = { ...result.dyn, art: art || undefined }; + result.ink = html; + } measured.current = result; // The same layout is the same state: a measure that changes nothing renders nothing. // (A layout is plain data that the engine builds in one order, so its text is a fair test.) if (JSON.stringify(dynRef.current) !== JSON.stringify(result.dyn)) { 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]); + if (!hasStops(model, result.dyn)) { setHoverTrace(null); setTouchTrace(null); } + // A figure hidden (the viewer's list is open) was not measured: the viewer keeps the drawing's size and place it had. A text figure's art is in the DOM + // only once React has written it, so its size is read after that (below). + if (viewer && result.tokens && !model.text) viewer.onMeasured(result, fig); + }, [model, base, options, component, viewer, rtl, auto, given, loaded, placements, order, placementFor, dirAt, spec, textModule, transcriptHtml, placedFrom, errorOnce]); + + // The viewer's text figure (9.3): its size is read once React has written the art it measured, so the zoom fits the art and not the transcript. + React.useLayoutEffect(() => { + const fig = figRef.current; + if (viewer && model.text && fig && measured.current?.tokens) viewer.onMeasured(measured.current, fig); + }, [viewer, model, ink]); // Measured before the first paint, then whenever the figure's width changes or the real faces arrive. React.useLayoutEffect(() => { @@ -167,7 +345,9 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin return () => { live = false; observer.disconnect(); cancelAnimationFrame(frame); if (marks) forced.removeEventListener("change", measure); }; }, [measure, model]); - const trace = focusTrace ?? hoverTrace; + // An animated text figure builds by ink (1.2) as a drawn figure's entrance plays: the motion module plays it when it comes into view, settles it as it + // settles any entrance, and keeps the first visit's mark (below, its art counts as its lines). + const trace = focusTrace ?? touchTrace ?? hoverTrace; React.useLayoutEffect(() => { const fig = figRef.current; if (fig) applyTrace(fig, P, measured.current?.geo ?? null, measured.current?.tokens ?? null, base, trace); @@ -175,7 +355,7 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin // In the frame an animated figure's lines are first drawn it is marked pending, before any paint (DECISIONS 292, 1.5); the module, once loaded, // follows the lines each time they are drawn again. What it follows is the drawing itself, not the string: if React wrote the ink again for any reason // (a remount, the faces arriving with the same lines), the reveal and the loops are built again on the new elements. - const drawn = React.useRef<{ svg: Element | null; controller: MotionController | null } | null>(null); + const drawn = React.useRef<{ svg: Element | null; art: Element | null; controller: MotionController | null } | null>(null); // The motion code failed to load. A figure hidden when it failed (inside a closed disclosure, an unselected tab) had no lines and no entrance to settle // then: the lines it draws when it is shown are settled in the frame they are drawn, so they are never left pending. const motionFailed = React.useRef(false); @@ -183,9 +363,11 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin const fig = figRef.current; if (!fig || !animated || !measured.current?.tokens) return; const svg = fig.querySelector(`.${P}-ink > .${P}-svg`); - if (drawn.current && drawn.current.svg === svg && drawn.current.controller === controller) return; - drawn.current = { svg, controller }; - entranceDrawn(fig, Boolean(measured.current.geo?.lines.length)); + // A text sequence's art is its lines (1.2): the build waits for it, as an entrance waits for drawn lines. + const art = model.text ? fig.querySelector(`.${P}-text[data-art]`) : null; + if (drawn.current && drawn.current.svg === svg && drawn.current.art === art && drawn.current.controller === controller) return; + drawn.current = { svg, art, controller }; + entranceDrawn(fig, Boolean(measured.current.geo?.lines.length) || Boolean(art)); if (motionFailed.current) settleEntrance(fig); controller?.redrawn(); }); @@ -215,6 +397,35 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin React.useEffect(() => { controller?.sendValue(sendValue); }, [sendValue, controller]); const settle = () => { if (animated && figRef.current) settleEntrance(figRef.current); }; + // The viewer (DECISIONS 310): "Expand" exists once script runs. Its module loads at the button's first hover, focus or touch; a press before it has + // arrived makes the button busy until the dialog opens. While the viewer is open the page's figure holds its loops and settles a running entrance (9.7). + const [scripted, setScripted] = React.useState(false); + const [onTouch, setOnTouch] = React.useState(false); + React.useEffect(() => { if (!viewer) { setScripted(true); setOnTouch(matchMedia("(hover: none), (pointer: coarse)").matches); } }, [viewer]); + const expandRef = React.useRef(null); + const [viewerModule, setViewerModule] = React.useState(null); + const [viewerOpen, setViewerOpen] = React.useState(false); + const [opening, setOpening] = React.useState(false); + const fetchViewer = React.useCallback(() => loadViewer().then((mod) => { setViewerModule(() => mod); return mod; }, (error: unknown) => { + if (process.env.NODE_ENV !== "production") warnOnce(component, `the viewer could not load (${String(error)}); "Expand" stays and does nothing`); + return null; + }), [component]); + const preloadViewer = () => { if (!viewerModule) void fetchViewer(); }; + const openViewer = () => { + if (opening) return; + settle(); + if (viewerModule) { setViewerOpen(true); return; } + setOpening(true); + void fetchViewer().then((mod) => { setOpening(false); if (mod) setViewerOpen(true); }); + }; + const closeViewer = React.useCallback(() => setViewerOpen(false), []); + React.useLayoutEffect(() => { + const fig = figRef.current; + if (!fig || viewer) return; + fig.toggleAttribute("data-viewing", viewerOpen); + if (viewerOpen && animated) settleEntrance(fig); + }, [viewerOpen, viewer, animated]); + const nodeOf = (target: EventTarget | null) => { const el = (target as HTMLElement | null)?.closest?.(`.${P}-node`); return el && figRef.current?.contains(el) ? el : null; @@ -231,9 +442,11 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin const node = nodeOf(event.target); if (!node || event.defaultPrevented) return; settle(); - if (event.key === "Escape") { if (focusTrace || hoverTrace) { event.preventDefault(); setFocusTrace(null); setHoverTrace(null); } return; } + // In the viewer Esc always closes the dialog, traced or not (9.8): the figure leaves it to the dialog. + if (event.key === "Escape") { if (!viewer && (focusTrace || hoverTrace || touchTrace)) { event.preventDefault(); setFocusTrace(null); setHoverTrace(null); setTouchTrace(null); } return; } if (!stops) return; - const to = keyTarget(model, node.dataset.node!, event.key); + // The model is mirrored right to left, so the table is already physical. + const to = keyTarget(model, node.dataset.node!, event.key, dynRef.current.layout === "drawn"); if (!to) return; event.preventDefault(); const next = { ...dynRef.current, stop: to }; @@ -267,6 +480,17 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin setHoverTrace(node && hasStops(model, dynRef.current) ? node.dataset.node! : null); }, onPointerLeave: (event: React.PointerEvent) => { onPointerLeave?.(event); setHoverTrace(null); }, + "data-touch": !viewer && (onTouch || touched) ? "" : undefined, + onClick: (event: React.MouseEvent) => { + props.onClick?.(event as React.MouseEvent); + const fig = figRef.current; + if (!fig || event.defaultPrevented) return; + const next = tapTrace(fig, P, event.nativeEvent, touchTrace); + if (next === undefined) return; + settle(); + setTouched(true); + setTouchTrace(next); + }, }; const toggle = ( @@ -282,12 +506,47 @@ export function DiagramFigure({ spec, component, title: _title, heading: _headin {dyn.open ? "Hide the list" : "View as list"} ); - const hint = hintEntries(model).map((entry) => ( + const hint = hintEntries(model, dyn.layout === "drawn").map((entry) => ( {entry.keys.map((k, i) => {i ? " " : null}{k})} {entry.words} )); const tree = figureTree(model, dyn, options); - // The foot (1.9): "View as list", then the run button and "Pause animations", which the motion module draws when it has loaded. + // The viewer's figure shows its drawing alone: its head, key, hint and foot are the dialog's. + if (viewer) return toReact(tree, { source, summary, hint: null, toggle: null }, inkHtml, root) as React.ReactElement; + // The foot (1.9, and DECISIONS 310, 9.1): "View as list", "Expand", then the run button and "Pause animations", which the motion module draws when it has loaded. const Foot = motionModule?.MotionFoot; - const foot = Foot && controller ? <>{toggle} : toggle; + const expand = zoom && scripted ? ( + <> + + {viewerOpen && viewerModule ? ( + + ) : null} + + ) : null; + // "Clear highlight" (1.5): last in the foot, mounted whenever the figure is on touch and can be traced, aria-disabled until a trace is up. A text + // sequence (its art or its transcript) has no lines a tap traces, so it has none, as in the skill, which mounts it only for a figure drawn with lines. + const clear = !viewer && !model.text && (onTouch || touched) && ink ? ( + + ) : null; + const foot = <>{toggle}{expand}{Foot && controller ? : null}{clear}; return toReact(tree, { source, summary, hint, toggle: foot }, inkHtml, root) as React.ReactElement; } diff --git a/packages/react/src/diagram-layout-graph.ts b/packages/react/src/diagram-layout-graph.ts new file mode 100644 index 00000000..97a34df4 --- /dev/null +++ b/packages/react/src/diagram-layout-graph.ts @@ -0,0 +1,80 @@ +// The graph automatic layout hands elk (DECISIONS 306, 1.8, and the ruling, DECISIONS 322): the cards, the lines and the groups, and the one fixed set of +// options. Internal to diagram-layout: not an export of the package, so its helpers and elk's graph shape are in no public declaration. Nothing runs at load. + +import type { DiagramGroup } from "./diagram-core"; +import type { DiagramPlacementInput } from "./diagram-layout"; + +export interface ElkNode { id: string; width?: number; height?: number; x?: number; y?: number; children?: ElkNode[]; layoutOptions?: Record; edges?: Array<{ id: string; sources: string[]; targets: string[] }> } + +// Every card one box of one size (only the layer and the order are read, so the result never depends on a measured pixel), and one fixed set of options: +// layered, randomSeed 1, model order for nodes and edges, cycle breaking by model order, node placement by network simplex. Partitioning is never switched on. +// The ruling on DECISIONS 306 and 313 (automatic layout): network simplex in place of Brandes and Köpf, because it reads a line's straightness priority, and a +// main line carries one (STRAIGHT): the main path comes out as one straight run in both directions. +export const W = 200, H = 80; +const STRAIGHT = "10"; +const options = (direction: "right" | "down"): Record => ({ + "elk.algorithm": "layered", + "elk.direction": direction === "right" ? "RIGHT" : "DOWN", + "elk.randomSeed": "1", + "elk.hierarchyHandling": "INCLUDE_CHILDREN", + "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES", + "elk.layered.cycleBreaking.strategy": "MODEL_ORDER", + "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX", + "elk.layered.spacing.nodeNodeBetweenLayers": "64", + "elk.spacing.nodeNode": "48", + "elk.edgeRouting": "ORTHOGONAL", +}); + +export interface Card { id: string; group?: string; way?: boolean } +export interface Line { from: string; to: string; main: boolean; k: number } + +/** The cards and the lines a figure is placed from, in the author's order. */ +export function partsOf(input: DiagramPlacementInput): { cards: Card[]; lines: Line[]; groups: DiagramGroup[] } { + const cards: Card[] = input.type === "schema" ? (input.tables ?? []).map((t) => ({ id: String(t.name) })) : (input.nodes ?? []).map((n) => ({ id: String(n.id), group: n.group })); + const raw = input.type === "schema" + ? (input.tables ?? []).flatMap((t) => (t.columns ?? []).filter((c) => c.references).map((c) => ({ from: String(t.name), to: String(c.references).split(".")[0]!, main: false }))) + : (input.edges ?? []).map((e) => ({ from: String(e.from), to: String(e.to), main: e.kind === "main" })); + const ids = new Set(cards.map((c) => c.id)); + const lines = raw.filter((e) => ids.has(e.from) && ids.has(e.to)).map((e, k) => ({ ...e, k })); + return { cards, lines, groups: input.type === "architecture" ? input.groups ?? [] : [] }; +} + +/** + * The main line goes straight on (the ruling, rule 2): a card with three or more leaving lines, exactly one of them main, hands elk its leaving lines with + * the main one in the middle (half the others, rounded down, before it), each of the others in the author's order. Every other line keeps its place. + */ +export function mainInTheMiddle(lines: T[]): T[] { + const bySource = new Map(); + lines.forEach((e, k) => { if (!bySource.has(e.from)) bySource.set(e.from, []); bySource.get(e.from)!.push(k); }); + const out = lines.slice(); + for (const slots of bySource.values()) { + const main = slots.filter((k) => lines[k]!.main); + if (slots.length < 3 || main.length !== 1) continue; + const rest = slots.filter((k) => k !== main[0]); + const order = [...rest.slice(0, Math.floor(rest.length / 2)), main[0]!, ...rest.slice(Math.floor(rest.length / 2))]; + slots.forEach((slot, j) => { out[slot] = lines[order[j]!]!; }); + } + return out; +} + +/** The graph handed to elk: cards in the author's order (a way's boxes before the card its line ends on), groups as hierarchy, lines as ordered above. */ +export function graphOf(cards: Card[], lines: Line[], groups: DiagramGroup[], direction: "right" | "down"): ElkNode { + const kids = new Map([["", []]]); + for (const g of groups) kids.set(g.id, []); + for (const c of cards) (kids.get(c.group ?? "") ?? kids.get("")!).push({ id: c.id, width: W, height: H }); + const children = [...kids.get("")!]; + // A group goes into its parent unless its chain of parents comes back to it (a cycle, the engine's development error): then it is a group of the root, + // so elk is never handed a hierarchy that holds itself (Neon's P2 of the code review). + const cycles = (g: DiagramGroup) => { const seen = new Set([g.id]); for (let p = g.parent; p; p = groups.find((x) => x.id === p)?.parent) { if (seen.has(p)) return true; seen.add(p); } return false; }; + for (const g of groups) { + const box: ElkNode = { id: `group:${g.id}`, children: kids.get(g.id), layoutOptions: { "elk.padding": "[top=32,left=16,bottom=16,right=16]" } }; + (g.parent && kids.has(g.parent) && !cycles(g) ? kids.get(g.parent)! : children).push(box); + } + return { id: "root", layoutOptions: options(direction), children, edges: lines.map((e, k) => ({ id: `e${k}`, sources: [e.from], targets: [e.to], ...(e.main ? { layoutOptions: { "elk.layered.priority.straightness": STRAIGHT } } : {}) })) }; +} + +/** The graph of the first run, as the first decision's tests read it. */ +export function elkGraph(input: DiagramPlacementInput, direction: "right" | "down"): ElkNode { + const { cards, lines, groups } = partsOf(input); + return graphOf(cards, mainInTheMiddle(lines), groups, direction); +} diff --git a/packages/react/src/diagram-layout.ts b/packages/react/src/diagram-layout.ts new file mode 100644 index 00000000..7a126c7b --- /dev/null +++ b/packages/react/src/diagram-layout.ts @@ -0,0 +1,121 @@ +// Automatic layout (DECISIONS 306, 1.8): `@srasyndicate/basalt/diagram-layout`, the one module that imports elkjs (EPL-2.0 OR GPL-3.0-or-later, used under +// EPL-2.0, unmodified). It gives each card a column and a row and nothing else: elk's routes, ports and group boxes are never read, and Basalt sizes, +// routes, seats and stacks the figure as it does an authored one. Lead with build time: an app or page that places at build time (and passes `placement`) +// ships none of elkjs. A figure without `placement` loads this module on demand, at 640 or wider, and never at a phone's width. Nothing runs at load. + +import type { DiagramEdge, DiagramGroup, DiagramPlacement, SchemaTable } from "./diagram-core"; +import { graphOf, H, mainInTheMiddle, partsOf, W } from "./diagram-layout-graph"; +import type { Card, ElkNode, Line } from "./diagram-layout-graph"; + +/** What a figure is placed from: its type and the component's own props (cards, lines, groups). */ +export interface DiagramPlacementInput { + type: "architecture" | "flowchart" | "schema"; + nodes?: Array<{ id: string; group?: string }>; + tables?: SchemaTable[]; + edges?: DiagramEdge[]; + groups?: DiagramGroup[]; +} + + +/** Cards' boxes, absolute, from elk's result (a child's place is its parent's plus its own). */ +function absolute(node: ElkNode, ox = 0, oy = 0, out = new Map()) { + for (const c of node.children ?? []) { + const x = ox + (c.x ?? 0), y = oy + (c.y ?? 0); + if (c.children) absolute(c, x, y, out); else out.set(c.id, { x, y, w: c.width ?? W, h: c.height ?? H }); + } + return out; +} +/** Bands along one axis: cards sorted by where they start; a card starts a new band when it begins at or after the band's earliest end. */ +function bands(rects: Map, lo: (r: { x: number; y: number; w: number; h: number }) => number, hi: (r: { x: number; y: number; w: number; h: number }) => number) { + const ids = [...rects.keys()].sort((a, b) => lo(rects.get(a)!) - lo(rects.get(b)!) || (a < b ? -1 : a > b ? 1 : 0)); + const out = new Map(); + let band = 0, end = Infinity; + for (const id of ids) { + const r = rects.get(id)!; + if (lo(r) >= end - 0.5) { band++; end = Infinity; } + end = Math.min(end, hi(r)); + out.set(id, band + 1); + } + return out; +} + +type Cells = Record; +let elkMade: { layout: (graph: ElkNode) => Promise } | undefined; +async function cellsOf(graph: ElkNode): Promise { + if (!elkMade) { + const mod = (await import("./diagram-elk")) as unknown as { default: new () => { layout: (graph: ElkNode) => Promise } }; + elkMade = new mod.default(); + } + const rects = absolute(await elkMade.layout(graph)); + const col = bands(rects, (r) => r.x, (r) => r.x + r.w), row = bands(rects, (r) => r.y, (r) => r.y + r.h); + const cells: Cells = {}; + for (const id of rects.keys()) cells[id] = { col: col.get(id)!, row: row.get(id)! }; + return cells; +} + +/** A placement that cannot be used (1.8, 8.5): two cards in one cell, or a card inside the box of a group it is not in. */ +function unusable(cards: Card[], groups: DiagramGroup[], cells: Cells): boolean { + const seen = new Set(); + for (const c of cards) { const at = cells[c.id]; if (!at) return true; const key = `${at.col},${at.row}`; if (seen.has(key)) return true; seen.add(key); } + // A group's chain, outermost last; a parent named twice (a cycle) ends it (Neon's P2 of the code review). + const chain = (id?: string) => { const out: string[] = []; for (let g = id; g && !out.includes(g); g = groups.find((x) => x.id === g)?.parent) out.push(g); return out; }; + for (const g of groups) { + const mine = cards.filter((c) => chain(c.group).includes(g.id)); + if (!mine.length) continue; + const at = mine.map((c) => cells[c.id]!); + const box = { c1: Math.min(...at.map((a) => a.col)), c2: Math.max(...at.map((a) => a.col)), r1: Math.min(...at.map((a) => a.row)), r2: Math.max(...at.map((a) => a.row)) }; + if (cards.some((c) => !mine.includes(c) && cells[c.id]!.col >= box.c1 && cells[c.id]!.col <= box.c2 && cells[c.id]!.row >= box.r1 && cells[c.id]!.row <= box.r2)) return true; + } + return false; +} + +/** + * Places a figure in one direction: each card's column and row. The same answer in Node and in a browser. + * + * Two runs where a main line skips a layer (the ruling, rule 1). The first run gives every card its layer (its row laid down, its column laid right). A main + * line whose ends are two or more layers apart is then handed to elk as a chain through one box of a card's size in each layer it passes (its way), each box in + * a group by the rule below, and elk runs again. The way's boxes are read with the cards and then left out: their cells stay empty, so the main + * line has a way no card stands in. If the second run cannot be used or adds a layer, the first is. + */ +export async function placeDiagram(input: DiagramPlacementInput, direction: "right" | "down"): Promise { + const { cards, lines: authored, groups } = partsOf(input); + const lines = mainInTheMiddle(authored); + const first = await cellsOf(graphOf(cards, lines, groups, direction)); + const layer = (id: string) => (direction === "down" ? first[id]!.row : first[id]!.col); + // A group's chain, outermost last; a parent named twice (a cycle) ends it (Neon's P2 of the code review). + const chain = (id?: string) => { const out: string[] = []; for (let g = id; g && !out.includes(g); g = groups.find((x) => x.id === g)?.parent) out.push(g); return out; }; + const groupOf = new Map(cards.map((c) => [c.id, c.group])); + const all = cards.slice(); + const chained: Line[] = []; + let ways = 0; + for (const e of lines) { + const a = layer(e.from), b = layer(e.to); + if (!e.main || Math.abs(b - a) < 2) { chained.push(e); continue; } + const inA = chain(groupOf.get(e.from)), inB = chain(groupOf.get(e.to)); + const both = inA.find((g) => inB.includes(g)); + const boxes: Card[] = []; + let prev = e.from; + for (let l = a + Math.sign(b - a); l !== b; l += Math.sign(b - a)) { + const id = `way:${e.k}:${l}`; + // The box's group: the innermost group that holds either end and has a card in this layer (the target's side first), so the box stands beside the + // cards the line passes; with none, the innermost group that holds both ends, or no group. + const here = new Set(cards.filter((c) => layer(c.id) === l).flatMap((c) => chain(c.group))); + const group = inB.find((g) => here.has(g)) ?? inA.find((g) => here.has(g)) ?? both; + boxes.push({ id, group, way: true }); + chained.push({ ...e, from: prev, to: id }); + prev = id; + } + chained.push({ ...e, from: prev }); + all.splice(all.findIndex((c) => c.id === e.to), 0, ...boxes); + ways++; + } + const span = (c: Cells) => ({ cols: Math.max(1, ...Object.values(c).map((x) => x.col)), rows: Math.max(1, ...Object.values(c).map((x) => x.row)) }); + if (!ways) return { direction, ...span(first), cells: first }; + const second = await cellsOf(graphOf(all, chained, groups, direction)); + const cells: Cells = {}; + for (const c of cards) cells[c.id] = second[c.id]!; + // The second run stands only if it can be used and has no more layers than the first: a way fills layers that exist and never adds one. + const layers = (c: Cells) => Math.max(1, ...cards.map((x) => (direction === "down" ? c[x.id]!.row : c[x.id]!.col))); + // The tracks are counted over the cards and the ways together (`cols`, `rows`), so a track that holds only a way is still a track. + return unusable(cards, groups, cells) || layers(cells) > layers(first) ? { direction, ...span(first), cells: first } : { direction, ...span(second), cells }; +} diff --git a/packages/react/src/diagram-motion-core.ts b/packages/react/src/diagram-motion-core.ts index 360b3d1d..f523a38b 100644 --- a/packages/react/src/diagram-motion-core.ts +++ b/packages/react/src/diagram-motion-core.ts @@ -7,7 +7,7 @@ // This module plays that entrance when the figure comes into view, carries it across a re-measure on its one clock, settles it at once when the reader // acts or a mode turns on, and then runs the loops the data names while they may run. Every value is a token, read from the page. -import { entranceBlocked, pathD, settleEntrance } from "./diagram-core"; +import { entranceBlocked, pathD, settleEntrance, visitKey } from "./diagram-core"; import type { Geo, GLine, Model, Pt, Tokens } from "./diagram-core"; declare const process: { env: { NODE_ENV?: string } }; @@ -75,7 +75,7 @@ function join(fig: Figure): Page { } page.figs.add(fig); if (fig.drawing) page.io.observe(fig.drawing); - page.mo.observe(fig.host.fig, { attributes: true, attributeFilter: ["data-tracing"] }); + page.mo.observe(fig.host.fig, { attributes: true, attributeFilter: ["data-tracing", "data-viewing"] }); return page; } @@ -246,8 +246,20 @@ class Figure implements MotionController { }; } private entrance() { return this.host.fig.getAttribute("data-entrance"); } - private hasLines() { return Boolean(this.host.geo()?.lines.length); } - private traced() { return this.host.fig.hasAttribute("data-tracing"); } + /** The entrance ran on this visit (so a settle by the reader writes the first visit's mark). */ + private played = false; + private byMode() { const m = this.modes(); return m.held || m.print || m.reduce || m.forced; } + /** Writes the first visit's mark, where the figure asks for it (1.5). Storage that throws writes nothing: the entrance plays again next time. */ + private markVisit() { + const fig = this.host.fig; + if (!fig.hasAttribute("data-first-visit") || !fig.id) return; + try { localStorage.setItem(visitKey(fig), "1"); } catch { /* it plays again */ } + } + /** A text sequence's art, where it is shown (DECISIONS 306, 1.2): its build by ink and its run are this module's, as the drawn sequence's are. */ + private textCode(): HTMLElement | null { return this.host.model().text ? this.host.fig.querySelector(`.${this.host.P}-text[data-art] .${this.host.P}-text-ink`) : null; } + private hasLines() { return Boolean(this.host.geo()?.lines.length) || Boolean(this.textCode()); } + // A figure whose viewer is open holds its loops as a traced one does (DECISIONS 310, 9.7), and they start again when it closes. + private traced() { return this.host.fig.hasAttribute("data-tracing") || this.host.fig.hasAttribute("data-viewing"); } seen(entry: IntersectionObserverEntry) { this.inView = entry.isIntersecting; @@ -298,7 +310,9 @@ class Figure implements MotionController { // ---- The entrance (1.3 to 1.5) ---- private onSettle = () => { - // settleEntrance has already set data-entrance="done": every line whole, every label at rest, and then the loops may start. + // settleEntrance has already set data-entrance="done": every line whole, every label at rest, and then the loops may start. An entrance that played + // and gave way to the reader marks the first visit (1.5); one settled by a mode (the hold, print, reduced motion) does not. + if (this.played && !this.byMode()) this.markVisit(); this.clearIntro(); this.sync(); }; @@ -338,9 +352,11 @@ class Figure implements MotionController { private lineEl(l: GLine) { return this.host.fig.querySelector(`.${this.host.P}-edge[data-edge="${l.i}"]`); } private play() { + if (this.textCode()) { this.playText(); return; } const geo = this.host.geo(); if (!geo?.lines.length) return; this.host.fig.setAttribute("data-entrance", "running"); + this.played = true; this.t0 = now(); const { plans, factor } = this.plan(this.ordered(geo)); this.factor = factor; @@ -400,6 +416,15 @@ class Figure implements MotionController { const copy = svgEl("circle", { cx: dot.getAttribute("cx") ?? 0, cy: dot.getAttribute("cy") ?? 0, r: Number(dot.getAttribute("r") ?? 3) + 1, fill: "#fff" }, mask); clocked(copy.animate([{ opacity: 0 }, { opacity: 1 }], { duration: t.fast, delay: plan.start, easing: t.out, fill: "both" })); } + // Cardinality marks (DECISIONS 306, 1.1): the foreign-key end's fade in as the dot does, the referenced end's as a head does. + g.querySelectorAll(`.${P}-crow, .${P}-ring`).forEach((mark) => { + const ring = mark.tagName.toLowerCase() === "circle"; + const copy = ring + ? svgEl("circle", { cx: mark.getAttribute("cx") ?? 0, cy: mark.getAttribute("cy") ?? 0, r: Number(mark.getAttribute("r") ?? 3) + 1, fill: "#fff" }, mask) + : svgEl("path", { d: mark.getAttribute("d") ?? "", fill: "none", stroke: "#fff", "stroke-width": 3 }, mask); + const from = mark.getAttribute("data-end") === "from"; + clocked(copy.animate([{ opacity: 0 }, { opacity: 1 }], from ? { duration: t.fast, delay: plan.start, easing: t.out, fill: "both" } : { duration: t.slow, delay: plan.start + 0.85 * plan.dur, easing: t.out, fill: "both" })); + }); g.setAttribute("mask", `url(#${id})`); } // A sequence's labels are drawn in secondary ink before their turn and lift to primary over duration-slower (1.4). Built once, on the clock. @@ -421,11 +446,44 @@ class Figure implements MotionController { private finishIntro() { if (this.entrance() !== "running") return; + this.markVisit(); this.host.fig.setAttribute("data-entrance", "done"); this.clearIntro(); this.sync(); } + /** + * A text sequence builds by ink (1.2), when it comes into view as a drawn figure's entrance does, on the same clock and with the same settling, first visit + * and limit: before its turn a message's label is secondary and its arrow tertiary, and at its turn both lift to their resting ink over duration-slower, + * messages duration-diagram-step apart inside duration-diagram-limit. No line is hidden and there is no caret. + */ + private playText() { + const code = this.textCode(); + if (!code) return; + const fig = this.host.fig, t = this.t; + fig.setAttribute("data-entrance", "running"); + this.played = true; + this.t0 = now(); + const lines = [...code.querySelectorAll("[data-n]")]; + const count = Math.max(0, ...lines.map((l) => Number(l.dataset.n))); + const gap = count > 1 ? Math.min(t.step, (t.limit - t.slower) / (count - 1)) : 0; + const cs = getComputedStyle(fig); + const secondary = cs.getPropertyValue("--basalt-text-secondary").trim(), tertiary = cs.getPropertyValue("--basalt-text-tertiary").trim(); + for (const line of lines) { + const n = Number(line.dataset.n); + line.querySelectorAll('[data-ink="label"], [data-ink="main"], [data-ink="plain"]').forEach((el) => { + const before = el.dataset.ink === "label" ? secondary : tertiary; + const a = el.animate([{ color: before }, { color: before, offset: 0.001 }, { color: getComputedStyle(el).color }], { duration: t.slower, delay: (n - 1) * gap, easing: "ease-out", fill: "backwards" }); + a.startTime = this.t0; + this.intro.add(a); + }); + } + this.introEnd?.cancel(); + this.introEnd = fig.animate([], { duration: Math.max(1, (count - 1) * gap + t.slower) }); + this.introEnd.startTime = this.t0; + this.introEnd.finished.then(() => this.finishIntro(), () => {}); + } + private clearIntro() { for (const a of [...this.intro, ...this.labels]) a.cancel(); this.intro.clear(); @@ -442,7 +500,9 @@ class Figure implements MotionController { const state = this.entrance(); if (state === "running") { const geo = this.host.geo(); - if (!geo?.lines.length) { + if (this.textCode()) { + // A text sequence's build carries on: its art is the same rows, written again. + } else if (!geo?.lines.length) { // Narrowed to a layout with no lines: at rest, with no control (1.5). this.clearIntro(); this.host.fig.setAttribute("data-entrance", "done"); @@ -573,6 +633,16 @@ class Figure implements MotionController { const l = geo.lines.find((x) => x.i === i); if (!l) return; const tk = this.host.tokens(); + // A dashed line's own dashes march toward the head (DECISIONS 306, 1.5): one period (its 6 on 4 off, 10px) at speed-diagram-flow on ease-linear. + // Its open head does not move, and still it is the line the key draws. The 48px rule holds as for cuts. + if (l.kind === "dashed") { + if (this.visible(l, trimmed(l, tk?.head ?? 8)) < 48) return; + const line = this.host.fig.querySelector(`.${this.host.P}-edge[data-edge="${i}"] .${this.host.P}-line`); + if (!line) return; + const period = (tk?.dash ?? 6) + (tk?.dashGap ?? 4); + this.track(line.animate([{ strokeDashoffset: "0px" }, { strokeDashoffset: `${-period}px` }], { duration: (period / this.t.flow) * 1000, iterations: Infinity, easing: "linear" }), this.loops); + return; + } let made = this.flowEls.get(i); // An overlay lives in the ink: one the host wrote over is made again. if (made && !made.isConnected) { this.flowEls.delete(i); made = undefined; } @@ -769,9 +839,24 @@ class Figure implements MotionController { this.publish(); }; + /** + * A run's unreached messages are quiet (DECISIONS 306, 1.2): every message after the current one has its label in secondary ink and its line and head in + * diagram-edge-dim; its number and note are unchanged. -1 restores them all at once. + */ + private quiet(current: number, lines: GLine[]) { + const P = this.host.P, fig = this.host.fig; + const msgs = fig.querySelectorAll(`.${P}-msg`); + lines.forEach((l, k) => { + const ahead = current >= 0 && k > current; + msgs[k]?.toggleAttribute("data-ahead", ahead); + fig.querySelector(`.${P}-edge[data-edge="${l.i}"]`)?.toggleAttribute("data-ahead", ahead); + }); + } + private stopRun() { this.runGen++; this.runAt = -1; + this.host.fig.querySelectorAll("[data-ahead]").forEach((el) => el.removeAttribute("data-ahead")); for (const a of this.runAnims) a.cancel(); this.runAnims.clear(); if (this.dot && this.dotOwner === "run") { this.dot.style.display = "none"; this.dotOwner = null; } @@ -782,6 +867,7 @@ class Figure implements MotionController { /** The run: a packet through every message in order, each arrow a leg; at each arrival the number lifts and the receiver's head steps (1.10). */ private playRun(from: number) { + if (this.textCode()) { this.playTextRun(from); return; } const geo = this.host.geo(); if (!geo?.lines.length) return; for (const a of this.runAnims) a.cancel(); @@ -795,6 +881,7 @@ class Figure implements MotionController { for (let k = from; k < lines.length; k++) { if (!live()) return; this.runAt = k; + this.quiet(k, lines); const l = lines[k]!; const stops = [msgs[k] ?? null, this.node(l.to)]; if (matchMedia("(prefers-reduced-motion: reduce)").matches) { @@ -808,7 +895,39 @@ class Figure implements MotionController { for (const s of stops) this.depart(s); } else await this.leg(l, this.runAnims, live, stops); } - if (live()) { this.runAt = -1; this.publish(); } + if (live()) { this.runAt = -1; this.quiet(-1, lines); this.publish(); } + }; + go().catch((e) => { if (!aborted(e)) throw e; }); + } + + /** + * A text sequence's run (Neon's B6 of the code review): the colour-only run reduced motion already has, with the quiet. Each message in turn is current: + * its number lifts to primary, and every message after it is quiet (its label secondary, its arrow tertiary) until the run reaches it. + */ + private playTextRun(from: number) { + const code = this.textCode(); + if (!code) return; + for (const a of this.runAnims) a.cancel(); + this.runAnims.clear(); + const gen = ++this.runGen; + const live = () => gen === this.runGen; + const lines = [...code.querySelectorAll("[data-n]")]; + const count = Math.max(0, ...lines.map((l) => Number(l.dataset.n))); + const quiet = (current: number) => { for (const l of lines) l.toggleAttribute("data-ahead", current >= 0 && Number(l.dataset.n) > current); }; + this.runAt = from; + const go = async () => { + for (let k = from; k < count; k++) { + if (!live()) return; + this.runAt = k; + quiet(k + 1); + const these = lines.filter((l) => Number(l.dataset.n) === k + 1); + await this.wait(this.t.legMin + this.t.base, this.runAnims); + if (!live()) return; + for (const l of these) l.setAttribute("data-arrival", ""); + await this.wait(this.t.rest, this.runAnims); + for (const l of these) l.removeAttribute("data-arrival"); + } + if (live()) { this.runAt = -1; quiet(-1); this.publish(); } }; go().catch((e) => { if (!aborted(e)) throw e; }); } @@ -816,7 +935,7 @@ class Figure implements MotionController { /** * What a development build throws on (DECISIONS 292, 4.1): an id in the pulse or the packet's path that no node has, two neighbouring ids no line joins in - * that direction, both a pulse and a packet, flow on a dashed line, and flow on a line of the mover's route. And what it warns on: a flow line with no + * that direction, both a pulse and a packet, and flow on a line of the mover's route (flow on a dashed line marches its own dashes, DECISIONS 306, 1.5). And what it warns on: a flow line with no * label. Here, and not in the still engine, because only an animated figure reads them. */ export function motionErrors(m: Model): { errors: string[]; warnings: string[] } { @@ -839,7 +958,6 @@ export function motionErrors(m: Model): { errors: string[]; warnings: string[] } } for (const e of m.edges) { if (!e.flow) continue; - if (e.kind === "dashed") errors.push(`the line from ${e.from} to ${e.to} is dashed and flows: flow is on a main or plain line only`); if (onPath.has(e.i)) errors.push(`the line from ${e.from} to ${e.to} flows and is on the ${what}'s route: flow never runs on a line the mover travels`); if (!e.label) warnings.push(`the line from ${e.from} to ${e.to} flows but has no label: motion never carries a fact alone, so its label says it is a stream`); } diff --git a/packages/react/src/diagram-text.ts b/packages/react/src/diagram-text.ts new file mode 100644 index 00000000..08e1b9be --- /dev/null +++ b/packages/react/src/diagram-text.ts @@ -0,0 +1,172 @@ +// A sequence as text art (DECISIONS 306, 1.2): the same data as box-drawing characters, generated here and loaded on demand by a figure with +// variant="text" (React) or by the HTML skill's diagram-text module. The focal participant in a double-line box, the others single-line; lifelines │, a +// working stretch ┃; a main arrow ━━▶, a plain one ──▶, a dashed one ┄┄▷; frames in their own ink with the operator in primary. No character is ever +// written over a word, every frame closes on all four sides, and selecting the block copies the art exactly. Nothing runs at load. + +import type { DiagramLineKind, MBar, Model } from "./diagram-core"; +import { escapeHtml } from "./diagram-core"; + +type Ink = "focal" | "name" | "life" | "working" | "main" | "plain" | "label" | "num" | "note" | "frame" | "op" | "band" | ""; +interface Row { ch: string[]; ink: Ink[]; n?: number } + +/** The art: its HTML (one span a run of one ink, a line a row) and its widest line in characters. */ +export function textArt(m: Model): { html: string; width: number } { + const nodes = m.nodes; + const steps = m.steps; + const len = (s: string) => Array.from(s).length; + // Columns: each head a box round its name; centres far enough apart for every label between them, and for a self-call's words. + const boxW = nodes.map((n) => Math.max(8, len(n.name) + 4)); + const x = nodes.map(() => 0); + let at = 0; + nodes.forEach((_, k) => { x[k] = at + Math.floor(boxW[k]! / 2); at += boxW[k]! + 4; }); + const need = (a: number, b: number, chars: number) => { + const [lo, hi] = a < b ? [a, b] : [b, a]; + const short = chars - (x[hi]! - x[lo]!); + if (short > 0) for (let k = hi; k < nodes.length; k++) x[k]! += short; + }; + for (const s of steps) { + if (!("n" in s)) continue; + const a = m.byId.get(s.from)?.i ?? 0, b = m.byId.get(s.to)?.i ?? 0; + const words = Math.max(len(`${s.n} ${s.label}`), len(s.note ?? "")); + // A self-call's words go to the end side, the start side on the last participant: the neighbour there is held far enough off for them. + if (a === b) { if (a + 1 < nodes.length) need(a, a + 1, words + 8); else if (a > 0) need(a - 1, a, words + 8); } else need(a, b, words + 4); + } + const last = nodes.length - 1; + // A frame's header and an else row hold their words inside the frame, with both corners: a frame too narrow for them pushes the columns after it out (an + // inner frame by its inset too), and one on the last column widens the art (Neon's B6 of the code review). + const frameExtra = new Map(); + { + let depth = 0; + const stack: Array<{ at: number; a: number; b: number; inset: number; need: number }> = []; + const edgeL = (a: number, inset: number) => x[a]! - Math.floor(boxW[a]! / 2) - 1 + inset; + const edgeR = (b: number, inset: number) => x[b]! + Math.ceil(boxW[b]! / 2) - inset; + steps.forEach((s, at) => { + if ("open" in s) { stack.push({ at, a: s.a - 1, b: s.b - 1, inset: depth * 2, need: len(`[${s.open}]`) + 1 + len(` ${s.label} `) + 2 }); depth++; return; } + if ("otherwise" in s) { const f = stack[stack.length - 1]; if (f) f.need = Math.max(f.need, len("[else]") + 1 + len(` ${s.otherwise} `) + 2); return; } + if ("close" in s) { + depth = Math.max(0, depth - 1); + const f = stack.pop(); + if (!f) return; + // What an inner frame on the same last column already took is this frame's too; only the rest pushes the columns out again. + const have = frameExtra.get(f.at) ?? 0; + const short = f.need - (edgeR(f.b, f.inset) - edgeL(f.a, f.inset)) - have; + if (short > 0) { + if (f.b < last) for (let k = f.b + 1; k < nodes.length; k++) x[k]! += short; + frameExtra.set(f.at, have + short); + } + const total = frameExtra.get(f.at) ?? 0; + if (total) for (const p of stack) if (p.b === f.b) frameExtra.set(p.at, Math.max(frameExtra.get(p.at) ?? 0, total)); + } + }); + } + const selfWidth = Math.max(0, ...steps.map((s) => ("n" in s && s.from === s.to && (m.byId.get(s.from)?.i ?? 0) === last ? len(`${s.n} ${s.label}`) + 8 : 0))); + const W = (x[last] ?? 0) + Math.ceil((boxW[last] ?? 8) / 2) + selfWidth + 2 + Math.max(0, ...frameExtra.values()); + const rows: Row[] = []; + const row = (): Row => { const r = { ch: Array(W).fill(" "), ink: Array(W).fill("") }; rows.push(r); return r; }; + const put = (r: Row, from: number, text: string, ink: Ink) => { Array.from(text).forEach((c, k) => { const i = from + k; if (i >= 0 && i < W) { r.ch[i] = c; r.ink[i] = ink; } }); }; + // Which participants are working at a message (a bar on its lifeline). + const working = (k: number, n: number) => m.bars.some((bar: MBar) => bar.who === nodes[k]!.id && bar.from <= n && bar.to >= n); + let current = 0; + const lifelines = (r: Row) => nodes.forEach((_, k) => put(r, x[k]!, working(k, current) ? "┃" : "│", working(k, current) ? "working" : "life")); + // Heads. + const top = row(), mid = row(), bottom = row(); + nodes.forEach((n, k) => { + const left = x[k]! - Math.floor(boxW[k]! / 2), w = boxW[k]!; + const [tl, h, tr, v, bl, br] = n.focal ? ["╔", "═", "╗", "║", "╚", "╝"] : ["┌", "─", "┐", "│", "└", "┘"]; + const ink: Ink = n.focal ? "focal" : "name"; + put(top, left, tl + h.repeat(w - 2) + tr, ink); + put(mid, left, v, ink); put(mid, left + w - 1, v, ink); + put(mid, left + Math.floor((w - len(n.name)) / 2), n.name, ink); + put(bottom, left, bl + h.repeat(w - 2) + br, ink); + }); + // Frames: their columns' outer edges, a step inside for a nested one; their sides on every row while open. + const open: Array<{ l: number; r: number }> = []; + const sides = (r: Row) => { for (const f of open) { put(r, f.l, "│", "frame"); put(r, f.r, "│", "frame"); } }; + const spacer = () => { const r = row(); lifelines(r); sides(r); return r; }; + spacer(); + for (const [at, s] of steps.entries()) { + if ("band" in s) { + const r = row(); + const words = ` ${s.band} `; + put(r, 0, "─".repeat(W), "band"); + put(r, Math.max(0, Math.floor((W - len(words)) / 2)), words, "band"); + spacer(); + continue; + } + if ("open" in s) { + const a = s.a - 1, b = s.b - 1; + const inset = open.length * 2; + const f = { l: Math.max(0, x[a]! - Math.floor(boxW[a]! / 2) - 1 + inset), r: Math.min(W - 1, x[b]! + Math.ceil(boxW[b]! / 2) + (b === last && steps.some((t) => "n" in t && t.from === t.to) ? selfWidth : 0) - inset + (frameExtra.get(at) ?? 0)) }; + const r = row(); + lifelines(r); sides(r); + put(r, f.l, "┌" + "─".repeat(f.r - f.l - 1) + "┐", "frame"); + put(r, f.l + 1, `[${s.open}]`, "op"); + put(r, f.l + len(s.open) + 4, ` ${s.label} `, "label"); + open.push(f); + spacer(); + continue; + } + if ("otherwise" in s) { + const f = open[open.length - 1]; + if (!f) continue; + const r = row(); + lifelines(r); sides(r); + put(r, f.l, "├" + "┄".repeat(f.r - f.l - 1) + "┤", "frame"); + put(r, f.l + 1, "[else]", "op"); + put(r, f.l + 8, ` ${s.otherwise} `, "label"); + spacer(); + continue; + } + if ("close" in s) { + const f = open.pop(); + if (!f) continue; + const r = row(); + lifelines(r); sides(r); + put(r, f.l, "└" + "─".repeat(f.r - f.l - 1) + "┘", "frame"); + spacer(); + continue; + } + current = s.n; + const a = m.byId.get(s.from)?.i ?? 0, b = m.byId.get(s.to)?.i ?? 0; + const said = `${s.n} ${s.label}`; + const shaft = (k: DiagramLineKind) => (k === "main" ? "━" : k === "dashed" ? "┄" : "─"); + const head = (k: DiagramLineKind, right: boolean) => (k === "dashed" ? (right ? "▷" : "◁") : right ? "▶" : "◀"); + const ink: Ink = s.kind === "main" ? "main" : "plain"; + const r1 = row(), r2 = row(); + r1.n = s.n; r2.n = s.n; + lifelines(r1); sides(r1); lifelines(r2); sides(r2); + if (a === b) { + const left = a === last && nodes.length > 1; + const from = left ? x[a]! - 4 : x[a]! + 1; + put(r1, from, left ? "┌──" : "──┐", ink); + put(r2, from, left ? "└─" + head(s.kind, true) : head(s.kind, false) + "─┘", ink); + const wordsAt = left ? from - len(said) - 1 : x[a]! + 5; + put(r1, wordsAt, said.slice(0, len(String(s.n))), "num"); + put(r1, wordsAt + len(String(s.n)) + 1, s.label, "label"); + if (s.note) { const r3 = row(); lifelines(r3); sides(r3); put(r3, left ? from - len(s.note) - 1 : x[a]! + 5, s.note, "note"); } + } else { + const lo = Math.min(x[a]!, x[b]!), hi = Math.max(x[a]!, x[b]!), right = x[b]! > x[a]!; + const wordsAt = lo + Math.max(2, Math.floor((hi - lo - len(said)) / 2)); + put(r1, wordsAt - 1, " ", ""); + put(r1, wordsAt, String(s.n), "num"); + put(r1, wordsAt + len(String(s.n)), " " + s.label + " ", "label"); + const body = shaft(s.kind).repeat(Math.max(1, hi - lo - 2)); + put(r2, lo + 1, right ? body + head(s.kind, true) : head(s.kind, false) + body, ink); + if (s.note) { const r3 = row(); lifelines(r3); sides(r3); const at3 = lo + Math.max(2, Math.floor((hi - lo - len(s.note)) / 2)); put(r3, at3 - 1, ` ${s.note} `, "note"); } + } + } + spacer(); + // One span a run of one ink; a row's trailing spaces dropped, so a copy is the art and no more. + const html = rows.map((r) => { + const end = r.ch.join("").trimEnd().length; + let out = "", run = "", ink: Ink = r.ink[0] ?? ""; + for (let i = 0; i < end; i++) { + if (r.ink[i] !== ink && run) { out += ink ? `${escapeHtml(run)}` : escapeHtml(run); run = ""; } + ink = r.ink[i]!; + run += r.ch[i]; + } + if (run) out += ink ? `${escapeHtml(run)}` : escapeHtml(run); + return r.n ? `${out}` : out; + }).join("\n"); + return { html, width: Math.max(...rows.map((r) => r.ch.join("").trimEnd().length)) }; +} diff --git a/packages/react/src/diagram-viewer.tsx b/packages/react/src/diagram-viewer.tsx new file mode 100644 index 00000000..345146e3 --- /dev/null +++ b/packages/react/src/diagram-viewer.tsx @@ -0,0 +1,261 @@ +import * as React from "react"; + +import { Button, IconButton } from "./button"; +import type { DiagramFigureInternalProps, DiagramViewerMode } from "./diagram-figure"; +import type { buildModel, DiagramSpec, figureKey, figureList, hintEntries, Measured, measureFigure, Model, toHtml } from "./diagram-core"; +import { attachZoom, measureViewerFigure, revealIn, VIEWER_KEYS, viewerHint, viewerTextWidth } from "./diagram-zoom-core"; +import type { ViewerMemo, ZoomController, ZoomState } from "./diagram-zoom-core"; +import { createPortal } from "react-dom"; + +import { CloseGlyph } from "./glyphs/close"; +import { MinusGlyph } from "./glyphs/minus"; +import { PlusGlyph } from "./glyphs/plus"; + +// The diagram viewer (DECISIONS 301, part 9, as DECISIONS 310): "Expand" opens the figure's drawn layout in a dialog, where the reader zooms and pans it. +// The figure is drawn again from the same data, laid out once at 100% in real CSS pixels, and zoomed with one transform (diagram-zoom-core.ts). This module +// is loaded on demand by a figure's "Expand" (diagram-figure.tsx); it is not exported from the package. Its dialog is the form dialog's box and the sheet's head, +// body and foot, drawn on a native modal as the HTML skill's is, not Base UI's: an import of Base UI's dialog from a chunk any figure can load widens the +// Base UI chunk every other component's bundle shares (Button alone grew by 1.8 KB), so the viewer brings no Base UI but the button's. The implementation hasn't +// been reviewed, and no seat has drawn, checked or given a position on part 9: every value is the decider's alone. + +const P = "basalt-diagram"; + +/** + * What the figure hands the viewer: its own component and the engine's functions. The viewer imports none of them, so its chunk holds the dialog, the + * buttons and the zoom, and never a second copy of the engine. + */ +export interface ViewerKit { + Figure: (props: DiagramFigureInternalProps) => React.ReactNode; + Kbd: (props: { children?: React.ReactNode }) => React.ReactNode; + buildModel: typeof buildModel; + figureKey: typeof figureKey; + figureList: typeof figureList; + hintEntries: typeof hintEntries; + toHtml: typeof toHtml; + /** The figure's own surface-level context: the viewer's content is level 1, as a modal's is. */ + inLevel: (level: 1, children: React.ReactNode) => React.ReactNode; + measureFigure: typeof measureFigure; +} + +export interface DiagramViewerProps { + kit: ViewerKit; + spec: DiagramSpec; + component: string; + source?: React.ReactNode; + summary: React.ReactNode; + /** "Expand": focus returns to it when the viewer closes. */ + opener: React.RefObject; + onClose: () => void; +} + +const EMPTY: ZoomState = { zoom: 1, level: 100, fit: 1, min: 1, max: 4, atMin: false, atMax: false, atFit: true, listOpen: false }; + +/** A length token's value in CSS pixels, read from a probe the stage holds. */ +const probeWidth = (stage: HTMLElement | null, which: string) => stage?.querySelector(`.${P}-probe[data-probe="${which}"]`)?.offsetWidth ?? 0; + +export function DiagramViewer({ kit, spec, component, source, summary, opener, onClose }: DiagramViewerProps) { + const { Figure: DiagramFigure, Kbd, buildModel, figureKey, figureList, hintEntries, toHtml, inLevel, measureFigure } = kit; + // The viewer's figure is still (9.7): no entrance, flow, mover or run, so no motion code is loaded for it. + const still = React.useMemo(() => ({ ...spec, motion: "still" }), [spec]); + // An automatic figure's foot (its key hint) is read from a placed model: unplaced, every card is in one cell and the hint would say two arrows where the + // drawing has rows and columns (the pixel review's check on the viewer's hint). + const model = React.useMemo(() => buildModel(still, { placement: Array.isArray(still.placement) ? still.placement[0] : still.placement }), [still]); + const stageRef = React.useRef(null); + const sizerRef = React.useRef(null); + const layerRef = React.useRef(null); + const statusRef = React.useRef(null); + const zoomRef = React.useRef(null); + const [zoom, setZoom] = React.useState(EMPTY); + const [avail, setAvail] = React.useState(0); + const [dims, setDims] = React.useState({ row: 1104, contain: 480 }); + const [layout, setLayout] = React.useState<{ layout?: string; bare?: boolean; open?: boolean }>({}); + const [listOpen, setListOpen] = React.useState(false); + const descId = React.useId(); + + // The stage's inner width (its width less the padding of 9.4) is the width the figure may be laid out at; it is read again when the stage resizes. + const readStage = React.useCallback(() => { + const stage = stageRef.current, sizer = sizerRef.current; + if (!stage || !sizer) return; + const pad = Number.parseFloat(getComputedStyle(sizer).paddingLeft) || 0; + setAvail(Math.max(0, Math.floor(stage.clientWidth - 2 * pad))); + setDims({ row: probeWidth(stage, "row") || 1104, contain: probeWidth(stage, "contain") || 480 }); + }, []); + + // The dialog's content mounts in a portal: the stage is wired once it exists. + const [stageNode, setStageNode] = React.useState(null); + const setStage = React.useCallback((el: HTMLDivElement | null) => { stageRef.current = el; setStageNode(el); }, []); + React.useLayoutEffect(() => { + const stage = stageNode, sizer = sizerRef.current, layer = layerRef.current, status = statusRef.current; + if (!stage || !sizer || !layer || !status) return undefined; + const rest = Number.parseFloat(getComputedStyle(stage).getPropertyValue("--_rest")) || 300; + const z = attachZoom({ stage, sizer, layer, status, rest, onChange: setZoom }); + zoomRef.current = z; + readStage(); + let width = stage.clientWidth; + const observer = new ResizeObserver(() => { if (Math.abs(stage.clientWidth - width) >= 0.5) { width = stage.clientWidth; readStage(); } }); + observer.observe(stage); + // A focused card is brought into view by the least distance, space-4 clear of the stage's edge (9.5). + const onFocusIn = (event: FocusEvent) => { + const node = (event.target as HTMLElement | null)?.closest?.(`.${P}-node`); + if (node && stage.contains(node)) revealIn(stage, node, Number.parseFloat(getComputedStyle(stage).getPropertyValue("--_clear")) || 16); + }; + stage.addEventListener("focusin", onFocusIn); + return () => { z.destroy(); zoomRef.current = null; observer.disconnect(); stage.removeEventListener("focusin", onFocusIn); }; + }, [stageNode, readStage]); + + // After each layout the zoom learns the drawing's size at 100%: the figure's own box, read with the zoom taken off (offsetWidth ignores the transform). + const onMeasured = React.useCallback((measured: Measured, fig: HTMLElement) => { + setLayout({ layout: measured.dyn.layout, bare: measured.dyn.bare, open: measured.dyn.open }); + zoomRef.current?.size(fig.offsetWidth, fig.offsetHeight); + }, []); + const memo = React.useRef({}); + // The figure is laid out as the dialog opens, through its scale from .98; once the entrance has ended it is laid out again, unscaled, so its lines + // snap on the pixel grid they are drawn on. + const [settled, setSettled] = React.useState(0); + const viewer = React.useMemo(() => { + const layer = layerRef.current; + if (!(avail > 0) || !layer) return undefined; + return { + keys: VIEWER_KEYS, + room: () => { + const stage = stageRef.current, sizer = sizerRef.current; + const pad = sizer ? Number.parseFloat(getComputedStyle(sizer).paddingTop) || 0 : 0; + return { w: (stage?.clientWidth ?? 0) - 2 * pad, h: (stage?.clientHeight ?? 0) - 2 * pad }; + }, + onMeasured, + measure: (fig, m, p, base, current, apply, warn) => measureViewerFigure(fig, m, p, base, current, apply, warn, { layer, avail, row: dims.row, contain: dims.contain, memo: memo.current, measureFigure }), + textWidth: (need) => viewerTextWidth({ layer, avail, row: dims.row, contain: dims.contain, memo: memo.current, measureFigure }, need), + }; + }, [avail, dims, onMeasured, measureFigure, settled]); + + // A stack with no lines has its list open, as on the page (9.3). + const showList = listOpen || Boolean(layout.bare); + React.useLayoutEffect(() => { zoomRef.current?.list(showList); }, [showList]); + + const key = figureKey(P, model); + const keyHtml = React.useMemo(() => ({ __html: key ? toHtml(key) : "" }), [key]); + const listHtml = React.useMemo(() => ({ __html: figureList(P, model).map((v) => toHtml(v)).join("") }), [model]); + const hint = viewerHint(hintEntries(model, layout.layout === "drawn")).map((entry) => ( + {entry.keys.map((k, i) => {i ? " " : null}{/* A fragment, not a string: Kbd reads a string as a shortcut, and "+" is its separator. */}<>{k})} {entry.words} + )); + const off = zoom.listOpen; + const z = () => zoomRef.current; + + // The dialog: shown as a modal when it mounts; Esc (the browser's cancel), Close and a press on the scrim close it, after its own exit motion; focus + // returns to "Expand". While it is open the page behind does not scroll (the stylesheet), and Tab wraps inside it. + const dialogRef = React.useRef(null); + const titleId = React.useId(); + const closing = React.useRef(false); + const onCloseRef = React.useRef(onClose); + onCloseRef.current = onClose; + const close = React.useCallback(() => { + const d = dialogRef.current; + if (!d || closing.current) return; + closing.current = true; + if (d.open) d.close(); + }, []); + React.useLayoutEffect(() => { + const d = dialogRef.current; + if (!d) return undefined; + if (!d.open) d.showModal(); + stageRef.current?.focus({ preventScroll: true }); + let timer = 0; + const onClose = () => { + closing.current = true; + opener.current?.focus({ preventScroll: true }); + const out = (Number.parseFloat(getComputedStyle(d).getPropertyValue("--_out")) || 0); + timer = window.setTimeout(() => onCloseRef.current(), out); + }; + let down = false; + const outside = (e: MouseEvent) => { const r = d.getBoundingClientRect(); return e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom; }; + const onDown = (e: PointerEvent) => { down = e.target === d && outside(e); }; + const onClick = (e: MouseEvent) => { if (down && e.target === d && outside(e)) close(); down = false; }; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Tab" || e.defaultPrevented) return; + const all = Array.from(d.querySelectorAll('a[href],button:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter((n) => n.getClientRects().length && !n.closest("[hidden]")); + if (!all.length) return; + const first = all[0]!, last = all[all.length - 1]!, at = document.activeElement; + if (e.shiftKey && (at === first || at === d)) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && at === last) { e.preventDefault(); first.focus(); } + }; + // A linked card is followed on a click, a tap or Enter; a link that stays in this tab closes the viewer first (9.7). The dialog closes as the click is + // handled, and the browser then follows the link as it would anywhere: a new tab's link leaves the viewer open. + const onLink = (e: MouseEvent) => { + const a = (e.target as Element | null)?.closest?.(`a.${P}-node[href]`) as HTMLAnchorElement | null; + if (!a || !d.contains(a) || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || (a.target && a.target !== "_self")) return; + close(); + }; + const onEntered = (e: TransitionEvent) => { if (e.target === d && e.propertyName === "transform" && d.open && !closing.current) setSettled((n) => n + 1); }; + d.addEventListener("transitionend", onEntered); + d.addEventListener("close", onClose); + d.addEventListener("pointerdown", onDown); + d.addEventListener("click", onClick); + d.addEventListener("click", onLink); + d.addEventListener("keydown", onKey); + return () => { clearTimeout(timer); d.removeEventListener("transitionend", onEntered); d.removeEventListener("close", onClose); d.removeEventListener("pointerdown", onDown); d.removeEventListener("click", onClick); d.removeEventListener("click", onLink); d.removeEventListener("keydown", onKey); if (d.open) d.close(); }; + }, [opener, close]); + + return createPortal( + + {inLevel(1, <> +
+
+

{model.title}

+ {source !== undefined && source !== null ?

{source}

: null} +
+ +
+

{summary}

+
+
, + document.body, + ); +} + diff --git a/packages/react/src/diagram-zoom-core.ts b/packages/react/src/diagram-zoom-core.ts new file mode 100644 index 00000000..2c26e5c7 --- /dev/null +++ b/packages/react/src/diagram-zoom-core.ts @@ -0,0 +1,416 @@ +// The diagram viewer's stage (DECISIONS 301, part 9, as DECISIONS 310): zoom and pan for a figure laid out once at 100%, for React's viewer and the HTML +// skill's diagram-zoom module alike. Plain DOM and no React, so the two zoom, pan, pinch and speak the same way. Nothing here runs when the module loads. +// +// The layer holds the laid-out figure at its real CSS pixels; the zoom is one `transform: scale()` on it, inside a sizer as large as the zoomed drawing +// (plus the stage's padding) so the stage has something to scroll. A pan is a scroll. Nothing is animated: a step, the wheel and a pinch land at once. +// The engine never measures a zoomed figure: the viewer gives this the layer's size at 100% (`size`), read with the zoom taken off. + +import type { Dyn, Measured, Model } from "./diagram-core"; + +type MeasureFigure = (fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn?: (s: string) => void, sizeTo?: (least: number) => void) => Measured; + +/** The viewer's addition to the figure's keys sentence (9.8). */ +export const VIEWER_KEYS = "Plus and minus zoom, zero fits the drawing, Escape closes."; + +/** The viewer's key hint (9.8): the figure's, with Esc closing and the zoom keys added. */ +export function viewerHint(entries: Array<{ keys: string[]; words: string }>): Array<{ keys: string[]; words: string }> { + const out = entries.filter((e) => e.keys[0] !== "Esc"); + return [...out, { keys: ["+", "−"], words: "zoom" }, { keys: ["0"], words: "fit" }, { keys: ["Esc"], words: "close" }]; +} + +/** The ladder the buttons and keys step on (9.4): a browser's own, shortened. */ +export const ZOOM_STEPS = [25, 33, 50, 67, 75, 100, 125, 150, 200, 300, 400]; +const MAX = 4; +const FIT_CAP = 2; +/** The wheel (9.4): the zoom is multiplied by 2 to the power of minus a hundredth of the delta, one event's delta held to 25 either way. */ +const WHEEL_STEP = 100; +const WHEEL_HOLD = 25; +const EPS = 0.0005; + +export interface ZoomState { + /** The zoom as a ratio (1 is 100%). */ + zoom: number; + /** The level as whole per cent, as the foot writes it. */ + level: number; + fit: number; + min: number; + max: number; + atMin: boolean; + atMax: boolean; + atFit: boolean; + /** "View as list" is open: the zoom controls are disabled and the stage scrolls as a page. */ + listOpen: boolean; +} + +export interface ZoomHost { + /** The scrolling box (role="group", tabindex 0). */ + stage: HTMLElement; + /** Sized to the zoomed drawing; its padding is the stage's padding (space-6 from 720, space-4 under it). */ + sizer: HTMLElement; + /** The laid-out figure's box: the transform is on it. */ + layer: HTMLElement; + /** The one polite status line, visually hidden. */ + status: HTMLElement; + /** `duration-slower` in ms: the status speaks once the level has rested this long. */ + rest: number; + onChange: (state: ZoomState) => void; +} + +export interface ZoomController { + /** The layer's laid-out size at 100%, in CSS pixels, after every layout. */ + size: (width: number, height: number) => void; + zoomIn: () => void; + zoomOut: () => void; + fit: () => void; + state: () => ZoomState; + /** The list is in the stage in place of the drawing (9.9): gestures stop; closing it brings the drawing back at its zoom and place. */ + list: (open: boolean) => void; + /** Whether the press that has just ended travelled: a travelled press is a pan, never a click. */ + travelled: () => boolean; + destroy: () => void; +} + +interface Pt { x: number; y: number } + +export function attachZoom(host: ZoomHost): ZoomController { + const { stage, sizer, layer, status } = host; + let W = 0, H = 0; + let zoom = 1, fitZoom = 1; + // The reader has zoomed: a resize keeps their zoom (inside the new limits) and the point at the middle; untouched, it stays at Fit. + let touched = false; + let listOpen = false; + let saved: { left: number; top: number } | null = null; + let spoken = ""; + let speakTimer = 0; + + const pad = () => Number.parseFloat(getComputedStyle(sizer).paddingTop) || 0; + const minOf = () => Math.min(fitZoom, 1); + const clamp = (z: number) => Math.min(MAX, Math.max(minOf(), z)); + + function computeFit() { + if (!W || !H) return 1; + const p = pad(); + const cw = stage.clientWidth - 2 * p, ch = stage.clientHeight - 2 * p; + if (cw <= 0 || ch <= 0) return Math.min(1, FIT_CAP); + // The largest whole per cent at which the whole drawing shows inside the padding, 200% at most. + const raw = Math.min(cw / W, ch / H); + return Math.min(FIT_CAP, Math.floor(raw * 100 + 1e-6) / 100); + } + + function state(): ZoomState { + const min = minOf(); + return { + zoom, level: Math.round(zoom * 100), fit: fitZoom, min, max: MAX, + atMin: zoom <= min + EPS, atMax: zoom >= MAX - EPS, atFit: Math.abs(zoom - fitZoom) < EPS, listOpen, + }; + } + function changed() { + host.onChange(state()); + stage.toggleAttribute("data-pannable", W * zoom > stage.clientWidth - 2 * pad() + 0.5 || H * zoom > stage.clientHeight - 2 * pad() + 0.5); + } + function speak() { + clearTimeout(speakTimer); + const words = `Zoom ${Math.round(zoom * 100)}%`; + // Once the level has not changed for duration-slower, so a pinch is spoken once. + speakTimer = window.setTimeout(() => { if (words !== spoken) { spoken = words; status.textContent = words; } }, host.rest); + } + + /** Writes the zoom: the sizer takes the zoomed drawing's size and the layer its scale. No transition: a zoom lands at once. */ + function paint() { + sizer.style.width = `${W * zoom}px`; + sizer.style.height = `${H * zoom}px`; + layer.style.transform = `scale(${zoom})`; + } + + /** The drawing's point (at 100%) under a point of the window. */ + function contentAt(p: Pt): Pt { + const r = layer.getBoundingClientRect(); + return { x: (p.x - r.left) / zoom, y: (p.y - r.top) / zoom }; + } + /** Scrolls so the drawing's point `c` is under the window's point `p`. */ + function holdAt(c: Pt, p: Pt) { + const r = layer.getBoundingClientRect(); + stage.scrollLeft += r.left + c.x * zoom - p.x; + stage.scrollTop += r.top + c.y * zoom - p.y; + } + const middle = (): Pt => { const r = stage.getBoundingClientRect(); return { x: r.left + stage.clientWidth / 2, y: r.top + stage.clientHeight / 2 }; }; + + function zoomTo(next: number, anchor: Pt = middle(), held?: Pt) { + if (listOpen) return; + const z = clamp(next); + if (Math.abs(z - zoom) < 1e-6) { changed(); return; } + const c = held ?? contentAt(anchor); + zoom = z; + paint(); + holdAt(c, anchor); + changed(); + speak(); + } + + function step(up: boolean) { + touched = true; + const at = zoom * 100; + const next = up ? ZOOM_STEPS.find((s) => s > at + 0.5) : [...ZOOM_STEPS].reverse().find((s) => s < at - 0.5); + zoomTo(next === undefined ? (up ? MAX : minOf()) : next / 100); + } + + function toFit() { + if (listOpen) return; + touched = false; + zoom = fitZoom; + paint(); + // At Fit the whole drawing shows: centred where it is smaller than the stage (the sizer's auto margins), from its top start corner otherwise. + stage.scrollTop = 0; + stage.scrollLeft = getComputedStyle(stage).direction === "rtl" ? stage.scrollWidth : 0; + changed(); + speak(); + } + + function size(width: number, height: number) { + if (!width || !height) return; + const keep = touched && W && H ? contentAt(middle()) : null; + W = width; + H = height; + fitZoom = computeFit(); + if (!touched) { + zoom = fitZoom; + paint(); + stage.scrollTop = 0; + stage.scrollLeft = getComputedStyle(stage).direction === "rtl" ? stage.scrollWidth : 0; + } else { + zoom = clamp(zoom); + paint(); + if (keep) holdAt(keep, middle()); + } + changed(); + } + + // ---- The wheel: a plain wheel scrolls; with Ctrl or Command (and a trackpad pinch, sent as a wheel with Ctrl) it zooms about the pointer ---- + function onWheel(event: WheelEvent) { + if (listOpen || !(event.ctrlKey || event.metaKey)) return; + event.preventDefault(); + const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? stage.clientHeight : 1; + const delta = Math.max(-WHEEL_HOLD, Math.min(WHEEL_HOLD, event.deltaY * unit)); + touched = true; + zoomTo(zoom * 2 ** (-delta / WHEEL_STEP), { x: event.clientX, y: event.clientY }); + } + + // ---- Keys, only while focus is in the stage (WCAG 2.1.4): + or = in, - out, 0 Fit. The browser's own Ctrl and Command zoom keys are left alone ---- + function onKey(event: KeyboardEvent) { + if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || listOpen) return; + if (event.key === "+" || event.key === "=") { event.preventDefault(); step(true); } else if (event.key === "-" || event.key === "−") { event.preventDefault(); step(false); } else if (event.key === "0") { event.preventDefault(); toFit(); } + } + + // ---- Pan and pinch: a press that travels more than space-1 is a drag, one for one; two fingers pinch about their midpoint ---- + const pointers = new Map(); + let start: Pt | null = null; + let last: Pt | null = null; + let dragging = false; + let moved = false; + let pinch: { d0: number; z0: number; c: Pt } | null = null; + const travel = () => Number.parseFloat(getComputedStyle(stage).getPropertyValue("--_travel")) || 4; + const mid = (): Pt => { const [a, b] = [...pointers.values()]; return { x: (a!.x + b!.x) / 2, y: (a!.y + b!.y) / 2 }; }; + const spread = (): number => { const [a, b] = [...pointers.values()]; return Math.hypot(a!.x - b!.x, a!.y - b!.y); }; + + function onDown(event: PointerEvent) { + if (listOpen) return; + if (event.pointerType === "mouse" && event.button !== 0) return; + pointers.set(event.pointerId, { x: event.clientX, y: event.clientY }); + if (pointers.size === 1) { start = { x: event.clientX, y: event.clientY }; last = start; dragging = false; moved = false; } + if (pointers.size === 2 && event.pointerType === "touch") { + const m = mid(); + pinch = { d0: spread() || 1, z0: zoom, c: contentAt(m) }; + moved = true; + dragging = false; + try { stage.setPointerCapture(event.pointerId); } catch { /* the pointer has gone */ } + } + } + function onMove(event: PointerEvent) { + if (!pointers.has(event.pointerId) || listOpen) return; + pointers.set(event.pointerId, { x: event.clientX, y: event.clientY }); + if (pinch && pointers.size >= 2) { + touched = true; + const z = clamp(pinch.z0 * (spread() / pinch.d0)); + const m = mid(); + if (Math.abs(z - zoom) > 1e-6) { zoom = z; paint(); changed(); speak(); } + holdAt(pinch.c, m); + return; + } + if (pointers.size !== 1 || !start || !last) return; + const p = { x: event.clientX, y: event.clientY }; + if (!dragging) { + if (Math.hypot(p.x - start.x, p.y - start.y) <= travel()) return; + dragging = true; + moved = true; + stage.setAttribute("data-dragging", ""); + try { stage.setPointerCapture(event.pointerId); } catch { /* the pointer has gone */ } + } + stage.scrollLeft -= p.x - last.x; + stage.scrollTop -= p.y - last.y; + last = p; + event.preventDefault(); + } + function onUp(event: PointerEvent) { + if (!pointers.has(event.pointerId)) return; + pointers.delete(event.pointerId); + if (pointers.size < 2) pinch = null; + if (pointers.size === 1) { + // A pinch that leaves one finger down pans from where that finger is: no jump. + const [p] = [...pointers.values()]; + last = p!; + start = p!; + dragging = true; + return; + } + if (pointers.size === 0) { + dragging = false; + stage.removeAttribute("data-dragging"); + start = last = null; + // No momentum and no rubber band: lifted, it stops. + } + } + // A press that travelled is a pan: the click it ends in does nothing (a link is not followed, a card is not traced). + function onClick(event: MouseEvent) { + if (!moved) return; + moved = false; + event.preventDefault(); + event.stopPropagation(); + } + + const resize = new ResizeObserver(() => { + if (!W || !H) return; + const keep = touched ? contentAt(middle()) : null; + fitZoom = computeFit(); + if (!touched) { zoom = fitZoom; paint(); } else { zoom = clamp(zoom); paint(); if (keep) holdAt(keep, middle()); } + changed(); + }); + resize.observe(stage); + + stage.addEventListener("wheel", onWheel, { passive: false }); + stage.addEventListener("keydown", onKey); + stage.addEventListener("pointerdown", onDown); + stage.addEventListener("pointermove", onMove); + stage.addEventListener("pointerup", onUp); + stage.addEventListener("pointercancel", onUp); + stage.addEventListener("click", onClick, true); + + return { + size, + zoomIn: () => step(true), + zoomOut: () => step(false), + fit: toFit, + state, + list(open: boolean) { + if (open === listOpen) return; + if (open) { saved = { left: stage.scrollLeft, top: stage.scrollTop }; listOpen = true; stage.setAttribute("data-list", ""); stage.scrollTop = 0; } else { + listOpen = false; + stage.removeAttribute("data-list"); + paint(); + if (saved) { stage.scrollLeft = saved.left; stage.scrollTop = saved.top; } + saved = null; + } + changed(); + }, + travelled: () => moved, + destroy() { + clearTimeout(speakTimer); + resize.disconnect(); + stage.removeEventListener("wheel", onWheel); + stage.removeEventListener("keydown", onKey); + stage.removeEventListener("pointerdown", onDown); + stage.removeEventListener("pointermove", onMove); + stage.removeEventListener("pointerup", onUp); + stage.removeEventListener("pointercancel", onUp); + stage.removeEventListener("click", onClick, true); + }, + }; +} + +/** Brings a focused card into the stage's view by the least distance, `margin` clear of its edges (9.5). */ +export function revealIn(stage: HTMLElement, el: Element, margin: number): void { + const s = stage.getBoundingClientRect(); + const r = el.getBoundingClientRect(); + const left = s.left + margin, right = s.left + stage.clientWidth - margin, top = s.top + margin, bottom = s.top + stage.clientHeight - margin; + if (r.left < left) stage.scrollLeft -= left - r.left; else if (r.right > right) stage.scrollLeft += Math.min(r.right - right, r.left - left); + if (r.top < top) stage.scrollTop -= top - r.top; else if (r.bottom > bottom) stage.scrollTop += Math.min(r.bottom - bottom, r.top - top); +} + +/** A text sequence in the viewer (9.3): the layer is the art's own width, `need` being the figure's width at which the widest line just fits. */ +export function viewerTextWidth(v: ViewerLayout, need: number): void { + v.memo.art = Math.ceil(need); + v.layer.style.width = `${v.memo.art}px`; +} + +/** What the viewer's figure remembers between layouts: the least width the engine was found to draw this data at (0: none). */ +export interface ViewerMemo { model?: unknown; least?: number; art?: number } +export interface ViewerLayout { + /** The layer the figure is laid out in: its width is the layout width; its transform (the zoom) is taken off while it is measured. */ + layer: HTMLElement; + /** The stage's inner width, the page row and `size-breakpoint-container`, in CSS pixels. */ + avail: number; + row: number; + contain: number; + memo: ViewerMemo; + /** The engine's measure (diagram-core's measureFigure), handed over so this module holds no copy of it. */ + measureFigure: MeasureFigure; +} + +/** + * The viewer's layout (DECISIONS 310, 9.3), for React and the skill alike: the figure is laid out at the stage's inner width, never under its least drawn + * width and never over the page row unless that width is more; a stack is held only when nothing is drawn, at most the container's width. The engine + * measures only at 100%: the zoom is taken off the layer while it measures and put back before anything paints. + */ +export function measureViewerFigure(fig: HTMLElement, m: Model, P: string, base: string, current: Dyn, apply: (dyn: Dyn) => void, warn: ((s: string) => void) | undefined, v: ViewerLayout): Measured { + const { layer, memo, measureFigure } = v; + if (memo.model !== m) { memo.model = m; memo.least = undefined; memo.art = undefined; } + // A text sequence holds the art at its own width, never the transcript (9.3): the figure reports the art's width (textWidth) and the layer takes it. + if (m.text) { + layer.style.width = `${memo.art ?? Math.min(v.avail, v.row)}px`; + const zoomedText = layer.style.transform; + layer.style.transform = "none"; + const out = measureFigure(fig, m, P, base, current, apply, warn); + layer.style.transform = zoomedText; + return out; + } + const sizeTo = (least: number) => { layer.style.width = `${Math.max(memo.least || least, Math.min(v.avail, v.row))}px`; }; + // The layer has no width of its own until the first layout: it starts at the stage's, so the figure can be measured. + if (!layer.style.width) layer.style.width = `${Math.min(v.avail, v.row)}px`; + const zoomed = layer.style.transform; + layer.style.transform = "none"; + // A dialog still opening is scaled (from .98): the layer is scaled by the inverse while it is measured, so what is read is 100% whatever its ancestors do. + const ancestors = layer.offsetWidth ? layer.getBoundingClientRect().width / layer.offsetWidth : 1; + const unscale = Math.abs(ancestors - 1) > 1e-4 ? ` scale(${1 / ancestors})` : ""; + layer.style.transform = unscale || "none"; + // The engine snaps lines to the page's pixel grid from the drawing's origin. The layer sits wherever the stage centres it, so it is moved to the + // nearest whole pixel while it is measured (its drawing's origin): the ink is then the string a page drawing on whole pixels draws, whatever the zoom or the stage's size. + const r = (fig.querySelector(`.${P}-drawing`) ?? layer).getBoundingClientRect(); + const fx = r.left - Math.round(r.left), fy = r.top - Math.round(r.top); + if (fx || fy) layer.style.transform = `translate(${-fx / ancestors}px, ${-fy / ancestors}px)${unscale}`; + // Before the least drawn width is known, a refusal at the token sum is expected and is not the author's to fix: it says nothing. + let result = measureFigure(fig, m, P, base, current, apply, memo.least === undefined ? undefined : warn, sizeTo); + // The least drawn width is the first width the engine draws the figure at, which the token sum can undercount (a sequence's columns are measured, a + // decision may be taller than wide at a width). Found once by trying wider layouts, in steps of 16 and then by the pixel, up to half the row past it. A width + // counts when it draws twice running: measured from the stack, then again from its own drawn state, as every later measure is. + if (result.dyn.layout === "stacked" && memo.least === undefined && result.least !== undefined) { + const from = result.dyn; + const at = (w: number) => { + layer.style.width = `${w}px`; + const first = measureFigure(fig, m, P, base, from, apply); + return first.dyn.layout === "drawn" ? measureFigure(fig, m, P, base, first.dyn, apply) : first; + }; + const start = Math.max(result.least, Math.min(v.avail, v.row)); + const cap = Math.max(v.row, start) * 1.5; + let found: number | undefined; + for (let w = start + 16; w <= cap && found === undefined; w += 16) if (at(w).dyn.layout === "drawn") found = w; + if (found !== undefined) for (let w = found - 15; w < found; w++) if (at(w).dyn.layout === "drawn") { found = w; break; } + memo.least = found ?? 0; + result = found !== undefined ? at(found) : measureFigure(fig, m, P, base, from, apply, warn, sizeTo); + } + if (result.dyn.layout === "stacked" && fig.clientWidth > v.contain) { + layer.style.width = `${v.contain}px`; + result = measureFigure(fig, m, P, base, result.dyn, apply, warn); + } + layer.style.transform = zoomed; + return result; +} + diff --git a/packages/react/src/flowchart-diagram.tsx b/packages/react/src/flowchart-diagram.tsx index bd6115ec..585d37da 100644 --- a/packages/react/src/flowchart-diagram.tsx +++ b/packages/react/src/flowchart-diagram.tsx @@ -2,11 +2,11 @@ import * as React from "react"; import { DiagramFigure } from "./diagram-figure"; import type { DiagramFigureProps } from "./diagram-figure"; -import type { DiagramEdge, DiagramShapeLabels, FlowchartNode } from "./diagram-core"; +import type { DiagramEdge, DiagramShapeLabels, FlowchartNode, DiagramPlacement, DiagramUnplaced } from "./diagram-core"; export type { DiagramEdge, DiagramLegend, DiagramLineKind, DiagramShapeLabels, DiagramSide, FlowchartNode } from "./diagram-core"; -export interface FlowchartDiagramProps extends DiagramFigureProps { +interface FlowchartDiagramBase 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. */ @@ -15,8 +15,28 @@ export interface FlowchartDiagramProps extends DiagramFigureProps { shapeLabels?: DiagramShapeLabels; } +/** + * Authored (the default): every card carries its `col` and `row`. Automatic (`layout: "auto"`, DECISIONS 306, 1.8): no card needs them, and none are read. + */ +export type FlowchartDiagramProps = Omit & ( + | { layout?: "authored"; direction?: never; placement?: never; nodes: FlowchartNode[] } + | { + /** + * `"auto"` (DECISIONS 306, 1.8): elkjs gives each card a column and a row, and Basalt sizes, routes and seats the figure as it does an authored one; a + * card's `col` and `row` are left out (and not read). Place at build time with `placeDiagram` from `@srasyndicate/basalt/diagram-layout` and pass + * `placement`: then elkjs never loads in the browser. Without it the layout module loads on demand at 640 or wider. + */ + layout: "auto"; + /** Under `"auto"`: the one direction tried. Left out, the type's own (right for an architecture and a schema, down for a flowchart), then the other. */ + direction?: "right" | "down"; + /** Under `"auto"`: `placeDiagram`'s answer for one direction or both. */ + placement?: DiagramPlacement | DiagramPlacement[]; + nodes: Array>; + } +); + /** A flowchart (DECISIONS 281): 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, motion, title, heading, legend, ...props }: FlowchartDiagramProps) { - const spec = React.useMemo(() => ({ type: "flowchart" as const, title, heading, legend, nodes, edges, shapeLabels, motion }), [title, heading, legend, nodes, edges, shapeLabels, motion]); - return ; +export function FlowchartDiagram({ nodes, edges, shapeLabels, motion, entrance, layout, direction, placement, title, heading, legend, ...props }: FlowchartDiagramProps) { + const spec = React.useMemo(() => ({ type: "flowchart" as const, title, heading, legend, nodes: nodes as FlowchartNode[], edges, shapeLabels, motion, entrance, layout, direction, placement }), [title, heading, legend, nodes, edges, shapeLabels, motion, entrance, layout, direction, placement]); + return ; } diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 737fbf1b..a0baa535 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -94,15 +94,15 @@ 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, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramSide } from "./architecture-diagram"; +export type { ArchitectureDiagramProps, ArchitectureNode, DiagramEdge, DiagramFigureProps, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } 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 type { DiagramFrameLabels, SequenceDiagramProps, SequenceMessage, SequenceParticipant, SequenceStep } from "./sequence-diagram"; export { SchemaDiagram } from "./schema-diagram"; -export type { SchemaColumn, SchemaDiagramProps, SchemaTable } from "./schema-diagram"; +export type { DiagramCardinality, DiagramCardinalityPair, 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 index 41b451d5..6a272d58 100644 --- a/packages/react/src/schema-diagram.tsx +++ b/packages/react/src/schema-diagram.tsx @@ -2,11 +2,11 @@ import * as React from "react"; import { DiagramFigure } from "./diagram-figure"; import type { DiagramFigureProps } from "./diagram-figure"; -import type { SchemaTable } from "./diagram-core"; +import type { SchemaTable, DiagramPlacement, DiagramUnplaced } from "./diagram-core"; -export type { DiagramLegend, SchemaColumn, SchemaTable } from "./diagram-core"; +export type { DiagramCardinality, DiagramCardinalityPair, DiagramLegend, SchemaColumn, SchemaTable } from "./diagram-core"; -export interface SchemaDiagramProps extends DiagramFigureProps { +interface SchemaDiagramBase 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. @@ -14,8 +14,28 @@ export interface SchemaDiagramProps extends DiagramFigureProps { tables: SchemaTable[]; } +/** + * Authored (the default): every card carries its `col` and `row`. Automatic (`layout: "auto"`, DECISIONS 306, 1.8): no card needs them, and none are read. + */ +export type SchemaDiagramProps = Omit & ( + | { layout?: "authored"; direction?: never; placement?: never; tables: SchemaTable[] } + | { + /** + * `"auto"` (DECISIONS 306, 1.8): elkjs gives each card a column and a row, and Basalt sizes, routes and seats the figure as it does an authored one; a + * card's `col` and `row` are left out (and not read). Place at build time with `placeDiagram` from `@srasyndicate/basalt/diagram-layout` and pass + * `placement`: then elkjs never loads in the browser. Without it the layout module loads on demand at 640 or wider. + */ + layout: "auto"; + /** Under `"auto"`: the one direction tried. Left out, the type's own (right for an architecture and a schema, down for a flowchart), then the other. */ + direction?: "right" | "down"; + /** Under `"auto"`: `placeDiagram`'s answer for one direction or both. */ + placement?: DiagramPlacement | DiagramPlacement[]; + tables: Array>; + } +); + /** A database schema (DECISIONS 281): table cards with keys and a few columns; drawn, a line from each foreign key to the key it references. */ -export function SchemaDiagram({ tables, motion, title, heading, legend, ...props }: SchemaDiagramProps) { - const spec = React.useMemo(() => ({ type: "schema" as const, title, heading, legend, tables, motion }), [title, heading, legend, tables, motion]); - return ; +export function SchemaDiagram({ tables, motion, entrance, layout, direction, placement, title, heading, legend, ...props }: SchemaDiagramProps) { + const spec = React.useMemo(() => ({ type: "schema" as const, title, heading, legend, tables: tables as SchemaTable[], motion, entrance, layout, direction, placement }), [title, heading, legend, tables, motion, entrance, layout, direction, placement]); + return ; } diff --git a/packages/react/src/sequence-diagram.tsx b/packages/react/src/sequence-diagram.tsx index 157cbf36..8c4c55b5 100644 --- a/packages/react/src/sequence-diagram.tsx +++ b/packages/react/src/sequence-diagram.tsx @@ -2,9 +2,9 @@ import * as React from "react"; import { DiagramFigure } from "./diagram-figure"; import type { DiagramFigureProps } from "./diagram-figure"; -import type { SequenceParticipant, SequenceStep } from "./diagram-core"; +import type { SequenceParticipant, SequenceStep, DiagramFrameLabels } from "./diagram-core"; -export type { DiagramLegend, DiagramLineKind, SequenceParticipant, SequenceStep } from "./diagram-core"; +export type { DiagramFrameLabels, DiagramLegend, DiagramLineKind, SequenceMessage, SequenceParticipant, SequenceStep } from "./diagram-core"; export interface SequenceDiagramProps extends DiagramFigureProps { /** The participants, start to end. `short` names one in the stacked list. */ @@ -13,10 +13,14 @@ export interface SequenceDiagramProps extends DiagramFigureProps { steps: SequenceStep[]; /** Animated only: "Play the run" in the foot sends one packet through every message in order; while it runs it reads "Stop the run". */ run?: boolean; + /** The words for each frame operator and an alt's later branches (DECISIONS 306, 1.2): "Only if", "Repeats", "One of these", "Otherwise". */ + frameLabels?: DiagramFrameLabels; + /** `"text"` draws the same data as box-drawing characters in a code block, and a transcript where the art does not fit (1.2). Default `"drawn"`. */ + variant?: "drawn" | "text"; } /** A sequence diagram (DECISIONS 281): a head and a lifeline a participant, a 56px row a message; stacked, a numbered list. */ -export function SequenceDiagram({ participants, steps, run, motion, title, heading, legend, ...props }: SequenceDiagramProps) { - const spec = React.useMemo(() => ({ type: "sequence" as const, title, heading, legend, participants, steps, motion, run }), [title, heading, legend, participants, steps, motion, run]); - return ; +export function SequenceDiagram({ participants, steps, run, frameLabels, variant, motion, entrance, title, heading, legend, ...props }: SequenceDiagramProps) { + const spec = React.useMemo(() => ({ type: "sequence" as const, title, heading, legend, participants, steps, motion, entrance, run, frameLabels, variant }), [title, heading, legend, participants, steps, motion, entrance, run, frameLabels, variant]); + return ; } diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css index 97e519db..f712bded 100644 --- a/packages/react/src/styles/components.css +++ b/packages/react/src/styles/components.css @@ -4857,7 +4857,7 @@ } .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-gutter] > .basalt-diagram-drawing { --_gutter: var(--_gw, 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); @@ -4866,14 +4866,40 @@ .basalt-diagram[data-type="schema"] > .basalt-diagram-drawing { --_row-gap: var(--basalt-space-8); --_col-gap: var(--basalt-space-12); + /* Far keys' corridors (DECISIONS 306, 1.1): the engine writes spacer tracks round the author's rows (--_rows) on the drawn layout alone. */ + --_d-rows: var(--_drawn) var(--_rows, none); display: grid; grid-template-columns: var(--_d-cols, repeat(auto-fit, minmax(min(100%, var(--_track, var(--basalt-size-diagram-table))), 1fr))); + grid-template-rows: var(--_d-rows, none); gap: var(--_d-gap, var(--basalt-space-4)); align-items: start; max-width: none; } + /* A schema that draws cardinality marks (DECISIONS 306, 1.1): its column gap is space-12 plus space-3, so three lanes keep 18 from its tables. */ + .basalt-diagram[data-type="schema"][data-marks] > .basalt-diagram-drawing { --_col-gap: calc(var(--basalt-space-12) + var(--basalt-space-3)); } .basalt-diagram[data-type="sequence"] > .basalt-diagram-drawing { display: flex; gap: 0; } + /* Right to left (DECISIONS 306, 1.7): the engine lays out a mirrored model on a left-to-right grid, so the drawing is set left to right and what is in it + is set right to left again; identifiers are isolated left to right as runs, never as blocks, so they keep the card's start edge. */ + .basalt-diagram[data-rtl] > .basalt-diagram-drawing { direction: ltr; } + .basalt-diagram[data-rtl] > .basalt-diagram-drawing :is(.basalt-diagram-node > :not(.basalt-diagram-mark), .basalt-diagram-lane-name, .basalt-diagram-said, .basalt-diagram-note, .basalt-diagram-band, .basalt-diagram-fhead, .basalt-diagram-felse) { direction: rtl; } + .basalt-diagram[data-rtl] .basalt-diagram-gbox > .basalt-diagram-glabel { inset-inline: auto var(--basalt-space-3); } + /* Stacked, a group's label is on its start side too (the sweep's 66-3), its masking margin mirrored. */ + .basalt-diagram[data-rtl] .basalt-diagram-group > .basalt-diagram-glabel { inset-inline: auto var(--basalt-space-3); margin-inline: 0 calc(-1 * var(--basalt-space-1-5)); } + /* A Mono detail is one left-to-right run in a right-to-left card (B5 of the pixel review), so its words keep their order and the card's start edge. */ + .basalt-diagram[data-rtl] .basalt-diagram-runs { direction: ltr; unicode-bidi: isolate; } + /* A frame's header, its else row and its rule are set right to left, so their place across the mirrored grid is measured from the frame's end edge in + the grid's own coordinates (--_fl and --_fw are left-to-right): the tab is in the frame's top start corner, on the right. */ + .basalt-diagram[data-rtl] .basalt-diagram-fhead { inset-inline-start: calc(100% - var(--_fl) - var(--_fw) + var(--basalt-size-hairline)); } + .basalt-diagram[data-rtl] .basalt-diagram-felse { padding-inline-start: calc(100% - var(--_fl) - var(--_fw) + var(--basalt-space-3)); } + .basalt-diagram[data-rtl] .basalt-diagram-felse::before { inset-inline-start: var(--_d-fer, calc(-1 * var(--basalt-space-4))); } + /* A self-call's words beside its loop, by the loop's physical side (data-self is the grid's own, left to right), in a label set right to left. */ + .basalt-diagram[data-rtl] .basalt-diagram-msg[data-self="end"] :is(.basalt-diagram-said, .basalt-diagram-note) { --_d-sj: var(--_drawn) left; margin-inline-start: 0; margin-inline-end: var(--_d-sm, 0); } + .basalt-diagram[data-rtl] .basalt-diagram-msg[data-self="start"] :is(.basalt-diagram-said, .basalt-diagram-note) { --_d-sj: var(--_drawn) right; margin-inline-end: 0; margin-inline-start: var(--_d-sm, 0); } + .basalt-diagram[data-rtl] :is(.basalt-diagram-run, .basalt-diagram-mlabel, .basalt-diagram-tname, .basalt-diagram-cname, .basalt-diagram-ctype, .basalt-diagram-label, .basalt-diagram-glabel, .basalt-diagram-kind) { unicode-bidi: isolate; } + .basalt-diagram[data-rtl] :is(.basalt-diagram-run, .basalt-diagram-mlabel, .basalt-diagram-cname, .basalt-diagram-label) { direction: ltr; } + .basalt-diagram[data-rtl] .basalt-diagram-arrow { scale: -1 1; } + /* 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); @@ -4901,6 +4927,11 @@ 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); } + /* A card grows to hold its ports (DECISIONS 306, section 4, call 3): the least height at which every port is on the flat part of its side and + size-diagram-head from the next, drawn layout only. */ + .basalt-diagram-node { --_d-mh: var(--_drawn) var(--_mh, auto); min-height: var(--_d-mh, auto); } + /* Stacked, a node held taller than its words (the 44px touch floor) centres them on the block axis (the sweep's 66-1). */ + .basalt-diagram-node { --_d-jc: var(--_drawn) normal; justify-content: var(--_d-jc, center); } .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); } @@ -4935,6 +4966,12 @@ /* A mark with one form for both grounds may set --_ml alone (the skill writes it once): the dark form falls back to it. */ .basalt-diagram-node[data-focal] > .basalt-diagram-mark { --_mf: var(--_dkm) var(--_ml); background-image: var(--_mf, var(--_md, var(--_ml))); } .basalt-diagram-node[data-mark] > .basalt-diagram-mark + :is(.basalt-diagram-kind, .basalt-diagram-name) { padding-inline-end: var(--basalt-space-6); } + /* A participant's head centres its words: its first line keeps space-6 clear on both sides. Stacked, the chip draws the mark inline before the name, + space-1-5 apart; the focal chip takes the other theme's form, as the focal card does (DECISIONS 306, 1.6). */ + .basalt-diagram-node[data-shape="participant"][data-mark] > .basalt-diagram-mark + :is(.basalt-diagram-kind, .basalt-diagram-name) { padding-inline: var(--basalt-space-6); } + .basalt-diagram-node[data-shape="participant"] > .basalt-diagram-mark { --_d-pmp: var(--_drawn) absolute; position: var(--_d-pmp, static); flex: none; margin-inline-end: var(--_d-pmm, var(--basalt-space-1-5)); --_d-pmm: var(--_drawn) 0; } + .basalt-diagram-node[data-shape="participant"][data-mark] { --_d-pfd: var(--_drawn) column; flex-direction: var(--_d-pfd, row); } + .basalt-diagram-node[data-shape="participant"][data-mark] > .basalt-diagram-mark + .basalt-diagram-name { --_d-pnp: var(--_drawn) var(--basalt-space-6); padding-inline: var(--_d-pnp, 0); } /* 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); } @@ -4960,6 +4997,50 @@ .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 card that is a link (DECISIONS 306, 1.4): the card is the link and the figure's roving stop. Its cue is foundations' arrow (the core arrow-right, or + external for a new tab) at 16, space-1-5 after the name's last word, which it never leaves: secondary at rest (the focal card's quiet ink), primary + on hover and focus, travelling space-0-5. Hover and focus underline the name; a press is a colour step, never a scale. */ + .basalt-diagram-node[data-link] { color: inherit; text-decoration: none; -webkit-tap-highlight-color: transparent; } + .basalt-diagram-name-end { white-space: nowrap; } + .basalt-diagram-node[data-link] .basalt-diagram-name-end::after { + content: ""; + display: inline-block; + width: var(--basalt-size-icon-sm); + height: var(--basalt-size-icon-sm); + margin-inline-start: var(--basalt-space-1-5); + vertical-align: calc(-1 * var(--basalt-space-0-5)); + background: var(--basalt-text-secondary); + mask: url("%glyph-mask:arrow-right%") center / contain no-repeat; + transition: transform var(--basalt-duration-base) var(--basalt-ease-out), background-color var(--basalt-duration-base) var(--basalt-ease-out); + } + .basalt-diagram-node[data-link="external"] .basalt-diagram-name-end::after { mask-image: url("%glyph-mask:external%"); } + .basalt-diagram-node[data-link][data-focal] .basalt-diagram-name-end::after { background: var(--basalt-diagram-focal-ink); opacity: var(--basalt-opacity-amount); } + .basalt-diagram-node[data-link]:is(:hover, :focus-visible) .basalt-diagram-name-end::after { background: var(--basalt-text-primary); transform: translateX(var(--basalt-space-0-5)); } + .basalt-diagram-node[data-link][data-focal]:is(:hover, :focus-visible) .basalt-diagram-name-end::after { background: var(--basalt-diagram-focal-ink); opacity: 1; } + .basalt-diagram-node[data-link]:is(:hover, :focus-visible) :is(.basalt-diagram-name, .basalt-diagram-tname) { text-decoration: underline var(--basalt-size-hairline); text-underline-offset: var(--basalt-size-underline-offset); } + /* The press: the card's fill under state-hover's wash, one colour from color-mix at the token's own alpha (black 4% in light, white 6% in dark), as the + still table's pinned cells take theirs. */ + .basalt-diagram-node[data-link]:active { background: light-dark(color-mix(in srgb, var(--basalt-neutral-0) 4%, var(--_surface, var(--basalt-surface-1))), color-mix(in srgb, var(--basalt-neutral-100) 6%, var(--_surface, var(--basalt-surface-1)))); } + @supports not (color: light-dark(white, black)) { + .basalt-diagram-node[data-link]:active { background: color-mix(in srgb, color-mix(in srgb, var(--basalt-neutral-100) 6%, var(--_surface, var(--basalt-surface-1))) var(--_dkp), color-mix(in srgb, var(--basalt-neutral-0) 4%, var(--_surface, var(--basalt-surface-1)))); } + } + .basalt-diagram-node[data-link][data-focal]:active { background: var(--basalt-action-primary-press); } + .basalt-diagram-node[data-link]:dir(rtl) .basalt-diagram-name-end::after { scale: -1 1; } + .basalt-diagram-node[data-link]:dir(rtl):is(:hover, :focus-visible) .basalt-diagram-name-end::after { transform: translateX(calc(-1 * var(--basalt-space-0-5))); } + @media (prefers-reduced-motion: reduce) { + .basalt-diagram-node[data-link]:is(:hover, :focus-visible) .basalt-diagram-name-end::after, .basalt-diagram-node[data-link]:dir(rtl):is(:hover, :focus-visible) .basalt-diagram-name-end::after { transform: none; } + } + /* A card that answers a tap is at least size-tap-min tall on touch (1.5). */ + @media (pointer: coarse) { + .basalt-diagram-node[data-link] { min-height: var(--basalt-size-tap-min); } + } + @media (forced-colors: active) { + .basalt-diagram .basalt-diagram-node[data-link] :is(.basalt-diagram-name, .basalt-diagram-tname) { color: LinkText; text-decoration: underline; } + .basalt-diagram .basalt-diagram-node[data-link] .basalt-diagram-name-end::after { forced-color-adjust: none; background: LinkText; } + .basalt-diagram .basalt-diagram-node[data-link][data-focal] :is(.basalt-diagram-name, .basalt-diagram-tname) { color: Canvas; } + .basalt-diagram .basalt-diagram-node[data-link][data-focal] .basalt-diagram-name-end::after { background: Canvas; } + } + /* 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 { @@ -4973,21 +5054,30 @@ border: var(--basalt-size-hairline) dashed var(--basalt-diagram-structure); border-radius: var(--basalt-radius-lg); } + .basalt-diagram-group { --_tl: 0; } .basalt-diagram-group:first-child { margin-block-start: 0; } + .basalt-diagram-group[data-turn] { padding-block-start: calc(var(--basalt-space-12) + var(--basalt-space-4) * var(--_tl, 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); } + /* Stacked, a group's label sits on a ground plate over the lines, so a line that crosses it stops either side (DECISIONS 306, 1.3). */ + .basalt-diagram-group > .basalt-diagram-glabel { z-index: 1; margin-inline-start: calc(-1 * var(--basalt-space-1-5)); padding-inline: var(--basalt-space-1-5); background: var(--_ground); } .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)); + /* One level past the cells on each side, two where a child group reaches that side (DECISIONS 306, 1.3: --_gt, --_ge, --_gb, --_gs). */ + margin-block: calc(-1 * var(--_gt, 1) * var(--basalt-space-8)) calc(-1 * var(--_gb, 1) * var(--basalt-space-4)); + margin-inline: calc(-1 * var(--_gs, 1) * var(--basalt-space-4)) calc(-1 * var(--_ge, 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 nested group (1.3): space-4 inside its parent at the sides and below, space-8 below its top, radius 8. Its label is the merged label. */ + .basalt-diagram-gbox[data-depth="2"], .basalt-diagram-group[data-depth="2"] { border-radius: var(--basalt-radius-md); } + .basalt-diagram-list-group[data-depth="2"], .basalt-diagram-list-items[data-depth="2"] { margin-inline-start: var(--basalt-space-5); } /* 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; } @@ -4996,6 +5086,14 @@ /* 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; } + /* A sequence's layers (1.2: lifelines, frames, bars, lines, plates and labels): its ink and its steps are not layers of their own, so its lifelines sit + under its frames and its bars and lines over them, and every plate over those. */ + .basalt-diagram[data-type="sequence"] > .basalt-diagram-drawing > .basalt-diagram-ink { z-index: auto; } + .basalt-diagram-lifes { position: absolute; top: 0; left: 0; z-index: 0; overflow: visible; } + .basalt-diagram[data-type="sequence"] .basalt-diagram-ink > .basalt-diagram-svg { z-index: 2; } + .basalt-diagram[data-type="sequence"] .basalt-diagram-steps { z-index: auto; } + .basalt-diagram[data-type="sequence"] .basalt-diagram-msg :is(.basalt-diagram-said, .basalt-diagram-note) { position: relative; z-index: 3; } + .basalt-diagram[data-type="sequence"] :is(.basalt-diagram-fhead, .basalt-diagram-felse) { z-index: 3; } .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); } @@ -5010,6 +5108,10 @@ .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); } + /* Cardinality marks (DECISIONS 306, 1.1): 1px in the line's own ink, on a shaft that runs through them; a ring is filled with the ground so the + shaft does not show through it. */ + .basalt-diagram-crow { fill: none; stroke: var(--basalt-diagram-edge); stroke-width: var(--basalt-size-hairline); stroke-linecap: butt; stroke-linejoin: miter; transition: stroke var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram-ring { fill: var(--_ground); stroke: var(--basalt-diagram-edge); stroke-width: var(--basalt-size-hairline); transition: stroke var(--basalt-duration-fast) var(--basalt-ease-out); } .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); } @@ -5018,9 +5120,13 @@ .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); } + .basalt-diagram-edge[data-lit] :is(.basalt-diagram-crow, .basalt-diagram-ring) { stroke: var(--basalt-diagram-edge-main); } + .basalt-diagram-edge[data-dim] :is(.basalt-diagram-crow, .basalt-diagram-ring) { 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); } + /* A label of two lines (DECISIONS 306, 1.4): its author's break, both lines in one ink on one plate, each on a 16px line. */ + .basalt-diagram-label[data-lines="2"] { height: calc(2 * var(--basalt-text-xs-line-height)); } .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 @@ -5036,7 +5142,7 @@ padding: 0; list-style: none; } - .basalt-diagram-actor { display: flex; min-width: 0; } + .basalt-diagram-actor { --_d-ac: var(--_drawn) var(--_ac, auto); display: flex; min-width: 0; grid-column: var(--_d-ac, auto); grid-row: 1; } .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); @@ -5081,16 +5187,97 @@ --_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); } + /* Stacked, a row that follows a frame draws no divider: the frame's own edge parts them (P3 of the pixel review). */ + .basalt-diagram-frame + .basalt-diagram-msgs > .basalt-diagram-msg:first-child { border-top-color: transparent; } .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-route { --_d-rd: var(--_drawn) none; display: var(--_d-rd, inline-flex); grid-column: 2; align-items: center; column-gap: var(--basalt-space-1); row-gap: 0; flex-wrap: wrap; color: var(--basalt-text-secondary); } + /* The arrow and the name it points at are one unbreakable item, so a route that wraps breaks before the arrow (the sweep's 66-2). */ + .basalt-diagram-to { display: inline-flex; align-items: center; gap: var(--basalt-space-1); white-space: nowrap; } .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; } + /* An activation bar (DECISIONS 306, 1.2): size-diagram-activation wide, the head's fill inside a 1px structure edge, radius-2xs. Structure: whole from + an entrance's first frame, unchanged by a trace. */ + .basalt-diagram-bar { fill: var(--_surface, var(--basalt-surface-1)); stroke: var(--basalt-diagram-structure); stroke-width: var(--basalt-size-hairline); rx: var(--basalt-radius-2xs); } + /* A frame (1.2): a step that holds steps, structure and never a panel: no fill, no rim, no level; 1px solid structure, radius 12 (a frame inside a + frame radius 4, space-2 inside it on every side they share). Drawn, it spans its participants' columns, from the first's start edge to the last's + end edge; stacked, it is the same box round its rows. Its header is a 36px row: the tab (the operator) in the top start corner, then the label; + an alt's later branch starts under a dashed rule (4 on 4, exact) in a 28px row. Every word of a frame sits on a ground plate. */ + .basalt-diagram-frame { + --_d-fpi: var(--_drawn) 0; + --_cw: calc((100% - (var(--_cols, 1) - 1) * var(--basalt-space-5)) / var(--_cols, 1)); + --_d-fl: var(--_drawn) calc((var(--_a) - 1) * (var(--_cw) + var(--basalt-space-5)) + var(--_fis, 0) * var(--basalt-space-2)); + --_d-fw: var(--_drawn) calc((var(--_b) - var(--_a)) * (var(--_cw) + var(--basalt-space-5)) - var(--basalt-space-5) - (var(--_fis, 0) + var(--_fie, 0)) * var(--basalt-space-2)); + --_fl: var(--_d-fl, 0%); + --_fw: var(--_d-fw, 100%); + /* The else rule runs edge to edge of the frame (P2 of the pixel review): drawn, the frame's columns; stacked, the frame's whole box, past its padding. */ + --_d-fel: var(--_drawn) var(--_fl); + --_d-few: var(--_drawn) var(--_fw); + --_d-fer: var(--_drawn) calc(100% - var(--_fl) - var(--_fw)); + position: relative; + padding-block: var(--basalt-size-control-lg) var(--basalt-space-2); + padding-inline: var(--_d-fpi, var(--basalt-space-4)); + } + .basalt-diagram-frame + .basalt-diagram-frame { margin-block-start: var(--basalt-space-2); } + .basalt-diagram-frame[data-depth="2"] { --_d-fl: var(--_drawn) calc((var(--_a) - 1) * (var(--_cw) + var(--basalt-space-5)) + var(--_fis, 0) * var(--basalt-space-2)); } + .basalt-diagram-fbox { position: absolute; inset-block: 0; inset-inline-start: var(--_fl); z-index: 1; box-sizing: border-box; width: var(--_fw); border: var(--basalt-size-hairline) solid var(--basalt-diagram-structure); border-radius: var(--basalt-radius-lg); pointer-events: none; } + .basalt-diagram-frame[data-depth="2"] > .basalt-diagram-fbox { border-radius: var(--basalt-radius-xs); } + .basalt-diagram-fhead { position: absolute; top: var(--basalt-size-hairline); inset-inline-start: calc(var(--_fl) + var(--basalt-size-hairline)); display: flex; align-items: flex-start; gap: var(--basalt-space-3); margin: 0; white-space: nowrap; } + .basalt-diagram-ftab { padding: var(--basalt-space-1) var(--basalt-space-3); border-inline-end: var(--basalt-size-hairline) solid var(--basalt-diagram-structure); border-block-end: var(--basalt-size-hairline) solid var(--basalt-diagram-structure); border-end-end-radius: var(--basalt-radius-xs); background: var(--_ground); color: var(--basalt-text-primary); font: var(--basalt-font-weight-semibold) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); } + .basalt-diagram-flabel { margin-block-start: var(--basalt-space-1); margin-inline-start: calc(-1 * var(--basalt-space-1-5)); padding-inline: var(--basalt-space-1-5); background: var(--_ground); 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-felse { position: relative; display: flex; align-items: center; gap: var(--basalt-space-1-5); height: var(--basalt-size-control-sm); margin: 0; padding-inline-start: calc(var(--_fl) + var(--basalt-space-3)); white-space: nowrap; } + .basalt-diagram-felse::before { content: ""; position: absolute; top: 0; inset-inline-start: var(--_d-fel, calc(-1 * var(--basalt-space-4))); width: var(--_d-few, calc(100% + 2 * var(--basalt-space-4))); height: var(--basalt-size-hairline); background: var(--basalt-diagram-structure); mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 1' preserveAspectRatio='none'%3E%3Crect width='1' height='1'/%3E%3C/svg%3E") 0 0 / calc(2 * var(--basalt-size-diagram-guide-dash)) var(--basalt-size-hairline) repeat-x; } + .basalt-diagram-felse .basalt-diagram-flabel { margin-block-start: 0; margin-inline-start: 0; } + .basalt-diagram-fword { margin-inline-start: calc(-1 * var(--basalt-space-1-5)); padding-inline: var(--basalt-space-1-5); background: var(--_ground); 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-fword + .basalt-diagram-flabel { margin-inline-start: calc(-1 * var(--basalt-space-1-5)); } + .basalt-diagram-key-letters[data-op] { color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-semibold); } + /* A sequence as text (DECISIONS 306, 1.2): a code block (surface-sunken, the rim, radius 8, space-4 padding; Geist Mono text-xs on the code line height), + always left to right. The art where its widest line fits, the transcript where it does not: nothing scrolls sideways, and a transcript's line breaks + between participants and words, never inside a name. Inks: the focal participant primary 600, others secondary; lifelines tertiary, a working stretch + secondary; a main arrow primary, plain and dashed secondary; labels primary; numbers, notes and frames tertiary, the operator primary 600. */ + .basalt-diagram-text { + box-sizing: border-box; + margin: 0; + padding: var(--basalt-space-4); + overflow: hidden; + border: var(--basalt-size-hairline) solid var(--basalt-border-rim); + border-top-color: var(--basalt-border-rim-top); + border-radius: var(--basalt-radius-md); + background: var(--basalt-surface-sunken); + color: var(--basalt-text-secondary); + direction: ltr; + font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-size-code-line-height) var(--basalt-font-family-mono); + white-space: pre-wrap; + overflow-wrap: break-word; + } + .basalt-diagram-text[data-art] { white-space: pre; overflow-wrap: normal; } + .basalt-diagram-drawing:has(> .basalt-diagram-text) { max-width: none; } + /* The art's code element is the block's text, never an inline code chip: a page's own code style (the skill's core gives inline code a fill) would band + every row (P-R2 of the code re-check). */ + .basalt-diagram-text .basalt-diagram-text-ink { font: inherit; padding: 0; border: 0; border-radius: 0; background: none; color: inherit; } + .basalt-diagram-tx-name, .basalt-diagram-tx-to { white-space: nowrap; color: var(--basalt-text-primary); } + /* A transcript's line (B6 of the pixel review): a block indented by its frame, its message's lines hanging under the sender. */ + .basalt-diagram-tx-line { + display: block; + /* stylelint-disable-next-line unit-disallowed-list -- characters of the Mono transcript: its indents are counted in characters, as the art's columns are */ + padding-inline-start: calc(var(--_in, 0) * 1ch); + /* stylelint-disable-next-line unit-disallowed-list -- characters of the Mono transcript: the number's width before the sender it hangs under */ + text-indent: calc(-1 * var(--_hang, 0) * 1ch); + } + .basalt-diagram-text [data-ink="focal"], .basalt-diagram-text [data-ink="op"] { color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-semibold); } + .basalt-diagram-text :is([data-ink="name"], [data-ink="working"], [data-ink="plain"]) { color: var(--basalt-text-secondary); } + .basalt-diagram-text :is([data-ink="main"], [data-ink="label"]) { color: var(--basalt-text-primary); } + .basalt-diagram-text :is([data-ink="life"], [data-ink="num"], [data-ink="note"], [data-ink="frame"], [data-ink="band"]) { color: var(--basalt-text-tertiary); } + .basalt-diagram-key-glyph { font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-mono); color: var(--basalt-text-secondary); } + .basalt-diagram-key-glyph[data-ink="main"] { color: var(--basalt-text-primary); } + .basalt-diagram-key-glyph[data-ink="focal"] { color: var(--basalt-text-primary); font-weight: var(--basalt-font-weight-semibold); } + @media (forced-colors: active) { .basalt-diagram-text :is([data-ink]) { color: CanvasText; } } + /* 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); @@ -5136,6 +5323,13 @@ .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); } + /* On touch (DECISIONS 306, 1.5), where lines are drawn, the hint's seat says how to trace; nowhere else. */ + .basalt-diagram-tap-hint { display: none; 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[data-touch][data-layout="drawn"] > .basalt-diagram-tap-hint, .basalt-diagram[data-touch][data-layout="stacked"]:not([data-bare], [data-type="sequence"], [data-type="schema"]) > .basalt-diagram-tap-hint { display: block; } + .basalt-diagram[data-touch] > .basalt-diagram-hint { display: none; } + /* A card that answers a tap is at least size-tap-min tall on touch. */ + .basalt-diagram[data-touch] .basalt-diagram-node { min-height: var(--basalt-size-tap-min); } + @media (pointer: coarse) { .basalt-diagram-clear { min-height: var(--basalt-size-tap-min); } } .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; } @@ -5157,7 +5351,7 @@ .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; } + .basalt-diagram-node, .basalt-diagram-line, .basalt-diagram-tip, .basalt-diagram-crow, .basalt-diagram-ring, .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; } @@ -5170,11 +5364,15 @@ /* 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]):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: ; } } + @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"]:not([data-marks])) > .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]):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 -- an architecture of 4 columns with three group levels at its sides (DECISIONS 306, 1.3): 4 × 144 + 3 × 64 + 3 × 16 = 816px */ + @container (width >= 816px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="3"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 4 columns with four group levels at its sides: 4 × 144 + 3 × 64 + 4 × 16 = 832px */ + @container (width >= 832px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="4"][data-reach="4"] > .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 */ @@ -5185,8 +5383,12 @@ @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 -- an architecture of 5 columns with three group levels at its sides: 5 × 144 + 4 × 64 + 3 × 16 = 1024px */ + @container (width >= 1024px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="3"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 5 columns with four group levels: 5 × 144 + 4 × 64 + 4 × 16 = 1040px */ + @container (width >= 1040px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="5"][data-reach="4"] > .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: ; } } + @container (width >= 1040px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="4"]:not([data-marks]) > .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 */ @@ -5195,12 +5397,25 @@ @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 -- an architecture of 6 columns with three group levels at its sides: 6 × 144 + 5 × 64 + 3 × 16 = 1232px */ + @container (width >= 1232px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="3"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- an architecture of 6 columns with four group levels at its sides: 6 × 144 + 5 × 64 + 4 × 16 = 1248px */ + @container (width >= 1248px) { .basalt-diagram:not([data-layout])[data-type="architecture"][data-cols="6"][data-reach="4"] > .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: ; } } + @container (width >= 1312px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="5"]:not([data-marks]) > .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: ; } } + @container (width >= 1584px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-cols="6"]:not([data-marks]) > .basalt-diagram-drawing { --_drawn: ; } } + /* A schema that draws cardinality marks has gaps of space-12 plus space-3 (60, DECISIONS 306, 1.1); two columns are under the 640 floor. */ + /* stylelint-disable-next-line basalt/container-length -- a marked schema of 3: 3 × size-diagram-table (224) + 2 × 60 = 792px */ + @container (width >= 792px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-marks][data-cols="3"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a marked schema of 4: 4 × 224 + 3 × 60 = 1076px */ + @container (width >= 1076px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-marks][data-cols="4"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a marked schema of 5: 5 × 224 + 4 × 60 = 1360px */ + @container (width >= 1360px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-marks][data-cols="5"] > .basalt-diagram-drawing { --_drawn: ; } } + /* stylelint-disable-next-line basalt/container-length -- a marked schema of 6: 6 × 224 + 5 × 60 = 1644px */ + @container (width >= 1644px) { .basalt-diagram:not([data-layout])[data-type="schema"][data-marks][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. */ @@ -5212,7 +5427,7 @@ @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-svg, .basalt-diagram-lifes, .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; } @@ -5222,6 +5437,11 @@ .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; } + /* Cardinality marks follow their line; a ring's fill is Canvas (DECISIONS 306, 1.10). */ + .basalt-diagram :is(.basalt-diagram-crow, .basalt-diagram-ring) { stroke: CanvasText; } + .basalt-diagram .basalt-diagram-ring { fill: Canvas; } + .basalt-diagram .basalt-diagram-edge[data-dim] :is(.basalt-diagram-crow, .basalt-diagram-ring) { stroke: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-lit] :is(.basalt-diagram-crow, .basalt-diagram-ring) { 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; } @@ -5247,6 +5467,12 @@ .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; } + /* An activation bar's edge carries "working" (CanvasText), its fill Canvas; a frame's edges and its else rule are GrayText, its words CanvasText + on Canvas plates (DECISIONS 306, 1.10). */ + .basalt-diagram .basalt-diagram-bar { fill: Canvas; stroke: CanvasText; } + .basalt-diagram .basalt-diagram-fbox, .basalt-diagram .basalt-diagram-ftab { border-color: GrayText; } + .basalt-diagram .basalt-diagram-felse::before { background: GrayText; } + .basalt-diagram :is(.basalt-diagram-ftab, .basalt-diagram-flabel, .basalt-diagram-fword) { color: CanvasText; background: Canvas; } /* No mark is drawn, and the first line keeps no padding for one (DECISIONS 292, 2.7): the card's words name the service. */ .basalt-diagram .basalt-diagram-mark { display: none; } .basalt-diagram .basalt-diagram-node[data-mark] > .basalt-diagram-mark + :is(.basalt-diagram-kind, .basalt-diagram-name) { padding-inline-end: 0; } @@ -5254,8 +5480,45 @@ /* Print: the lines, the key's swatches, a card's mark and every focal node's fill print whatever the reader's "Background graphics" setting (DECISIONS 292, 2.6; every focal node, with a mark or without, DECISIONS 298). */ @media print { - .basalt-diagram-svg, .basalt-diagram-swatch, .basalt-diagram-arrow, .basalt-diagram-mark, .basalt-diagram-node[data-focal] { -webkit-print-color-adjust: exact; print-color-adjust: exact; } - .basalt-diagram-hint { display: none; } + .basalt-diagram-svg, .basalt-diagram-lifes, .basalt-diagram-swatch, .basalt-diagram-arrow, .basalt-diagram-mark, .basalt-diagram-node[data-focal] { -webkit-print-color-adjust: exact; print-color-adjust: exact; } + .basalt-diagram-hint, .basalt-diagram-tap-hint, .basalt-diagram-clear, .basalt-diagram-download { display: none !important; } + /* A figure prints untraced (DECISIONS 306, 1.7): every line, head and label in its resting ink, over a trace, a touch trace or a quiet run. */ + .basalt-diagram .basalt-diagram-edge :is(.basalt-diagram-line, .basalt-diagram-tip[data-open]) { stroke: var(--basalt-diagram-edge) !important; } + .basalt-diagram .basalt-diagram-edge .basalt-diagram-line[data-kind="main"] { stroke: var(--basalt-diagram-edge-main) !important; } + .basalt-diagram .basalt-diagram-edge :is(.basalt-diagram-tip:not([data-open]), .basalt-diagram-dot) { fill: var(--basalt-diagram-edge) !important; } + .basalt-diagram .basalt-diagram-edge .basalt-diagram-tip[data-kind="main"]:not([data-open]) { fill: var(--basalt-diagram-edge-main) !important; } + .basalt-diagram .basalt-diagram-edge :is(.basalt-diagram-crow, .basalt-diagram-ring) { stroke: var(--basalt-diagram-edge) !important; } + .basalt-diagram .basalt-diagram-label { color: var(--basalt-diagram-edge) !important; } + } + + /* While a figure is read for a file (diagram-export), nothing in it transitions, so a theme it is read in applies at once. */ + .basalt-exporting, .basalt-exporting * { transition: none !important; } + + /* A run's unreached messages are quiet (DECISIONS 306, 1.2): label secondary, line and head diagram-edge-dim; number and note unchanged. Stopping, + finishing, printing or tracing restores them at once; the ink changes over duration-fast on ease-out. No opacity. */ + .basalt-diagram-msg[data-ahead] .basalt-diagram-mlabel { color: var(--basalt-text-secondary); transition: color var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-diagram-edge[data-ahead] .basalt-diagram-line { stroke: var(--basalt-diagram-edge-dim); } + .basalt-diagram-edge[data-ahead] .basalt-diagram-tip:not([data-open]) { fill: var(--basalt-diagram-edge-dim); } + .basalt-diagram-edge[data-ahead] .basalt-diagram-tip[data-open] { stroke: var(--basalt-diagram-edge-dim); } + /* The text art's run and its build (1.2): an unreached message's label secondary and its arrow tertiary, the current one's number primary; before the build + reaches a message (pending), the same quiet. */ + .basalt-diagram-text [data-n][data-ahead] [data-ink="label"], .basalt-diagram[data-motion="animated"][data-entrance="pending"] .basalt-diagram-text [data-n] [data-ink="label"] { color: var(--basalt-text-secondary); } + .basalt-diagram-text [data-n][data-ahead] :is([data-ink="main"], [data-ink="plain"]), .basalt-diagram[data-motion="animated"][data-entrance="pending"] .basalt-diagram-text [data-n] :is([data-ink="main"], [data-ink="plain"]) { color: var(--basalt-text-tertiary); } + .basalt-diagram-text [data-n][data-arrival] [data-ink="num"] { color: var(--basalt-text-primary); } + @media (prefers-reduced-motion: reduce) { + .basalt-diagram-msg[data-ahead] .basalt-diagram-mlabel { transition: none; } + } + @media (forced-colors: active) { + .basalt-diagram .basalt-diagram-msg[data-ahead] .basalt-diagram-mlabel { color: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-ahead] .basalt-diagram-line { stroke: GrayText; } + /* The head goes with its line (Neon's B7 of the code review). */ + .basalt-diagram .basalt-diagram-edge[data-ahead] .basalt-diagram-tip:not([data-open]) { fill: GrayText; } + .basalt-diagram .basalt-diagram-edge[data-ahead] .basalt-diagram-tip[data-open] { stroke: GrayText; } + .basalt-diagram .basalt-diagram-text [data-n][data-ahead] [data-ink] { color: GrayText; } + .basalt-diagram .basalt-diagram-text [data-n][data-arrival] [data-ink="num"] { color: Highlight; } + } + @media print { + .basalt-diagram .basalt-diagram-msg[data-ahead] .basalt-diagram-mlabel { color: var(--basalt-text-primary) !important; } } /* ---- Diagram motion (DECISIONS 292): the entrance, flow, the pulse, the packet, the arrival step and the foot's two buttons ---- @@ -5316,6 +5579,127 @@ .basalt-diagram :is(.basalt-diagram-flow, .basalt-diagram-bead, .basalt-diagram-packet, .basalt-diagram-motion-defs) { display: none !important; } } + /* ---- Diagram viewer (DECISIONS 310; part 9 of DECISIONS 301): "Expand", and the dialog where a figure's drawn layout is zoomed and panned ---- + The form dialog's box with the sheet's head, body and foot (DECISIONS 155, 222): from 720 the window less space-4 on every side, under it the whole + window. The body is the stage: it scrolls both ways, so a pan is a scroll. The figure in it is laid out once at 100% (the layer's width) and zoomed + with one transform: never a viewBox, CSS zoom, a canvas or a picture, and no layer is held (no will-change). Nothing in it moves: a zoom step lands + at once. Decided by the council's decider alone; no draft, check or position. The implementation hasn't been reviewed. */ + @media (pointer: coarse) { + .basalt-diagram-expand { min-height: var(--basalt-size-tap-min); } + } + /* From 720 the window less space-4 on every side; under it the form dialog's full-screen modal, unchanged. */ + /* stylelint-disable-next-line unit-disallowed-list -- size-breakpoint-md (720px): a media query cannot read a token */ + @media (width >= 720px) { + /* stylelint-disable-next-line unit-disallowed-list -- the window less space-4 on every side (viewport units); a fixed-length token cannot say it */ + .basalt-dialog[data-form].basalt-diagram-viewer, .basalt-dialog[data-form][data-held].basalt-diagram-viewer { width: calc(100vw - 2 * var(--basalt-space-4)); max-width: none; height: calc(100dvh - 2 * var(--basalt-space-4)); max-height: none; } + } + .basalt-diagram-viewer .basalt-sheet-head { flex: none; } + .basalt-diagram-viewer-source { overflow-wrap: break-word; } + .basalt-diagram-stage { + /* The stage's padding round the drawing (9.4), the travel that makes a press a drag (space-1), the margin a focused card keeps from the edge (space-4), + and the rest before the zoom is spoken (duration-slower), read by the script. */ + --_pad: var(--basalt-space-4); + --_travel: var(--basalt-space-1); + --_clear: var(--basalt-space-4); + --_rest: var(--basalt-duration-slower); + position: relative; + flex: 1 1 auto; + display: flex; + min-height: 0; + overflow: auto; + overscroll-behavior: contain; + scrollbar-gutter: stable; + touch-action: none; + outline: none; + } + /* stylelint-disable-next-line unit-disallowed-list -- size-breakpoint-md (720px): a media query cannot read a token */ + @media (width >= 720px) { .basalt-diagram-stage { --_pad: var(--basalt-space-6); } } + /* The flush field's ring: the stage meets the dialog's clipping edges, so its ring is inset at -2. */ + .basalt-diagram-stage:focus-visible { outline: var(--basalt-size-focus-width) solid var(--basalt-border-focus); outline-offset: calc(-1 * var(--basalt-size-focus-width)); } + .basalt-diagram-stage[data-pannable] { cursor: grab; } + .basalt-diagram-stage[data-pannable][data-dragging] { cursor: grabbing; } + /* The list is the page's list, in the stage at 100%: ordinary touch scrolling, its words selectable. */ + .basalt-diagram-stage[data-list] { display: block; touch-action: pan-y; } + .basalt-diagram-probe { position: absolute; top: 0; left: 0; height: 0; visibility: hidden; pointer-events: none; } + .basalt-diagram-probe[data-probe="row"] { width: calc(var(--basalt-size-page-width) - 2 * var(--basalt-size-gutter)); } + .basalt-diagram-probe[data-probe="contain"] { width: var(--basalt-size-breakpoint-container); } + /* The sizer is as large as the zoomed drawing, plus the padding; its auto margins centre a drawing smaller than the stage and resolve to 0 past it. */ + .basalt-diagram-sizer { position: relative; flex: none; box-sizing: content-box; margin: auto; padding: var(--_pad); } + .basalt-diagram-sizer[hidden] { display: none; } + .basalt-diagram-layer { position: absolute; top: var(--_pad); inset-inline-start: var(--_pad); transform-origin: 0 0; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; } + .basalt-diagram-layer:dir(rtl) { transform-origin: 100% 0; } + /* The viewer's figure shows its drawing alone: the dialog holds its title, its key, its hint and its controls. */ + .basalt-diagram[data-viewer] { gap: 0; } + .basalt-diagram[data-viewer] > :is(.basalt-diagram-head, .basalt-diagram-key, .basalt-diagram-hint, .basalt-diagram-tap-hint, .basalt-diagram-foot, .basalt-diagram-list, .basalt-diagram-summary) { display: none; } + .basalt-diagram-viewer-list { box-sizing: border-box; max-width: calc(var(--basalt-size-page-width) - 2 * var(--basalt-size-gutter) + 2 * var(--_pad)); padding: var(--_pad); } + .basalt-diagram-viewer-foot { display: flex; flex-direction: column; gap: var(--basalt-space-3); padding-block-start: var(--basalt-space-3); } + .basalt-diagram-viewer-key { --_ground: var(--_surface, var(--basalt-surface-overlay)); } + .basalt-diagram-viewer-key .basalt-diagram-key { padding-block-start: 0; border-top: 0; } + .basalt-diagram-viewer-key[data-layout="drawn"] .basalt-diagram-entry[data-when="stacked"], .basalt-diagram-viewer-key[data-layout="stacked"] .basalt-diagram-entry[data-when="drawn"], .basalt-diagram-viewer-key[data-bare] .basalt-diagram-entry[data-line] { display: none; } + .basalt-diagram-viewer-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--basalt-space-2); } + .basalt-diagram-zoom { display: flex; align-items: center; gap: var(--basalt-space-1); } + /* The level between the two buttons, its width held for "400%" so the buttons never move. */ + .basalt-diagram-level { display: inline-grid; justify-items: center; 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); font-variant-numeric: tabular-nums; } + .basalt-diagram-level::before { content: attr(data-reserve); grid-area: 1 / 1; visibility: hidden; } + .basalt-diagram-level > span { grid-area: 1 / 1; } + .basalt-diagram-viewer-hint { flex: 1 1 auto; min-width: 0; } + .basalt-diagram-viewer-end { display: flex; gap: var(--basalt-space-2); margin-inline-start: auto; } + @media (pointer: coarse) { + .basalt-diagram-zoom .basalt-button, .basalt-diagram-viewer-end .basalt-button { min-height: var(--basalt-size-tap-min); min-width: var(--basalt-size-tap-min); } + } + @media (forced-colors: active) { + .basalt-diagram-level { color: CanvasText; } + .basalt-diagram-viewer-foot [aria-disabled="true"] { color: GrayText; } + } + /* The viewer and its scrim do not print: the page prints its own figure, untraced and light. "Expand" does not print. */ + @media print { + /* With no transition: a display transition (the dialog's own, allow-discrete) would hold it on screen past the change. */ + .basalt-diagram-expand, .basalt-diagram-viewer { display: none !important; transition: none !important; } + } + + /* ---- Diagram viewer, React's dialog (DECISIONS 310): the form dialog's box on a native modal , as the HTML skill's is ---- + Base UI's dialog is not imported by the viewer's chunk (it would widen the Base UI chunk every component shares), so the box's motion is written here for + the native element: from 720 a scale from .98 and a fade over duration-slow, under it the sheet's rise over duration-slower, each out at three quarters on + ease-in, and a fade alone under reduced motion. The scrim is its ::backdrop. The page behind does not scroll while it is open. */ + dialog.basalt-dialog.basalt-diagram-viewer { + --_out: calc(var(--basalt-duration-slow) * 0.75); + margin: 0; + /* The rim stays (the form dialog's own, B4 of the pixel review): only the browser's dialog margin and its inline and block insets are reset, so the box is + placed by its top and left in either direction (right to left, the browser's inset-inline-end would otherwise win and push it off the window). */ + right: auto; + bottom: auto; + max-width: none; + max-height: none; + opacity: 0; + transform: translate(-50%, -50%) scale(0.98); + transition-property: opacity, transform, overlay, display; + transition-behavior: allow-discrete; + transition-duration: var(--_out); + transition-timing-function: var(--basalt-ease-in); + } + dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 1; transform: translate(-50%, -50%); transition-duration: var(--basalt-duration-slow); transition-timing-function: var(--basalt-ease-out); } + @starting-style { dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 0; transform: translate(-50%, -50%) scale(0.98); } } + dialog.basalt-dialog.basalt-diagram-viewer::backdrop { background: var(--basalt-scrim); opacity: 0; transition: opacity var(--_out) var(--basalt-ease-in), overlay var(--_out) allow-discrete, display var(--_out) allow-discrete; } + dialog.basalt-dialog.basalt-diagram-viewer[open]::backdrop { opacity: 1; transition-duration: var(--basalt-duration-slow); transition-timing-function: var(--basalt-ease-out); } + @starting-style { dialog.basalt-dialog.basalt-diagram-viewer[open]::backdrop { opacity: 0; } } + :root:has(dialog.basalt-diagram-viewer[open]) { overflow: hidden; } + /* stylelint-disable-next-line unit-disallowed-list -- size-breakpoint-md (720px): a media query cannot read a token */ + @media (width < 720px) { + dialog.basalt-dialog.basalt-diagram-viewer { --_out: calc(var(--basalt-duration-slower) * 0.75); opacity: 1; transform: translateY(100%); } + dialog.basalt-dialog.basalt-diagram-viewer[open] { transform: none; transition-duration: var(--basalt-duration-slower); } + @starting-style { dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 1; transform: translateY(100%); } } + } + @media (prefers-reduced-motion: reduce) { + dialog.basalt-dialog.basalt-diagram-viewer, dialog.basalt-dialog.basalt-diagram-viewer[open] { transform: translate(-50%, -50%); } + @starting-style { dialog.basalt-dialog.basalt-diagram-viewer[open] { transform: translate(-50%, -50%); } } + } + /* stylelint-disable-next-line unit-disallowed-list -- size-breakpoint-md (720px): a media query cannot read a token */ + @media (width < 720px) and (prefers-reduced-motion: reduce) { + dialog.basalt-dialog.basalt-diagram-viewer, dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 0; transform: none; } + dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 1; } + @starting-style { dialog.basalt-dialog.basalt-diagram-viewer[open] { opacity: 0; transform: 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-checks.test.mjs b/packages/react/test/diagram-checks.test.mjs new file mode 100644 index 00000000..ceb9b72b --- /dev/null +++ b/packages/react/test/diagram-checks.test.mjs @@ -0,0 +1,62 @@ +// 5.1's development checks after the decider's ruling 1 on the batch B re-check: the first list is reported as an error (Model.errors, which the figure +// reports with console.error once and the skill with console.error), the second as a warning, and the figure is drawn as production draws it: the same +// markup with the checks on or off. Node only: the engine's model and its markup, from the built package. The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import path from "node:path"; +import { test } from "node:test"; +import { pathToFileURL } from "node:url"; + +const pkg = path.join(path.dirname(new URL(import.meta.url).pathname), ".."); +const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + +const seq = (steps, extra = {}) => ({ type: "sequence", title: "t", summary: "s", participants: [{ id: "a", name: "A" }, { id: "b", name: "B" }], steps, ...extra }); +const arch = (extra) => ({ type: "architecture", title: "t", summary: "s", nodes: [{ id: "a", name: "A", col: 1, row: 1 }, { id: "b", name: "B", col: 2, row: 1 }], edges: [], ...extra }); +const schema = (columns) => ({ type: "schema", title: "t", summary: "s", tables: [{ name: "a", col: 1, row: 1, columns }, { name: "b", col: 2, row: 1, columns: [{ name: "id", key: "PK" }, { name: "k" }] }] }); + +// Each item of 5.1's first list, with the words its error says. +const FIRST = [ + ["cardinality without references", schema([{ name: "x", cardinality: { from: "one" } }]), /states a cardinality but references nothing/], + ["a cardinality that is not a form", schema([{ name: "x", key: "FK", references: "b.id", cardinality: { from: "many" } }]), /not one, zero-or-one, one-or-many or zero-or-many/], + ["a referenced end of many", schema([{ name: "x", key: "FK", references: "b.id", cardinality: { from: "one", to: "one-or-many" } }]), /references one row at most/], + ["cardinality on some keys and not all", schema([{ name: "x", key: "FK", references: "b.id", cardinality: { from: "one" } }, { name: "y", key: "FK", references: "b.k" }]), /stated on 1 of 2 foreign keys/], + ["a deactivate with no open bar", seq([{ from: "a", to: "b", label: "x", deactivate: true }]), /has none open/], + ["a fourth nested bar", seq([1, 2, 3, 4].map((n) => ({ from: "a", to: "b", label: String(n), activate: true }))), /fourth bar/], + ["an alt with one branch", seq([{ frame: "alt", branches: [{ label: "one", steps: [{ from: "a", to: "b", label: "x" }] }] }]), /one branch/], + ["an empty frame", seq([{ frame: "opt", label: "o", steps: [] }]), /is empty/], + ["a third frame level", seq([{ frame: "opt", label: "o", steps: [{ frame: "opt", label: "p", steps: [{ frame: "opt", label: "q", steps: [{ from: "a", to: "b", label: "x" }] }] }] }]), /frame is a third level/], + ["a band in a frame", seq([{ frame: "opt", label: "o", steps: [{ band: "phase" }, { from: "a", to: "b", label: "x" }] }]), /is inside a frame/], + ["a frame label past 40 characters", seq([{ frame: "opt", label: "x".repeat(41), steps: [{ from: "a", to: "b", label: "x" }] }]), /over 40 characters/], + ["a third group level", arch({ groups: [{ id: "g", label: "G" }, { id: "h", label: "H", parent: "g" }, { id: "i", label: "I", parent: "h" }] }), /is a third level: groups nest two deep/], + ["an unknown parent", arch({ groups: [{ id: "g", label: "G", parent: "nope" }] }), /which is not a group/], + ["a cycle of groups", arch({ groups: [{ id: "g", label: "G", parent: "h" }, { id: "h", label: "H", parent: "g" }] }), /each other's parent/], + ["a label with two breaks", arch({ edges: [{ from: "a", to: "b", label: "one\ntwo\nthree" }] }), /more than one break/], + ["a label line past 28 characters", arch({ edges: [{ from: "a", to: "b", label: "x".repeat(29) }] }), /over 28 characters/], + ["a break in a sequence's label", seq([{ from: "a", to: "b", label: "one\ntwo" }]), /label has a break/], + ["an empty href", arch({ nodes: [{ id: "a", name: "A", col: 1, row: 1, href: " " }] }), /href is empty/], + ["an href on a participant", seq([{ from: "a", to: "b", label: "x" }], { participants: [{ id: "a", name: "A", href: "#x" }, { id: "b", name: "B" }] }), /cannot be a link/], + ["layout auto on a sequence", seq([{ from: "a", to: "b", label: "x" }], { layout: "auto" }), /layout="auto" is for/], +]; + +for (const [what, spec, words] of FIRST) test(`5.1's first list: ${what} is an error, not a warning, and the markup is production's`, () => { + const m = core.buildModel(spec); + assert.equal(m.errors.filter((e) => words.test(e)).length, 1, `${what}: ${JSON.stringify(m.errors)}`); + assert.ok(!m.warnings.some((w) => words.test(w)), `${what} is not also a warning`); + const html = (model) => core.toHtml(core.figureTree(model, {}, { prefix: "basalt-diagram", base: "dg1", hasSource: false, hiddenClass: "basalt-visually-hidden" })); + assert.equal(html(m), html(core.buildModel(spec, { checks: false })), "drawn as production draws it"); +}); + +test("5.1's second list stays a warning: a far key not drawn, a card grown to hold its ports, more than 100 cards", () => { + const n = (id, col, row) => ({ id, name: id, kind: "part", col, row }); + const grown = core.buildModel({ type: "architecture", title: "t", summary: "s", nodes: [n("a", 1, 1), n("b", 2, 1), n("c", 2, 2), n("d", 2, 3)], edges: [{ from: "a", to: "b" }, { from: "a", to: "c" }, { from: "a", to: "d" }] }); + assert.ok(grown.warnings.some((w) => /use another side/.test(w))); + assert.deepEqual(grown.errors, []); + const big = core.buildModel({ type: "architecture", title: "t", summary: "s", nodes: Array.from({ length: 101 }, (_, k) => n(`n${k}`, (k % 10) + 1, Math.floor(k / 10) + 1)), edges: [] }); + assert.ok(big.warnings.some((w) => /101 cards/.test(w))); + assert.deepEqual(big.errors, []); +}); + +test("the extended CIMIP figures report no error", async () => { + const fs = await import("node:fs"); + const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); + for (const [key, spec] of Object.entries(B)) assert.deepEqual(core.buildModel(spec).errors, [], key); +}); diff --git a/packages/react/test/diagram-fixes.test.mjs b/packages/react/test/diagram-fixes.test.mjs index 88a364bd..dadb2d7e 100644 --- a/packages/react/test/diagram-fixes.test.mjs +++ b/packages/react/test/diagram-fixes.test.mjs @@ -97,7 +97,7 @@ describe("slots on a side (Neon's finding 13)", () => { describe("the development checks cost production nothing (Neon's finding 14)", () => { // Phrases only the checks write (a property name such as `crossings` is code, not a check's words). const WORDS = ["share the cell at column", "main lines are drawn but", "is not a kind of line", "more than three is an error", "would leave the drawing", "in the drawn layout", - "third end lane", "stands for", "is used twice", "two columns apart", "closer than space-3"]; + "fifth end lane", "stands for", "is used twice", "a third lane in its corridor", "closer than space-3", "states a cardinality but references nothing"]; const bundle = async (entry, mode) => (await esbuild.build({ stdin: { contents: entry, resolveDir: pkg, loader: "js" }, bundle: true, minify: true, format: "esm", write: false, logLevel: "silent", external: ["react", "react-dom", "react/jsx-runtime"], define: { "process.env.NODE_ENV": JSON.stringify(mode) }, @@ -119,7 +119,7 @@ describe("the development checks cost production nothing (Neon's finding 14)", ( test("the motion module's production build holds none of its checks' words", async () => { const entry = `import { motionErrors } from "./dist/diagram-motion.js"; console.log(motionErrors);`; const [prod, dev] = [await bundle(entry, "production"), await bundle(entry, "development")]; - for (const w of ["names both a pulse and a packet", "flows but has no label", "is dashed and flows", "no line joins them in that direction"]) { + for (const w of ["names both a pulse and a packet", "flows but has no label", "no line joins them in that direction"]) { assert.ok(!prod.includes(w), `production holds "${w}"`); assert.ok(dev.includes(w), `development lacks "${w}"`); } @@ -198,3 +198,68 @@ describe("a decision no taller than it is wide (Fable's polish P4)", () => { await page.close(); }); }); + +describe("section 4's three calls (DECISIONS 306; Neon's B12 of the code review)", () => { + test("call 1: from its first drawn width the CIMIP flowchart is drawn at every whole width to 1,440, and no decision is taller than it is wide", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "flow", spec: DATA.flowchart }]); + let first = null; + const off = []; + for (let w = 930; w <= 1440; w++) { + await page.evaluate((w) => document.getElementById("root").style.setProperty("--w", `${w}px`), w); + await frames(page, 2); + const layout = await page.getAttribute("#fig-flow", "data-layout"); + if (layout === "drawn") { + first ??= w; + const tall = await page.evaluate(() => [...document.querySelectorAll("#fig-flow .basalt-diagram-node[data-shape='decision']")].some((n) => { const r = n.getBoundingClientRect(); return r.height > r.width + 0.5; })); + if (tall) off.push(`${w}: a decision taller than wide`); + } else if (first !== null) off.push(`${w}: stacked after drawing at ${first}`); + } + assert.ok(first !== null && first <= 976, `first drawn at ${first}`); + assert.deepEqual(off, []); + await page.close(); + }); + + test("call 2: a one-column schema's two overlapping turn-backs take two lanes space-3 apart, and the padding is the outermost lane plus space-1", async () => { + const { page } = await figurePage(); + const t = (name, row, refs = []) => ({ name, col: 1, row, columns: [{ name: "id", key: "PK" }, ...refs.map((r) => ({ name: `${r}_id`, key: "FK", references: `${r}.id` }))] }); + await draw(page, [{ key: "one", spec: { type: "schema", title: "One column", summary: "Keys.", legend: { plain: "A foreign key" }, tables: [t("a", 1), t("b", 2, ["c"]), t("c", 3, ["a"])] } }]); + assert.equal(await page.getAttribute("#fig-one", "data-layout"), "drawn"); + const got = await page.evaluate(() => { + const fig = document.querySelector("#fig-one"), d = fig.querySelector(".basalt-diagram-drawing").getBoundingClientRect(); + const right = Math.max(...[...fig.querySelectorAll(".basalt-diagram-node")].map((n) => n.getBoundingClientRect().right)) - d.left; + const lanes = [...fig.querySelectorAll(".basalt-diagram-svg .basalt-diagram-line")].map((p) => Math.max(...p.getAttribute("d").match(/-?[\d.]+/g).map(Number).filter((_, k) => k % 2 === 0)) - right).sort((a, b) => a - b); + return { lanes, pad: d.width - right }; + }); + assert.equal(got.lanes.length, 2); + assert.ok(Math.abs(got.lanes[0] - 16) <= 0.5 && Math.abs(got.lanes[1] - 28) <= 0.5, JSON.stringify(got)); + assert.ok(Math.abs(got.pad - 32) <= 0.5, `the padding is space-5 plus space-3 (${got.pad})`); + await page.close(); + }); + + test("call 3: a card whose side holds a straight line and two others is 48 tall at every width from its first drawn one, its ports on the flat part and 8 apart", async () => { + const { page } = await figurePage(); + const spec = { type: "architecture", title: "Ports", summary: "A fixture for the fit rule.", legend: { main: "Request", plain: "Call" }, + nodes: [{ id: "a", name: "Incident response coordinator", col: 1, row: 2 }, { id: "b", name: "Queue", col: 2, row: 2 }, { id: "c", name: "Store", col: 2, row: 3 }, { id: "d", name: "Audit", col: 2, row: 4 }, { id: "e", name: "Search", col: 3, row: 2 }, { id: "f", name: "Mail", col: 4, row: 2 }], + edges: [{ from: "a", to: "b", kind: "main" }, { from: "a", to: "c", toSide: "left" }, { from: "a", to: "d", toSide: "left" }, { from: "b", to: "e" }, { from: "e", to: "f" }] }; + await draw(page, [{ key: "ports", spec }]); + let first = null; + const off = []; + for (let w = 760; w <= 1440; w += 4) { + await page.evaluate((w) => document.getElementById("root").style.setProperty("--w", `${w}px`), w); + await frames(page, 2); + if ((await page.getAttribute("#fig-ports", "data-layout")) !== "drawn") { if (first !== null) off.push(`${w}: stacked`); continue; } + first ??= w; + const a = await page.evaluate(() => { + const n = document.querySelector('#fig-ports .basalt-diagram-node[data-node="a"]').getBoundingClientRect(); + const ys = [...document.querySelectorAll("#fig-ports .basalt-diagram-edge")].filter((g) => g.dataset.from === "a").map((g) => Number(g.querySelector(".basalt-diagram-line").getAttribute("d").match(/-?[\d.]+/g)[1]) + document.querySelector("#fig-ports .basalt-diagram-drawing").getBoundingClientRect().top - n.top).sort((p, q) => p - q); + return { h: n.height, ys }; + }); + if (a.h < 48 - 0.5) off.push(`${w}: ${a.h} tall`); + if (a.ys[0] < 8 - 0.5 || a.ys[a.ys.length - 1] > a.h - 8 + 0.5 || a.ys.some((y, k) => k && y - a.ys[k - 1] < 8 - 0.5)) off.push(`${w}: ports ${a.ys.join(", ")} on ${a.h}`); + } + assert.ok(first !== null); + assert.deepEqual(off, []); + await page.close(); + }); +}); diff --git a/packages/react/test/diagram-geometry.mjs b/packages/react/test/diagram-geometry.mjs index 80e10c83..4ab9db19 100644 --- a/packages/react/test/diagram-geometry.mjs +++ b/packages/react/test/diagram-geometry.mjs @@ -41,11 +41,14 @@ function inspect(P, selector) { 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 width = parseFloat(getComputedStyle(g.querySelector(`.${P}-line`)).strokeWidth); + // A line that states its cardinality (DECISIONS 306, 1.1) has no head: its shaft runs to the table's edge, and its referenced end's marks stand for the head. + const marks = g.querySelector(`.${P}-crow[data-end="to"]`); + if (marks) { const tip = pts[pts.length - 1]; return { i: g.dataset.edge, from: g.dataset.from, to: g.dataset.to, pts, stop: tip, tip, width, tipEl: marks }; } 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 }; }); diff --git a/packages/react/test/diagram-keys.test.mjs b/packages/react/test/diagram-keys.test.mjs new file mode 100644 index 00000000..f51b9223 --- /dev/null +++ b/packages/react/test/diagram-keys.test.mjs @@ -0,0 +1,207 @@ +// The spatial arrow keys (DECISIONS 306, 1.5; section 8's list for diagram-keys.test.mjs): drawn, the arrows go to the nearest card in that direction by +// the cards' columns and rows; stacked, and where some card could not be reached, they keep the author's order. In Chromium against the built package. +// The table is the decision's proof (proof/spatial-cells.json, copied to test/fixtures). The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import { pathToFileURL } from "node:url"; + +import { fixturePage, launch, pkg } from "./support.mjs"; + +const DATA = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8")); +const TABLE = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "diagram-spatial-cells.json"), "utf8")); +const NAMES = { architecture: "architecture", flowchart: "flowchart", dataFlow: "data flow", sequence: "sequence", schema: "schema" }; +const P = "basalt-diagram"; +const KEY = { right: "ArrowRight", left: "ArrowLeft", down: "ArrowDown", up: "ArrowUp" }; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +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 }; +function Host() { + const [list, setList] = React.useState(() => Object.entries(data).map(([key, d]) => { const { type, ...props } = d; return { key, type, props }; })); + window.__set = (next) => flushSync(() => setList(next)); + return
{list.map(({ key, type, props }) => { const X = C[type]; return ; })}
; +} +createRoot(document.getElementById("root")).render();`; +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 keysPage({ theme = "dark", width = 1440, dir } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height: 1000 } }); + if (dir) await page.evaluate((dir) => { document.documentElement.dir = dir; }, dir); + await page.addStyleTag({ content: "body{margin:0;padding:16px} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + return { page, errors }; +} +/** Focuses a card by script (as the keyboard would reach it), presses a key, and names the card focused after it. */ +async function press(page, key, id, k) { + await page.locator(`#fig-${key} .${P}-node[data-node="${id}"]`).focus(); + await page.keyboard.press(k); + return page.evaluate(() => document.activeElement?.getAttribute("data-node") ?? null); +} + +describe("drawn: the four-direction table", () => { + for (const theme of ["dark", "light"]) for (const dir of ["ltr", "rtl"]) { + test(`${theme}, ${dir}: each CIMIP figure's arrows equal the proof's table${dir === "rtl" ? ", left and right mirrored" : ""}`, async () => { + const { page, errors } = await keysPage({ theme, dir }); + for (const [key, name] of Object.entries(NAMES)) { + assert.equal(await page.locator(`#fig-${key}`).getAttribute("data-layout"), "drawn", key); + const table = TABLE[name].table; + for (const [id, ways] of Object.entries(table)) for (const [way, want] of Object.entries(ways)) { + const k = dir === "rtl" && (way === "left" || way === "right") ? KEY[way === "left" ? "right" : "left"] : KEY[way]; + assert.equal(await press(page, key, id, k), want ?? id, `${key}: ${way} from ${id}`); + } + } + assert.deepEqual(errors, []); + await page.close(); + }); + } + test("every card is reached from every card in the five figures; a figure built to strand a card keeps the author's order and warns", async () => { + for (const name of Object.values(NAMES)) assert.equal(TABLE[name].everyCardFromEveryCard, true); + const { page } = await keysPage(); + const warnings = []; + page.on("console", (m) => { if (m.type() === "warning") warnings.push(m.text()); }); + // Five cards in an X: the middle one is reached from no corner by the rule (each corner's nearest card along an arrow is another corner), so the figure keeps + // the author's order (Neon's B12: the earlier fixture stranded nothing, and the test accepted either answer). + const X = [[1, 1], [1, 3], [2, 2], [3, 1], [3, 3]]; + const spec = { title: "Stranded", summary: "A card no arrow reaches.", nodes: X.map(([col, row], k) => ({ id: `n${k}`, name: `N${k}`, col, row })), edges: [] }; + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const m = core.buildModel({ type: "architecture", ...spec }); + assert.equal(core.spatialTable(m), null, "the X strands a card"); + assert.ok(m.warnings.some((w) => /cannot be reached from another by the arrow keys/.test(w)), "and a development build says so"); + await page.evaluate((spec) => window.__set([{ key: "strand", type: "architecture", props: spec }]), spec); + await frames(page, 4); + assert.equal(await page.locator("#fig-strand").getAttribute("data-layout"), "drawn"); + // n0 is at column 1, row 1: spatially → would go to n3 (column 3, row 1); in the author's order it goes to n1. + assert.equal(await press(page, "strand", "n0", "ArrowRight"), "n1"); + assert.equal(await press(page, "strand", "n1", "ArrowRight"), "n2"); + await page.close(); + }); +}); + +describe("stacked and the hint", () => { + test("stacked, the arrows are the author's order; the hint shows four arrows where the drawn figure has rows and columns, two otherwise", async () => { + const { page } = await keysPage({ width: 600 }); + assert.equal(await page.locator("#fig-architecture").getAttribute("data-layout"), "stacked"); + const ids = DATA.architecture.nodes.map((n) => n.id); + assert.equal(await press(page, "architecture", ids[0], "ArrowRight"), ids[1]); + assert.equal(await press(page, "architecture", ids[1], "ArrowUp"), ids[0]); + await page.setViewportSize({ width: 1440, height: 1000 }); + await frames(page, 4); + const arrows = (key) => page.locator(`#fig-${key} .${P}-hint > span:first-child kbd`).evaluateAll((ks) => ks.map((k) => k.textContent).filter((t) => /^[←↑↓→]$/.test(t))); + assert.deepEqual(await arrows("architecture"), ["←", "↑", "↓", "→"]); + assert.deepEqual(await arrows("sequence"), ["←", "→"]); + const sentence = await page.locator(`#fig-architecture .${P}-drawing`).evaluate((d) => d.getAttribute("aria-describedby").split(" ").map((id) => document.getElementById(id)?.textContent).join(" ")); + assert.match(sentence, /the nearest part in that direction/); + await page.close(); + }); +}); + +// The trace on touch (1.5; Neon's B12 of the code review, still missing at the re-check): a tap on the ground, a scroll, a linked card, the foot, a +// touchscreen laptop's first tap, and the stacked schema and sequence. Written while browser tests are paused (DECISIONS 330): not run in the round that +// wrote it. +const BX = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +async function touchPage({ width = 1440, mobile = true, items } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme: "dark", standards: true, viewport: { width, height: 1000 }, hasTouch: true, isMobile: mobile }); + await page.addStyleTag({ content: "body{margin:0;padding:16px} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + if (items) await page.evaluate((items) => window.__set(items), items); + await frames(page, 6); + return { page, errors }; +} +const lit = (page, key) => page.locator(`#fig-${key} .${P}-edge[data-lit]`).count(); +const clearState = (page, key) => page.locator(`#fig-${key} .${P}-clear`).evaluateAll((b) => b.map((x) => x.getAttribute("aria-disabled"))); + +describe("the trace on touch", () => { + test("a tap on the ground clears a trace; with none up it changes nothing", async () => { + const { page, errors } = await touchPage(); + const ground = async () => { const box = await page.locator(`#fig-architecture .${P}-drawing`).boundingBox(); await page.touchscreen.tap(box.x + 4, box.y + box.height - 4); await page.waitForTimeout(150); }; + await ground(); + assert.equal(await lit(page, "architecture"), 0); + assert.deepEqual(await clearState(page, "architecture"), ["true"], "Clear highlight stays disabled"); + await page.tap(`#fig-architecture .${P}-node[data-node="svc"]`); + await page.waitForTimeout(150); + assert.ok((await lit(page, "architecture")) > 0, "the card is traced"); + await ground(); + assert.equal(await lit(page, "architecture"), 0, "the ground clears it"); + assert.deepEqual(await clearState(page, "architecture"), ["true"]); + assert.deepEqual(errors, []); + await page.close(); + }); + + test("a scroll that starts on a card traces nothing", async () => { + const { page } = await touchPage({ width: 390 }); + const card = await page.locator(`#fig-flowchart .${P}-node`).first().boundingBox(); + const cdp = await page.context().newCDPSession(page); + const at = (dy) => [{ x: card.x + card.width / 2, y: card.y + card.height / 2 + dy, id: 1 }]; + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: at(0) }); + for (let k = 1; k <= 10; k++) await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: at(-12 * k) }); + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + await page.waitForTimeout(200); + for (const key of Object.keys(NAMES)) assert.equal(await lit(page, key), 0, `${key}: no trace`); + await page.close(); + }); + + test("a linked card follows its link and is never traced", async () => { + const { page } = await touchPage({ items: [{ key: "arch", type: "architecture", props: (({ type, ...p }) => p)(BX.architecture) }, { key: "sequence", type: "sequence", props: (({ type, ...p }) => p)(BX.sequence) }] }); + await page.tap(`#fig-arch a.${P}-node[data-node="svc"]`); + await page.waitForTimeout(200); + assert.equal(await page.evaluate(() => location.hash), "#fig-sequence", "the link is followed"); + assert.equal(await lit(page, "arch"), 0, "and nothing is traced"); + assert.deepEqual(await clearState(page, "arch"), ["true"]); + await page.close(); + }); + + test("the foot does not move when Clear highlight is enabled, and Clear highlight is last in it", async () => { + const { page } = await touchPage(); + const foot = () => page.locator(`#fig-architecture .${P}-foot > *`).evaluateAll((els) => els.map((e) => { const r = e.getBoundingClientRect(); return [e.className, Math.round(r.left * 2) / 2, Math.round(r.top * 2) / 2, Math.round(r.width * 2) / 2, Math.round(r.height * 2) / 2]; })); + const before = await foot(); + assert.match(before.at(-1)[0], /-clear\b/, "last in the foot"); + await page.tap(`#fig-architecture .${P}-node[data-node="svc"]`); + await page.waitForTimeout(200); + assert.deepEqual(await clearState(page, "architecture"), [null]); + assert.deepEqual(await foot(), before, "every control in its place and size"); + await page.close(); + }); + + test("a touchscreen laptop: the first tap traces and mounts Clear highlight, last in the foot, after an animated figure's controls", async () => { + const motion = { key: "flow", type: "data-flow", props: { ...(({ type, ...p }) => p)(BX.dataFlow), motion: "animated" } }; + const { page } = await touchPage({ mobile: false, items: [motion] }); + const onTouch = await page.evaluate(() => matchMedia("(hover: none), (pointer: coarse)").matches); + // A laptop's media says hover and a fine pointer: no Clear highlight until a finger is used. (Where the emulated media says touch, it is there from the start.) + if (!onTouch) assert.equal(await page.locator(`#fig-flow .${P}-clear`).count(), 0, "not mounted before a tap"); + const card = page.locator(`#fig-flow .${P}-node:not([href])`).first(); + await card.tap(); + await page.waitForTimeout(200); + assert.ok((await lit(page, "flow")) > 0, "the first tap traces"); + const order = await page.locator(`#fig-flow .${P}-foot > *`).evaluateAll((els) => els.map((e) => e.className)); + assert.match(order.at(-1), /-clear\b/, `last in the foot ${JSON.stringify(order)}`); + await page.close(); + }); + + test("a text sequence, as art at 1440 and as the transcript at 390, has no Clear highlight: a tap traces nothing in it", async () => { + for (const width of [1440, 390]) { + const { page } = await touchPage({ width, items: [{ key: "text", type: "sequence", props: (({ type, ...p }) => p)(BX.textSequence) }] }); + await page.waitForSelector(`#fig-text .${P}-text .${P}-text-ink`); + await page.locator(`#fig-text .${P}-text`).tap(); + await page.waitForTimeout(200); + assert.equal(await page.locator(`#fig-text .${P}-clear`).count(), 0, `${width}: no Clear highlight`); + await page.close(); + } + }); + + test("at 390 the stacked schema and sequence, which draw no lines, show no tap hint and no Clear highlight", async () => { + const { page } = await touchPage({ width: 390 }); + for (const key of ["schema", "sequence"]) { + assert.equal(await page.locator(`#fig-${key}`).getAttribute("data-layout"), "stacked", key); + assert.equal(await page.locator(`#fig-${key} .${P}-clear`).count(), 0, `${key}: no Clear highlight`); + assert.equal(await page.locator(`#fig-${key} .${P}-hint`).evaluateAll((els) => els.filter((e) => e.checkVisibility() && e.textContent.trim()).length), 0, `${key}: no hint`); + } + await page.close(); + }); +}); diff --git a/packages/react/test/diagram-layout.test.mjs b/packages/react/test/diagram-layout.test.mjs new file mode 100644 index 00000000..429ebc95 --- /dev/null +++ b/packages/react/test/diagram-layout.test.mjs @@ -0,0 +1,343 @@ +// Automatic layout after the decider's ruling (DECISIONS 322, on DECISIONS 306 and 313, section 1.8): a main line keeps a way, network simplex with a +// straightness priority on main lines, a decision's point that a line leaves takes no other line, a turn-back needs a gutter, and one warning when +// neither direction draws. The ruling's list of tests; the figures are its proof's (test/fixtures/diagram-layout.json, the CIMIP ones in +// cimip-diagrams-b.json). In Node and in Chromium against the built package. The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import { pathToFileURL } from "node:url"; + +import * as esbuild from "esbuild"; + +import { inspectSource } from "./diagram-geometry.mjs"; +import { fixturePage, launch, pkg } from "./support.mjs"; + +const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +const L = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "diagram-layout.json"), "utf8")); +const FIG = { autoArchitecture: B.autoArchitecture, autoFlowchart: B.autoFlowchart, autoSchema: B.autoSchema, ...L.figures }; +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:0 16px} #root{width:var(--w,1104px)}`; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const HOST = ` +import * as Layout from "./dist/diagram-layout.js"; +window.__place = Layout.placeDiagram; +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, schema: B.SchemaDiagram }; +function Host() { + const [list, setList] = React.useState([]); + window.__set = (next) => flushSync(() => setList(next)); + return
{list.map(({ key, spec, dir }) => { const { type, ...props } = spec; const X = C[type]; return
; })}
; +} +createRoot(document.getElementById("root")).render();`; + +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 figurePage({ theme = "dark", width = 1440, height = 1000, dev = true } = {}) { + const { page, errors } = await fixturePage(browser, "", { theme, viewport: { width, height }, standards: true }); + const built = await esbuild.build({ + stdin: { contents: `import * as React from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import * as B from "./dist/index.js"; ${HOST}`, resolveDir: pkg, loader: "tsx" }, + bundle: true, format: "iife", write: false, jsx: "automatic", platform: "browser", logLevel: "silent", define: { "process.env.NODE_ENV": dev ? '"development"' : '"production"' }, + }); + const warnings = []; + page.on("console", (m) => { if (m.type() === "warning" || m.type() === "error") warnings.push(m.text()); }); + await page.addScriptTag({ content: built.outputFiles[0].text }); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + return { page, errors, warnings }; +} +/** Draws the figures and waits until each automatic one has its placement (the layout module loads at 640 or wider) and is laid out. */ +const draw = async (page, items) => { + await page.evaluate((items) => window.__set(items), items); + await page.waitForFunction((n) => document.querySelectorAll(".basalt-diagram[data-layout]").length >= n, items.length); + await page.waitForTimeout(400); + await frames(page, 4); +}; +const widthTo = async (page, w) => { await page.evaluate((w) => document.getElementById("root").style.setProperty("--w", `${w}px`), w); await frames(page, 4); }; +const inspect = (page, key) => page.evaluate(`${inspectSource()}("${P}", "#fig-${key}")`); +const strip = (p) => ({ cols: p.cols, rows: p.rows, cells: p.cells }); + +describe("placeDiagram", () => { + test("the cells, cols and rows of the ruling's proof, in both directions, on five fresh runs in Node", async () => { + for (let run = 0; run < 5; run++) { + // A fresh module each run: a query string makes Node load it again, with its own elk. + const { placeDiagram } = await import(`${pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href}?run=${run}`); + for (const key of ["autoArchitecture", "nestedArchitecture", "autoFlowchart", "autoSchema"]) for (const d of ["down", "right"]) { + const got = await placeDiagram(FIG[key], d); + assert.equal(got.direction, d); + assert.deepEqual(strip(got), L.cells[key][d], `${key} laid ${d}, run ${run + 1}`); + } + } + }); + + test("the graph handed to elk: network simplex, straightness 10 on main lines only, no partitioning; at most two layouts a direction", async () => { + const layout = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href); + // The graph's helpers are internal (diagram-layout-graph, in no public declaration: Neon's B11); the module is read straight from dist. + const graph = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout-graph.js")).href); + assert.ok(!("elkGraph" in layout) && !("mainInTheMiddle" in layout), "the public module exports placeDiagram and no helper"); + const g = graph.elkGraph(FIG.autoArchitecture, "down"); + assert.equal(g.layoutOptions["elk.layered.nodePlacement.strategy"], "NETWORK_SIMPLEX"); + assert.ok(!JSON.stringify(g).includes("partitioning"), "no elk.partitioning option anywhere"); + const main = new Set(FIG.autoArchitecture.edges.map((e, k) => (e.kind === "main" ? `${e.from}>${e.to}` : null)).filter(Boolean)); + for (const e of g.edges) { + const isMain = main.has(`${e.sources[0]}>${e.targets[0]}`); + assert.equal(e.layoutOptions?.["elk.layered.priority.straightness"], isMain ? "10" : undefined, `${e.sources[0]} to ${e.targets[0]}`); + } + // The main line in the middle: a card with three or more leaving lines, one of them main. + const order = graph.mainInTheMiddle([{ from: "a", main: false, n: 1 }, { from: "a", main: false, n: 2 }, { from: "a", main: true, n: 3 }, { from: "b", main: false, n: 4 }]); + assert.deepEqual(order.map((e) => e.n), [1, 3, 2, 4]); + // Count elk's layouts: the class diagram-layout imports is this module's default. + const ELK = (await import(pathToFileURL(path.join(pkg, "dist", "diagram-elk.js")).href)).default; + const real = ELK.prototype.layout; + let calls = 0; + ELK.prototype.layout = function (...args) { calls++; return real.apply(this, args); }; + try { + for (const key of Object.keys(FIG)) for (const d of ["down", "right"]) { + calls = 0; + await layout.placeDiagram(FIG[key], d); + assert.ok(calls >= 1 && calls <= 2, `${key} laid ${d}: ${calls} layouts`); + } + } finally { ELK.prototype.layout = real; } + }); + + test("a way-only track is kept: the two-main-lines figure laid down is 2 columns with every card in the first", async () => { + const { placeDiagram } = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href); + const got = await placeDiagram(FIG.twoMains, "down"); + assert.equal(got.cols, 2); + assert.ok(Object.values(got.cells).every((c) => c.col === 1), JSON.stringify(got.cells)); + // The engine's tracks are the placement's, not the cards' own. + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + assert.equal(core.buildModel(FIG.twoMains, { placement: got }).cols, 2); + }); + + test("in the browser, placeDiagram returns Node's cells", async () => { + const { page } = await figurePage(); + for (const key of ["autoArchitecture", "nestedArchitecture", "autoFlowchart", "autoSchema"]) for (const d of ["down", "right"]) { + const got = await page.evaluate(({ spec, d }) => window.__place(spec, d), { spec: FIG[key], d }); + assert.deepEqual(strip(got), L.cells[key][d], `${key} laid ${d} in the browser`); + } + await page.close(); + }); +}); + +describe("the package (Neon B11)", () => { + test("no declaration names elkjs or the graph's helpers, and elkjs's licence ships beside its copy", () => { + const read = (f) => fs.readFileSync(path.join(pkg, "dist", f), "utf8"); + for (const f of ["diagram-elk.d.ts", "diagram-layout.d.ts"]) assert.doesNotMatch(read(f), /["']elkjs|ElkNode|elkGraph|mainInTheMiddle/, f); + assert.match(read("elkjs/LICENSE.md"), /Eclipse Public License/); + assert.match(fs.readFileSync(path.join(pkg, "THIRD-PARTY-NOTICES.md"), "utf8"), /copied unchanged into this package/); + }); +}); + +describe("the CIMIP figures draw", () => { + for (const theme of ["dark", "light"]) test(`${theme}: at 1104 the architecture is drawn laid down in 4 columns and the flowchart in 3, every line and label, no problem; named right, each stacks`, async () => { + const { page, errors } = await figurePage({ theme }); + await draw(page, [{ key: "arch", spec: FIG.autoArchitecture }, { key: "flow", spec: FIG.autoFlowchart }]); + for (const [key, cols, spec] of [["arch", "4", FIG.autoArchitecture], ["flow", "3", FIG.autoFlowchart]]) { + const g = await inspect(page, key); + assert.equal(g.layout, "drawn", key); + assert.equal(await page.locator(`#fig-${key}`).getAttribute("data-cols"), cols, `${key}: columns`); + assert.equal(g.lines.length, spec.edges.length, `${key}: every line`); + assert.equal(g.labels.length, spec.edges.filter((e) => e.label).length, `${key}: every label`); + assert.deepEqual(g.problems, [], `${key}: ${JSON.stringify(g.problems)}`); + } + await draw(page, [{ key: "arch", spec: { ...FIG.autoArchitecture, direction: "right" } }, { key: "flow", spec: { ...FIG.autoFlowchart, direction: "right" } }]); + assert.equal(await page.locator("#fig-arch").getAttribute("data-layout"), "stacked"); + assert.equal(await page.locator("#fig-flow").getAttribute("data-layout"), "stacked"); + assert.deepEqual(errors, []); + await page.close(); + }); + + test("from 800 (the architecture) and 720 (the flowchart) to 1,440, in steps of 16, each is drawn at every width", async () => { + const { page } = await figurePage({ width: 1500, dev: false }); + await page.addStyleTag({ content: "#root{display:grid;gap:64px}" }); + await draw(page, [{ key: "arch", spec: FIG.autoArchitecture }, { key: "flow", spec: FIG.autoFlowchart }]); + const off = []; + for (let w = 720; w <= 1440; w += 16) { + await widthTo(page, w); + await page.waitForTimeout(60); + if (w >= 800 && (await page.locator("#fig-arch").getAttribute("data-layout")) !== "drawn") off.push(`architecture at ${w}`); + if ((await page.locator("#fig-flow").getAttribute("data-layout")) !== "drawn") off.push(`flowchart at ${w}`); + } + assert.deepEqual(off, []); + await page.close(); + }); +}); + +describe("the side choice", () => { + test("rule 3: two answers to one side draw, four ways out of one decision stack and warn; a named side counts toward its side's three", async () => { + const { page, warnings } = await figurePage(); + await draw(page, [{ key: "two", spec: L.fixed.twoToOneSide }, { key: "four", spec: L.fixed.fourWaysOut }]); + assert.equal(await page.locator("#fig-two").getAttribute("data-layout"), "drawn"); + assert.deepEqual((await inspect(page, "two")).problems, []); + assert.equal(await page.locator("#fig-four").getAttribute("data-layout"), "stacked"); + assert.ok(warnings.some((w) => /would lie on one another/.test(w)), JSON.stringify(warnings)); + await page.close(); + // A card with three lines named out of its right side: a line that chooses takes another side. + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const n = (id) => ({ id, name: id, kind: "part" }); + const spec = { type: "architecture", layout: "auto", title: "t", summary: "s", nodes: ["a", "b", "c", "d", "e"].map(n), + edges: [{ from: "a", to: "b", fromSide: "right" }, { from: "a", to: "c", fromSide: "right" }, { from: "a", to: "d", fromSide: "right" }, { from: "a", to: "e" }] }; + const placement = { direction: "down", cells: { a: { col: 1, row: 2 }, b: { col: 2, row: 1 }, c: { col: 2, row: 2 }, d: { col: 2, row: 3 }, e: { col: 2, row: 4 } } }; + const m = core.buildModel(spec, { placement }); + assert.notEqual(m.edges[3].fromSide, "right", "the right side already holds three named lines"); + assert.equal(m.edges[3].fromSide, "bottom"); + }); + + test("rule 4: the two-main-lines figure draws right to left at 1104, no turn-back on the drawing's edge", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "rtl", spec: FIG.twoMains, dir: "rtl" }]); + const g = await inspect(page, "rtl"); + assert.equal(g.layout, "drawn"); + assert.deepEqual(g.problems, []); + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const { placeDiagram } = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href); + for (const d of ["down", "right"]) { + const placement = await placeDiagram(FIG.twoMains, d); + for (const rtl of [false, true]) { + const m = core.buildModel(FIG.twoMains, { placement, rtl }); + for (const e of m.edges) { + if (!e.fromSide || e.fromSide !== e.toSide) continue; + const a = m.byId.get(e.from); + const beyond = e.fromSide === "right" ? a.col < m.cols : e.fromSide === "left" ? a.col > 1 : e.fromSide === "bottom" ? a.row < m.rows : a.row > 1; + assert.ok(beyond, `${e.from} to ${e.to} turns back on the drawing's ${e.fromSide} edge (laid ${d}${rtl ? ", right to left" : ""})`); + } + } + } + await page.close(); + }); +}); + +describe("rule 5: the author is told why", () => { + test("the nested-group architecture with two-line labels warns once at 1104 with both directions' reasons, not again after a resize; at 390 nothing", async () => { + const { page, warnings } = await figurePage(); + await draw(page, [{ key: "nested", spec: FIG.nestedArchitecture }]); + assert.equal(await page.locator("#fig-nested").getAttribute("data-layout"), "stacked"); + const said = () => warnings.filter((w) => /draws in neither direction/.test(w)); + assert.equal(said().length, 1, JSON.stringify(warnings)); + assert.match(said()[0], /layout="auto" draws in neither direction at 1104px, so the figure is stacked: laid right it needs \d+px; laid down no clean seat for "SQL · NOTIFY one transaction"\. Name a side/); + assert.ok(!said()[0].includes("\n"), "a label's break is a space in the warning"); + await widthTo(page, 1096); + await page.waitForTimeout(200); + assert.equal(said().length, 1, "the same reasons at a new width are not a new warning"); + await page.close(); + const small = await figurePage({ width: 390 }); + await widthTo(small.page, 358); + await small.page.evaluate((spec) => window.__set([{ key: "nested", spec }]), FIG.nestedArchitecture); + await small.page.waitForTimeout(500); + assert.deepEqual(small.warnings.filter((w) => /draws in neither direction/.test(w)), []); + await small.page.close(); + }); +}); + +describe("the viewer", () => { + async function openViewer(page, key) { + const button = page.locator(`#fig-${key} .${P}-expand`); + await button.scrollIntoViewIfNeeded(); + await button.click(); + await page.waitForSelector(`dialog.${P}-viewer[open] .${P}[data-layout]`); + await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {})))); + await page.waitForTimeout(500); + await frames(page, 4); + return page.evaluate((P) => { const f = document.querySelector(`dialog.${P}-viewer .${P}-layer .${P}`); return { layout: f.getAttribute("data-layout"), cols: f.getAttribute("data-cols") }; }, P); + } + test("with no placement prop, the viewer's figure is drawn where the page's is: laid right at 1440 by 900, laid down at 390 by 844", async () => { + const wide = await figurePage({ width: 1440, height: 900 }); + await draw(wide.page, [{ key: "arch", spec: FIG.autoArchitecture }]); + assert.equal(await wide.page.locator("#fig-arch").getAttribute("data-layout"), "drawn"); + assert.deepEqual(await openViewer(wide.page, "arch"), { layout: "drawn", cols: String(L.cells.autoArchitecture.right.cols) }); + await wide.page.close(); + // At 390 the page's figure is stacked and loads nothing; the viewer's figure is laid out at its least drawn width, and places itself. + const phone = await figurePage({ width: 390, height: 844 }); + await widthTo(phone.page, 358); + await phone.page.evaluate((spec) => window.__set([{ key: "arch", spec }]), FIG.autoArchitecture); + await phone.page.waitForSelector("#fig-arch[data-layout]"); + assert.deepEqual(await openViewer(phone.page, "arch"), { layout: "drawn", cols: String(L.cells.autoArchitecture.down.cols) }); + await phone.page.close(); + }); +}); + +describe("a layout that is out of date (Opus P5 on the re-check)", () => { + test("cards that change while the layout runs: the stale answer is discarded and the figure is laid out again on the new cards", async () => { + const { page, errors } = await figurePage(); + // Two figures under one key: the second replaces the first's cards before the layout module has answered (both in one task, so no answer can land + // between them). The figure must draw as a fresh figure of the second's data draws (the control), with none of the first's cards. + const first = FIG.autoArchitecture, second = FIG.autoFlowchart; + const cells = (key) => page.evaluate(({ P, key }) => Object.fromEntries([...document.querySelectorAll(`#fig-${key} .${P}-node`)].map((n) => [n.dataset.node, ["--_c", "--_r", "--_r2"].map((v) => n.style.getPropertyValue(v)).join(" ")])), { P, key }); + await page.evaluate(({ a, b }) => { window.__set([{ key: "p5", spec: a }]); window.__set([{ key: "p5", spec: b }]); }, { a: first, b: second }); + await page.waitForFunction(() => document.querySelector("#fig-p5")?.getAttribute("data-layout") === "drawn", null, { timeout: 15000 }); + await draw(page, [{ key: "p5", spec: second }, { key: "ctl", spec: second }]); + await page.waitForFunction(() => document.querySelector("#fig-ctl")?.getAttribute("data-layout") === "drawn", null, { timeout: 15000 }); + await frames(page, 4); + const got = await cells("p5"); + assert.deepEqual(Object.keys(got).sort(), second.nodes.map((n) => n.id).sort(), "the second figure's cards, none of the first's"); + assert.deepEqual(got, await cells("ctl"), "each card in the cell of the second figure's own placement"); + // A change of lines alone (the same cards) lays out again too. + const relined = { ...second, edges: second.edges.slice(0, -1) }; + await draw(page, [{ key: "p5", spec: relined }, { key: "ctl2", spec: relined }]); + await page.waitForFunction(() => document.querySelector("#fig-ctl2")?.getAttribute("data-layout") === "drawn", null, { timeout: 15000 }); + await frames(page, 4); + const relaid = await cells("p5"); + assert.deepEqual(relaid, await cells("ctl2"), "after the lines changed"); + assert.notDeepEqual(relaid, got, "and the placement moved (placeDiagram gives other cells without the last line)"); + assert.deepEqual(errors, []); + await page.close(); + }); +}); + +describe("the layout module is fetched only when a figure needs it (Neon B12)", () => { + // The other fixtures bundle into one script, where a dynamic import is inlined and no request can be seen. Here the page is an app's: an ES module + // build with code splitting, served from a routed origin, so each lazy chunk is a request of its own. The chunk that holds elkjs is found from esbuild's + // metafile, not by its name. + const ORIGIN = "http://basalt.test"; + const APP = `import * as React from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import * as B from "./dist/index.js"; +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram }; +function Host() { const [list, setList] = React.useState([]); window.__set = (next) => flushSync(() => setList(next)); return
{list.map(({ key, spec }) => { const { type, ...props } = spec; const X = C[type]; return ; })}
; } +createRoot(document.getElementById("root")).render();`; + let files, elkChunk; + before(async () => { + const built = await esbuild.build({ stdin: { contents: APP, resolveDir: pkg, loader: "tsx" }, bundle: true, splitting: true, format: "esm", outdir: "/out", write: false, metafile: true, jsx: "automatic", platform: "browser", logLevel: "silent", define: { "process.env.NODE_ENV": '"production"' } }); + files = new Map(built.outputFiles.map((f) => [f.path.replace(/^\/out/, ""), f.text])); + elkChunk = Object.entries(built.metafile.outputs).find(([, o]) => Object.keys(o.inputs).some((i) => i.endsWith("dist/diagram-elk.js")))?.[0].replace(/^\/?out/, ""); + }); + async function appPage(width) { + const page = await browser.newPage({ viewport: { width, height: 1000 } }); + const asked = []; + await page.route(`${ORIGIN}/**`, (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/") return route.fulfill({ contentType: "text/html", body: `
` }); + if (url.pathname === "/styles.css") return route.fulfill({ contentType: "text/css", body: fs.readFileSync(path.join(pkg, "dist", "styles.css"), "utf8") }); + asked.push(url.pathname); + const body = files.get(url.pathname); + return body === undefined ? route.fulfill({ status: 404, body: "" }) : route.fulfill({ contentType: "text/javascript", body }); + }); + await page.goto(`${ORIGIN}/`); + await page.waitForFunction(() => typeof window.__set === "function"); + return { page, asked }; + } + + test("a fixed layout and a phone's automatic one fetch no layout; an automatic figure at 1104 fetches it once", async () => { + assert.ok(elkChunk, "esbuild put elkjs in a chunk of its own"); + const fixed = { type: "architecture", title: "t", summary: "s", nodes: [{ id: "a", name: "A", col: 1, row: 1 }, { id: "b", name: "B", col: 2, row: 1 }], edges: [{ from: "a", to: "b" }] }; + const wide = await appPage(1440); + await wide.page.evaluate((spec) => window.__set([{ key: "fixed", spec }]), fixed); + await wide.page.waitForSelector("#fig-fixed[data-layout]"); + await wide.page.waitForTimeout(500); + assert.ok(!wide.asked.includes(elkChunk), `a fixed layout fetches no layout ${JSON.stringify(wide.asked)}`); + await wide.page.evaluate((spec) => window.__set([{ key: "auto", spec }, { key: "auto2", spec }]), FIG.autoArchitecture); + await wide.page.waitForFunction(() => document.querySelector("#fig-auto")?.getAttribute("data-layout") === "drawn", null, { timeout: 15000 }); + assert.equal(wide.asked.filter((p) => p === elkChunk).length, 1, `fetched once for two figures ${JSON.stringify(wide.asked)}`); + await wide.page.close(); + // Under 640 an automatic figure stacks without asking where its cards go (8.5), so nothing is fetched. + const phone = await appPage(390); + await phone.page.evaluate((spec) => window.__set([{ key: "auto", spec }]), FIG.autoArchitecture); + await phone.page.waitForSelector("#fig-auto[data-layout='stacked']"); + await phone.page.waitForTimeout(800); + assert.ok(!phone.asked.includes(elkChunk), `the phone fetches no layout ${JSON.stringify(phone.asked)}`); + await phone.page.close(); + }); +}); diff --git a/packages/react/test/diagram-motion.test.mjs b/packages/react/test/diagram-motion.test.mjs index 7f842e62..c399f4d6 100644 --- a/packages/react/test/diagram-motion.test.mjs +++ b/packages/react/test/diagram-motion.test.mjs @@ -103,7 +103,8 @@ describe("still is untouched (first)", () => { const seen = await page.evaluate(() => [...document.querySelectorAll("figure")].map((f) => ({ entrance: f.getAttribute("data-entrance"), motion: f.getAttribute("data-motion"), parts: f.querySelectorAll(".basalt-diagram-flow, .basalt-diagram-bead, .basalt-diagram-packet, .basalt-diagram-motion-defs, .basalt-diagram-play, .basalt-diagram-pause, [mask^='url(#dg']").length, - foot: f.querySelector(".basalt-diagram-foot").children.length, + // "View as list" alone of the motion's concern: "Expand" (DECISIONS 310, 9.1) is every figure's and is not counted. + foot: f.querySelectorAll(".basalt-diagram-foot > :not(.basalt-diagram-expand)").length, }))); for (const s of seen) assert.deepEqual(s, { entrance: null, motion: null, parts: 0, foot: 1 }); assert.deepEqual(errors, []); @@ -527,7 +528,6 @@ describe("one mover (then)", () => { "a pulse id that is no node": `{ ...S.animated("architecture"), pulse: ["browser", "nowhere"] }`, "two ids no line joins that way": `{ ...S.animated("architecture"), pulse: ["svc", "alb"] }`, "both a pulse and a packet": `{ ...S.animated("architecture"), packet: { path: ["browser", "alb"] } }`, - "flow on a dashed line": `{ ...S.animated("architecture"), edges: S.animated("architecture").edges.map((e) => (e.kind === "dashed" ? { ...e, flow: true } : e)) }`, "flow on the mover's line": `{ ...S.animated("architecture"), edges: S.animated("architecture").edges.map((e) => (e.from === "alb" ? { ...e, flow: true } : e)) }`, }; for (const [name, expr] of Object.entries(cases)) { @@ -539,6 +539,17 @@ describe("one mover (then)", () => { }); } + // Flow on a dashed line is allowed (DECISIONS 306, 1.5): its own dashes march toward the head, one period at speed-diagram-flow; no error. + test("a dashed line that flows marches its own dashes, with no error", async () => { + const { page, warnings } = await devPage(); + await draw(page, [["arch", `{ ...S.animated("architecture"), pulse: undefined, edges: S.animated("architecture").edges.map((e) => (e.kind === "dashed" ? { ...e, flow: true } : e)) }`]]); + await until(page, () => document.querySelector("#fig-arch .basalt-diagram-pause")); + await page.evaluate(() => { const f = document.getElementById("fig-arch"); f.setAttribute("data-entrance", "done"); f.dispatchEvent(new Event("basalt-diagram-settle")); }); + await until(page, () => [...document.querySelectorAll('#fig-arch .basalt-diagram-line[data-kind="dashed"]')].some((l) => l.getAnimations().length > 0)); + assert.equal(await page.locator("#error-arch").count(), 0); + assert.ok(!warnings.some((w) => /dashed and flows/.test(w))); + }); + test("a flow line with no label warns", async () => { const { page, warnings } = await devPage(); await draw(page, [["arch", `{ ...S.animated("architecture"), edges: S.animated("architecture").edges.map((e) => (e.from === "svc" && e.to === "s3" ? { ...e, flow: true, label: undefined } : e)) }`]]); @@ -1129,7 +1140,8 @@ describe("section 7's checks, batch A", () => { edges: getComputedStyle(f.querySelector(".basalt-diagram-edges")).visibility, masked: f.querySelectorAll(".basalt-diagram-edge[mask], .basalt-diagram-motion-defs").length, parts: f.querySelectorAll(".basalt-diagram-flow, .basalt-diagram-bead, .basalt-diagram-packet, .basalt-diagram-play, .basalt-diagram-pause").length, - foot: f.querySelector(".basalt-diagram-foot").children.length, + // "View as list" alone of the motion's concern: "Expand" (DECISIONS 310, 9.1) is every figure's and is not counted. + foot: f.querySelectorAll(".basalt-diagram-foot > :not(.basalt-diagram-expand)").length, lines: f.querySelectorAll(".basalt-diagram-svg .basalt-diagram-line").length, animations: f.getAnimations({ subtree: true }).length, }))); diff --git a/packages/react/test/diagram-output.test.mjs b/packages/react/test/diagram-output.test.mjs new file mode 100644 index 00000000..62cc5c46 --- /dev/null +++ b/packages/react/test/diagram-output.test.mjs @@ -0,0 +1,93 @@ +// Print, right to left and export (DECISIONS 306, 1.7; section 8's list for diagram-output.test.mjs), on the extended CIMIP figures. In Chromium against +// the built package. The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; + +import { fixturePage, launch } from "./support.mjs"; + +const P = "basalt-diagram"; +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const HOST = ` +import data from "./test/fixtures/cimip-diagrams-b.json"; +import { diagramToSvg, diagramToPng } from "./dist/diagram-export.js"; +window.__svg = (id, o) => diagramToSvg(document.getElementById(id), o).then((b) => b.text()); +window.__png = (id, o) => diagramToPng(document.getElementById(id), o).then((b) => createImageBitmap(b)).then((i) => [i.width, i.height]); +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, "data-flow": B.DataFlowDiagram, sequence: B.SequenceDiagram, schema: B.SchemaDiagram }; +createRoot(document.getElementById("root")).render(
{Object.entries(data).map(([key, d]) => { const { type, ...props } = d; const X = C[type]; return ; })}
);`; +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 outPage({ theme = "dark", width = 1440, dir } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height: 1200 } }); + if (dir) await page.evaluate((d) => { document.documentElement.dir = d; }, dir); + await page.addStyleTag({ content: "body{margin:0;padding:16px;background:var(--basalt-surface-page)} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 6); + return { page, errors }; +} + +describe("print", () => { + test("from the dark theme with no beforeprint: the page's tokens compute to light, and a traced figure's lines to their resting ink; no hint or control prints", async () => { + const { page } = await outPage({ theme: "dark" }); + await page.locator(`#fig-architecture .${P}-node[data-node="alb"]`).hover(); + await frames(page, 4); + const lightPrimary = await page.evaluate(() => { document.documentElement.dataset.theme = "light"; const v = getComputedStyle(document.documentElement).getPropertyValue("--basalt-text-primary"); document.documentElement.dataset.theme = "dark"; return v.trim(); }); + await page.emulateMedia({ media: "print" }); + const got = await page.evaluate((P) => { + const fig = document.querySelector("#fig-architecture"); + // A traced plain line (ALB's line to the service is plain): read as it prints. (Neon's B12: the check was skipped when a main line was found first.) + const lit = fig.querySelector(`.${P}-edge[data-lit] .${P}-line[data-kind="plain"], .${P}-edge[data-dim] .${P}-line[data-kind="plain"]`); + const rest = fig.querySelector(`.${P}-edge:not([data-lit]):not([data-dim]) .${P}-line[data-kind="plain"]`) ?? fig.querySelector(`.${P}-line[data-kind="plain"]`); + return { primary: getComputedStyle(document.documentElement).getPropertyValue("--basalt-text-primary").trim(), scheme: getComputedStyle(document.documentElement).colorScheme, + hint: getComputedStyle(fig.querySelector(`.${P}-hint`)).display, expand: getComputedStyle(fig.querySelector(`.${P}-expand`)).display, + traced: lit ? [getComputedStyle(lit).stroke, lit.getAttribute("data-kind")] : null, plain: rest ? getComputedStyle(rest).stroke : null }; + }, P); + assert.equal(got.primary, lightPrimary); + assert.equal(got.scheme, "light"); + assert.equal(got.hint, "none"); + assert.equal(got.expand, "none"); + assert.ok(got.traced, "a traced plain line is there to read"); + assert.equal(got.traced[0], got.plain, "a traced line prints in its resting ink"); + await page.close(); + }); +}); + +describe("right to left", () => { + test("every CIMIP figure is drawn mirrored under dir=rtl, the first participant at the right; a Mono detail keeps the card's start edge", async () => { + const { page, errors } = await outPage({ dir: "rtl" }); + for (const key of ["architecture", "flowchart", "dataFlow", "sequence", "schema"]) assert.equal(await page.locator(`#fig-${key}`).getAttribute("data-layout"), "drawn", key); + const heads = await page.locator(`#fig-sequence .${P}-node`).evaluateAll((els) => els.map((e) => e.getBoundingClientRect().left)); + assert.ok(heads[0] > heads[heads.length - 1], "the first participant is at the right"); + const browserX = await page.locator(`#fig-architecture .${P}-node[data-node="browser"]`).evaluate((e) => e.getBoundingClientRect().left); + const albX = await page.locator(`#fig-architecture .${P}-node[data-node="alb"]`).evaluate((e) => e.getBoundingClientRect().left); + assert.ok(browserX > albX, "column 1 is at the right"); + const edge = await page.locator(`#fig-architecture .${P}-node[data-node="alb"]`).evaluate((card, P) => { const d = card.querySelector(`.${P}-detail`); return Math.abs(card.getBoundingClientRect().right - d.getBoundingClientRect().right); }, P); + assert.ok(edge < 16, `the detail keeps the card's start (right) edge: ${edge}`); + assert.deepEqual(errors, []); + await page.close(); + }); +}); + +describe("export", () => { + for (const theme of ["dark", "light"]) test(`${theme}: no foreignObject; a title and a desc; every node and label; no text under 12px; a traced figure exports at rest; the PNG is twice the SVG`, async () => { + const { page } = await outPage({ theme }); + await page.locator(`#fig-architecture .${P}-node[data-node="svc"]`).hover(); + await frames(page, 3); + const svg = await page.evaluate(() => window.__svg("fig-architecture")); + assert.ok(!svg.includes("foreignObject")); + assert.match(svg, /How a request reaches the agent<\/title>/); + assert.match(svg, /<desc>[^<]{20,}<\/desc>/); + for (const word of ["Browser", "ALB", "Aurora", "CloudWatch", "HTTPS", "RunTask", "Request", "Data"]) assert.ok(svg.includes(`>${word}<`), `the file has "${word}"`); + const sizes = [...svg.matchAll(/font-size="([\d.]+)"/g)].map((m) => Number(m[1])); + assert.ok(sizes.length > 50 && Math.min(...sizes) >= 12, `the smallest text is ${Math.min(...sizes)}px`); + assert.ok(!/data-lit|data-dim/.test(svg)); + const [w, h] = [Number(/ width="(\d+)"/.exec(svg)[1]), Number(/ height="(\d+)"/.exec(svg)[1])]; + const [pw, ph] = await page.evaluate(() => window.__png("fig-architecture")); + assert.deepEqual([pw, ph], [w * 2, h * 2]); + const other = theme === "dark" ? "light" : "dark"; + const svgOther = await page.evaluate((t) => window.__svg("fig-architecture", { theme: t }), other); + assert.notEqual(/<rect width="\d+" height="\d+" fill="([^"]+)"/.exec(svgOther)[1], /<rect width="\d+" height="\d+" fill="([^"]+)"/.exec(svg)[1], "the other theme's ground"); + await page.close(); + }); +}); diff --git a/packages/react/test/diagram-parts.test.mjs b/packages/react/test/diagram-parts.test.mjs new file mode 100644 index 00000000..f3f90fe4 --- /dev/null +++ b/packages/react/test/diagram-parts.test.mjs @@ -0,0 +1,166 @@ +// Nested groups, link cards and two-line labels (DECISIONS 306, 1.3 and 1.4; part of section 8's list for diagram-parts.test.mjs), on the extended CIMIP +// architecture (test/fixtures/cimip-diagrams-b.json), end lanes and several entries into one card, and marks on steps and participants. In Chromium against +// the built package, both themes. +// The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; + +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { fixturePage, launch, pkg } from "./support.mjs"; + +const P = "basalt-diagram"; +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const HOST = ` +import data from "./test/fixtures/cimip-diagrams-b.json"; +const C = { architecture: B.ArchitectureDiagram, schema: B.SchemaDiagram }; +createRoot(document.getElementById("root")).render(<div style={{ display: "grid", gap: 64 }}>{["architecture", "schema"].map((key) => { const { type, ...props } = data[key]; const X = C[type]; return <X key={key} id={"fig-" + key} {...props} />; })}</div>);`; +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 partsPage({ theme = "dark", width = 1440, touch = false } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height: 1200 }, hasTouch: touch, isMobile: touch }); + if (touch) await page.evaluate(() => { const meta = document.createElement("meta"); meta.name = "viewport"; meta.content = "width=device-width, initial-scale=1"; document.head.append(meta); }); + await page.addStyleTag({ content: "body{margin:0;padding:16px} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + return { page, errors }; +} + +describe("nested groups", () => { + for (const theme of ["dark", "light"]) test(`${theme}: the inner boundary is 16 inside the outer at the end side and 32 below its top; radius 8 against 12; the sentence names the chain`, async () => { + const { page, errors } = await partsPage({ theme }); + const g = await page.evaluate((P) => { + const box = (id) => { const el = document.querySelector(`#fig-architecture .${P}-gbox[data-group="${id}"]`); const r = el.getBoundingClientRect(); return { l: r.left, r: r.right, t: r.top, b: r.bottom, radius: getComputedStyle(el).borderTopLeftRadius }; }; + const cell = (id) => document.querySelector(`#fig-architecture .${P}-node[data-node="${id}"]`).getBoundingClientRect(); + return { aws: box("aws"), data: box("data"), aurora: cell("aurora"), sentence: document.querySelector(`#fig-architecture .${P}-node[data-node="aurora"]`).getAttribute("aria-label") }; + }, P); + assert.equal(Math.round(g.aws.r - g.data.r), 16, "16 inside at the end side"); + assert.equal(Math.round(g.data.t - g.aws.t), 32, "32 below the outer's top"); + assert.equal(Math.round(g.aurora.top - g.data.t), 32, "the inner box is space-8 above its first card"); + assert.equal(g.aws.radius, "12px"); + assert.equal(g.data.radius, "8px"); + assert.match(g.sentence, /In Data & logs, in AWS · your account\./); + assert.deepEqual(errors, []); + await page.close(); + }); + test("stacked, a nested group is a wrapper inside its parent's, and the list nests", async () => { + const { page } = await partsPage({ width: 390 }); + assert.equal(await page.locator(`#fig-architecture .${P}-group[data-group="aws"] .${P}-group[data-group="data"]`).count(), 1); + const list = await page.locator(`#fig-architecture .${P}-list .${P}-list-group`).allTextContents(); + assert.deepEqual(list.filter((t) => /AWS|Data/.test(t)), ["AWS · your account", "Data & logs"]); + await page.close(); + }); +}); + +describe("link cards", () => { + test("a link card is an <a>, the figure is one tab stop, the arrows reach the link and Enter follows it; its name begins with the visible name", async () => { + const { page } = await partsPage(); + const svc = page.locator(`#fig-architecture .${P}-node[data-node="svc"]`); + assert.equal(await svc.evaluate((e) => e.tagName), "A"); + assert.equal(await svc.getAttribute("href"), "#fig-sequence"); + assert.match(await svc.getAttribute("aria-label"), /^cimip service/); + // One tab stop: the figure's roving stop is the first card; the arrows reach the link. + const stops = await page.locator(`#fig-architecture .${P}-node[tabindex="0"]`).count(); + assert.equal(stops, 1); + await page.locator(`#fig-architecture .${P}-node[data-node="alb"]`).focus(); + await page.keyboard.press("ArrowRight"); + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("data-node")), "svc"); + await page.keyboard.press("Enter"); + await frames(page); + assert.equal(await page.evaluate(() => location.hash), "#fig-sequence"); + await page.close(); + }); + test("the cue: secondary at rest, primary and travelling on hover, never alone on a line; no scale on press; 44px on touch", async () => { + const { page } = await partsPage(); + const cue = (sel) => page.locator(sel).evaluate((e) => { const s = getComputedStyle(e, "::after"); return { bg: `${s.backgroundColor} ${s.opacity}`, transform: s.transform, w: s.width }; }); + const end = `#fig-architecture .${P}-node[data-node="svc"] .${P}-name-end`; + const rest = await cue(end); + assert.equal(rest.w, "16px"); + await page.locator(`#fig-architecture .${P}-node[data-node="svc"]`).hover(); + await page.waitForTimeout(250); + const hover = await cue(end); + assert.notEqual(hover.bg, rest.bg, "the focal card's cue lifts from its quiet ink"); + assert.notEqual(hover.transform, "none"); + assert.match(await page.locator(`#fig-architecture .${P}-node[data-node="svc"] .${P}-name`).evaluate((e) => getComputedStyle(e).textDecorationLine), /underline/); + assert.equal(await page.locator(end).evaluate((e) => getComputedStyle(e).whiteSpace), "nowrap", "the arrow holds the last word"); + await page.mouse.down(); + assert.equal(await page.locator(`#fig-architecture .${P}-node[data-node="svc"]`).evaluate((e) => getComputedStyle(e).transform), "none"); + await page.mouse.up(); + await page.close(); + const phone = await partsPage({ width: 390, touch: true }); + const h = await phone.page.locator(`#fig-architecture .${P}-node[data-node="svc"]`).evaluate((e) => e.getBoundingClientRect().height); + assert.ok(h >= 44); + await phone.page.close(); + }); +}); + +describe("two-line labels", () => { + for (const theme of ["dark", "light"]) test(`${theme}: both lines in one ink on one plate, 32 tall; the list joins them with a space`, async () => { + const { page } = await partsPage({ theme }); + const two = await page.locator(`#fig-architecture .${P}-label[data-lines="2"]`).evaluateAll((els) => els.map((e) => ({ h: e.getBoundingClientRect().height, text: e.innerText, colors: [...new Set([getComputedStyle(e).color])] }))); + assert.equal(two.length, 2); + for (const l of two) { assert.equal(Math.round(l.h), 32); assert.equal(l.text.split("\n").length, 2); assert.equal(l.colors.length, 1); } + const list = await page.locator(`#fig-architecture .${P}-list`).evaluate((e) => e.textContent); + assert.match(list, /SQL · NOTIFY one transaction/); + await page.close(); + }); +}); + +// A stacked spine of eight cards with end lines out of the first: n lines that overlap need n lanes (DECISIONS 306, 1.3). +const SPINE = (lines) => ({ title: "Lanes", summary: "End lines.", legend: { plain: "Call" }, nodes: Array.from({ length: 8 }, (_, k) => ({ id: `n${k}`, name: `N${k}`, col: 1, row: k + 1 })), edges: lines.map(([a, b]) => ({ from: `n${a}`, to: `n${b}` })) }); +const SET_HOST = ` +function Host() { + const [spec, setSpec] = React.useState(null); + window.__set = (next) => flushSync(() => setSpec(next)); + return spec ? <B.ArchitectureDiagram id="fig-lanes" {...spec} /> : null; +} +createRoot(document.getElementById("root")).render(<Host />);`; + +describe("end lanes and several entries into one card (1.3; Neon's B12)", () => { + test("three and four lanes at a space-3-5 pitch, the gutter its lanes and space-3; a fifth draws no lines and opens the list; several entries into one card turn space-5 apart, outermost lowest", async () => { + const { page } = await fixturePage(browser, SET_HOST, { standards: true, viewport: { width: 390, height: 1400 } }); + await page.evaluate(() => document.fonts.ready); + const lanes = async (lines) => { + await page.evaluate((spec) => window.__set(spec), SPINE(lines)); + await frames(page, 5); + return page.evaluate(() => { + const fig = document.querySelector("#fig-lanes"); + const d = fig.querySelector(".basalt-diagram-drawing").getBoundingClientRect(); + const cardsR = Math.max(...[...fig.querySelectorAll(".basalt-diagram-node")].map((n) => n.getBoundingClientRect().right)) - d.left; + const xs = [...new Set([...fig.querySelectorAll(".basalt-diagram-svg .basalt-diagram-line")].map((p) => Math.max(...p.getAttribute("d").match(/-?[\d.]+/g).map(Number).filter((_, k) => k % 2 === 0))))].map((x) => Math.round((x - cardsR) * 2) / 2).sort((a, b) => a - b); + return { bare: fig.hasAttribute("data-bare"), open: !fig.querySelector(".basalt-diagram-list").hidden, gutter: d.right - d.left - cardsR, xs }; + }); + }; + // Lines that all pass n1..n2 overlap: three of them, then four. + const three = await lanes([[0, 3], [0, 4], [0, 5]]); + assert.ok(!three.bare && Math.abs(three.gutter - 54) <= 0.5, JSON.stringify(three)); + assert.deepEqual(three.xs.map((x, k) => (k ? x - three.xs[k - 1] : 0)).slice(1), [14, 14]); + const four = await lanes([[0, 3], [0, 4], [0, 5], [0, 6]]); + assert.ok(!four.bare && Math.abs(four.gutter - 68) <= 0.5, JSON.stringify(four)); + const five = await lanes([[0, 3], [0, 4], [0, 5], [0, 6], [0, 7]]); + assert.ok(five.bare && five.open, JSON.stringify(five)); + // Two end lines into one card (n5, from n0 and n1): the outer line turns lowest, the inner space-5 higher. + await page.evaluate((spec) => window.__set(spec), SPINE([[0, 5], [1, 5]])); + await frames(page, 5); + const turns = await page.evaluate(() => [...document.querySelectorAll("#fig-lanes .basalt-diagram-edge")].filter((g) => g.dataset.to === "n5").map((g) => { const n = g.querySelector(".basalt-diagram-line").getAttribute("d").match(/-?[\d.]+/g).map(Number); const pts = []; for (let k = 0; k + 1 < n.length; k += 2) pts.push([n[k], n[k + 1]]); let turn = null; for (let k = 1; k < pts.length; k++) if (Math.abs(pts[k][1] - pts[k - 1][1]) < 0.01 && Math.abs(pts[k][0] - pts[k - 1][0]) > 2) turn = pts[k][1]; return { lane: Math.max(...pts.map((p) => p[0])), turn }; }).sort((a, b) => b.lane - a.lane)); + assert.equal(turns.length, 2); + assert.ok(turns[0].turn > turns[1].turn, `the outermost lane turns lowest ${JSON.stringify(turns)}`); + assert.ok(Math.abs(turns[0].turn - turns[1].turn - 20) <= 1, `space-5 apart ${JSON.stringify(turns)}`); + await page.close(); + }); +}); + +describe("marks on steps and participants (1.6; Neon's B10 and B12)", () => { + test("a data flow step's mark counts its lane's label as its words; a participant may carry a mark and a person never needs one", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const flow = (lane) => core.buildModel({ type: "data-flow", title: "t", summary: "s", lanes: [{ id: "s3", label: lane }], nodes: [{ id: "seg", lane: "s3", col: 1, name: "Sealed segment", mark: { onLight: "a.svg", says: ["S3"] } }], edges: [] }); + assert.deepEqual(flow("S3").warnings, [], "the lane's label says S3"); + assert.ok(flow("Storage").warnings.some((w) => /stands for S3/.test(w)), "and without it the mark carries a fact alone"); + const seq = core.buildModel({ type: "sequence", title: "t", summary: "s", participants: [{ id: "a", name: "Amazon S3", mark: { onLight: "a.svg", says: ["S3"] } }, { id: "p", name: "Marcus" }], steps: [{ from: "p", to: "a", label: "put" }] }); + assert.deepEqual(seq.warnings, []); + assert.ok(seq.nodes[0].mark && !seq.nodes[1].mark); + }); +}); diff --git a/packages/react/test/diagram-recheck.test.mjs b/packages/react/test/diagram-recheck.test.mjs new file mode 100644 index 00000000..a472ddc9 --- /dev/null +++ b/packages/react/test/diagram-recheck.test.mjs @@ -0,0 +1,132 @@ +// The batch B re-check's fixes in the forms node can check (the browser forms are in diagram-review.test.mjs, written while browser tests are paused): +// the text art's glyph measured at 100% in both engines, the transcript's route held with its arrow (ruling 3), the label room over a turn into a group's +// first card (ruling 4), elkjs as one copy (ruling 2), and the skill's figures written from the same engine as React's. The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { test } from "node:test"; +import { pathToFileURL } from "node:url"; + +const pkg = path.join(path.dirname(new URL(import.meta.url).pathname), ".."); +const root = path.join(pkg, "..", ".."); +const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); +// The viewer's layout is bundled into diagram-viewer.js; its source has only type imports, so node strips the types and loads it as it is. +const zoom = await import(pathToFileURL(path.join(pkg, "src", "diagram-zoom-core.ts")).href); +const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +const css = fs.readFileSync(path.join(pkg, "src", "styles", "components.css"), "utf8"); +const html = (spec, P = "basalt-diagram") => core.toHtml(core.figureTree(core.buildModel(spec), {}, { prefix: P, base: "d", hasSource: false, hiddenClass: P === "diagram" ? "visually-hidden" : "basalt-visually-hidden" })); + +test("the text art's glyph is measured at 100%: offsetWidth on one unbreakable run, in React and the skill, never a box a transform scales", () => { + const figure = fs.readFileSync(path.join(pkg, "src", "diagram-figure.tsx"), "utf8"); + const skill = fs.readFileSync(path.join(root, "tools", "html-skill", "src", "modules", "diagram-text.js"), "utf8"); + for (const [who, src] of [["React", figure], ["the skill", skill]]) { + const at = src.search(/["']─["']\.repeat\(40\)/); + assert.ok(at > 0, `${who}: the probe`); + const probe = src.slice(at - 400, at + 400); + assert.match(probe, /["']display:inline-block;white-space:pre["']/, `${who}: one unbreakable run`); + assert.match(probe, /probe\.offsetWidth \/ 40/, `${who}: offsetWidth, which no transform scales`); + assert.doesNotMatch(probe, /getBoundingClientRect/, `${who}: never the zoomed box`); + } +}); + +test("the viewer holds the art at the width the figure reports, whatever the zoom: the layer's width is set and its transform left alone", () => { + const layer = { style: { width: "", transform: "scale(0.5)" } }; + const memo = {}; + zoom.viewerTextWidth({ layer, avail: 1200, row: 1104, contain: 640, memo, measureFigure: () => null }, 812.2); + assert.deepEqual(layer.style, { width: "813px", transform: "scale(0.5)" }); + layer.style.transform = "scale(2)"; + zoom.viewerTextWidth({ layer, avail: 1200, row: 1104, contain: 640, memo, measureFigure: () => null }, 812.2); + assert.equal(layer.style.width, "813px", "the same at 200%"); +}); + +test("ruling 3: a transcript route's arrow and receiver are one run that never breaks, so a wrapped route's second line starts with the arrow", () => { + const m = core.buildModel(B.textSequence); + const lines = core.transcript("basalt-diagram", m).map((v) => core.toHtml(v)); + const routes = lines.filter((l) => /data-ink="num"/.test(l)); + assert.ok(routes.length > 3); + for (const l of routes) { + // The sender, a space, then one run holding the arrow, a space and the receiver: nothing after it on the line. + assert.match(l, /<span class="basalt-diagram-tx-name">[^<]*<\/span> <span class="basalt-diagram-tx-to"><span data-ink="(main|plain)">(━▶|─▶|┄▷)<\/span> [^<]*<\/span><\/span>$/, l); + } + const rule = css.match(/\.basalt-diagram-tx-name, \.basalt-diagram-tx-to \{([^}]*)\}/); + assert.ok(rule && /white-space: nowrap/.test(rule[1]), "the run does not break inside"); + // The second line hangs under the sender: the route's line has a hang of the number's digits and two spaces. + for (const l of routes) assert.match(l, /style="--_in:\d+;--_hang:\d+"/); +}); + +test("ruling 4: a group entered by a turn into its first card makes room for the turn's label, space-12 plus space-4 a line", () => { + const out = html(B.architecture); + const g = out.match(/<div class="basalt-diagram-group" data-group="data"[^>]*>/)?.[0]; + assert.ok(g && /data-turn=""/.test(g) && /--_tl:2/.test(g), g); + // A group no turn enters has neither. + for (const other of out.match(/<div class="basalt-diagram-group"[^>]*>/g)) if (other !== g) assert.doesNotMatch(other, /data-turn|--_tl/, other); + // An unlabelled turn keeps space-12: the group is marked, with no label lines. + const plain = structuredClone(B.architecture); + for (const e of plain.edges) if (e.to === "aurora") delete e.label; + const pg = html(plain).match(/<div class="basalt-diagram-group" data-group="data"[^>]*>/)?.[0]; + assert.ok(pg && /data-turn=""/.test(pg) && !/--_tl/.test(pg), pg); + assert.match(css, /\.basalt-diagram-group\[data-turn\] \{ padding-block-start: calc\(var\(--basalt-space-12\) \+ var\(--basalt-space-4\) \* var\(--_tl, 0\)\); \}/); +}); + +test("ruling 2: elkjs is a build input at exactly 0.12.1, shipped once as dist/diagram-elk.js with its licence", () => { + const p = JSON.parse(fs.readFileSync(path.join(pkg, "package.json"), "utf8")); + assert.equal(p.dependencies?.elkjs, undefined, "not a dependency an app installs"); + assert.equal(p.devDependencies?.elkjs, "0.12.1"); + const allowed = JSON.parse(fs.readFileSync(path.join(root, "dependencies.allowed.json"), "utf8")); + assert.equal(allowed.$copied?.["packages/react"]?.elkjs, "0.12.1"); + const elk = fs.readFileSync(path.join(pkg, "dist", "diagram-elk.js"), "utf8"); + assert.doesNotMatch(elk, /from\s*["']elkjs/, "the copy imports no elkjs"); + assert.ok(fs.existsSync(path.join(pkg, "dist", "elkjs", "LICENSE.md")), "its licence"); + for (const f of fs.readdirSync(path.join(pkg, "dist")).filter((f) => f.endsWith(".js") && f !== "diagram-elk.js")) assert.doesNotMatch(fs.readFileSync(path.join(pkg, "dist", f), "utf8"), /from\s*["']elkjs|import\(["']elkjs/, `${f} reaches elkjs only through diagram-elk.js`); +}); + +test("the skill writes batch B's figures from the same engine: compose.mjs's markup is the engine's, prefix for prefix", async () => { + const layout = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href); + const { compose } = await import(pathToFileURL(path.join(root, ".agent", "skills", "basalt-html", "compose.mjs")).href); + for (const [key, spec] of Object.entries(B)) { + if (!spec?.type) continue; + const page = compose(`<title>D
`).html; + const drawing = (s, P) => { const at = s.indexOf(`
= 0, `${key}: ${P}'s drawing`); const ends = [`
s.indexOf(e, at)).filter((e) => e > at); return s.slice(at, Math.min(...ends)); }; + // (To the ink layer, or a text figure's hint: the slots after it, the hint's keys and the foot, are each engine's own and tested with each.) + const fromSkill = drawing(page, "diagram"); + // An automatic figure is written on the placement compose.mjs made in the type's own direction; React draws on the same answer once it has it. + const auto = spec.layout === "auto"; + const placed = auto ? await layout.placeDiagram({ type: spec.type, nodes: spec.nodes, tables: spec.tables, edges: spec.edges, groups: spec.groups }, spec.direction ?? (spec.type === "flowchart" ? "down" : "right")) : undefined; + const fromEngine = drawing(core.toHtml(core.figureTree(core.buildModel(spec, { placement: placed }), {}, { prefix: "diagram", base: "d", hasSource: false, hiddenClass: "visually-hidden" })), "diagram"); + const ids = (s) => s.replace(/(id|aria-labelledby|aria-describedby|aria-controls|href)="[^"]*"/g, '$1=""'); + assert.equal(ids(fromSkill), ids(fromEngine), key); + } +}); + +test("a text sequence has no Clear highlight in React, as in the skill: the React figure mounts it only for a figure that is not text", () => { + const figure = fs.readFileSync(path.join(pkg, "src", "diagram-figure.tsx"), "utf8"); + assert.match(figure, /const clear = !viewer && !model\.text && \(onTouch \|\| touched\) && ink \?/); + // The skill mounts it only where the figure has an ink layer with lines in it, which a text figure never has. + const skill = fs.readFileSync(path.join(root, "tools", "html-skill", "src", "modules", "diagram.js"), "utf8"); + assert.match(skill, /var want = touched && !viewer && ink && ink\.innerHTML !== '';/); + assert.doesNotMatch(html(B.textSequence), /class="basalt-diagram-ink"/, "a text figure's markup has no ink layer"); +}); + +test("the viewer's list and key (its two sinks) carry hostile words as text: figureList and figureKey through toHtml escape every text and attribute; so do the text art and the transcript", async () => { + const p = (n) => ``; + const a = (n) => `">`; + const specs = [ + { type: "architecture", title: "T" + p(1), summary: "S" + p(2), legend: { main: "M" + p(3), plain: "P" + p(4), dashed: "D" + p(5), focal: "F" + p(6) }, + groups: [{ id: "g" + a(7), label: "G" + p(8) }], + nodes: [{ id: "a" + a(9), kind: "K" + p(10), name: "A" + p(11), detail: "dt" + p(12), col: 1, row: 1, group: "g" + a(7) }, { id: "b", name: "B" + p(13), focal: true, col: 2, row: 1 }], + edges: [{ from: "a" + a(9), to: "b", kind: "main", label: "L" + p(14) }, { from: "b", to: "a" + a(9), kind: "dashed", label: "R" + p(15) }] }, + { type: "sequence", variant: "text", title: "T" + p(16), summary: "S" + p(17), legend: { main: "M" + p(18) }, + participants: [{ id: "a", name: "PA" + p(19) }, { id: "b", name: "PB" + p(20) }], steps: [{ band: "Bd" + p(21) }, { from: "a", to: "b", label: "Msg" + p(22), note: "N" + p(23) }, { frame: "alt", label: "F" + p(24), branches: [{ label: "x" + p(25), steps: [{ from: "b", to: "a", label: "y" + p(26) }] }, { label: "z" + p(27), steps: [{ from: "a", to: "b", label: "w" + p(28) }] }] }] }, + { type: "schema", title: "T" + p(29), summary: "S" + p(30), tables: [{ name: "t" + p(31), col: 1, row: 1, columns: [{ name: "id" + p(32), key: "PK", type: "uuid" + p(33) }] }, { name: "u", col: 2, row: 1, columns: [{ name: "k", key: "FK", references: "t" + p(31) + ".id" + p(32) }] }] }, + ]; + const text = await import(pathToFileURL(path.join(pkg, "dist", "diagram-text.js")).href); + for (const spec of specs) { + const m = core.buildModel(spec, { checks: false }); + const list = core.figureList("basalt-diagram", m).map((v) => core.toHtml(v)).join(""); + const key = core.figureKey("basalt-diagram", m); + const out = [list, key ? core.toHtml(key) : "", ...(m.text ? [...core.transcript("basalt-diagram", m).map((v) => core.toHtml(v)), text.textArt(m).html] : [])].join(""); + assert.ok(out.length > 0); + assert.doesNotMatch(out, / 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(); }); + +const HOST = ` +import * as Export from "./dist/diagram-export.js"; +window.__export = Export; +const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, "data-flow": B.DataFlowDiagram, sequence: B.SequenceDiagram, schema: B.SchemaDiagram }; +function Host() { + const [list, setList] = React.useState([]); + window.__set = (next) => flushSync(() => setList(next)); + return
{list.map(({ key, spec, dir }) => { const { type, ...props } = spec; const X = C[type]; return
; })}
; +} +createRoot(document.getElementById("root")).render();`; + +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 reviewPage({ theme = "dark", width = 1440, height = 900, touch = false, dev = false, media } = {}) { + const { page, errors } = await fixturePage(browser, "", { theme, viewport: { width, height }, standards: true, hasTouch: touch, isMobile: touch }); + const built = await esbuild.build({ + stdin: { contents: `import * as React from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import * as B from "./dist/index.js"; ${HOST}`, resolveDir: pkg, loader: "tsx" }, + bundle: true, format: "iife", write: false, jsx: "automatic", platform: "browser", logLevel: "silent", define: { "process.env.NODE_ENV": dev ? '"development"' : '"production"' }, + }); + const warnings = []; + page.on("console", (m) => { if (m.type() === "warning" || m.type() === "error") warnings.push(m.text()); }); + if (touch) await page.evaluate(() => { const meta = document.createElement("meta"); meta.name = "viewport"; meta.content = "width=device-width, initial-scale=1"; document.head.append(meta); }); + if (media) await page.emulateMedia(media); + await page.addScriptTag({ content: built.outputFiles[0].text }); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + return { page, errors, warnings }; +} +const draw = async (page, items) => { await page.evaluate((items) => window.__set(items), items); await page.waitForFunction((n) => document.querySelectorAll(".basalt-diagram[data-layout]").length >= n, items.length); await frames(page, 5); }; +const inspect = (page, key) => page.evaluate(`${inspectSource()}("${P}", "#fig-${key}")`); +async function openViewer(page, key, how = "click") { + const button = page.locator(`#fig-${key} .${P}-expand`); + await button.scrollIntoViewIfNeeded(); + if (how === "tap") await button.tap(); else await button.click(); + await page.waitForSelector(`dialog.${P}-viewer[open] .${P}[data-layout]`); + await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {})))); + await page.waitForTimeout(300); + await frames(page, 4); +} +const rect = (page, sel) => page.locator(sel).first().evaluate((e) => { const r = e.getBoundingClientRect(); return { l: r.left, r: r.right, t: r.top, b: r.bottom, w: r.width, h: r.height }; }); + +describe("the viewer (Fable B1 to B4, Neon B1 to B3)", () => { + for (const theme of ["dark", "light"]) test(`${theme}: a disabled control takes no hover, press or scale and does not match an enabled one's ink; "Clear highlight" with no trace is disabled the same way`, async () => { + const { page } = await reviewPage({ theme }); + await draw(page, [{ key: "schema", spec: B.schema }]); + await openViewer(page, "schema"); + const out = `dialog.${P}-viewer button[aria-label="Zoom out"]`, zin = `dialog.${P}-viewer button[aria-label="Zoom in"]`; + const look = (sel) => page.locator(sel).evaluate((e) => { const s = getComputedStyle(e); return { color: s.color, bg: s.backgroundColor, transform: s.transform, cursor: s.cursor, disabled: e.hasAttribute("data-disabled"), aria: e.getAttribute("aria-disabled"), focusable: e.tabIndex >= 0 }; }); + const rest = await look(out), live = await look(zin); + assert.equal(rest.aria, "true"); + assert.ok(rest.disabled && rest.focusable, "disabled, and still focusable"); + assert.notEqual(rest.color, live.color, "a disabled control loses its ink"); + await page.hover(out); + await page.waitForTimeout(200); + const hovered = await look(out); + assert.equal(hovered.color, rest.color, "no hover lift"); + assert.equal(hovered.bg, rest.bg, "no hover wash"); + await page.mouse.down(); + await page.waitForTimeout(150); + const pressed = await look(out); + assert.equal(pressed.transform, "none", "no press scale"); + assert.equal(pressed.bg, rest.bg, "no press step"); + await page.mouse.up(); + await page.close(); + const touch = await reviewPage({ theme, width: 390, height: 844, touch: true }); + await touch.page.evaluate(() => document.getElementById("root").style.setProperty("max-width", "1104px")); + await draw(touch.page, [{ key: "arch", spec: B.architecture }]); + await touch.page.setViewportSize({ width: 1200, height: 900 }); + await touch.page.waitForTimeout(400); + const clear = touch.page.locator(`#fig-arch .${P}-clear`); + assert.equal(await clear.count(), 1, "Clear highlight is in the foot on touch"); + const c = await clear.evaluate((e) => ({ disabled: e.hasAttribute("data-disabled"), color: getComputedStyle(e).color })); + const toggle = await touch.page.locator(`#fig-arch .${P}-toggle`).evaluate((e) => getComputedStyle(e).color); + assert.ok(c.disabled, "Clear highlight is disabled with no trace"); + assert.notEqual(c.color, toggle, "and does not look like a live control"); + await touch.page.close(); + }); + + test("a linked card in the viewer closes the viewer and is followed, by a click and by Enter; a new tab's link leaves it open", async () => { + const { page } = await reviewPage(); + await draw(page, [{ key: "arch", spec: B.architecture }]); + await openViewer(page, "arch"); + const link = page.locator(`dialog.${P}-viewer a.${P}-node[data-node="svc"]`); + assert.equal(await link.getAttribute("href"), "#fig-sequence"); + await link.click(); + await page.waitForTimeout(400); + assert.equal(await page.evaluate(() => location.hash), "#fig-sequence"); + assert.equal(await page.locator(`dialog.${P}-viewer[open]`).count(), 0, "the viewer is closed"); + await page.evaluate(() => { location.hash = ""; }); + await openViewer(page, "arch"); + await page.locator(`dialog.${P}-viewer a.${P}-node[data-node="svc"]`).focus(); + await page.keyboard.press("Enter"); + await page.waitForTimeout(400); + assert.equal(await page.locator(`dialog.${P}-viewer[open]`).count(), 0, "Enter closes it too"); + await page.close(); + }); + + for (const [w, h] of [[1440, 900], [390, 844]]) test(`at ${w} by ${h}, a text sequence's viewer holds the art at its own width, never the transcript`, async () => { + const { page } = await reviewPage({ width: w, height: h }); + await draw(page, [{ key: "text", spec: B.textSequence }]); + await openViewer(page, "text"); + await page.waitForSelector(`dialog.${P}-viewer .${P}-text[data-art]`); + const got = await page.evaluate((P) => { + const pre = document.querySelector(`dialog.${P}-viewer .${P}-text`); + return { art: pre.hasAttribute("data-art"), scrolls: pre.scrollWidth > pre.clientWidth + 1, tx: pre.querySelectorAll(`.${P}-tx-line`).length, width: pre.getBoundingClientRect().width }; + }, P); + assert.ok(got.art && !got.scrolls && got.tx === 0, JSON.stringify(got)); + assert.ok(got.width > 480, "wider than the stack's 480"); + // The art's width at 100% does not change with the zoom (both reviews' B3/B2: the glyph was measured under the layer's scale): zoom in twice, Fit, + // zoom out; at each the art is whole, and the layer's own width, which no transform scales, is the same. + const at100 = await page.evaluate((P) => { const pre = document.querySelector(`dialog.${P}-viewer .${P}-text`); return { w: pre.offsetWidth, scroll: pre.scrollWidth, client: pre.clientWidth }; }, P); + assert.equal(at100.scroll, at100.client, "the art scrolls nowhere"); + for (const key of ["=", "=", "0", "-"]) { + await page.keyboard.press(key); + await page.waitForTimeout(450); + await frames(page, 4); + const now = await page.evaluate((P) => { const pre = document.querySelector(`dialog.${P}-viewer .${P}-text`); return { art: pre.hasAttribute("data-art"), w: pre.offsetWidth, scroll: pre.scrollWidth, client: pre.clientWidth }; }, P); + assert.deepEqual(now, { art: true, w: at100.w, scroll: now.client, client: now.client }, `after ${key}`); + } + await page.close(); + }); + + for (const theme of ["dark", "light"]) test(`${theme}: the viewer's dialog has the form dialog's rim, and right to left it is inside the window`, async () => { + const { page } = await reviewPage({ theme }); + await draw(page, [{ key: "schema", spec: B.schema }]); + await openViewer(page, "schema"); + const rim = await page.locator(`dialog.${P}-viewer`).evaluate((d) => { const s = getComputedStyle(d); return { w: s.borderTopWidth, style: s.borderTopStyle, top: s.borderTopColor, side: s.borderLeftColor }; }); + const panel = await page.evaluate(() => { const d = document.createElement("div"); d.className = "basalt-card"; document.body.append(d); const s = getComputedStyle(d); const out = { top: s.borderTopColor, side: s.borderLeftColor }; d.remove(); return out; }); + assert.deepEqual(rim, { w: "1px", style: "solid", top: panel.top, side: panel.side }); + await page.keyboard.press("Escape"); + await page.waitForTimeout(400); + await page.evaluate(() => { document.documentElement.dir = "rtl"; }); + await frames(page, 4); + await openViewer(page, "schema"); + const r = await rect(page, `dialog.${P}-viewer`); + assert.ok(r.l >= 15.5 && r.r <= 1440 - 15.5, `inside the window: ${JSON.stringify(r)}`); + await page.close(); + }); +}); + +describe("right to left, drawn (Fable B5, Neon B4)", () => { + test("a frame's tab is in its frame's top start corner, the else rule inside its frame, a self-call's words beside its loop, and a Mono detail reads in order", async () => { + const { page } = await reviewPage(); + await draw(page, [{ key: "seq", spec: B.sequence, dir: "rtl" }, { key: "arch", spec: B.architecture, dir: "rtl" }]); + assert.equal(await page.locator("#fig-seq").getAttribute("data-layout"), "drawn"); + const frames2 = await page.evaluate((P) => [...document.querySelectorAll(`#fig-seq .${P}-frame`)].map((f) => { + const box = f.querySelector(`:scope > .${P}-fbox`).getBoundingClientRect(), head = f.querySelector(`:scope > .${P}-fhead`).getBoundingClientRect(); + const rules = [...f.querySelectorAll(`:scope > .${P}-felse`)].map((e) => { const s = getComputedStyle(e, "::before"); const r = e.getBoundingClientRect(); return { l: r.left + parseFloat(s.left), w: parseFloat(s.width) }; }); + return { op: f.dataset.op, box: [box.left, box.right], head: [head.left, head.right], rules }; + }), P); + for (const f of frames2) { + assert.ok(f.head[0] >= f.box[0] - 0.5 && f.head[1] <= f.box[1] + 0.5, `${f.op}: the header is inside its frame ${JSON.stringify(f)}`); + assert.ok(Math.abs(f.head[1] - (f.box[1] - 1)) <= 1, `${f.op}: at the frame's start (right) edge`); + for (const r of f.rules) assert.ok(Math.abs(r.l - f.box[0]) <= 1 && Math.abs(r.w - (f.box[1] - f.box[0])) <= 1, `${f.op}: the else rule spans the frame`); + } + // Message 2 is the service's self-call: its loop goes to the left (the end side right to left), and its words are beside the loop, on the left. + const self = await page.evaluate((P) => { + const li = document.querySelector(`#fig-seq .${P}-msg[data-self]`); + const said = li.querySelector(`.${P}-said`).getBoundingClientRect(); + const o = document.querySelector(`#fig-seq .${P}-drawing`).getBoundingClientRect(); + const line = [...document.querySelectorAll(`#fig-seq .${P}-edge`)].find((g) => g.dataset.from === li.dataset.from && g.dataset.to === li.dataset.to); + const xs = line.querySelector(`.${P}-line`).getAttribute("d").match(/-?[\d.]+/g).map(Number).filter((_, k) => k % 2 === 0); + return { side: li.dataset.self, said: [said.left - o.left, said.right - o.left], loop: [Math.min(...xs), Math.max(...xs)] }; + }, P); + if (self.side === "start") assert.ok(self.said[1] <= self.loop[0] + 0.5, `the words are left of the loop ${JSON.stringify(self)}`); + else assert.ok(self.said[0] >= self.loop[1] - 0.5, `the words are right of the loop ${JSON.stringify(self)}`); + // "N tasks · stateless" reads in that order, left to right. + const order = await page.evaluate((P) => [...document.querySelectorAll(`#fig-arch .${P}-node[data-node="svc"] .${P}-run`)].sort((a, b) => a.getBoundingClientRect().left - b.getBoundingClientRect().left || a.getBoundingClientRect().top - b.getBoundingClientRect().top).map((r) => r.textContent).join(" "), P); + assert.equal(order, "N tasks · stateless"); + await page.close(); + }); +}); + +describe("stacked (Fable P2, P3, answer 1; the sweep's 66-1 to 66-3)", () => { + for (const theme of ["dark", "light"]) test(`${theme}: at 390 the else rule runs edge to edge of its frame, no row divider lies on a frame's edge, and no turn into a group's first card is under its label`, async () => { + const { page } = await reviewPage({ theme, width: 390, height: 900 }); + await draw(page, [{ key: "seq", spec: B.sequence }, { key: "arch", spec: B.architecture }]); + const got = await page.evaluate((P) => { + const out = { rules: [], after: [] }; + for (const f of document.querySelectorAll(`#fig-seq .${P}-frame`)) { + const box = f.getBoundingClientRect(); + for (const e of f.querySelectorAll(`:scope > .${P}-felse`)) { const s = getComputedStyle(e, "::before"); const r = e.getBoundingClientRect(); out.rules.push({ l: r.left + parseFloat(s.left), w: parseFloat(s.width), box: [box.left, box.width] }); } + const next = f.nextElementSibling; + if (next?.matches(`.${P}-msgs`)) out.after.push(getComputedStyle(next.firstElementChild).borderTopColor); + } + return out; + }, P); + assert.ok(got.rules.length > 0); + for (const r of got.rules) assert.ok(Math.abs(r.l - r.box[0]) <= 1 && Math.abs(r.w - r.box[1]) <= 1, JSON.stringify(r)); + assert.ok(got.after.length > 0); + for (const c of got.after) assert.match(c, /rgba\(0, 0, 0, 0\)|transparent/, "the row after a frame draws no divider"); + // Answer 1, and the decider's ruling 4 on the re-check: the inner group "Data & logs" is entered by a labelled turn into its first card. The group has + // space-12 above that card plus space-4 for each line of the label (two lines: 80); the label lies inside the group's box, at least space-1 under the + // group label's line, its lower edge no more than space-4 above its turn; nothing grows above the group for it; and no turn point is under the + // group's label. + const g = await page.evaluate((P) => { + const group = [...document.querySelectorAll(`#fig-arch .${P}-group`)].find((x) => x.hasAttribute("data-turn")); + if (!group) return null; + const box = group.getBoundingClientRect(); + const label = group.querySelector(`:scope > .${P}-glabel`).getBoundingClientRect(); + const first = group.querySelector(`.${P}-node`); + const o = document.querySelector(`#fig-arch .${P}-drawing`).getBoundingClientRect(); + const turns = [...document.querySelectorAll(`#fig-arch .${P}-edge`)].filter((e) => e.dataset.to === first.dataset.node).map((e) => { + const n = e.querySelector(`.${P}-line`).getAttribute("d").match(/-?[\d.]+/g).map(Number); + const pts = []; for (let k = 0; k + 1 < n.length; k += 2) pts.push({ x: n[k] + o.left, y: n[k + 1] + o.top }); + const tag = document.querySelector(`#fig-arch .${P}-label[data-edge="${e.dataset.edge}"]`)?.getBoundingClientRect(); + // The turn: the last run across, the one into the card. + const end = pts.at(-1); + const across = [...pts].reverse().find((p, k, all) => k + 1 < all.length && Math.abs(all[k + 1].y - p.y) < 0.5) ?? end; + return { pts, turn: across.y, tag: tag && { t: tag.top, b: tag.bottom, l: tag.left, r: tag.right } }; + }); + return { pad: getComputedStyle(group).paddingTop, grown: group.style.getPropertyValue("--_ggrow"), box: { t: box.top, b: box.bottom, l: box.left, r: box.right }, label: { t: label.top, b: label.bottom, l: label.left, r: label.right }, turns }; + }, P); + assert.ok(g, "a group whose first card is entered by a turn is marked"); + assert.equal(g.pad, "80px", "space-12 plus space-4 for each of the label's two lines"); + assert.equal(g.grown, "", "nothing grows above the group for it"); + const labelled = g.turns.filter((t) => t.tag); + assert.ok(labelled.length > 0, "the turn's label is drawn"); + for (const t of labelled) { + assert.ok(t.tag.t >= g.box.t && t.tag.b <= g.box.b && t.tag.l >= g.box.l - 0.5 && t.tag.r <= g.box.r + 0.5, `inside the group ${JSON.stringify({ tag: t.tag, box: g.box })}`); + assert.ok(t.tag.t >= g.label.b + 4 - 0.5, `at least space-1 under the group's label ${JSON.stringify({ tag: t.tag, label: g.label })}`); + assert.ok(t.tag.b <= t.turn + 0.5 && t.turn - t.tag.b <= 16 + 0.5, `its lower edge at most space-4 above its turn ${JSON.stringify(t)}`); + } + for (const t of g.turns) for (const p of t.pts) assert.ok(!(p.y > g.label.t && p.y < g.label.b && p.x > g.label.l && p.x < g.label.r), `no turn point under the label ${JSON.stringify(p)}`); + // An unlabelled turn keeps space-12: the same figure with the label taken off the turn's line. + const plain = structuredClone(B.architecture); + for (const e of plain.edges) if (e.to === "aurora") delete e.label; + await draw(page, [{ key: "plain", spec: plain }]); + assert.equal(await page.locator(`#fig-plain .${P}-group[data-turn]`).evaluate((x) => getComputedStyle(x).paddingTop), "48px"); + await page.close(); + }); + + test("66-1: on touch a one-line end node's words are centred in its 44px box; 66-2: a wrapped route breaks before its arrow and keeps the 16px pitch", async () => { + const { page } = await reviewPage({ width: 390, height: 900, touch: true }); + await draw(page, [{ key: "flow", spec: B.flowchart }, { key: "seq", spec: B.sequence }]); + const node = await page.evaluate((P) => { + const n = [...document.querySelectorAll(`#fig-flow .${P}-node`)].find((e) => e.textContent.includes("Told it was already decided")); + const r = n.getBoundingClientRect(), w = n.querySelector(`.${P}-name`).getBoundingClientRect(); + return { h: r.height, above: w.top - r.top, below: r.bottom - w.bottom }; + }, P); + assert.ok(node.h >= 44 - 0.5); + assert.ok(Math.abs(node.above - node.below) <= 0.5, JSON.stringify(node)); + const routes = await page.evaluate((P) => [...document.querySelectorAll(`#fig-seq .${P}-route`)].map((r) => { + const to = r.querySelector(`.${P}-to`), arrow = r.querySelector("svg"); + const lines = new Set([...r.getClientRects()].map((x) => Math.round(x.top))); + return { to: Boolean(to), arrowWithName: to && to.contains(arrow), gap: getComputedStyle(r).rowGap, wrapped: to && to.getBoundingClientRect().top > r.getBoundingClientRect().top + 1, ok: !to || [...to.getClientRects()].length === 1 }; + }), P); + for (const r of routes) { assert.ok(r.to && r.arrowWithName && r.ok); assert.equal(r.gap, "0px"); } + await page.close(); + }); + + test("66-3: right to left, a stacked group's label is on its start side (the right)", async () => { + const { page } = await reviewPage({ width: 390, height: 900 }); + await draw(page, [{ key: "arch", spec: B.architecture, dir: "rtl" }]); + const g = await page.evaluate((P) => [...document.querySelectorAll(`#fig-arch .${P}-group`)].map((x) => { const r = x.getBoundingClientRect(), l = x.querySelector(`:scope > .${P}-glabel`).getBoundingClientRect(); return { start: l.left - r.left, end: r.right - l.right }; }), P); + assert.ok(g.length > 0); + for (const x of g) assert.ok(x.end < x.start, JSON.stringify(x)); + await page.close(); + }); +}); + +describe("the text sequence (Fable B6, P4, P7; Neon B6)", () => { + for (const theme of ["dark", "light"]) test(`${theme}: ruling 3, at 390 a transcript route that wraps breaks before its arrow, and its second line starts with the arrow under the sender`, async () => { + const { page } = await reviewPage({ theme, width: 390, height: 900 }); + await draw(page, [{ key: "text", spec: B.textSequence }]); + await page.waitForFunction((P) => document.querySelector(`#fig-text .${P}-tx-line`), P); + const routes = await page.evaluate((P) => [...document.querySelectorAll(`#fig-text .${P}-tx-line[data-n]`)].filter((l) => l.querySelector(`.${P}-tx-to`)).map((l) => { + const name = l.querySelector(`.${P}-tx-name`).getBoundingClientRect(); + const to = l.querySelector(`.${P}-tx-to`); + const arrow = to.firstElementChild.getBoundingClientRect(); + return { n: l.dataset.n, runs: to.getClientRects().length, wrapped: arrow.top > name.top + 1, arrowLeft: arrow.left, nameLeft: name.left, arrowTop: arrow.top, nameTop: name.top, lines: Math.round(l.getBoundingClientRect().height / parseFloat(getComputedStyle(l).lineHeight)) }; + }), P); + assert.ok(routes.length > 3); + assert.ok(routes.some((r) => r.wrapped), `at 390 some route wraps (Fable measured 1, 8 and 10) ${JSON.stringify(routes)}`); + for (const r of routes) { + assert.equal(r.runs, 1, `message ${r.n}: the arrow and the receiver never part`); + if (r.wrapped) assert.ok(Math.abs(r.arrowLeft - r.nameLeft) <= 0.5, `message ${r.n}: the arrow under the sender ${JSON.stringify(r)}`); + else assert.ok(Math.abs(r.arrowTop - r.nameTop) <= 0.5, `message ${r.n}: one line`); + assert.ok(r.lines <= 2, `message ${r.n}: two lines at most`); + } + await page.close(); + }); + + test("the transcript: a message's label and note on lines of their own, each hanging under the sender inside its frame's indent; the key's focal swatch is the art's double box", async () => { + const { page } = await reviewPage({ width: 390, height: 900 }); + await draw(page, [{ key: "text", spec: B.textSequence }]); + const got = await page.evaluate((P) => { + const lines = [...document.querySelectorAll(`#fig-text .${P}-tx-line[data-n]`)]; + const byN = new Map(); + for (const l of lines) { const n = l.dataset.n; if (!byN.has(n)) byN.set(n, []); byN.get(n).push(l); } + return [...byN.values()].map((ls) => { + const first = ls[0], sender = first.querySelector(`.${P}-tx-name`).getBoundingClientRect().left; + return { n: first.dataset.n, lines: ls.length, label: ls[1]?.textContent, hang: ls.slice(1).map((l) => { const r = document.createRange(); r.selectNodeContents(l); return r.getClientRects()[0].left - sender; }), labelInLine1: first.textContent.includes(ls[1]?.textContent ?? "\u0000") }; + }); + }, P); + assert.ok(got.length >= 10); + for (const m of got) { + assert.ok(m.lines >= 2 && m.label && !m.labelInLine1, JSON.stringify(m)); + for (const x of m.hang) assert.ok(Math.abs(x) <= 1, `message ${m.n} hangs under its sender (${x})`); + } + const focal = await page.locator(`#fig-text .${P}-entry[data-focal] .${P}-key-glyph`).textContent(); + assert.equal(focal, "╔═╗"); + await page.close(); + }); + + test("textArt: a frame's header too long for its columns widens the frame, with both corners; a self-call on the last participant keeps its words off the next lifeline", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const text = await import(pathToFileURL(path.join(pkg, "dist", "diagram-text.js")).href); + const m = core.buildModel({ type: "sequence", variant: "text", title: "t", summary: "s", participants: [{ id: "a", name: "A" }, { id: "b", name: "B" }], + steps: [{ frame: "opt", label: "a very long condition header for it", steps: [{ from: "a", to: "b", label: "go" }, { from: "b", to: "b", label: "self", note: "a much longer note than the self label" }] }] }); + const rows = text.textArt(m).html.replace(/<[^>]+>/g, "").replace(/&/g, "&").split("\n"); + const top = rows.find((r) => r.includes("[opt]")); + assert.match(top, /┌.*\[opt\].*a very long condition header for it.*┐/); + const bottom = rows.filter((r) => r.trimStart().startsWith("└─") && r.includes("┘")).pop(); + assert.equal(top.indexOf("┌"), bottom.indexOf("└")); + assert.equal(top.lastIndexOf("┐"), bottom.lastIndexOf("┘")); + const noteRow = rows.find((r) => r.includes("a much longer note than the self label")); + assert.ok(noteRow, "the note is whole"); + assert.equal(noteRow[top.indexOf("┌")], "│", "the frame's side is not written over"); + }); + + test("animated: the build waits until the art is in view, then plays; run: true shows Play the run, and the run quiets the messages not yet reached", async () => { + const { page } = await reviewPage({ width: 1440, height: 600 }); + const spec = { ...B.textSequence, motion: "animated", run: true }; + await page.evaluate((spec) => window.__set([{ key: "spacer", spec: { type: "schema", title: "Spacer", summary: "s", tables: Array.from({ length: 6 }, (_, k) => ({ name: `t${k}`, col: 1, row: k + 1, columns: [{ name: "id" }] })) } }, { key: "text", spec }]), spec); + await page.waitForSelector(`#fig-text .${P}-text[data-art]`); + await page.waitForTimeout(600); + assert.equal(await page.locator("#fig-text").getAttribute("data-entrance"), "pending", "out of view, the build waits"); + await page.locator("#fig-text").scrollIntoViewIfNeeded(); + await page.waitForFunction(() => ["running", "done"].includes(document.querySelector("#fig-text").getAttribute("data-entrance"))); + const play = page.locator(`#fig-text button`, { hasText: "Play the run" }); + assert.equal(await play.count(), 1, "Play the run"); + await page.evaluate(() => document.getAnimations().forEach((a) => a.finish())); + await play.click(); + await page.waitForTimeout(200); + const ahead = await page.locator(`#fig-text .${P}-text [data-n][data-ahead]`).count(); + assert.ok(ahead > 0, "messages not yet reached are quiet"); + await page.close(); + }); +}); + +describe("export (Neon B5)", () => { + test("a flowchart's diamonds keep their size and stroke; a running entrance and a quiet run export at rest; the else rule is drawn; the lines are under the cards", async () => { + const { page } = await reviewPage(); + await draw(page, [{ key: "flow", spec: B.flowchart }, { key: "seq", spec: { ...B.sequence, motion: "animated", run: true } }]); + const svg = await page.evaluate(async () => await (await window.__export.diagramToSvg(document.querySelector("#fig-flow"), { fonts: "name" })).text()); + const diamonds = [...svg.matchAll(/]*>/g)].map((m) => m[0]); + assert.ok(diamonds.length > 0); + for (const d of diamonds) assert.match(d, /width="[\d.]+" height="[\d.]+"/); + assert.match(svg, /vector-effect="non-scaling-stroke"/); + const ink = svg.indexOf(' await (await window.__export.diagramToSvg(document.querySelector("#fig-seq"), { fonts: "name" })).text()); + assert.doesNotMatch(mid, /-reveal-/); + assert.match(mid, /stroke-dasharray="4 4"/, "the else rule is in the file"); + await page.evaluate(() => document.getAnimations().forEach((a) => a.finish())); + await page.locator(`#fig-seq button`, { hasText: "Play the run" }).click(); + await page.waitForTimeout(300); + assert.ok(await page.locator(`#fig-seq [data-ahead]`).count() > 0); + const run = await page.evaluate(async () => await (await window.__export.diagramToSvg(document.querySelector("#fig-seq"), { fonts: "name" })).text()); + const secondary = await page.evaluate(() => getComputedStyle(document.querySelector("#fig-seq")).getPropertyValue("--basalt-text-secondary").trim()); + const labels = await page.evaluate((P) => [...document.querySelectorAll(`#fig-seq .${P}-mlabel`)].map((e) => e.textContent), P); + assert.ok(await page.locator(`#fig-seq [data-ahead]`).count() > 0, "the run is put back after the read"); + const last = labels[labels.length - 1].split(" ")[0]; + const fill = new RegExp(`fill="([^"]+)"[^>]*>${last.replace(/[{}/]/g, (c) => `\\${c}`)}<`).exec(run)?.[1]; + assert.ok(fill && fill !== secondary, `an unreached message exports in its resting ink (${fill})`); + await page.close(); + }); +}); + +describe("automatic layout and the schema (Neon B8, B9, P1 to P3)", () => { + test("a placement with two cards in one cell is not used: the figure stacks and a development build names the cards", async () => { + const { page, warnings } = await reviewPage({ dev: true }); + await draw(page, [{ key: "bad", spec: { type: "architecture", layout: "auto", title: "Two in one", summary: "s", nodes: [{ id: "a", name: "A" }, { id: "b", name: "B" }], edges: [{ from: "a", to: "b" }], placement: { direction: "right", cells: { a: { col: 1, row: 1 }, b: { col: 1, row: 1 } } } } }]); + assert.equal(await page.locator("#fig-bad").getAttribute("data-layout"), "stacked"); + assert.ok(warnings.some((w) => /puts a and b in one cell/.test(w)), JSON.stringify(warnings)); + await page.close(); + }); + + test("a one-column marked schema: turn-backs that state different things at one key take lanes of their own and draw", async () => { + const { page } = await reviewPage(); + await draw(page, [{ key: "one", spec: { type: "schema", title: "One column", summary: "s", tables: [ + { name: "users", col: 1, row: 1, columns: [{ name: "id", key: "PK" }] }, + { name: "a", col: 1, row: 2, columns: [{ name: "x", key: "FK", references: "users.id", cardinality: { from: "zero-or-many", to: "one" } }] }, + { name: "b", col: 1, row: 3, columns: [{ name: "y", key: "FK", references: "users.id", cardinality: { from: "zero-or-many", to: "zero-or-one" } }] }, + ] } }]); + const g = await inspect(page, "one"); + assert.equal(g.layout, "drawn"); + assert.equal(g.lines.length, 2); + assert.deepEqual(g.problems, []); + await page.close(); + }); + + test("placeDiagram: an empty figure and a cycle of groups answer; right to left a way-only column stays", async () => { + const { placeDiagram } = await import(pathToFileURL(path.join(pkg, "dist", "diagram-layout.js")).href); + const empty = await placeDiagram({ type: "architecture", nodes: [], edges: [] }, "right"); + assert.deepEqual([empty.cols, empty.rows], [1, 1]); + const cyc = await Promise.race([placeDiagram({ type: "architecture", groups: [{ id: "g", label: "G", parent: "h" }, { id: "h", label: "H", parent: "g" }], nodes: [{ id: "a", group: "g" }, { id: "b", group: "h" }], edges: [{ from: "a", to: "b", kind: "main" }] }, "down"), new Promise((r) => setTimeout(() => r("hung"), 5000))]); + assert.notEqual(cyc, "hung"); + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const placement = { direction: "down", cols: 2, rows: 2, cells: { a: { col: 2, row: 1 }, b: { col: 2, row: 2 } } }; + const spec = { type: "architecture", layout: "auto", title: "t", summary: "s", nodes: [{ id: "a", name: "A" }, { id: "b", name: "B" }], edges: [{ from: "a", to: "b", kind: "main" }] }; + assert.equal(core.buildModel(spec, { placement }).cols, 2); + assert.equal(core.buildModel(spec, { placement, rtl: true }).cols, 2); + }); + + test("a straight line and two others on one half grow a card to 48, not 49 (Neon P1)", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const n = (id, col, row) => ({ id, name: id, kind: "part", col, row }); + const m = core.buildModel({ type: "architecture", title: "t", summary: "s", nodes: [n("a", 1, 1), n("b", 2, 1), n("c", 2, 2), n("d", 2, 3)], edges: [{ from: "a", to: "b" }, { from: "a", to: "c" }, { from: "a", to: "d" }] }, { checks: false }); + assert.equal(core.portFloors(m).a, 48); + }); +}); + +describe("the sequence's fit and order (Neon B7, P8)", () => { + test("words that would lie on a frame's side stack the figure, and only for that; the lifelines are under the frames, the bars and lines over them", async () => { + const { page } = await reviewPage(); + // Opus's fixture on the re-check (R2): a note on the first message long enough to run across the start side of the frame below it. Its two controls + // fail the test if anything but B7a's rule stacks it: the same note with no frame draws, and a short note with the frame draws. + const spec = (note, frame = true) => ({ type: "sequence", title: "t", summary: "s", participants: [{ id: "a", name: "Alpha" }, { id: "b", name: "Bravo" }, { id: "c", name: "Charlie" }], + steps: [{ from: "a", to: "b", label: "first", note }, frame ? { frame: "opt", label: "if", steps: [{ from: "b", to: "c", label: "inside" }] } : { from: "b", to: "c", label: "inside" }] }); + const LONG = "a note long enough to run across the frame's start side and over it by a wide margin"; + await draw(page, [{ key: "cross", spec: spec(LONG) }, { key: "open", spec: spec(LONG, false) }, { key: "short", spec: spec("n") }, { key: "seq", spec: B.sequence }]); + const layout = (key) => page.locator(`#fig-${key}`).getAttribute("data-layout"); + assert.equal(await layout("open"), "drawn", "the long note with no frame draws: the room rule does not stack it"); + assert.equal(await layout("short"), "drawn", "a short note with the frame draws"); + assert.equal(await layout("cross"), "stacked", "the long note over the frame's side stacks the figure"); + const z = await page.evaluate((P) => { + const fig = document.querySelector("#fig-seq"); + const zi = (sel) => getComputedStyle(fig.querySelector(sel)).zIndex; + return { lifes: zi(`.${P}-lifes`), frame: zi(`.${P}-fbox`), lines: zi(`.${P}-ink > .${P}-svg`), said: zi(`.${P}-msg .${P}-said`), steps: zi(`.${P}-steps`), ink: zi(`.${P}-ink`) }; + }, P); + assert.deepEqual(z, { lifes: "0", frame: "1", lines: "2", said: "3", steps: "auto", ink: "auto" }); + await page.close(); + }); + + test("forced colours: a quiet run's head goes with its line", async () => { + const { page } = await reviewPage({ media: { forcedColors: "active" } }); + await draw(page, [{ key: "seq", spec: { ...B.sequence, motion: "animated", run: true } }]); + await page.evaluate(() => { const g = document.querySelector("#fig-seq .basalt-diagram-edge"); g.setAttribute("data-ahead", ""); }); + const c = await page.evaluate((P) => { const g = document.querySelector(`#fig-seq .${P}-edge[data-ahead]`); return { line: getComputedStyle(g.querySelector(`.${P}-line`)).stroke, tip: getComputedStyle(g.querySelector(`.${P}-tip`)).fill }; }, P); + assert.ok(c.line === c.tip || (c.tip === "none"), JSON.stringify(c)); + await page.close(); + }); +}); + +describe("the package's lazy parts (Neon B12)", () => { + test("the index and every diagram component reach diagram-layout, its graph, elkjs, export, the viewer, motion and the text art only by a dynamic import", () => { + const dist = path.join(pkg, "dist"); + const statics = (file) => [...fs.readFileSync(path.join(dist, file), "utf8").matchAll(/(?:^|[;\n])\s*(?:import|export)\s[^;]*?from\s*"(\.\/[^"]+)"|(?:^|[;\n])\s*import\s*"(\.\/[^"]+)"/g)].map((m) => path.normalize(path.join(path.dirname(file), m[1] ?? m[2]))); + const lazy = ["diagram-layout.js", "diagram-layout-graph.js", "diagram-elk.js", "diagram-export.js", "diagram-viewer.js", "diagram-motion.js", "diagram-text.js"]; + for (const entry of ["index.js", "architecture-diagram.js", "flowchart-diagram.js", "data-flow-diagram.js", "sequence-diagram.js", "schema-diagram.js"]) { + const seen = new Set([entry]); + const todo = [entry]; + while (todo.length) for (const next of statics(todo.pop())) if (!seen.has(next) && fs.existsSync(path.join(dist, next))) { seen.add(next); todo.push(next); } + for (const name of lazy) assert.ok(!seen.has(name), `${entry} reaches ${name} statically`); + for (const file of seen) assert.doesNotMatch(fs.readFileSync(path.join(dist, file), "utf8"), /Eclipse Layout Kernel/, `${entry} reaches elkjs through ${file}`); + } + }); +}); + +describe("motion (Neon B12: the quiet run and the first visit)", () => { + test("a drawn run quiets every message after the current one and restores them all when stopped", async () => { + const { page } = await reviewPage(); + await draw(page, [{ key: "seq", spec: { ...B.sequence, motion: "animated", run: true } }]); + await page.evaluate(() => document.getAnimations().forEach((a) => a.finish())); + await page.locator(`#fig-seq button`, { hasText: "Play the run" }).click(); + await page.waitForTimeout(250); + const during = await page.evaluate((P) => { const msgs = [...document.querySelectorAll(`#fig-seq .${P}-msg`)]; const k = msgs.findIndex((m) => m.hasAttribute("data-ahead")); return { first: k, after: msgs.slice(k).every((m) => m.hasAttribute("data-ahead")), label: k >= 0 ? getComputedStyle(msgs[k].querySelector(`.${P}-mlabel`)).color : null, rest: getComputedStyle(msgs[0].querySelector(`.${P}-mlabel`)).color }; }, P); + assert.ok(during.first > 0 && during.after, JSON.stringify(during)); + assert.notEqual(during.label, during.rest, "a quiet label is in another ink"); + await page.locator(`#fig-seq button`, { hasText: "Stop the run" }).click(); + await frames(page, 3); + assert.equal(await page.locator(`#fig-seq [data-ahead]`).count(), 0); + await page.close(); + }); + + test("entrance: first-visit stores a mark when the entrance finishes, and the next visit is at rest", async () => { + const { page } = await reviewPage(); + // On a real (fake-host) origin, so localStorage works: the fixture's own page, served there. + const html = await page.evaluate(() => { document.getElementById("root").replaceChildren(); return `${document.documentElement.outerHTML}`; }); + await page.route("https://basalt.test/**", (route) => route.fulfill({ contentType: "text/html", body: html })); + await page.goto("https://basalt.test/"); + await page.evaluate(() => document.fonts.ready); + const spec = { ...B.architecture, motion: "animated", entrance: "first-visit" }; + await draw(page, [{ key: "arch", spec }]); + await page.waitForFunction(() => document.querySelector("#fig-arch").getAttribute("data-entrance") === "running"); + await page.evaluate(() => document.getAnimations().forEach((a) => a.finish())); + await page.waitForFunction(() => document.querySelector("#fig-arch").getAttribute("data-entrance") === "done"); + const key = await page.evaluate(() => Object.keys(localStorage).find((k) => k.startsWith("basalt-diagram-entrance:"))); + assert.ok(key && key.endsWith("#fig-arch"), String(key)); + await page.evaluate(() => window.__set([])); + await frames(page, 2); + await draw(page, [{ key: "arch", spec }]); + assert.equal(await page.locator("#fig-arch").getAttribute("data-entrance"), "done", "the second visit is at rest from its first frame"); + await page.close(); + }); +}); + +describe("right to left, every figure (Neon B12)", () => { + for (const theme of ["dark", "light"]) test(`${theme}: the five extended figures drawn right to left pass the merged geometry suite at 1104`, async () => { + const { page } = await reviewPage({ theme }); + const keys = ["architecture", "flowchart", "dataFlow", "sequence", "schema"]; + await draw(page, keys.map((k) => ({ key: k, spec: B[k], dir: "rtl" }))); + for (const k of keys) { + const g = await inspect(page, k); + assert.equal(g.layout, "drawn", k); + assert.deepEqual(g.problems, [], `${k}: ${JSON.stringify(g.problems)}`); + } + await page.close(); + }); +}); diff --git a/packages/react/test/diagram-schema.test.mjs b/packages/react/test/diagram-schema.test.mjs new file mode 100644 index 00000000..ae67ea88 --- /dev/null +++ b/packages/react/test/diagram-schema.test.mjs @@ -0,0 +1,376 @@ +// A schema's cardinality and its far keys (DECISIONS 306, 1.1, revised by 313; section 8's list for diagram-schema.test.mjs), on the extended CIMIP +// schema (test/fixtures/cimip-diagrams-b.json: cardinality on every key, approvals.incident_id and approvals.decided_by two columns away) and small +// fixtures. In Chromium against the built package, both themes. The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import { pathToFileURL } from "node:url"; + +import * as esbuild from "esbuild"; + +import { inspectSource } from "./diagram-geometry.mjs"; +import { fixturePage, launch, pkg } from "./support.mjs"; + +const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +const A = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8")); +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:0 16px} #root{width:var(--w,1104px)}`; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const HOST = ` +function Host() { + const [list, setList] = React.useState([]); + window.__set = (next) => flushSync(() => setList(next)); + return
{list.map(({ key, spec }) => { const { type, ...props } = spec; return ; })}
; +} +createRoot(document.getElementById("root")).render();`; + +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 figurePage({ theme = "dark", width = 1440, dev = false } = {}) { + // A development build, so the warnings are written; the fixtures are production builds, which drop them. + const { page, errors } = await fixturePage(browser, "", { theme, viewport: { width, height: 1400 }, standards: true }); + const built = await esbuild.build({ + stdin: { contents: `import * as React from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import * as B from "./dist/index.js"; ${HOST}`, resolveDir: pkg, loader: "tsx" }, + bundle: true, format: "iife", write: false, jsx: "automatic", platform: "browser", logLevel: "silent", define: { "process.env.NODE_ENV": dev ? '"development"' : '"production"' }, + }); + const warnings = []; + page.on("console", (m) => { if (m.type() === "warning" || m.type() === "error") warnings.push(m.text()); }); + await page.addScriptTag({ content: built.outputFiles[0].text }); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + return { page, errors, warnings }; +} +const draw = async (page, items) => { await page.evaluate((items) => window.__set(items), items); await frames(page, 5); }; +const widthTo = async (page, w) => { await page.evaluate((w) => document.getElementById("root").style.setProperty("--w", `${w}px`), w); await frames(page, 5); }; +const inspect = (page, key) => page.evaluate(`${inspectSource()}("${P}", "#fig-${key}")`); + +/** Each drawn foreign key: its path's points, its marks (bars' x, a foot's point, a ring), the tables' edges, and computed inks. */ +const readLines = (page, key) => page.evaluate(({ P, key }) => { + const fig = document.querySelector(`#fig-${key}`); + const drawing = fig.querySelector(`.${P}-drawing`); + const o = drawing.getBoundingClientRect(); + const rect = (id) => { const r = fig.querySelector(`.${P}-node[data-node="${id}"]`).getBoundingClientRect(); return { l: r.left - o.left, r: r.right - o.left, t: r.top - o.top, b: r.bottom - o.top }; }; + const nums = (d) => d.match(/-?[\d.]+/g).map(Number); + return [...fig.querySelectorAll(`.${P}-edge`)].map((g) => { + const line = g.querySelector(`.${P}-line`); + const d = line.getAttribute("d"); + // The route's points (a Q's control point is the corner) and the runs written between corners (L … then Q): where each elbow starts and ends. + const pts = [], straight = []; + for (const m of d.matchAll(/([MLQ])([^MLQ]*)/g)) { + const n = m[2].trim().split(/[ ,]+/).map(Number); + if (m[1] === "Q") { straight.push({ x: n[2], y: n[3] }); pts.pop(); pts.push({ x: n[0], y: n[1] }); } else { pts.push({ x: n[0], y: n[1] }); straight.push({ x: n[0], y: n[1] }); } + } + const end = (which) => { + const crow = g.querySelector(`.${P}-crow[data-end="${which}"]`); + const ring = g.querySelector(`.${P}-ring[data-end="${which}"]`); + return crow ? { crow: crow.getAttribute("d"), segs: [...crow.getAttribute("d").matchAll(/M([^M]*)/g)].map((s) => nums(s[1])), ring: ring ? { cx: +ring.getAttribute("cx"), cy: +ring.getAttribute("cy"), r: +ring.getAttribute("r") } : null, stroke: getComputedStyle(crow).stroke, ringStroke: ring ? getComputedStyle(ring).stroke : null, ringFill: ring ? getComputedStyle(ring).fill : null } : null; + }; + return { i: g.dataset.edge, from: g.dataset.from, to: g.dataset.to, d, pts, straight, stroke: getComputedStyle(line).stroke, tip: !!g.querySelector(`.${P}-tip`), dot: !!g.querySelector(`.${P}-dot`), fromEnd: end("from"), toEnd: end("to"), a: rect(g.dataset.from), b: rect(g.dataset.to), ox: o.left - Math.floor(o.left), oy: o.top - Math.floor(o.top) }; + }); +}, { P, key }); + +const col = (name, extra = {}) => ({ name, type: "text", ...extra }); +const fk = (name, references, from, to) => ({ name, key: "FK", references, ...(from ? { cardinality: { from, ...(to ? { to } : {}) } } : {}) }); +const table = (name, c, r, columns) => ({ name, col: c, row: r, columns }); +const schema = (tables, extra = {}) => ({ type: "schema", title: "A schema", summary: "Tables and their keys.", legend: { plain: "A foreign key" }, tables, ...extra }); + +// Four forms on straight lines, each from its own row to the row level with it. +const FORMS = [["one", "one"], ["zero-or-one", "zero-or-one"], ["one-or-many", "one"], ["zero-or-many", "zero-or-one"]]; +const formsSpec = schema([ + table("a", 1, 1, FORMS.map(([from, to], k) => fk(`k${k}`, `b.c${k}`, from, to))), + table("b", 2, 1, FORMS.map((_, k) => col(`c${k}`, { key: k ? undefined : "PK" }))), +]); +// n lines from a's first rows to b's rows below them: their runs in the gutter overlap, so they take n lanes. +const lanesSpec = (n) => schema([ + table("a", 1, 1, Array.from({ length: n }, (_, k) => fk(`f${k}`, `b.x${n + k}`, "zero-or-many", "one"))), + table("b", 2, 1, Array.from({ length: 2 * n }, (_, k) => col(`x${k}`))), +]); +// Three far lines from z to three keys of x, over a table that spans both rows of column 2: all three take the margin above. +const corridorSpec = schema([ + table("x", 1, 1, [col("p0", { key: "PK" }), col("p1"), col("p2")]), + table("y", 2, [1, 2], [col("id", { key: "PK" })]), + table("w", 1, 2, [col("id", { key: "PK" })]), + table("z", 3, 1, [fk("r0", "x.p0"), fk("r1", "x.p1"), fk("r2", "x.p2")]), +]); + +describe("the four forms", () => { + for (const theme of ["dark", "light"]) test(`${theme}: each form's marks at its distances, on the shaft, snapped with the line, in the line's ink at rest, traced and dimmed`, async () => { + const { page, errors } = await figurePage({ theme }); + await draw(page, [{ key: "forms", spec: formsSpec }]); + assert.equal(await page.locator("#fig-forms").getAttribute("data-layout"), "drawn"); + const lines = await readLines(page, "forms"); + assert.equal(lines.length, 4); + // Where each mark's ink is, from its table's edge along the line: a bar is the pixel ending at its distance; a foot's point; a ring's middle. + const read = (end, edge, y, out) => { + const bars = [], foot = []; + for (const s of end.segs) { + if (s.length === 3) bars.push((s[0] - edge) * out + 0.5); // M x y V y2: x is the bar's middle + else foot.push(s); + } + return { bars: bars.sort((p, q) => p - q), foot: foot.length ? (foot[0][2] - edge) * out : null, footSpread: foot.length ? [foot[0][1] - y, foot[0][5] - y] : null, ring: end.ring ? (end.ring.cx - edge) * out : null, ringR: end.ring?.r }; + }; + const want = { + one: { bars: [4, 8], foot: null, ring: null }, + "zero-or-one": { bars: [4], foot: null, ring: 10.5 }, + "one-or-many": { bars: [11], foot: 7.5, ring: null }, + "zero-or-many": { bars: [], foot: 7.5, ring: 10.5 }, + }; + lines.sort((p, q) => p.pts[0].y - q.pts[0].y); + lines.forEach((l, k) => { + const [fromForm, toForm] = FORMS[k]; + assert.ok(!l.tip && !l.dot, "no head and no dot where the cardinality is stated"); + const y = l.pts[0].y; + assert.equal(l.pts.length, 2, "a straight line"); + // The shaft runs from table edge to table edge, on whole pixels of the edge. + assert.ok(Math.abs(l.pts[0].x - l.a.r) <= 0.5 && Math.abs(l.pts[1].x - l.b.l) <= 0.5, "the shaft runs to both tables' edges"); + const f = read(l.fromEnd, l.pts[0].x, y, 1), t = read(l.toEnd, l.pts[1].x, y, -1); + for (const [got, form] of [[f, fromForm], [t, toForm]]) { + assert.deepEqual(got.bars, want[form].bars, `${form}: its bars`); + assert.equal(got.foot, want[form].foot, `${form}: its foot's point`); + if (got.foot !== null) assert.deepEqual(got.footSpread, [-4, 4], `${form}: its spokes end space-1 either side`); + assert.equal(got.ring, want[form].ring, `${form}: its ring`); + if (got.ring !== null) { + assert.equal(got.ringR, 3, "a ring is size-dot across its stroke's middle"); + assert.deepEqual([got.ring - got.ringR - 0.5, got.ring + got.ringR + 0.5], [7, 14], "its ink runs from 7 to 14, inside the zone"); + } + // Every mark's ink inside the 14px zone. + for (const b of got.bars) assert.ok(b - 1 >= 0 && b <= 14, `${form}: a bar inside the zone`); + } + // Snapped with the line: the line on a half pixel, a bar's middle on a half pixel, both in the page's grid. + const half = (v, off) => Math.abs(((v + off) % 1 + 1) % 1 - 0.5) < 0.02; + assert.ok(half(y, l.oy), `the line is on a half pixel (${y})`); + for (const s of [...l.fromEnd.segs, ...l.toEnd.segs].filter((s) => s.length === 3)) assert.ok(half(s[0], l.ox), `a bar is on a half pixel (${s[0]})`); + // In the line's own ink at rest; the ring is filled with the ground. + for (const e of [l.fromEnd, l.toEnd]) { assert.equal(e.stroke, l.stroke); if (e.ring) assert.equal(e.ringStroke, l.stroke); } + }); + const ground = await page.evaluate((P) => getComputedStyle(document.querySelector("#fig-forms")).getPropertyValue("--_ground").trim(), P); + assert.ok(ground, "the figure has a ground"); + // Traced (a hovered table) the marks take the main ink, and every other line's marks dim with their line. + const inks = await page.evaluate((P) => { const s = getComputedStyle(document.querySelector("#fig-forms")); return { main: s.getPropertyValue("--basalt-diagram-edge-main").trim(), dim: s.getPropertyValue("--basalt-diagram-edge-dim").trim() }; }, P); + await page.hover(`#fig-forms .${P}-node[data-node="a"]`); + await page.waitForTimeout(250); + const lit = await readLines(page, "forms"); + for (const l of lit) for (const e of [l.fromEnd, l.toEnd]) { assert.equal(e.stroke, l.stroke, "traced: the marks keep the line's ink"); if (e.ring) assert.equal(e.ringStroke, l.stroke); } + const litStroke = lit[0].stroke; + // Dimmed: draw a second figure's line... a table with no lines dims every line: use a schema where one table has its own line. + await draw(page, [{ key: "forms", spec: schema([...formsSpec.tables, table("c", 3, 1, [col("id", { key: "PK" }), fk("b0", "b.c0", "zero-or-many", "one")])]) }]); + await page.hover(`#fig-forms .${P}-node[data-node="c"]`); + await page.waitForTimeout(250); + const dim = (await readLines(page, "forms")).filter((l) => l.from === "a"); + assert.ok(dim.length === 4); + for (const l of dim) { assert.notEqual(l.stroke, litStroke, "the other lines dim"); for (const e of [l.fromEnd, l.toEnd]) assert.equal(e.stroke, l.stroke, "dimmed: the marks keep the line's ink"); } + void inks; + assert.deepEqual(errors, []); + await page.close(); + }); +}); + +describe("the zone, the gap and the lanes", () => { + test("no elbow starts inside the 14px zone; the gap is 60 with marks and 48 without", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "marked", spec: B.schema }, { key: "plain", spec: A.schema }]); + const gap = (key) => page.evaluate(({ P, key }) => parseFloat(getComputedStyle(document.querySelector(`#fig-${key} .${P}-drawing`)).columnGap), { P, key }); + assert.equal(await gap("marked"), 60); + assert.equal(await gap("plain"), 48); + assert.equal(await page.locator("#fig-marked").getAttribute("data-marks"), ""); + assert.equal(await page.locator("#fig-plain").getAttribute("data-marks"), null); + for (const l of await readLines(page, "marked")) { + // The written runs: the first L after M, and the last point before the end, are where the first and last elbows start. + const s = l.straight; + if (s.length < 3) continue; + const first = Math.hypot(s[1].x - s[0].x, s[1].y - s[0].y), last = Math.hypot(s[s.length - 1].x - s[s.length - 2].x, s[s.length - 1].y - s[s.length - 2].y); + assert.ok(first >= 14 - 0.01, `${l.from} to ${l.to}: its first elbow starts ${first.toFixed(2)} from the edge`); + assert.ok(last >= 14 - 0.01, `${l.from} to ${l.to}: its last elbow ends ${last.toFixed(2)} from the edge`); + } + await page.close(); + }); + + for (const theme of ["dark", "light"]) test(`${theme}: a marked gutter's lanes are at 30; 20 and 40; 18, 30 and 42, every elbow 3.5 or more outside the zone; a fourth leaves one line out and warns`, async () => { + const { page, warnings } = await figurePage({ theme, dev: true }); + for (const [n, want] of [[1, [30]], [2, [20, 40]], [3, [18, 30, 42]]]) { + await draw(page, [{ key: "lanes", spec: lanesSpec(n) }]); + assert.equal(await page.locator("#fig-lanes").getAttribute("data-layout"), "drawn", `${n} lanes: drawn`); + const lines = await readLines(page, "lanes"); + assert.equal(lines.length, n); + const xs = lines.map((l) => l.pts[1].x - l.a.r).sort((p, q) => p - q); + xs.forEach((x, k) => assert.ok(Math.abs(x - want[k]) <= 0.5, `${n} lanes: lane ${k + 1} at ${x} (${want[k]})`)); + for (const l of lines) { + const s = l.straight; + const first = Math.hypot(s[1].x - s[0].x, s[1].y - s[0].y), last = Math.hypot(s[s.length - 1].x - s[s.length - 2].x, s[s.length - 1].y - s[s.length - 2].y); + assert.ok(first >= 14 && last >= 14, `${n} lanes: the elbows start outside the zone (${first}, ${last})`); + // The lane's room outside the zone: its distance from either table less 14. + assert.ok(Math.min(l.pts[1].x - l.a.r, l.b.l - l.pts[1].x) - 14 >= 3.5, `${n} lanes: 3.5 or more outside the zone`); + } + } + warnings.length = 0; + await draw(page, [{ key: "lanes", spec: lanesSpec(4) }]); + assert.equal(await page.locator("#fig-lanes").getAttribute("data-layout"), "drawn", "a tight line never stacks the figure"); + const four = await readLines(page, "lanes"); + assert.equal(four.length, 3, "one line is left out"); + assert.ok(!four.some((l) => l.i === "3"), "the later in the author's order"); + assert.ok(warnings.some((w) => /a\.f3|a to b would need a fourth lane in a marked gutter/.test(w)), JSON.stringify(warnings)); + // Its row still writes the target. + assert.match(await page.locator(`#fig-lanes .${P}-node[data-node="a"] .${P}-row[data-row="3"] .${P}-ctype`).textContent(), /→ b/); + await page.close(); + }); +}); + +describe("the extended CIMIP schema", () => { + for (const theme of ["dark", "light"]) test(`${theme}: drawn at 1,104 with every key drawn, and at 1,096; its far keys pass through no table and every crossing is cut, before and during a trace`, async () => { + const { page, errors } = await figurePage({ theme }); + await draw(page, [{ key: "schema", spec: B.schema }]); + const keys = B.schema.tables.flatMap((t) => t.columns.filter((c) => c.references).map((c) => `${t.name}>${c.references.split(".")[0]}`)); + for (const w of [1104, 1096]) { + await widthTo(page, w); + const g = await inspect(page, "schema"); + assert.equal(g.layout, "drawn", `drawn at ${w}`); + assert.deepEqual(g.problems, [], `${w}: ${JSON.stringify(g.problems)}`); + assert.deepEqual(g.lines.map((l) => `${l.from}>${l.to}`).sort(), keys.slice().sort(), `${w}: every key is drawn`); + assert.ok(g.crossings.every((c) => c.cut), JSON.stringify(g.crossings)); + } + await widthTo(page, 1104); + // The far keys: approvals to incidents along the margin above, approvals to users along the gap between rows 2 and 3. + const lines = await readLines(page, "schema"); + const far = (to) => lines.find((l) => l.from === "approvals" && l.to === to && Math.abs(l.a.l - l.b.r) > 300); + const inc = far("incidents"), users = far("users"); + assert.ok(inc && users, "both far keys are drawn"); + const rects = await page.evaluate((P) => { const o = document.querySelector(`#fig-schema .${P}-drawing`).getBoundingClientRect(); return Object.fromEntries([...document.querySelectorAll(`#fig-schema .${P}-node`)].map((n) => { const r = n.getBoundingClientRect(); return [n.dataset.node, { t: r.top - o.top, b: r.bottom - o.top }]; })); }, P); + const runY = (l) => l.pts[2].y; + assert.ok(runY(inc) < rects.agent_runs.t, "approvals to incidents runs above the first row"); + assert.ok(runY(inc) > 0, "inside the drawing"); + assert.ok(runY(users) > rects.agent_runs.b && runY(users) < rects.sandboxes.t, "approvals to users runs in the gap between rows 2 and 3"); + // The rows: a margin corridor adds space-8 above the first row, the gap that carries a corridor is space-10, the other stays space-8, and no + // margin below. One lane in the gap's middle (space-3-5 clear of each side with two); the margin's lane space-4 above the first row. + const tracks = await page.evaluate((P) => getComputedStyle(document.querySelector(`#fig-schema .${P}-drawing`)).gridTemplateRows.split(" ").map(parseFloat), P); + assert.deepEqual([tracks.length, tracks[0], tracks[2], tracks[4], tracks[6]], [7, 32, 32, 40, 0]); + const gapTop = tracks[0] + tracks[1] + tracks[2] + tracks[3]; + assert.ok(Math.abs(runY(users) - (gapTop + 20)) <= 0.5, `one lane, in the gap's middle (${runY(users)}, ${gapTop})`); + assert.ok(Math.abs(rects.room_events.t - runY(inc) - 16) <= 0.5, "the margin's lane is space-4 out"); + assert.equal(rects.sandboxes.t, gapTop + 40); + // During a trace every crossing is still cut, the traced line on top. + await page.hover(`#fig-schema .${P}-node[data-node="approvals"]`); + await page.waitForTimeout(250); + const traced = await inspect(page, "schema"); + assert.deepEqual(traced.problems, [], JSON.stringify(traced.problems)); + assert.ok(traced.crossings.every((c) => c.cut)); + assert.deepEqual(errors, []); + await page.close(); + }); + + test("two arrivals at one key that state different things are 8px apart; the same thing shares a bus", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "two", spec: schema([ + table("a", 1, 1, [col("id", { key: "PK" }), fk("u", "b.id", "zero-or-many", "one")]), + table("c", 1, 2, [col("id", { key: "PK" }), fk("u", "b.id", "zero-or-many", "zero-or-one")]), + table("d", 1, 3, [col("id", { key: "PK" }), fk("u", "b.id", "zero-or-many", "one")]), + table("b", 2, 2, [col("id", { key: "PK" })]), + ]) }]); + const lines = await readLines(page, "two"); + assert.equal(lines.length, 3); + const tip = (from) => lines.find((l) => l.from === from).pts.at(-1); + assert.equal(tip("c").y - tip("a").y, 8, "the two statements arrive 8 apart"); + assert.equal(tip("a").y, tip("d").y, "the same statement shares its arrival"); + const lastX = (from) => lines.find((l) => l.from === from).pts.at(-2).x; + assert.equal(lastX("a"), lastX("d"), "and its bus"); + assert.notEqual(lastX("a"), lastX("c"), "a different statement takes its own lane"); + await page.close(); + }); + + test("a third line in one corridor is left out alone, and a development build names it", async () => { + const { page, warnings } = await figurePage({ dev: true }); + await draw(page, [{ key: "corr", spec: corridorSpec }]); + assert.equal(await page.locator("#fig-corr").getAttribute("data-layout"), "drawn"); + const lines = await readLines(page, "corr"); + assert.deepEqual(lines.map((l) => l.i).sort(), ["0", "1"], "the third, in the author's order, is left out"); + assert.ok(warnings.some((w) => /z to x would need a third lane in its corridor/.test(w)), JSON.stringify(warnings)); + const g = await inspect(page, "corr"); + assert.deepEqual(g.problems, []); + // Two lanes in the margin, space-4 and space-4 plus space-3 above the first row; the farther-going outermost (here: equal, so nested by its run). + const top = await page.evaluate((P) => { const o = document.querySelector(`#fig-corr .${P}-drawing`).getBoundingClientRect(); return document.querySelector(`#fig-corr .${P}-node[data-node="x"]`).getBoundingClientRect().top - o.top; }, P); + assert.deepEqual(lines.map((l) => Math.round(top - l.pts[2].y)).sort((p, q) => p - q), [16, 28]); + await page.close(); + }); +}); + +describe("the key, the list and the row", () => { + for (const theme of ["dark", "light"]) test(`${theme}: the key shows exactly the forms drawn, and none stacked; the list and the sentence carry the words; the row is unchanged`, async () => { + const { page } = await figurePage({ theme }); + await draw(page, [{ key: "schema", spec: B.schema }, { key: "half", spec: schema([table("a", 1, 1, [col("id", { key: "PK" }), fk("b_id", "b.id", "one", "one")]), table("b", 2, 1, [col("id", { key: "PK" })])]) }]); + const shown = (key) => page.evaluate(({ P, key }) => [...document.querySelectorAll(`#fig-${key} .${P}-entry`)].filter((e) => getComputedStyle(e).display !== "none").map((e) => e.textContent), { P, key }); + assert.deepEqual(await shown("schema"), ["PKPrimary key", "FKForeign key", "Exactly one", "Zero or one", "One or many", "Zero or many", "The table most of the others reference"]); + assert.deepEqual(await shown("half"), ["PKPrimary key", "FKForeign key", "Exactly one"], "only the forms drawn"); + // Each swatch is a 24px line carrying its form. + const sw = await page.evaluate((P) => [...document.querySelectorAll(`#fig-schema .${P}-swatch[data-card]`)].map((s) => [s.dataset.card, s.getAttribute("width"), !!s.querySelector(`.${P}-crow`), !!s.querySelector(`.${P}-ring`)]), P); + assert.deepEqual(sw, [["one", "24", true, false], ["zero-or-one", "24", true, true], ["one-or-many", "24", true, false], ["zero-or-many", "24", true, true]]); + // The list: "decided_by, foreign key, references users.id (zero or many approvals to zero or one users)". + const item = await page.evaluate((P) => [...document.querySelectorAll(`#fig-schema .${P}-list li`)].map((li) => li.textContent).find((t) => t.startsWith("decided_by")), P); + assert.equal(item, "decided_by, foreign key, references users.id (zero or many approvals to zero or one users)"); + const sentence = await page.locator(`#fig-schema .${P}-node[data-node="approvals"]`).getAttribute("aria-label"); + assert.match(sentence, /users \(decided_by: zero or many approvals to zero or one users\)/); + assert.match(await page.locator(`#fig-schema .${P}-node[data-node="users"]`).getAttribute("aria-label"), /approvals \(decided_by: zero or many approvals to zero or one users\)/); + // The row writes its target, as it did; no tag. + const row = await page.evaluate((P) => [...document.querySelectorAll(`#fig-schema .${P}-node[data-node="approvals"] .${P}-row`)].map((r) => r.textContent), P); + assert.deepEqual(row, ["PKidtext", "FKincident_id→ incidents", "FKrun_id→ agent_runs", "FKdecided_by→ users", "commandtext", "risklow | medium | high", "statuspending"]); + // Stacked: no lines, so no marks, and the key keeps the foreign key's arrow. + await widthTo(page, 390); + assert.equal(await page.locator("#fig-schema").getAttribute("data-layout"), "stacked"); + const stacked = await shown("schema"); + assert.ok(!stacked.some((t) => /Exactly one|Zero or|One or many/.test(t)), JSON.stringify(stacked)); + assert.ok(stacked.includes("→The table a foreign key references"), JSON.stringify(stacked)); + assert.equal(await page.locator(`#fig-schema .${P}-drawing .${P}-crow`).count(), 0); + await page.close(); + }); +}); + +describe("modes", () => { + test("forced colours: the marks follow their line and a ring's fill is Canvas; print: the resting ink over a trace", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "forms", spec: formsSpec }]); + await page.emulateMedia({ forcedColors: "active" }); + await frames(page, 3); + let l = (await readLines(page, "forms"))[1]; + assert.equal(l.fromEnd.stroke, l.stroke); + assert.equal(l.toEnd.ringFill, await page.evaluate(() => { const d = document.createElement("div"); d.style.color = "Canvas"; document.body.append(d); const c = getComputedStyle(d).color; d.remove(); return c; })); + await page.emulateMedia({ forcedColors: "none", media: "print" }); + await page.hover(`#fig-forms .${P}-node[data-node="a"]`); + await frames(page, 3); + const rest = await page.evaluate(() => getComputedStyle(document.querySelector("#fig-forms")).getPropertyValue("--basalt-diagram-edge").trim()); + l = (await readLines(page, "forms"))[0]; + const probe = await page.evaluate((c) => { const d = document.createElement("div"); d.style.color = c; document.querySelector("#fig-forms").append(d); const v = getComputedStyle(d).color; d.remove(); return v; }, rest); + assert.equal(l.fromEnd.stroke, probe, "printed untraced, in the resting ink"); + await page.close(); + }); +}); + +describe("development errors", () => { + test("cardinality without references, a referenced end of many, and some keys stated and not all", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + // 5.1's first list: errors (Model.errors, which the figure reports with console.error), never warnings (the decider's ruling 1 on the re-check). + const warns = (tables) => core.buildModel(schema(tables)).errors; + const b = table("b", 2, 1, [col("id", { key: "PK" })]); + assert.ok(warns([table("a", 1, 1, [{ name: "x", cardinality: { from: "one" } }]), b]).some((w) => /a\.x states a cardinality but references nothing/.test(w))); + assert.ok(warns([table("a", 1, 1, [fk("x", "b.id", "one", "one-or-many")]), b]).some((w) => /references one row at most/.test(w))); + assert.ok(warns([table("a", 1, 1, [fk("x", "b.id", "one"), fk("y", "b.id")]), b]).some((w) => /stated on 1 of 2 foreign keys.*a\.y has none/.test(w))); + assert.ok(warns([table("a", 1, 1, [fk("x", "b.id", "many")]), b]).some((w) => /not one, zero-or-one, one-or-many or zero-or-many/.test(w))); + // None of them in a figure that states every key. + assert.deepEqual(core.buildModel(B.schema).warnings, []); + assert.deepEqual(core.buildModel(B.schema).errors, []); + // The referenced end defaults to one. + assert.deepEqual(core.buildModel(schema([table("a", 1, 1, [fk("x", "b.id", "zero-or-many")]), b])).edges[0].card, { from: "zero-or-many", to: "one" }); + }); + test("production: an unstated line in a figure that states some draws as today, and the key shows both", async () => { + const { page } = await figurePage(); + await draw(page, [{ key: "mixed", spec: schema([table("a", 1, 1, [fk("x", "b.id", "one"), fk("y", "b.k")]), table("b", 2, 1, [col("id", { key: "PK" }), col("k")])]) }]); + const lines = await readLines(page, "mixed"); + assert.deepEqual(lines.map((l) => [l.tip, l.dot, !!l.fromEnd]), [[false, false, true], [true, true, false]]); + const shown = await page.evaluate((P) => [...document.querySelectorAll(`#fig-mixed .${P}-entry`)].filter((e) => getComputedStyle(e).display !== "none").map((e) => e.textContent), P); + assert.deepEqual(shown, ["PKPrimary key", "FKForeign key", "A foreign key", "Exactly one"]); + await page.close(); + }); +}); diff --git a/packages/react/test/diagram-sequence.test.mjs b/packages/react/test/diagram-sequence.test.mjs new file mode 100644 index 00000000..40e3d62a --- /dev/null +++ b/packages/react/test/diagram-sequence.test.mjs @@ -0,0 +1,163 @@ +// A sequence's activations and frames (DECISIONS 306, 1.2; section 8's list for diagram-sequence.test.mjs), on the extended CIMIP sequence +// (test/fixtures/cimip-diagrams-b.json), and the text variant. In Chromium against the built package, both themes. +// The implementation hasn't been reviewed. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import { pathToFileURL } from "node:url"; + +import { fixturePage, launch, pkg } from "./support.mjs"; + +const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +const P = "basalt-diagram"; +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const HOST = ` +import data from "./test/fixtures/cimip-diagrams-b.json"; +function Host() { + const [spec, setSpec] = React.useState(() => { const { type, ...props } = data.sequence; return props; }); + window.__set = (next) => flushSync(() => setSpec(next)); + return ; +} +createRoot(document.getElementById("root")).render();`; +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 seqPage({ theme = "dark", width = 1440 } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height: 1200 } }); + await page.addStyleTag({ content: "body{margin:0;padding:16px} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + return { page, errors }; +} +const read = (page) => page.evaluate((P) => { + const fig = document.querySelector("#seq"); + const d = fig.querySelector(`.${P}-drawing`).getBoundingClientRect(); + const rel = (r) => ({ l: r.left - d.left, r: r.right - d.left, t: r.top - d.top, b: r.bottom - d.top }); + return { + layout: fig.getAttribute("data-layout"), w: d.width, h: d.height, + bars: [...fig.querySelectorAll(`.${P}-svg .${P}-bar`)].map((b) => ({ ...rel(b.getBoundingClientRect()), fill: getComputedStyle(b).fill, stroke: getComputedStyle(b).stroke })), + lives: [...fig.querySelectorAll(`.${P}-life`)].filter((l) => !l.closest(`.${P}-swatch`)).map((l) => rel(l.getBoundingClientRect()).l), + lines: [...fig.querySelectorAll(`.${P}-edge`)].map((g) => ({ i: g.dataset.edge, d: g.querySelector(`.${P}-line`).getAttribute("d"), tip: g.querySelector(`.${P}-tip`)?.getAttribute("d") })), + boxes: [...fig.querySelectorAll(`.${P}-fbox`)].map((b) => ({ ...rel(b.getBoundingClientRect()), depth: b.parentElement.dataset.depth, op: b.parentElement.dataset.op, border: getComputedStyle(b).borderTopWidth, style: getComputedStyle(b).borderTopStyle })), + heads: [...fig.querySelectorAll(`.${P}-node`)].map((n) => rel(n.getBoundingClientRect())), + nums: [...fig.querySelectorAll(`.${P}-drawing .${P}-num`)].map((n) => n.textContent), + key: [...fig.querySelectorAll(`.${P}-entry`)].filter((e) => getComputedStyle(e).display !== "none").map((e) => e.textContent), + list: [...fig.querySelectorAll(`.${P}-list .${P}-list-group`)].map((e) => e.textContent), + }; +}, P); + +describe("activations", () => { + for (const theme of ["dark", "light"]) test(`${theme}: bars are 8 wide on their lifelines, in the head's fill and a structure edge; lines end on a bar's edge`, async () => { + const { page, errors } = await seqPage({ theme }); + const g = await read(page); + assert.equal(g.layout, "drawn"); + assert.equal(g.bars.length, 2, "the service's bar and the sandbox's"); + for (const bar of g.bars) { + assert.ok(Math.abs(bar.r - bar.l - 8) <= 1, `width ${bar.r - bar.l}`); + assert.ok(g.lives.some((x) => Math.abs((bar.l + bar.r) / 2 - x) <= 1), "centred on a lifeline"); + assert.notEqual(bar.fill, "none"); + } + // Message 6 (POST /v1/runs) opens the sandbox's bar: its head's point is on the bar's start edge. + const six = g.lines.find((l) => l.i === "6"); + const endX = Number(/^M([\d.]+) /.exec(six.tip)[1]); + const agentBar = g.bars.sort((a, b) => b.l - a.l)[0]; + assert.ok(Math.abs(endX - agentBar.l) <= 1, `${endX} against ${agentBar.l}`); + assert.deepEqual(errors, []); + await page.close(); + }); +}); + +describe("frames", () => { + for (const theme of ["dark", "light"]) test(`${theme}: every frame has four solid sides inside the drawing and spans its participants; a nested frame is 8px inside where they share a side; the key and the list say the operators`, async () => { + const { page } = await seqPage({ theme }); + const g = await read(page); + assert.equal(g.boxes.length, 3); + for (const b of g.boxes) { + assert.equal(b.border, "1px"); + assert.equal(b.style, "solid"); + assert.ok(b.l >= -0.01 && b.r <= g.w + 0.01 && b.t >= -0.01 && b.b <= g.h + 0.01, `${b.op} inside the drawing`); + } + const opt = g.boxes.find((b) => b.op === "opt"), loop = g.boxes.find((b) => b.op === "loop"), alt = g.boxes.find((b) => b.op === "alt"); + // opt spans the service to the sandbox: from the service head's start edge to the sandbox head's end edge. + assert.ok(Math.abs(opt.l - g.heads[1].l) <= 1 && Math.abs(opt.r - g.heads[3].r) <= 1, "opt spans its participants"); + assert.ok(Math.abs(loop.l - opt.l - 8) <= 1, "the loop is 8 inside the opt at their shared start side"); + assert.ok(Math.abs(alt.l) <= 1 && Math.abs(alt.r - g.w) <= 1, "alt spans every participant"); + assert.deepEqual(g.nums, Array.from({ length: 13 }, (_, k) => String(k + 1)), "messages number straight through"); + for (const words of ["optOnly if", "loopRepeats", "altOne of these", "Working"]) assert.ok(g.key.some((k) => k.replace(/\s+/g, "") === words.replace(/\s+/g, "")), `the key says ${words}`); + assert.deepEqual(g.list.filter((t) => /^(Only if|Repeats|One of these|Otherwise):/.test(t)), ["Only if: First run on an incident only", "Repeats: Until private IP", "One of these: Approved", "Otherwise: Rejected or timed out"]); + await page.close(); + }); + test("stacked, the frames box their rows and messages keep their numbers", async () => { + const { page } = await seqPage({ width: 390 }); + const g = await read(page); + assert.equal(g.layout, "stacked"); + assert.equal(g.boxes.length, 3); + assert.deepEqual(g.nums, Array.from({ length: 13 }, (_, k) => String(k + 1))); + await page.close(); + }); + test("a header too long for its frame stacks the figure", async () => { + const { page } = await seqPage(); + await page.evaluate((spec) => { + const { type, ...props } = spec; + props.steps = [{ frame: "opt", label: "A condition far longer than the two columns of one self-call can ever hold on its own line", steps: [{ from: "svc", to: "svc", label: "x" }] }]; + window.__set(props); + }, B.sequence); + await frames(page, 4); + assert.equal((await read(page)).layout, "stacked"); + await page.close(); + }); +}); + +describe("the text variant (1.2; section 8)", () => { + test("the art is byte-stable for fixed data, every frame has its four corners, and no lifeline glyph is inside a word", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const text = await import(pathToFileURL(path.join(pkg, "dist", "diagram-text.js")).href); + const m = () => core.buildModel(B.textSequence); + const a = text.textArt(m()).html, b = text.textArt(m()).html; + assert.equal(a, b, "the same data writes the same art"); + const rows = a.replace(/<[^>]+>/g, "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").split("\n"); + const count = (c) => rows.join("").split(c).length - 1; + assert.equal(count("┌"), count("└"), "every frame that opens closes"); + assert.equal(count("┐"), count("┘")); + // A word (a label) is never cut by a lifeline glyph: each label is found whole on one row. + for (const st of B.textSequence.steps.flatMap(function flat(s) { return s.steps ? s.steps.flatMap(flat) : s.branches ? s.branches.flatMap((x) => x.steps.flatMap(flat)) : [s]; })) { + if (st.label) assert.ok(rows.some((r) => r.includes(st.label)), `"${st.label}" is whole`); + } + }); + + for (const width of [1440, 390, 360]) test(`at ${width} the block never scrolls sideways; the pre is aria-hidden; the key's swatches are glyphs`, async () => { + const { page } = await fixturePage(browser, ` +import data from "./test/fixtures/cimip-diagrams-b.json"; +const { type, ...props } = data.textSequence; +createRoot(document.getElementById("root")).render();`, { standards: true, viewport: { width, height: 1200 } }); + await page.addStyleTag({ content: "body{margin:0;padding:16px} #root{max-width:1104px;margin:0 auto}" }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 6); + const got = await page.evaluate((P) => { + const pre = document.querySelector(`#text .${P}-text`); + const names = [...pre.querySelectorAll(`.${P}-tx-name`)].map((n) => n.getClientRects().length); + return { scroll: pre.scrollWidth - pre.clientWidth, hidden: pre.getAttribute("aria-hidden"), art: pre.hasAttribute("data-art"), broken: names.filter((n) => n > 1).length, swatches: document.querySelectorAll(`#text .${P}-swatch`).length, glyphs: document.querySelectorAll(`#text .${P}-key-glyph`).length }; + }, P); + assert.ok(got.scroll <= 1, JSON.stringify(got)); + assert.equal(got.hidden, "true"); + assert.equal(got.broken, 0, "no name breaks across lines"); + assert.equal(got.swatches, 0); + assert.ok(got.glyphs > 0); + if (width === 1440) assert.ok(got.art, "at 1440 the art fits"); + else assert.ok(!got.art, "on a phone, the transcript"); + await page.close(); + }); + + test("the bars: a bar left open closes at its participant's last message; development errors (Model.errors, the figure's console.error) for a deactivate with no bar, a fourth bar and frames", async () => { + const core = await import(pathToFileURL(path.join(pkg, "dist", "diagram-core.js")).href); + const seq = (steps) => core.buildModel({ type: "sequence", title: "t", summary: "s", participants: [{ id: "a", name: "A" }, { id: "b", name: "B" }], steps }); + const open = seq([{ from: "a", to: "b", label: "1", activate: true }, { from: "a", to: "b", label: "2" }, { from: "b", to: "a", label: "3" }]); + assert.deepEqual(open.bars.map((x) => [x.who, x.from, x.to]), [["b", 1, 3]]); + assert.ok(seq([{ from: "a", to: "b", label: "1", deactivate: true }]).errors.some((w) => /closes a bar on a, which has none open/.test(w))); + assert.ok(seq([1, 2, 3, 4].map((n) => ({ from: "a", to: "b", label: String(n), activate: true }))).errors.some((w) => /fourth bar/.test(w))); + assert.ok(seq([{ frame: "alt", branches: [{ label: "one", steps: [{ from: "a", to: "b", label: "x" }] }] }]).errors.some((w) => /alt frame has one branch/.test(w))); + assert.ok(seq([{ frame: "opt", label: "o", steps: [{ frame: "opt", label: "p", steps: [{ frame: "opt", label: "q", steps: [{ from: "a", to: "b", label: "x" }] }] }] }]).errors.some((w) => /third level/.test(w))); + }); +}); diff --git a/packages/react/test/diagram-viewer.test.mjs b/packages/react/test/diagram-viewer.test.mjs new file mode 100644 index 00000000..c3e4369a --- /dev/null +++ b/packages/react/test/diagram-viewer.test.mjs @@ -0,0 +1,561 @@ +// The diagram viewer (DECISIONS 301, part 9, as DECISIONS 310; section 8's list for diagram-viewer.test.mjs): "Expand", the dialog, the layout width, Fit, +// the steps, what holds still, the keys, pan, the ink at every level, sharpness, the status line, focus, the trace, the list and print. In Chromium against +// the built package. The implementation hasn't been reviewed; part 9 had no draft, check or position. +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 { 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 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}`; +// The layout widths of 9.12 (proof/zoom/fit.json), with the flowchart's least drawn width at 976 after call 1 of section 4. +const LAYOUT = { architecture: 784, flowchart: 976, dataFlow: 1080, sequence: 807, schema: 1056 }; +const LADDER = [25, 33, 50, 67, 75, 100, 125, 150, 200, 300, 400]; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +// The host: the five CIMIP figures (or `window.__set(list)`), each with the id `fig-`; `zoom` and `motion` per figure from the list. +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 }; +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
{list.map(({ key, type, props }) => { const X = C[type]; return ; })}
; +} +createRoot(document.getElementById("root")).render();`; + +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 viewerPage({ theme = "dark", width = 1440, height = 900, touch = false, scale = 1, media } = {}) { + const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height }, deviceScaleFactor: scale, hasTouch: touch, isMobile: touch }); + if (touch) await page.evaluate(() => { const meta = document.createElement("meta"); meta.name = "viewport"; meta.content = "width=device-width, initial-scale=1"; document.head.append(meta); }); + if (media) await page.emulateMedia(media); + await page.addStyleTag({ content: PAGE }); + await page.evaluate(() => document.fonts.ready); + await frames(page, 4); + return { page, errors }; +} + +/** Opens a figure's viewer and waits until its figure is laid out and the dialog has finished its entrance. */ +async function open(page, key, { tap = false } = {}) { + const button = page.locator(`#fig-${key} .${P}-expand`); + await button.scrollIntoViewIfNeeded(); + if (tap) await button.tap(); else await button.click(); + await page.waitForSelector(`dialog.${P}-viewer[open] .${P}[data-layout]`); + await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {})))); + await frames(page, 3); +} +const state = (page) => page.evaluate((P) => { + const d = document.querySelector(`dialog.${P}-viewer`); + const stage = d.querySelector(`.${P}-stage`); + const layer = d.querySelector(`.${P}-layer`); + const fig = layer.querySelector(`.${P}`); + const sizer = d.querySelector(`.${P}-sizer`); + const pad = parseFloat(getComputedStyle(sizer).paddingTop); + const m = /scale\(([\d.]+)\)/.exec(layer.style.transform); + return { + level: d.querySelector(`.${P}-level > span`).textContent, + zoom: m ? Number(m[1]) : 1, + width: fig.offsetWidth, height: fig.offsetHeight, layout: fig.getAttribute("data-layout"), + stage: { w: stage.clientWidth, h: stage.clientHeight, left: stage.scrollLeft, top: stage.scrollTop }, pad, + dialog: d.getBoundingClientRect().toJSON(), radius: getComputedStyle(d).borderTopLeftRadius, + shadow: getComputedStyle(d).boxShadow, border: getComputedStyle(d).borderTopWidth, + }; +}, P); +const levelOf = async (page) => Number((await page.locator(`.${P}-level > span`).textContent()).replace("%", "")); + +describe("the button", () => { + test("Expand follows View as list in every figure's foot, in words; zoom: false leaves it out; the server's HTML has none", async () => { + const { page, errors } = await viewerPage(); + for (const key of KEYS) { + const foot = await page.locator(`#fig-${key} .${P}-foot > button`).evaluateAll((els) => els.map((e) => [e.className, e.textContent, e.getAttribute("aria-haspopup")])); + assert.ok(foot[0][0].includes(`${P}-toggle`), `${key}: View as list is first`); + assert.ok(foot[1][0].includes(`${P}-expand`) && foot[1][1] === "Expand" && foot[1][2] === "dialog", `${key}: Expand is second, with its words`); + } + await page.evaluate((data) => window.__set([{ key: "schema", type: "schema", props: { ...(({ type, ...p }) => p)(data.schema), zoom: false } }]), DATA); + await frames(page); + assert.equal(await page.locator(`.${P}-expand`).count(), 0); + assert.deepEqual(errors, []); + await page.close(); + // Before script: the server's markup has no Expand. + const B = await import(path.join(pkg, "dist", "index.js")); + const React = require("react"); + const { type, ...props } = DATA.architecture; + const html = renderToString(React.createElement(B.ArchitectureDiagram, props)); + assert.ok(!html.includes(`${P}-expand`)); + }); + test("on touch the button is at least 44px tall", async () => { + const { page } = await viewerPage({ width: 390, height: 844, touch: true }); + const h = await page.locator(`#fig-architecture .${P}-expand`).evaluate((e) => e.getBoundingClientRect().height); + assert.ok(h >= 44, `${h}`); + await page.close(); + }); +}); + +describe("the dialog", () => { + for (const theme of ["dark", "light"]) { + test(`${theme}: at 1440 by 900 the window less 16, radius 12; Esc, Close and the scrim close it and focus returns to Expand; the page does not scroll`, async () => { + const { page, errors } = await viewerPage({ theme }); + await open(page, "architecture"); + const s = await state(page); + assert.deepEqual([Math.round(s.dialog.x), Math.round(s.dialog.y), Math.round(s.dialog.width), Math.round(s.dialog.height)], [16, 16, 1408, 868]); + assert.equal(s.radius, "12px"); + assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).overflow), "hidden"); + const y0 = await page.evaluate(() => scrollY); + await page.mouse.move(5, 450); + await page.mouse.wheel(0, 400); + await frames(page, 3); + assert.equal(await page.evaluate(() => scrollY), y0, "the page behind does not scroll"); + const isFocused = () => page.evaluate((P) => document.activeElement?.classList.contains(`${P}-expand`) && document.activeElement.closest("#fig-architecture") !== null, P); + await page.keyboard.press("Escape"); + await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" }); + assert.ok(await isFocused(), "Esc returns focus to Expand"); + await open(page, "architecture"); + await page.locator(`dialog.${P}-viewer .basalt-sheet-close`).click(); + await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" }); + assert.ok(await isFocused(), "Close returns focus to Expand"); + await open(page, "architecture"); + await page.mouse.click(5, 450); + await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" }); + assert.ok(await isFocused(), "the scrim returns focus to Expand"); + assert.deepEqual(errors, []); + await page.close(); + }); + } + test("at 390 by 844 it is the whole window, with no radius, rim or shadow", async () => { + const { page } = await viewerPage({ width: 390, height: 844, touch: true }); + await open(page, "schema", { tap: true }); + const s = await state(page); + assert.deepEqual([Math.round(s.dialog.x), Math.round(s.dialog.y), Math.round(s.dialog.width), Math.round(s.dialog.height)], [0, 0, 390, 844]); + assert.equal(s.radius, "0px"); + assert.equal(s.shadow, "none"); + assert.equal(s.border, "0px"); + await page.close(); + }); +}); + +describe("the layout width and Fit", () => { + for (const [w, h] of [[390, 844], [1440, 900], [1920, 1080]]) { + test(`at ${w} by ${h}: each CIMIP figure is drawn at its layout width and opens at Fit, the whole drawing in the stage's padding and 1% more would not be, never over 200%`, async () => { + const { page, errors } = await viewerPage({ width: w, height: h, touch: w < 720 }); + for (const key of KEYS) { + await open(page, key, { tap: w < 720 }); + const s = await state(page); + assert.equal(s.layout, "drawn", `${key} at ${w}`); + assert.equal(s.width, w < 720 ? LAYOUT[key] : 1104, `${key} at ${w}: the layout width`); + const fit = Math.min(2, Math.floor(Math.min((s.stage.w - 2 * s.pad) / s.width, (s.stage.h - 2 * s.pad) / s.height) * 100 + 1e-6) / 100); + assert.ok(Math.abs(s.zoom - fit) < 1e-6, `${key} at ${w}: opens at ${s.zoom}, Fit is ${fit}`); + assert.ok(s.width * s.zoom <= s.stage.w - 2 * s.pad + 0.01 && s.height * s.zoom <= s.stage.h - 2 * s.pad + 0.01, `${key} at ${w}: inside the padding`); + if (fit < 2) assert.ok(s.width * (fit + 0.01) > s.stage.w - 2 * s.pad || s.height * (fit + 0.01) > s.stage.h - 2 * s.pad, `${key} at ${w}: 1% more would not fit`); + // The limits: Fit or 100%, whichever is less, and 400%. + for (let i = 0; i < 14; i++) await page.locator(`dialog.${P}-viewer button[aria-label="Zoom out"]`).click({ force: true }); + assert.equal(await levelOf(page), Math.round(Math.min(fit, 1) * 100), `${key} at ${w}: the lower limit`); + for (let i = 0; i < 14; i++) await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click({ force: true }); + assert.equal(await levelOf(page), 400); + if (w < 720) await page.locator(`dialog.${P}-viewer .basalt-sheet-close`).tap(); else await page.keyboard.press("Escape"); + await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" }); + } + assert.deepEqual(errors, []); + await page.close(); + }); + } + test("a figure with no drawn layout holds its stack, and a stack with no lines has its list open", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + // Seven cards in a row and five lines out of the first: every line passes through a card, so no drawn layout is used, and its stack would need a fifth + // end lane, so it draws no lines (Neon's B12: the earlier fixture was drawn, and the test passed either way). + // At the re-check this failed (Opus R2, P-R3), and the fault was the engine's: measureFigure returned the bare state without applying it, so the figure + // kept its last try's attributes and React, seeing a state equal to the one before, wrote nothing. + await page.evaluate(() => window.__set([{ key: "bad", type: "architecture", props: { title: "Refused", summary: "A figure with no drawn layout.", legend: { plain: "Call" }, + nodes: Array.from({ length: 7 }, (_, k) => ({ id: `n${k}`, name: `N${k}`, col: k + 1, row: 1 })), + edges: [2, 3, 4, 5, 6].map((k) => ({ from: "n0", to: `n${k}`, kind: "plain" })) } }])); + await frames(page, 4); + assert.equal(await page.locator("#fig-bad").getAttribute("data-layout"), "stacked"); + assert.equal(await page.locator("#fig-bad").getAttribute("data-bare"), "", "the page's stack is bare"); + await open(page, "bad"); + const s = await state(page); + assert.equal(s.layout, "stacked", "the viewer holds the stack"); + const list = await page.evaluate((P) => { const d = document.querySelector(`dialog.${P}-viewer`); const l = d.querySelector(`.${P}-viewer-list`); return { list: Boolean(l && !l.hidden && l.getClientRects().length), sizer: d.querySelector(`.${P}-sizer`).hidden }; }, P); + assert.deepEqual(list, { list: true, sizer: true }, "and a stack with no lines has its list open"); + await page.close(); + }); +}); + +describe("zoom", () => { + test("from each ladder value Zoom in and Zoom out land on the next; a button at a limit is aria-disabled, mounted and focused; Fit is disabled at Fit; the level never moves the buttons", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "schema"); + const zin = page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`); + const zout = page.locator(`dialog.${P}-viewer button[aria-label="Zoom out"]`); + const fit = page.locator(`dialog.${P}-viewer .${P}-fit`); + assert.equal(await fit.getAttribute("aria-disabled"), "true"); + const x0 = await zin.evaluate((e) => e.getBoundingClientRect().x); + const fitLevel = await levelOf(page); + let at = fitLevel; + while (at < 400) { + await zin.focus(); + await page.keyboard.press("Enter"); + const next = await levelOf(page); + assert.equal(next, LADDER.find((v) => v > at + 0.5), `in from ${at}`); + assert.equal(await zin.evaluate((e) => e.getBoundingClientRect().x), x0, `the level ${next}% moved the button`); + at = next; + } + assert.equal(await zin.getAttribute("aria-disabled"), "true"); + assert.ok(await zin.evaluate((e) => document.activeElement === e), "a button at its limit keeps focus"); + while (at > Math.min(fitLevel, 100)) { + await zout.click(); + const next = await levelOf(page); + const want = [...LADDER].reverse().find((v) => v < at - 0.5); + assert.equal(next, want === undefined || want < Math.min(fitLevel, 100) ? Math.min(fitLevel, 100) : want, `out from ${at}`); + at = next; + } + assert.equal(await zout.getAttribute("aria-disabled"), "true"); + await page.close(); + }); + + test("a step lands in one frame: the layer has no transition or animation, with and without reduced motion", async () => { + for (const reducedMotion of ["no-preference", "reduce"]) { + const { page } = await viewerPage({ media: { reducedMotion } }); + await open(page, "architecture"); + const layer = page.locator(`dialog.${P}-viewer .${P}-layer`); + assert.equal(await layer.evaluate((e) => getComputedStyle(e).transitionDuration), "0s"); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + assert.equal(await layer.evaluate((e) => e.getAnimations({ subtree: true }).length), 0); + await page.close(); + } + }); + + test("what holds still: the stage's middle under a button and a key, the pointer under Ctrl and the wheel, within a pixel", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "schema"); + // A drawing point at the stage's middle, and where it is after a step. + const at = (cx, cy) => page.evaluate(([P, cx, cy]) => { + const layer = document.querySelector(`dialog.${P}-viewer .${P}-layer`); + const r = layer.getBoundingClientRect(); + const z = Number(/scale\(([\d.]+)\)/.exec(layer.style.transform)?.[1] ?? 1); + return { x: (cx - r.left) / z, y: (cy - r.top) / z }; + }, [P, cx, cy]); + const middle = await page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => { const r = s.getBoundingClientRect(); return { x: r.left + s.clientWidth / 2, y: r.top + s.clientHeight / 2 }; }); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + const before = await at(middle.x, middle.y); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + let after = await at(middle.x, middle.y); + assert.ok(Math.abs(before.x - after.x) <= 1 && Math.abs(before.y - after.y) <= 1, `button: ${JSON.stringify([before, after])}`); + await page.locator(`dialog.${P}-viewer .${P}-stage`).focus(); + const k0 = await at(middle.x, middle.y); + await page.keyboard.press("="); + after = await at(middle.x, middle.y); + assert.ok(Math.abs(k0.x - after.x) <= 1 && Math.abs(k0.y - after.y) <= 1, "key"); + const pointer = { x: middle.x - 300, y: middle.y - 120 }; + await page.mouse.move(pointer.x, pointer.y); + const w0 = await at(pointer.x, pointer.y); + const l0 = await levelOf(page); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, 20); + await page.keyboard.up("Control"); + await frames(page); + const w1 = await at(pointer.x, pointer.y); + assert.ok((await levelOf(page)) < l0, "Ctrl and the wheel zoom out"); + assert.ok(Math.abs(w0.x - w1.x) <= 1 && Math.abs(w0.y - w1.y) <= 1, `wheel: ${JSON.stringify([w0, w1])}`); + await page.close(); + }); + + test("a pinch zooms about the midpoint of two fingers, by the ratio of their spread", async () => { + const { page } = await viewerPage({ width: 390, height: 844, touch: true, scale: 1 }); + await open(page, "architecture", { tap: true }); + const z0 = (await state(page)).zoom; + const box = await page.locator(`dialog.${P}-viewer .${P}-stage`).boundingBox(); + const cx = box.x + box.width / 2, cy = box.y + box.height / 2; + const at = () => page.evaluate(([P, cx, cy]) => { const layer = document.querySelector(`dialog.${P}-viewer .${P}-layer`); const r = layer.getBoundingClientRect(); const z = Number(/scale\(([\d.]+)\)/.exec(layer.style.transform)?.[1] ?? 1); return { x: (cx - r.left) / z, y: (cy - r.top) / z }; }, [P, cx, cy]); + const p0 = await at(); + const cdp = await page.context().newCDPSession(page); + const pts = (d) => [{ x: cx - d, y: cy, id: 1 }, { x: cx + d, y: cy, id: 2 }]; + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: pts(20) }); + for (let d = 22; d <= 40; d += 2) await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: pts(d) }); + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + await frames(page); + const z1 = (await state(page)).zoom; + assert.ok(Math.abs(z1 - Math.min(4, z0 * 2)) < 0.02, `${z0} -> ${z1}`); + const p1 = await at(); + assert.ok(Math.abs(p0.x - p1.x) <= 1 && Math.abs(p0.y - p1.y) <= 1, `${JSON.stringify([p0, p1])}`); + await page.close(); + }); + + test("keys: + = - and 0 work with focus on the stage or a card and do nothing on a button; the arrows move between cards and bring the card into view", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "architecture"); + const fitLevel = await levelOf(page); + assert.ok(await page.evaluate((P) => document.activeElement?.classList.contains(`${P}-stage`), P), "focus opens on the stage"); + await page.keyboard.press("+"); + assert.ok((await levelOf(page)) > fitLevel); + await page.keyboard.press("0"); + assert.equal(await levelOf(page), fitLevel); + await page.keyboard.press("Tab"); + assert.ok(await page.evaluate((P) => Boolean(document.activeElement?.closest(`dialog .${P}-node`)), P), "the roving stop is after the stage"); + await page.keyboard.press("="); + const zoomed = await levelOf(page); + assert.ok(zoomed > fitLevel); + await page.keyboard.press("-"); + assert.ok((await levelOf(page)) < zoomed); + for (let i = 0; i < 4; i++) await page.keyboard.press("="); + for (let i = 0; i < 5; i++) await page.keyboard.press("ArrowRight"); + const seen = await page.evaluate((P) => { const s = document.querySelector(`dialog .${P}-stage`); const n = document.activeElement.getBoundingClientRect(); const r = s.getBoundingClientRect(); return n.left >= r.left && n.right <= r.left + s.clientWidth && n.top >= r.top && n.bottom <= r.top + s.clientHeight; }, P); + assert.ok(seen, "the focused card is in view"); + await page.locator(`dialog.${P}-viewer .${P}-fit`).focus(); + const l = await levelOf(page); + await page.keyboard.press("="); + assert.equal(await levelOf(page), l, "a key on a button does nothing"); + await page.close(); + }); +}); + +describe("pan", () => { + test("a drag past 4px scrolls the stage one for one and selects nothing; a press that does not travel is a click; the plain wheel scrolls; nothing continues after the pointer lifts", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "schema"); + for (let i = 0; i < 3; i++) await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + const s0 = (await state(page)).stage; + const box = await page.locator(`dialog.${P}-viewer .${P}-stage`).boundingBox(); + const x = box.x + box.width / 2, y = box.y + box.height / 2; + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(x - 100, y - 60, { steps: 10 }); + await page.mouse.up(); + const s1 = (await state(page)).stage; + assert.equal(s1.left - s0.left, 100); + assert.equal(s1.top - s0.top, 60); + assert.equal(await page.evaluate(() => String(getSelection())), ""); + await frames(page, 5); + assert.deepEqual((await state(page)).stage, s1, "no momentum"); + await page.mouse.wheel(0, 80); + await frames(page); + assert.ok((await state(page)).stage.top > s1.top, "the plain wheel scrolls"); + // A press that does not travel is a click: hovering traces, and a click on a card focuses nothing new but does not pan. + const s2 = (await state(page)).stage; + await page.mouse.click(x, y); + assert.deepEqual((await state(page)).stage, s2); + await page.close(); + }); + test("on touch one finger pans the stage", async () => { + const { page } = await viewerPage({ width: 390, height: 844, touch: true }); + await open(page, "schema", { tap: true }); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).tap(); + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).tap(); + const s0 = (await state(page)).stage; + const box = await page.locator(`dialog.${P}-viewer .${P}-stage`).boundingBox(); + const cdp = await page.context().newCDPSession(page); + const cx = box.x + box.width / 2, cy = box.y + box.height / 2; + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x: cx, y: cy, id: 1 }] }); + for (let k = 1; k <= 10; k++) await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: cx - 4 * k, y: cy - 3 * k, id: 1 }] }); + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + const s1 = (await state(page)).stage; + assert.equal(s1.left - s0.left, 40, JSON.stringify([s0, s1])); + await page.close(); + }); +}); + +describe("the ink", () => { + test("is the same string at every level and the page figure's at that width; a resize and the fonts arriving while zoomed leave it a fresh layout's", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + const pageInk = await page.locator(`#fig-schema .${P}-ink`).innerHTML(); + await open(page, "schema"); + const ink = () => page.locator(`dialog.${P}-viewer .${P}-ink`).innerHTML(); + const normalise = (s) => s.replace(/dg[\w-]+?-/g, "ID-"); + const first = await ink(); + // The page's drawing snaps from its own origin: where that origin is on whole pixels the strings are equal; otherwise every number is within the + // half pixel of a snap. + const whole = await page.locator(`#fig-schema .${P}-drawing`).evaluate((d) => { const r = d.getBoundingClientRect(); return Number.isInteger(r.left) && Number.isInteger(r.top); }); + if (whole) assert.equal(normalise(first), normalise(pageInk), "the viewer's ink is the page's at 1104"); + else { + const nums = (s) => normalise(s).match(/-?\d+(\.\d+)?/g).map(Number); + const [a, b] = [nums(first), nums(pageInk)]; + assert.equal(a.length, b.length); + assert.ok(a.every((v, k) => Math.abs(v - b[k]) <= 1), "the viewer's ink is the page's at 1104, within a snap"); + } + for (let i = 0; i < 6; i++) { + await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + assert.equal(await ink(), first, `at ${await levelOf(page)}%`); + } + await page.evaluate(async () => { document.fonts.dispatchEvent?.(new Event("loadingdone")); }); + await page.setViewportSize({ width: 1400, height: 900 }); + await frames(page, 4); + assert.equal(normalise(await ink()), normalise(first), "a resize while zoomed keeps a fresh layout's ink"); + await page.close(); + }); + + for (const theme of ["dark", "light"]) { + test(`${theme}: sharpness: a region of the layer at 300% on a 1x screen equals the same region at 100% on a 3x screen; no will-change, viewBox scaling, zoom, canvas or image`, async () => { + for (const key of ["schema", "architecture"]) { + const a = await viewerPage({ theme, width: 1440, height: 900, scale: 1 }); + await open(a.page, key); + await a.page.locator(`dialog.${P}-viewer .${P}-stage`).focus(); + // From Fit, step to 300% with the keys, then read a region the zoom shows from the layer's top start. + for (let i = 0; i < 12 && (await levelOf(a.page)) < 300; i++) await a.page.keyboard.press("="); + assert.equal(await levelOf(a.page), 300); + await a.page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => { s.scrollLeft = 0; s.scrollTop = 0; }); + const layerBox = await a.page.locator(`dialog.${P}-viewer .${P}-layer`).boundingBox(); + const clip = { x: Math.round(layerBox.x), y: Math.round(layerBox.y), width: 600, height: 300 }; + const big = await pixels(a.page, clip); + const props = await a.page.locator(`dialog.${P}-viewer .${P}-layer`).evaluate((l) => ({ will: getComputedStyle(l).willChange, zoom: getComputedStyle(l).zoom, canvas: l.querySelectorAll("canvas, img:not(.basalt-diagram-mark img)").length, views: [...l.querySelectorAll("svg[viewBox]")].filter((s) => { const v = s.getAttribute("viewBox").split(/\s+/).map(Number); return Math.abs(v[2] - s.width.baseVal.value) > 0.5 || Math.abs(v[3] - s.height.baseVal.value) > 0.5; }).length })); + assert.equal(props.will, "auto"); + assert.equal(props.zoom, "1"); + assert.equal(props.canvas, 0); + assert.equal(props.views, 0); + await a.page.close(); + const b = await viewerPage({ theme, width: 1440, height: 900, scale: 3 }); + await open(b.page, key); + await b.page.locator(`dialog.${P}-viewer .${P}-stage`).focus(); + for (let i = 0; i < 12 && (await levelOf(b.page)) > 100; i++) await b.page.keyboard.press("-"); + for (let i = 0; i < 12 && (await levelOf(b.page)) < 100; i++) await b.page.keyboard.press("="); + assert.equal(await levelOf(b.page), 100); + await b.page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => { s.scrollLeft = 0; s.scrollTop = 0; }); + const lb = await b.page.locator(`dialog.${P}-viewer .${P}-layer`).boundingBox(); + const small = await pixels(b.page, { x: lb.x, y: lb.y, width: 200, height: 100 }); + assert.equal(big.length, small.length); + let differ = 0; + for (let i = 0; i < big.length; i++) if (big[i].some((c, k) => Math.abs(c - small[i][k]) > 8)) differ++; + assert.ok(differ / big.length < 0.01, `${key}: ${differ} of ${big.length} pixels differ`); + await b.page.close(); + } + }); + } +}); + +describe("speech, focus and the trace", () => { + test("the status line says the level once, duration-slower after the last change: three key presses, and a real pinch of twenty moves", async () => { + const watch = (page) => page.evaluate((P) => { const s = document.querySelector(`dialog.${P}-viewer [role="status"]`); window.__said = []; new MutationObserver(() => window.__said.push(s.textContent)).observe(s, { childList: true, characterData: true, subtree: true }); }, P); + const keys = await viewerPage({ width: 1440, height: 900 }); + await open(keys.page, "architecture"); + await watch(keys.page); + assert.equal(await keys.page.locator(`dialog.${P}-viewer [role="status"]`).textContent(), "", "opening says nothing"); + await keys.page.locator(`dialog.${P}-viewer .${P}-stage`).focus(); + for (let i = 0; i < 3; i++) await keys.page.keyboard.press("="); + await keys.page.waitForTimeout(150); + assert.deepEqual(await keys.page.evaluate(() => window.__said), [], "nothing while it changes"); + await keys.page.waitForTimeout(400); + const said = await keys.page.evaluate(() => window.__said); + assert.equal(said.length, 1); + assert.equal(said[0], `Zoom ${await levelOf(keys.page)}%`); + await keys.page.close(); + // A pinch (Opus B12): two fingers on the stage, twenty moves 16ms apart, spreading from 40 to 80px; the level changes on every move and is said once. + const { page } = await viewerPage({ width: 390, height: 844, touch: true, scale: 1 }); + await open(page, "architecture", { tap: true }); + await watch(page); + const box = await page.locator(`dialog.${P}-viewer .${P}-stage`).boundingBox(); + const cx = box.x + box.width / 2, cy = box.y + box.height / 2; + const pts = (d) => [{ x: cx - d, y: cy, id: 1 }, { x: cx + d, y: cy, id: 2 }]; + const cdp = await page.context().newCDPSession(page); + const levels = []; + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: pts(20) }); + for (let k = 1; k <= 20; k++) { + await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: pts(20 + k) }); + await page.waitForTimeout(16); + levels.push((await state(page)).zoom); + } + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + assert.ok(new Set(levels).size > 10, `the level moved with the fingers ${JSON.stringify(levels)}`); + assert.deepEqual(await page.evaluate(() => window.__said), [], "nothing while the fingers move"); + await page.waitForTimeout(600); + const spoken = await page.evaluate(() => window.__said); + assert.equal(spoken.length, 1, JSON.stringify(spoken)); + assert.equal(spoken[0], `Zoom ${await levelOf(page)}%`); + await page.close(); + }); + + for (const theme of ["dark", "light"]) { + test(`${theme}: focus opens on the stage with an inset ring; the order is Close, the stage, the roving stop, the foot; axe passes at Fit and at 400%`, async () => { + const { page } = await viewerPage({ theme, width: 1440, height: 900 }); + await open(page, "architecture"); + await page.keyboard.press("Shift+Tab"); + await page.keyboard.press("Tab"); + const ring = await page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => [document.activeElement === s, getComputedStyle(s).outlineOffset, getComputedStyle(s).outlineWidth]); + assert.deepEqual(ring, [true, "-2px", "2px"]); + await page.keyboard.press("Shift+Tab"); + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Close"); + await page.keyboard.press("Tab"); + await page.keyboard.press("Tab"); + assert.ok(await page.evaluate((P) => Boolean(document.activeElement?.closest(`.${P}-node`)), P)); + await page.keyboard.press("Tab"); + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom out"); + await page.evaluate(() => { document.title = "Basalt"; document.documentElement.lang = "en"; }); + await page.addScriptTag({ content: axeSource }); + const audit = () => page.evaluate(() => window.axe.run(document.querySelector("dialog"), { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] }, resultTypes: ["violations"] }).then((r) => r.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).slice(0, 3).join("; ")}`))); + assert.deepEqual(await audit(), [], "at Fit"); + await page.locator(`dialog.${P}-viewer .${P}-stage`).focus(); + for (let i = 0; i < 10; i++) await page.keyboard.press("="); + assert.deepEqual(await audit(), [], "at 400%"); + await page.close(); + }); + } + + test("a trace by hover and by focus works; there is no hint line for touch and no Clear highlight; no entrance or flow runs; the page's figure holds its loops while the viewer is open", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await page.evaluate((data) => window.__set([{ key: "arch", type: "architecture", props: { ...(({ type, ...p }) => p)(data.architecture), motion: "animated" } }]), DATA); + await frames(page, 4); + await open(page, "arch"); + assert.ok(await page.locator("#fig-arch").evaluate((f) => f.hasAttribute("data-viewing"))); + const node = page.locator(`dialog.${P}-viewer .${P}-node`).first(); + await node.hover(); + await frames(page); + assert.ok(await page.locator(`dialog.${P}-viewer .${P}`).evaluate((f) => f.hasAttribute("data-tracing")), "hover traces"); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}`).getAttribute("data-entrance"), null, "no entrance"); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}-flow`).count(), 0, "no flow"); + assert.equal(await page.locator(`dialog.${P}-viewer :is(.${P}-clear, .${P}-play, .${P}-pause)`).count(), 0); + await page.keyboard.press("Escape"); + await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" }); + assert.ok(!(await page.locator("#fig-arch").evaluate((f) => f.hasAttribute("data-viewing")))); + await page.close(); + }); + + test("View as list puts the list in the stage and disables the zoom controls; Hide the list returns the drawing at its zoom and place", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "schema"); + for (let i = 0; i < 3; i++) await page.locator(`dialog.${P}-viewer button[aria-label="Zoom in"]`).click(); + await page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => { s.scrollLeft = 120; s.scrollTop = 80; }); + const before = await state(page); + const toggle = page.locator(`dialog.${P}-viewer .${P}-toggle`); + await toggle.click(); + assert.equal(await toggle.textContent(), "Hide the list"); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}-viewer-list`).isVisible(), true); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}-sizer`).isVisible(), false); + for (const label of ["Zoom out", "Zoom in"]) assert.equal(await page.locator(`dialog.${P}-viewer button[aria-label="${label}"]`).getAttribute("aria-disabled"), "true"); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}-stage`).evaluate((s) => getComputedStyle(s).touchAction), "pan-y"); + await toggle.click(); + const back = await state(page); + assert.equal(back.level, before.level); + assert.deepEqual([back.stage.left, back.stage.top], [before.stage.left, before.stage.top]); + await page.close(); + }); + + test("print with the viewer open: the dialog is not displayed, the page's figure is", async () => { + const { page } = await viewerPage({ width: 1440, height: 900 }); + await open(page, "architecture"); + await page.emulateMedia({ media: "print" }); + assert.equal(await page.locator(`dialog.${P}-viewer`).evaluate((d) => getComputedStyle(d).display), "none"); + assert.notEqual(await page.locator("#fig-architecture").evaluate((f) => getComputedStyle(f).display), "none"); + await page.close(); + }); + + test("forced colours: the viewer's figure draws its geometry, and the level is CanvasText", async () => { + const { page } = await viewerPage({ width: 1440, height: 900, media: { forcedColors: "active" } }); + await open(page, "architecture"); + const s = await state(page); + assert.equal(s.layout, "drawn"); + assert.equal(await page.locator(`dialog.${P}-viewer .${P}-level`).evaluate((e) => getComputedStyle(e).color), await page.evaluate(() => { const p = document.createElement("span"); p.style.color = "CanvasText"; document.body.append(p); const c = getComputedStyle(p).color; p.remove(); return c; })); + await page.close(); + }); +}); diff --git a/packages/react/test/diagrams.test.mjs b/packages/react/test/diagrams.test.mjs index debc0320..099b6ca5 100644 --- a/packages/react/test/diagrams.test.mjs +++ b/packages/react/test/diagrams.test.mjs @@ -281,7 +281,7 @@ describe("the fit rule (1.11) and seats (1.8)", () => { }); // Neon's blocking finding 1 on #126: two turn-backs to different keys, beside each other, were drawn on one lane. - test("turn-backs to different keys never lie on one another: in a gutter each takes a lane; with no gutter (one column) the schema stays stacked", async () => { + test("turn-backs to different keys never lie on one another: in a gutter each takes a lane; with no gutter (one column) each takes a lane of the padding (call 2)", async () => { const { page } = await diagramPage(); const t = (name, col, row, refs = []) => ({ name, col, row, columns: [{ name: "id", key: "PK" }, ...refs.map((r) => ({ name: `${r}_id`, key: "FK", references: `${r}.id` }))] }); const schema = (key, tables) => ({ key, type: "schema", props: { title: key, summary: "Keys.", legend: { plain: "A foreign key" }, tables } }); @@ -297,7 +297,8 @@ describe("the fit rule (1.11) and seats (1.8)", () => { const lanes = (key) => page.evaluate((key) => [...document.querySelectorAll(`#fig-${key} .basalt-diagram-svg .basalt-diagram-line`)].map((p) => { const n = p.getAttribute("d").match(/-?[\d.]+/g).map(Number); return Math.min(...n.filter((_, k) => k % 2 === 0)); }), key); for (const width of [1440, 1000]) { await resize(page, width); - assert.equal(await page.getAttribute("#fig-crossed", "data-layout"), "stacked", `at ${width}: no lane for both, so no drawing`); + // A one-column schema's overlapping turn-backs take two lanes (DECISIONS 306, section 4, call 2), so the figure is drawn. + assert.equal(await page.getAttribute("#fig-crossed", "data-layout"), "drawn", `at ${width}: a lane each, so drawn`); assert.equal(await page.getAttribute("#fig-apart", "data-layout"), "drawn", `at ${width}`); assert.equal(await page.getAttribute("#fig-gutter", "data-layout"), "drawn", `at ${width}`); for (const key of ["crossed", "apart", "gutter"]) assert.deepEqual((await inspect(page, key)).problems, [], `${key} at ${width}`); @@ -403,14 +404,17 @@ describe("derivation (1.6, 1.13): the sides, slots and stacked routes of the exa // 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); - // Lanes are allocated across each overlapping set: A to C, B to E and D to H overlap in a chain, so each takes the lane outside the one before, and the - // third lane is reported, never laid on the second. + // Four end lanes at most (DECISIONS 306, 1.3): three overlapping end lines take three lanes; a fifth is the development error. + const three = 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(three).third, false); + assert.equal(core.stackPlan(three).laneCount, 3); + const five = core.buildModel({ type: "architecture", title: "t", nodes: "abcdefghij".split("").map((id, k) => node(id, 1, k + 1)), edges: [{ from: "a", to: "j" }, { from: "a", to: "i" }, { from: "b", to: "h" }, { from: "b", to: "g" }, { from: "c", to: "f" }] }); + assert.equal(core.stackPlan(five).third, true); + // Lanes are allocated across each overlapping set: A to C, B to E and D to H overlap in a chain, so each takes the lane outside the one before; a + // third lane is drawn now (four at most, DECISIONS 306, 1.3), never laid on the second. const chain = core.stackPlan(core.buildModel({ type: "architecture", title: "t", nodes: "abcdefgh".split("").map((id, k) => node(id, 1, k + 1)), edges: [{ from: "a", to: "c" }, { from: "b", to: "e" }, { from: "d", to: "h" }] })); assert.deepEqual(chain.lanes, [0, 1, 2]); - assert.equal(chain.third, true); + assert.equal(chain.third, false); // Two that do not overlap share the inner lane; two that do take one each. assert.deepEqual(core.stackPlan(core.buildModel({ type: "architecture", title: "t", nodes: "abcdef".split("").map((id, k) => node(id, 1, k + 1)), edges: [{ from: "a", to: "c" }, { from: "d", to: "f" }, { from: "b", to: "e" }] })).lanes, [0, 0, 1]); // Two straight lines between one pair, one each way, take the quarter points at both ends, so neither lies on the other. @@ -466,7 +470,9 @@ describe("accessibility (1.14)", () => { 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"]]) { + // Drawn, the arrows are spatial (DECISIONS 306, 1.5; the decision's table in test/fixtures/diagram-spatial-cells.json): down from the ALB is ECS, up + // from Aurora goes nowhere. Home and End are the ends, as before. + for (const [key, to] of [["ArrowRight", "alb"], ["ArrowDown", "ecs"], ["ArrowLeft", "browser"], ["ArrowUp", "aurora"], ["ArrowUp", "aurora"], ["End", "sys"], ["ArrowRight", "cw"], ["Home", "browser"]]) { await page.keyboard.press(key); assert.equal(await at(), to, `${key}`); } @@ -586,11 +592,19 @@ describe("tracing (1.15)", () => { await page.close(); }); - test("on touch (no hover) a tap traces nothing", async () => { + // A trace on touch comes back (DECISIONS 306, 1.5): a tap traces a card, the same card clears it, and "Clear highlight" is mounted, aria-disabled until then. + test("on touch (no hover) a tap traces, the same tap clears, and Clear highlight follows", async () => { const { page } = await diagramPage({ hasTouch: true, isMobile: true, viewport: { width: 1440, height: 1000 } }); + const clear = page.locator(`#fig-architecture .${P}-clear`); + assert.equal(await clear.getAttribute("aria-disabled"), "true"); + await page.tap(`#fig-architecture .${P}-node[data-node="svc"]`); + await page.waitForTimeout(150); + assert.ok((await page.locator(`#fig-architecture .${P}-edge[data-lit]`).count()) > 0); + assert.equal(await clear.getAttribute("aria-disabled"), null); 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); + assert.equal(await page.locator(`#fig-architecture [aria-live]`).count(), 0); await page.close(); }); }); diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index a4fe1304..e51eebdb 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -18,7 +18,7 @@ "AppHeader": 1285, "AppShell": 104323, "AppTile": 1112, - "ArchitectureDiagram": 67928, + "ArchitectureDiagram": 101300, "ArrowDownGlyph": 2868, "ArrowLeftGlyph": 2869, "ArrowRightGlyph": 2859, @@ -70,7 +70,7 @@ "CopyGlyph": 2884, "Countdown": 3016, "CoverageStrip": 1570, - "DataFlowDiagram": 67945, + "DataFlowDiagram": 101243, "DateAge": 2527, "DescriptionColumns": 216, "DescriptionItem": 593, @@ -105,7 +105,7 @@ "Fieldset": 6390, "FilterResult": 698, "FilterToolbar": 774, - "FlowchartDiagram": 67894, + "FlowchartDiagram": 101264, "Form": 8730, "FormGrid": 438, "FormGridItem": 628, @@ -232,7 +232,7 @@ "STAGE_WORDS": 149, "STATUS_MESSAGE_MS": 26, "SandboxesGlyph": 2963, - "SchemaDiagram": 67842, + "SchemaDiagram": 101212, "SearchDialog": 89118, "SearchField": 18406, "SearchGlyph": 3181, @@ -251,7 +251,7 @@ "SelectableList": 821, "SelectionBar": 25913, "Separator": 4531, - "SequenceDiagram": 67890, + "SequenceDiagram": 101240, "SettingsGlyph": 3100, "ShareBar": 1411, "Sheet": 70793, @@ -427,11 +427,11 @@ "useWaitMark": 303 }, "package": { - "bytes": 911732, - "gzip": 302234 + "bytes": 945503, + "gzip": 314974 }, "styles": { - "bytes": 429096, - "gzip": 55422 + "bytes": 460057, + "gzip": 59068 } } diff --git a/packages/react/test/fixtures/cimip-diagrams-b.json b/packages/react/test/fixtures/cimip-diagrams-b.json new file mode 100644 index 00000000..0d3856a1 --- /dev/null +++ b/packages/react/test/fixtures/cimip-diagrams-b.json @@ -0,0 +1,1648 @@ +{ + "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" + }, + { + "id": "data", + "label": "Data & logs", + "parent": "aws" + } + ], + "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, + "href": "#fig-sequence" + }, + { + "id": "aurora", + "kind": "database", + "name": "Aurora PostgreSQL", + "detail": "metadata · live window", + "detailMono": true, + "group": "data", + "col": 4, + "row": 1, + "branch": true + }, + { + "id": "s3", + "kind": "object store", + "name": "S3", + "detail": "sealed segments · transcripts", + "detailMono": true, + "group": "data", + "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\none transaction", + "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\none stream a tab" + }, + { + "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": "Where the event is written" + }, + "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", + "activation": "Working" + }, + "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", + "activate": true + }, + { + "from": "svc", + "to": "svc", + "label": "records the run", + "note": "run.started, one transaction" + }, + { + "frame": "opt", + "label": "First run on an incident only", + "steps": [ + { + "from": "svc", + "to": "ecs", + "label": "RunTask", + "note": "idempotency token = sandbox id" + }, + { + "frame": "loop", + "label": "Until private IP", + "steps": [ + { + "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", + "activate": true + }, + { + "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" + }, + { + "frame": "alt", + "branches": [ + { + "label": "Approved", + "steps": [ + { + "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" + } + ] + }, + { + "label": "Rejected or timed out", + "steps": [ + { + "from": "svc", + "to": "agent", + "kind": "main", + "label": "POST /v1/runs/{id}/input", + "note": "the run stops" + } + ] + } + ] + }, + { + "from": "agent", + "to": "svc", + "kind": "dashed", + "label": "done", + "note": "outcome: completed", + "deactivate": true + } + ] + }, + "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, agent_runs and approvals reference incidents.id; memberships, incidents and approvals reference users.id; agent_runs references sandboxes.id; and approvals references agent_runs.id. Each foreign key says how many rows each end allows.", + "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", + "cardinality": { + "from": "one-or-many", + "to": "one" + } + }, + { + "name": "user_id", + "key": "PK", + "references": "users.id", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "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", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "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", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "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", + "cardinality": { + "from": "zero-or-many", + "to": "zero-or-one" + } + }, + { + "name": "last_seq", + "type": "integer" + }, + { + "name": "summary", + "type": "text" + } + ], + "href": "#fig-architecture" + }, + { + "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", + "cardinality": { + "from": "zero-or-one", + "to": "one" + } + }, + { + "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", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "name": "sandbox_id", + "key": "FK", + "references": "sandboxes.id", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "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": 6, + "columns": [ + { + "name": "id", + "key": "PK", + "type": "text" + }, + { + "name": "incident_id", + "key": "FK", + "references": "incidents.id", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "name": "run_id", + "key": "FK", + "references": "agent_runs.id", + "cardinality": { + "from": "zero-or-many", + "to": "one" + } + }, + { + "name": "decided_by", + "key": "FK", + "references": "users.id", + "cardinality": { + "from": "zero-or-many", + "to": "zero-or-one" + } + }, + { + "name": "command", + "type": "text" + }, + { + "name": "risk", + "type": "low | medium | high" + }, + { + "name": "status", + "type": "pending" + } + ] + } + ] + }, + "autoArchitecture": { + "type": "architecture", + "title": "How a request reaches the agent (placed automatically)", + "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" + }, + { + "id": "alb", + "kind": "load balancer", + "name": "ALB", + "detail": "OIDC sign-in · HTTP/2", + "detailMono": true, + "group": "aws" + }, + { + "id": "svc", + "kind": "ECS service", + "name": "cimip service", + "detail": "N tasks · stateless", + "detailMono": true, + "focal": true, + "group": "aws" + }, + { + "id": "aurora", + "kind": "database", + "name": "Aurora PostgreSQL", + "detail": "metadata · live window", + "detailMono": true, + "group": "aws", + "branch": true + }, + { + "id": "s3", + "kind": "object store", + "name": "S3", + "detail": "sealed segments · transcripts", + "detailMono": true, + "group": "aws", + "branch": true + }, + { + "id": "ecs", + "kind": "control plane", + "name": "ECS", + "detail": "RunTask · StopTask", + "detailMono": true, + "group": "aws", + "branch": true + }, + { + "id": "bedrock", + "kind": "model", + "name": "Bedrock", + "detail": "the scribe · the agent", + "group": "aws", + "branch": true + }, + { + "id": "agent", + "kind": "ECS task · one per incident", + "name": "Agent sandbox", + "detail": "private IP · :8080", + "detailMono": true, + "group": "aws" + }, + { + "id": "cw", + "kind": "logs", + "name": "CloudWatch", + "detail": "the agent's logs, traces", + "group": "aws", + "branch": true + }, + { + "id": "sys", + "kind": "your systems", + "name": "Production", + "detail": "read-only tools", + "group": "aws" + } + ], + "edges": [ + { + "from": "browser", + "to": "alb", + "kind": "main", + "label": "HTTPS" + }, + { + "from": "alb", + "to": "svc", + "kind": "main" + }, + { + "from": "svc", + "to": "aurora", + "label": "SQL · NOTIFY" + }, + { + "from": "svc", + "to": "s3", + "label": "PUT" + }, + { + "from": "svc", + "to": "ecs", + "label": "RunTask" + }, + { + "from": "svc", + "to": "bedrock", + "label": "scribe" + }, + { + "from": "svc", + "to": "agent", + "kind": "main", + "label": "HTTP + SSE" + }, + { + "from": "ecs", + "to": "agent", + "kind": "dashed", + "label": "starts" + }, + { + "from": "agent", + "to": "bedrock", + "label": "inference" + }, + { + "from": "agent", + "to": "cw", + "kind": "dashed", + "label": "logs" + }, + { + "from": "agent", + "to": "sys", + "label": "tools · approved actions" + } + ], + "layout": "auto" + }, + "autoFlowchart": { + "type": "flowchart", + "title": "Who may decide what the agent asks to run (placed automatically)", + "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 + }, + { + "id": "risk", + "name": "CIMIP sets the risk", + "detail": "higher of the agent's and its own", + "focal": true + }, + { + "id": "who", + "shape": "decision", + "name": "Who is deciding?" + }, + { + "id": "obs", + "shape": "terminal", + "name": "Can't decide", + "detail": "observers only read", + "branch": true + }, + { + "id": "med", + "shape": "decision", + "name": "Risk medium or lower?", + "branch": true + }, + { + "id": "wait", + "shape": "terminal", + "name": "Waits for the commander or deputy", + "branch": true + }, + { + "id": "may", + "name": "May decide", + "detail": "high risk asks twice" + }, + { + "id": "first", + "shape": "decision", + "name": "First decision?" + }, + { + "id": "told", + "shape": "terminal", + "name": "Told it was already decided", + "branch": true + }, + { + "id": "rec", + "shape": "terminal", + "name": "Recorded, then sent until acknowledged" + } + ], + "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" + }, + { + "from": "may", + "to": "first", + "kind": "main" + }, + { + "from": "first", + "to": "told", + "label": "no" + }, + { + "from": "first", + "to": "rec", + "kind": "main", + "label": "yes" + } + ], + "layout": "auto" + }, + "autoSchema": { + "type": "schema", + "title": "The tables an incident and its runs live in (placed automatically)", + "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 most of the others reference" + }, + "tables": [ + { + "name": "memberships", + "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", + "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", + "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", + "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", + "more": 2, + "columns": [ + { + "name": "id", + "key": "PK", + "type": "text" + }, + { + "name": "subject", + "type": "unique" + }, + { + "name": "name", + "type": "text" + }, + { + "name": "roles", + "type": "jsonb" + } + ] + }, + { + "name": "sandboxes", + "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", + "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", + "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" + } + ] + } + ], + "layout": "auto" + }, + "textSequence": { + "type": "sequence", + "title": "An agent run, as text art", + "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", + "activation": "Working" + }, + "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", + "activate": true + }, + { + "from": "svc", + "to": "svc", + "label": "records the run", + "note": "run.started, one transaction" + }, + { + "frame": "opt", + "label": "First run on an incident only", + "steps": [ + { + "from": "svc", + "to": "ecs", + "label": "RunTask", + "note": "idempotency token = sandbox id" + }, + { + "frame": "loop", + "label": "Until private IP", + "steps": [ + { + "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", + "activate": true + }, + { + "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" + }, + { + "frame": "alt", + "branches": [ + { + "label": "Approved", + "steps": [ + { + "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" + } + ] + }, + { + "label": "Rejected or timed out", + "steps": [ + { + "from": "svc", + "to": "agent", + "kind": "main", + "label": "POST /v1/runs/{id}/input", + "note": "the run stops" + } + ] + } + ] + }, + { + "from": "agent", + "to": "svc", + "kind": "dashed", + "label": "done", + "note": "outcome: completed", + "deactivate": true + } + ], + "variant": "text" + } +} \ No newline at end of file diff --git a/packages/react/test/fixtures/diagram-layout.json b/packages/react/test/fixtures/diagram-layout.json new file mode 100644 index 00000000..2dd9db50 --- /dev/null +++ b/packages/react/test/fixtures/diagram-layout.json @@ -0,0 +1,1478 @@ +{ + "about": "DECISIONS 322 (the ruling on automatic layout): the proof figures (auto-ruling/proof-figures.json; the CIMIP ones are cimip-diagrams-b.json), the two flowcharts on given cells (fixed-figures.json) and the ruled cells (proof/cells-ruled.json).", + "figures": { + "nestedArchitecture": { + "type": "architecture", + "title": "How a request reaches the agent (nested groups, placed automatically)", + "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" + }, + { + "id": "data", + "label": "Data & logs", + "parent": "aws" + } + ], + "nodes": [ + { + "id": "browser", + "kind": "client", + "name": "Browser", + "detail": "Edge on iOS, Android" + }, + { + "id": "alb", + "kind": "load balancer", + "name": "ALB", + "detail": "OIDC sign-in · HTTP/2", + "detailMono": true, + "group": "aws" + }, + { + "id": "svc", + "kind": "ECS service", + "name": "cimip service", + "detail": "N tasks · stateless", + "detailMono": true, + "focal": true, + "group": "aws", + "href": "#fig-sequence" + }, + { + "id": "aurora", + "kind": "database", + "name": "Aurora PostgreSQL", + "detail": "metadata · live window", + "detailMono": true, + "group": "data", + "branch": true + }, + { + "id": "s3", + "kind": "object store", + "name": "S3", + "detail": "sealed segments · transcripts", + "detailMono": true, + "group": "data", + "branch": true + }, + { + "id": "ecs", + "kind": "control plane", + "name": "ECS", + "detail": "RunTask · StopTask", + "detailMono": true, + "group": "aws", + "branch": true + }, + { + "id": "bedrock", + "kind": "model", + "name": "Bedrock", + "detail": "the scribe · the agent", + "group": "aws", + "branch": true + }, + { + "id": "agent", + "kind": "ECS task · one per incident", + "name": "Agent sandbox", + "detail": "private IP · :8080", + "detailMono": true, + "group": "aws" + }, + { + "id": "cw", + "kind": "logs", + "name": "CloudWatch", + "detail": "the agent's logs, traces", + "group": "aws", + "branch": true + }, + { + "id": "sys", + "kind": "your systems", + "name": "Production", + "detail": "read-only tools", + "group": "aws" + } + ], + "edges": [ + { + "from": "browser", + "to": "alb", + "kind": "main", + "label": "HTTPS" + }, + { + "from": "alb", + "to": "svc", + "kind": "main" + }, + { + "from": "svc", + "to": "aurora", + "label": "SQL · NOTIFY\none transaction" + }, + { + "from": "svc", + "to": "s3", + "label": "PUT" + }, + { + "from": "svc", + "to": "ecs", + "label": "RunTask" + }, + { + "from": "svc", + "to": "bedrock", + "label": "scribe" + }, + { + "from": "svc", + "to": "agent", + "kind": "main", + "label": "HTTP + SSE\none stream a tab" + }, + { + "from": "ecs", + "to": "agent", + "kind": "dashed", + "label": "starts" + }, + { + "from": "agent", + "to": "bedrock", + "label": "inference" + }, + { + "from": "agent", + "to": "cw", + "kind": "dashed", + "label": "logs" + }, + { + "from": "agent", + "to": "sys", + "label": "tools · approved actions" + } + ], + "layout": "auto" + }, + "nestedOneLine": { + "type": "architecture", + "title": "How a request reaches the agent (nested groups, one-line labels, placed automatically)", + "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" + }, + { + "id": "data", + "label": "Data & logs", + "parent": "aws" + } + ], + "nodes": [ + { + "id": "browser", + "kind": "client", + "name": "Browser", + "detail": "Edge on iOS, Android" + }, + { + "id": "alb", + "kind": "load balancer", + "name": "ALB", + "detail": "OIDC sign-in · HTTP/2", + "detailMono": true, + "group": "aws" + }, + { + "id": "svc", + "kind": "ECS service", + "name": "cimip service", + "detail": "N tasks · stateless", + "detailMono": true, + "focal": true, + "group": "aws", + "href": "#fig-sequence" + }, + { + "id": "aurora", + "kind": "database", + "name": "Aurora PostgreSQL", + "detail": "metadata · live window", + "detailMono": true, + "group": "data", + "branch": true + }, + { + "id": "s3", + "kind": "object store", + "name": "S3", + "detail": "sealed segments · transcripts", + "detailMono": true, + "group": "data", + "branch": true + }, + { + "id": "ecs", + "kind": "control plane", + "name": "ECS", + "detail": "RunTask · StopTask", + "detailMono": true, + "group": "aws", + "branch": true + }, + { + "id": "bedrock", + "kind": "model", + "name": "Bedrock", + "detail": "the scribe · the agent", + "group": "aws", + "branch": true + }, + { + "id": "agent", + "kind": "ECS task · one per incident", + "name": "Agent sandbox", + "detail": "private IP · :8080", + "detailMono": true, + "group": "aws" + }, + { + "id": "cw", + "kind": "logs", + "name": "CloudWatch", + "detail": "the agent's logs, traces", + "group": "aws", + "branch": true + }, + { + "id": "sys", + "kind": "your systems", + "name": "Production", + "detail": "read-only tools", + "group": "aws" + } + ], + "edges": [ + { + "from": "browser", + "to": "alb", + "kind": "main", + "label": "HTTPS" + }, + { + "from": "alb", + "to": "svc", + "kind": "main" + }, + { + "from": "svc", + "to": "aurora", + "label": "SQL · NOTIFY" + }, + { + "from": "svc", + "to": "s3", + "label": "PUT" + }, + { + "from": "svc", + "to": "ecs", + "label": "RunTask" + }, + { + "from": "svc", + "to": "bedrock", + "label": "scribe" + }, + { + "from": "svc", + "to": "agent", + "kind": "main", + "label": "HTTP + SSE" + }, + { + "from": "ecs", + "to": "agent", + "kind": "dashed", + "label": "starts" + }, + { + "from": "agent", + "to": "bedrock", + "label": "inference" + }, + { + "from": "agent", + "to": "cw", + "kind": "dashed", + "label": "logs" + }, + { + "from": "agent", + "to": "sys", + "label": "tools · approved actions" + } + ], + "layout": "auto" + }, + "loopBack": { + "type": "flowchart", + "layout": "auto", + "title": "A retry loop", + "legend": { + "main": "Usual path" + }, + "summary": "A test figure.", + "nodes": [ + { + "id": "start", + "shape": "terminal", + "name": "Start" + }, + { + "id": "try", + "name": "Try the call" + }, + { + "id": "ok", + "shape": "decision", + "name": "Did it work?" + }, + { + "id": "wait", + "name": "Wait and count", + "branch": true + }, + { + "id": "done", + "shape": "terminal", + "name": "Done" + } + ], + "edges": [ + { + "from": "start", + "to": "try", + "kind": "main" + }, + { + "from": "try", + "to": "ok", + "kind": "main" + }, + { + "from": "ok", + "to": "wait", + "label": "no" + }, + { + "from": "wait", + "to": "try", + "label": "again" + }, + { + "from": "ok", + "to": "done", + "kind": "main", + "label": "yes" + } + ] + }, + "threePlain": { + "type": "flowchart", + "layout": "auto", + "title": "Three ways out, none usual", + "legend": { + "main": "Usual path" + }, + "summary": "A test figure.", + "nodes": [ + { + "id": "in", + "shape": "terminal", + "name": "A request" + }, + { + "id": "kind", + "shape": "decision", + "name": "What kind?" + }, + { + "id": "a", + "name": "Read", + "branch": true + }, + { + "id": "b", + "name": "Write", + "branch": true + }, + { + "id": "c", + "name": "Delete", + "branch": true + }, + { + "id": "log", + "shape": "terminal", + "name": "Logged" + } + ], + "edges": [ + { + "from": "in", + "to": "kind", + "kind": "main" + }, + { + "from": "kind", + "to": "a", + "label": "read" + }, + { + "from": "kind", + "to": "b", + "label": "write" + }, + { + "from": "kind", + "to": "c", + "label": "delete" + }, + { + "from": "a", + "to": "log" + }, + { + "from": "b", + "to": "log" + }, + { + "from": "c", + "to": "log" + } + ] + }, + "longWay": { + "type": "flowchart", + "layout": "auto", + "title": "A main line past two steps", + "legend": { + "main": "Usual path" + }, + "summary": "A test figure.", + "nodes": [ + { + "id": "s", + "shape": "terminal", + "name": "Start" + }, + { + "id": "gate", + "shape": "decision", + "name": "Checked before?" + }, + { + "id": "p1", + "name": "Look it up", + "branch": true + }, + { + "id": "p2", + "name": "Score it", + "branch": true + }, + { + "id": "end", + "shape": "terminal", + "name": "Answer" + } + ], + "edges": [ + { + "from": "s", + "to": "gate", + "kind": "main" + }, + { + "from": "gate", + "to": "p1", + "label": "no" + }, + { + "from": "p1", + "to": "p2" + }, + { + "from": "p2", + "to": "end" + }, + { + "from": "gate", + "to": "end", + "kind": "main", + "label": "yes" + } + ] + }, + "twoMains": { + "type": "architecture", + "layout": "auto", + "title": "Two request paths", + "legend": { + "main": "Request path", + "dashed": "Async" + }, + "summary": "A test figure.", + "groups": [ + { + "id": "edge", + "label": "Edge" + }, + { + "id": "core", + "label": "Core" + } + ], + "nodes": [ + { + "id": "user", + "kind": "client", + "name": "User" + }, + { + "id": "cdn", + "kind": "cache", + "name": "CDN", + "group": "edge" + }, + { + "id": "gw", + "kind": "gateway", + "name": "Gateway", + "group": "edge" + }, + { + "id": "api", + "kind": "service", + "name": "API", + "group": "core" + }, + { + "id": "jobs", + "kind": "queue", + "name": "Jobs", + "group": "core" + }, + { + "id": "db", + "kind": "database", + "name": "Store", + "group": "core" + } + ], + "edges": [ + { + "from": "user", + "to": "cdn", + "kind": "main", + "label": "GET" + }, + { + "from": "user", + "to": "gw", + "kind": "main", + "label": "POST" + }, + { + "from": "cdn", + "to": "gw", + "label": "miss" + }, + { + "from": "gw", + "to": "api", + "kind": "main" + }, + { + "from": "api", + "to": "jobs", + "kind": "dashed", + "label": "enqueue" + }, + { + "from": "api", + "to": "db", + "label": "SQL" + }, + { + "from": "jobs", + "to": "db", + "label": "SQL" + } + ] + } + }, + "fixed": { + "twoToOneSide": { + "type": "flowchart", + "layout": "auto", + "direction": "down", + "title": "Two ways out, both to the end side", + "legend": { + "main": "Usual path" + }, + "summary": "A test figure.", + "nodes": [ + { + "id": "d", + "shape": "decision", + "name": "Which?" + }, + { + "id": "a", + "name": "First" + }, + { + "id": "b", + "name": "Second" + } + ], + "edges": [ + { + "from": "d", + "to": "a", + "label": "one" + }, + { + "from": "d", + "to": "b", + "label": "two" + } + ], + "placement": { + "direction": "down", + "cells": { + "d": { + "col": 1, + "row": 1 + }, + "a": { + "col": 2, + "row": 2 + }, + "b": { + "col": 3, + "row": 2 + } + } + } + }, + "fourWaysOut": { + "type": "flowchart", + "layout": "auto", + "direction": "down", + "title": "Four ways out of one decision", + "legend": { + "main": "Usual path" + }, + "summary": "A test figure.", + "nodes": [ + { + "id": "in", + "shape": "terminal", + "name": "In" + }, + { + "id": "d", + "shape": "decision", + "name": "Which?" + }, + { + "id": "a", + "name": "First" + }, + { + "id": "b", + "name": "Second" + }, + { + "id": "c", + "name": "Third" + }, + { + "id": "e", + "name": "Fourth" + } + ], + "edges": [ + { + "from": "in", + "to": "d", + "kind": "main" + }, + { + "from": "d", + "to": "a", + "label": "one" + }, + { + "from": "d", + "to": "b", + "label": "two" + }, + { + "from": "d", + "to": "c", + "label": "three" + }, + { + "from": "d", + "to": "e", + "label": "four" + } + ], + "placement": { + "direction": "down", + "cells": { + "in": { + "col": 2, + "row": 1 + }, + "d": { + "col": 2, + "row": 2 + }, + "a": { + "col": 1, + "row": 3 + }, + "b": { + "col": 2, + "row": 3 + }, + "c": { + "col": 3, + "row": 3 + }, + "e": { + "col": 4, + "row": 3 + } + } + } + } + }, + "cells": { + "autoArchitecture": { + "down": { + "cols": 4, + "rows": 6, + "cells": { + "browser": { + "col": 3, + "row": 1 + }, + "alb": { + "col": 3, + "row": 2 + }, + "svc": { + "col": 3, + "row": 3 + }, + "aurora": { + "col": 4, + "row": 4 + }, + "s3": { + "col": 1, + "row": 4 + }, + "ecs": { + "col": 2, + "row": 4 + }, + "bedrock": { + "col": 3, + "row": 6 + }, + "agent": { + "col": 2, + "row": 5 + }, + "cw": { + "col": 2, + "row": 6 + }, + "sys": { + "col": 1, + "row": 6 + } + } + }, + "right": { + "cols": 6, + "rows": 4, + "cells": { + "browser": { + "col": 1, + "row": 3 + }, + "alb": { + "col": 2, + "row": 3 + }, + "svc": { + "col": 3, + "row": 3 + }, + "aurora": { + "col": 4, + "row": 4 + }, + "s3": { + "col": 4, + "row": 1 + }, + "ecs": { + "col": 4, + "row": 2 + }, + "bedrock": { + "col": 6, + "row": 3 + }, + "agent": { + "col": 5, + "row": 2 + }, + "cw": { + "col": 6, + "row": 2 + }, + "sys": { + "col": 6, + "row": 1 + } + } + } + }, + "autoFlowchart": { + "down": { + "cols": 3, + "rows": 7, + "cells": { + "req": { + "col": 2, + "row": 1 + }, + "risk": { + "col": 2, + "row": 2 + }, + "who": { + "col": 2, + "row": 3 + }, + "obs": { + "col": 1, + "row": 4 + }, + "med": { + "col": 3, + "row": 4 + }, + "wait": { + "col": 3, + "row": 5 + }, + "may": { + "col": 2, + "row": 5 + }, + "first": { + "col": 2, + "row": 6 + }, + "told": { + "col": 1, + "row": 7 + }, + "rec": { + "col": 2, + "row": 7 + } + } + }, + "right": { + "cols": 7, + "rows": 3, + "cells": { + "req": { + "col": 1, + "row": 2 + }, + "risk": { + "col": 2, + "row": 2 + }, + "who": { + "col": 3, + "row": 2 + }, + "obs": { + "col": 4, + "row": 1 + }, + "med": { + "col": 4, + "row": 3 + }, + "wait": { + "col": 5, + "row": 3 + }, + "may": { + "col": 5, + "row": 2 + }, + "first": { + "col": 6, + "row": 2 + }, + "told": { + "col": 7, + "row": 1 + }, + "rec": { + "col": 7, + "row": 2 + } + } + } + }, + "autoSchema": { + "down": { + "cols": 3, + "rows": 5, + "cells": { + "memberships": { + "col": 1, + "row": 1 + }, + "room_events": { + "col": 2, + "row": 1 + }, + "log_segments": { + "col": 3, + "row": 1 + }, + "incidents": { + "col": 2, + "row": 2 + }, + "users": { + "col": 1, + "row": 3 + }, + "sandboxes": { + "col": 2, + "row": 3 + }, + "agent_runs": { + "col": 2, + "row": 4 + }, + "approvals": { + "col": 2, + "row": 5 + } + } + }, + "right": { + "cols": 5, + "rows": 3, + "cells": { + "memberships": { + "col": 1, + "row": 1 + }, + "room_events": { + "col": 1, + "row": 2 + }, + "log_segments": { + "col": 1, + "row": 3 + }, + "incidents": { + "col": 2, + "row": 2 + }, + "users": { + "col": 3, + "row": 1 + }, + "sandboxes": { + "col": 3, + "row": 2 + }, + "agent_runs": { + "col": 4, + "row": 2 + }, + "approvals": { + "col": 5, + "row": 2 + } + } + } + }, + "nestedArchitecture": { + "down": { + "cols": 4, + "rows": 6, + "cells": { + "browser": { + "col": 3, + "row": 1 + }, + "alb": { + "col": 3, + "row": 2 + }, + "svc": { + "col": 3, + "row": 3 + }, + "aurora": { + "col": 3, + "row": 4 + }, + "s3": { + "col": 4, + "row": 4 + }, + "ecs": { + "col": 1, + "row": 4 + }, + "bedrock": { + "col": 3, + "row": 6 + }, + "agent": { + "col": 2, + "row": 5 + }, + "cw": { + "col": 2, + "row": 6 + }, + "sys": { + "col": 1, + "row": 6 + } + } + }, + "right": { + "cols": 6, + "rows": 5, + "cells": { + "browser": { + "col": 1, + "row": 4 + }, + "alb": { + "col": 2, + "row": 4 + }, + "svc": { + "col": 3, + "row": 4 + }, + "aurora": { + "col": 4, + "row": 4 + }, + "s3": { + "col": 4, + "row": 5 + }, + "ecs": { + "col": 4, + "row": 1 + }, + "bedrock": { + "col": 6, + "row": 3 + }, + "agent": { + "col": 5, + "row": 2 + }, + "cw": { + "col": 6, + "row": 2 + }, + "sys": { + "col": 6, + "row": 1 + } + } + } + }, + "nestedOneLine": { + "down": { + "cols": 4, + "rows": 6, + "cells": { + "browser": { + "col": 3, + "row": 1 + }, + "alb": { + "col": 3, + "row": 2 + }, + "svc": { + "col": 3, + "row": 3 + }, + "aurora": { + "col": 3, + "row": 4 + }, + "s3": { + "col": 4, + "row": 4 + }, + "ecs": { + "col": 1, + "row": 4 + }, + "bedrock": { + "col": 3, + "row": 6 + }, + "agent": { + "col": 2, + "row": 5 + }, + "cw": { + "col": 2, + "row": 6 + }, + "sys": { + "col": 1, + "row": 6 + } + } + }, + "right": { + "cols": 6, + "rows": 5, + "cells": { + "browser": { + "col": 1, + "row": 4 + }, + "alb": { + "col": 2, + "row": 4 + }, + "svc": { + "col": 3, + "row": 4 + }, + "aurora": { + "col": 4, + "row": 4 + }, + "s3": { + "col": 4, + "row": 5 + }, + "ecs": { + "col": 4, + "row": 1 + }, + "bedrock": { + "col": 6, + "row": 3 + }, + "agent": { + "col": 5, + "row": 2 + }, + "cw": { + "col": 6, + "row": 2 + }, + "sys": { + "col": 6, + "row": 1 + } + } + } + }, + "loopBack": { + "down": { + "cols": 2, + "rows": 4, + "cells": { + "start": { + "col": 1, + "row": 1 + }, + "try": { + "col": 1, + "row": 2 + }, + "ok": { + "col": 1, + "row": 3 + }, + "wait": { + "col": 2, + "row": 4 + }, + "done": { + "col": 1, + "row": 4 + } + } + }, + "right": { + "cols": 4, + "rows": 2, + "cells": { + "start": { + "col": 1, + "row": 1 + }, + "try": { + "col": 2, + "row": 1 + }, + "ok": { + "col": 3, + "row": 1 + }, + "wait": { + "col": 4, + "row": 2 + }, + "done": { + "col": 4, + "row": 1 + } + } + } + }, + "threePlain": { + "down": { + "cols": 3, + "rows": 4, + "cells": { + "in": { + "col": 2, + "row": 1 + }, + "kind": { + "col": 2, + "row": 2 + }, + "a": { + "col": 1, + "row": 3 + }, + "b": { + "col": 2, + "row": 3 + }, + "c": { + "col": 3, + "row": 3 + }, + "log": { + "col": 2, + "row": 4 + } + } + }, + "right": { + "cols": 4, + "rows": 3, + "cells": { + "in": { + "col": 1, + "row": 2 + }, + "kind": { + "col": 2, + "row": 2 + }, + "a": { + "col": 3, + "row": 1 + }, + "b": { + "col": 3, + "row": 2 + }, + "c": { + "col": 3, + "row": 3 + }, + "log": { + "col": 4, + "row": 2 + } + } + } + }, + "longWay": { + "down": { + "cols": 2, + "rows": 5, + "cells": { + "s": { + "col": 2, + "row": 1 + }, + "gate": { + "col": 2, + "row": 2 + }, + "p1": { + "col": 1, + "row": 3 + }, + "p2": { + "col": 1, + "row": 4 + }, + "end": { + "col": 2, + "row": 5 + } + } + }, + "right": { + "cols": 5, + "rows": 2, + "cells": { + "s": { + "col": 1, + "row": 2 + }, + "gate": { + "col": 2, + "row": 2 + }, + "p1": { + "col": 3, + "row": 1 + }, + "p2": { + "col": 4, + "row": 1 + }, + "end": { + "col": 5, + "row": 2 + } + } + } + }, + "twoMains": { + "down": { + "cols": 2, + "rows": 6, + "cells": { + "user": { + "col": 1, + "row": 1 + }, + "cdn": { + "col": 1, + "row": 2 + }, + "gw": { + "col": 1, + "row": 3 + }, + "api": { + "col": 1, + "row": 4 + }, + "jobs": { + "col": 1, + "row": 5 + }, + "db": { + "col": 1, + "row": 6 + } + } + }, + "right": { + "cols": 6, + "rows": 2, + "cells": { + "user": { + "col": 1, + "row": 2 + }, + "cdn": { + "col": 2, + "row": 1 + }, + "gw": { + "col": 3, + "row": 2 + }, + "api": { + "col": 4, + "row": 2 + }, + "jobs": { + "col": 5, + "row": 1 + }, + "db": { + "col": 6, + "row": 2 + } + } + } + } + } +} \ No newline at end of file diff --git a/packages/react/test/fixtures/diagram-spatial-cells.json b/packages/react/test/fixtures/diagram-spatial-cells.json new file mode 100644 index 00000000..4bd7038a --- /dev/null +++ b/packages/react/test/fixtures/diagram-spatial-cells.json @@ -0,0 +1,261 @@ +{ + "architecture": { + "everyCardFromEveryCard": true, + "table": { + "browser": { + "right": "alb", + "left": null, + "down": "ecs", + "up": "aurora" + }, + "alb": { + "right": "svc", + "left": "browser", + "down": "ecs", + "up": "aurora" + }, + "svc": { + "right": "s3", + "left": "alb", + "down": "agent", + "up": "aurora" + }, + "aurora": { + "right": null, + "left": "svc", + "down": "s3", + "up": null + }, + "s3": { + "right": null, + "left": "svc", + "down": "bedrock", + "up": "aurora" + }, + "ecs": { + "right": "bedrock", + "left": "browser", + "down": "agent", + "up": "alb" + }, + "bedrock": { + "right": null, + "left": "ecs", + "down": "cw", + "up": "s3" + }, + "agent": { + "right": "bedrock", + "left": "ecs", + "down": "sys", + "up": "svc" + }, + "cw": { + "right": null, + "left": "sys", + "down": null, + "up": "bedrock" + }, + "sys": { + "right": "cw", + "left": "ecs", + "down": null, + "up": "agent" + } + } + }, + "flowchart": { + "everyCardFromEveryCard": true, + "table": { + "req": { + "right": "med", + "left": "obs", + "down": "risk", + "up": null + }, + "risk": { + "right": "med", + "left": "obs", + "down": "who", + "up": "req" + }, + "who": { + "right": "med", + "left": "obs", + "down": "may", + "up": "risk" + }, + "obs": { + "right": "who", + "left": null, + "down": "told", + "up": "risk" + }, + "med": { + "right": "wait", + "left": "who", + "down": "may", + "up": "risk" + }, + "wait": { + "right": null, + "left": "med", + "down": "may", + "up": "risk" + }, + "may": { + "right": "med", + "left": "obs", + "down": "first", + "up": "who" + }, + "first": { + "right": "med", + "left": "told", + "down": "rec", + "up": "may" + }, + "told": { + "right": "first", + "left": null, + "down": "rec", + "up": "obs" + }, + "rec": { + "right": "med", + "left": "told", + "down": null, + "up": "first" + } + } + }, + "data flow": { + "everyCardFromEveryCard": true, + "table": { + "send": { + "right": "append", + "left": null, + "down": "append", + "up": null + }, + "append": { + "right": "row", + "left": "send", + "down": "seal", + "up": "send" + }, + "row": { + "right": "hear", + "left": "seal", + "down": "seg", + "up": "append" + }, + "hear": { + "right": "see", + "left": "row", + "down": "see", + "up": "row" + }, + "see": { + "right": null, + "left": "hear", + "down": "seg", + "up": "hear" + }, + "seal": { + "right": "row", + "left": "send", + "down": "seg", + "up": "append" + }, + "seg": { + "right": "see", + "left": "seal", + "down": null, + "up": "row" + } + } + }, + "schema": { + "everyCardFromEveryCard": true, + "table": { + "memberships": { + "right": "users", + "left": null, + "down": null, + "up": "log_segments" + }, + "room_events": { + "right": "incidents", + "left": null, + "down": "log_segments", + "up": null + }, + "log_segments": { + "right": "incidents", + "left": null, + "down": "memberships", + "up": "room_events" + }, + "incidents": { + "right": "agent_runs", + "left": "room_events", + "down": "users", + "up": null + }, + "users": { + "right": "sandboxes", + "left": "memberships", + "down": null, + "up": "incidents" + }, + "sandboxes": { + "right": "approvals", + "left": "users", + "down": null, + "up": "agent_runs" + }, + "agent_runs": { + "right": "approvals", + "left": "incidents", + "down": "sandboxes", + "up": null + }, + "approvals": { + "right": null, + "left": "agent_runs", + "down": "sandboxes", + "up": null + } + } + }, + "sequence": { + "everyCardFromEveryCard": true, + "table": { + "marcus": { + "right": "svc", + "left": null, + "down": null, + "up": null + }, + "svc": { + "right": "ecs", + "left": "marcus", + "down": null, + "up": null + }, + "ecs": { + "right": "agent", + "left": "svc", + "down": null, + "up": null + }, + "agent": { + "right": null, + "left": "ecs", + "down": null, + "up": null + } + } + } +} \ No newline at end of file diff --git a/packages/tokens/build.mjs b/packages/tokens/build.mjs index 0d49b0cb..185b59a9 100644 --- a/packages/tokens/build.mjs +++ b/packages/tokens/build.mjs @@ -193,6 +193,17 @@ const css = [ " }", "}", "", + "/* Print (DECISIONS 306, 1.7): the light set, whatever theme the screen shows, on the root and on every selector that sets a theme, last, so", + " it wins over each of them. Generated from the light tokens, so it cannot drift. --_dkm is the diagram marks' theme switch (components.css),", + " set to the light form. An app that prints dark on purpose overrides this with its own CSS. */", + "@media print {", + ` ${MORE_CONTRAST_SELECTORS} {`, + " color-scheme: light;", + " --_dkm: initial;", + ...themed("light").map((t) => decl(t, " ")), + " }", + "}", + "", ].join("\n"); // shadcn/ui's variable names, so its components and blocks pick up Basalt unchanged. diff --git a/packages/tokens/test/contrast.test.mjs b/packages/tokens/test/contrast.test.mjs index 9e6e5ed6..482d8542 100644 --- a/packages/tokens/test/contrast.test.mjs +++ b/packages/tokens/test/contrast.test.mjs @@ -1042,6 +1042,58 @@ for (const theme of THEMES) { }); } +// ---- Print (DECISIONS 306, 1.7): the light set, last, on every selector that sets a theme ---- + +test("print: the token CSS ends with a print block that sets every light colour token to its light value, with color-scheme light, on every theme selector", () => { + const at = tokensCss.lastIndexOf("@media print {"); + assert.ok(at > tokensCss.indexOf("prefers-contrast: more") && at > tokensCss.indexOf("prefers-reduced-motion"), "the print block is last"); + const block = tokensCss.slice(at); + assert.equal(block.trim().split("\n").at(-1), "}", "nothing follows the print block"); + for (const selector of [":root", '[data-theme="light"]', '[data-theme="dark"]', ".light", ".dark", ':root:not([data-theme="light"]):not(.light)']) assert.ok(block.includes(selector), `print is not declared on ${selector}`); + assert.match(block, /color-scheme: light;/); + assert.match(block, /--_dkm: initial;/); + // Every colour declared by the light theme's block is declared again in print, with the same value. + const lightBlock = tokensCss.match(/:root, \[data-theme="light"\], \.light \{([\s\S]*?)\n\}/)[1]; + const decls = (text) => Object.fromEntries([...text.matchAll(/(--basalt-[\w-]+): ([^;]+);/g)].map((m) => [m[1], m[2]])); + const light = decls(lightBlock), print = decls(block); + assert.ok(Object.keys(light).length > 50); + for (const [name, value] of Object.entries(light)) assert.equal(print[name], value, `${name} in print`); +}); + +// DECISIONS 306, 1.0 (Neon's B12 on the batch's code review): every colour in a new seat of batch B joins these tests on levels 0 to 3, in both themes and +// under more contrast. Cardinality marks are the line's own ink; an activation bar's edge is the structure role on its fill (the figure's level) and on the +// ground beside it; a frame's and a nested group's edges are the structure role; a quiet run's line is edge-dim; the text art's inks are on surface-sunken; +// a linked card's words hold on the press step (state-hover) over each level. +for (const theme of THEMES) { + const onLevels = LEVELS.map((n) => [n, color(theme, n)]); + test(`${theme}: batch B's seats: marks, a bar's edge, frames and nested groups, a quiet run, at 3:1 on levels 0 to 3 and under more contrast`, () => { + for (const name of ["diagram-edge-main", "diagram-edge", "diagram-edge-dim", "diagram-structure"]) { + atLeast(theme, name, 3, onLevels); + for (const [bgName, bg] of onLevels) assert.ok(ratio(over(more(theme, name), bg), bg) >= 3, `${theme}: ${name} on ${bgName} under more contrast`); + } + // A bar's fill is the figure's level (surface-1 on the page); its edge holds against that fill and against the page beside it. + const fill = color(theme, "surface-1"); + assert.ok(ratio(over(color(theme, "diagram-structure"), fill), fill) >= 3, `${theme}: a bar's edge on its fill`); + assert.ok(ratio(over(color(theme, "diagram-structure"), color(theme, "surface-0")), color(theme, "surface-0")) >= 3, `${theme}: a bar's edge on the ground`); + }); + test(`${theme}: the text art's inks on surface-sunken (tertiary, secondary, primary) hold 4.5:1, and under more contrast`, () => { + const sunken = [["surface-sunken", color(theme, "surface-sunken")]]; + for (const name of ["text-tertiary", "text-secondary", "text-primary"]) { + atLeast(theme, name, 4.5, sunken); + assert.ok(ratio(over(more(theme, name), sunken[0][1]), sunken[0][1]) >= 4.5, `${theme}: ${name} on surface-sunken under more contrast`); + } + }); + test(`${theme}: a linked card's words hold 4.5:1 on its press step (state-hover) over levels 0 to 3`, () => { + for (const [bgName, bg] of onLevels) { + const step = over(color(theme, "state-hover"), bg); + for (const name of ["text-primary", "text-secondary", "text-tertiary"]) { + const r = ratio(over(more(theme, name), step), step); + assert.ok(r >= 4.5 || (name === "text-tertiary" && ratio(over(color(theme, "text-secondary"), step), step) >= 4.5), `${theme}: ${name} on the press step over ${bgName} is ${fmt(r)}:1`); + } + } + }); +} + // ---- Versions and release notes (DECISIONS 320, 2.8 and 2.10) ---- // // The release page's new pairs. The arrival's plate is plate-0 on the page and plate-1 inside a callout (an action entry); on it the source line and a count diff --git a/packages/tokens/tokens/primitives.tokens.json b/packages/tokens/tokens/primitives.tokens.json index b7698c00..d391a580 100644 --- a/packages/tokens/tokens/primitives.tokens.json +++ b/packages/tokens/tokens/primitives.tokens.json @@ -1219,6 +1219,22 @@ }, "$description": "A diagram's arrowhead, its length and its width, for every kind of line (DECISIONS 281)." }, + "diagram-activation": { + "$type": "dimension", + "$value": { + "value": 8, + "unit": "px" + }, + "$description": "The width of an activation bar on a sequence diagram's lifeline (DECISIONS 306, 1.0)." + }, + "diagram-foot": { + "$type": "dimension", + "$value": { + "value": 14, + "unit": "px" + }, + "$description": "The room a cardinality mark takes at a foreign key line's end; no elbow starts inside it (DECISIONS 306, 1.0)." + }, "diagram-guide-dash": { "$type": "dimension", "$value": { diff --git a/scripts/check-deps.mjs b/scripts/check-deps.mjs index 63ed6816..ed9c43d0 100644 --- a/scripts/check-deps.mjs +++ b/scripts/check-deps.mjs @@ -56,7 +56,14 @@ export function checkDependencies(repo = repoRoot) { const where = `packages/${dir}`; const pkg = JSON.parse(fs.readFileSync(file, "utf8")); const kinds = ["dependencies", "peerDependencies", "optionalDependencies"]; - compare(where, [...new Set(kinds.flatMap((k) => Object.keys(pkg[k] ?? {})))]); + // An approved package whose file is copied into dist is a devDependency (it is not installed with the package), listed in $copied at the exact version + // the copy was made from: it counts as used while that devDependency is there, at that version. + const copied = allowed.$copied?.[where] ?? {}; + for (const [name, version] of Object.entries(copied)) { + const dev = pkg.devDependencies?.[name]; + if (dev !== version) problems.push(`$copied: ${where} "${name}" is listed as "${version}" but is ${dev === undefined ? "not a devDependency" : `"${dev}" in devDependencies`}; the copy in dist and the list must agree.`); + } + compare(where, [...new Set([...kinds.flatMap((k) => Object.keys(pkg[k] ?? {})), ...Object.keys(copied).filter((name) => pkg.devDependencies?.[name] === copied[name])])]); for (const kind of kinds) for (const [name, version] of Object.entries(pkg[kind] ?? {})) { if (EXACT.test(version)) continue; if (ranges[where]?.[name] === version) continue; diff --git a/scripts/verify-packages.mjs b/scripts/verify-packages.mjs index 66e2e982..aa6d2ca9 100644 --- a/scripts/verify-packages.mjs +++ b/scripts/verify-packages.mjs @@ -91,6 +91,17 @@ assert.ok(tokens.dark['text-primary'].hex); assert.equal(accents.cobalt.dark.hex const phosphor = await import('@srasyndicate/basalt/phosphor'); assert.deepEqual(phosphor.BASALT_PHOSPHOR_WEIGHTS, ['bold', 'fill']); assert.throws(() => phosphor.phosphorWeightsEsbuild({}), /weights/); assert.equal(phosphor.phosphorWeightsRollup({ weights: ['bold'] }).transform('x', '/a/b.js'), null); console.log('Packed consumer: runtime, server rendering, exact token types, exports, fonts and RSC boundary pass.');`); process.stdout.write(run(process.execPath, ["smoke.mjs"], consumer)); + // elkjs is a build input of the package, not a dependency (the decider's ruling 2 on the batch B re-check): the package ships its one copy, + // dist/diagram-elk.js, so a consumer with no elkjs installed places an automatic figure. + fs.rmSync(path.join(consumer, "node_modules", "elkjs"), { recursive: true, force: true }); + fs.writeFileSync(path.join(consumer, "place.mjs"), `import assert from 'node:assert/strict'; import fs from 'node:fs'; +assert.ok(!fs.existsSync(new URL('./node_modules/elkjs', import.meta.url)), 'no elkjs in the consumer'); +const { placeDiagram } = await import('@srasyndicate/basalt/diagram-layout'); +const placed = await placeDiagram({ type: 'architecture', nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ from: 'a', to: 'b', kind: 'main' }, { from: 'b', to: 'c' }] }, 'right'); +assert.deepEqual(Object.keys(placed.cells).sort(), ['a', 'b', 'c']); +assert.ok(placed.cells.a.col < placed.cells.c.col); +console.log('Packed consumer: an automatic figure is placed with no elkjs installed.');`); + process.stdout.write(run(process.execPath, ["place.mjs"], consumer)); // A React Server Component, built by Next.js (A5-18): what the package holds that is neither a component nor a hook must be callable on the server. Each // page is static, so a call that throws ("Attempted to call formatStamp() from the server but formatStamp is on the client") fails the build, and a constant // that arrives as a client reference (CONFIRM_MS / 1000 is NaN, with no error) shows in the page's HTML. The components still come through as components. diff --git a/tools/html-skill/build.mjs b/tools/html-skill/build.mjs index f3e59b8d..94c185b1 100644 --- a/tools/html-skill/build.mjs +++ b/tools/html-skill/build.mjs @@ -52,7 +52,9 @@ function tokensFile(name) { if (!fs.existsSync(file)) throw new Error("html-skill: packages/tokens/dist is missing; run `npm run build` first"); return fs.readFileSync(file, "utf8").trim(); } -const tokensCss = () => tokensFile("tokens.css"); +// The token CSS's print block (DECISIONS 306, 1.7) is React's: the skill keeps its own beforeprint switch to the light theme (core.js), so a page does not +// carry the light set twice. Unifying the two is backlog. +const tokensCss = () => tokensFile("tokens.css").replace(/\/\* Print \(DECISIONS 306[\s\S]*?\*\/\n@media print \{[\s\S]*?\n\}(\n|$)/, ""); /** * The generated tokens declare every alias again in the dark `prefers-color-scheme` block, because a nested @@ -256,6 +258,26 @@ function diagramMotionCss() { if (start < 0 || end < 0) throw new Error("html-skill: the diagram motion section of packages/react/src/styles/components.css moved; update diagramMotionCss"); return `@layer basalt {\n${react.slice(start, end).replaceAll(".basalt-diagram", ".diagram")}\n}\n`; } +/** + * The diagram-zoom module's stylesheet (DECISIONS 310): the "Diagram viewer" section of components.css, with React's names as the skill's (the dialog, the + * sheet's parts, the button and the icon), so the viewer in a page is React's viewer. + */ +function diagramZoomCss() { + const react = fs.readFileSync(path.join(repo, "packages", "react", "src", "styles", "components.css"), "utf8"); + const start = react.indexOf(" /* ---- Diagram viewer (DECISIONS 310"); + const end = react.indexOf(" /* ---- ", start + 10); + if (start < 0 || end < 0) throw new Error("html-skill: the diagram viewer section of packages/react/src/styles/components.css moved; update diagramZoomCss"); + const css = react.slice(start, end) + .replaceAll("var(--_surface, var(--basalt-surface-overlay))", "var(--panel-bg, var(--basalt-surface-overlay))") + .replaceAll(".basalt-diagram", ".diagram") + .replaceAll(".basalt-dialog-backdrop", "dialog.modal::backdrop") + .replaceAll(".basalt-dialog", ".dialog") + .replaceAll(".basalt-sheet-", ".sheet-") + .replaceAll(".basalt-button", ".btn") + .replaceAll(".basalt-icon", ".icon"); + if (/basalt-(?!duration|space|size|text|font|border|surface)/.test(css.replace(/--basalt-[\w-]+/g, ""))) throw new Error("html-skill: the diagram viewer section names a React class diagramZoomCss 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. It is a development build of the engine * (NODE_ENV "development"): the skill keeps the checks a production React build drops, since compose.mjs reports them when it writes a page. @@ -275,6 +297,8 @@ export function build() { const manifest = JSON.parse(src("modules.json")); const files = {}; files["compose.mjs"] = src("compose.mjs"); + // The placer compose.mjs runs for an automatic diagram (DECISIONS 306, 1.8): React's placeDiagram, with elkjs left to resolve from the repository. + files["parts/diagram-place.mjs"] = esbuild.buildSync({ entryPoints: [path.join(srcDir, "diagram-place.mjs")], bundle: true, format: "esm", platform: "node", target: "node20", write: false, logLevel: "silent", external: ["elkjs", "elkjs/*"] }).outputFiles[0].text; files["parts/manifest.json"] = `${JSON.stringify(manifest, null, 2)}\n`; files["parts/core.css"] = minifyCss(`${dedupeSystemDark(filterTokens(tokensCss(), inCore))}\n${src("core.css")}`); files["parts/core.js"] = minifyJs(src("core.js")); @@ -289,10 +313,11 @@ export function build() { if (name === "diagram") files["parts/diagram.css"] = minifyCss(`${dedupeSystemDark(filterTokens(tokensCss(), inDiagram))}\n${diagramCss()}`); // The motion section, with the motion tokens (the diagram durations and speeds) that only an animated diagram reads. if (name === "diagram-motion") files["parts/diagram-motion.css"] = minifyCss(`${filterTokens(tokensCss(), inDiagramMotion)}\n${diagramMotionCss()}`); + if (name === "diagram-zoom") files["parts/diagram-zoom.css"] = minifyCss(diagramZoomCss()); for (const ext of ["css", "js"]) { const file = path.join(srcDir, "modules", `${name}.${ext}`); if (!fs.existsSync(file)) continue; - if (ext === "js" && (name === "diagram" || name === "diagram-motion")) files[`parts/${name}.js`] = minifyJs(bundleModule(file)); + if (ext === "js" && (name === "diagram" || name === "diagram-motion" || name === "diagram-zoom" || name === "diagram-export" || name === "diagram-text")) 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")); } } diff --git a/tools/html-skill/src/compose.mjs b/tools/html-skill/src/compose.mjs index 4def7a29..a1b2acef 100644 --- a/tools/html-skill/src/compose.mjs +++ b/tools/html-skill/src/compose.mjs @@ -33,6 +33,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import vm from "node:vm"; +import { MessageChannel, receiveMessageOnPort, Worker } from "node:worker_threads"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -581,7 +582,12 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = // 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. const code = `${held.restore(markup, true)}\n${styles.map((style) => stripCssComments(style.css)).join("\n")}`; - const chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use, glyphNames: Object.keys(glyphFile) }); + let chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use, glyphNames: Object.keys(glyphFile) }); + // The diagram viewer (DECISIONS 310): a page with a figure has "Expand" and its dialog, unless every figure on it says "zoom": false. A figure drawn from + // script (Basalt.diagram) may want it, so it counts. + if (chosen.modules.includes("diagram") && !chosen.modules.includes("diagram-zoom") && "diagram-zoom" in manifest.modules && zoomWanted(held, code)) { + chosen = detect(code, manifest, Object.keys(iconFile.icons), { all, use: [...use, "diagram-zoom"], glyphNames: Object.keys(glyphFile) }); + } // A module the body never triggers, which is in only because another module's script builds its markup (the palette's rows and key chips). const bare = { ...manifest, modules: Object.fromEntries(Object.entries(manifest.modules).map(([n, m]) => [n, { ...m, requires: [] }])) }; const direct = detect(code, bare, [], { all, use }).modules; @@ -630,6 +636,30 @@ export function compose(body, { fonts = true, lang = "en", all = false, parts = return { html, modules: chosen.modules, icons: chosen.icons, glyphs: chosen.glyphs, built, external: externalReferences(held, markup), diagrams: diagramNotes, bytes: Buffer.byteLength(html) }; } +/** + * An automatic diagram's placement for both directions (DECISIONS 306, 1.8), from parts/diagram-place.mjs run in a worker, waited for here: elk answers with + * a promise and compose is synchronous, so this thread sleeps on a shared flag until the worker has posted its answer and woken it. + */ +function placeNow(parts, spec) { + const signal = new SharedArrayBuffer(4); + const { port1, port2 } = new MessageChannel(); + const worker = new Worker(path.join(parts, "diagram-place.mjs"), { workerData: { spec, port: port2, signal }, transferList: [port2] }); + Atomics.wait(new Int32Array(signal), 0, 0, 60_000); + const got = receiveMessageOnPort(port1)?.message; + worker.terminate(); + port1.close(); + if (!got || got.error) throw new Error(got?.error ?? "the placer did not answer"); + return got.placement; +} + +/** Whether any figure on the page keeps its viewer: a `data-diagram` JSON without `"zoom": false`, or a figure drawn from script. */ +function zoomWanted(held, code) { + if (/Basalt\s*\.\s*diagram\b/.test(code)) return true; + const specs = held.saved.filter((item) => item.kind === "script" && item.attrs.some(([k]) => k === "data-diagram")); + if (!specs.length) return true; + return specs.some((item) => { try { return JSON.parse(item.inner).zoom !== false; } catch { return true; } }); +} + /** * A diagram's words, written into the page (DECISIONS 281, 1.19): each `
` 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 @@ -661,11 +691,24 @@ function writeDiagrams(markup, held, parts, notes, marks) { 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; } // Each card's mark: a bundled id is checked and its rule written once; the page's own mark is read into the page and named by an id, so the JSON // the script reads carries the id and never a path. - if (spec && spec.type === "architecture" && Array.isArray(spec.nodes)) { + // An automatic figure (DECISIONS 306, 1.8) is placed here, at build time, for both directions; the page holds the placement and never elkjs. + if (spec && spec.layout === "auto" && !spec.placement && ["architecture", "flowchart", "schema"].includes(spec.type)) { + try { + spec.placement = placeNow(parts, spec); + const inner = `\n${JSON.stringify(spec).replace(/ inner); + item.inner = inner; + } catch (e) { notes.push(`${spec.title ?? "a diagram"} could not be placed (${String(e.message).split("\n")[0]}); it is stacked`); } + } + // An architecture's cards, a data flow's steps and a sequence's participants may carry one (DECISIONS 306, 1.6). + const cards = spec && (spec.type === "architecture" || spec.type === "data-flow") ? spec.nodes : spec && spec.type === "sequence" ? spec.participants : null; + if (Array.isArray(cards)) { let rewrote = false; - for (const n of spec.nodes) { + for (const n of cards) { if (!n || n.mark === undefined || n.mark === null) continue; - if (typeof n.mark === "string") useMark(marks, n.mark, n, notes); + // A data flow's step counts its lane's label as its words, as React's check does (DECISIONS 306, 1.6; Neon's B10 of the code review). + const lane = spec.type === "data-flow" && Array.isArray(spec.lanes) ? spec.lanes.find((l) => l && l.id === n.lane) : null; + if (typeof n.mark === "string") useMark(marks, n.mark, lane ? { ...n, laneLabel: lane.label } : n, notes); else { n.mark = ownMark(marks, n.mark); rewrote = true; } } if (rewrote) { @@ -715,7 +758,7 @@ function useMark(marks, id, node, notes) { } function checkSays(file, id, node, notes) { const says = (Object.hasOwn(file.says, id) ? file.says[id] : undefined) ?? []; - const words = [node.name, node.kind, node.detail].filter(Boolean).join(" ").toLowerCase(); + const words = [node.name, node.kind, node.detail, node.laneLabel].filter(Boolean).join(" ").toLowerCase(); if (says.length && !says.some((w) => words.includes(w.toLowerCase()))) notes.push(`${node.id}'s mark (${id}) stands for ${says.join(" or ")}, and none of its words say so: a mark never carries a fact alone`); } diff --git a/tools/html-skill/src/diagram-place.mjs b/tools/html-skill/src/diagram-place.mjs new file mode 100644 index 00000000..674da6ac --- /dev/null +++ b/tools/html-skill/src/diagram-place.mjs @@ -0,0 +1,19 @@ +// compose.mjs's placer (DECISIONS 306, 1.8): run as a worker, it places one figure for both directions through React's own placeDiagram (elkjs, a +// build-time dependency of the tool, resolved from the repository) and hands the placement back on its port, then wakes compose.mjs, which waits for it +// (compose is synchronous). A page never holds elkjs. Bundled into parts/ by build.mjs. +import { workerData } from "node:worker_threads"; + +import { placeDiagram } from "../../../packages/react/src/diagram-layout.ts"; + +const { spec, port, signal } = workerData; +const flag = new Int32Array(signal); +try { + const directions = spec.direction ? [spec.direction] : spec.type === "flowchart" ? ["down", "right"] : ["right", "down"]; + const out = []; + for (const d of directions) out.push(await placeDiagram(spec, d)); + port.postMessage({ placement: out }); +} catch (e) { + port.postMessage({ error: String(e && e.message ? e.message : e) }); +} +Atomics.store(flag, 0, 1); +Atomics.notify(flag, 0); diff --git a/tools/html-skill/src/modules.json b/tools/html-skill/src/modules.json index 79d89147..e37b5a8b 100644 --- a/tools/html-skill/src/modules.json +++ b/tools/html-skill/src/modules.json @@ -1,5 +1,5 @@ { - "$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 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). Raised in cimip-gaps-2 batch B5 (the touch sizes under 720 whatever the pointer: each coarse-pointer target rule also answers a window under 720, about 20 bytes a rule; forms merged its three into one and stays under 3500): select 9000 to 9100 (measured 9064), selection 1480 to 1500 (1486), filter 17450 to 17500 (17473), option-chips 6850 to 6900 (6853), menu 8900 to 8950 (8902). B5 fix pass 1 (Astra): core 34550 to 34950 (measured 34911: 30762 CSS and 4149 JS) for stacked links in a column, each giving up the side of its 44px box that meets a neighbour, so a tap on a link's words is always that link's; core had 12 bytes free. DECISIONS 274 (the owner's pick: under 720 the toast stack hangs from the bar): toast 15700 to 16050 (measured 16035; 8 bytes were free; the stack's direction became one sign variable, trimming 585 of the 920 bytes the phone form first took). B5 merged with main (5ad5345a): main's own core measured 34930 against its 34550 cap before B5; with B5 (the touch sizes under 720 and stacked links in a column) it is 35331, so core is 35350; nav 5350 to 5400 (measured 5364: B4's nav plus the touch size under 720). The full run after the stream (DECISIONS 246): the site footer's links keep their own flex column under 720, as React's, out of the bare-link touch rule (26 bytes), so core is 35400 (measured 35357); sheet 5250 to 5400 (measured 5368: React's B5 ring room, ported: the held actions reach space-1-5 above their band, clipped, and the body keeps space-1-5 at each end). Raised for diagram motion and service marks (DECISIONS 292): skillMd 12550 to 12650 for the diagram-motion module's one line; diagram 87200 to 91000 for what a still diagram now carries (a card's mark and its seat, the pending frame, the comparison that writes a drawing only when it changed, and the print rule), and its usage 2600 to 4300 for the decision's four lines and the list of mark ids; the new diagram-motion module (the motion engine, its stylesheet and the motion tokens, in a page only when a diagram is animated) at 26200. Raised when the diagram tests were first run (DECISIONS 298): diagram 91000 to 91250 and diagram-motion 26200 to 26850. Raised in batch A of the diagrams backlog (DECISIONS 301): diagram 91250 to 92400, for the engine fixes it bundles (a decision kept no taller than it is wide, labels on whole pixels, slots beside a straight line, a one-column schema's turn-back); the skill keeps the development checks a production React build now drops. Raised again in that batch's review fixes: diagram 92400 to 92650, for the drawn layout refusing two lines laid on one another (Neon's blocking finding 1 on #126). Fix round 1 of #124 had already taken them to 91205 and 26621 with the tests unrun; this round added 1 byte (every focal node prints its fill; a one-form mark's dark form falls back to its light one) and 180 (the entrance keeps its own clock when it is drawn again while paused). DECISIONS 320 (versions and release notes): the release module is new (budget 15900 at first, usage 2400); topbar, app-shell and tab-bar gain the version link's classes (budgets: topbar 17700 to 19900, app-shell 4300 to 5200 with the rail's tooltip for it, tab-bar 4850 to 5200), their usage caps rising 2900 to 3100, 2600 to 2850 and 2250 to 2400 for its one line each; skillMd rose 12650 to 12800 for the release module's line and .version-link in topbar's. The code review of round 68 adds data-focus-self to the popover module (its Tab walk; budget 4950 to 5600, usage cap 950 to 1100) and logical start and end for its alignment; the release module's header grid and the Sources panel's touch rows take it to 16900. The spacing sweep of round 68 (DECISIONS 326: Copy link's words on the edge, the callout's last change, its reference column, the last release, the touch rows' end and the whole code chip) takes the release module to 17400. The ruling on where a release ends (DECISIONS 331: no padding under the last change in a release, a release-ending fold's hang, an arrived change keeping its padding, the panel holding its first margin, Build details 44 on touch and a closed Fixed panel taking no room) takes it to 19000. The code recheck of round 68 (recheck 5) has the popover's Tab walk follow Safari's own rule (Tab skips links on Apple's WebKit, Option-Tab reaches them): popover 5600 to 5900. The pixel recheck of round 68 has the Sources panel's touch rows keep their 20px lines with the link's box as hit area, space-3 rows and space-6 between two linked values (recheck-pixels 4), and the release's whole header take the arrival's plate: release 19000 to 19600. Merging #127 (stages, DECISIONS 316 and 328) into the versioning branch: both had raised skillMd from 12650 to 12800 for their own module's line, and together they came to 12886; SKILL.md was tightened in its wording (no rule dropped) to stay within 12800.Raised in the repo review (23 Nov 2026; budgets are soft, the owner's word): notifications 12450 to 12700 (a link is written only when relative, http, https or mailto, and side and align are checked before they reach the markup), combobox 11200 to 11350 (a disabled field's hidden input is disabled too, now and later), tooltip 3200 to 3550 (the gap to the opener is the tooltip's own, and hover and keyboard focus each hold it open; WCAG 1.4.13), chart 34750 to 34800 (the scale's step search and gridlines are bounded, so extreme values cannot hang the page), spinner 650 to 720 (its held rule moved in from loops, so a ring-only page keeps a stored hold), kbd 2900 to 2950, palette 11400 to 11500 (and its usage text 1350 to 1400, for the Mod line) and toast 16050 to 16200 (Mod in a palette item's keys is bound as it is drawn, and a toast action's aria-keyshortcuts resolves Mod). The safe-sinks rule (decided by the owner, Fable, Astra and Muse, 23 Nov 2026): skillMd 12650 to 12900, and 13050 with main's own raise merged in (one line: data goes in as textContent, a link passes Basalt.safeHref, an option comes from a fixed list), core 35400 to 35650, and 35800 with main's own raise merged in, and its usage 2950 to 3200 (one safeHref, published as Basalt.safeHref, and _.pick, in place of a copy in each module; esc escapes the apostrophe), link-tabs 5750 to 5900 (a refused link dispatches no event), diagram 92650 to 93000 (a card's mark is a relative path, https or a data: image).", + "$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 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). Raised in cimip-gaps-2 batch B5 (the touch sizes under 720 whatever the pointer: each coarse-pointer target rule also answers a window under 720, about 20 bytes a rule; forms merged its three into one and stays under 3500): select 9000 to 9100 (measured 9064), selection 1480 to 1500 (1486), filter 17450 to 17500 (17473), option-chips 6850 to 6900 (6853), menu 8900 to 8950 (8902). B5 fix pass 1 (Astra): core 34550 to 34950 (measured 34911: 30762 CSS and 4149 JS) for stacked links in a column, each giving up the side of its 44px box that meets a neighbour, so a tap on a link's words is always that link's; core had 12 bytes free. DECISIONS 274 (the owner's pick: under 720 the toast stack hangs from the bar): toast 15700 to 16050 (measured 16035; 8 bytes were free; the stack's direction became one sign variable, trimming 585 of the 920 bytes the phone form first took). B5 merged with main (5ad5345a): main's own core measured 34930 against its 34550 cap before B5; with B5 (the touch sizes under 720 and stacked links in a column) it is 35331, so core is 35350; nav 5350 to 5400 (measured 5364: B4's nav plus the touch size under 720). The full run after the stream (DECISIONS 246): the site footer's links keep their own flex column under 720, as React's, out of the bare-link touch rule (26 bytes), so core is 35400 (measured 35357); sheet 5250 to 5400 (measured 5368: React's B5 ring room, ported: the held actions reach space-1-5 above their band, clipped, and the body keeps space-1-5 at each end). Raised for diagram motion and service marks (DECISIONS 292): skillMd 12550 to 12650 for the diagram-motion module's one line; diagram 87200 to 91000 for what a still diagram now carries (a card's mark and its seat, the pending frame, the comparison that writes a drawing only when it changed, and the print rule), and its usage 2600 to 4300 for the decision's four lines and the list of mark ids; the new diagram-motion module (the motion engine, its stylesheet and the motion tokens, in a page only when a diagram is animated) at 26200. Raised when the diagram tests were first run (DECISIONS 298): diagram 91000 to 91250 and diagram-motion 26200 to 26850. Raised in batch A of the diagrams backlog (DECISIONS 301): diagram 91250 to 92400, for the engine fixes it bundles (a decision kept no taller than it is wide, labels on whole pixels, slots beside a straight line, a one-column schema's turn-back); the skill keeps the development checks a production React build now drops. Raised again in that batch's review fixes: diagram 92400 to 92650, for the drawn layout refusing two lines laid on one another (Neon's blocking finding 1 on #126). Fix round 1 of #124 had already taken them to 91205 and 26621 with the tests unrun; this round added 1 byte (every focal node prints its fill; a one-form mark's dark form falls back to its light one) and 180 (the entrance keeps its own clock when it is drawn again while paused). DECISIONS 320 (versions and release notes): the release module is new (budget 15900 at first, usage 2400); topbar, app-shell and tab-bar gain the version link's classes (budgets: topbar 17700 to 19900, app-shell 4300 to 5200 with the rail's tooltip for it, tab-bar 4850 to 5200), their usage caps rising 2900 to 3100, 2600 to 2850 and 2250 to 2400 for its one line each; skillMd rose 12650 to 12800 for the release module's line and .version-link in topbar's. The code review of round 68 adds data-focus-self to the popover module (its Tab walk; budget 4950 to 5600, usage cap 950 to 1100) and logical start and end for its alignment; the release module's header grid and the Sources panel's touch rows take it to 16900. The spacing sweep of round 68 (DECISIONS 326: Copy link's words on the edge, the callout's last change, its reference column, the last release, the touch rows' end and the whole code chip) takes the release module to 17400. The ruling on where a release ends (DECISIONS 331: no padding under the last change in a release, a release-ending fold's hang, an arrived change keeping its padding, the panel holding its first margin, Build details 44 on touch and a closed Fixed panel taking no room) takes it to 19000. The code recheck of round 68 (recheck 5) has the popover's Tab walk follow Safari's own rule (Tab skips links on Apple's WebKit, Option-Tab reaches them): popover 5600 to 5900. The pixel recheck of round 68 has the Sources panel's touch rows keep their 20px lines with the link's box as hit area, space-3 rows and space-6 between two linked values (recheck-pixels 4), and the release's whole header take the arrival's plate: release 19000 to 19600. Merging #127 (stages, DECISIONS 316 and 328) into the versioning branch: both had raised skillMd from 12650 to 12800 for their own module's line, and together they came to 12886; SKILL.md was tightened in its wording (no rule dropped) to stay within 12800. Raised in diagram batch B's fix round (DECISIONS 318, the owner's diagram raise; and 326's sweep), each to its measured size: diagram 137700 to 144100 (the two reviews' fixes in the shared engine: right to left frames and self-calls, the corridors' and lanes' development words, the unusable-placement check, the transcript's hanging lines, the text art's frame widening, the frame-side fit check, the sequence's layers, the stacked group's turn room), diagram-motion 28450 to 30450 (the text sequence's build by ink and its colour-only run, moved into the motion module), diagram-zoom 17000 to 17600 (a linked card closes the viewer; the text art's own width; a placed model for the key hint), diagram-export 7850 to 10450 (an export at rest: sized drawing SVGs, no reveal masks, the pseudo-element rules, the lines under the cards, a viewer's figure read at 100% with its head and key, the rim's lit top). Raised at the batch B re-check (the decider's four rulings): diagram 144100 to 145100 (5.1's first list reported as errors apart from the warnings, a turn's label lines on the group entered by it and the seats beside its turn, the bare stack applied, the text art's reset of the core's inline code chip). Merging main (#127 and #128) into diagram batch B: skillMd keeps main's 12800 (batch B had raised it to 12950 for its diagram lines); SKILL.md was tightened in its wording to stay within it, no rule dropped; core takes main's 35550.Raised in the repo review (23 Nov 2026; budgets are soft, the owner's word): notifications 12450 to 12700 (a link is written only when relative, http, https or mailto, and side and align are checked before they reach the markup), combobox 11200 to 11350 (a disabled field's hidden input is disabled too, now and later), tooltip 3200 to 3550 (the gap to the opener is the tooltip's own, and hover and keyboard focus each hold it open; WCAG 1.4.13), chart 34750 to 34800 (the scale's step search and gridlines are bounded, so extreme values cannot hang the page), spinner 650 to 720 (its held rule moved in from loops, so a ring-only page keeps a stored hold), kbd 2900 to 2950, palette 11400 to 11500 (and its usage text 1350 to 1400, for the Mod line) and toast 16050 to 16200 (Mod in a palette item's keys is bound as it is drawn, and a toast action's aria-keyshortcuts resolves Mod). The safe-sinks rule (decided by the owner, Fable, Astra and Muse, 23 Nov 2026): skillMd 12650 to 12900, and 13050 with main's own raise merged in (one line: data goes in as textContent, a link passes Basalt.safeHref, an option comes from a fixed list), core 35400 to 35650, and 35800 with main's own raise merged in, and its usage 2950 to 3200 (one safeHref, published as Basalt.safeHref, and _.pick, in place of a copy in each module; esc escapes the apostrophe), link-tabs 5750 to 5900 (a refused link dispatches no event), diagram 92650 to 93000 (a card's mark is a relative path, https or a data: image). Merging #129 into diagram batch B: diagram keeps batch B's 145100 plus #129's mark check, set to its measure, and batch B's usage 4600.", "budgets": { "skillMd": 13050, "core": 35800 @@ -820,8 +820,8 @@ "art", "kbd" ], - "budget": 93000, - "usage": 4300, + "budget": 145450, + "usage": 4600, "builds": [ "kbd" ] @@ -847,8 +847,8 @@ "toggle", "glyph" ], - "budget": 26850, - "usage": 1300, + "budget": 30450, + "usage": 1450, "builds": [ "loops", "toggle", @@ -858,6 +858,64 @@ "pause" ] }, + "diagram-zoom": { + "classes": [ + "diagram-expand", + "diagram-viewer", + "diagram-stage", + "diagram-sizer", + "diagram-layer", + "diagram-zoom", + "diagram-level", + "diagram-probe", + "diagram-viewer-foot", + "diagram-viewer-key", + "diagram-viewer-row", + "diagram-viewer-hint", + "diagram-viewer-end", + "diagram-viewer-list", + "diagram-viewer-source" + ], + "requires": [ + "diagram", + "dialog", + "dialog-form", + "sheet" + ], + "budget": 17600, + "usage": 900, + "builds": [ + "dialog", + "dialog-form", + "sheet" + ] + }, + "diagram-export": { + "text": [ + "\"export\"\\s*:\\s*true" + ], + "textWords": [ + "a diagram's \"export\": true" + ], + "requires": [ + "diagram" + ], + "budget": 10450, + "usage": 700 + }, + "diagram-text": { + "text": [ + "\"variant\"\\s*:\\s*\"text\"" + ], + "textWords": [ + "a sequence's \"variant\": \"text\"" + ], + "requires": [ + "diagram" + ], + "budget": 5450, + "usage": 700 + }, "sparkline": { "classes": [ "sparkline", diff --git a/tools/html-skill/src/modules/diagram-export.js b/tools/html-skill/src/modules/diagram-export.js new file mode 100644 index 00000000..fb62ae93 --- /dev/null +++ b/tools/html-skill/src/modules/diagram-export.js @@ -0,0 +1,43 @@ +/* Basalt HTML script, diagram-export module (DECISIONS 306, 1.7): a figure whose JSON says "export": true gets "Download SVG" and "Download PNG" in its + foot (secondary small buttons, before "Clear highlight"), and in its viewer's foot, where they write the viewer's drawing at 100%. They write the figure in + the theme shown: native SVG, never foreignObject, its words as text, the faces embedded. The code is React's (packages/react/src/diagram-export.ts), + bundled into this module by build.mjs. compose.mjs adds it only to a page with such a figure. The implementation hasn't been reviewed. + Source: tools/html-skill/src/modules/diagram-export.js (do not edit the copy in the skill folder). */ +import { diagramToPng, diagramToSvg, exportName } from "../../../../packages/react/src/diagram-export.ts"; + +(function (B) { + 'use strict'; + var _ = B._; + + function save(blob, name) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = name; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000); + } + function button(words, run) { + var b = document.createElement('button'); + b.type = 'button'; + b.className = 'btn diagram-download'; + b.setAttribute('data-variant', 'secondary'); + b.setAttribute('data-size', 'sm'); + var label = document.createElement('span'); + label.textContent = words; + b.appendChild(label); + b.addEventListener('click', run); + return b; + } + + /** Puts the two buttons in a foot, before "Clear highlight", for the figure `fig`. Returns them, so a redraw can take them out. */ + _.diagramExport = function (foot, fig) { + var svg = button('Download SVG', function () { diagramToSvg(fig).then(function (b) { save(b, exportName(fig, 'svg')); }); }); + var png = button('Download PNG', function () { diagramToPng(fig).then(function (b) { save(b, exportName(fig, 'png')); }); }); + var clear = foot.querySelector('.diagram-clear'); + foot.insertBefore(svg, clear); + foot.insertBefore(png, clear); + return [svg, png]; + }; +})(window.Basalt); diff --git a/tools/html-skill/src/modules/diagram-text.js b/tools/html-skill/src/modules/diagram-text.js new file mode 100644 index 00000000..716acda0 --- /dev/null +++ b/tools/html-skill/src/modules/diagram-text.js @@ -0,0 +1,35 @@ +/* Basalt HTML script, diagram-text module (DECISIONS 306, 1.2): a sequence whose JSON says "variant": "text" is a code block of box-drawing characters + where its widest line fits, and its transcript (written into the page by compose.mjs) where it does not. The art is React's own + (packages/react/src/diagram-text.ts), bundled here by build.mjs. Under "motion": "animated" it builds by ink as it comes into view (the diagram-motion module). The implementation hasn't been reviewed. + Source: tools/html-skill/src/modules/diagram-text.js (do not edit the copy in the skill folder). */ +import { textArt } from "../../../../packages/react/src/diagram-text.ts"; + +(function (B) { + 'use strict'; + B._.diagramText = function (figure, model, spec, viewer) { + var pre = figure.querySelector('.diagram-text'); + var code = pre && pre.querySelector('.diagram-text-ink'); + if (!code) return; + if (!figure.__transcript) figure.__transcript = code.innerHTML; + var made = textArt(model); + // A glyph's width at 100%: offsetWidth, which no transform scales (the viewer's layer is zoomed when this runs), on one unbreakable run. + var probe = document.createElement('span'); + probe.style.cssText = 'display:inline-block;white-space:pre'; + probe.textContent = '─'.repeat(40); + pre.appendChild(probe); + var cw = probe.offsetWidth / 40; + probe.remove(); + var cs = getComputedStyle(pre); + var room = pre.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight); + // In the viewer the art is held at its own width, never the transcript (DECISIONS 310, 9.3). + if (viewer && viewer.textWidth) { + viewer.textWidth(made.width * cw + (figure.clientWidth - room) + 1); + room = pre.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight); + } + var art = made.width * cw <= room + 0.5; + var html = art ? made.html : figure.__transcript; + if (code.innerHTML !== html) code.innerHTML = html; + pre.toggleAttribute('data-art', art); + // Under "motion": "animated" the art builds by ink when it comes into view: the diagram-motion module's, as a drawn figure's entrance is. + }; +})(window.Basalt); diff --git a/tools/html-skill/src/modules/diagram-zoom.js b/tools/html-skill/src/modules/diagram-zoom.js new file mode 100644 index 00000000..c90798b4 --- /dev/null +++ b/tools/html-skill/src/modules/diagram-zoom.js @@ -0,0 +1,167 @@ +/* Basalt HTML script, diagram-zoom module (DECISIONS 301, part 9, as DECISIONS 310): "Expand" in a figure's foot opens the viewer, a form dialog + (the dialog module's, with the sheet's head, body and foot) whose body is a stage: the figure's drawn layout, laid out once at 100% and zoomed by + the reader with one transform, from Fit or 100% to 400%; a pan is a scroll. The zoom and pan are React's own (packages/react/src/diagram-zoom-core.ts, + bundled into this module by build.mjs); the figure is drawn by the diagram module's engine (Basalt._.diagramKit), so this holds no second copy of it. + compose.mjs adds this module to a page with a figure unless every figure on it says "zoom": false. The implementation hasn't been reviewed. + Source: tools/html-skill/src/modules/diagram-zoom.js (do not edit the copy in the skill folder). */ +import { attachZoom, measureViewerFigure, revealIn, VIEWER_KEYS, viewerHint, viewerTextWidth } from "../../../../packages/react/src/diagram-zoom-core.ts"; + +(function (B) { + 'use strict'; + var _ = B._; + var serial = 0; + + function esc(s) { return _.diagramKit.escapeHtml(String(s == null ? '' : s)); } + function kbd(k) { return '' + esc(k) + ''; } + function px(el, prop) { return parseFloat(getComputedStyle(el).getPropertyValue(prop)) || 0; } + + /** Builds the viewer for one figure and opens it; closing it removes it. */ + function openViewer(page, spec, ctx, opener) { + var kit = _.diagramKit; + var still = Object.assign({}, spec, { motion: 'still' }); + // An automatic figure's key hint is read from a placed model, as React's (unplaced, every card is in one cell). + var model = kit.buildModel(still, { placement: Array.isArray(still.placement) ? still.placement[0] : still.placement }); + var id = 'dgv' + (++serial); + var key = kit.figureKey('diagram', model); + var hint = viewerHint(kit.hintEntries(model, true)).map(function (e) { return '' + e.keys.map(kbd).join(' ') + ' ' + esc(e.words) + ''; }).join(''); + var d = document.createElement('dialog'); + d.className = 'panel float modal dialog diagram-viewer'; + d.setAttribute('data-form', ''); + d.setAttribute('aria-describedby', id + '-summary'); + d.innerHTML = + '

' + esc(model.title) + '

' + + (spec.source ? '

' + esc(spec.source) + '

' : '') + '
' + + '
' + + '

' + esc(spec.summary) + '

' + + '
' + + '' + + '
' + + '
' + + (key ? '
' + kit.toHtml(key) + '
' : '') + + '
' + + '' + + '' + + '' + + '
' + + '' + + '
' + + '
'; + document.body.appendChild(d); + var stage = d.querySelector('.diagram-stage'), sizer = d.querySelector('.diagram-sizer'), layer = d.querySelector('.diagram-layer'); + var fig = layer.firstChild, status = d.querySelector('[role="status"]'), level = d.querySelector('.diagram-level > span'); + var keyBox = d.querySelector('.diagram-viewer-key'), toggle = d.querySelector('.diagram-toggle'); + var buttons = { out: d.querySelector('[data-zoom="out"]'), in: d.querySelector('[data-zoom="in"]'), fit: d.querySelector('[data-zoom="fit"]') }; + var list = null, listOpen = false, bare = false; + var setOff = function (b, off) { if (off) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); }; + var zoom = attachZoom({ + stage: stage, sizer: sizer, layer: layer, status: status, rest: px(stage, '--_rest') || 300, + onChange: function (s) { + level.textContent = s.level + '%'; + setOff(buttons.out, s.listOpen || s.atMin); + setOff(buttons.in, s.listOpen || s.atMax); + setOff(buttons.fit, s.listOpen || s.atFit); + }, + }); + var memo = {}; + var view = { + layer: layer, avail: 0, row: 1104, contain: 480, memo: memo, measureFigure: kit.measureFigure, keys: VIEWER_KEYS, + room: function () { var pad = parseFloat(getComputedStyle(sizer).paddingTop) || 0; return { w: stage.clientWidth - 2 * pad, h: stage.clientHeight - 2 * pad }; }, + measure: function (f, m, p, base, current, apply, warn) { return measureViewerFigure(f, m, p, base, current, apply, warn, view); }, + textWidth: function (need) { viewerTextWidth(view, need); }, + onMeasured: function (measured, f) { + stage.setAttribute('data-layout', measured.dyn.layout || ''); + if (keyBox) { keyBox.setAttribute('data-layout', measured.dyn.layout || ''); keyBox.toggleAttribute('data-bare', Boolean(measured.dyn.bare)); } + bare = Boolean(measured.dyn.bare); + toggle.hidden = bare; + showList(listOpen || bare); + zoom.size(f.offsetWidth, f.offsetHeight); + }, + }; + function readStage() { + view.avail = Math.max(0, Math.floor(stage.clientWidth - 2 * (parseFloat(getComputedStyle(sizer).paddingLeft) || 0))); + view.row = d.querySelector('[data-probe="row"]').offsetWidth || 1104; + view.contain = d.querySelector('[data-probe="contain"]').offsetWidth || 480; + } + function showList(open) { + if (open && !list) { + list = document.createElement('div'); + list.className = 'diagram-list diagram-viewer-list'; + list.innerHTML = kit.figureList('diagram', model).map(function (v) { return kit.toHtml(v); }).join(''); + stage.appendChild(list); + } + // The place is kept before the drawing is hidden, and given back once it shows again. + if (open) zoom.list(true); + if (list) list.hidden = !open; + sizer.hidden = open; + if (!open) zoom.list(false); + } + toggle.addEventListener('click', function () { + listOpen = !listOpen; + toggle.setAttribute('aria-expanded', String(listOpen)); + toggle.firstElementChild.textContent = listOpen ? 'Hide the list' : 'View as list'; + showList(listOpen || bare); + }); + buttons.out.addEventListener('click', function () { if (!buttons.out.hasAttribute('aria-disabled')) zoom.zoomOut(); }); + buttons.in.addEventListener('click', function () { if (!buttons.in.hasAttribute('aria-disabled')) zoom.zoomIn(); }); + buttons.fit.addEventListener('click', function () { if (!buttons.fit.hasAttribute('aria-disabled')) zoom.fit(); }); + // A linked card is followed on a click, a tap or Enter; a link that stays in this tab closes the viewer first (DECISIONS 310, 9.7). + d.addEventListener('click', function (e) { + var a = e.target.closest && e.target.closest('a.diagram-node[href]'); + if (!a || !d.contains(a) || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || (a.target && a.target !== '_self')) return; + if (d.open) d.close(); + }); + stage.addEventListener('focusin', function (e) { + var node = e.target.closest && e.target.closest('.diagram-node'); + if (node && stage.contains(node)) revealIn(stage, node, px(stage, '--_clear') || 16); + }); + + // The viewer's foot has the downloads too, writing the viewer's drawing (DECISIONS 310, 9.11). + if (spec.export === true && typeof _.diagramExport === 'function') _.diagramExport(d.querySelector('.diagram-viewer-end'), fig); + B.openDialog(d, opener); + readStage(); + kit.draw(fig, still, false, view); + // Focus opens on the stage, so the zoom keys and the scrolling keys work at once and no card is traced (9.8). + setTimeout(function () { stage.focus({ preventScroll: true }); }, 0); + var width = stage.clientWidth; + var observer = new ResizeObserver(function () { + if (Math.abs(stage.clientWidth - width) < 0.5) return; + width = stage.clientWidth; + readStage(); + if (fig.__diagram) fig.__diagram.layout(); + }); + observer.observe(stage); + // Laid out again once the dialog's entrance has ended, unscaled, so its lines snap on the pixel grid they are drawn on. + d.addEventListener('transitionend', function (e) { if (e.target === d && e.propertyName === 'transform' && d.open && fig.__diagram) fig.__diagram.layout(); }); + page.setAttribute('data-viewing', ''); + if (ctx.animated) ctx.settle(); + d.addEventListener('close', function () { + observer.disconnect(); + zoom.destroy(); + if (fig.__diagram) fig.__diagram.stop(); + page.removeAttribute('data-viewing'); + // The dialog leaves on its own motion, then goes. + setTimeout(function () { d.remove(); }, px(d, '--_dur') * 0.75 || 300); + }); + } + + /** Puts "Expand" after "View as list" in a figure's foot. Returns what the diagram module calls when it draws the figure again. */ + _.diagramZoom = function (page, spec, ctx) { + var foot = page.querySelector(':scope > .diagram-foot'); + if (!foot) return null; + var old = foot.querySelector('.diagram-expand'); + if (old) old.remove(); + var button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn diagram-expand'; + button.setAttribute('data-variant', 'secondary'); + button.setAttribute('data-size', 'sm'); + button.setAttribute('aria-haspopup', 'dialog'); + // Words only, as React's (a deviation from 9.1): the core set draws no expand glyph. + button.innerHTML = 'Expand'; + var toggle = foot.querySelector('.diagram-toggle'); + if (toggle && toggle.nextSibling) foot.insertBefore(button, toggle.nextSibling); else foot.appendChild(button); + var onClick = function () { openViewer(page, spec, ctx, button); }; + button.addEventListener('click', onClick); + return { destroy: function () { button.removeEventListener('click', onClick); button.remove(); } }; + }; +})(window.Basalt); diff --git a/tools/html-skill/src/modules/diagram.js b/tools/html-skill/src/modules/diagram.js index d44efada..421332a2 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, entranceDrawn, escapeHtml, figureTree, hasStops, hintEntries, keyTarget, measureFigure, moveStop, settleEntrance, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts"; +import { applyTrace, tapTrace, buildModel, entranceDrawn, escapeHtml, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, moveStop, settleEntrance, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts"; (function (B) { 'use strict'; @@ -12,8 +12,8 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops 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 options(base, spec, viewer) { + return { prefix: P, base: base, hasSource: spec.source !== undefined && spec.source !== null && spec.source !== '', hiddenClass: 'visually-hidden', viewer: viewer ? viewer.keys : undefined }; } function slots(model, spec, base, open) { var kbd = function (k) { return '' + escapeHtml(k) + ''; }; @@ -26,16 +26,23 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops } /** 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)); + function markup(spec, base, viewer) { + // An automatic figure's words are written on the placement compose.mjs made, in the type's own direction, so before script its cards are in their + // cells and not piled into one (Neon's B8 of the code review). + var auto = spec.layout === 'auto' && (spec.type === 'architecture' || spec.type === 'flowchart' || spec.type === 'schema'); + var list = auto ? (Array.isArray(spec.placement) ? spec.placement : spec.placement ? [spec.placement] : []) : []; + var first = spec.direction || (spec.type === 'flowchart' ? 'down' : 'right'); + var placed = null; + for (var i = 0; i < list.length; i++) if (list[i].direction === first) placed = list[i]; + var model = buildModel(spec, { placement: placed || list[0] }); + var tree = figureTree(model, {}, options(base, spec, viewer)); 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 - '
'.length), warnings: model.warnings }; + return { open: html.slice(0, open + 1), inner: html.slice(open + 1, html.length - ''.length), warnings: model.errors.map(function (e) { return 'error: ' + e; }).concat(model.warnings) }; } // 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', 'data-bare']; + var OWN = ['aria-labelledby', 'data-type', 'data-cols', 'data-reach', 'data-gutter', 'data-marks', 'data-layout', 'data-measured', 'data-bare']; var OWN_STYLE = ['--_cols', '--_gpad', '--_track']; /** @@ -43,17 +50,25 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops * 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) { + function draw(figure, spec, attach, viewer) { if (figure.__diagram) figure.__diagram.stop(); var base = (figure.getAttribute('aria-labelledby') || '').replace(/-title$/, '').replace(/[^A-Za-z0-9_-]/g, ''); - var model = buildModel(spec); + // Right to left (DECISIONS 306, 1.7): the figure follows its computed direction, and the model is mirrored. + var rtl = getComputedStyle(figure).direction === 'rtl'; + // Automatic layout (DECISIONS 306, 1.8): a page places at build time (compose.mjs writes `placement` for both directions); a page never holds elkjs. + var auto = spec.layout === 'auto' && (spec.type === 'architecture' || spec.type === 'flowchart' || spec.type === 'schema'); + var placements = auto ? (Array.isArray(spec.placement) ? spec.placement : spec.placement ? [spec.placement] : []) : []; + if (auto && !placements.length) console.warn('Basalt diagram: "layout": "auto" needs a placement, which compose.mjs writes at build time; drawn from script, place it with placeDiagram (@srasyndicate/basalt/diagram-layout) and pass "placement". The figure is stacked'); + var order = spec.direction ? [spec.direction] : spec.type === 'flowchart' ? ['down', 'right'] : ['right', 'down']; + var placeOf = function (d) { for (var i = 0; i < placements.length; i++) if (placements[i].direction === d) return placements[i]; return undefined; }; + var model = buildModel(spec, { rtl: rtl, placement: auto ? placeOf(order[0]) : undefined }); 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 made = markup(spec, base, viewer); var holder = document.createElement('div'); holder.innerHTML = made.open + ''; var fresh = holder.firstChild; @@ -69,22 +84,56 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops figure.insertAdjacentHTML('beforeend', made.inner); } model.warnings.forEach(function (w) { console.warn('Basalt diagram: ' + w); }); - var opts = options(base, spec); + // 5.1's first list is an error (the decider's ruling 1 on the re-check): console.error, and the figure is drawn as it would be anyway. + model.errors.forEach(function (e) { console.error('Basalt diagram: ' + e); }); + if (model.motion.animated && model.motion.firstVisit && !figure.id) console.error('Basalt diagram: "entrance": "first-visit" needs an id on the figure: without one the entrance plays on every visit'); + var opts = options(base, spec, viewer); var state = {}; var measured = null; - var focusTrace = null, hoverTrace = null; + var focusTrace = null, hoverTrace = null, touchTrace = null; var warned = Object.create(null); - var warn = function (m) { if (!warned[m]) { warned[m] = 1; console.warn('Basalt diagram: ' + m); } }; + var warn = function (m, level) { if (!warned[m]) { warned[m] = 1; (level === 'error' ? console.error : 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'); // Motion (DECISIONS 292) is the diagram-motion module's: compose.mjs adds it to a page whose diagram says "motion": "animated". Without it the // figure is as still. `drawn` is the ink last written, so a measure that draws the same lines writes nothing. - var animated = model.motion.animated && typeof _.diagramMotion === 'function'; + var animated = !viewer && model.motion.animated && typeof _.diagramMotion === 'function'; var motion = null, drawn = null; var settle = function () { if (animated) settleEntrance(figure); }; - function retrace() { applyTrace(figure, P, measured && measured.geo, measured && measured.tokens, base, focusTrace || hoverTrace); } + function retrace() { applyTrace(figure, P, measured && measured.geo, measured && measured.tokens, base, focusTrace || touchTrace || hoverTrace); syncClear(); } + // A trace on touch (DECISIONS 306, 1.5): "Clear highlight", last in the foot, is mounted whenever the figure is on touch and drawn with lines, and + // aria-disabled until a trace is up. "On touch" is the media's, or a figure that has taken a touch tap. + var clearBtn = null, touched = !viewer && matchMedia('(hover: none), (pointer: coarse)').matches; + function syncClear() { + var want = touched && !viewer && ink && ink.innerHTML !== ''; + figure.toggleAttribute('data-touch', Boolean(touched && !viewer)); + if (want && !clearBtn) { + var foot = figure.querySelector(':scope > .diagram-foot'); + if (!foot) return; + clearBtn = document.createElement('button'); + clearBtn.type = 'button'; + clearBtn.className = 'btn diagram-clear'; + clearBtn.setAttribute('data-variant', 'secondary'); + clearBtn.setAttribute('data-size', 'sm'); + clearBtn.innerHTML = 'Clear highlight'; + clearBtn.addEventListener('click', function () { if (touchTrace) { touchTrace = null; retrace(); } }); + foot.appendChild(clearBtn); + } else if (!want && clearBtn) { clearBtn.remove(); clearBtn = null; } + // "Clear highlight" is last in the foot, after the motion module's buttons, which may be added after it (Neon's P7); never moved while it has focus. + if (clearBtn && clearBtn !== clearBtn.parentNode.lastElementChild && document.activeElement !== clearBtn) clearBtn.parentNode.appendChild(clearBtn); + if (clearBtn) { if (touchTrace) clearBtn.removeAttribute('aria-disabled'); else clearBtn.setAttribute('aria-disabled', 'true'); } + } + function onTap(event) { + if (event.defaultPrevented) return; + var next = tapTrace(figure, P, event, touchTrace); + if (next === undefined) return; + settle(); + touched = true; + touchTrace = next; + retrace(); + } // The toggle's words and state follow the list's (a stack drawn with no lines opens it). function syncToggle() { if (!toggle) return; @@ -92,17 +141,63 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops toggle.firstElementChild.textContent = state.open ? 'Hide the list' : 'View as list'; } function layout() { - measured = measureFigure(figure, model, P, base, state, apply, warn); + // An automatic figure: the first direction, in order, whose drawn layout fits at this width; none fits, the first, stacked. + if (auto && placements.length > 1 && !viewer) { + var chosen = null, why = [], fitsByWidth = false; + for (var k = 0; k < order.length && !chosen; k++) { + var place = placeOf(order[k]); + if (!place) continue; + var trial = buildModel(spec, { rtl: rtl, placement: place }); + var said = []; + var t = measureFigure(figure, trial, P, base, {}, function (d) { syncAttributes(figure, figureTree(trial, d, opts)); }, function (w) { said.push(w); }); + if (t.dyn.layout === 'drawn') { chosen = trial; break; } + var reasons = said.filter(function (w) { return w.indexOf('the drawn layout does not fit') === 0; }).map(function (w) { return w.replace(/^the drawn layout does not fit at \d+px: /, ''); }); + if (reasons.length) fitsByWidth = true; + why.push('laid ' + order[k] + ' ' + (reasons.length ? reasons.join('; ') : 'it needs ' + Math.ceil(t.least || 0) + 'px')); + } + // When no direction draws and one had the width, one warning for the figure and its reasons (DECISIONS 322, rule 5), as React's. + if (!chosen && fitsByWidth) { + var key = why.join('; ').replace(/\d+px/g, ''); + if (figure.__autoWarned !== key) { figure.__autoWarned = key; console.warn('Basalt diagram: layout="auto" draws in neither direction at ' + Math.round(figure.clientWidth) + 'px, so the figure is stacked: ' + why.join('; ') + '. Name a side on a line named here (fromSide, toSide), shorten a label named here, or write the figure authored: placeDiagram returns every cell to start from'); } + } + model = chosen || buildModel(spec, { rtl: rtl, placement: placeOf(order[0]) }); + } + // In the viewer, the direction with the larger Fit in the stage; a tie keeps the type's own (DECISIONS 310, 9.3). + if (auto && placements.length > 1 && viewer && !spec.direction && viewer.room) { + var room = viewer.room(), best = -1, pickM = null; + for (var j = 0; j < order.length; j++) { + var pl = placeOf(order[j]); + if (!pl) continue; + var tm = buildModel(spec, { rtl: rtl, placement: pl }); + var tr = viewer.measure(figure, tm, P, base, {}, function (d) { syncAttributes(figure, figureTree(tm, d, opts)); }); + if (tr.dyn.layout !== 'drawn') continue; + // Fit as the viewer takes it (whole per cents, 200% at most), so a tie at 200% keeps the type's own direction. + var fit = Math.min(2, Math.floor(Math.min(room.w / figure.offsetWidth, room.h / figure.offsetHeight) * 100 + 1e-6) / 100); + if (fit > best + 1e-6) { best = fit; pickM = tm; } + } + if (pickM) model = pickM; + } + // The viewer's figure (DECISIONS 310, the diagram-zoom module) is laid out at the stage's width and measured only at 100%. + measured = (viewer ? viewer.measure : measureFigure)(figure, model, P, base, state, apply, warn); state = measured.dyn; apply(state); syncToggle(); + // The key hint follows the layout: four arrows where the drawn figure has rows and columns (DECISIONS 306, 1.5). + var hintEl = figure.querySelector(':scope > .diagram-hint'); + if (hintEl) { var hintHtml = hintEntries(model, state.layout === 'drawn').map(function (e) { return '' + e.keys.map(function (k) { return '' + escapeHtml(k) + ''; }).join(' ') + ' ' + escapeHtml(e.words) + ''; }).join(''); if (hintEl.innerHTML !== hintHtml) hintEl.innerHTML = hintHtml; } // 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 (!hasStops(model, state)) hoverTrace = touchTrace = null; var fresh = ink && measured.ink !== drawn; if (fresh) { ink.innerHTML = measured.ink; drawn = measured.ink; } retrace(); // In the frame an animated figure's lines are first drawn it is pending; after that the motion module follows a drawing that changed. - if (animated && measured.tokens) { entranceDrawn(figure, Boolean(measured.geo && measured.geo.lines.length)); if (fresh && motion) motion.redrawn(); } + // The text variant (DECISIONS 306, 1.2): the art where its widest line fits the block (the diagram-text module's), the transcript otherwise; in the + // viewer, the art at its own width (9.3). Written before the entrance reads it (its art is its lines) and before the viewer reads the figure's size. + var hadArt = model.text ? figure.querySelector('.diagram-text[data-art]') : null; + if (model.text && typeof _.diagramText === 'function') _.diagramText(figure, model, spec, viewer); + var art = model.text ? figure.querySelector('.diagram-text[data-art]') : null; + if (animated && measured.tokens) { entranceDrawn(figure, Boolean(measured.geo && measured.geo.lines.length) || Boolean(art)); if ((fresh || art !== hadArt) && motion) motion.redrawn(); } + if (viewer && viewer.onMeasured && measured.tokens) viewer.onMeasured(measured, figure); } function setState(next) { state = next; apply(state); } // A move of the roving stop touches the two nodes it moves between, not the whole figure. @@ -113,9 +208,10 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops var node = nodeOf(event.target); if (!node || event.defaultPrevented) return; settle(); - if (event.key === 'Escape') { if (focusTrace || hoverTrace) { event.preventDefault(); focusTrace = hoverTrace = null; retrace(); } return; } + // In the viewer Esc always closes the dialog, traced or not (DECISIONS 310, 9.8). + if (event.key === 'Escape') { if (!viewer && (focusTrace || hoverTrace || touchTrace)) { event.preventDefault(); focusTrace = hoverTrace = touchTrace = null; retrace(); } return; } if (!hasStops(model, state)) return; - var to = keyTarget(model, node.getAttribute('data-node'), event.key); + var to = keyTarget(model, node.getAttribute('data-node'), event.key, state.layout === 'drawn'); if (!to) return; event.preventDefault(); setStop(to); @@ -158,6 +254,7 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops figure.addEventListener('focusout', onFocusOut); figure.addEventListener('pointerover', onOver); figure.addEventListener('pointerleave', onLeave); + figure.addEventListener('click', onTap); if (toggle) toggle.addEventListener('click', onToggle); layout(); var width = figure.clientWidth, frame = 0, live = true; @@ -174,13 +271,21 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops var marks = model.nodes.some(function (n) { return n.mark; }); if (marks) forced.addEventListener('change', layout); if (animated) motion = _.diagramMotion(figure, { fig: figure, P: P, base: base, model: function () { return model; }, geo: function () { return measured && measured.geo; }, tokens: function () { return measured && measured.tokens; } }, spec); + // "Expand" and the viewer (DECISIONS 310) are the diagram-zoom module's: compose.mjs adds it to a page unless every figure on it says "zoom": false. + var zoom = !viewer && spec.zoom !== false && typeof _.diagramZoom === 'function' ? _.diagramZoom(figure, spec, { model: model, settle: settle, animated: animated }) : null; + // "Download SVG" and "Download PNG" (DECISIONS 306, 1.7) are the diagram-export module's, for a figure that says "export": true. + var exportFoot = figure.querySelector(':scope > .diagram-foot'); + var exports = !viewer && spec.export === true && exportFoot && typeof _.diagramExport === 'function' ? _.diagramExport(exportFoot, figure) : []; figure.__diagram = { stop: function () { + if (zoom) zoom.destroy(); + exports.forEach(function (b) { b.remove(); }); live = false; observer.disconnect(); cancelAnimationFrame(frame); if (marks) forced.removeEventListener('change', layout); if (motion) motion.destroy(); figure.removeEventListener('keydown', onKey); figure.removeEventListener('focusin', onFocusIn); figure.removeEventListener('focusout', onFocusOut); - figure.removeEventListener('pointerover', onOver); figure.removeEventListener('pointerleave', onLeave); + figure.removeEventListener('pointerover', onOver); figure.removeEventListener('pointerleave', onLeave); figure.removeEventListener('click', onTap); + if (clearBtn) clearBtn.remove(); if (toggle) toggle.removeEventListener('click', onToggle); }, layout: layout, @@ -207,6 +312,8 @@ import { applyTrace, buildModel, entranceDrawn, escapeHtml, figureTree, hasStops } _.diagramMarkup = markup; + // What the viewer (the diagram-zoom module) draws with: this module's engine, so that module holds no second copy of it. + _.diagramKit = { draw: draw, buildModel: buildModel, figureKey: figureKey, figureList: figureList, hintEntries: hintEntries, toHtml: toHtml, escapeHtml: escapeHtml, settleEntrance: settleEntrance, measureFigure: measureFigure }; B.diagram = function (figure, spec) { var d = figure.__diagram; var key = d && d.send ? sendless(spec) : null; diff --git a/tools/html-skill/src/sinks.allowed.json b/tools/html-skill/src/sinks.allowed.json index 43262508..2fa7cc2d 100644 --- a/tools/html-skill/src/sinks.allowed.json +++ b/tools/html-skill/src/sinks.allowed.json @@ -7,7 +7,9 @@ "modules/command-list.js": { "count": 2, "data": true, "takes": "the list's frame from its data-label, data-noun and data-placeholder, and a detail pane's string from the author's own detail function", "safe": "the attributes go through esc; a detail string is the author's code, not data" }, "modules/copy.js": { "count": 3, "data": false, "takes": "the button's own markup, and the copied or failed state's glyph and words", "safe": "markup the button already held, and constants" }, "modules/diagram-motion.js": { "count": 1, "data": false, "takes": "the pause button's check seat with the pause glyph", "safe": "constant markup and a drawing from the glyph set" }, - "modules/diagram.js": { "count": 3, "data": true, "takes": "a diagram's figure, its words and its ink, from the page's diagram JSON", "safe": "React's diagram engine (diagram-core.ts) writes them, escaping every text and attribute; a card's mark is a path compose.mjs read into a data: image" }, + "modules/diagram.js": { "count": 4, "data": true, "takes": "a diagram's figure, its words and its ink, from the page's diagram JSON, and its key hint", "safe": "React's diagram engine (diagram-core.ts) writes them, escaping every text and attribute; a card's mark is a path compose.mjs read into a data: image; the hint's keys and words are the engine's own, through escapeHtml" }, + "modules/diagram-text.js": { "count": 1, "data": true, "takes": "a text sequence's art or its transcript, from the page's diagram JSON", "safe": "the engine's textArt and transcript write them, every name, label and note through escapeHtml; the transcript is the figure's own markup read back" }, + "modules/diagram-zoom.js": { "count": 2, "data": true, "takes": "the viewer dialog's frame (its title, source and summary, its key and hint) and the figure's list, from the page's diagram JSON", "safe": "the title, source, summary and the hint's words go through esc; the key and the list are the engine's figureKey and figureList through toHtml, which escapes every text and attribute; ids are the module's own" }, "modules/filter.js": { "count": 1, "data": true, "takes": "its element helper's markup: the Clear button's word and the chip's glyphs", "safe": "constants only; the group's label and each value's label are set as textContent" }, "modules/framed-art.js": { "count": 1, "data": true, "takes": "the art's alt text, shown when the image fails", "safe": "the text goes through esc" }, "modules/glyph.js": { "count": 1, "data": false, "takes": "a core glyph's drawing", "safe": "drawings from the generated glyph set; the name picks one, it is never written" }, diff --git a/tools/html-skill/src/usage/diagram-export.md b/tools/html-skill/src/usage/diagram-export.md new file mode 100644 index 00000000..511d845a --- /dev/null +++ b/tools/html-skill/src/usage/diagram-export.md @@ -0,0 +1,6 @@ +# diagram-export + +Added for you when a diagram's JSON says `"export": true`. + +- The figure's foot gets "Download SVG" and "Download PNG", and so does its viewer's (the drawn layout at 100%, whatever the zoom). Each writes the figure in the theme shown: the title and source, the drawing and the key, at rest; native SVG with its words as text and the faces embedded; the PNG at 2x. +- Without `"export": true` there are no buttons and no module. Don't add your own. diff --git a/tools/html-skill/src/usage/diagram-motion.md b/tools/html-skill/src/usage/diagram-motion.md index 479364ef..efba91b7 100644 --- a/tools/html-skill/src/usage/diagram-motion.md +++ b/tools/html-skill/src/usage/diagram-motion.md @@ -5,5 +5,6 @@ Added for you when a diagram's JSON says `"motion": "animated"` (with `loops`); - **Entrance:** in view (two fifths of it), each line draws once in the author's order, inside five seconds; a sequence's arrows go in message order and each label lifts from secondary to primary. Every word is at rest from the first frame. It never plays under reduced motion, in forced colours, under the hold or in print, and settles at once on a hover, a focus, a key or a control. - **Loops:** a flow line's cuts, a pulse's bead, a repeating packet. They run only in view, never while a node is traced, and stop under the page's hold. The figure's foot then has "Pause animations" (the hold's own button, built for you) after "View as list". Don't add a second one for the diagram. - **One mover a figure:** a pulse or a packet, never both. Flow is a state of a line and never runs on a line the mover travels. +- **First visit:** `"entrance": "first-visit"` with an `id` on the figure plays the entrance once; later visits are at rest. A text sequence builds by ink instead, in view. - **Run:** "Play the run" sends one dot through a sequence's messages; it reads "Stop the run" while it runs. It works under the hold and under reduced motion (by colour alone). - `Basalt.diagram(figure, spec)` with a new `packet.send` value sends one message. diff --git a/tools/html-skill/src/usage/diagram-text.md b/tools/html-skill/src/usage/diagram-text.md new file mode 100644 index 00000000..fdc9beb4 --- /dev/null +++ b/tools/html-skill/src/usage/diagram-text.md @@ -0,0 +1,6 @@ +# diagram-text + +Added for you when a sequence's JSON says `"variant": "text"`. + +- The same data as box-drawing characters in a code block, where its widest line fits; elsewhere the transcript (one line a message), which the page holds before script. Nothing scrolls sideways, and the block is hidden from assistive technology: the title, the summary and "View as list" carry it. +- With `"motion": "animated"` it builds by ink: labels and arrows lift in message order, no line hidden, no caret. diff --git a/tools/html-skill/src/usage/diagram-zoom.md b/tools/html-skill/src/usage/diagram-zoom.md new file mode 100644 index 00000000..a6355aee --- /dev/null +++ b/tools/html-skill/src/usage/diagram-zoom.md @@ -0,0 +1,8 @@ +# diagram-zoom + +Added for you on a page with a diagram (with `dialog`, `dialog-form` and `sheet`), unless every figure's JSON says `"zoom": false`. + +- **Expand:** in the figure's foot after "View as list", once script runs. It opens the viewer: the drawn layout in a dialog (the window less 16px from 720, the whole window under it), even where the page shows the stack. +- **Zoom:** it opens at Fit (the whole drawing, 200% at most). "Zoom out", "Zoom in" and "Fit" in the foot; `+`, `-` and `0` with focus in the stage; Ctrl or Command with the wheel, a trackpad pinch and two fingers zoom about the pointer. From Fit or 100% to 400%. +- **Pan:** the stage scrolls both ways; a drag, one finger, the wheel or the arrow keys. A trace works; nothing animates. Esc closes it. +- Don't build a viewer of your own, and don't scale a figure on the page. diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index e50d6a93..eb31b43e 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -16,14 +16,15 @@ 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`). +- **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`; `cardinality: { "from", "to" }` on every foreign key or none draws crow's feet: `from` is `one`, `zero-or-one`, `one-or-many` or `zero-or-many`, `to` is `one` or `zero-or-one`). - **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 but a card's service mark. The drawn layout is used only where it fits; otherwise the figure is stacked, one column at most 480 wide. - **Motion:** `"motion": "animated"` (default still) draws each line once in view, every word at rest; it brings in `diagram-motion` (its usage says the rest). Motion never carries a fact alone. -- **Flow, pulse, packet:** `"flow": true` on a `main` or `plain` edge marches it (give it a label). `"pulse": ["a", "b", "c"]` runs a bead along a route; `"packet": { "path": [...], "repeat": true }` sends a dot. One of pulse and packet; never flow on the mover's route. Architecture and data flow only. +- **Flow, pulse, packet:** `"flow": true` on an edge marches it (a dashed line's own dashes) (give it a label). `"pulse": ["a", "b", "c"]` runs a bead along a route; `"packet": { "path": [...], "repeat": true }` sends a dot. One of pulse and packet; never flow on the mover's route. Architecture and data flow only. - **Run:** `"run": true` on a sequence adds "Play the run", a dot through every message. -- **Mark:** `"mark": "aws-ecs-service"` on an architecture node, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: ``. +- **Parts:** a group's `parent` (two levels); `href` (and `"target": "_blank"`) makes a card a link; a label's `"\n"` is its one break; a sequence's message `activate`/`deactivate` (a bar) and steps `{ "frame": "opt" | "loop", "label", "steps" }` or `{ "frame": "alt", "branches": [...] }`; `"variant": "text"` draws it as text art; `"layout": "auto"` places the cards for you (compose.mjs, at build time); `"entrance": "first-visit"` with an `id` plays the entrance once. +- **Mark:** `"mark": "aws-ecs-service"` on an architecture node, a data flow's step or a sequence's participant, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: ``. - **Marks:** `aws-*`, `azure-*`, `gcp-*`, `kubernetes`, `temporal`, `sonarqube`, `github`, `coderabbit`, `greptile`, `blacksmith`, `jenkins`, `servicenow`, `blazemeter`. `node .agent/skills/basalt-html/compose.mjs --marks [aws azure gcp ...]` prints each id with the words its card must say and which are unofficial; a database card (Aurora, RDS) takes `aws-database`. diff --git a/tools/html-skill/test/compose.test.mjs b/tools/html-skill/test/compose.test.mjs index e10596ac..23285edd 100644 --- a/tools/html-skill/test/compose.test.mjs +++ b/tools/html-skill/test/compose.test.mjs @@ -425,8 +425,9 @@ 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"); - // node:vm runs the diagram module's own script to write a figure's words into the page (DECISIONS 281, 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"]); + // node:vm runs the diagram module's own script to write a figure's words into the page (DECISIONS 281, 1.19); node:worker_threads runs the placer + // for an automatic diagram (DECISIONS 306, 1.8), whose elkjs resolves from the repository only when a page asks for one: 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", "node:worker_threads"]); assert.doesNotMatch(source, /\bfetch\(|https?\.request|node:(net|http|https|dns|child_process)/); }); }); diff --git a/tools/html-skill/test/diagram-motion.test.mjs b/tools/html-skill/test/diagram-motion.test.mjs index b1966e82..5445f351 100644 --- a/tools/html-skill/test/diagram-motion.test.mjs +++ b/tools/html-skill/test/diagram-motion.test.mjs @@ -25,7 +25,8 @@ describe("compose.mjs", () => { test("a still diagram brings in no motion module, no loops and no mark; an animated one brings both modules", () => { const still = compose(page([figure(STILL.architecture)])); assert.ok(!still.modules.includes("diagram-motion") && !still.modules.includes("loops")); - assert.ok(!still.html.includes("data:image/svg+xml,%3Csvg")); + // No service mark's rule (a link card's cue is a core glyph's mask in the stylesheet, DECISIONS 306, 1.4, and is not a mark). + assert.ok(!/\.diagram-node\[data-mark=/.test(still.html)); const moving = compose(page([figure(animated("dataFlow"))])); assert.ok(moving.modules.includes("diagram-motion") && moving.modules.includes("loops")); assert.match(moving.html, /]*data-motion="animated"/); diff --git a/tools/html-skill/test/diagrams.test.mjs b/tools/html-skill/test/diagrams.test.mjs index bf296f43..5924f940 100644 --- a/tools/html-skill/test/diagrams.test.mjs +++ b/tools/html-skill/test/diagrams.test.mjs @@ -218,3 +218,68 @@ describe("behaviour", () => { assert.match(js, /diagramMarkup/); }); }); + +describe("batch B's fix round in the skill (Neon B8, B10)", () => { + const B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); + test("an automatic figure's words are written on its placement before script: no two cards in one cell, and the columns are the placement's", () => { + const html = compose(`D
`).html; + const fig = /]*id="fig-a"[^>]*>/.exec(html)[0]; + assert.match(fig, /data-cols="(\d+)"/); + assert.notEqual(/data-cols="(\d+)"/.exec(fig)[1], "1"); + const cells = [...html.matchAll(/data-node="([^"]+)"[^>]*style="--_c:(\d+);--_r:(\d+)/g)].map((m) => `${m[2]},${m[3]}`); + assert.ok(cells.length >= 10, `${cells.length} cards`); + assert.equal(new Set(cells).size, cells.length, "no two cards in one cell"); + }); + test("a data flow step's mark counts its lane's label as its words, as React's check does", () => { + const spec = { type: "data-flow", title: "t", summary: "s", lanes: [{ id: "s3", label: "Amazon S3" }], nodes: [{ id: "n1", lane: "s3", col: 1, name: "Store logs", mark: "aws-s3-bucket" }], edges: [] }; + const out = compose(`D
`); + assert.ok(!JSON.stringify(out.diagrams ?? []).includes("none of its words say so"), JSON.stringify(out.diagrams)); + }); +}); + +// Batch B (Opus B12 on the re-check): the same comparison for the extended CIMIP figures (frames, activation bars, cardinality, far keys, groups two +// deep, the automatic layouts and the text sequence), React against the skill, in both themes at 1440 and 390. Written while browser tests are paused +// (DECISIONS 330): not run in the round that wrote it. +const DATA_B = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams-b.json"), "utf8")); +const KEYS_B = Object.keys(DATA_B).filter((k) => DATA_B[k]?.type); +const bodyB = (width = 1104) => `Diagrams B
${KEYS_B.map((k) => `
`).join("")}
`; +const REACT_B = ` +import data from "./test/fixtures/cimip-diagrams-b.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).filter(([, d]) => d && d.type).map(([key, d]) => { const X = C[d.type]; const { type, ...props } = d; return ; })}
; } +createRoot(document.getElementById("root")).render();`; +/** Waits until every figure has settled: at 1440 an automatic layout placed and drawn (no marker says it is still placing, so its drawn layout is the + * sign), and a text sequence's art or transcript written. */ +const settled = (p, prefix, width) => p.waitForFunction(({ prefix, width }) => [...document.querySelectorAll("figure[id^='fig-']")].every((f) => f.getAttribute("data-layout") && (width < 1440 || !/^fig-auto/.test(f.id) || f.getAttribute("data-layout") === "drawn") && (!f.querySelector(`.${prefix}-text`) || f.querySelector(`.${prefix}-text`).children.length)), { prefix, width }, { timeout: 20000 }); +const readB = async (p, key, prefix) => { + const fig = await read(p, key, prefix).catch(() => null); + const text = await p.evaluate(({ key, prefix }) => { const pre = document.querySelector(`#fig-${key} .${prefix}-text`); return pre ? { art: pre.hasAttribute("data-art"), html: pre.innerHTML.replaceAll(`${prefix}-`, "P-") } : null; }, { key, prefix }); + return { fig, text }; +}; + +describe("parity with React, batch B", () => { + for (const theme of ["dark", "light"]) for (const width of [1440, 390]) { + test(`${theme} at ${width}: batch B's figures have the same layout, ink, boxes, styles and text art`, async () => { + const { page: rp, errors: re } = await fixturePage(reactBrowser, REACT_B, { theme, viewport: { width, height: 1000 }, standards: true }); + await rp.addStyleTag({ content: `${FONTS} *, ::before, ::after { box-sizing: border-box; } body { margin: 0; background: var(--basalt-surface-0); color: var(--basalt-text-primary); font: var(--basalt-font-weight-regular) var(--basalt-text-base-size) / var(--basalt-text-base-line-height) var(--basalt-font-family-sans); } #root{display:block}` }); + await rp.evaluate(() => document.fonts.ready); + const skill = await openHtml(browser, compose(bodyB()).html, { scheme: theme, width }); + await settled(rp, "basalt-diagram", width); + await settled(skill.page, "diagram", width); + for (const key of KEYS_B) { + const a = await readB(rp, key, "basalt-diagram"); + const b = await readB(skill.page, key, "diagram"); + assert.deepEqual(b.text, a.text, `${key}: the text art`); + if (!a.fig) continue; + assert.equal(b.fig.layout, a.fig.layout, `${key}: layout`); + assert.deepEqual(b.fig.boxes, a.fig.boxes, `${key}: node boxes`); + assert.equal(b.fig.ink, a.fig.ink, `${key}: the ink`); + assert.deepEqual(b.fig.styles, a.fig.styles, `${key}: computed styles`); + } + assert.deepEqual(re, []); + assert.deepEqual(skill.errors, []); + await rp.close(); + await skill.context.close(); + }); + } +}); diff --git a/tools/html-skill/test/support-hostile.mjs b/tools/html-skill/test/support-hostile.mjs index 9a5f71c2..e2159553 100644 --- a/tools/html-skill/test/support-hostile.mjs +++ b/tools/html-skill/test/support-hostile.mjs @@ -11,6 +11,8 @@ const diagram = { type: "architecture", title: "D" + p(81), summary: "S" + p(82) groups: [{ id: "g" + a(87), label: "G" + p(88) }], nodes: [{ id: "a", kind: "K" + p(89), name: "A" + p(90), col: 1, row: 1, group: "g" + a(87) }, { id: "b", name: "B" + p(91), detail: "dt" + p(92), focal: true, col: 2, row: 1 }], edges: [{ from: "a", to: "b", kind: "main" }] }; +const textSequence = { type: "sequence", variant: "text", export: true, title: "TX" + p(93), source: "So" + p(94), summary: "Su" + p(95), legend: { main: "LM" + p(96) }, + participants: [{ id: "a", name: "PA" + p(97) }, { id: "b", name: "PB" + p(98) }], steps: [{ from: "a", to: "b", label: "Msg" + p(99), note: "Nt" + p(100) }, { frame: "opt", label: "Fr" + p(101), steps: [{ from: "b", to: "a", label: "Back" + p(102) }] }] }; export const hostileBody = () => `xss probe

Probe

@@ -18,6 +20,7 @@ export const hostileBody = () => `xss probe
+
diff --git a/tools/review/build.mjs b/tools/review/build.mjs index 6259de5c..c581fe65 100644 --- a/tools/review/build.mjs +++ b/tools/review/build.mjs @@ -12,6 +12,8 @@ import { execFileSync } from "node:child_process"; import fs from "node:fs"; + +import { withGlyphMasks } from "../../packages/react/glyph-mask.mjs"; import path from "node:path"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; @@ -32,6 +34,9 @@ const out = path.resolve(outAt >= 0 ? args[outAt + 1] : path.join(repo, ".review // --still: shoot with every transition and animation at zero length and every loop held, so two builds of the same code give the same pixels // (tools/review/pixel-proof.mjs compares them). It changes only the tooling's own clock: a shot of a mid-motion state is the end of that motion. const still = args.includes("--still"); +// --only a,b: shoot those steps alone (by id), into --out, keeping each step's number, so a re-shot picture has its round's name. +const onlyAt = args.indexOf("--only"); +const only = onlyAt >= 0 ? new Set(args[onlyAt + 1].split(",")) : null; // What a still takes out of a shot: the CSS transitions and animations (zero length); the JS glides, which read the duration tokens off the root (a number that rolls, a // line that travels to its new value: 1ms, not zero, because a glide divides by it); a text caret, which blinks; and then, just before the shot, whatever finite animation // is still running is finished, so a transition that began after the page loaded (a focus ring, a plate) is at its end and not near it. @@ -85,7 +90,7 @@ const untilQuiet = async (page, label) => { if (!done) { gateWarnings.push(label); console.warn(`${label}: the page still had timers pending after 10s; shot anyway`); } if (audit && before !== (await text())) console.log(`GATE CHANGED ${label}`); }; -const wanted = args.filter((a, i) => !a.startsWith("--") && (outAt < 0 || i !== outAt + 1)); +const wanted = args.filter((a, i) => !a.startsWith("--") && (outAt < 0 || i !== outAt + 1) && (onlyAt < 0 || i !== onlyAt + 1)); fs.mkdirSync(out, { recursive: true }); // ---- the page, once per round @@ -134,7 +139,8 @@ const css = [ // comes after `basalt` on purpose: it is where a round shows an option the owner has not decided ("Option, not // shipped"), scoped to a wrapper that says so. "@layer review, basalt, review-options;", - fs.readFileSync(path.join(reactPkg, "src/styles/components.css"), "utf8"), + // The source stylesheet, with its core-glyph masks written in, as the package's build writes them. + withGlyphMasks(fs.readFileSync(path.join(reactPkg, "src/styles/components.css"), "utf8")), // The accent classes are generated with the tokens; Badge's accent tone reads them. fs.readFileSync(path.join(repo, "packages/tokens/dist/css/accents.css"), "utf8"), `@layer review {\n${fs.readFileSync(path.join(here, "walkthrough.css"), "utf8")}\n}`, @@ -298,6 +304,7 @@ for (const id of rounds) { // Every step and state at the desktop width and at a phone's 390px, in both themes. let n = 1; for (const step of meta) { + if (only && !only.has(step.id)) { n++; continue; } for (const stateFull of ["default", ...step.states]) { // "name@1024" is a state shot at that one width. A step may also set `widths`, `scales` (1 for 1x, 2 for 2x) and `height`. const state = stateFull.split("@")[0]; @@ -311,7 +318,7 @@ for (const id of rounds) { // ends in one of them (an open menu "menu-forced-colours-lit") takes the same emulation, with or without "-lit". const mode = state.replace(/-lit$/, ""); const media = mode.endsWith("forced-colours") ? { forcedColors: "active", colorScheme: theme } : mode.endsWith("forced-mixed") ? { forcedColors: "active", colorScheme: theme === "dark" ? "light" : "dark" } : mode.endsWith("reduced-motion") ? { reducedMotion: "reduce" } : mode.endsWith("more-contrast") ? { contrast: "more" } : {}; - const page = await browser.newPage({ viewport: { width, height: step.height ?? (overlay ? 640 : 400) }, deviceScaleFactor: scale, hasTouch: state.startsWith("chart-touch") || state === "touch" || Boolean(step.touch && width < 720), isMobile: (id === "48" && state === "touch") || Boolean(step.touch && width < 720), ...media }); + const page = await browser.newPage({ viewport: { width, height: step.heights?.[`${state}@${width}`] ?? step.height ?? (overlay ? 640 : 400) }, deviceScaleFactor: scale, hasTouch: state.startsWith("chart-touch") || state === "touch" || Boolean(step.touch && width < 720), isMobile: (id === "48" && state === "touch") || Boolean(step.touch && width < 720), ...media }); page.on("pageerror", (e) => errors.push(`${step.id}/${state}/${theme}: ${e.message}`)); // Round 25's framed art: one address that never answers (the loading state, held) and one that is refused (the failed state). if (id === "25") { diff --git a/tools/review/round66.tsx b/tools/review/round66.tsx new file mode 100644 index 00000000..866b4f33 --- /dev/null +++ b/tools/review/round66.tsx @@ -0,0 +1,282 @@ +// Round 66: Basalt's diagrams, batch B (DECISIONS 301; the decision is 306, revised by 313, with part 9, the viewer, as 310). A heavy council round: two +// drafts and one check, decided by Fable, revised after the final positions. Part 9 (the viewer) is the owner's own addition and skipped three steps: no +// draft, no check and no seat's position; every value in it is the decider's alone. Built by Opus from the decision; the implementation has not been +// reviewed. The content is CIMIP's figures extended as each part needs (test/fixtures/cimip-diagrams-b.json), with automatic and text-art versions. + +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-b.json"; +import type { Round } from "./rounds"; +import { diagramToSvg } from "../../packages/react/src/diagram-export"; +import { awsEcsService } from "../../packages/react/src/marks/aws-ecs-service"; +import { awsEcsTask } from "../../packages/react/src/marks/aws-ecs-task"; +import { awsS3Bucket } from "../../packages/react/src/marks/aws-s3-bucket"; + +// Marks on a sequence's participants (DECISIONS 306, 1.6): the service and the sandbox, and none on Marcus, who is a person. +const PARTICIPANT_MARKS: Record = { svc: awsEcsService, agent: awsEcsTask }; + +type Key = keyof typeof data; +const isShot = () => new URLSearchParams(window.location.search).get("shot") === "1"; +const frames = (n: number) => new Promise((resolve) => { let k = 0; const step = () => (++k >= n ? resolve() : requestAnimationFrame(step)); requestAnimationFrame(step); }); + +/** A figure exported to SVG (diagram-export) and shown as the file, beside nothing else: what an app's own Download button would write. */ +function Exported({ k }: { k: Key }) { + const host = React.useRef(null); + const [url, setUrl] = React.useState(null); + React.useEffect(() => { + let ready: () => void = () => {}; + if (isShot()) (window as unknown as { __BASALT_READY__?: Promise }).__BASALT_READY__ = new Promise((resolve) => { ready = resolve; }); + (async () => { + await frames(8); + const fig = host.current?.querySelector("figure"); + if (!fig) return; + // The theme shown (the default), read when the shot has set it. + const blob = await diagramToSvg(fig); + setUrl(URL.createObjectURL(blob)); + await frames(4); + ready(); + })(); + }, []); + return ( +
+
+ {url ? : null} +
+ ); +} + +/** Figures the fixture does not hold, for the parts that had no picture (the pixel review's P5). */ +type Inline = { type: "architecture" | "data-flow" | "schema" } & Record; +const DATA_FLOW_PARTS: Inline = (() => { + const d = structuredClone(data.dataFlow) as unknown as Inline & { nodes: Array>; edges: Array> }; + // A mark on a step (1.6): the sealed segment, in the S3 lane, carries S3's own mark; the lane's label says S3. + for (const n of d.nodes) if (n.id === "seg") n.mark = awsS3Bucket; + // A dashed flow (1.5): the batch line's own dashes march. Two more lines make two cards entered by several end lines (1.3), seen stacked. + d.edges = [...d.edges.map((e) => (e.kind === "dashed" ? { ...e, flow: true } : e)), { from: "append", to: "seal", label: "window check" }, { from: "hear", to: "seg", label: "cursor sync" }]; + // Still, so the shot shows every line (an animated figure's lines wait until it comes into view); its flow marches where motion is asked for. + return { ...d, title: "How one message reaches everyone in the room (extended)", summary: `${String(d.summary)} Two more lines show several end lines entering one card when it is stacked.` }; +})(); +// The same data flow drawn, in lanes (the pixel re-check's N1): the step's mark and the dashed line, without the two lines that stack the extended one. +const DATA_FLOW_DRAWN: Inline = (() => { + const d = structuredClone(data.dataFlow) as unknown as Inline & { nodes: Array>; edges: Array> }; + for (const n of d.nodes) if (n.id === "seg") n.mark = awsS3Bucket; + d.edges = d.edges.map((e) => (e.kind === "dashed" ? { ...e, flow: true } : e)); + return { ...d, title: "How one message reaches everyone in the room (a step's mark, a dashed flow)" }; +})(); +const schemaTable = (name: string, row: number, refs: string[] = []) => ({ name, col: 1, row, columns: [{ name: "id", key: "PK" }, ...refs.map((r) => ({ name: `${r}_id`, key: "FK", references: `${r}.id` }))] }); +const CALL_2: Inline = { type: "schema", title: "One column: turn-backs beside each other take lanes (section 4, call 2)", summary: "b references c and c references a; their turn-backs run beside each other down the column's end side, so each takes a lane.", legend: { plain: "A foreign key" }, tables: [schemaTable("a", 1), schemaTable("b", 2, ["c"]), schemaTable("c", 3, ["a"])] }; +const CALL_3: Inline = { type: "architecture", title: "A card grows to hold its ports (section 4, call 3)", summary: "The coordinator's end side holds a straight line and two others, so it is 48 tall at every width.", legend: { main: "Request", plain: "Call" }, + nodes: [{ id: "a", name: "Incident response coordinator", col: 1, row: 2 }, { id: "b", name: "Queue", col: 2, row: 2 }, { id: "c", name: "Store", col: 2, row: 3 }, { id: "d", name: "Audit", col: 2, row: 4 }, { id: "e", name: "Search", col: 3, row: 2 }, { id: "f", name: "Mail", col: 4, row: 2 }], + edges: [{ from: "a", to: "b", kind: "main" }, { from: "a", to: "c", toSide: "left" }, { from: "a", to: "d", toSide: "left" }, { from: "b", to: "e" }, { from: "e", to: "f" }] }; +function InlineFigure({ spec }: { spec: Inline }) { + const { type, ...props } = spec; + const figure = type === "architecture" ? )} /> + : type === "data-flow" ? )} /> + : )} />; + return
{figure}
; +} + +/** A figure from the extended fixture. A "viewer" state opens its viewer (and "viewer-200" zooms to 200%) once it is drawn, for the shot. */ +function Diagram({ k, state }: { k: Key; state: string }) { + const host = React.useRef(null); + React.useEffect(() => { + if (!isShot() || !state.startsWith("viewer")) return; + let ready: () => void = () => {}; + (window as unknown as { __BASALT_READY__?: Promise }).__BASALT_READY__ = new Promise((resolve) => { ready = resolve; }); + (async () => { + await frames(6); + host.current?.querySelector(".basalt-diagram-expand")?.click(); + // Drawn (an automatic figure places itself first), or a text figure's art: whichever the viewer holds when it has settled. + for (let t = 0; t < 120 && !document.querySelector("dialog.basalt-diagram-viewer .basalt-diagram[data-layout='drawn'], dialog.basalt-diagram-viewer .basalt-diagram-text[data-art]"); t++) await frames(2); + await new Promise((r) => setTimeout(r, 400)); + if (state === "viewer-200") { + const level = () => Number(document.querySelector(".basalt-diagram-level > span")?.textContent?.replace("%", "") ?? 0); + for (let i = 0; i < 12 && level() < 200; i++) { document.querySelector('dialog.basalt-diagram-viewer button[aria-label="Zoom in"]')?.click(); await frames(2); } + } + await frames(4); + ready(); + })(); + }, [state]); + const { type, ...props } = structuredClone(data[k]) as unknown as { type: string } & Record; + if (type === "sequence") for (const p of props.participants as Array<{ id: string; mark?: unknown }>) if (PARTICIPANT_MARKS[p.id]) p.mark = PARTICIPANT_MARKS[p.id]; + const figure = (() => { + switch (type) { + case "architecture": return )} />; + case "flowchart": return )} />; + case "data-flow": return )} />; + case "sequence": return )} />; + default: return )} />; + } + })(); + return
{figure}
; +} + +const COMMON = [ + "Decided by the council (DECISIONS 306, revised by 313): the owner sees this PR before it merges. Built by Opus; the implementation has not been reviewed.", + "A figure that uses none of the new keys draws what it drew before, except the flowchart: a decision taller than wide is now a fit failure (section 4, call 1), so CIMIP's flowchart is stacked through 975 and drawn from 976.", +]; +const W = [1440, 390]; + +export const ROUND_66: Round = { + id: "66", + title: "Diagrams, batch B: the viewer, frames and activations, nested groups, link cards, two-line labels, spatial keys, text art, automatic layout, right to left and export (DECISIONS 306 and 310)", + summary: "Batch B, whole. The viewer (part 9, the owner's addition) opens any figure's drawn layout in a dialog to zoom and pan; the sequence gains activation bars and opt, loop and alt frames, and a text-art form; groups nest two deep; a card may be a link; an edge label may hold its author's break; the arrow keys move by the cards' columns and rows; a schema states how many and draws keys two columns away; automatic layout places a figure for you. Also: a trace on touch, an entrance on a first visit, flow on a dashed line, marks on steps and participants, right to left, export and print, and section 4's three calls. Fixed after both reviews and the spacing sweep (DECISIONS 326).", + reviewed: false, + steps: [ + { + id: "viewer", + name: "The viewer: Expand, Fit, zoom and pan", + intro: "\"Expand\" in every figure's foot opens the drawn layout in a dialog: the window less 16px from 720, the whole window under it. It opens at Fit; a phone gets the drawing its page cannot show.", + decisions: [ + "Part 9 skipped three steps: no draft, no check and no seat's position. Every value is the decider's alone (DECISIONS 310).", + "Laid out once at 100% in real CSS pixels and zoomed with one transform: never a viewBox, CSS zoom, a canvas or a picture. Fit is the whole drawing in the stage, 200% at most; the limits are Fit or 100% and 400%; steps 25 to 400 land at once.", + "Two deviations, for the owner: \"Expand\" is words only (Phosphor's ArrowsOutSimple cost every still figure 2.2 KB in six weights, and the core set draws no expand glyph), and the dialog is the form dialog's box on a native modal , as the HTML skill's is (Base UI's dialog in the viewer's chunk widened the Base UI chunk every component shares).", + "Under 100% the words are under 12px: an overview, with no size or contrast claim. Nothing moves in the viewer but a trace.", + ], + tryIt: ["Press Expand, then + and - (or Ctrl and the wheel, or pinch): the point under the pointer holds still. Drag to pan. 0 is Fit. Esc closes and focus returns to Expand.", "On a phone: two fingers zoom about their midpoint, one finger pans.", "These shots open the viewer by script, so the stage shows its keyboard focus ring (2px, drawn inside at −2). A mouse click or a tap opens it with no ring; the keyboard shows the ring, as decided."], + states: ["viewer", "viewer-200"], + widths: W, + scales: [2], + height: 900, + touch: true, + demo: ({ state }) => , + }, + { + id: "architecture", + name: "Architecture: nested groups, a link card and two-line labels", + intro: "\"Data & logs\" sits inside AWS: 16px inside it at the sides and 32 below its top, radius 8. The cimip service card is a link, with the arrow after its name. Two labels carry their author's break.", + decisions: [...COMMON, "A stacked group's label sits on a ground plate over the lines (1.3). Where a turn into the inner group's first card runs at the label's height, the line runs behind the plate: a visual question for the owner."], + tryIt: ["Hover the cimip service card: its name underlines and the arrow lifts. Tab to the figure and press the arrows: they move by the cards' columns and rows. Enter on the service follows its link."], + states: ["viewer"], + widths: W, + scales: [2], + height: 1600, + touch: true, + demo: ({ state }) => , + }, + { + id: "sequence", + name: "Sequence: activations and frames", + intro: "The service works from the mention to the end, the sandbox from its run to \"done\". An opt holds a loop, and an alt has two branches.", + decisions: [...COMMON, "A frame is structure, never a panel: no fill, no rim, no level; every word of it sits on a ground plate, so a lifeline or a bar stops either side of it. An activation bar is the vertical bar nearest the one the owner ruled out (item 8 of the decision)."], + tryIt: ["Open View as list: the frames are sub-headings (\"Only if: ...\", \"Otherwise: ...\") and messages keep their numbers."], + widths: W, + scales: [2], + height: 1800, + touch: true, + demo: ({ state }) => , + }, + { + id: "schema", + name: "Schema: cardinality, far keys and a link table", + intro: "Every foreign key states how many rows each end allows, so its dot and head give way to crow's-foot marks in the line's ink. approvals references incidents and users two columns away: the first runs along the margin above the first row, the second along the gap between rows 2 and 3, which grows to 40. The incidents table is a link.", + decisions: [ + ...COMMON, + "Cardinality (1.1): bars at 4 and 8, a foot from a point at 7.5, a ring centred at 10.5, every mark inside the 14px zone; the column gap is 60 where marks are drawn, and a marked gutter's lanes keep 18 from the tables (three at most).", + "Far keys (1.1): a corridor is a row gap clear of the tables between, or the margin above or below, the one nearest the middle of the two rows. A gap that carries one is space-10; a margin adds space-8. A line with no lane left is not drawn, and its row still writes the target.", + "Builder's readings where the decision is silent: a bar's 1px ink is the pixel that ends at its distance (so 3 to 4 for \"a bar at 4\"); two far lines to one key share a corridor lane; an interior corridor's two lanes take the order that crosses least.", + ], + tryIt: ["Hover approvals: its three lines, marks included, take the main ink and the rest dim. Narrow to 390: the stack draws no lines, and the key keeps the foreign key's arrow. Open View as list: decided_by reads \"zero or many approvals to zero or one users\"."], + widths: W, + scales: [2], + height: 1200, + touch: true, + demo: ({ state }) => , + }, + { + id: "auto", + name: "Automatic layout: elkjs places, Basalt draws", + intro: "The CIMIP architecture, flowchart and schema with layout=\"auto\" and no col or row: elkjs gives each card a column and a row, and Basalt sizes, routes and seats the figure as it does an authored one.", + decisions: [ + "elkjs (EPL-2.0 OR GPL-3.0-or-later, used under EPL-2.0) loads on demand here; an app that places at build time and passes placement ships none of it, and the HTML skill always places at build time.", + "After the decider's ruling (DECISIONS 322): a main line that skips a layer keeps a way (a second elk run, its cells left empty), network simplex places the main path straight, a decision's point that a line leaves takes no other line, and a turn-back needs a gutter. At 1104 the architecture draws laid down (4 by 6, all 11 lines and 10 labels, one crossing, cut), the flowchart laid down (3 by 7) and the schema laid down (3 by 5), as the ruling's proof drew them.", + "When neither direction draws, a development build says why, once, with each direction's reason. The viewer takes the placements the page loaded and the direction with the larger Fit in its stage.", + ], + tryIt: ["Narrow the window: under 640 nothing is loaded and the figure is stacked."], + widths: W, + scales: [2], + height: 3000, + touch: true, + states: ["viewer"], + demo: ({ state }) => <>, + }, + { + id: "text", + name: "A sequence as text art", + intro: "variant=\"text\": the same data as box-drawing characters, where its widest line fits; on a phone the transcript.", + decisions: [...COMMON, "No line-by-line reveal and no caret (item 1 for the owner): under motion=\"animated\" it builds by ink, as the drawn sequence does."], + tryIt: ["Select the art and copy it: the clipboard holds the art exactly.", "Expand: the viewer holds the art at its own width, never the transcript, on a phone too (the viewer shots)."], + states: ["viewer"], + widths: W, + scales: [2], + height: 2000, + heights: { "viewer@390": 844 }, + touch: true, + demo: ({ state }) => , + }, + { + id: "rtl", + name: "Right to left", + intro: "The architecture and the sequence in a right-to-left page: the figure mirrors, its words do not.", + decisions: ["Column 1 is at the right and the first participant at the right; named sides swap; the arrow keys stay physical. The stack is not mirrored (its rail is laid out on the left): drawn, with every line."], + tryIt: ["Tab into the architecture and press the arrows: they move where they point."], + widths: W, + scales: [2], + height: 2600, + touch: true, + demo: ({ state }) =>
, + }, + { + id: "export", + name: "Export: the file an app's Download button writes", + intro: "diagramToSvg on the extended architecture, shown as the SVG file it wrote: native SVG, words as text, the faces embedded, at rest.", + decisions: ["@srasyndicate/basalt/diagram-export is a module the app loads on demand and wires to its own button; a figure grows no control. The HTML skill's \"export\": true adds the two buttons."], + tryIt: ["Open the image in a new tab: it is an SVG whose words select as text."], + widths: [1440], + scales: [2], + height: 1100, + demo: () => , + }, + { + id: "print", + name: "Print: light and untraced", + intro: "The token CSS ends with a print block: any page printed from the dark theme prints in the light one, and a figure prints in its resting ink.", + decisions: ["The print theme is the whole package's, not the diagrams' alone (item 5 of the decision). An app that prints dark on purpose overrides it."], + tryIt: ["Print this page from the dark theme."], + states: ["print@1440"], + widths: [1440], + scales: [2], + height: 1200, + demo: ({ state }) => , + }, + { + id: "data-flow", + name: "Data flow: a step's mark, a dashed flow, and several end lines into one card", + intro: "The CIMIP data flow drawn in its lanes: the sealed segment, in the S3 lane, carries S3's mark, and the batch line is dashed and flows. Below it, the same data flow with two more lines: stacked, two cards are each entered by two end lines, which nest.", + decisions: [ + ...COMMON, + "A step's mark (1.6) is 16px in its top end corner; the lane's label counts as the step's words, so \"S3\" says what the mark stands for.", + "A dashed flow (1.5): one period every 625ms, the dashes where the key draws them whenever they rest. The figure here is still, so its lines show in the shot: with motion=\"animated\" the batch line's dashes march.", + "Several end lines into one card (1.3): the outermost lane's line turns lowest and enters nearest the end edge; each further in turns space-5 higher and enters space-3 further in; their labels sit space-2-5 clear of the innermost entry, each on its own turn's height.", + ], + tryIt: ["Narrow to 390: the two cards entered by two end lines show the nesting and the labels' seats."], + widths: W, + scales: [2], + height: 2600, + touch: true, + demo: () => <>, + }, + { + id: "calls", + name: "Section 4's calls 2 and 3: a one-column schema's lanes, and a card grown to hold its ports", + intro: "A one-column schema whose two turn-backs run beside each other takes two lanes in its end padding. A card whose side holds a straight line and two others grows to 48, so each port is on the flat part and 8 from the next, at every width.", + decisions: [...COMMON, "Call 2: lanes space-3 apart, nested, the padding space-5 then space-5 plus space-3. Call 3: the card is never shorter than its ports need, so a side never stacks the figure."], + tryIt: ["Narrow the window from 1440: the coordinator keeps its 48 while its name wraps and unwraps."], + widths: W, + scales: [2], + height: 900, + demo: () => <>, + }, + ], +}; diff --git a/tools/review/rounds.tsx b/tools/review/rounds.tsx index 544f0e2f..a3b5365a 100644 --- a/tools/review/rounds.tsx +++ b/tools/review/rounds.tsx @@ -131,6 +131,7 @@ import { ROUND_62 } from "./round62"; import { ROUND_63 } from "./round63"; import { ROUND_64 } from "./round64"; import { ROUND_65 } from "./round65"; +import { ROUND_66 } from "./round66"; import { ROUND_67 } from "./round67"; import { ROUND_68 } from "./round68"; @@ -151,6 +152,8 @@ export interface Step { scales?: number[]; /** The viewport height. Default 400, or 640 for an open state. */ height?: number; + /** The viewport's height for one state at one width, keyed "state@width" (a dialog shot at a phone's own height): it wins over `height`. */ + heights?: Record; /** Shot edge to edge, with none of the page's own padding, so a page specimen is the width the shot is named for (a layout round's row is then the real row). */ bleed?: boolean; /** Shoot widths under 720 as a phone: touch and mobile emulation (a coarse pointer, the 44px targets, focus by touch). */ @@ -703,6 +706,6 @@ ROUNDS.push(ROUND_62); ROUNDS.push(ROUND_63); ROUNDS.push(ROUND_64); ROUNDS.push(ROUND_65); -// Round 66 is left for diagram batch B (claude/diagrams-b), building beside this one. +ROUNDS.push(ROUND_66); ROUNDS.push(ROUND_67); ROUNDS.push(ROUND_68); diff --git a/tools/review/walkthrough.tsx b/tools/review/walkthrough.tsx index 3cfede75..b516bd5e 100644 --- a/tools/review/walkthrough.tsx +++ b/tools/review/walkthrough.tsx @@ -13,13 +13,13 @@ import { ROUNDS } from "./rounds"; declare global { interface Window { __BASALT_ROUND__: string; - __BASALT_STEPS__: Array<{ id: string; name: string; states: string[]; widths?: number[]; scales?: number[]; height?: number; touch?: boolean }>; + __BASALT_STEPS__: Array<{ id: string; name: string; states: string[]; widths?: number[]; scales?: number[]; height?: number; heights?: Record; touch?: boolean }>; } } const round = ROUNDS.find((r) => r.id === window.__BASALT_ROUND__)!; // for build.mjs: which steps and states to screenshot -window.__BASALT_STEPS__ = round.steps.map((s) => ({ id: s.id, name: s.name, states: s.states ?? [], widths: s.widths, scales: s.scales, height: s.height, touch: s.touch })); +window.__BASALT_STEPS__ = round.steps.map((s) => ({ id: s.id, name: s.name, states: s.states ?? [], widths: s.widths, scales: s.scales, height: s.height, heights: s.heights, touch: s.touch })); const params = new URLSearchParams(location.search); const shot = params.get("shot") === "1"; const initialTheme = params.get("theme") ?? (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");