diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index 42d20273..b2668f8f 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -9,10 +9,10 @@ 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`. Each usage names the modules it needs and the markup that adds it. `--usage` alone prints the index. -2. Write the **body** to a file: the HTML inside ``, with the classes the usage names. It may carry `` (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 (for a file only a tool reads), `--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. +1. Pick modules below and print their usage in one call, always with core: `node .agent/skills/basalt-html/compose.mjs --usage core table status callout`. Each usage names the modules it needs and the markup that adds it. `--usage` alone prints the index. +2. Write the **body** to a file: HTML inside `<body>`, using those classes. It may carry `<title>` (else first `<h1>`), `<style>`, and head tags: `<meta name="description">`, `og:`/`twitter:` meta, `<link rel="icon" href="data:…">` or `canonical` (others refused); 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). Adds doctype, meta, theme bootstrap, Geist inlined, core, used modules and quoted icons; prints what it added, one warning line for each module added. `--no-fonts` skips Geist (for a file only a tool reads), `--lang fr` sets language, `--all` adds all modules. +4. Open the page in both themes at 1440 and 390 wide before handing 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. @@ -96,20 +96,21 @@ Markup your script builds (a `.row`) isn't seen: add `<!-- basalt:use rows -->` - **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 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. +Your CSS goes in a body `<style>` (moved after Basalt's), with `--basalt-*` tokens only. Element selectors (`a`, `button`, `h1`) go in `@layer reset { }`, under any Basalt class; class rules can sit unlayered. Basalt's classes are in `@layer basalt`: any unlayered rule of yours wins without `!important`. Never restyle a Basalt class from an element rule. ## Rules -- **Monochrome.** Colour only in named roles: status (a dot or icon beside its word), a product's accent, syntax in code. Never decorative, never the only carrier of meaning. +- **Monochrome.** Colour only in named roles: status (a dot or icon beside its word), a product's accent, syntax in code. Never decorative or the only carrier of meaning. - **Type:** Geist and Geist Mono, weights 400, 500 and 600 only. Mono for identifiers, code, numbers in logs. -- **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. +- **Levels, rim, nesting.** A panel (`.panel`, `.card`, `.callout`, `.code`, `.table-wrap`) is its holder's level plus one (cap 3), with a 1px rim and no shadow. Level is position, not importance: a hero is level 1. Group by space and dividers first; a panel is for a distinct object; at most one panel deep. Only what leaves the flow (menu, popover, dialog) takes `.float` and a shadow. - **Keys.** No single-character shortcuts on the page (WCAG 2.1.4): a shortcut needs ⌘, ⌃ or ⌥. -- **Edges.** A ghost `.btn` that starts or ends a head takes `data-edge="start"` or `"end"`, never a hand margin. +- **Edges.** A ghost `.btn` starting or ending a head takes `data-edge="start"` or `"end"`, never a hand margin. - **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; add no colours). +- **Both themes, always.** WCAG 2.2 AA: 4.5:1 text, 3:1 boundaries, focus, 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. +- **390px wide** must work: no sideways scroll, touch targets 44px or more (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. +- **Diagram files** (`.drawio`, `.vsdx`, `.lucid`): never by hand; run diagram JSON through `basalt-diagram-export` (here `node packages/react/bin/basalt-diagram-export.mjs`). +- 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 are core glyphs (`data-glyph`), not icons. A script naming one writes it quoted (`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/parts/manifest.json b/.agent/skills/basalt-html/parts/manifest.json index fc6b29ca..47526262 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 <!-- basalt:use name --> comment, and when another module needs it (requires). Modules are added in the order listed here, which is the order of the source files' cascade. classes: every class the module's CSS styles (the test checks them against the CSS and against SKILL.md). budget: the most bytes its minified CSS and JS may reach together. budgets: skillMd (SKILL.md, the context an agent pays: never above what it was), core (the CSS and JS of every page). icons: Phosphor names the module's script draws itself. Raised in the first parity PR (the owner's \"bring up the parity\"): forms (the number-input, search-clear and file-input chrome), disclosure (the native details marker), status (the accent reader and the forced-colours badge border), spinner (a fixed 16px ring), and the new number, range and accent modules. skillMd rose 10555 to 10900 for the new rules (number field, native chrome, the braille rule, the accent). Raised in the second parity PR (popup rows, levels and the segment's pill): segment 1400 to 3700 (the shared sliding pill: its script, 1.5 KB, and its CSS with the pill's two fallbacks), rows 3600 to 4300 (#27's plate-in-a-row geometry, the plate per level, the glide's shared plate and the forced-colours lit row, net of the removed bar), palette 9400 to 11300 (the glide's script, 2.4 KB: it follows the lit row, travels on a pointer, snaps on a key, and fades in place on leaving). The art module (DECISIONS 101 and 104) is the token groups only some pages name, taken out of the core so the core stays under its cap: the chart roles and lengths, the art colours, the aspect ratios and the stage headroom, in both themes (2087 bytes at 2100; it grows only when a token of those groups is added). A page gets it when its body names one of them, a var() in its own style included. The every-module page has no cap of its own (owner, DECISIONS 79): each part is capped, and a page carries only the parts it uses. usage: the most bytes of a module's usage text (src/usage/NAME.md; core.usage for core.md), which compose.mjs --usage prints on demand. It is context an agent pays only for the modules its page uses, so it is capped per part as SKILL.md and the CSS and script are (DECISIONS 79 and 109). Each is set a little above what its text was when the usage moved out of SKILL.md (DECISIONS 109); raising one needs a reason in the PR, and a rise of 40 to 50% is the owner's. textWords: each text pattern said in words, which compose.mjs --usage prints instead of the regular expression (one for each entry of text, in order). builds: modules a module requires whose markup its script writes, so --usage prints a line saying so instead of their usage text (the palette builds its own rows and key chips). The council's clarity check of the usage texts (all three: not yet clear) raised eight caps because the texts gained what an agent had to guess: callout 200 to 700 (the icon and one wrapper div around the title and body as markup, the four status icons, the role React's Callout renders), palette 1100 to 1300 (an item shown whole, keys as an array, keywords), stats 450 to 800 (a snippet of the figures and of the dl), tabs 500 to 650 (the unselected panels), code 250 to 450 (the markup and what each token class means), segment 150 to 300 (a click does not switch it), progress 150 to 350 (the empty span that paints the fill), theme 250 to 400 (leave the button empty), and accent 250 to 300. Topbar went down, 700 to 500, as its build detail was cut. Raised in the usage PR (the council's clarity check): palette 11300 to 11450 (the module grew 11283 to 11448, +165, about 1.5%), for the guard that makes a string `keys` warn and draw no chip instead of throwing in `keys.filter`, which the palette's usage already promised. Round 2 of the clarity check: tabs 650 to 750 (the panel's top space shown in the snippet, and that the script selects a tab on click). Raised in the site-icons and status PR (skill-parity part A, DECISIONS 106 and 107): status 1650 to 1900 (the neutral, pending and running marks, the badge's real border, and the forced-colours disc, net of the red danger word it drops) and its usage 400 to 1000 (every status in words, the word alone, running, forced colours); rows 4300 to 4450 (the profile list's seat rule and the status parts on a lit row) and its usage 300 to 600 (the profile list, with the one mistake: never an empty element for the seat). New: the links module (2671 bytes: the social row, the new-tab arrow's CSS and the script that draws it; budget 2750) and its usage (1746 bytes; cap 1850), which carries the social link, the glyph set, icon only and the new tab. Dropping Regular halves icons.json. Added in the overlay PR (skill-parity-4, batch 7 step 2, DECISIONS 108): the shared plate leaves palette.js for a glide module (the palette, a menu and the notification centre all call it), so the palette's cap went down, 11450 to 9250, and rows 4450 to 3850 (the plate's CSS moved to glide); and the overlay layer comes in as seven modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: popover (the native popup shell), menu, dialog (the dialog and alert dialog), sheet (on every side, the top one the site header's narrow menu), tooltip, toast and notifications (the centre). skillMd is unchanged in its cap (the eight new index lines fit within it); the core is unchanged in bytes. Added in the figures and charts PR (skill-parity-5, batch 7 step 3, DECISIONS 108): four modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: meter (React's Meter, CSS only, 2581 bytes), dlist (the description list, CSS only, 1265), terminal (the code block's transcript: its CSS, 3242, and the script that draws the gutter, the copy button and the replay, 4824) and chart (React's TimeChart and ChartGroup: 7313 of CSS and 23262 of script, which port chart.tsx's scale, layout, lane, labels, sentences, keyboard and table; it needs the art tokens, the table and the kbd chips, and a page without a chart carries none of it). Stats grew for the source line (budget 700 to 850, 798 bytes; its usage 800 to 950, 675 to 899 bytes, +33%, under the owner's 40 to 50%). skillMd is unchanged in its cap (four index lines fit within it); the core is unchanged in bytes. Added in the forms and selection PR (skill-parity-6, batch 7 step 4, DECISIONS 108): six modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: select (React's Select: the native select's closed trigger in every browser and, where `appearance: base-select` is shipped, the styled list with its two-line rows; a small script that says which input lit a row, 7740 bytes before it, choice (Checkbox, Radio, RadioGroup and Switch as styled native inputs; CSS only, with the first-frame rule), choice-card (ChoiceCard; CSS only), toggle (the pressed toggle's plate and check seat on .btn; CSS only), selection (a table's checkbox column: its fixed width and the script that sets aria-selected, the mixed header box and the count) and loops (the page-level hold on every loop with its switch: the held look and the script that stores it). The select's styles left forms, whose budget fell 3650 to 3250. skillMd rose 8621 to the size of its six new index lines, within its cap; the core is unchanged in bytes; compose adds the stored-hold line to the head of a page that has the loops module. Revised in the same PR (the lead's review of the build): the select gains select.js (one row is lit at a time, by whichever of the pointer and the keys moved last), and choice, toggle, selection and loops carry the first-frame rule, so a state a script sets on load (a mixed header box, the stored hold) paints at once with no crossfade. Added in the navigation and layout PR (skill-parity-7, batch 7 step 5, DECISIONS 108): five modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: glyph (Basalt's core glyphs drawn by name, at rest and selected, from a table the build works out from the drawn set; a page carries only the glyphs it names, and the drawing of a core glyph from data-glyph left the sheet module, which draws none now), nav (React's Nav: the sidebar's, the narrow menu's and More's rows, with the shared hugging pill), topbar-nav (the site header's links, one action and narrow menu, built by script from the bar's markup), app-shell (the shell, its sidebar and rail, and the app header) and tab-bar (the phone tab bar). The topbar module became the site header's bar (React's SiteHeader, DECISIONS 108: 56px with its line inside, the 44 by 44 brand target, the narrow-screen buttons, the derived sticky offset), budget 1600 to 3200 because its rules gained the app header's shared smoke, and its usage 500 to 750 (+50%) for the lockup's markup (the links, action and menu are topbar-nav's usage). Glide 3700 to 3950: the navigation's pill is a shape inside the row that the plate follows (about 200 bytes). The core's usage 2000 to 2100 (+5%): h2 is the Section step, the prose column's measure, and a link already 44px tall needs no margin. skillMd rose 9317 to 9863 for five index lines, under its cap; the core CSS grew 38 bytes (the layout tokens replace raw lengths, the gutter is one derived property, h2, .prose and .lead follow foundations) and the core script is unchanged. A module's media query writes %bp-md%, %bp-lg% or %bp-container% and the build substitutes the breakpoint tokens. Added in the tables and filters PR (skill-parity-8, batch 7 step 6, DECISIONS 108): the existing table module gains React's table additions (DECISIONS 95: the row header, \"Not observed\", the row density and the scroll hint with its small script), budget 1400 to 3000 (it was 1134 bytes of CSS; it is 2168 of CSS and 693 of script) and its usage 700 to 950 (+36%); and two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: still-table (React's Table with `columns`: the fixed layout from a colgroup, the whole header cell as the sort button with its reserved seat, aria-sort, the pinned columns and their divider, the empty row; 4767 of CSS and 3264 of script, budget 8200) and filter (React's MultiSelect and FilterResult: the chips, the trigger and checklist with the search band from ten values, Clear held in place, the one debounced result line, and the narrowing of a table by `data-column`; 8240 of CSS and 7978 of script, budget 16400; it needs the popover, glide, glyph and choice modules). The core is unchanged in bytes. skillMd rose 9863 to 10128 for two index lines and the CaretUpDown icon's name, within its cap. Added in the commands PR (skill-parity-9, batch 7 step 7, DECISIONS 103 and 108): one new module a page carries only when it uses it, command-list (React's CommandList: the command panel set in the page, list plus preview, the push; it extends the palette and needs rows, kbd and glide; 5229 of CSS and 8734 of script, budget 14000, usage 2150). Two-line rows come to the existing modules: rows 3850 to 5350 (the described row's grid and description line, the push's chevron: 1481 bytes of CSS, the same rules React's menu rows carry), palette 9250 to 9900 (its rows are one function the list shares, with the description and the two-tier ranking of title matches over keyword and description matches; +636) and its usage 1300 to 1350, rows' usage 600 to 800, and glide 3950 to 4000 (a host that is idle counts as having no lit row, +54). skillMd rose 10128 to 10259 for one index line, within its cap; the core's CSS grew 24 bytes (.split.aside takes size-list-width in place of its raw 20rem: the same 320px, so no pixel moves) and the core script is unchanged. Added in the art PR (skill-parity-10, batch 7 step 8, DECISIONS 104 and 108): two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: stage (React's Stage and PairedArt: full-bleed art under the site header, the pull-up by the sticky offset, the headroom, the paired art that follows the page's theme, and the forced-colours and print rules; CSS only, 1179 bytes) and framed-art (React's FramedArt: the figure, its rim and radius, the reserved box, the placeholder and the failed alt, the caption and credit; 2208 bytes of CSS and the 733-byte script that sets the frame's phase); both need the art tokens. The bar stays smoked over a stage: React clears it only over a stage that passed the headroom test helper, and a page has no test run (DECISIONS 108's note), so the skill builds no clear state. skillMd rose 10259 to 10500 for two index lines, within its cap; the core is unchanged in bytes. The callout gained the status rim in the same PR (DECISIONS 82, D8's status callouts): success, warning and danger draw their border in the status colour at 45% mixed in sRGB over the callout's own level, one solid colour on every side, and CanvasText in forced colours with the icon; the status colour is now one property the icon and the rim read. Its budget rose 900 to 1150 (the module is 1089 bytes, from 792: +297, about 37%); its usage is unchanged. Added in the overlays-and-the-rest PR (skill-parity-11, batch 7 step 9, DECISIONS 90 and 108): the last two parts of D8's part 5, each a module a page carries only when it uses it, with its own cap and usage cap set a little above its size: combobox (React's Combobox: the input with its caret button inside, the popup of the menu's rows with the glide's shared plate and two-line options, the filtering, the keys, the hidden value, the empty message and the check; 4342 of CSS and 6423 of script, budget 10900, usage 2150; it needs forms, popover and glide, and builds the last two) and sparkline (React's Sparkline: the label and latest value, the line, the axis, the empty sentence and the loading line that breathes; 1609 of CSS and 1874 of script, budget 3600, usage 950). The combobox copies the menu's row rules, as the select's list does, because React's Combobox renders MenuItem rows (a 40px hit area, a 36px plate) and the skill's .row is the palette's 44px: it carries no menu script. popover.js gains the combobox popup in the list of popups that keep focus where it is (+21 bytes, within its cap). skillMd rose 10500 to 10724 for two index lines, within its cap; the core is unchanged in bytes. Added in the motion-rules PR (DECISIONS 136 and 139): one module, ambient (a page's one ambient loop: CSS 828 bytes, script 433, budget 1300, usage 800), taken out of loops so the hold's own module grows only by the icon toggle's glyph swap (loops 2000 to 2200, +10%; its usage 1300 to 1650 for the icon form and the new settings-row sentence, +27%); and the chart's entrance (`entrance: true`: the marks' animations, their conditions and the redraw that restarts them at the elapsed time, 23262 to 25299 bytes of script; budget 30700 to 32800, +7%, usage 2500 to 2950, +18%). The core grew by the three tokens (27704 to 27862 bytes of CSS, under its cap). its stage usage gained the ambient art's line (1650 to 1750, +6%). skillMd rose 10724 to the size of the ambient index line, within its cap. Raised again in the motion-rules amendment (DECISIONS 143): chart 32800 to 33800 (script 25299 to 26375 bytes, +4%; +10% over the 30700 it began with) for the glide a new data set makes mid-entrance, print settling it, and `Basalt.pageChange()`; its usage 2950 to 3150 (+26% over the 2500 it began with). Raised in the second motion-rules amendment (DECISIONS 148): chart 33800 to 34400 (script 26375 to 26970 bytes: a line and its markers glide from their drawn geometry, and `beforeprint` settles the entrance; +12% over the 30700 it began with); topbar-nav 6900 to 7500 (+8.7%: the narrow menu's pause row, its CSS and 275 bytes of script, DECISIONS 148 item 2); loops usage 1650 to 1800 (+38% over the 1300 it began with, for the icon form's `title` and the menu row). Raised in the audit-design-b PR (DECISIONS 138 and 139): still-table 8200 to 13400 (+63%: the module was 7927 bytes and is 13311; the cut cell's plate, its focus stops and its dismissal, ported from React's cell-peek.ts, are 4273 bytes of script and 1111 of CSS; a still table that truncates needs them). The same PR: core usage 2100 to 2250 (+7%: the skip link, one bullet), forms usage 350 to 480 (+37%: the required mark), still-table usage 1950 to 2150 (+10%: the cut cell and the width rule), notifications usage 1050 to 1100 (+5%: the 44px entry on touch). The skip link's rim and radius took the core 30457 to 30609 bytes, under its cap (the rules that hang it under the bar are the topbar module's: 3200 to 3600, +12.5%); core 30720 to 31050 (+1.1%, DECISIONS 147: also the bar's links left out of the rule: the pseudo-element that makes a short standalone link a 44 by 44 target), skip-link script in the topbar module (3200 to 4150 over this PR, +30%: the rules that hang the link under the bar, 3600, and the script that reads the bar's real edge, 4150), sparkline 3600 to 4050 (+12.5%: React's ticker structure, so the value copies once on its line, and in forced colours the strips go and the number is plain text), forms budget 3250 to 3500 (+7.7%: the necessity word), notifications 9050 to 9250 (+2.2%: the 44px entry). Raised in the audit-design-b PR's E2 port (DECISIONS 138 and 139: the core set draws check, close, the chevrons, copy, plus, minus and search wherever a component draws them): the modules that drew a Phosphor icon for one of those now carry the core glyph's whole SVG, written in at build time (`%glyph-svg:name%`, the markup the glyph module's `_.glyph(name)` returns, so no module needs the glyph module and a page pays for nothing it does not use), and the Phosphor path of the same icon leaves the page. Each module's own bytes rose by that markup, and a page's total moved by what the Phosphor path it no longer carries saves: menu 8600 to 8900 (+303), combobox 10900 to 11200 (+303), copy 1900 to 2400 (+640), terminal 8100 to 8850 (+761), toast 13850 to 14150 (+325), number 2900 to 3400 (+557), filter 16400 to 17050 (+785), palette 9900 to 10450 (+536); the command list shares the palette's search drawing and fell 20 bytes. Set in integration-nov15, where the type-layout, motion-rules and audit-design-b branches meet: the combined tree measured SKILL.md 10959 bytes (each side's cap was 10900: both added index lines), core 31192 bytes (caps 30720 and 31050: the page-row and display rules, the three motion tokens and the skip link and 44px target rules all land in the core CSS) and core usage 2348 bytes (caps 2300 and 2250: type-layout's line and the skip-link bullet), so each is set to the measured bytes rounded up to the next 50: skillMd 10900 to 11000, core 31050 to 31200, core usage 2300 to 2350. Raised in the audit-design PR (decisions 138 and 139, parts A, D and C11): core 30720 to 31600 (+2.9%: the more-contrast block and its three aliases, and the field boundary token, every page carries as React does; the shadow-pill token is gone; the script gained `reserve`, 240 bytes), segment 3700 to 4100 and tabs 2300 to 2700 (the chosen label is 600 against 400, its width reserved by a span that carries its own copy, drawn unseen at 600; the pill's drop shadow is gone), and the segment's usage 300 to 380 (the weight and the glyph-only button). Raised again in the audit-design-a amendment (decision 145): core 31600 to 32300 (reserve() also reserves a label that is not plain text), segment 4100 to 5100 and tabs 2700 to 3500 (the second copy of such a label, and an icon drawn in both its forms), glyph 1100 to 1300 (a glyph in a segment or tab is drawn in both forms). Raised in the second audit-design-a amendment (decision 149): core 32300 to 32800 (reserve() builds the second copy of a label without any id, name, reference or hidden control, and does not copy a frame or media), segment 5100 to 5400 and its usage 380 to 500 (the 600 is on the label, the one-line rule and the usage text); the still-table cap is back at 8200, as the wash is on every cell again. Return 3 of the audit-design-a build (decision 149): tabs 3500 to 3700 (a tab the script has not reserved is 600 itself when selected, and one it declined is marked; the same two lines are in segment, which stays under 5400). Raised in the audit-fix-c2 PR (engineering, no pixel changes): toast 13850 to 14350 (the module was 13789 bytes and is 14288, +499, 3.6%) for F6, which focuses the Notifications region and Shift+Tab or Escape from it (or from the first toast) leaves it for where focus came from (and keeps a dialog's focus trap from wrapping it), as Base UI's viewport does in React, and for placing the region from focus (in the modal that holds it, or in the body), so a toast is never under a backdrop or in an inert modal whatever order the modals opened in (A3-09); the palette module grew 9864 to 9897 of its 9900 so that a palette opened over a modal sits inside it; topbar 3200 to 3250 (3123 to 3233, +110) for the scroll margin on what the bar holds, so a Tab into the bar from a scrolled page does not scroll the page (React's rule from PR #66); stage usage 1650 to 1750 (1580 to 1713, +8%) for the art's new place in the markup, after the content (A1-09), the stage's own CSS rising 1179 to 1208 within its 1250. skillMd rose 10724 to 10876 for the sentence that says a body may carry head tags, within its 10900. compose.mjs, the tool an agent runs, has no cap here (it is never in a page): it grew 21673 to 38153 bytes for the tokenizer that reads a body as HTML does and the head tags. Raised in the site-parts PR (DECISIONS 146, round 39), which folds each new part into the module it belongs with, so SKILL.md gains no index line (it has 41 bytes under its cap and a new module needs about 100): topbar 4150 to 17600 (+13450: the site footer and its disclosures, the lockup by pixel density, and a bar that arrives or leaves and returns, with its observer; a page that has a .topbar and no footer carries them too: the alternative, a module for each, needs its own index line and so SKILL.md bytes) and its usage 950 to 2900 (the footer's markup, the lockup's and the phase's); theme 650 to 4550 (the three-word theme choice: its CSS 2230 bytes and its script, 2277, with arrows, storage and the system listener) and its usage 400 to 1150 (the choice's markup written in full, so the right word is chosen before any script); segment 3700 to 3800 (a radio group's checked state besides a pressed button); stage 1250 to 2150 (its first script, 768 bytes, for fit and anchor) and its usage 1750 to 2000; framed-art 3000 to 3900 (drawn art in the frame: fit, anchor, no scaling strokes) and its usage 1250 to 1400. SKILL.md rose 10959 to 10992 (the topbar and theme index lines name .site-footer and .theme-choice). The head's theme line also writes data-theme-choice. Raised in site-parts return 2 (DECISIONS 146 B1 and B4): theme 4550 to 5350 (+800: the icon form of the theme choice, [data-theme-menu], whose button shows the theme in use, is named for the choice and opens the page's own .menu of three radio rows, in the theme script's 3073 bytes; the menu and popover modules are the page's, brought by its markup, so no module line was added and SKILL.md is 10993 of 11000) and its usage 1150 to 2200 (+91%: the menu's markup is written in full, and the deprecated toggle is said once); app-shell usage 2000 to 2100 and topbar-nav usage 1900 to 1950 (the theme control leaves the bar's text; the tools and the end cluster come in). The two example bodies still carry the deprecated data-theme-toggle. Return 2, F3 (DECISIONS 146 F): stage 2150 to 2250 (script 842 bytes: slice is the stage's default, as a frame's, and a drawing's own preserveAspectRatio stands unless the stage names data-fit or data-anchor) and its usage 2000 to 2150. framed-art 3900 to 4000 (a drawing's own preserveAspectRatio stands unless the figure names data-fit or data-anchor, +101 bytes). Return 3: theme 5350 to 5900 (script +569 bytes: who wrote data-theme, so System follows the system's change live and a theme the page set by hand, or a .dark or .light root, survives it). Raised in the controls port (DECISIONS 154): skillMd 11000 to 11200 for two index lines (link-tabs and option-chips, 214 bytes together), and core 31200 to 31600 for the nine tokens the port adds to every page's token CSS (the control rungs 44 to 64, two container widths, the confirm hold and the amount's opacity, 311 bytes). New modules (DECISIONS 154): link-tabs 2700 (its sizes, the 640 container step, the forced-colours underline, and the select that replaces the row under 720 with its 590-byte script, A15; it requires the select module), option-chips 5700 (the chip's states each written for a native radio inside a label, which needs :has on every one, plus the 1 KB script that keeps an aria-disabled chip reachable and never chosen). Return 3 (DECISIONS 154 conformance): link-tabs 2700 to 3100 and its usage 1650 to 1850 (the select's height for each row size, and a script that reads aria-current when it is needed and watches it move: 3,048 bytes), option-chips 5700 to 6700 (each state written twice, as a state attribute and as :has(), so no browser needs :has(): 4,975 CSS and 1,623 script). Return 4 (DECISIONS 158, Q2): link-tabs 3100 to 4300 and its usage 1850 to 2400 (the \"Go to\" label drawn at the select's start with its measured clearance, the select's accessible name kept as the words and the chosen page's, and the key hold that keeps a letter or an arrow on the closed select from navigating: 4,174 bytes, CSS 2,951 and script 1,223). Raised in the links-and-rows port (DECISIONS 152; the owner's approval is the lead's to confirm): the new link-rows module (5050 bytes of CSS, 50 of them for Castle's big-row arrow stepping colour over duration-fast, return 1, 1500 of usage: the directory's and the big rows' CSS, whose arrow is a core glyph drawn as a mask, and their tokens, size-row taken out of the core like type-layout's), disclosure 1550 to 3500 (Show all: the track, the clip and the settle, 1.5 KB of script and 1.8 KB of CSS), copy 2400 to 3500 (the form with words: the one cell and its script). SKILL.md rose 10959 to 10997 for one line, within its 11000 cap. Raised in the charts port PR (DECISIONS 153, D7a): chart 34400 to 34650 (script 26970 to 27270 bytes, +1.1% on the 34283 it was: `Basalt.trailingMean`, the trend maths React exports as `trailingMean`, 300 bytes), its usage 3150 to 3350 (+6%: one line for it). The tokens the batch adds (chart-lit-top, -mid and -base in both themes, size-chart-plot-sm, size-chart-row, size-meter-marker and radius-2xs) took the art module 2087 to 2546 bytes (budget 2100 to 2600, +24%: the chart tokens are its group) and the core 31192 to 31250 (cap 31200 to 31300, +0.3%: radius-2xs). Only D7a names a skill module in the charts ballot; the lit marks, the headline frame, the phase chart, the share bar, the coverage strip, the marks row and the range meter are React-only in this batch. Added in the overlays-and-search PR (DECISIONS 155, D10b and D13a): the sheet gains React's head, body and foot (the 44px close, the 20/28 title over a 13px count, the divider and the safe areas; its CSS 3.6 to 5.2 KB, budget 4050 to 5250, +30%) and its usage 1050 to 1450 (+38%: the anatomy and the step's focus, two bullets); and one new module a page carries only when it uses it, search (React's SearchDialog: the form, the field's -2 outline, the count line, the fixed-height results area and the rows with their picture slots and full-bleed hover wash; CSS only, 4368 bytes, budget 4400, usage 2050; it requires the dialog). The dialog's title draws no ring when script focuses it. skillMd rose 10959 to 11079 for the search line (the sheet's line is unchanged: its usage carries the anatomy), so its cap rose 11000 to 11100 (+0.9%). The core's CSS grew 31192 to 31421 bytes for the six new size tokens (the wide dialog, the search trigger and the logo and picture slots of a search result): its cap rose 31200 to 31450 (+0.8%). The two 44px values (the sheet's close and the search field) are local to their modules, with a lint exception that says they join the controls batch's size token (DECISIONS 154). Set in integration-nov15b, where audit-design-a, audit-fix-c2, site-parts, port-controls, port-links-rows, port-charts and port-overlays-search meet: the combined tree measured SKILL.md 11560 bytes (the caps were 11000, 11100 and 11200: each side added index lines), core 34086 bytes (caps 31300 to 33550: every side's rules land in the core CSS and script), topbar 17660 (17600 from site-parts, plus audit-fix-c2's skip-link and focus work), number 3453 (3400), palette 11379 (11000, audit-fix-c2's hosted scrim plus the core search glyph), dialog 5120 (5100), toast 15692 (15400) and stage usage 2248 (2150), each over every side's cap, so each is set to the measured bytes rounded up to the next 50: skillMd 11200 to 11600, core 33550 to 34100, topbar 17600 to 17700, number 3400 to 3500, palette 11000 to 11400, dialog 5100 to 5150, toast 15400 to 15700, stage usage 2150 to 2250. The segment cap is the base's 5400 plus port-controls' 100 (5500), unchanged by the merge. Raised in integration-nov15b, join 2 (a link tab takes the selected state, DECISIONS 138 A, 145, 149 and 154's D12 row): link-tabs 4300 to 5750 (+34%: the module was 4174 bytes and is 5736; the 600 against 400, the reserved width and the second copy of a composed label, an icon drawn in both its forms, the same rules a tab carries, 1,530 bytes of CSS and script) and its usage 2400 to 2550 (+6%: one bullet). The cap is the measured bytes rounded up to the next 50; a module that needs the tab's rules carries them as the segment and tabs modules do, so a page without link tabs pays nothing. Raised in the panels, art and parts port (DECISIONS 162): table 3000 to 3150 and its usage 950 to 1450 (the flat form and the two-line cell), stage 2250 to 2600 and its usage 2250 to 3100 (the closing block: its held art, forced colours and print; its section gap is type-layout's --basalt-section-gap, which a page with data-closing brings), the new app-tile 4300 (a 120-point polygon clip and the hairline's mask of the same outline), captioned 2000 and period 1400; skillMd 11600 to 11950 for one index line each for captioned, app-tile and period (358 bytes; the file is 11918). Raised in the logs, status and forms port (DECISIONS 162): core 34100 to 34200 (the new size-field-label-inline token, 80px, is written into every page's tokens: 25 bytes); dlist 1300 to 1900 and its usage 950 to 1060 (the stacked form, R9 and R10: a title over its text, 20px between entries, no divider; one usage line). Raised in audit-fix-c6 (the owner's cap, raised by the builder and for the owner to confirm): glyph 1300 to 1900, for redrawing a glyph when its ancestor's aria-current or data-current moves (the lists that hold glyphs are watched). Raised in the colour-ink-ladder build (DECISIONS 166): core 34200 to 34350 (the four lifted dark inks are four new primitives, each written into every page's tokens: the core measured 34307). Raised in the audit-2-design build (DECISIONS 167, Q7a): disclosure 3500 to 3800 (the core chevron drawn as a mask in place of two borders: the module measured 3755). Joined in the integration of c7 (#86) and c10 (#91): option-chips 6750 to 6850 (c7's reset resync and c10's data-ready together measure 6839). Raised in table-sort-3 (DECISIONS 257 and 261, the owner's pick: three sort states, the arrow after the label, explainers on column titles): still-table 13400 to 14650 (+9.3%: the module was 13343 bytes and is 14602; the end-aligned label's move by a transform, its right-to-left sign and the indicator that waits for it on a fine pointer, 912 bytes of CSS; the third state, the sort from the table's own order and a .explainer kept out of the button, 347 bytes of script) and its usage 2150 to 2250 (2197: the third state and the own order); the new explainer module 5850 (5842: a manual native popover opened from the sort button on hover, keyboard focus and a long press, placed above the header or beside it, 1752 bytes of CSS and 4090 of script; a page without explainers pays nothing) and its usage 900; skillMd 12250 to 12400 for the explainer's index line (113 bytes; the file is 12352). Each cap is the measured bytes rounded up to the next 50. Raised in table-sort-3's fix pass (Astra's review): explainer 5850 to 6900 (+18%: 5842 to 6864 bytes; the gap between the header and the card kept while a pointer crosses it, the close when its header leaves the view whatever has focus, the dismissal held until pointer and focus have both left, and its page-wide listeners and timers scoped to an open card and stopped when the table leaves the page, 1,022 bytes of script). 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. The fix round after both reviews of 421348e8 sets them to the measured sizes again: core 38950 to 39600 (every room says all three forms, and a hung word's box grows by a short room's shortfall), search to 5700 (it places its top again on a resize and with the keyboard; an empty list holds no padding), command-list to 14700 (it keeps the taller of its two heights), notifications to 12950 (the bell's edge), pane to 1950 (the page column's room), chart to 34950 (the date line's reason), and code, diagram-zoom, filter, links, sheet, still-table, tab-bar and topbar each by under 150 bytes (the three forms of a room; the selection column's width however given). Merged with main at db0bc418 (#129 to #131), DECISIONS 336's caps are set to the measured sizes again: core 35800 to 38950 and its usage 3200 to 3650, toast 16200 to 16750, terminal to 12700 (13050 with the open items' ruling: both copy buttons draw their three glyphs once, so a refused copy shows the close with no markup written after), diagram-zoom 17600 to 17750 (its viewer's Close and Zoom out hung, and the foot's room). Raised in DECISIONS 336 (reserved room across every component, claude/reserved-room), each to its measured size: core 35550 to 38700 (the edge rule a ghost .btn hangs by at a head, its ring and touch hit area, the side insets by direction, the .panel-head and page section-head that hang their last button by themselves) and its usage 2950 to 3450 (how data-edge and --basalt-edge-room are written); search 4400 to 5200 (search.js, the held top), terminal 11950 to 12550 (the close glyph for a refused copy, the edge on both copies), links 2750 to 3300 (the first icon link hung, the card room, the 20px glyph), toast 16050 to 16650 (the 46px hit areas on touch), selection 1500 to 1650 and still-table 14650 to 15000 (the 44px select column), command-list 14000 to 14350 (the panel hugs, the room is page), menu 8950 to 9150 (the column every row keeps when any row has a check or a glyph), notifications 12450 to 12600, filter 17500 to 17600, forms 3500 to 3550, sheet 5400 to 5450, topbar-nav 7550 to 7600 and app-shell 5200 to 5250 (logical sides, the edge and the room); topbar's usage 3100 to 3200 (a bar's last ghost control takes data-edge); command-list's usage 2150 to 2300 (the panel hugs; the room is page, and only on the page); dialog-form's usage 1300 to 1350 (its Close is written data-icon-only data-edge=\"end\"). Raised in the polish ruling of 336 (the selection box keeps to the cell's line): selection 1650 to 1750 (the box's start margin, min(space-4, half the spare room): 1710 measured) and its usage 1150 to 1350 (the rule's sentence: 1313 measured).", + "$comment": "Which parts of the skill's CSS and JS a page gets. The core is always in. A module is in when the page's body has one of its classes, attributes or tags, matches one of its text patterns, or is named in a <!-- basalt:use name --> comment, and when another module needs it (requires). Modules are added in the order listed here, which is the order of the source files' cascade. classes: every class the module's CSS styles (the test checks them against the CSS and against SKILL.md). budget: the most bytes its minified CSS and JS may reach together. budgets: skillMd (SKILL.md, the context an agent pays: never above what it was), core (the CSS and JS of every page). icons: Phosphor names the module's script draws itself. Raised in the first parity PR (the owner's \"bring up the parity\"): forms (the number-input, search-clear and file-input chrome), disclosure (the native details marker), status (the accent reader and the forced-colours badge border), spinner (a fixed 16px ring), and the new number, range and accent modules. skillMd rose 10555 to 10900 for the new rules (number field, native chrome, the braille rule, the accent). Raised in the second parity PR (popup rows, levels and the segment's pill): segment 1400 to 3700 (the shared sliding pill: its script, 1.5 KB, and its CSS with the pill's two fallbacks), rows 3600 to 4300 (#27's plate-in-a-row geometry, the plate per level, the glide's shared plate and the forced-colours lit row, net of the removed bar), palette 9400 to 11300 (the glide's script, 2.4 KB: it follows the lit row, travels on a pointer, snaps on a key, and fades in place on leaving). The art module (DECISIONS 101 and 104) is the token groups only some pages name, taken out of the core so the core stays under its cap: the chart roles and lengths, the art colours, the aspect ratios and the stage headroom, in both themes (2087 bytes at 2100; it grows only when a token of those groups is added). A page gets it when its body names one of them, a var() in its own style included. The every-module page has no cap of its own (owner, DECISIONS 79): each part is capped, and a page carries only the parts it uses. usage: the most bytes of a module's usage text (src/usage/NAME.md; core.usage for core.md), which compose.mjs --usage prints on demand. It is context an agent pays only for the modules its page uses, so it is capped per part as SKILL.md and the CSS and script are (DECISIONS 79 and 109). Each is set a little above what its text was when the usage moved out of SKILL.md (DECISIONS 109); raising one needs a reason in the PR, and a rise of 40 to 50% is the owner's. textWords: each text pattern said in words, which compose.mjs --usage prints instead of the regular expression (one for each entry of text, in order). builds: modules a module requires whose markup its script writes, so --usage prints a line saying so instead of their usage text (the palette builds its own rows and key chips). The council's clarity check of the usage texts (all three: not yet clear) raised eight caps because the texts gained what an agent had to guess: callout 200 to 700 (the icon and one wrapper div around the title and body as markup, the four status icons, the role React's Callout renders), palette 1100 to 1300 (an item shown whole, keys as an array, keywords), stats 450 to 800 (a snippet of the figures and of the dl), tabs 500 to 650 (the unselected panels), code 250 to 450 (the markup and what each token class means), segment 150 to 300 (a click does not switch it), progress 150 to 350 (the empty span that paints the fill), theme 250 to 400 (leave the button empty), and accent 250 to 300. Topbar went down, 700 to 500, as its build detail was cut. Raised in the usage PR (the council's clarity check): palette 11300 to 11450 (the module grew 11283 to 11448, +165, about 1.5%), for the guard that makes a string `keys` warn and draw no chip instead of throwing in `keys.filter`, which the palette's usage already promised. Round 2 of the clarity check: tabs 650 to 750 (the panel's top space shown in the snippet, and that the script selects a tab on click). Raised in the site-icons and status PR (skill-parity part A, DECISIONS 106 and 107): status 1650 to 1900 (the neutral, pending and running marks, the badge's real border, and the forced-colours disc, net of the red danger word it drops) and its usage 400 to 1000 (every status in words, the word alone, running, forced colours); rows 4300 to 4450 (the profile list's seat rule and the status parts on a lit row) and its usage 300 to 600 (the profile list, with the one mistake: never an empty element for the seat). New: the links module (2671 bytes: the social row, the new-tab arrow's CSS and the script that draws it; budget 2750) and its usage (1746 bytes; cap 1850), which carries the social link, the glyph set, icon only and the new tab. Dropping Regular halves icons.json. Added in the overlay PR (skill-parity-4, batch 7 step 2, DECISIONS 108): the shared plate leaves palette.js for a glide module (the palette, a menu and the notification centre all call it), so the palette's cap went down, 11450 to 9250, and rows 4450 to 3850 (the plate's CSS moved to glide); and the overlay layer comes in as seven modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: popover (the native popup shell), menu, dialog (the dialog and alert dialog), sheet (on every side, the top one the site header's narrow menu), tooltip, toast and notifications (the centre). skillMd is unchanged in its cap (the eight new index lines fit within it); the core is unchanged in bytes. Added in the figures and charts PR (skill-parity-5, batch 7 step 3, DECISIONS 108): four modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: meter (React's Meter, CSS only, 2581 bytes), dlist (the description list, CSS only, 1265), terminal (the code block's transcript: its CSS, 3242, and the script that draws the gutter, the copy button and the replay, 4824) and chart (React's TimeChart and ChartGroup: 7313 of CSS and 23262 of script, which port chart.tsx's scale, layout, lane, labels, sentences, keyboard and table; it needs the art tokens, the table and the kbd chips, and a page without a chart carries none of it). Stats grew for the source line (budget 700 to 850, 798 bytes; its usage 800 to 950, 675 to 899 bytes, +33%, under the owner's 40 to 50%). skillMd is unchanged in its cap (four index lines fit within it); the core is unchanged in bytes. Added in the forms and selection PR (skill-parity-6, batch 7 step 4, DECISIONS 108): six modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: select (React's Select: the native select's closed trigger in every browser and, where `appearance: base-select` is shipped, the styled list with its two-line rows; a small script that says which input lit a row, 7740 bytes before it, choice (Checkbox, Radio, RadioGroup and Switch as styled native inputs; CSS only, with the first-frame rule), choice-card (ChoiceCard; CSS only), toggle (the pressed toggle's plate and check seat on .btn; CSS only), selection (a table's checkbox column: its fixed width and the script that sets aria-selected, the mixed header box and the count) and loops (the page-level hold on every loop with its switch: the held look and the script that stores it). The select's styles left forms, whose budget fell 3650 to 3250. skillMd rose 8621 to the size of its six new index lines, within its cap; the core is unchanged in bytes; compose adds the stored-hold line to the head of a page that has the loops module. Revised in the same PR (the lead's review of the build): the select gains select.js (one row is lit at a time, by whichever of the pointer and the keys moved last), and choice, toggle, selection and loops carry the first-frame rule, so a state a script sets on load (a mixed header box, the stored hold) paints at once with no crossfade. Added in the navigation and layout PR (skill-parity-7, batch 7 step 5, DECISIONS 108): five modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: glyph (Basalt's core glyphs drawn by name, at rest and selected, from a table the build works out from the drawn set; a page carries only the glyphs it names, and the drawing of a core glyph from data-glyph left the sheet module, which draws none now), nav (React's Nav: the sidebar's, the narrow menu's and More's rows, with the shared hugging pill), topbar-nav (the site header's links, one action and narrow menu, built by script from the bar's markup), app-shell (the shell, its sidebar and rail, and the app header) and tab-bar (the phone tab bar). The topbar module became the site header's bar (React's SiteHeader, DECISIONS 108: 56px with its line inside, the 44 by 44 brand target, the narrow-screen buttons, the derived sticky offset), budget 1600 to 3200 because its rules gained the app header's shared smoke, and its usage 500 to 750 (+50%) for the lockup's markup (the links, action and menu are topbar-nav's usage). Glide 3700 to 3950: the navigation's pill is a shape inside the row that the plate follows (about 200 bytes). The core's usage 2000 to 2100 (+5%): h2 is the Section step, the prose column's measure, and a link already 44px tall needs no margin. skillMd rose 9317 to 9863 for five index lines, under its cap; the core CSS grew 38 bytes (the layout tokens replace raw lengths, the gutter is one derived property, h2, .prose and .lead follow foundations) and the core script is unchanged. A module's media query writes %bp-md%, %bp-lg% or %bp-container% and the build substitutes the breakpoint tokens. Added in the tables and filters PR (skill-parity-8, batch 7 step 6, DECISIONS 108): the existing table module gains React's table additions (DECISIONS 95: the row header, \"Not observed\", the row density and the scroll hint with its small script), budget 1400 to 3000 (it was 1134 bytes of CSS; it is 2168 of CSS and 693 of script) and its usage 700 to 950 (+36%); and two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: still-table (React's Table with `columns`: the fixed layout from a colgroup, the whole header cell as the sort button with its reserved seat, aria-sort, the pinned columns and their divider, the empty row; 4767 of CSS and 3264 of script, budget 8200) and filter (React's MultiSelect and FilterResult: the chips, the trigger and checklist with the search band from ten values, Clear held in place, the one debounced result line, and the narrowing of a table by `data-column`; 8240 of CSS and 7978 of script, budget 16400; it needs the popover, glide, glyph and choice modules). The core is unchanged in bytes. skillMd rose 9863 to 10128 for two index lines and the CaretUpDown icon's name, within its cap. Added in the commands PR (skill-parity-9, batch 7 step 7, DECISIONS 103 and 108): one new module a page carries only when it uses it, command-list (React's CommandList: the command panel set in the page, list plus preview, the push; it extends the palette and needs rows, kbd and glide; 5229 of CSS and 8734 of script, budget 14000, usage 2150). Two-line rows come to the existing modules: rows 3850 to 5350 (the described row's grid and description line, the push's chevron: 1481 bytes of CSS, the same rules React's menu rows carry), palette 9250 to 9900 (its rows are one function the list shares, with the description and the two-tier ranking of title matches over keyword and description matches; +636) and its usage 1300 to 1350, rows' usage 600 to 800, and glide 3950 to 4000 (a host that is idle counts as having no lit row, +54). skillMd rose 10128 to 10259 for one index line, within its cap; the core's CSS grew 24 bytes (.split.aside takes size-list-width in place of its raw 20rem: the same 320px, so no pixel moves) and the core script is unchanged. Added in the art PR (skill-parity-10, batch 7 step 8, DECISIONS 104 and 108): two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: stage (React's Stage and PairedArt: full-bleed art under the site header, the pull-up by the sticky offset, the headroom, the paired art that follows the page's theme, and the forced-colours and print rules; CSS only, 1179 bytes) and framed-art (React's FramedArt: the figure, its rim and radius, the reserved box, the placeholder and the failed alt, the caption and credit; 2208 bytes of CSS and the 733-byte script that sets the frame's phase); both need the art tokens. The bar stays smoked over a stage: React clears it only over a stage that passed the headroom test helper, and a page has no test run (DECISIONS 108's note), so the skill builds no clear state. skillMd rose 10259 to 10500 for two index lines, within its cap; the core is unchanged in bytes. The callout gained the status rim in the same PR (DECISIONS 82, D8's status callouts): success, warning and danger draw their border in the status colour at 45% mixed in sRGB over the callout's own level, one solid colour on every side, and CanvasText in forced colours with the icon; the status colour is now one property the icon and the rim read. Its budget rose 900 to 1150 (the module is 1089 bytes, from 792: +297, about 37%); its usage is unchanged. Added in the overlays-and-the-rest PR (skill-parity-11, batch 7 step 9, DECISIONS 90 and 108): the last two parts of D8's part 5, each a module a page carries only when it uses it, with its own cap and usage cap set a little above its size: combobox (React's Combobox: the input with its caret button inside, the popup of the menu's rows with the glide's shared plate and two-line options, the filtering, the keys, the hidden value, the empty message and the check; 4342 of CSS and 6423 of script, budget 10900, usage 2150; it needs forms, popover and glide, and builds the last two) and sparkline (React's Sparkline: the label and latest value, the line, the axis, the empty sentence and the loading line that breathes; 1609 of CSS and 1874 of script, budget 3600, usage 950). The combobox copies the menu's row rules, as the select's list does, because React's Combobox renders MenuItem rows (a 40px hit area, a 36px plate) and the skill's .row is the palette's 44px: it carries no menu script. popover.js gains the combobox popup in the list of popups that keep focus where it is (+21 bytes, within its cap). skillMd rose 10500 to 10724 for two index lines, within its cap; the core is unchanged in bytes. Added in the motion-rules PR (DECISIONS 136 and 139): one module, ambient (a page's one ambient loop: CSS 828 bytes, script 433, budget 1300, usage 800), taken out of loops so the hold's own module grows only by the icon toggle's glyph swap (loops 2000 to 2200, +10%; its usage 1300 to 1650 for the icon form and the new settings-row sentence, +27%); and the chart's entrance (`entrance: true`: the marks' animations, their conditions and the redraw that restarts them at the elapsed time, 23262 to 25299 bytes of script; budget 30700 to 32800, +7%, usage 2500 to 2950, +18%). The core grew by the three tokens (27704 to 27862 bytes of CSS, under its cap). its stage usage gained the ambient art's line (1650 to 1750, +6%). skillMd rose 10724 to the size of the ambient index line, within its cap. Raised again in the motion-rules amendment (DECISIONS 143): chart 32800 to 33800 (script 25299 to 26375 bytes, +4%; +10% over the 30700 it began with) for the glide a new data set makes mid-entrance, print settling it, and `Basalt.pageChange()`; its usage 2950 to 3150 (+26% over the 2500 it began with). Raised in the second motion-rules amendment (DECISIONS 148): chart 33800 to 34400 (script 26375 to 26970 bytes: a line and its markers glide from their drawn geometry, and `beforeprint` settles the entrance; +12% over the 30700 it began with); topbar-nav 6900 to 7500 (+8.7%: the narrow menu's pause row, its CSS and 275 bytes of script, DECISIONS 148 item 2); loops usage 1650 to 1800 (+38% over the 1300 it began with, for the icon form's `title` and the menu row). Raised in the audit-design-b PR (DECISIONS 138 and 139): still-table 8200 to 13400 (+63%: the module was 7927 bytes and is 13311; the cut cell's plate, its focus stops and its dismissal, ported from React's cell-peek.ts, are 4273 bytes of script and 1111 of CSS; a still table that truncates needs them). The same PR: core usage 2100 to 2250 (+7%: the skip link, one bullet), forms usage 350 to 480 (+37%: the required mark), still-table usage 1950 to 2150 (+10%: the cut cell and the width rule), notifications usage 1050 to 1100 (+5%: the 44px entry on touch). The skip link's rim and radius took the core 30457 to 30609 bytes, under its cap (the rules that hang it under the bar are the topbar module's: 3200 to 3600, +12.5%); core 30720 to 31050 (+1.1%, DECISIONS 147: also the bar's links left out of the rule: the pseudo-element that makes a short standalone link a 44 by 44 target), skip-link script in the topbar module (3200 to 4150 over this PR, +30%: the rules that hang the link under the bar, 3600, and the script that reads the bar's real edge, 4150), sparkline 3600 to 4050 (+12.5%: React's ticker structure, so the value copies once on its line, and in forced colours the strips go and the number is plain text), forms budget 3250 to 3500 (+7.7%: the necessity word), notifications 9050 to 9250 (+2.2%: the 44px entry). Raised in the audit-design-b PR's E2 port (DECISIONS 138 and 139: the core set draws check, close, the chevrons, copy, plus, minus and search wherever a component draws them): the modules that drew a Phosphor icon for one of those now carry the core glyph's whole SVG, written in at build time (`%glyph-svg:name%`, the markup the glyph module's `_.glyph(name)` returns, so no module needs the glyph module and a page pays for nothing it does not use), and the Phosphor path of the same icon leaves the page. Each module's own bytes rose by that markup, and a page's total moved by what the Phosphor path it no longer carries saves: menu 8600 to 8900 (+303), combobox 10900 to 11200 (+303), copy 1900 to 2400 (+640), terminal 8100 to 8850 (+761), toast 13850 to 14150 (+325), number 2900 to 3400 (+557), filter 16400 to 17050 (+785), palette 9900 to 10450 (+536); the command list shares the palette's search drawing and fell 20 bytes. Set in integration-nov15, where the type-layout, motion-rules and audit-design-b branches meet: the combined tree measured SKILL.md 10959 bytes (each side's cap was 10900: both added index lines), core 31192 bytes (caps 30720 and 31050: the page-row and display rules, the three motion tokens and the skip link and 44px target rules all land in the core CSS) and core usage 2348 bytes (caps 2300 and 2250: type-layout's line and the skip-link bullet), so each is set to the measured bytes rounded up to the next 50: skillMd 10900 to 11000, core 31050 to 31200, core usage 2300 to 2350. Raised in the audit-design PR (decisions 138 and 139, parts A, D and C11): core 30720 to 31600 (+2.9%: the more-contrast block and its three aliases, and the field boundary token, every page carries as React does; the shadow-pill token is gone; the script gained `reserve`, 240 bytes), segment 3700 to 4100 and tabs 2300 to 2700 (the chosen label is 600 against 400, its width reserved by a span that carries its own copy, drawn unseen at 600; the pill's drop shadow is gone), and the segment's usage 300 to 380 (the weight and the glyph-only button). Raised again in the audit-design-a amendment (decision 145): core 31600 to 32300 (reserve() also reserves a label that is not plain text), segment 4100 to 5100 and tabs 2700 to 3500 (the second copy of such a label, and an icon drawn in both its forms), glyph 1100 to 1300 (a glyph in a segment or tab is drawn in both forms). Raised in the second audit-design-a amendment (decision 149): core 32300 to 32800 (reserve() builds the second copy of a label without any id, name, reference or hidden control, and does not copy a frame or media), segment 5100 to 5400 and its usage 380 to 500 (the 600 is on the label, the one-line rule and the usage text); the still-table cap is back at 8200, as the wash is on every cell again. Return 3 of the audit-design-a build (decision 149): tabs 3500 to 3700 (a tab the script has not reserved is 600 itself when selected, and one it declined is marked; the same two lines are in segment, which stays under 5400). Raised in the audit-fix-c2 PR (engineering, no pixel changes): toast 13850 to 14350 (the module was 13789 bytes and is 14288, +499, 3.6%) for F6, which focuses the Notifications region and Shift+Tab or Escape from it (or from the first toast) leaves it for where focus came from (and keeps a dialog's focus trap from wrapping it), as Base UI's viewport does in React, and for placing the region from focus (in the modal that holds it, or in the body), so a toast is never under a backdrop or in an inert modal whatever order the modals opened in (A3-09); the palette module grew 9864 to 9897 of its 9900 so that a palette opened over a modal sits inside it; topbar 3200 to 3250 (3123 to 3233, +110) for the scroll margin on what the bar holds, so a Tab into the bar from a scrolled page does not scroll the page (React's rule from PR #66); stage usage 1650 to 1750 (1580 to 1713, +8%) for the art's new place in the markup, after the content (A1-09), the stage's own CSS rising 1179 to 1208 within its 1250. skillMd rose 10724 to 10876 for the sentence that says a body may carry head tags, within its 10900. compose.mjs, the tool an agent runs, has no cap here (it is never in a page): it grew 21673 to 38153 bytes for the tokenizer that reads a body as HTML does and the head tags. Raised in the site-parts PR (DECISIONS 146, round 39), which folds each new part into the module it belongs with, so SKILL.md gains no index line (it has 41 bytes under its cap and a new module needs about 100): topbar 4150 to 17600 (+13450: the site footer and its disclosures, the lockup by pixel density, and a bar that arrives or leaves and returns, with its observer; a page that has a .topbar and no footer carries them too: the alternative, a module for each, needs its own index line and so SKILL.md bytes) and its usage 950 to 2900 (the footer's markup, the lockup's and the phase's); theme 650 to 4550 (the three-word theme choice: its CSS 2230 bytes and its script, 2277, with arrows, storage and the system listener) and its usage 400 to 1150 (the choice's markup written in full, so the right word is chosen before any script); segment 3700 to 3800 (a radio group's checked state besides a pressed button); stage 1250 to 2150 (its first script, 768 bytes, for fit and anchor) and its usage 1750 to 2000; framed-art 3000 to 3900 (drawn art in the frame: fit, anchor, no scaling strokes) and its usage 1250 to 1400. SKILL.md rose 10959 to 10992 (the topbar and theme index lines name .site-footer and .theme-choice). The head's theme line also writes data-theme-choice. Raised in site-parts return 2 (DECISIONS 146 B1 and B4): theme 4550 to 5350 (+800: the icon form of the theme choice, [data-theme-menu], whose button shows the theme in use, is named for the choice and opens the page's own .menu of three radio rows, in the theme script's 3073 bytes; the menu and popover modules are the page's, brought by its markup, so no module line was added and SKILL.md is 10993 of 11000) and its usage 1150 to 2200 (+91%: the menu's markup is written in full, and the deprecated toggle is said once); app-shell usage 2000 to 2100 and topbar-nav usage 1900 to 1950 (the theme control leaves the bar's text; the tools and the end cluster come in). The two example bodies still carry the deprecated data-theme-toggle. Return 2, F3 (DECISIONS 146 F): stage 2150 to 2250 (script 842 bytes: slice is the stage's default, as a frame's, and a drawing's own preserveAspectRatio stands unless the stage names data-fit or data-anchor) and its usage 2000 to 2150. framed-art 3900 to 4000 (a drawing's own preserveAspectRatio stands unless the figure names data-fit or data-anchor, +101 bytes). Return 3: theme 5350 to 5900 (script +569 bytes: who wrote data-theme, so System follows the system's change live and a theme the page set by hand, or a .dark or .light root, survives it). Raised in the controls port (DECISIONS 154): skillMd 11000 to 11200 for two index lines (link-tabs and option-chips, 214 bytes together), and core 31200 to 31600 for the nine tokens the port adds to every page's token CSS (the control rungs 44 to 64, two container widths, the confirm hold and the amount's opacity, 311 bytes). New modules (DECISIONS 154): link-tabs 2700 (its sizes, the 640 container step, the forced-colours underline, and the select that replaces the row under 720 with its 590-byte script, A15; it requires the select module), option-chips 5700 (the chip's states each written for a native radio inside a label, which needs :has on every one, plus the 1 KB script that keeps an aria-disabled chip reachable and never chosen). Return 3 (DECISIONS 154 conformance): link-tabs 2700 to 3100 and its usage 1650 to 1850 (the select's height for each row size, and a script that reads aria-current when it is needed and watches it move: 3,048 bytes), option-chips 5700 to 6700 (each state written twice, as a state attribute and as :has(), so no browser needs :has(): 4,975 CSS and 1,623 script). Return 4 (DECISIONS 158, Q2): link-tabs 3100 to 4300 and its usage 1850 to 2400 (the \"Go to\" label drawn at the select's start with its measured clearance, the select's accessible name kept as the words and the chosen page's, and the key hold that keeps a letter or an arrow on the closed select from navigating: 4,174 bytes, CSS 2,951 and script 1,223). Raised in the links-and-rows port (DECISIONS 152; the owner's approval is the lead's to confirm): the new link-rows module (5050 bytes of CSS, 50 of them for Castle's big-row arrow stepping colour over duration-fast, return 1, 1500 of usage: the directory's and the big rows' CSS, whose arrow is a core glyph drawn as a mask, and their tokens, size-row taken out of the core like type-layout's), disclosure 1550 to 3500 (Show all: the track, the clip and the settle, 1.5 KB of script and 1.8 KB of CSS), copy 2400 to 3500 (the form with words: the one cell and its script). SKILL.md rose 10959 to 10997 for one line, within its 11000 cap. Raised in the charts port PR (DECISIONS 153, D7a): chart 34400 to 34650 (script 26970 to 27270 bytes, +1.1% on the 34283 it was: `Basalt.trailingMean`, the trend maths React exports as `trailingMean`, 300 bytes), its usage 3150 to 3350 (+6%: one line for it). The tokens the batch adds (chart-lit-top, -mid and -base in both themes, size-chart-plot-sm, size-chart-row, size-meter-marker and radius-2xs) took the art module 2087 to 2546 bytes (budget 2100 to 2600, +24%: the chart tokens are its group) and the core 31192 to 31250 (cap 31200 to 31300, +0.3%: radius-2xs). Only D7a names a skill module in the charts ballot; the lit marks, the headline frame, the phase chart, the share bar, the coverage strip, the marks row and the range meter are React-only in this batch. Added in the overlays-and-search PR (DECISIONS 155, D10b and D13a): the sheet gains React's head, body and foot (the 44px close, the 20/28 title over a 13px count, the divider and the safe areas; its CSS 3.6 to 5.2 KB, budget 4050 to 5250, +30%) and its usage 1050 to 1450 (+38%: the anatomy and the step's focus, two bullets); and one new module a page carries only when it uses it, search (React's SearchDialog: the form, the field's -2 outline, the count line, the fixed-height results area and the rows with their picture slots and full-bleed hover wash; CSS only, 4368 bytes, budget 4400, usage 2050; it requires the dialog). The dialog's title draws no ring when script focuses it. skillMd rose 10959 to 11079 for the search line (the sheet's line is unchanged: its usage carries the anatomy), so its cap rose 11000 to 11100 (+0.9%). The core's CSS grew 31192 to 31421 bytes for the six new size tokens (the wide dialog, the search trigger and the logo and picture slots of a search result): its cap rose 31200 to 31450 (+0.8%). The two 44px values (the sheet's close and the search field) are local to their modules, with a lint exception that says they join the controls batch's size token (DECISIONS 154). Set in integration-nov15b, where audit-design-a, audit-fix-c2, site-parts, port-controls, port-links-rows, port-charts and port-overlays-search meet: the combined tree measured SKILL.md 11560 bytes (the caps were 11000, 11100 and 11200: each side added index lines), core 34086 bytes (caps 31300 to 33550: every side's rules land in the core CSS and script), topbar 17660 (17600 from site-parts, plus audit-fix-c2's skip-link and focus work), number 3453 (3400), palette 11379 (11000, audit-fix-c2's hosted scrim plus the core search glyph), dialog 5120 (5100), toast 15692 (15400) and stage usage 2248 (2150), each over every side's cap, so each is set to the measured bytes rounded up to the next 50: skillMd 11200 to 11600, core 33550 to 34100, topbar 17600 to 17700, number 3400 to 3500, palette 11000 to 11400, dialog 5100 to 5150, toast 15400 to 15700, stage usage 2150 to 2250. The segment cap is the base's 5400 plus port-controls' 100 (5500), unchanged by the merge. Raised in integration-nov15b, join 2 (a link tab takes the selected state, DECISIONS 138 A, 145, 149 and 154's D12 row): link-tabs 4300 to 5750 (+34%: the module was 4174 bytes and is 5736; the 600 against 400, the reserved width and the second copy of a composed label, an icon drawn in both its forms, the same rules a tab carries, 1,530 bytes of CSS and script) and its usage 2400 to 2550 (+6%: one bullet). The cap is the measured bytes rounded up to the next 50; a module that needs the tab's rules carries them as the segment and tabs modules do, so a page without link tabs pays nothing. Raised in the panels, art and parts port (DECISIONS 162): table 3000 to 3150 and its usage 950 to 1450 (the flat form and the two-line cell), stage 2250 to 2600 and its usage 2250 to 3100 (the closing block: its held art, forced colours and print; its section gap is type-layout's --basalt-section-gap, which a page with data-closing brings), the new app-tile 4300 (a 120-point polygon clip and the hairline's mask of the same outline), captioned 2000 and period 1400; skillMd 11600 to 11950 for one index line each for captioned, app-tile and period (358 bytes; the file is 11918). Raised in the logs, status and forms port (DECISIONS 162): core 34100 to 34200 (the new size-field-label-inline token, 80px, is written into every page's tokens: 25 bytes); dlist 1300 to 1900 and its usage 950 to 1060 (the stacked form, R9 and R10: a title over its text, 20px between entries, no divider; one usage line). Raised in audit-fix-c6 (the owner's cap, raised by the builder and for the owner to confirm): glyph 1300 to 1900, for redrawing a glyph when its ancestor's aria-current or data-current moves (the lists that hold glyphs are watched). Raised in the colour-ink-ladder build (DECISIONS 166): core 34200 to 34350 (the four lifted dark inks are four new primitives, each written into every page's tokens: the core measured 34307). Raised in the audit-2-design build (DECISIONS 167, Q7a): disclosure 3500 to 3800 (the core chevron drawn as a mask in place of two borders: the module measured 3755). Joined in the integration of c7 (#86) and c10 (#91): option-chips 6750 to 6850 (c7's reset resync and c10's data-ready together measure 6839). Raised in table-sort-3 (DECISIONS 257 and 261, the owner's pick: three sort states, the arrow after the label, explainers on column titles): still-table 13400 to 14650 (+9.3%: the module was 13343 bytes and is 14602; the end-aligned label's move by a transform, its right-to-left sign and the indicator that waits for it on a fine pointer, 912 bytes of CSS; the third state, the sort from the table's own order and a .explainer kept out of the button, 347 bytes of script) and its usage 2150 to 2250 (2197: the third state and the own order); the new explainer module 5850 (5842: a manual native popover opened from the sort button on hover, keyboard focus and a long press, placed above the header or beside it, 1752 bytes of CSS and 4090 of script; a page without explainers pays nothing) and its usage 900; skillMd 12250 to 12400 for the explainer's index line (113 bytes; the file is 12352). Each cap is the measured bytes rounded up to the next 50. Raised in table-sort-3's fix pass (Astra's review): explainer 5850 to 6900 (+18%: 5842 to 6864 bytes; the gap between the header and the card kept while a pointer crosses it, the close when its header leaves the view whatever has focus, the dismissal held until pointer and focus have both left, and its page-wide listeners and timers scoped to an open card and stopped when the table leaves the page, 1,022 bytes of script). 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. The fix round after both reviews of 421348e8 sets them to the measured sizes again: core 38950 to 39600 (every room says all three forms, and a hung word's box grows by a short room's shortfall), search to 5700 (it places its top again on a resize and with the keyboard; an empty list holds no padding), command-list to 14700 (it keeps the taller of its two heights), notifications to 12950 (the bell's edge), pane to 1950 (the page column's room), chart to 34950 (the date line's reason), and code, diagram-zoom, filter, links, sheet, still-table, tab-bar and topbar each by under 150 bytes (the three forms of a room; the selection column's width however given). Merged with main at db0bc418 (#129 to #131), DECISIONS 336's caps are set to the measured sizes again: core 35800 to 38950 and its usage 3200 to 3650, toast 16200 to 16750, terminal to 12700 (13050 with the open items' ruling: both copy buttons draw their three glyphs once, so a refused copy shows the close with no markup written after), diagram-zoom 17600 to 17750 (its viewer's Close and Zoom out hung, and the foot's room). Raised in DECISIONS 336 (reserved room across every component, claude/reserved-room), each to its measured size: core 35550 to 38700 (the edge rule a ghost .btn hangs by at a head, its ring and touch hit area, the side insets by direction, the .panel-head and page section-head that hang their last button by themselves) and its usage 2950 to 3450 (how data-edge and --basalt-edge-room are written); search 4400 to 5200 (search.js, the held top), terminal 11950 to 12550 (the close glyph for a refused copy, the edge on both copies), links 2750 to 3300 (the first icon link hung, the card room, the 20px glyph), toast 16050 to 16650 (the 46px hit areas on touch), selection 1500 to 1650 and still-table 14650 to 15000 (the 44px select column), command-list 14000 to 14350 (the panel hugs, the room is page), menu 8950 to 9150 (the column every row keeps when any row has a check or a glyph), notifications 12450 to 12600, filter 17500 to 17600, forms 3500 to 3550, sheet 5400 to 5450, topbar-nav 7550 to 7600 and app-shell 5200 to 5250 (logical sides, the edge and the room); topbar's usage 3100 to 3200 (a bar's last ghost control takes data-edge); command-list's usage 2150 to 2300 (the panel hugs; the room is page, and only on the page); dialog-form's usage 1300 to 1350 (its Close is written data-icon-only data-edge=\"end\"). Raised in the polish ruling of 336 (the selection box keeps to the cell's line): selection 1650 to 1750 (the box's start margin, min(space-4, half the spare room): 1710 measured) and its usage 1150 to 1350 (the rule's sentence: 1313 measured). Merging main (#130, #131) into claude/diagram-interop: diagram usage 4600 to 4850 (+5.4%: Batch B's diagram usage plus the basalt-diagram-export rule line, measured 4806), then 4850 to 5050 (noting that .lucid is for Lucid's REST API only and to use .vsdx in Lucid's UI, measured 4999).", "budgets": { "skillMd": 13050, "core": 39600 @@ -821,7 +821,7 @@ "kbd" ], "budget": 145450, - "usage": 4600, + "usage": 5050, "builds": [ "kbd" ] diff --git a/.agent/skills/basalt-html/parts/usage/diagram.md b/.agent/skills/basalt-html/parts/usage/diagram.md index eb31b43e..5d343dae 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram.md +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -28,3 +28,4 @@ Boxes and the lines between them. `compose.mjs` writes the figure's words into t - **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: `<!-- basalt:marks aws-s3-bucket temporal -->`. - **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`. +- **Export:** never hand-write `.drawio`, `.vsdx` or `.lucid`; author this diagram JSON and run `basalt-diagram-export <input.json|page.html> --to drawio,vsdx,lucid` (in-repo: `node packages/react/bin/basalt-diagram-export.mjs` after `npm run build`). `.lucid` is for Lucid's REST API only (`POST https://api.lucid.co/v1/documents` with a token, type `x-application/vnd.lucid.standardImport`); to import through Lucid's own screen, use `.vsdx`. diff --git a/dependencies.allowed.json b/dependencies.allowed.json index b0a0ed36..d92059b0 100644 --- a/dependencies.allowed.json +++ b/dependencies.allowed.json @@ -1,5 +1,5 @@ { - "$comment": "Runtime dependencies the owner has approved, per package, with the reason. Adding one needs the owner's approval in the PR that adds it (AGENTS.md). Dev dependencies are not listed: they are not installed with the package. One of them, geist, is copied into dist as the font files, under its own licence (dist/fonts/OFL.txt). Every version is exact (scripts/check-deps.mjs fails on a range, a tag, an alias or a URL) except those listed in $ranges, the host app's own React, which a package cannot pin.", + "$comment": "Runtime dependencies the owner has approved, per package, with the reason. Adding one needs the owner's approval in the PR that adds it (AGENTS.md). Dev dependencies are not listed: they are not installed with the package. One of them, geist, is copied into dist as the font files, under its own licence (dist/fonts/OFL.txt). Every version is exact (scripts/check-deps.mjs fails on a range, a tag, an alias or a URL) except those listed in $ranges, the host app's own React and optional peer dependencies, which a package cannot pin.", "packages/react": { "@base-ui/react": "Accessible unstyled primitives under every component (foundations: Primitives).", "cmdk": "Command menu filtering and keyboard selection (MIT, pacocoursey/cmdk). Bailey approved it for the Benji primitives.", @@ -7,11 +7,13 @@ "@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.", + "playwright": "Optional peer: headless Chromium for basalt-diagram-export's default exact geometry measurement (DECISIONS 348). Not installed unless the host installs it; the CLI falls back to approximate headless layout with a warning when absent.", "react": "Peer: the host app's React.", "react-dom": "Peer: the host app's React DOM." }, "$ranges": { "packages/react": { + "playwright": ">=1.40.0 <2", "react": ">=19", "react-dom": ">=19" } diff --git a/package-lock.json b/package-lock.json index ae913114..4a7e3e60 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7242,6 +7242,9 @@ "cmdk": "1.1.1", "shiki": "4.6.0" }, + "bin": { + "basalt-diagram-export": "bin/basalt-diagram-export.mjs" + }, "devDependencies": { "@types/react": "19.3.0", "@types/react-dom": "19.3.0", @@ -7255,8 +7258,14 @@ "typescript": "7.0.2" }, "peerDependencies": { + "playwright": ">=1.40.0 <2", "react": ">=19", "react-dom": ">=19" + }, + "peerDependenciesMeta": { + "playwright": { + "optional": true + } } }, "packages/tokens": { diff --git a/packages/react/bin/basalt-diagram-export.mjs b/packages/react/bin/basalt-diagram-export.mjs new file mode 100755 index 00000000..45419a2f --- /dev/null +++ b/packages/react/bin/basalt-diagram-export.mjs @@ -0,0 +1,593 @@ +#!/usr/bin/env node +// basalt-diagram-export (DECISIONS 311, 314, 324, 327) +// Deterministically exports Basalt diagram JSON (or `<script type="application/json" data-diagram>` blocks in HTML) +// to draw.io (.drawio), Microsoft Visio (.vsdx), and Lucid Standard Import (.lucid / .lucid.json). +// By default, measures boxes and routes through headless Chromium + Basalt's real layout engine using the +// optional `playwright` peer dependency; when Playwright or Chromium is unavailable, falls back to Basalt's +// pure-JS headless layout and warns on stderr that geometry is approximate. +// Usage: +// basalt-diagram-export <input.json|page.html> [--to drawio,vsdx,lucid] [--theme light|dark|adaptive] [--marks omit|embed] [--out <dir|file>] [--width <px>] [--browser|--headless] +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { + diagramToDrawio, + diagramToLucid, + diagramToLucidJson, + diagramToVsdx, + exportMeasuredDiagram, + isBundledMarkEmbeddable, + placeAutoDiagram, +} from "../dist/diagram-interop.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const pkgRoot = path.resolve(here, ".."); +const pkgVersion = JSON.parse(fs.readFileSync(path.join(pkgRoot, "package.json"), "utf8")).version || "0.0.0"; +const VALID_FORMATS = ["drawio", "vsdx", "lucid", "lucid-json"]; +const VALID_THEMES = ["light", "dark", "adaptive"]; +const VALID_MARKS = ["omit", "embed"]; +const HEADLESS_ENGINE = `Basalt ${pkgVersion} headless (approximate)`; +const CHROMIUM_LAUNCH_OPTS = { + headless: true, + args: ["--blink-settings=forceAndroidOverlayScrollbar=true", "--disable-partial-raster"], +}; + +function usage() { + return [ + "Usage: basalt-diagram-export <input.json|page.html> [options]", + "", + "Options:", + " --to <list> Comma-separated formats: drawio,vsdx,lucid,lucid-json (default: drawio,vsdx,lucid)", + " --theme <name> light, dark, or adaptive (default: light; adaptive applies to draw.io)", + " --marks <mode> omit or embed (default: omit; embed includes only marks whose manifest terms allow diagram use)", + " --out <path> Output directory (or exact file path for one diagram and one format)", + " --width <px> Target drawing width in CSS pixels (default: 1104)", + " --browser Require headless Chromium + Basalt's engine (fail if Playwright/Chromium is unavailable)", + " --headless Use pure-JS approximate headless layout without launching Chromium", + " -h, --help Show this help", + "", + "Formats:", + " drawio Uncompressed draw.io XML (.drawio).", + " vsdx Microsoft Visio (.vsdx); also use .vsdx to import through Lucid's own screen.", + " lucid Lucid Standard Import (.lucid) for Lucid's REST API only", + " (POST https://api.lucid.co/v1/documents with a token, type x-application/vnd.lucid.standardImport);", + " to import through Lucid's own screen, use .vsdx.", + " lucid-json Plain document.json form of Lucid Standard Import.", + "", + ].join("\n"); +} + +function slug(s) { + return String(s || "") + .replace(/([a-z0-9])([A-Z])/g, "$1-$2") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "diagram"; +} + +function extFor(format) { + if (format === "drawio") return ".drawio"; + if (format === "vsdx") return ".vsdx"; + if (format === "lucid") return ".lucid"; + return ".lucid.json"; +} + +/** Extracts `<script ... data-diagram ...>JSON</script>` blocks from HTML, ignoring comments, textarea, code, pre, and template blocks. */ +export function extractDiagramsFromHtml(html) { + const masked = html + .replace(/<!--[\s\S]*?-->/g, (m) => " ".repeat(m.length)) + .replace(/<(textarea|pre|code|template)\b[^>]*>[\s\S]*?<\/\1>/gi, (m) => " ".repeat(m.length)); + + const out = []; + const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi; + let match; + while ((match = re.exec(masked)) !== null) { + const attrs = match[1] ?? ""; + if (!/(?:^|\s)data-diagram(?:\s|=|$)/i.test(attrs)) continue; + const raw = (match[2] ?? "").trim(); + if (!raw) continue; + let spec; + try { + spec = JSON.parse(raw); + } catch (err) { + throw new Error(`basalt-diagram-export: invalid JSON in <script data-diagram>: ${err.message}`); + } + if (!spec || typeof spec !== "object" || typeof spec.type !== "string") { + throw new Error("basalt-diagram-export: <script data-diagram> must hold a Basalt diagram object with a `type`"); + } + const before = masked.slice(Math.max(0, match.index - 240), match.index); + const figId = before.match(/<figure\b[^>]*\bid=["']([^"']+)["'][^>]*>\s*$/i)?.[1]; + out.push({ + name: slug(figId ? figId.replace(/^fig-/, "") : spec.title || `${spec.type}-${out.length + 1}`), + spec, + }); + } + return out; +} + +/** Reads one or more named diagram specs from a JSON or HTML file. */ +export function readDiagramsFromFile(inputPath) { + const raw = fs.readFileSync(inputPath, "utf8"); + const ext = path.extname(inputPath).toLowerCase(); + const stem = path.basename(inputPath).replace(/(\.body)?\.(html?|json)$/i, ""); + if (ext === ".html" || ext === ".htm") { + const found = extractDiagramsFromHtml(raw); + if (!found.length) throw new Error(`basalt-diagram-export: no <script data-diagram> found in ${inputPath}`); + return deduplicateNames(found); + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch (err) { + throw new Error(`basalt-diagram-export: could not parse JSON in ${inputPath}: ${err.message}`); + } + if (Array.isArray(parsed)) { + const list = parsed.map((spec, idx) => ({ name: slug(spec?.title || `${stem}-${idx + 1}`), spec })); + return deduplicateNames(list); + } + if (parsed && typeof parsed === "object" && typeof parsed.type === "string") { + return [{ name: slug(stem), spec: parsed }]; + } + if (parsed && typeof parsed === "object") { + const entries = Object.entries(parsed) + .filter(([, v]) => v && typeof v === "object" && typeof v.type === "string") + .map(([k, spec]) => ({ name: slug(k), spec })); + if (entries.length) return deduplicateNames(entries); + } + throw new Error(`basalt-diagram-export: ${inputPath} does not hold a Basalt diagram JSON object, array, or map`); +} + +function deduplicateNames(items) { + const seen = new Map(); + return items.map((item) => { + const count = seen.get(item.name) ?? 0; + seen.set(item.name, count + 1); + return count === 0 ? item : { ...item, name: `${item.name}-${count + 1}` }; + }); +} + +/** + * Builds a mark resolver when `--marks embed` is requested. + * Bundled mark ids are gated by `isBundledMarkEmbeddable` (derived from marks/manifest.json terms at build time) + * and read from the packaged `dist/marks/<id>.js` modules. Custom mark file paths (e.g. `{ onLight: "logo.svg" }`) + * are resolved relative to the input file's directory; missing or non-SVG paths warn on stderr rather than vanishing silently. + */ +function createMarkResolver(inputDir) { + const distMarksCache = new Map(); + const fileCache = new Map(); + const warned = new Set(); + + const warnOnce = (msg) => { + if (warned.has(msg)) return; + warned.add(msg); + process.stderr.write(`basalt-diagram-export: warning: ${msg}\n`); + }; + + return (idOrPath, theme) => { + if (!idOrPath) return undefined; + // Bundled mark id (lowercase slug like "aws-ecs-service" or "kubernetes") + if (/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(idOrPath)) { + if (!isBundledMarkEmbeddable(idOrPath)) return undefined; + if (!distMarksCache.has(idOrPath)) { + const file = path.join(pkgRoot, "dist", "marks", `${idOrPath}.js`); + if (!fs.existsSync(file)) { + distMarksCache.set(idOrPath, null); + return undefined; + } + const src = fs.readFileSync(file, "utf8"); + const onLight = src.match(/onLight:\s*"([^"]+)"/)?.[1]; + const onDark = src.match(/onDark:\s*"([^"]+)"/)?.[1]; + distMarksCache.set(idOrPath, onLight ? { onLight, onDark } : null); + } + const entry = distMarksCache.get(idOrPath); + if (!entry) return undefined; + return theme === "dark" ? (entry.onDark ?? entry.onLight) : entry.onLight; + } + + // Custom mark file path relative to the input file (e.g. "logo.svg" or "./marks/logo.svg") + const trimmed = String(idOrPath).trim(); + if (trimmed.startsWith("<svg") || trimmed.startsWith("data:image/svg+xml")) return trimmed; + if (/^https?:\/\//i.test(trimmed)) { + warnOnce(`skipping remote custom mark URL "${trimmed}" (only local SVG files and data URIs can be embedded offline)`); + return undefined; + } + const resolved = path.resolve(inputDir, trimmed); + if (!fileCache.has(resolved)) { + if (!fs.existsSync(resolved)) { + warnOnce(`custom mark file "${trimmed}" not found (looked at ${resolved})`); + fileCache.set(resolved, null); + } else { + const content = fs.readFileSync(resolved, "utf8").trim(); + if (!content.startsWith("<svg")) { + warnOnce(`custom mark file "${trimmed}" is not SVG markup (expected <svg ...>)`); + fileCache.set(resolved, null); + } else { + fileCache.set(resolved, content); + } + } + } + return fileCache.get(resolved) ?? undefined; + }; +} + +function browserUnavailableError(message) { + const err = new Error(message); + err.basaltBrowserUnavailable = true; + return err; +} + +/** Loads Playwright from the caller's project, this package's ancestors, or Node's global/ESM resolution. */ +async function loadPlaywright() { + const roots = [path.join(process.cwd(), "package.json"), path.join(pkgRoot, "package.json")]; + for (const anchor of roots) { + try { + const req = createRequire(anchor); + const pw = req("playwright"); + if (pw?.chromium) return pw; + } catch { + // try next resolution anchor + } + } + try { + const pw = await import("playwright"); + if (pw?.chromium) return pw; + } catch { + // not installed + } + throw browserUnavailableError( + "basalt-diagram-export: exact browser measurement requires Playwright (install with: npm install -D playwright && npx playwright install chromium)", + ); +} + +/** + * Packaged, self-contained headless Chromium measurement harness. + * Uses only files shipped inside `@srasyndicate/basalt/dist` (styles.css, Geist WOFF2 fonts, + * diagram-core.js, and diagram-interop.js) so browser measurement works identically from a packed + * install outside the monorepo as well as inside the repo. + * Each figure is measured alone at (0, 0) so multi-figure files match single-figure exports byte-for-byte. + */ +async function measureInBrowser(items, width) { + const distDir = path.join(pkgRoot, "dist"); + const stylesPath = path.join(distDir, "styles.css"); + const sansFontPath = path.join(distDir, "fonts", "Geist-Variable.woff2"); + const monoFontPath = path.join(distDir, "fonts", "GeistMono-Variable.woff2"); + const corePath = path.join(distDir, "diagram-core.js"); + if (!fs.existsSync(stylesPath) || !fs.existsSync(corePath)) { + throw new Error("basalt-diagram-export: browser measurement requires built dist assets (styles.css and diagram-core.js)"); + } + + const { chromium } = await loadPlaywright(); + + let browser; + try { + browser = await chromium.launch(CHROMIUM_LAUNCH_OPTS); + } catch (err) { + throw browserUnavailableError( + `basalt-diagram-export: could not launch Chromium (${err.message}). If browsers are not installed, run: npx playwright install chromium`, + ); + } + + try { + const measuredBy = `Chromium ${browser.version()}, ${process.platform}, Basalt ${pkgVersion}`; + const stylesCss = fs.readFileSync(stylesPath, "utf8"); + const fontCss = fs.existsSync(sansFontPath) && fs.existsSync(monoFontPath) + ? `@font-face{font-family:"Geist";src:url("data:font/woff2;base64,${fs.readFileSync(sansFontPath).toString("base64")}") format("woff2");font-weight:100 900;font-style:normal}` + + `@font-face{font-family:"Geist Mono";src:url("data:font/woff2;base64,${fs.readFileSync(monoFontPath).toString("base64")}") format("woff2");font-weight:100 900;font-style:normal}` + : ""; + + const entriesJson = JSON.stringify( + items.map((it) => ({ spec: it.spec, placements: it.placements ?? null })), + ).replace(/</g, "\\u003c"); + const harnessHtml = + `<!doctype html><html lang="en" data-theme="light"><head><meta charset="utf-8">` + + `<style>${fontCss}\n${stylesCss}\nhtml,body{margin:0;padding:0;background:var(--basalt-surface-page);color:var(--basalt-text-primary);font-family:var(--basalt-font-family-sans)}</style>` + + `<script>window.process={env:{NODE_ENV:"production"}};</script>` + + `</head><body><main id="host" style="margin:0;padding:0;width:${width}px"></main>` + + `<script type="module">\n` + + `import { buildModel, figureTree, measureFigure, syncAttributes, toHtml } from "https://basalt.local/diagram-core.js";\n` + + `import { readMeasuredExtras } from "https://basalt.local/diagram-interop.js";\n` + + `const entries = ${entriesJson};\n` + + `const targetWidth = ${width};\n` + + `const host = document.getElementById("host");\n` + + `await Promise.all([...document.fonts].map((f) => f.load()));\n` + + `await document.fonts.ready;\n` + + `window.__measureAll = async () => {\n` + + ` const out = [];\n` + + ` for (let idx = 0; idx < entries.length; idx++) {\n` + + ` const { spec, placements } = entries[idx];\n` + + ` const base = "exp-" + idx;\n` + + ` const opts = { prefix: "basalt-diagram", base, hasSource: Boolean(spec.source), hiddenClass: "basalt-visually-hidden" };\n` + + ` const candidates = spec.layout === "auto" && Array.isArray(placements) && placements.length ? placements : [undefined];\n` + + ` const tryMeasure = async (placement, allowWiden) => {\n` + + ` const model = buildModel(spec, { checks: false, placement });\n` + + ` if (model.unplaced) return null;\n` + + ` host.replaceChildren();\n` + + ` host.style.width = targetWidth + "px";\n` + + ` const wrap = document.createElement("div");\n` + + ` wrap.innerHTML = toHtml(figureTree(model, {}, opts), { summary: spec.summary || "", source: spec.source || "" });\n` + + ` const fig = wrap.firstElementChild;\n` + + ` fig.id = base;\n` + + ` host.appendChild(fig);\n` + + ` await document.fonts.ready;\n` + + ` if (!document.fonts.check('600 14px Geist') || !document.fonts.check('12px "Geist Mono"')) {\n` + + ` throw new Error("Geist fonts did not load before measuring figure " + idx);\n` + + ` }\n` + + ` await new Promise((r) => requestAnimationFrame(r));\n` + + ` let widenedTo = null;\n` + + ` const sizeTo = allowWiden ? (least) => { if (least > targetWidth) { widenedTo = Math.ceil(least); host.style.width = widenedTo + "px"; } } : undefined;\n` + + ` const res = measureFigure(fig, model, "basalt-diagram", base, { layout: "drawn" }, (d) => syncAttributes(fig, figureTree(model, d, opts)), undefined, sizeTo);\n` + + ` return { res, extras: readMeasuredExtras(fig, "basalt-diagram"), placement, widenedTo };\n` + + ` };\n` + + ` let chosen = null;\n` + + ` for (const placement of candidates) {\n` + + ` const attempt = await tryMeasure(placement, false);\n` + + ` if (attempt?.res?.dyn?.layout === "drawn" && attempt.res.geo) { chosen = attempt; break; }\n` + + ` }\n` + + ` if (!chosen) {\n` + + ` for (const placement of candidates) {\n` + + ` const attempt = await tryMeasure(placement, true);\n` + + ` if (attempt?.res?.dyn?.layout === "drawn" && attempt.res.geo) { chosen = attempt; break; }\n` + + ` }\n` + + ` }\n` + + ` out.push(chosen ? { geo: chosen.res.geo, extras: chosen.extras, placement: chosen.placement, widenedTo: chosen.widenedTo } : { geo: null, extras: {}, placement: candidates[0], widenedTo: null });\n` + + ` }\n` + + ` return out;\n` + + `};\n` + + `window.__ready = true;\n` + + `</script></body></html>`; + + const context = await browser.newContext({ viewport: { width: Math.max(width + 128, 1280), height: 1200 }, deviceScaleFactor: 1 }); + const page = await context.newPage(); + await page.route("https://basalt.local/**", async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/" || url.pathname === "/index.html") { + await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: harnessHtml }); + return; + } + const rel = url.pathname.replace(/^\/+/, ""); + const candidate = path.resolve(distDir, rel); + if (!candidate.startsWith(distDir + path.sep) || !fs.existsSync(candidate)) { + await route.fulfill({ status: 404, body: "not found" }); + return; + } + const body = fs.readFileSync(candidate); + const ct = candidate.endsWith(".js") + ? "application/javascript; charset=utf-8" + : candidate.endsWith(".css") + ? "text/css; charset=utf-8" + : "application/octet-stream"; + await route.fulfill({ status: 200, contentType: ct, body }); + }); + + const pageErrors = []; + page.on("pageerror", (e) => pageErrors.push(e.message)); + await page.goto("https://basalt.local/index.html", { waitUntil: "load" }); + await page.waitForFunction(() => window.__ready === true, null, { timeout: 30000 }); + const results = await page.evaluate(() => window.__measureAll()); + if (pageErrors.length) { + throw new Error(`basalt-diagram-export: browser page error: ${pageErrors.join("; ")}`); + } + return { measuredBy, results }; + } finally { + await browser.close(); + } +} + +function parseArgs(argv) { + let input = null; + let to = ["drawio", "vsdx", "lucid"]; + let theme = "light"; + let marks = "omit"; + let out = null; + let width = 1104; + let browser = false; + let headless = false; + let help = false; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === "-h" || arg === "--help") { help = true; continue; } + if (arg === "--browser") { browser = true; continue; } + if (arg === "--headless") { headless = true; continue; } + if (arg === "--to") { + const val = argv[++i]; + if (!val) throw new Error("basalt-diagram-export: --to expects a comma-separated list of formats"); + to = val.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean); + for (const f of to) if (!VALID_FORMATS.includes(f)) throw new Error(`basalt-diagram-export: unknown format "${f}" (expected ${VALID_FORMATS.join(", ")})`); + continue; + } + if (arg === "--theme") { + theme = (argv[++i] ?? "").trim().toLowerCase(); + if (!VALID_THEMES.includes(theme)) throw new Error(`basalt-diagram-export: unknown theme "${theme}" (expected ${VALID_THEMES.join(", ")})`); + continue; + } + if (arg === "--marks") { + marks = (argv[++i] ?? "").trim().toLowerCase(); + if (!VALID_MARKS.includes(marks)) throw new Error(`basalt-diagram-export: unknown --marks mode "${marks}" (expected omit or embed)`); + continue; + } + if (arg === "--out") { + out = argv[++i]; + if (!out) throw new Error("basalt-diagram-export: --out expects a directory or file path"); + continue; + } + if (arg === "--width") { + width = Number(argv[++i]); + if (!Number.isFinite(width) || width < 320) throw new Error("basalt-diagram-export: --width must be a number >= 320"); + continue; + } + if (arg.startsWith("-")) throw new Error(`basalt-diagram-export: unknown option "${arg}"`); + if (!input) input = arg; + else throw new Error(`basalt-diagram-export: unexpected argument "${arg}"`); + } + if (browser && headless) { + throw new Error("basalt-diagram-export: --browser and --headless cannot be used together"); + } + const mode = browser ? "browser" : headless ? "headless" : "auto"; + return { input, to, theme, marks, out, width, mode, help }; +} + +async function prepareItems(items) { + const prepared = []; + for (const item of items) { + const { spec } = item; + if (spec.layout === "auto") { + const placed = spec.placement ? spec : await placeAutoDiagram(spec); + const placements = placed.placement + ? (Array.isArray(placed.placement) ? placed.placement : [placed.placement]) + : undefined; + prepared.push({ ...item, spec: placed, placements }); + } else { + prepared.push({ ...item, placements: undefined }); + } + } + return prepared; +} + +async function main() { + let opts; + try { + opts = parseArgs(process.argv.slice(2)); + } catch (err) { + process.stderr.write(`${err.message}\n`); + process.exit(1); + } + if (opts.help || !opts.input) { + process.stdout.write(usage()); + process.exit(opts.help ? 0 : 1); + } + + const inputPath = path.resolve(opts.input); + if (!fs.existsSync(inputPath)) { + process.stderr.write(`basalt-diagram-export: input not found: ${opts.input}\n`); + process.exit(1); + } + + let items; + try { + items = readDiagramsFromFile(inputPath); + } catch (err) { + process.stderr.write(`${err.message}\n`); + process.exit(1); + } + + const looksLikeFileOut = Boolean(opts.out && /\.(drawio|vsdx|lucid|json)$/i.test(opts.out)); + if (looksLikeFileOut) { + if (items.length !== 1 || opts.to.length !== 1) { + process.stderr.write( + `basalt-diagram-export: --out "${opts.out}" looks like a file path, which requires one diagram and one format (pass a directory for multiple outputs)\n`, + ); + process.exit(1); + } + const expectedExt = extFor(opts.to[0]); + if (!opts.out.toLowerCase().endsWith(expectedExt)) { + process.stderr.write( + `basalt-diagram-export: --out "${opts.out}" extension does not match format "${opts.to[0]}" (expected "${expectedExt}")\n`, + ); + process.exit(1); + } + } + const singleFileOut = looksLikeFileOut; + + items = await prepareItems(items); + + const resolveMark = opts.marks === "embed" ? createMarkResolver(path.dirname(inputPath)) : undefined; + let measuredList = null; + let measuredBy = HEADLESS_ENGINE; + if (opts.mode === "headless") { + process.stderr.write("basalt-diagram-export: using approximate headless geometry (--headless)\n"); + } else { + try { + const m = await measureInBrowser(items, opts.width); + measuredList = m.results; + measuredBy = m.measuredBy; + } catch (err) { + if (opts.mode === "browser" || !err?.basaltBrowserUnavailable) throw err; + const detail = String(err.message || "").replace(/^basalt-diagram-export:\s*/i, ""); + const hasAuto = items.some((it) => it.spec.layout === "auto"); + const autoNote = hasAuto ? " (an automatic figure may take another direction if text wraps differently)" : ""; + process.stderr.write( + `basalt-diagram-export: warning: ${detail}; falling back to approximate headless geometry${autoNote}\n`, + ); + } + } + + const outDir = singleFileOut + ? path.dirname(path.resolve(opts.out)) + : path.resolve(opts.out ?? path.dirname(inputPath)); + fs.mkdirSync(outDir, { recursive: true }); + + const written = []; + for (let idx = 0; idx < items.length; idx++) { + const { name, spec, placements } = items[idx]; + const measured = measuredList ? measuredList[idx] : null; + const useMeasured = Boolean(measured?.geo); + const engineLabel = useMeasured ? measuredBy : HEADLESS_ENGINE; + if (measuredList && !useMeasured) { + if (opts.mode === "browser") { + throw new Error(`basalt-diagram-export: "${name}" did not fit drawn in Chromium (--browser)`); + } + process.stderr.write( + `basalt-diagram-export: warning: "${name}" did not fit drawn in Chromium; falling back to approximate headless geometry\n`, + ); + } + if (useMeasured && measured.widenedTo) { + process.stderr.write( + `basalt-diagram-export: note: "${name}" widened to ${measured.widenedTo}px (from --width ${opts.width}) to fit drawn\n`, + ); + } + const baseOpts = { + theme: opts.theme, + marks: opts.marks, + resolveMark, + width: opts.width, + diagramId: name, + placement: measured?.placement ?? placements, + measuredBy: engineLabel, + }; + + for (const format of opts.to) { + let data; + if (useMeasured) { + const res = exportMeasuredDiagram(spec, measured.geo, format, { ...baseOpts, extras: measured.extras }); + data = format === "lucid-json" ? `${JSON.stringify(res, null, 2)}\n` : res; + } else if (format === "drawio") { + data = diagramToDrawio(spec, baseOpts); + } else if (format === "vsdx") { + data = diagramToVsdx(spec, baseOpts); + } else if (format === "lucid") { + data = diagramToLucid(spec, baseOpts); + } else { + data = `${JSON.stringify(diagramToLucidJson(spec, baseOpts), null, 2)}\n`; + } + const outPath = singleFileOut ? path.resolve(opts.out) : path.join(outDir, `${name}${extFor(format)}`); + fs.writeFileSync(outPath, data); + written.push({ path: outPath, bytes: typeof data === "string" ? Buffer.byteLength(data) : data.byteLength, format }); + } + } + + for (const w of written) { + const note = w.format === "lucid" + ? " — Lucid REST API only (POST https://api.lucid.co/v1/documents with a token, type x-application/vnd.lucid.standardImport; use .vsdx to import through Lucid's own screen)" + : ""; + process.stdout.write(`${path.relative(process.cwd(), w.path) || w.path} (${w.bytes} bytes)${note}\n`); + } +} + +function isMain() { + if (!process.argv[1]) return false; + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +if (isMain()) { + main().catch((err) => { + process.stderr.write(`${err.message}\n`); + process.exit(1); + }); +} diff --git a/packages/react/build.mjs b/packages/react/build.mjs index 5073bdf0..38dfe52c 100644 --- a/packages/react/build.mjs +++ b/packages/react/build.mjs @@ -95,6 +95,36 @@ await esbuild.build({ banner: { js: `"use client";` }, }); +// Diagram interop (DECISIONS 311, 314): a subpath outside the index (@srasyndicate/basalt/diagram-interop) built as one +// standalone ESM module so it shares no chunk with still diagrams or any root export (0 bytes added to every root import). +// Embeddable marks and attributions are derived directly from marks/manifest.json's terms at build time, and NODE_ENV is +// defined to "production" so native browser ESM (without a bundler) never hits `process is not defined`. +const marksManifest = JSON.parse(fs.readFileSync(path.join(here, "marks", "manifest.json"), "utf8")); +const embeddableMarks = marksManifest.marks + .filter((m) => !m.unofficial && (m.terms?.quotes ?? []).some((q) => /architectur\w* diagrams?|for your diagrams|Apache-2\.0/i.test(q))) + .map((m) => m.id); +const markAttributions = Object.fromEntries( + marksManifest.marks + .filter((m) => embeddableMarks.includes(m.id) && m.attribution) + .map((m) => [m.id, m.attribution]), +); +await esbuild.build({ + bundle: true, + format: "esm", + platform: "neutral", + target: "es2022", + logLevel: "warning", + entryPoints: [path.join(here, "src/diagram-interop.ts")], + outdir: dist, + external, + plugins: [{ name: "lazy-diagram-layout", setup(build) { build.onResolve({ filter: /^\.\/diagram-layout$/ }, (args) => (args.kind === "dynamic-import" ? { path: "./diagram-layout.js", external: true } : undefined)); } }], + define: { + "process.env.NODE_ENV": '"production"', + __BASALT_EMBEDDABLE_MARKS__: JSON.stringify(JSON.stringify(embeddableMarks)), + __BASALT_MARK_ATTRIBUTIONS__: JSON.stringify(JSON.stringify(markAttributions)), + }, +}); + // 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. @@ -222,7 +252,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", "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")).filter((f) => /\.tsx?$/.test(f) && !f.endsWith(".d.ts") && !["command-panel.tsx", "glyph-flight.tsx", "diagram-motion.tsx", "diagram-motion-core.ts", "diagram-interop.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/<id>, never imported by the index, so an // app pays for the marks it imports and no others. Generated by marks/generate.mjs. @@ -286,7 +316,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", "diagram-viewer.js", "diagram-elk.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-interop.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}`); } diff --git a/packages/react/package.json b/packages/react/package.json index 647c7cb7..86901ad1 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -33,6 +33,10 @@ "types": "./dist/diagram-layout.d.ts", "default": "./dist/diagram-layout.js" }, + "./diagram-interop": { + "types": "./dist/diagram-interop.d.ts", + "default": "./dist/diagram-interop.js" + }, "./marks/*": { "types": "./dist/marks/*.d.ts", "default": "./dist/marks/*.js" @@ -43,8 +47,12 @@ "./components.css": "./dist/components.css", "./fonts.css": "./dist/fonts.css" }, + "bin": { + "basalt-diagram-export": "./bin/basalt-diagram-export.mjs" + }, "files": [ "dist", + "bin", "THIRD-PARTY-MARKS.md", "THIRD-PARTY-NOTICES.md" ], @@ -55,9 +63,15 @@ "test": "node ../../scripts/test-react.mjs" }, "peerDependencies": { + "playwright": ">=1.40.0 <2", "react": ">=19", "react-dom": ">=19" }, + "peerDependenciesMeta": { + "playwright": { + "optional": true + } + }, "dependencies": { "@base-ui/react": "1.9.0", "@phosphor-icons/react": "2.1.10", diff --git a/packages/react/src/diagram-interop.ts b/packages/react/src/diagram-interop.ts new file mode 100644 index 00000000..a0d9451c --- /dev/null +++ b/packages/react/src/diagram-interop.ts @@ -0,0 +1,182 @@ +// @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314, 324, 327) +// Deterministic, zero-dependency exporters from Basalt's diagram model (or a live figure's measured Geo) +// to draw.io (.drawio), Microsoft Visio (.vsdx), and Lucid Standard Import (.lucid and JSON). +// Lives on a separate subpath outside the package index so still diagrams pay zero bytes for it. +import type { DiagramPlacement, DiagramSpec, Geo } from "./diagram-core"; +import { sceneToDrawio } from "./interop/drawio"; +import { sceneToLucid, sceneToLucidJson } from "./interop/lucid"; +import { bundledMarkAttribution, isBundledMarkEmbeddable, layoutHeadless, readMeasuredExtras, sceneFromMeasured } from "./interop/scene"; +import { sceneToVsdx } from "./interop/vsdx"; +import type { + DiagramCardinality, + InteropFormat, + InteropMarkResolver, + InteropMarksMode, + InteropOptions, + InteropScene, + InteropTheme, + LucidBoundingBox, + LucidColorFill, + LucidCustomData, + LucidDocument, + LucidEndpoint, + LucidEndpointStyle, + LucidFieldSize, + LucidImageFill, + LucidLine, + LucidLineText, + LucidPage, + LucidShape, + LucidShapeStyle, + LucidStroke, + LucidSwimLane, + LucidTableCell, + MeasuredBand, + MeasuredExtras, + MeasuredFrame, + MeasuredFrameDivider, + MeasuredGroup, + MeasuredInteropOptions, + MeasuredLane, + SceneBand, + SceneBar, + SceneBox, + SceneEdge, + SceneFrame, + SceneFrameDivider, + SceneGroup, + SceneLabel, + SceneLane, + SceneLifeline, + SceneMark, + SceneNode, + ScenePort, + SceneTableRow, +} from "./interop/types"; + +/** + * Places a `layout: "auto"` diagram through `@srasyndicate/basalt/diagram-layout` (elkjs, loaded on demand) + * and returns a shallow copy of `spec` with `placement` populated. Non-auto or already-placed specs are returned as-is. + */ +export async function placeAutoDiagram(spec: DiagramSpec): Promise<DiagramSpec> { + if (spec.layout !== "auto" || spec.placement) return spec; + if (spec.type !== "architecture" && spec.type !== "flowchart" && spec.type !== "schema") return spec; + const { placeDiagram } = await import("./diagram-layout"); + const order: Array<"right" | "down"> = spec.direction + ? [spec.direction] + : spec.type === "flowchart" + ? ["down", "right"] + : ["right", "down"]; + const input = { + type: spec.type, + nodes: spec.nodes as Array<{ id: string; group?: string }> | undefined, + tables: spec.tables, + edges: spec.edges, + groups: spec.groups, + }; + const placements: DiagramPlacement[] = []; + for (const dir of order) placements.push(await placeDiagram(input, dir)); + return { ...spec, placement: placements }; +} + +/** Exports a Basalt diagram spec directly to uncompressed `.drawio` XML (valid against mxfile-1.0.xsd). */ +export function diagramToDrawio(spec: DiagramSpec, options: InteropOptions = {}): string { + const scene = layoutHeadless(spec, options); + return sceneToDrawio(scene, options.theme ?? "light"); +} + +/** Exports a Basalt diagram spec directly to a deterministic Microsoft Visio `.vsdx` OPC archive. */ +export function diagramToVsdx(spec: DiagramSpec, options: InteropOptions = {}): Uint8Array { + const scene = layoutHeadless(spec, options); + return sceneToVsdx(scene, options.theme ?? "light"); +} + +/** + * Exports a Basalt diagram spec to a deterministic Lucid Standard Import `.lucid` ZIP archive for Lucid's REST API + * (`POST https://api.lucid.co/v1/documents` with a token, type `x-application/vnd.lucid.standardImport`). + * To import through Lucid's own screen, use `.vsdx` (`diagramToVsdx`). + */ +export function diagramToLucid(spec: DiagramSpec, options: InteropOptions = {}): Uint8Array { + const scene = layoutHeadless(spec, options); + return sceneToLucid(scene, options.theme ?? "light"); +} + +/** + * Exports a Basalt diagram spec to the plain JSON form of Lucid Standard Import (`document.json`, for Lucid's REST API; + * to import through Lucid's own screen, use `.vsdx`). + */ +export function diagramToLucidJson(spec: DiagramSpec, options: InteropOptions = {}): LucidDocument { + const scene = layoutHeadless(spec, options); + return sceneToLucidJson(scene, options.theme ?? "light"); +} + +/** + * Exports a live figure's measured `Geo` (from diagram-core's `measureFigure`) to `.drawio`, `.vsdx`, `.lucid` + * (Lucid REST API only: `POST https://api.lucid.co/v1/documents` with a token, type `x-application/vnd.lucid.standardImport`; + * to import through Lucid's own screen, use `.vsdx`), or Lucid JSON. + */ +export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: "drawio", options?: MeasuredInteropOptions): string; +export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: "vsdx" | "lucid", options?: MeasuredInteropOptions): Uint8Array; +export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: "lucid-json", options?: MeasuredInteropOptions): LucidDocument; +export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: InteropFormat, options?: MeasuredInteropOptions): string | Uint8Array | LucidDocument; +export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: InteropFormat, options: MeasuredInteropOptions = {}): string | Uint8Array | LucidDocument { + const scene = sceneFromMeasured(spec, geo, options.extras, options); + const theme = options.theme ?? "light"; + if (format === "drawio") return sceneToDrawio(scene, theme); + if (format === "vsdx") return sceneToVsdx(scene, theme); + if (format === "lucid") return sceneToLucid(scene, theme); + if (format === "lucid-json") return sceneToLucidJson(scene, theme); + throw new Error(`diagram-interop: unknown format "${String(format)}" (expected drawio, vsdx, lucid or lucid-json)`); +} + +export { bundledMarkAttribution, isBundledMarkEmbeddable, layoutHeadless as measureDiagramHeadless, readMeasuredExtras }; + +export type { + DiagramCardinality, + DiagramPlacement, + DiagramSpec, + Geo, + InteropFormat, + InteropMarkResolver, + InteropMarksMode, + InteropOptions, + InteropScene, + InteropTheme, + LucidBoundingBox, + LucidColorFill, + LucidCustomData, + LucidDocument, + LucidEndpoint, + LucidEndpointStyle, + LucidFieldSize, + LucidImageFill, + LucidLine, + LucidLineText, + LucidPage, + LucidShape, + LucidShapeStyle, + LucidStroke, + LucidSwimLane, + LucidTableCell, + MeasuredBand, + MeasuredExtras, + MeasuredFrame, + MeasuredFrameDivider, + MeasuredGroup, + MeasuredInteropOptions, + MeasuredLane, + SceneBand, + SceneBar, + SceneBox, + SceneEdge, + SceneFrame, + SceneFrameDivider, + SceneGroup, + SceneLabel, + SceneLane, + SceneLifeline, + SceneMark, + SceneNode, + ScenePort, + SceneTableRow, +}; diff --git a/packages/react/src/interop/drawio.ts b/packages/react/src/interop/drawio.ts new file mode 100644 index 00000000..64198b1c --- /dev/null +++ b/packages/react/src/interop/drawio.ts @@ -0,0 +1,770 @@ +// Deterministic draw.io (.drawio / mxGraphModel XML) exporter (DECISIONS 311, 314, 324, 327). +// Conforms strictly to mxfile-1.0.xsd: uncompressed XML, no XML comments, positive integer page sizes, +// real parent-child containers (including nested groups and sequence frames), activation bars, +// crow's-foot cardinality arrows, one glued orthogonal edge per Basalt edge, attached edgeLabel children, +// and exact port-snapped inner waypoints so first and last segments are strictly axis-aligned. +import type { DiagramCardinality, Pt } from "../diagram-core"; +import { encodeSvgDataUri, paletteFor, round2, round4, round6, snapRouteToPorts } from "./scene"; +import type { ThemePalette } from "./scene"; +import type { InteropScene, InteropTheme, SceneBox, SceneNode } from "./types"; + +const DRAWIO_CARD: Record<DiagramCardinality, string> = { + one: "ERmandOne", + "zero-or-one": "ERzeroToOne", + "one-or-many": "ERoneToMany", + "zero-or-many": "ERzeroToMany", +}; + +function rowPortY(ptY: number, rowBox: SceneBox): number { + const raw = rowBox.h > 0 ? Math.max(0, Math.min(1, (ptY - rowBox.y) / rowBox.h)) : 0.5; + return Math.abs(raw - 0.5) < 0.05 ? 0.5 : round6(raw); +} + +function escXml(s: string): string { + return String(s) + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, """); +} + +function cellStyle(parts: string[]): string { + return `${parts.join(";")};`; +} + +/** Point along an orthogonal polyline at arc-length fraction t in [0, 1]. */ +function pointAtArcFraction(pts: readonly Pt[], t: number): Pt { + if (pts.length === 0) return { x: 0, y: 0 }; + if (pts.length === 1) return pts[0]!; + const segLen = (a: Pt, b: Pt): number => { + const dx = b.x - a.x, dy = b.y - a.y; + return Math.abs(dx) < 1e-9 || Math.abs(dy) < 1e-9 ? Math.abs(dx) + Math.abs(dy) : Math.sqrt(dx * dx + dy * dy); + }; + let total = 0; + for (let i = 0; i < pts.length - 1; i++) total += segLen(pts[i]!, pts[i + 1]!); + if (total <= 0) return pts[0]!; + const target = Math.max(0, Math.min(1, t)) * total; + let acc = 0; + for (let i = 0; i < pts.length - 1; i++) { + const a = pts[i]!; + const b = pts[i + 1]!; + const seg = segLen(a, b); + if (acc + seg >= target && seg > 0) { + const f = (target - acc) / seg; + return { x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }; + } + acc += seg; + } + return pts[pts.length - 1]!; +} + +/** Wraps two distinct light/dark ground SVG forms into one SVG switching on prefers-color-scheme. */ +function adaptiveMarkSvg(lightModeSvg: string, darkModeSvg: string): string { + const inner = (raw: string) => raw.replace(/^<svg\b/, '<svg width="16" height="16"'); + return ( + `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">` + + `<style>.d{display:none}@media(prefers-color-scheme:dark){.l{display:none}.d{display:inline}}</style>` + + `<g class="l">${inner(lightModeSvg)}</g>` + + `<g class="d">${inner(darkModeSvg)}</g>` + + `</svg>` + ); +} + +export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light"): string { + const adaptive = theme === "adaptive"; + const singleTheme: "light" | "dark" = theme === "dark" ? "dark" : "light"; + const L = paletteFor("light"); + const D = paletteFor("dark"); + const P = singleTheme === "dark" ? D : L; + const col = (key: keyof ThemePalette): string => (adaptive ? `light-dark(${L[key]},${D[key]})` : P[key]); + + const pad = scene.pad; + const pageW = Math.max(1, Math.ceil(scene.width + pad * 2)); + const pageH = Math.max(1, Math.ceil(scene.height + pad * 2)); + + const cells: string[] = []; + cells.push(` <mxCell id="0"/>`); + cells.push(` <mxCell id="1" parent="0"/>`); + + // Exact emitted world boxes for every connectable vertex (used to snap waypoints in draw.io's own coordinates) + const worldBoxByCell = new Map<string, SceneBox>(); + + // 1. Groups (architecture containers, outer-first so nested depth-2 groups parent inside depth-1) + const groupBoxes = new Map<string, SceneBox>(); + for (const g of scene.groups) { + const worldBox: SceneBox = { x: round2(g.box.x + pad), y: round2(g.box.y + pad), w: round2(g.box.w), h: round2(g.box.h) }; + groupBoxes.set(g.id, worldBox); + const parentBox = g.parent ? groupBoxes.get(g.parent) : undefined; + const parentId = parentBox ? `group-${g.parent}` : "1"; + const relX = round2(worldBox.x - (parentBox ? parentBox.x : 0)); + const relY = round2(worldBox.y - (parentBox ? parentBox.y : 0)); + const arcSize = g.depth > 1 ? 16 : 24; + const style = cellStyle([ + "rounded=1", + "absoluteArcSize=1", + `arcSize=${arcSize}`, + "whiteSpace=wrap", + "html=1", + "container=1", + "collapsible=0", + "recursiveResize=0", + "pointerEvents=0", + "fillColor=none", + `strokeColor=${col("structure")}`, + "strokeWidth=1", + "dashed=1", + "dashPattern=4 4", + "verticalAlign=top", + "align=left", + "spacingTop=6", + "spacingLeft=10", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=12", + "fontStyle=0", + ]); + cells.push( + ` <mxCell id="group-${escXml(g.id)}" value="${escXml(g.label)}" style="${escXml(style)}" vertex="1" connectable="0" parent="${escXml(parentId)}">\n` + + ` <mxGeometry x="${relX}" y="${relY}" width="${worldBox.w}" height="${worldBox.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + // 2. Data-flow horizontal lane containers (horizontal text in the 120px left label column) + const laneBoxes = new Map<string, SceneBox>(); + for (let k = 0; k < scene.lanes.length; k++) { + const lane = scene.lanes[k]!; + const box: SceneBox = { x: round2(lane.box.x + pad), y: round2(lane.box.y + pad), w: round2(lane.box.w), h: round2(lane.box.h) }; + laneBoxes.set(lane.id, box); + const rightSpace = Math.max(0, round2(box.w - lane.labelWidth)); + const style = cellStyle([ + "rounded=0", + "whiteSpace=wrap", + "html=1", + "container=1", + "collapsible=0", + "recursiveResize=0", + "pointerEvents=0", + "fillColor=none", + `strokeColor=${col("divider")}`, + "strokeWidth=1", + "align=left", + "verticalAlign=middle", + "spacingLeft=4", + `spacingRight=${rightSpace}`, + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + "fontStyle=0", + ]); + cells.push( + ` <mxCell id="lane-${escXml(lane.id)}" value="${escXml(lane.label)}" style="${escXml(style)}" vertex="1" connectable="0" parent="1">\n` + + ` <mxGeometry x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + // 3. Sequence lifelines, phase bands, combined frames, and activation bars + for (const lf of scene.lifelines) { + const lx = round2(lf.x + pad); + const y1 = round2(lf.y1 + pad); + const h = round2(Math.max(1, lf.y2 - lf.y1)); + // Unrotated partialRectangle with left=1 only draws a crisp vertical dashed stroke at x = box.x (= lx). + // Never use direction=south on a connectable lifeline: mxGraph rotates exitY/entryY by 90 degrees. + const box: SceneBox = { x: lx, y: y1, w: 2, h }; + const cellId = `life-${lf.participantId}`; + worldBoxByCell.set(cellId, box); + const style = cellStyle([ + "shape=partialRectangle", + "top=0", + "bottom=0", + "right=0", + "left=1", + "html=1", + "fillColor=none", + `strokeColor=${col("structure")}`, + "strokeWidth=1", + "dashed=1", + "dashPattern=4 4", + ]); + cells.push( + ` <mxCell id="${escXml(cellId)}" value="" style="${escXml(style)}" vertex="1" parent="1">\n` + + ` <mxGeometry x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) { + const band = scene.bands[bIdx]!; + const bx = round2(pad); + const by = round2(band.y + pad); + const bw = round2(band.w); + const bh = round2(band.h); + const style = cellStyle([ + "shape=line", + "html=1", + "fillColor=none", + `strokeColor=${col("divider")}`, + "strokeWidth=1", + "align=center", + "verticalAlign=middle", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + "fontStyle=0", + "labelBackgroundColor=default", + "defaultLabelBackgroundColor=page", + ]); + cells.push( + ` <mxCell id="band-${bIdx}" value="${escXml(band.text)}" style="${escXml(style)}" vertex="1" connectable="0" parent="1">\n` + + ` <mxGeometry x="${bx}" y="${by}" width="${bw}" height="${bh}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + // 3b. Sequence frames (opt/loop/alt containers with corner operator tab and dashed branch dividers) + const frameBoxes = new Map<string, SceneBox>(); + for (const f of scene.frames) { + const worldBox: SceneBox = { x: round2(f.box.x + pad), y: round2(f.box.y + pad), w: round2(f.box.w), h: round2(f.box.h) }; + frameBoxes.set(f.id, worldBox); + const parentBox = f.parentId ? frameBoxes.get(f.parentId) : undefined; + const parentId = parentBox ? `frame-${f.parentId}` : "1"; + const relX = round2(worldBox.x - (parentBox ? parentBox.x : 0)); + const relY = round2(worldBox.y - (parentBox ? parentBox.y : 0)); + const frameId = `frame-${f.id}`; + const frameStyle = cellStyle([ + "rounded=1", + "absoluteArcSize=1", + `arcSize=${f.depth > 1 ? 8 : 24}`, + "whiteSpace=wrap", + "html=1", + "container=1", + "collapsible=0", + "recursiveResize=0", + "pointerEvents=0", + "fillColor=none", + `strokeColor=${col("structure")}`, + "strokeWidth=1", + ]); + cells.push( + ` <mxCell id="${escXml(frameId)}" value="" style="${escXml(frameStyle)}" vertex="1" connectable="0" parent="${escXml(parentId)}">\n` + + ` <mxGeometry x="${relX}" y="${relY}" width="${worldBox.w}" height="${worldBox.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + + const tabRelX = round2(f.tabBox.x + pad - worldBox.x); + const tabRelY = round2(f.tabBox.y + pad - worldBox.y); + const tabW = round2(f.tabBox.w); + const tabH = round2(f.tabBox.h); + const tabStyle = cellStyle([ + "shape=partialRectangle", + "top=0", + "left=0", + "right=1", + "bottom=1", + "rounded=0", + "html=1", + `fillColor=${col("page")}`, + `strokeColor=${col("structure")}`, + "strokeWidth=1", + "align=center", + "verticalAlign=middle", + `fontColor=${col("textPrimary")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=12", + "fontStyle=1", + ]); + cells.push( + ` <mxCell id="frame-tab-${escXml(f.id)}" value="${escXml(f.operator)}" style="${escXml(tabStyle)}" vertex="1" connectable="0" parent="${escXml(frameId)}">\n` + + ` <mxGeometry x="${tabRelX}" y="${tabRelY}" width="${tabW}" height="${tabH}" as="geometry"/>\n` + + ` </mxCell>`, + ); + + if (f.label) { + const lb = f.labelBox ?? { + x: round2(f.tabBox.x + f.tabBox.w + 6), + y: round2(f.tabBox.y + 4), + w: round2(Math.min(Math.max(16, f.box.w - (f.tabBox.w + 12)), f.label.length * 7 + 12)), + h: 16, + }; + const lblX = round2(lb.x + pad - worldBox.x); + const lblY = round2(lb.y + pad - worldBox.y - 1); + const lblW = round2(lb.w); + const lblH = round2(Math.max(18, lb.h + 2)); + const lblStyle = cellStyle([ + "text", + "html=1", + "strokeColor=none", + `fillColor=${col("page")}`, + "align=left", + "verticalAlign=middle", + "spacing=0", + "spacingLeft=4", + "spacingRight=4", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + ]); + const lblVal = `<span style="font-weight:500;">${escXml(f.label)}</span>`; + cells.push( + ` <mxCell id="frame-label-${escXml(f.id)}" value="${escXml(lblVal)}" style="${escXml(lblStyle)}" vertex="1" connectable="0" parent="${escXml(frameId)}">\n` + + ` <mxGeometry x="${lblX}" y="${lblY}" width="${lblW}" height="${lblH}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + f.dividers.forEach((div, k) => { + const divRelY = round2(div.y + pad - worldBox.y); + const divStyle = cellStyle([ + "shape=line", + "html=1", + "fillColor=none", + `strokeColor=${col("structure")}`, + "strokeWidth=1", + "dashed=1", + "dashPattern=4 4", + ]); + cells.push( + ` <mxCell id="frame-div-${escXml(f.id)}-${k}" value="" style="${escXml(divStyle)}" vertex="1" connectable="0" parent="${escXml(frameId)}">\n` + + ` <mxGeometry x="0" y="${round2(divRelY - 1)}" width="${worldBox.w}" height="2" as="geometry"/>\n` + + ` </mxCell>`, + ); + if (div.label || f.operator === "alt") { + const eb = div.labelBox ?? { + x: round2(f.box.x + 6), + y: round2(div.y + Math.max(0, (div.h - 16) / 2)), + w: round2(Math.min(Math.max(16, f.box.w - 12), ((f.operator === "alt" ? 4 : 0) + div.label.length) * 7 + 16)), + h: 16, + }; + const elseX = round2(eb.x + pad - worldBox.x); + const elseY = round2(eb.y + pad - worldBox.y - 1); + const elseW = round2(eb.w); + const elseH = round2(Math.max(18, eb.h + 2)); + const elseVal = f.operator === "alt" + ? `<span style="font-family:Geist Mono,Consolas,monospace;font-weight:400;${adaptive ? "opacity:0.65;" : `color:${P.textTertiary};`}">else</span>` + + (div.label ? ` <span style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-weight:500;${adaptive ? "opacity:0.8;" : `color:${P.textSecondary};`}">${escXml(div.label)}</span>` : "") + : `<span style="font-weight:500;">${escXml(div.label)}</span>`; + const elseStyle = cellStyle([ + "text", + "html=1", + "strokeColor=none", + `fillColor=${col("page")}`, + "align=left", + "verticalAlign=middle", + "spacing=0", + "spacingLeft=4", + "spacingRight=4", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + ]); + cells.push( + ` <mxCell id="frame-else-${escXml(f.id)}-${k}" value="${escXml(elseVal)}" style="${escXml(elseStyle)}" vertex="1" connectable="0" parent="${escXml(frameId)}">\n` + + ` <mxGeometry x="${elseX}" y="${elseY}" width="${elseW}" height="${elseH}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + }); + } + + // 3c. Sequence activation bars (drawn over lifelines and frames, under message connectors) + for (const bar of scene.bars) { + const box: SceneBox = { x: round2(bar.box.x + pad), y: round2(bar.box.y + pad), w: round2(bar.box.w), h: round2(bar.box.h) }; + worldBoxByCell.set(bar.id, box); + const barStyle = cellStyle([ + "rounded=1", + "absoluteArcSize=1", + "arcSize=4", + "html=1", + `fillColor=${col("cardFill")}`, + `strokeColor=${col("structure")}`, + "strokeWidth=1", + ]); + cells.push( + ` <mxCell id="${escXml(bar.id)}" value="" style="${escXml(barStyle)}" vertex="1" parent="1">\n` + + ` <mxGeometry x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + // 4. Nodes (cards, flowchart shapes, participants, schema tables with row cells) + const formatCardHtml = (n: SceneNode): string => { + const isFocal = n.focal; + const nameColor = isFocal ? P.focalInk : P.textPrimary; + const kindColor = isFocal ? P.focalQuiet : P.textTertiary; + const detailColor = isFocal ? P.focalQuiet : P.textSecondary; + const padMark = n.mark + ? (n.shape === "participant" ? "padding-left:24px;padding-right:24px;" : "padding-right:24px;") + : ""; + + if (n.shape === "decision") { + return adaptive + ? `<div style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;line-height:1.35;text-align:center;">${escXml(n.name)}</div>` + : `<div style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;line-height:1.35;text-align:center;color:${nameColor};">${escXml(n.name)}</div>`; + } + const align = n.shape === "terminal" || n.shape === "participant" ? "text-align:center;" : ""; + const kindSpan = n.kind + ? adaptive + ? `<div style="font-family:Geist Mono,Consolas,monospace;font-size:11px;line-height:1.35;opacity:0.65;${align}${padMark}">${escXml(n.kind)}</div>` + : `<div style="font-family:Geist Mono,Consolas,monospace;font-size:11px;line-height:1.35;color:${kindColor};${align}${padMark}">${escXml(n.kind)}</div>` + : ""; + const namePad = !n.kind ? padMark : ""; + const nameSpan = adaptive + ? `<div style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-size:14px;font-weight:600;line-height:1.35;${align}${namePad}">${escXml(n.name)}</div>` + : `<div style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-size:14px;font-weight:600;line-height:1.35;color:${nameColor};${align}${namePad}">${escXml(n.name)}</div>`; + const detailFont = n.detailMono ? "Geist Mono,Consolas,monospace" : "Geist,Inter,Helvetica,Arial,sans-serif"; + const detailSpan = n.detail + ? adaptive + ? `<div style="font-family:${detailFont};font-size:12px;line-height:1.35;opacity:0.78;margin-top:2px;${align}">${escXml(n.detail)}</div>` + : `<div style="font-family:${detailFont};font-size:12px;line-height:1.35;color:${detailColor};margin-top:2px;${align}">${escXml(n.detail)}</div>` + : ""; + return `${kindSpan}${nameSpan}${detailSpan}`; + }; + + for (const n of scene.nodes) { + const worldBox: SceneBox = { x: round2(n.box.x + pad), y: round2(n.box.y + pad), w: round2(n.box.w), h: round2(n.box.h) }; + let parentId = "1"; + let parentBox: SceneBox | undefined; + if (n.group && groupBoxes.has(n.group)) { + parentId = `group-${n.group}`; + parentBox = groupBoxes.get(n.group); + } else if (n.laneId && laneBoxes.has(n.laneId)) { + parentId = `lane-${n.laneId}`; + parentBox = laneBoxes.get(n.laneId); + } + const relX = round2(worldBox.x - (parentBox ? parentBox.x : 0)); + const relY = round2(worldBox.y - (parentBox ? parentBox.y : 0)); + const cellId = `node-${n.id}`; + worldBoxByCell.set(cellId, worldBox); + + const isFocal = n.focal; + const fill = isFocal ? col("focalFill") : col("cardFill"); + const stroke = isFocal + ? col("focalBorder") + : scene.type === "flowchart" + ? col("structure") + : col("cardBorder"); + + if (n.shape === "table") { + // Schema table: container vertex with header + child column row vertices so FK edges glue straight to row cells + const headerH = n.headerH ?? 37; + const style = cellStyle([ + "swimlane", + "horizontal=1", + `startSize=${headerH}`, + "collapsible=0", + "recursiveResize=0", + "rounded=1", + "absoluteArcSize=1", + "arcSize=16", + "whiteSpace=wrap", + "html=1", + `fillColor=${fill}`, + `swimlaneFillColor=${fill}`, + `strokeColor=${stroke}`, + "strokeWidth=1", + `fontColor=${isFocal ? col("focalInk") : col("textPrimary")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=14", + "fontStyle=1", + "align=left", + "spacingLeft=12", + ]); + cells.push( + ` <mxCell id="${escXml(cellId)}" value="${escXml(n.name)}" style="${escXml(style)}" vertex="1" parent="${escXml(parentId)}">\n` + + ` <mxGeometry x="${relX}" y="${relY}" width="${worldBox.w}" height="${worldBox.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + + for (const row of n.rows ?? []) { + const rowCellId = `row-${n.id}-${row.index}`; + const rowRelY = round2(row.y); + const rowH = round2(row.h); + const rowWorld: SceneBox = { x: worldBox.x, y: round2(worldBox.y + rowRelY), w: worldBox.w, h: rowH }; + worldBoxByCell.set(rowCellId, rowWorld); + + const innerW = Math.max(40, round2(worldBox.w - 28)); + const rightWord = row.refTable ? `→ ${row.refTable}` : row.type ?? ""; + const keyCss = adaptive + ? "opacity:0.65;" + : `color:${isFocal ? P.focalQuiet : P.textTertiary};`; + const nameCss = adaptive ? "" : `color:${isFocal ? P.focalInk : P.textPrimary};`; + const typeCss = adaptive + ? `opacity:${row.refTable ? "0.78" : "0.65"};` + : `color:${isFocal ? P.focalQuiet : row.refTable ? P.textSecondary : P.textTertiary};`; + const rowHtml = + `<table style="width:${innerW}px;border-collapse:collapse;font-family:Geist Mono,Consolas,monospace;font-size:12px;line-height:1.35;">` + + `<tr>` + + `<td style="width:24px;padding:0;text-align:left;white-space:nowrap;${keyCss}">${row.key ? escXml(row.key) : ""}</td>` + + `<td style="padding:0 6px 0 0;text-align:left;white-space:nowrap;${nameCss}">${escXml(row.name)}</td>` + + `<td style="padding:0;text-align:right;white-space:nowrap;${typeCss}">${escXml(rightWord)}</td>` + + `</tr></table>`; + const rowStyle = cellStyle([ + "text", + "html=1", + "whiteSpace=wrap", + "overflow=hidden", + "strokeColor=none", + "fillColor=none", + "align=left", + "verticalAlign=middle", + "spacingLeft=12", + "spacingRight=12", + "spacingTop=0", + "spacingBottom=0", + `fontColor=${isFocal ? col("focalInk") : col("textPrimary")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=12", + ]); + cells.push( + ` <mxCell id="${escXml(rowCellId)}" value="${escXml(rowHtml)}" style="${escXml(rowStyle)}" vertex="1" parent="${escXml(cellId)}">\n` + + ` <mxGeometry x="0" y="${rowRelY}" width="${worldBox.w}" height="${rowH}" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + + if (n.more) { + const lastRow = n.rows?.[n.rows.length - 1]; + const moreY = round2(lastRow ? lastRow.y + lastRow.h + 2 : headerH + 4); + const moreStyle = cellStyle([ + "text", + "html=1", + "strokeColor=none", + "fillColor=none", + "align=left", + "verticalAlign=middle", + "spacingLeft=12", + `fontColor=${isFocal ? col("focalQuiet") : col("textTertiary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + ]); + cells.push( + ` <mxCell id="more-${escXml(n.id)}" value="${escXml(`+ ${n.more} more`)}" style="${escXml(moreStyle)}" vertex="1" connectable="0" parent="${escXml(cellId)}">\n` + + ` <mxGeometry x="0" y="${moreY}" width="${worldBox.w}" height="20" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + continue; + } + + const shapeParts: string[] = []; + if (n.shape === "decision") { + shapeParts.push("rhombus", "perimeter=rhombusPerimeter", "whiteSpace=wrap", "html=1", "align=center", "verticalAlign=middle", "spacingLeft=10", "spacingRight=10"); + } else if (n.shape === "terminal") { + shapeParts.push("rounded=1", "arcSize=50", "whiteSpace=wrap", "html=1", "align=center", "verticalAlign=middle", "spacingLeft=16", "spacingRight=16", "spacingTop=8", "spacingBottom=8"); + } else if (n.shape === "participant") { + shapeParts.push("rounded=1", "absoluteArcSize=1", "arcSize=16", "whiteSpace=wrap", "html=1", "align=center", "verticalAlign=middle", "spacingLeft=12", "spacingRight=12", "spacingTop=8", "spacingBottom=8"); + } else { + shapeParts.push("rounded=1", "absoluteArcSize=1", "arcSize=16", "whiteSpace=wrap", "html=1", "align=left", "verticalAlign=middle", "spacingLeft=12", "spacingRight=12", "spacingTop=8", "spacingBottom=8"); + } + shapeParts.push( + `fillColor=${fill}`, + `strokeColor=${stroke}`, + "strokeWidth=1", + `fontColor=${isFocal ? col("focalInk") : col("textPrimary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=14", + ); + + cells.push( + ` <mxCell id="${escXml(cellId)}" value="${escXml(formatCardHtml(n))}" style="${escXml(cellStyle(shapeParts))}" vertex="1" parent="${escXml(parentId)}">\n` + + ` <mxGeometry x="${relX}" y="${relY}" width="${worldBox.w}" height="${worldBox.h}" as="geometry"/>\n` + + ` </mxCell>`, + ); + + // Embedded service mark (only when marks: "embed" and allowed by manifest terms) + if (n.mark) { + // Focal card uses the opposite theme's mark form because its fill is inverted. + const lightModeSvg = isFocal ? n.mark.svgDark : n.mark.svgLight; + const darkModeSvg = isFocal ? n.mark.svgLight : n.mark.svgDark; + const svg = adaptive && lightModeSvg !== darkModeSvg + ? adaptiveMarkSvg(lightModeSvg, darkModeSvg) + : singleTheme === "dark" + ? darkModeSvg + : lightModeSvg; + const uri = encodeSvgDataUri(svg); + const mx = round2(Math.max(4, worldBox.w - 12 - 16)); + const markStyle = cellStyle([ + "shape=image", + "verticalLabelPosition=bottom", + "verticalAlign=top", + "imageAspect=1", + "aspect=fixed", + "strokeColor=none", + "fillColor=none", + `image=${uri}`, + ]); + cells.push( + ` <mxCell id="mark-${escXml(n.id)}" value="" style="${escXml(markStyle)}" vertex="1" connectable="0" parent="${escXml(cellId)}">\n` + + ` <mxGeometry x="${mx}" y="10" width="16" height="16" as="geometry"/>\n` + + ` </mxCell>`, + ); + } + } + + // 5. Edges: ONE glued orthogonal mxCell per Basalt edge, parent="1" so waypoints live in page coordinates + for (const e of scene.edges) { + const srcCellId = e.sequence + ? (e.fromBarId && worldBoxByCell.has(e.fromBarId) ? e.fromBarId : `life-${e.from}`) + : e.fk && e.fromRow !== undefined && worldBoxByCell.has(`row-${e.from}-${e.fromRow}`) + ? `row-${e.from}-${e.fromRow}` + : `node-${e.from}`; + const dstCellId = e.sequence + ? (e.toBarId && worldBoxByCell.has(e.toBarId) ? e.toBarId : `life-${e.to}`) + : e.fk && e.toRow !== undefined && worldBoxByCell.has(`row-${e.to}-${e.toRow}`) + ? `row-${e.to}-${e.toRow}` + : `node-${e.to}`; + + const srcBox = worldBoxByCell.get(srcCellId); + const dstBox = worldBoxByCell.get(dstCellId); + if (!srcBox || !dstBox) continue; + + // Exact exit/entry fractional ports on the referenced cell + const exitX = e.sequence && srcCellId.startsWith("life-") ? 0 : round6(e.fromPort.x); + const exitY = e.fk && srcCellId.startsWith("row-") + ? rowPortY((e.pts[0]?.y ?? 0) + pad, srcBox) + : round6(e.fromPort.y); + const entryX = e.sequence && dstCellId.startsWith("life-") ? 0 : round6(e.toPort.x); + const entryY = e.fk && dstCellId.startsWith("row-") + ? rowPortY((e.pts[e.pts.length - 1]?.y ?? 0) + pad, dstBox) + : round6(e.toPort.y); + + // Compute exact port coordinates in draw.io's page coordinates and snap waypoints to them + const startPt: Pt = { x: round2(srcBox.x + exitX * srcBox.w), y: round2(srcBox.y + exitY * srcBox.h) }; + const endPt: Pt = { x: round2(dstBox.x + entryX * dstBox.w), y: round2(dstBox.y + entryY * dstBox.h) }; + const rawPts: Pt[] = e.pts.map((p) => ({ x: round2(p.x + pad), y: round2(p.y + pad) })); + const snapped = snapRouteToPorts(rawPts, startPt, endPt, e.fromPort.side, e.toPort.side); + + const isMain = e.kind === "main"; + const isDashed = e.kind === "dashed"; + const strokeColor = isMain ? col("edgeMain") : col("edgePlain"); + const strokeWidth = isMain ? 2 : 1; + const arrowParts = e.card + ? [ + `startArrow=${DRAWIO_CARD[e.card.from]}`, + "startFill=0", + "startSize=10", + `endArrow=${DRAWIO_CARD[e.card.to]}`, + "endFill=0", + "endSize=10", + ] + : [ + `endArrow=${e.openTip ? "open" : "block"}`, + `endFill=${e.openTip ? 0 : 1}`, + "endSize=6", + ...(e.fk ? ["startArrow=oval", "startFill=1", "startSize=6"] : ["startArrow=none", "startFill=0"]), + ]; + + const styleParts = [ + e.sequence ? "edgeStyle=none" : "edgeStyle=orthogonalEdgeStyle", + "rounded=1", + "absoluteArcSize=1", + `arcSize=${e.sequence && e.from === e.to ? 8 : 16}`, + ...(e.sequence ? [] : ["orthogonalLoop=1", "jettySize=auto"]), + "html=1", + `strokeColor=${strokeColor}`, + `strokeWidth=${strokeWidth}`, + ...arrowParts, + `exitX=${exitX}`, + `exitY=${exitY}`, + "exitDx=0", + "exitDy=0", + "exitPerimeter=0", + `entryX=${entryX}`, + `entryY=${entryY}`, + "entryDx=0", + "entryDy=0", + "entryPerimeter=0", + "jumpStyle=gap", + "jumpSize=6", + `fontColor=${col("edgePlain")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=12", + "labelBackgroundColor=default", + "defaultLabelBackgroundColor=page", + ]; + if (isDashed) styleParts.push("dashed=1", "dashPattern=6 4"); + + const innerPts = snapped.slice(1, -1); + const ptsXml = innerPts.length + ? `\n <Array as="points">\n` + + innerPts.map((p) => ` <mxPoint x="${round2(p.x)}" y="${round2(p.y)}"/>`).join("\n") + + `\n </Array>` + : ""; + + const edgeId = `edge-${e.index}`; + cells.push( + ` <mxCell id="${edgeId}" value="" style="${escXml(cellStyle(styleParts))}" edge="1" parent="1" source="${escXml(srcCellId)}" target="${escXml(dstCellId)}">\n` + + ` <mxGeometry relative="1" as="geometry">${ptsXml}\n` + + ` </mxGeometry>\n` + + ` </mxCell>`, + ); + + if (e.label) { + const relX = round4(e.label.t * 2 - 1); + // Position labels via screen-space offset from the exact point at arc-fraction t (never edge-normal y, + // which flips sign on right-to-left edges). + const ptAtT = pointAtArcFraction(snapped, e.label.t); + const labelCx = e.label.box.x + pad + e.label.box.w / 2; + const labelCy = e.label.box.y + pad + e.label.box.h / 2; + const offX = e.label.on ? 0 : round2(labelCx - ptAtT.x); + const offY = e.label.on ? 0 : round2(labelCy - ptAtT.y); + const offsetPt = offX === 0 && offY === 0 + ? ` <mxPoint as="offset"/>` + : ` <mxPoint x="${offX}" y="${offY}" as="offset"/>`; + const lblBg = e.label.on || e.sequence + ? "labelBackgroundColor=default;defaultLabelBackgroundColor=page" + : "labelBackgroundColor=none"; + const mainTextHtml = escXml(e.label.text).replace(/\n/g, "<br/>"); + const lblValue = e.label.note + ? `<div style="font-family:Geist Mono,Consolas,monospace;font-size:12px;line-height:1.35;text-align:center;">${mainTextHtml}</div>` + + `<div style="font-family:Geist,Inter,Helvetica,Arial,sans-serif;font-size:11px;line-height:1.3;text-align:center;${adaptive ? "opacity:0.65;" : `color:${P.textTertiary};`}">${escXml(e.label.note)}</div>` + : mainTextHtml; + const lblStyle = cellStyle([ + "edgeLabel", + "html=1", + "align=center", + "verticalAlign=middle", + "resizable=0", + "points=[]", + `fontColor=${e.sequence ? col("textPrimary") : col("edgePlain")}`, + "fontFamily=Geist Mono, Consolas, monospace", + "fontSize=12", + lblBg, + ]); + cells.push( + ` <mxCell id="label-${e.index}" value="${escXml(lblValue)}" style="${escXml(lblStyle)}" vertex="1" connectable="0" parent="${edgeId}">\n` + + ` <mxGeometry x="${relX}" y="0" relative="1" as="geometry">\n` + + `${offsetPt}\n` + + ` </mxGeometry>\n` + + ` </mxCell>`, + ); + } + } + + const attributions: string[] = []; + for (const n of scene.nodes) { + if (n.mark?.attribution && !attributions.includes(n.mark.attribution)) { + attributions.push(n.mark.attribution); + } + } + const agentParts: string[] = []; + if (scene.measuredBy) agentParts.push(`Basalt Diagram Exporter (${scene.measuredBy})`); + if (attributions.length) agentParts.push(attributions.join(" ")); + const agentAttr = agentParts.length ? ` agent="${escXml(agentParts.join(" — "))}"` : ""; + + const bgAttr = adaptive ? "" : ` background="${P.page}"`; + const adaptiveAttr = adaptive ? ` adaptiveColors="auto"` : ` adaptiveColors="none"`; + + return ( + `<mxfile compressed="false"${agentAttr}>\n` + + ` <diagram id="${escXml(scene.id)}" name="${escXml(scene.title || scene.id)}">\n` + + ` <mxGraphModel dx="0" dy="0" grid="1" gridSize="8" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="${pageW}" pageHeight="${pageH}" math="0" shadow="0"${bgAttr}${adaptiveAttr}>\n` + + ` <root>\n` + + `${cells.join("\n")}\n` + + ` </root>\n` + + ` </mxGraphModel>\n` + + ` </diagram>\n` + + `</mxfile>\n` + ); +} diff --git a/packages/react/src/interop/lucid.ts b/packages/react/src/interop/lucid.ts new file mode 100644 index 00000000..cfc5385a --- /dev/null +++ b/packages/react/src/interop/lucid.ts @@ -0,0 +1,573 @@ +// Deterministic Lucid Standard Import (.lucid ZIP + document.json) exporter (DECISIONS 311, 314, 324, 327). +// Conforms to https://developer.lucid.co/docs/standard-import: +// - documentSettings.units = "px", rounding = 2 * px radius, explicit pt font-size on every text run +// - nested roundedRectangleContainer (assistedLayout: false, magnetize: true), swimLanes, table, decision, terminator +// - sequence frames, dashed branch dividers, activation bars, and crow's-foot cardinality endpoints +// - single glued lines (shapeEndpoint / lineEndpoint) with elbowControlPoints snapped in Lucid units +import type { DiagramCardinality, Pt } from "../diagram-core"; +import { paletteFor, round2, round6, snapRouteToPorts } from "./scene"; +import type { + InteropScene, + InteropTheme, + LucidCustomData, + LucidDocument, + LucidEndpoint, + LucidEndpointStyle, + LucidLine, + LucidLineText, + LucidShape, + LucidTableCell, + SceneBox, +} from "./types"; +import { makeDeterministicZip } from "./zip"; +import type { ZipEntry } from "./zip"; + +const LUCID_CARD: Record<DiagramCardinality, LucidEndpointStyle> = { + one: "exactlyOne", + "zero-or-one": "zeroOrOne", + "one-or-many": "oneOrMore", + "zero-or-many": "zeroOrMore", +}; + +function escHtml(s: string): string { + return String(s) + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, """); +} + +function lucidId(prefix: string, raw: string): string { + return `${prefix}_${raw.replace(/[^a-zA-Z0-9_]/g, "_")}`; +} + +export interface LucidBuildResult { + document: LucidDocument; + images: Array<{ name: string; svg: string }>; +} + +export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "light"): LucidBuildResult { + const singleTheme: "light" | "dark" = theme === "dark" ? "dark" : "light"; + const P = paletteFor(singleTheme); + const pad = scene.pad; + const canvasW = Math.max(1, Math.ceil(scene.width + pad * 2)); + const canvasH = Math.max(1, Math.ceil(scene.height + pad * 2)); + const transparentFill = `${P.page}00`; + + const shapes: LucidShape[] = []; + const lines: LucidLine[] = []; + const images: Array<{ name: string; svg: string }> = []; + const shapeBoxById = new Map<string, SceneBox>(); + const lifeByParticipant = new Map<string, { lineId: string; x: number; y1: number; y2: number }>(); + + // 1. Architecture group containers (outer-first zIndex 0/1, assistedLayout: false keeps Basalt's grid) + for (const g of scene.groups) { + const box: SceneBox = { x: round2(g.box.x + pad), y: round2(g.box.y + pad), w: round2(g.box.w), h: round2(g.box.h) }; + const groupData: LucidCustomData[] = [{ key: "basalt_group", value: g.id }]; + if (g.parent) groupData.push({ key: "basalt_parent_group", value: g.parent }); + shapes.push({ + id: lucidId("group", g.id), + type: "roundedRectangleContainer", + boundingBox: box, + style: { + fill: { type: "color", color: transparentFill }, + stroke: { color: P.structure, width: 1, style: "dashed" }, + rounding: g.depth > 1 ? 16 : 24, // 8px radius-md for nested, 12px radius-lg for outer + }, + magnetize: true, + assistedLayout: false, + containerTitle: { + text: `<span style="font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 9pt; color: ${P.textSecondary}; text-align: left;">${escHtml(g.label)}</span>`, + }, + customData: groupData, + zIndex: g.depth - 1, + }); + } + + // 2. Data-flow swimLanes container (horizontal lanes whose widths sum to exact boundingBox.h) + if (scene.lanes.length > 0) { + const top = round2(scene.lanes[0]!.box.y + pad); + const left = round2(scene.lanes[0]!.box.x + pad); + const width = round2(scene.lanes[0]!.box.w); + const laneWidths = scene.lanes.map((l) => round2(l.box.h)); + const totalH = round2(laneWidths.reduce((a, b) => a + b, 0)); + shapes.push({ + id: "swimlanes_0", + type: "swimLanes", + boundingBox: { x: left, y: top, w: width, h: totalH }, + style: { + fill: { type: "color", color: transparentFill }, + stroke: { color: P.divider, width: 1, style: "solid" }, + }, + vertical: false, + titleBar: { height: 0, verticalText: false }, + lanes: scene.lanes.map((l, idx) => ({ + title: l.label, + width: laneWidths[idx]!, + headerFill: P.page, + laneFill: transparentFill, + })), + magnetize: true, + zIndex: 0, + }); + } + + // 3. Sequence phase bands + for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) { + const band = scene.bands[bIdx]!; + const midY = round2(band.y + band.h / 2 + pad); + lines.push({ + id: `band_${bIdx}`, + lineType: "straight", + endpoint1: { type: "positionEndpoint", style: "none", position: { x: round2(pad), y: midY } }, + endpoint2: { type: "positionEndpoint", style: "none", position: { x: round2(pad + band.w), y: midY } }, + stroke: { color: P.divider, width: 1, style: "solid" }, + text: [ + { + text: `<span style="font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 9pt; color: ${P.textSecondary};">${escHtml(band.text)}</span>`, + position: 0.5, + side: "middle", + }, + ], + zIndex: 4, + }); + } + + // 4. Nodes (cards, flowchart shapes, participants, schema tables) + for (let nodeIdx = 0; nodeIdx < scene.nodes.length; nodeIdx++) { + const n = scene.nodes[nodeIdx]!; + const id = lucidId("node", n.id); + const box: SceneBox = { x: round2(n.box.x + pad), y: round2(n.box.y + pad), w: round2(n.box.w), h: round2(n.box.h) }; + shapeBoxById.set(n.id, box); + + const isFocal = n.focal; + const fill = isFocal ? P.focalFill : P.cardFill; + const stroke = isFocal + ? P.focalBorder + : scene.type === "flowchart" + ? P.structure + : P.cardBorder; + const nameColor = isFocal ? P.focalInk : P.textPrimary; + const kindColor = isFocal ? P.focalQuiet : P.textTertiary; + const detailColor = isFocal ? P.focalQuiet : P.textSecondary; + const nodeCustomData: LucidCustomData[] = [ + { key: "basalt_id", value: n.id }, + { key: "basalt_col", value: String(n.col) }, + { key: "basalt_row", value: String(n.row) }, + ...(scene.measuredBy ? [{ key: "basalt_measured_by", value: scene.measuredBy }] : []), + ]; + + if (n.shape === "table") { + const rows = n.rows ?? []; + const rowCount = 1 + rows.length + (n.more ? 1 : 0); + const colCount = 3; + const cells: LucidTableCell[] = []; + // Size header, column, and optional "+ N more" rows from the scene's actual row positions so + // userSpecifiedRows sums to exact boundingBox.h and every FK endpoint sits on its row's center. + const headerSize = round2(rows.length > 0 ? Math.max(20, rows[0]!.y) : box.h); + const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: headerSize }]; + let usedH = headerSize; + // Header row merged across all 3 columns + cells.push({ + xPosition: 0, + yPosition: 0, + mergeCellsRight: 2, + style: { fill: { type: "color", color: fill } }, + text: `<p style="text-align: left; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 10.5pt; font-weight: bold; color: ${nameColor};">${escHtml(n.name)}</p>`, + }); + for (let r = 0; r < rows.length; r++) { + const row = rows[r]!; + const yPos = r + 1; + const size = r < rows.length - 1 + ? round2(Math.max(16, rows[r + 1]!.y - row.y)) + : n.more + ? round2(Math.max(16, row.h)) + : round2(Math.max(16, box.h - usedH)); + rowSizes.push({ index: yPos, size }); + usedH = round2(usedH + size); + const rightWord = row.refTable ? `→ ${row.refTable}` : row.type ?? ""; + cells.push( + { + xPosition: 0, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: row.key ? `<p style="text-align: left; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 8.5pt; color: ${kindColor};">${escHtml(row.key)}</p>` : "", + }, + { + xPosition: 1, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: `<p style="text-align: left; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 9pt; color: ${nameColor};">${escHtml(row.name)}</p>`, + }, + { + xPosition: 2, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: rightWord + ? `<p style="text-align: right; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 8.5pt; color: ${row.refTable ? detailColor : kindColor};">${escHtml(rightWord)}</p>` + : "", + }, + ); + } + if (n.more) { + const moreIdx = rows.length + 1; + const moreSize = round2(Math.max(16, box.h - usedH)); + rowSizes.push({ index: moreIdx, size: moreSize }); + usedH = round2(usedH + moreSize); + cells.push({ + xPosition: 0, + yPosition: moreIdx, + mergeCellsRight: 2, + style: { fill: { type: "color", color: fill } }, + text: `<p style="text-align: left; font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 8.5pt; color: ${kindColor};">${escHtml(`+ ${n.more} more`)}</p>`, + }); + } + // Absorb any residual rounding delta on the final row so sum(userSpecifiedRows) === box.h strictly. + const deltaH = round2(box.h - usedH); + if (deltaH !== 0 && rowSizes.length > 0) { + const last = rowSizes[rowSizes.length - 1]!; + last.size = round2(Math.max(16, last.size + deltaH)); + } + const keyColW = 36; + const typeColW = Math.max(64, round2(box.w * 0.36)); + const nameColW = Math.max(60, round2(box.w - keyColW - typeColW)); + + shapes.push({ + id, + type: "table", + boundingBox: box, + style: { + fill: { type: "color", color: fill }, + stroke: { color: stroke, width: 1, style: "solid" }, + textColor: nameColor, + }, + rowCount, + colCount, + cells, + userSpecifiedRows: rowSizes, + userSpecifiedCols: [ + { index: 0, size: keyColW }, + { index: 1, size: nameColW }, + { index: 2, size: typeColW }, + ], + verticalBorder: false, + horizontalBorder: true, + customData: nodeCustomData, + zIndex: 10, + }); + continue; + } + + const align = n.shape === "decision" || n.shape === "terminal" || n.shape === "participant" ? "center" : "left"; + const linesHtml: string[] = []; + if (n.kind) { + linesHtml.push(`<p style="text-align: ${align}; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 8.5pt; color: ${kindColor};">${escHtml(n.kind)}</p>`); + } + linesHtml.push(`<p style="text-align: ${align}; font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 10.5pt;${n.shape === "decision" ? "" : " font-weight: bold;"} color: ${nameColor};">${escHtml(n.name)}</p>`); + if (n.detail) { + const ff = n.detailMono ? "'Geist Mono', 'Liberation Mono', monospace" : "'Geist', 'Liberation Sans', sans-serif"; + linesHtml.push(`<p style="text-align: ${align}; font-family: ${ff}; font-size: 9pt; color: ${detailColor};">${escHtml(n.detail)}</p>`); + } + + const shapeType = n.shape === "decision" ? "decision" : n.shape === "terminal" ? "terminator" : "rectangle"; + const shapeStyle: LucidShape["style"] = { + fill: { type: "color", color: fill }, + stroke: { color: stroke, width: 1, style: "solid" }, + textColor: nameColor, + }; + if (shapeType === "rectangle") shapeStyle.rounding = 16; // 8px Basalt radius-md * 2 + + shapes.push({ + id, + type: shapeType, + boundingBox: box, + style: shapeStyle, + text: linesHtml.join(""), + customData: nodeCustomData, + zIndex: 10, + }); + + if (n.mark) { + const fileName = `${n.mark.id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${images.length + 1}.svg`; + const useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark"; + images.push({ name: fileName, svg: useDarkForm ? n.mark.svgDark : n.mark.svgLight }); + shapes.push({ + id: lucidId("mark", n.id), + type: "rectangle", + boundingBox: { x: round2(box.x + box.w - 12 - 16), y: round2(box.y + 10), w: 16, h: 16 }, + style: { + fill: { type: "image", ref: fileName, imageScale: "fit" }, + stroke: { color: transparentFill, width: 0 }, + }, + ...(n.mark.attribution ? { customData: [{ key: "attribution", value: n.mark.attribution }] } : {}), + zIndex: 15, + }); + } + } + + // 5. Sequence lifelines (straight dashed lines attached to participant headers) + for (const lf of scene.lifelines) { + const lineId = lucidId("life", lf.participantId); + const pBox = shapeBoxById.get(lf.participantId); + const lx = round2(lf.x + pad); + const y1 = pBox ? round2(pBox.y + pBox.h) : round2(lf.y1 + pad); + const y2 = round2(lf.y2 + pad); + lifeByParticipant.set(lf.participantId, { lineId, x: lx, y1, y2 }); + const pFx = pBox && pBox.w > 0 ? round6(Math.max(0, Math.min(1, (lx - pBox.x) / pBox.w))) : 0.5; + lines.push({ + id: lineId, + lineType: "straight", + endpoint1: pBox + ? { type: "shapeEndpoint", style: "none", shapeId: lucidId("node", lf.participantId), position: { x: pFx, y: 1 } } + : { type: "positionEndpoint", style: "none", position: { x: lx, y: y1 } }, + endpoint2: { type: "positionEndpoint", style: "none", position: { x: lx, y: y2 } }, + stroke: { color: P.structure, width: 1, style: "dashed" }, + zIndex: 5, + }); + } + + // 5b. Sequence frames (opt/loop/alt containers, corner tab, header label, and dashed branch dividers) + for (const f of scene.frames) { + const box: SceneBox = { x: round2(f.box.x + pad), y: round2(f.box.y + pad), w: round2(f.box.w), h: round2(f.box.h) }; + const tabBox: SceneBox = { x: round2(f.tabBox.x + pad), y: round2(f.tabBox.y + pad), w: round2(f.tabBox.w), h: round2(f.tabBox.h) }; + const frameData: LucidCustomData[] = [ + { key: "basalt_frame", value: f.id }, + { key: "basalt_frame_op", value: f.operator }, + ]; + if (f.parentId) frameData.push({ key: "basalt_parent_frame", value: f.parentId }); + shapes.push({ + id: lucidId("frame", f.id), + type: "roundedRectangleContainer", + boundingBox: box, + style: { + fill: { type: "color", color: transparentFill }, + stroke: { color: P.structure, width: 1, style: "solid" }, + rounding: f.depth > 1 ? 8 : 24, // 4px radius-xs nested, 12px radius-lg outer + }, + magnetize: false, + assistedLayout: false, + customData: frameData, + zIndex: 5 + f.depth, + }); + shapes.push({ + id: lucidId("frame_tab", f.id), + type: "rectangle", + boundingBox: tabBox, + style: { + fill: { type: "color", color: P.page }, + stroke: { color: P.structure, width: 1, style: "solid" }, + rounding: 0, + textColor: P.textPrimary, + }, + text: `<p style="text-align: center; font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 9pt; font-weight: 600; color: ${P.textPrimary};">${escHtml(f.operator)}</p>`, + zIndex: 7 + f.depth, + }); + if (f.label) { + const lb = f.labelBox ?? { + x: round2(f.tabBox.x + f.tabBox.w + 6), + y: round2(f.tabBox.y + 4), + w: round2(Math.min(Math.max(16, f.box.w - (f.tabBox.w + 12)), f.label.length * 7 + 12)), + h: 16, + }; + shapes.push({ + id: lucidId("frame_label", f.id), + type: "rectangle", + boundingBox: { x: round2(lb.x + pad), y: round2(lb.y + pad - 1), w: round2(lb.w), h: round2(Math.max(18, lb.h + 2)) }, + style: { + fill: { type: "color", color: P.page }, + stroke: { color: transparentFill, width: 0 }, + textColor: P.textSecondary, + }, + text: `<p style="text-align: left; font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 9pt; font-weight: 500; color: ${P.textSecondary};">${escHtml(f.label)}</p>`, + zIndex: 7 + f.depth, + }); + } + f.dividers.forEach((div, k) => { + const divY = round2(div.y + pad); + lines.push({ + id: lucidId("frame_div", `${f.id}_${k}`), + lineType: "straight", + endpoint1: { type: "positionEndpoint", style: "none", position: { x: box.x, y: divY } }, + endpoint2: { type: "positionEndpoint", style: "none", position: { x: round2(box.x + box.w), y: divY } }, + stroke: { color: P.structure, width: 1, style: "dashed" }, + zIndex: 7 + f.depth, + }); + if (div.label || f.operator === "alt") { + const eb = div.labelBox ?? { + x: round2(f.box.x + 6), + y: round2(div.y + Math.max(0, (div.h - 16) / 2)), + w: round2(Math.min(Math.max(16, f.box.w - 12), ((f.operator === "alt" ? 4 : 0) + div.label.length) * 7 + 16)), + h: 16, + }; + const txt = f.operator === "alt" + ? `<span style="font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 9pt; font-weight: 400; color: ${P.textTertiary};">else</span>` + + (div.label ? ` <span style="font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 9pt; font-weight: 500; color: ${P.textSecondary};">${escHtml(div.label)}</span>` : "") + : `<span style="font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 9pt; font-weight: 500; color: ${P.textSecondary};">${escHtml(div.label)}</span>`; + shapes.push({ + id: lucidId("frame_else", `${f.id}_${k}`), + type: "rectangle", + boundingBox: { x: round2(eb.x + pad), y: round2(eb.y + pad - 1), w: round2(eb.w), h: round2(Math.max(18, eb.h + 2)) }, + style: { + fill: { type: "color", color: P.page }, + stroke: { color: transparentFill, width: 0 }, + textColor: P.textSecondary, + }, + text: `<p style="text-align: left;">${txt}</p>`, + zIndex: 8 + f.depth, + }); + } + }); + } + + // 5c. Sequence activation bars (rectangles above lifelines/frames, glued to message endpoints) + const barBoxById = new Map<string, SceneBox>(); + for (const bar of scene.bars) { + const box: SceneBox = { x: round2(bar.box.x + pad), y: round2(bar.box.y + pad), w: round2(bar.box.w), h: round2(bar.box.h) }; + barBoxById.set(bar.id, box); + shapes.push({ + id: lucidId("bar", bar.id), + type: "rectangle", + boundingBox: box, + style: { + fill: { type: "color", color: P.cardFill }, + stroke: { color: P.structure, width: 1, style: "solid" }, + rounding: 4, // 2px radius-2xs * 2 + }, + customData: [ + { key: "basalt_bar", value: bar.id }, + { key: "basalt_participant", value: bar.participantId }, + ], + zIndex: 9, + }); + } + + // 6. Connector lines (ONE per Basalt edge, snapped in Lucid's exact px coordinates) + for (const e of scene.edges) { + let endpoint1: LucidEndpoint; + let endpoint2: LucidEndpoint; + let startPt: Pt; + let endPt: Pt; + + if (e.sequence) { + const lf1 = lifeByParticipant.get(e.from); + const lf2 = lifeByParticipant.get(e.to); + if (!lf1 || !lf2) continue; + const b1 = e.fromBarId ? barBoxById.get(e.fromBarId) : undefined; + const b2 = e.toBarId ? barBoxById.get(e.toBarId) : undefined; + if (b1) { + const fx = round6(e.fromPort.x); + const fy = round6(e.fromPort.y); + startPt = { x: round2(b1.x + fx * b1.w), y: round2(b1.y + fy * b1.h) }; + endpoint1 = { type: "shapeEndpoint", style: "none", shapeId: lucidId("bar", e.fromBarId!), position: { x: fx, y: fy } }; + } else { + const pos1 = round6(e.fromPort.y); + startPt = { x: lf1.x, y: round2(lf1.y1 + pos1 * (lf1.y2 - lf1.y1)) }; + endpoint1 = { type: "lineEndpoint", style: "none", lineId: lf1.lineId, position: pos1 }; + } + const endStyle: LucidEndpointStyle = e.openTip ? "openArrow" : "arrow"; + if (b2) { + const tx = round6(e.toPort.x); + const ty = round6(e.toPort.y); + endPt = { x: round2(b2.x + tx * b2.w), y: round2(b2.y + ty * b2.h) }; + endpoint2 = { type: "shapeEndpoint", style: endStyle, shapeId: lucidId("bar", e.toBarId!), position: { x: tx, y: ty } }; + } else { + const pos2 = round6(e.toPort.y); + endPt = { x: lf2.x, y: round2(lf2.y1 + pos2 * (lf2.y2 - lf2.y1)) }; + endpoint2 = { type: "lineEndpoint", style: endStyle, lineId: lf2.lineId, position: pos2 }; + } + } else { + const srcBox = shapeBoxById.get(e.from); + const dstBox = shapeBoxById.get(e.to); + if (!srcBox || !dstBox) continue; + const fx = round6(e.fromPort.x); + const fy = round6(e.fromPort.y); + const tx = round6(e.toPort.x); + const ty = round6(e.toPort.y); + startPt = { x: round2(srcBox.x + fx * srcBox.w), y: round2(srcBox.y + fy * srcBox.h) }; + endPt = { x: round2(dstBox.x + tx * dstBox.w), y: round2(dstBox.y + ty * dstBox.h) }; + const startStyle: LucidEndpointStyle = e.card ? LUCID_CARD[e.card.from] : (e.fk ? "closedCircle" : "none"); + const endStyle: LucidEndpointStyle = e.card ? LUCID_CARD[e.card.to] : (e.openTip ? "openArrow" : "arrow"); + endpoint1 = { type: "shapeEndpoint", style: startStyle, shapeId: lucidId("node", e.from), position: { x: fx, y: fy } }; + endpoint2 = { type: "shapeEndpoint", style: endStyle, shapeId: lucidId("node", e.to), position: { x: tx, y: ty } }; + } + + const rawPts: Pt[] = e.pts.map((p) => ({ x: round2(p.x + pad), y: round2(p.y + pad) })); + const snapped = snapRouteToPorts(rawPts, startPt, endPt, e.fromPort.side, e.toPort.side); + const innerPts = snapped.slice(1, -1); + + const isMain = e.kind === "main"; + const isDashed = e.kind === "dashed"; + const lineObj: LucidLine = { + id: `edge_${e.index}`, + lineType: innerPts.length > 0 ? "elbow" : "straight", + endpoint1, + endpoint2, + stroke: { + color: isMain ? P.edgeMain : P.edgePlain, + width: isMain ? 2 : 1, + style: isDashed ? "dashed" : "solid", + }, + zIndex: 20, + }; + + if (innerPts.length > 0) { + lineObj.elbowControlPoints = innerPts.map((p) => ({ x: round2(p.x), y: round2(p.y) })); + } + + if (e.label) { + const labelHtml = escHtml(e.label.text).replace(/\n/g, "<br>"); + const texts: LucidLineText[] = [ + { + text: `<span style="font-family: 'Geist Mono', 'Liberation Mono', monospace; font-size: 9pt; color: ${e.sequence ? P.textPrimary : P.edgePlain};">${labelHtml}</span>`, + position: e.label.t, + side: e.label.on ? "middle" : "top", + }, + ]; + if (e.label.note) { + texts.push({ + text: `<span style="font-family: 'Geist', 'Liberation Sans', sans-serif; font-size: 8.5pt; color: ${P.textTertiary};">${escHtml(e.label.note)}</span>`, + position: e.label.t, + side: "bottom", + }); + } + lineObj.text = texts; + } + + lines.push(lineObj); + } + + return { + document: { + version: 1, + documentSettings: { units: "px" }, + pages: [ + { + id: lucidId("page", scene.id), + title: scene.title || scene.id, + settings: { + fillColor: P.page, + infiniteCanvas: false, + autoTiling: true, + size: { type: "custom", w: canvasW, h: canvasH }, + }, + shapes, + lines, + }, + ], + }, + images, + }; +} + +export function sceneToLucidJson(scene: InteropScene, theme: InteropTheme = "light"): LucidDocument { + return buildLucidPayload(scene, theme).document; +} + +export function sceneToLucid(scene: InteropScene, theme: InteropTheme = "light"): Uint8Array { + const { document, images } = buildLucidPayload(scene, theme); + const entries: ZipEntry[] = [ + { name: "document.json", data: `${JSON.stringify(document, null, 2)}\n` }, + ...images.map((img) => ({ name: `images/${img.name}`, data: img.svg })), + ]; + return makeDeterministicZip(entries); +} diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts new file mode 100644 index 00000000..b75cc842 --- /dev/null +++ b/packages/react/src/interop/scene.ts @@ -0,0 +1,2349 @@ +// Shared scene builder for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314, 324, 327). +// Reads Basalt's model and derived ports through diagram-core's existing exports without editing diagram-core.ts. +// Produces one normalized InteropScene either headlessly (pure JS + Geist metrics) or from a live figure's Geo. +// Every connector route is snapped to exact port coordinates so first and last segments are strictly axis-aligned. +import { buildModel, columnCount, derivedPorts, groupEdges, groupReach, portFloors, turnBackLanes } from "../diagram-core"; +import type { DiagramPlacement, DiagramSide, DiagramSpec, GLine, GNode, Geo, MBar, MNode, Model, Pt, Rect } from "../diagram-core"; +import type { + InteropMarkResolver, + InteropOptions, + InteropScene, + MeasuredBand, + MeasuredExtras, + MeasuredFrame, + MeasuredFrameDivider, + MeasuredGroup, + MeasuredLane, + SceneBand, + SceneBar, + SceneBox, + SceneEdge, + SceneFrame, + SceneFrameDivider, + SceneGroup, + SceneLabel, + SceneLane, + SceneLifeline, + SceneMark, + SceneNode, + ScenePort, + SceneTableRow, +} from "./types"; + +// ---- Resolved Basalt theme palette (sRGB hex, matching packages/tokens/tokens/theme.{light,dark}.tokens.json) ---- + +export interface ThemePalette { + page: string; + cardFill: string; + cardBorder: string; + divider: string; + focalFill: string; + focalBorder: string; + focalInk: string; + focalQuiet: string; + focalRule: string; + textPrimary: string; + textSecondary: string; + textTertiary: string; + edgeMain: string; + edgePlain: string; + structure: string; +} + +export function paletteFor(theme: "light" | "dark"): ThemePalette { + if (theme === "dark") { + return { + page: "#000000", + cardFill: "#0a0a0a", + cardBorder: "#1f1f1f", + divider: "#1f1f1f", + focalFill: "#ededed", + focalBorder: "#ededed", + focalInk: "#000000", + focalQuiet: "#595959", + focalRule: "#d9d9d9", + textPrimary: "#f4f4f4", + textSecondary: "#bababa", + textTertiary: "#979797", + edgeMain: "#f4f4f4", + edgePlain: "#bababa", + structure: "#616161", + }; + } + return { + page: "#fafafa", + cardFill: "#ffffff", + cardBorder: "#e6e6e6", + divider: "#e6e6e6", + focalFill: "#171717", + focalBorder: "#171717", + focalInk: "#ffffff", + focalQuiet: "#b3b3b3", + focalRule: "#262626", + textPrimary: "#171717", + textSecondary: "#4d4d4d", + textTertiary: "#6b6b6b", + edgeMain: "#171717", + edgePlain: "#4d4d4d", + structure: "#8a8a8a", + }; +} + +// ---- Mark terms allowlist (derived from packages/react/marks/manifest.json at build time) ---- +// Build-time constants injected by packages/react/build.mjs from manifest.json's `unofficial` and `terms.quotes` +// fields; parsed lazily on first call so loading the module allocates nothing at top level. + +declare const __BASALT_EMBEDDABLE_MARKS__: string | undefined; +declare const __BASALT_MARK_ATTRIBUTIONS__: string | undefined; + +let embeddableMarksCache: Set<string> | undefined; +let markAttributionsCache: Record<string, string> | undefined; + +function getEmbeddableMarks(): Set<string> | null { + if (embeddableMarksCache) return embeddableMarksCache; + if (typeof __BASALT_EMBEDDABLE_MARKS__ !== "string") return null; + embeddableMarksCache = new Set(JSON.parse(__BASALT_EMBEDDABLE_MARKS__) as string[]); + return embeddableMarksCache; +} + +function getMarkAttributions(): Record<string, string> { + if (markAttributionsCache) return markAttributionsCache; + markAttributionsCache = typeof __BASALT_MARK_ATTRIBUTIONS__ === "string" + ? (JSON.parse(__BASALT_MARK_ATTRIBUTIONS__) as Record<string, string>) + : {}; + return markAttributionsCache; +} + +/** Whether a bundled Basalt mark id is permitted for embedding in exported diagrams by marks/manifest.json terms. */ +export function isBundledMarkEmbeddable(id: string): boolean { + if (!id) return false; + const set = getEmbeddableMarks(); + return set ? set.has(id) : false; +} + +/** Returns the manifest licence/trademark attribution string for an embeddable bundled mark, if any. */ +export function bundledMarkAttribution(id: string): string | undefined { + if (!id) return undefined; + const attrs = getMarkAttributions(); + return Object.prototype.hasOwnProperty.call(attrs, id) ? attrs[id] : undefined; +} + +/** Extracts raw `<svg ...>...</svg>` markup from either raw SVG text or a `data:image/svg+xml,...` URI. */ +export function decodeSvgMarkup(input: string): string | undefined { + const s = input.trim(); + if (!s) return undefined; + if (s.startsWith("<svg")) return s; + if (s.startsWith("data:image/svg+xml;base64,")) { + const b64 = s.slice("data:image/svg+xml;base64,".length); + if (typeof atob === "function") return atob(b64); + return undefined; + } + if (s.startsWith("data:image/svg+xml,")) { + try { return decodeURIComponent(s.slice("data:image/svg+xml,".length)); } catch { return undefined; } + } + return undefined; +} + +/** Encodes raw SVG markup as a compact percent-encoded `data:image/svg+xml,...` URI. */ +export function encodeSvgDataUri(svg: string): string { + return `data:image/svg+xml,${encodeURIComponent(svg)}`; +} + +function resolveNodeMark(n: MNode, mode: "omit" | "embed", resolver?: InteropMarkResolver): SceneMark | undefined { + if (mode !== "embed" || !n.mark) return undefined; + if (n.mark.id) { + if (!isBundledMarkEmbeddable(n.mark.id) || !resolver) return undefined; + const rawLight = resolver(n.mark.id, "light"); + const rawDark = resolver(n.mark.id, "dark") ?? rawLight; + const svgLight = rawLight ? decodeSvgMarkup(rawLight) : undefined; + const svgDark = rawDark ? decodeSvgMarkup(rawDark) : svgLight; + if (!svgLight || !svgDark) return undefined; + return { id: n.mark.id, svgLight, svgDark, attribution: bundledMarkAttribution(n.mark.id) }; + } + if (n.mark.onLight) { + const rawLight = decodeSvgMarkup(n.mark.onLight) ?? (resolver ? resolver(n.mark.onLight, "light") : undefined); + const svgLight = rawLight ? decodeSvgMarkup(rawLight) : undefined; + const darkSrc = n.mark.onDark ?? n.mark.onLight; + const rawDark = decodeSvgMarkup(darkSrc) ?? (resolver ? resolver(darkSrc, "dark") : undefined); + const svgDark = rawDark ? decodeSvgMarkup(rawDark) : svgLight; + if (!svgLight || !svgDark) return undefined; + return { id: `custom-${n.id}`, svgLight, svgDark }; + } + return undefined; +} + +// ---- Exact Geist Sans / Geist Mono metrics (measured from bundled variable WOFF2 faces) ---- +// ASCII 32..126 advance widths in hundredths of em for Geist 400; 500 scales ~1.028x and 600 ~1.052x. +// Geist Mono is strictly 0.60em per glyph across all weights and symbols. + +const GEIST_400_EM = [ + 25, 21, 35, 48, 63, 80, 62, 18, 27, 27, 43, 56, 20, 42, 20, 39, + 67, 35, 62, 61, 62, 63, 59, 54, 60, 59, 30, 30, 54, 54, 54, 56, + 91, 67, 67, 70, 71, 59, 57, 70, 70, 25, 57, 62, 55, 86, 73, 74, + 63, 73, 67, 64, 56, 69, 66, 94, 61, 59, 54, 35, 36, 35, 43, 56, + 25, 55, 59, 54, 59, 55, 32, 59, 58, 23, 25, 55, 26, 86, 56, 56, + 59, 59, 34, 51, 33, 58, 54, 82, 55, 54, 52, 39, 26, 39, 52, +]; + +type FontRole = "name" | "name-500" | "mono" | "sans" | "table" | "label" | "lane"; + +function measureText(text: string, role: FontRole): number { + if (!text) return 0; + if (role === "mono" || role === "label") return text.length * 7.2; + if (role === "table") return text.length * 8.4; + const size = role === "name" || role === "name-500" ? 14 : 12; + const weightScale = role === "name" ? 1.052 : role === "name-500" || role === "lane" ? 1.028 : 1; + let sum = 0; + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code >= 32 && code <= 126) { + sum += GEIST_400_EM[code - 32]! / 100; + } else if (code === 0x00b7 || code === 0x2018 || code === 0x2019) { + sum += 0.23; // · ‘ ’ + } else if (code === 0x2192 || code === 0x2190) { + sum += 0.8; // → ← + } else if (code === 0x2014) { + sum += 0.91; // — + } else if (code === 0x2013 || code === 0x00d7) { + sum += 0.56; // – × + } else if (code === 0x201c || code === 0x201d) { + sum += 0.43; // “ ” + } else if (code === 0x2026) { + sum += 0.65; // … + } else { + sum += 0.6; + } + } + return sum * size * weightScale; +} + +const splitWords = (s?: string) => (s ? s.split(/\s+/).filter(Boolean) : []); + +/** Simulates CSS word wrapping within `maxWidth` and returns the wrapped line count and widest line width. */ +function wrapText(text: string, role: FontRole, maxWidth: number): { lines: number; width: number } { + const tokens = splitWords(text); + if (!tokens.length) return { lines: 0, width: 0 }; + const sp = measureText(" ", role); + let lines = 1; + let lineW = 0; + let maxLineW = 0; + for (const w of tokens) { + const ww = measureText(w, role); + if (lineW === 0) { + lineW = ww; + } else if (lineW + sp + ww <= maxWidth + 0.5) { + lineW += sp + ww; + } else { + maxLineW = Math.max(maxLineW, lineW); + lines++; + lineW = ww; + } + } + maxLineW = Math.max(maxLineW, lineW); + return { lines, width: maxLineW }; +} + +// ---- Math & geometry helpers ---- + +export const round2 = (n: number): number => Math.round(n * 100) / 100; +export const round4 = (n: number): number => Math.round(n * 10000) / 10000; +export const round6 = (n: number): number => Math.round(n * 1000000) / 1000000; +const isH = (s: DiagramSide) => s === "left" || s === "right"; +const opposite: Record<DiagramSide, DiagramSide> = { top: "bottom", bottom: "top", left: "right", right: "left" }; +const hit = (a: Rect, b: Rect, eps = 0.01) => a.l < b.r - eps && a.r > b.l + eps && a.t < b.b - eps && a.b > b.t + eps; +const grow = (a: Rect, p: number): Rect => ({ l: a.l - p, r: a.r + p, t: a.t - p, b: a.b + p }); +const rectToBox = (r: Rect): SceneBox => ({ x: round2(r.l), y: round2(r.t), w: round2(r.r - r.l), h: round2(r.b - r.t) }); +const boxToRect = (b: SceneBox): Rect => ({ l: b.x, t: b.y, r: b.x + b.w, b: b.y + b.h }); +const segmentsOf = (pts: Pt[]) => pts.slice(1).map((p, k) => [pts[k]!, p] as const); +const segRect = (a: Pt, b: Pt, w: number): Rect => ({ + l: Math.min(a.x, b.x) - w / 2, + r: Math.max(a.x, b.x) + w / 2, + t: Math.min(a.y, b.y) - w / 2, + b: Math.max(a.y, b.y) + w / 2, +}); + +function slugId(s: string): string { + const slug = s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); + return slug || "diagram"; +} + +function insideShape(p: Pt, n: GNode, pad: number): boolean { + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + if (n.shape === "decision") return Math.abs(p.x - cx) / hw + Math.abs(p.y - cy) / hh < 1 - pad / Math.min(hw, hh); + if (n.shape === "terminal") { + const rr = Math.min(hw, hh); + const ex = Math.min(Math.max(p.x, l + rr), r - rr); + const dx = p.x - ex, dy = p.y - cy; + return Math.sqrt(dx * dx + dy * dy) < rr - pad; + } + return p.x > l + pad && p.x < r - pad && p.y > t + pad && p.y < b - pad; +} + +function boxHitsShape(box: Rect, n: GNode): boolean { + if (!hit(box, n.rect)) return false; + if (n.shape !== "decision" && n.shape !== "terminal") return true; + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + if (n.shape === "decision") { + const px = Math.max(box.l, Math.min(cx, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + return Math.abs(px - cx) / hw + Math.abs(py - cy) / hh < 1 - 1e-6; + } + const rr = Math.min(hh, hw); + if (hit(box, { l: l + rr, r: r - rr, t, b })) return true; + for (const ex of [l + rr, r - rr]) { + const px = Math.max(box.l, Math.min(ex, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + const dx = px - ex, dy = py - cy; + if (Math.sqrt(dx * dx + dy * dy) < rr - 0.01) return true; + } + return false; +} + +function segmentThrough(a: Pt, b: Pt, n: GNode): boolean { + const dx = b.x - a.x, dy = b.y - a.y; + const len = Math.sqrt(dx * dx + dy * dy); + const steps = Math.max(2, Math.ceil(len / 2)); + for (let k = 1; k < steps; k++) { + const f = k / steps; + if (f * len < 1.5 || (1 - f) * len < 1.5) continue; + if (insideShape({ x: a.x + dx * f, y: a.y + dy * f }, n, 1)) return true; + } + return false; +} + +function findCrossingsCount(lines: GLine[], only: Set<number>): number { + let count = 0; + const e = 0.75; + for (let a = 0; a < lines.length; a++) { + for (let b = a + 1; b < lines.length; b++) { + const A = lines[a]!, B = lines[b]!; + if (!only.has(A.i) && !only.has(B.i)) continue; + for (const [p1, p2] of segmentsOf(A.pts)) { + for (const [q1, q2] of segmentsOf(B.pts)) { + const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; + if (aH === bH) continue; + const [h1, h2, v1, v2] = aH ? [p1, p2, q1, q2] : [q1, q2, p1, p2]; + const x = v1.x, y = h1.y; + if (x > Math.min(h1.x, h2.x) + e && x < Math.max(h1.x, h2.x) - e && y > Math.min(v1.y, v2.y) + e && y < Math.max(v1.y, v2.y) - e) count++; + } + } + } + } + return count; +} + +function overlapsCount(lines: GLine[], only: Set<number>): number { + let count = 0; + for (let a = 0; a < lines.length; a++) { + for (let b = a + 1; b < lines.length; b++) { + const A = lines[a]!, B = lines[b]!; + if (!only.has(A.i) && !only.has(B.i)) continue; + if (A.to === B.to && Math.abs(A.tip.x - B.tip.x) < 1 && Math.abs(A.tip.y - B.tip.y) < 1) continue; + const near = (A.width + B.width) / 2 + 0.5; + for (const [p1, p2] of segmentsOf(A.pts)) { + for (const [q1, q2] of segmentsOf(B.pts)) { + const aH = Math.abs(p1.y - p2.y) < 0.01, bH = Math.abs(q1.y - q2.y) < 0.01; + if (aH !== bH) continue; + const [ac, bc] = aH ? [p1.y, q1.y] : [p1.x, q1.x]; + if (Math.abs(ac - bc) >= near) continue; + const [a1, a2] = aH ? [p1.x, p2.x] : [p1.y, p2.y]; + const [b1, b2] = aH ? [q1.x, q2.x] : [q1.y, q2.y]; + if (Math.min(Math.max(a1, a2), Math.max(b1, b2)) - Math.max(Math.min(a1, a2), Math.min(b1, b2)) > 1) count++; + } + } + } + } + return count; +} + +function* permutations<T>(items: T[]): Generator<T[]> { + if (items.length <= 1 || items.length > 5) { yield items.slice(); return; } + for (let k = 0; k < items.length; k++) { + const rest = items.slice(0, k).concat(items.slice(k + 1)); + for (const p of permutations(rest)) yield [items[k]!, ...p]; + } +} + +function cleanOrthogonal(pts: Pt[]): Pt[] { + if (pts.length <= 1) return pts.map((p) => ({ ...p })); + const out: Pt[] = [{ ...pts[0]! }]; + for (let k = 1; k < pts.length; k++) { + const p = pts[k]!; + const last = out[out.length - 1]!; + if (Math.abs(p.x - last.x) < 1e-6 && Math.abs(p.y - last.y) < 1e-6) continue; + if (out.length >= 2) { + const prev = out[out.length - 2]!; + const sameX = Math.abs(prev.x - last.x) < 1e-6 && Math.abs(last.x - p.x) < 1e-6; + const sameY = Math.abs(prev.y - last.y) < 1e-6 && Math.abs(last.y - p.y) < 1e-6; + if (sameX || sameY) { + out[out.length - 1] = { ...p }; + continue; + } + } + out.push({ ...p }); + } + return out; +} + +/** + * Snaps an orthogonal polyline's endpoints to exact port coordinates `start` and `end`, + * propagating the aligned axis into the first and last inner waypoints so neither segment ever jogs + * (fixes the RunTask 0.5px pixel-snap jog in Visio, Lucidchart, and draw.io). + */ +export function snapRouteToPorts(pts: readonly Pt[], start: Pt, end: Pt, startSide?: DiagramSide, endSide?: DiagramSide): Pt[] { + if (pts.length < 2) return [{ ...start }, { ...end }]; + const q = pts.map((p) => ({ x: p.x, y: p.y })); + if (q.length === 2) { + // Straight 2-point connector: endpoints sit directly on start and end. + return [{ x: start.x, y: start.y }, { x: end.x, y: end.y }]; + } + const firstHoriz = startSide + ? isH(startSide) + : Math.abs(q[0]!.y - q[1]!.y) <= Math.abs(q[0]!.x - q[1]!.x); + const lastHoriz = endSide + ? isH(endSide) + : Math.abs(q[q.length - 2]!.y - q[q.length - 1]!.y) <= Math.abs(q[q.length - 2]!.x - q[q.length - 1]!.x); + + q[0] = { x: start.x, y: start.y }; + if (firstHoriz) q[1]!.y = start.y; else q[1]!.x = start.x; + + q[q.length - 1] = { x: end.x, y: end.y }; + if (lastHoriz) q[q.length - 2]!.y = end.y; else q[q.length - 2]!.x = end.x; + + // Keep any interior segments strictly orthogonal (for 4+ point routes, middle segment stays axis-aligned). + for (let k = 1; k < q.length - 2; k++) { + const a = q[k]!, b = q[k + 1]!; + if (Math.abs(a.x - b.x) <= Math.abs(a.y - b.y)) { + b.x = a.x; + } else { + b.y = a.y; + } + } + return cleanOrthogonal(q); +} + +/** Exact port point on a box boundary for fractional port `(fx, fy)`. */ +export function boxPortPoint(box: SceneBox, port: ScenePort): Pt { + return { + x: box.x + port.x * box.w, + y: box.y + port.y * box.h, + }; +} + +function portForSideSlot(side: DiagramSide, slot: number): ScenePort { + const f = round6(Math.max(0, Math.min(1, slot))); + if (side === "left") return { x: 0, y: f, side }; + if (side === "right") return { x: 1, y: f, side }; + if (side === "top") return { x: f, y: 0, side }; + return { x: f, y: 1, side }; +} + +function labelArcFraction(pts: readonly Pt[], box: SceneBox): number { + const cx = box.x + box.w / 2; + const cy = box.y + box.h / 2; + let total = 0; + const segLens: number[] = []; + for (let i = 1; i < pts.length; i++) { + const dx = pts[i]!.x - pts[i - 1]!.x; + const dy = pts[i]!.y - pts[i - 1]!.y; + const len = Math.abs(dx) < 1e-9 || Math.abs(dy) < 1e-9 ? Math.abs(dx) + Math.abs(dy) : Math.sqrt(dx * dx + dy * dy); + segLens.push(len); + total += len; + } + if (total <= 1e-6) return 0.5; + let bestDist2 = Infinity; + let bestAlong = total / 2; + let acc = 0; + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1]!, b = pts[i]!; + const dx = b.x - a.x, dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + const u = len2 > 0 ? Math.max(0, Math.min(1, ((cx - a.x) * dx + (cy - a.y) * dy) / len2)) : 0; + const px = a.x + u * dx, py = a.y + u * dy; + const ex = cx - px, ey = cy - py; + const d2 = ex * ex + ey * ey; + if (d2 < bestDist2) { + bestDist2 = d2; + bestAlong = acc + u * segLens[i - 1]!; + } + acc += segLens[i - 1]!; + } + return round4(Math.max(0.05, Math.min(0.95, bestAlong / total))); +} + +function dirOf(pts: Pt[]): "up" | "down" | "left" | "right" { + const a = pts[pts.length - 2]!, b = pts[pts.length - 1]!; + if (Math.abs(a.x - b.x) < 0.01) return b.y > a.y ? "down" : "up"; + return b.x > a.x ? "right" : "left"; +} + +function headBox(tip: Pt, dir: "up" | "down" | "left" | "right"): Rect { + const L = 8, W = 4; + if (dir === "down") return { l: tip.x - W, r: tip.x + W, t: tip.y - L, b: tip.y }; + if (dir === "up") return { l: tip.x - W, r: tip.x + W, t: tip.y, b: tip.y + L }; + if (dir === "right") return { l: tip.x - L, r: tip.x, t: tip.y - W, b: tip.y + W }; + return { l: tip.x, r: tip.x + L, t: tip.y - W, b: tip.y + W }; +} + +// ---- Automatic layout placement helper (DECISIONS 306, 327) ---- + +function pickPlacement( + spec: DiagramSpec, + override?: DiagramPlacement | DiagramPlacement[], + targetW?: number, + marksMode: "omit" | "embed" = "omit", + resolveMark?: InteropMarkResolver, +): DiagramPlacement | undefined { + if (spec.layout !== "auto") return undefined; + const raw = override ?? (spec as { placement?: DiagramPlacement | DiagramPlacement[] }).placement; + if (!raw) return undefined; + if (!Array.isArray(raw)) return raw; + if (!raw.length) return undefined; + const pref = (spec as { direction?: "right" | "down" }).direction; + const order: Array<"right" | "down"> = pref ? [pref] : spec.type === "flowchart" ? ["down", "right"] : ["right", "down"]; + const ordered: DiagramPlacement[] = []; + for (const dir of order) { + const cand = raw.find((p) => p.direction === dir); + if (cand && !ordered.includes(cand)) ordered.push(cand); + } + for (const cand of raw) if (!ordered.includes(cand)) ordered.push(cand); + + // Match the browser's direction rule: try candidates in order and pick the first whose minimum width fits targetW. + if (targetW !== undefined) { + for (const cand of ordered) { + const m = buildModel(spec, { checks: false, placement: cand }); + if (m.unplaced) continue; + const hasMarks = marksMode === "embed" && m.nodes.some((n) => Boolean(resolveNodeMark(n, marksMode, resolveMark))); + if (computeMinimums(m, hasMarks).least <= targetW) return cand; + } + } + return ordered.find((p) => !buildModel(spec, { checks: false, placement: p }).unplaced) ?? ordered[0]; +} + +function pickPlacementForMeasured( + spec: DiagramSpec, + geo: Geo, + override?: DiagramPlacement | DiagramPlacement[], +): DiagramPlacement | undefined { + if (spec.layout !== "auto") return undefined; + const raw = override ?? (spec as { placement?: DiagramPlacement | DiagramPlacement[] }).placement; + if (!raw) return undefined; + if (!Array.isArray(raw)) return raw; + if (raw.length <= 1) return raw[0]; + const rectById = new Map(geo.nodes.map((gn) => [gn.id, gn.rect])); + let best: DiagramPlacement | undefined; + let bestScore = -1; + for (const p of raw) { + if (buildModel(spec, { checks: false, placement: p }).unplaced) continue; + const ids = Object.keys(p.cells).filter((id) => rectById.has(id)); + let score = 0; + for (let i = 0; i < ids.length; i++) { + for (let j = i + 1; j < ids.length; j++) { + const a = ids[i]!, b = ids[j]!; + const ca = p.cells[a]!, cb = p.cells[b]!; + const ra = rectById.get(a)!, rb = rectById.get(b)!; + if (ca.col !== cb.col && (ca.col < cb.col) === (ra.l < rb.l - 1)) score++; + if (ca.row !== cb.row && (ca.row < cb.row) === (ra.t < rb.t - 1)) score++; + } + } + if (score > bestScore) { bestScore = score; best = p; } + } + return best ?? pickPlacement(spec, override); +} + +// ---- Headless layout (exact Basalt CSS grid + routing + label seating) ---- + +function computeMinimums(m: Model, hasMarks: boolean): { track: number; table: number; least: number } { + let track = 144; + let table = 224; + for (const n of m.nodes) { + if (n.shape === "table") { + for (const c of n.columns ?? []) { + const type = c.ref ? `→ ${c.ref.table}` : c.type ?? ""; + const row = 24 + measureText(c.name, "mono") + (type ? 12 + measureText(type, "mono") : 0) + 24 + 2; + table = Math.max(table, Math.ceil(row)); + } + table = Math.max(table, Math.ceil(measureText(n.name, "table") + 24 + 2)); + continue; + } + const pad = n.shape === "terminal" ? 40 : 24; + const seat = hasMarks && n.mark ? (n.shape === "participant" ? 48 : 24) : 0; + let widest = 0; + for (const w of splitWords(n.name)) widest = Math.max(widest, measureText(w, n.shape === "decision" ? "name-500" : "name") + (n.kind ? 0 : seat)); + if (m.type !== "data-flow") for (const w of splitWords(n.kind)) widest = Math.max(widest, measureText(w, "mono") + seat); + for (const w of splitWords(n.detail)) widest = Math.max(widest, measureText(w, n.mono ? "mono" : "sans")); + const need = n.shape === "decision" ? widest / 0.62 : widest + pad + 2; + track = Math.max(track, Math.ceil(need)); + } + const n = columnCount(m); + const oneColTurnBack = m.type === "schema" && m.cols === 1 && m.edges.length > 0; + let least: number; + if (m.type === "data-flow") least = 120 + n * (track + 48); + else if (m.type === "schema") { + const colGap = m.marks ? 60 : 48; + const tbPad = oneColTurnBack ? (m.marks ? 28 : 20) + (turnBackLanes(m).lanes > 1 ? 12 : 0) : 0; + least = n * table + (n - 1) * colGap + tbPad; + } else if (m.type === "sequence") least = n * track + (n - 1) * 20; + else least = n * track + (n - 1) * 64 + groupReach(m) * 16; + return { track, table, least: Math.max(640, least) }; +} + +function measureNodeHeight( + n: MNode, + trackW: number, + hasMark: boolean, + minH = 0, +): { h: number; rows?: SceneTableRow[]; headerH?: number } { + if (n.shape === "table") { + const headerH = 37; // 8 top + 20 line + 8 bottom + 1 border + const rowsPadTop = 4; + const rowH = 28; + const rows: SceneTableRow[] = (n.columns ?? []).map((c, idx) => ({ + index: idx, + name: c.name, + key: c.key, + type: c.type, + refTable: c.ref?.table, + y: headerH + rowsPadTop + idx * rowH, + h: rowH, + midY: headerH + rowsPadTop + idx * rowH + rowH / 2, + })); + const moreH = n.more ? 24 : 0; // 16 line + 8 bottom pad + const h = 2 + headerH + rowsPadTop * 2 + rows.length * rowH + moreH; + return { h, rows, headerH }; + } + if (n.shape === "decision") { + const heightFor = (ww: number) => { + const wrapped = wrapText(n.name, "name-500", ww); + const boxW = Math.min(ww, wrapped.width) + 20; + const boxH = Math.max(1, wrapped.lines) * 20 + 16; + const denom = 1 - boxW / trackW; + const half = denom > 0.05 ? boxH / 2 / denom : boxH * 10; + return { h: Math.max(64, Math.ceil(trackW / 5), Math.ceil(2 * half)), lines: wrapped.lines }; + }; + const baseW = trackW * 0.62; + let best = heightFor(baseW); + if (best.h > trackW) { + const widest = Math.floor(trackW - 20); + let cur = Math.ceil(baseW); + let tall = best.lines; + while (cur < widest && heightFor(widest).lines < tall) { + let lo = cur, hi = widest; + while (hi - lo > 1) { + const mid = (lo + hi) >> 1; + if (heightFor(mid).lines < tall) hi = mid; else lo = mid; + } + const tried = heightFor(hi); + if (tried.h <= trackW) { best = tried; break; } + cur = hi; + tall = tried.lines; + } + } + return { h: best.h }; + } + if (n.shape === "participant") { + const inner = Math.max(40, trackW - 26); + const markSeat = hasMark ? 48 : 0; + const kindLines = n.kind ? Math.max(1, wrapText(n.kind, "mono", Math.max(24, inner - markSeat)).lines) : 0; + const nameLines = Math.max(1, wrapText(n.name, "name", Math.max(24, inner - (n.kind ? 0 : markSeat))).lines); + return { h: 2 + 20 + kindLines * 16 + nameLines * 20 }; + } + // Architecture, flowchart step/terminal, data-flow step. + const padX = n.shape === "terminal" ? 40 : 24; + const inner = Math.max(40, trackW - padX - 2); + const markSeat = hasMark ? 24 : 0; + const kindLines = n.kind ? Math.max(1, wrapText(n.kind, "mono", Math.max(24, inner - markSeat)).lines) : 0; + const nameLines = Math.max(1, wrapText(n.name, "name", Math.max(24, inner - (n.kind ? 0 : markSeat))).lines); + const detailLines = n.detail ? Math.max(1, wrapText(n.detail, n.mono ? "mono" : "sans", inner).lines) : 0; + const detailGap = detailLines > 0 ? 2 : 0; + return { h: Math.max(minH, 2 + 20 + kindLines * 16 + nameLines * 20 + detailGap + detailLines * 16) }; +} + +function seatSceneLabels( + m: Model, + edges: SceneEdge[], + gNodes: GNode[], + groupRects: Rect[], + laneObstacles: Rect[], + bounds: Rect, +): Map<number, { box: SceneBox; on: boolean }> { + const placed: Rect[] = []; + const out = new Map<number, { box: SceneBox; on: boolean }>(); + const GROW = 4; + const gLines: GLine[] = edges.map((e) => ({ + i: e.index, + from: e.from, + to: e.to, + kind: e.kind, + pts: e.pts, + tip: e.pts[e.pts.length - 1]!, + dir: dirOf(e.pts), + width: e.kind === "main" ? 2 : 1, + })); + const heads = gLines.map((l) => headBox(l.tip, l.dir)); + const obstacles: Rect[] = [...laneObstacles]; + for (const g of groupRects) { + obstacles.push( + { l: g.l, r: g.r, t: g.t, b: g.t + 1 }, + { l: g.l, r: g.r, t: g.b - 1, b: g.b }, + { l: g.l, r: g.l + 1, t: g.t, b: g.b }, + { l: g.r - 1, r: g.r, t: g.t, b: g.b }, + ); + } + const order = edges + .filter((e) => m.edges[e.index]?.label) + .sort((a, b) => Number(b.kind === "main") - Number(a.kind === "main") || a.index - b.index); + + for (const edge of order) { + const text = m.edges[edge.index]!.label!; + const labelParts = text.split("\n"); + const w = Math.max(...labelParts.map((part) => measureText(part, "label"))); + const hgt = 16 * labelParts.length; + const lineW = edge.kind === "main" ? 2 : 1; + const segs = segmentsOf(edge.pts); + const last = segs.length - 1; + const runs: Array<{ horiz: boolean; c: number; p: number; q: number; len: number; pri: number }> = []; + segs.forEach(([a, b], k) => { + const horiz = Math.abs(a.y - b.y) < 0.01; + const s0 = horiz ? a.x : a.y; + let t0 = horiz ? b.x : b.y; + const dir = Math.sign(t0 - s0) || 1; + if (k === last) t0 -= dir * 8; + let parts: Array<[number, number]> = [[s0, t0]]; + const c = horiz ? a.y : a.x; + for (const g of groupRects) { + for (const edgeAt of horiz ? [g.l, g.r] : [g.t, g.b]) { + const within = horiz ? c > g.t && c < g.b : c > g.l && c < g.r; + if (!within) continue; + parts = parts.flatMap(([p, q]) => + edgeAt > Math.min(p, q) + 1 && edgeAt < Math.max(p, q) - 1 + ? ([[p, edgeAt], [edgeAt, q]] as Array<[number, number]>) + : ([[p, q]] as Array<[number, number]>), + ); + } + } + const outside = (p: number, q: number) => { + const mid = (p + q) / 2; + const pt = horiz ? { x: mid, y: c } : { x: c, y: mid }; + return !groupRects.some((g) => pt.x > g.l && pt.x < g.r && pt.y > g.t && pt.y < g.b); + }; + for (const [p, q] of parts) runs.push({ horiz, c, p, q, len: Math.abs(q - p), pri: parts.length > 1 && outside(p, q) ? 1 : 0 }); + }); + runs.sort((x, y) => y.pri - x.pri || y.len - x.len); + + const clear = (box: Rect, checkBounds = true) => { + const G = grow(box, GROW); + if (checkBounds && (box.l < bounds.l || box.r > bounds.r || box.t < bounds.t || box.b > bounds.b)) return false; + if (gNodes.some((n) => boxHitsShape(G, n))) return false; + if (placed.some((p) => hit(G, p))) return false; + if (heads.some((h0) => hit(G, h0))) return false; + if (obstacles.some((r) => hit(G, r))) return false; + return !gLines.some((o) => o.i !== edge.index && segmentsOf(o.pts).some(([a, b]) => hit(G, segRect(a, b, o.width)))); + }; + + let chosen: { box: Rect; on: boolean } | null = null; + for (const run of runs) { + for (const f of [0.5, 1 / 3, 2 / 3]) { + const mid = run.p + (run.q - run.p) * f; + const off = 8 + lineW / 2; + const cands: Array<{ box: Rect; on: boolean }> = []; + if (run.horiz) { + if (run.len >= w + 22) cands.push({ box: { l: mid - w / 2 - 4, r: mid + w / 2 + 4, t: run.c - hgt / 2, b: run.c + hgt / 2 }, on: true }); + cands.push({ box: { l: mid - w / 2, r: mid + w / 2, t: run.c - off - hgt, b: run.c - off }, on: false }); + cands.push({ box: { l: mid - w / 2, r: mid + w / 2, t: run.c + off, b: run.c + off + hgt }, on: false }); + } else { + if (run.len >= hgt + 12) cands.push({ box: { l: run.c - w / 2 - 4, r: run.c + w / 2 + 4, t: mid - hgt / 2, b: mid + hgt / 2 }, on: true }); + cands.push({ box: { l: run.c + off, r: run.c + off + w, t: mid - hgt / 2, b: mid + hgt / 2 }, on: false }); + cands.push({ box: { l: run.c - off - w, r: run.c - off, t: mid - hgt / 2, b: mid + hgt / 2 }, on: false }); + } + chosen = cands.find((c) => clear(c.box)) ?? null; + if (chosen) break; + } + if (chosen) break; + } + if (!chosen && runs.length > 0) { + const r0 = runs[0]!; + const mid = (r0.p + r0.q) / 2; + chosen = r0.horiz + ? { box: { l: mid - w / 2 - 4, r: mid + w / 2 + 4, t: r0.c - hgt / 2, b: r0.c + hgt / 2 }, on: true } + : { box: { l: r0.c - w / 2 - 4, r: r0.c + w / 2 + 4, t: mid - hgt / 2, b: mid + hgt / 2 }, on: true }; + } + if (chosen) { + placed.push(chosen.box); + out.set(edge.index, { box: rectToBox(chosen.box), on: chosen.on }); + } + } + return out; +} + +function groupCellsOf(m: Model, g: Model["groups"][number]) { + const mem = g.all.map((gid) => m.byId.get(gid)!).filter(Boolean); + 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)), + }; +} + +function groupLevelsOf(m: Model, g: Model["groups"][number], side: 0 | 1 | 2 | 3): number { + const c = groupCellsOf(m, g); + if (!c) return 1; + const kids = m.groups.filter((k) => k.parent === g.id); + const reaches = kids.some((k) => { + const kc = groupCellsOf(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; +} + +/** Computes a complete deterministic InteropScene from Basalt's DiagramSpec headlessly (no DOM or browser). */ +export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): InteropScene { + const marksMode = options.marks ?? "omit"; + const reqW = options.width ?? 1104; + const placement = pickPlacement(spec, options.placement, reqW, marksMode, options.resolveMark); + const m = buildModel(spec, { checks: false, placement }); + if (m.unplaced) { + throw new Error('layout="auto" diagram requires a placement: call placeAutoDiagram(spec) or pass options.placement before exporting'); + } + const pad = options.pad ?? 32; + const hasMarks = marksMode === "embed" && m.nodes.some((n) => Boolean(resolveNodeMark(n, marksMode, options.resolveMark))); + const mins = computeMinimums(m, hasMarks); + const targetW = Math.max(reqW, mins.least); + const id = options.diagramId ?? slugId(m.title || m.type); + + if (m.type === "sequence") { + return layoutSequenceHeadless(m, targetW, pad, id, marksMode, options.resolveMark, options.measuredBy); + } + + // Grid geometry + let padTop = 0, padRight = 0, padBottom = 0, padLeft = 0; + if (m.type === "architecture" && m.groups.length > 0) { + const ge = groupEdges(m); + padTop = ge[0] * 32; + padRight = ge[1] * 16; + padBottom = ge[2] * 16; + padLeft = ge[3] * 16; + } + if (m.type === "schema" && m.cols === 1 && m.edges.length > 0) { + const tb = turnBackLanes(m); + padRight = (m.marks ? 28 : 20) + (tb.lanes > 1 ? 12 : 0); + } + + const colGap = m.type === "schema" ? (m.marks ? 60 : 48) : m.type === "data-flow" ? 48 : 64; + const rowGap = m.type === "data-flow" ? 40 : m.type === "schema" ? 32 : 48; + const laneLabelW = m.type === "data-flow" ? 120 : 0; + + const colCount = m.cols; + const availW = targetW - padLeft - padRight - (m.type === "data-flow" ? laneLabelW + colCount * colGap : (colCount - 1) * colGap); + const trackW = round2(availW / colCount); + + // Column x spans (1-based index -> [l, r]). For data-flow, track 0 is lane label, tracks 1..colCount are step cols. + const gridCols: Array<[number, number]> = []; + if (m.type === "data-flow") { + gridCols.push([padLeft, padLeft + laneLabelW]); + let x = padLeft + laneLabelW + colGap; + for (let c = 0; c < colCount; c++) { + gridCols.push([round2(x), round2(x + trackW)]); + x += trackW + colGap; + } + } else { + let x = padLeft; + for (let c = 0; c < colCount; c++) { + gridCols.push([round2(x), round2(x + trackW)]); + x += trackW + colGap; + } + } + + // Measure each node height and compute row track heights (applying portFloors for multi-port boxes) + const floors = portFloors(m); + const nodeMeasured = new Map<string, { h: number; rows?: SceneTableRow[]; headerH?: number; mark?: SceneMark }>(); + const rowHeights: number[] = Array.from({ length: m.rows }, () => (m.type === "data-flow" ? 56 : 0)); + + for (const n of m.nodes) { + const mark = resolveNodeMark(n, marksMode, options.resolveMark); + const minH = Object.prototype.hasOwnProperty.call(floors, n.id) ? floors[n.id]! : 0; + const meas = measureNodeHeight(n, trackW, Boolean(mark), minH); + nodeMeasured.set(n.id, { ...meas, mark }); + if (n.row === n.row2) { + rowHeights[n.row - 1] = Math.max(rowHeights[n.row - 1]!, meas.h); + } + } + // Account for multi-row spanning tables (e.g. row: [1, 2]) + const buildGridRows = (topOffset: number, rowGaps: number[]): Array<[number, number]> => { + const effHeights = rowHeights.slice(); + for (const n of m.nodes) { + if (n.row2 > n.row) { + const meas = nodeMeasured.get(n.id)!; + let spanH = 0; + for (let r = n.row; r <= n.row2; r++) spanH += effHeights[r - 1]!; + for (let r = n.row; r < n.row2; r++) spanH += rowGaps[r - 1]!; + if (meas.h > spanH) effHeights[n.row2 - 1] = effHeights[n.row2 - 1]! + (meas.h - spanH); + } + } + const out: Array<[number, number]> = []; + let curY = topOffset; + for (let r = 0; r < m.rows; r++) { + const rh = Math.max(40, effHeights[r]!); + out.push([round2(curY), round2(curY + rh)]); + curY += rh + (rowGaps[r] ?? rowGap); + } + return out; + }; + + let rowGaps: number[] = Array.from({ length: Math.max(0, m.rows - 1) }, () => rowGap); + let gridRows = buildGridRows(padTop, rowGaps); + + // Schema far keys (|a.col - b.col| >= 2): choose corridors once on the unpadded grid, then widen used gaps/margins. + let corridorPick: Map<number, string> | undefined; + if (m.type === "schema" && gridRows.length > 0) { + const picked = new Map<number, string>(); + const used = new Set<string>(); + 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 cands: Array<{ key: string; y: number; inner: boolean }> = []; + for (let g = 1; g < gridRows.length; g++) { + if (!between.some((n) => n.row <= g && n.row2 >= g + 1)) { + cands.push({ key: `g${g}`, y: (gridRows[g - 1]![1] + gridRows[g]![0]) / 2, inner: true }); + } + } + cands.push( + { key: "top", y: gridRows[0]![0] - 16, inner: false }, + { key: "bottom", y: gridRows[gridRows.length - 1]![1] + 16, inner: false }, + ); + const yA = gridRows[a.row - 1]![0] + (nodeMeasured.get(a.id)?.rows?.[e.fromRow ?? 0]?.midY ?? 0); + const yB = gridRows[b.row - 1]![0] + (nodeMeasured.get(b.id)?.rows?.[e.toRow ?? 0]?.midY ?? 0); + const mid = (yA + yB) / 2; + const chosen = 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; + picked.set(k, chosen); + used.add(chosen); + }); + if (picked.size > 0) { + corridorPick = picked; + if (used.has("top")) padTop = 32; + if (used.has("bottom")) padBottom = 32; + rowGaps = rowGaps.map((g, idx) => (used.has(`g${idx + 1}`) ? 40 : g)); + gridRows = buildGridRows(padTop, rowGaps); + } + } + + const drawingH = round2(gridRows.length ? gridRows[gridRows.length - 1]![1] + padBottom : 100); + const drawingW = round2(targetW); + + // Place nodes + const sceneNodes: SceneNode[] = []; + const nodeById = new Map<string, SceneNode>(); + const gNodeMap = new Map<string, GNode>(); + + for (const n of m.nodes) { + const colIdx = m.type === "data-flow" ? n.col : n.col - 1; + const [cl, cr] = gridCols[colIdx]!; + const [rt] = gridRows[n.row - 1]!; + const [, rb] = gridRows[n.row2 - 1]!; + const meas = nodeMeasured.get(n.id)!; + const w = round2(cr - cl); + const h = round2(meas.h); + // Schema tables align to start of row cell; all other cards center vertically in their row track. + const y = m.type === "schema" ? rt : round2(rt + (rb - rt - h) / 2); + const box: SceneBox = { x: cl, y, w, h }; + const rows = meas.rows?.map((row) => ({ ...row, midY: round2(y + row.y + row.h / 2) })); + const sn: SceneNode = { + id: n.id, + name: n.name, + kind: n.kind, + detail: n.detail, + detailMono: n.mono, + focal: n.focal, + col: n.col, + row: n.row, + row2: n.row2, + shape: n.shape, + group: n.group, + laneId: m.type === "data-flow" ? m.lanes[(n.lane ?? 1) - 1]?.id : undefined, + laneIndex: n.lane ? n.lane - 1 : undefined, + step: n.step, + columns: n.columns, + rows, + headerH: meas.headerH, + more: n.more, + short: n.short, + box, + mark: meas.mark, + }; + sceneNodes.push(sn); + nodeById.set(n.id, sn); + gNodeMap.set(n.id, { id: n.id, rect: boxToRect(box), shape: n.shape, i: n.i }); + } + + // Groups (architecture, supporting nested depth 1 and 2, outer-first) + const sceneGroups: SceneGroup[] = []; + const groupRects: Rect[] = []; + if (m.type === "architecture") { + for (const g of m.groups) { + const c = groupCellsOf(m, g); + if (!c) continue; + const gt = groupLevelsOf(m, g, 0); + const ge = groupLevelsOf(m, g, 1); + const gb = groupLevelsOf(m, g, 2); + const gs = groupLevelsOf(m, g, 3); + const l = round2(gridCols[c.c1 - 1]![0] - gs * 16); + const r = round2(gridCols[c.c2 - 1]![1] + ge * 16); + const t = round2(gridRows[c.r1 - 1]![0] - gt * 32); + const b = round2(gridRows[c.r2 - 1]![1] + gb * 16); + const childGroups = m.groups.filter((k) => k.parent === g.id).map((k) => k.id); + groupRects.push({ l, t, r, b }); + sceneGroups.push({ + id: g.id, + label: g.label, + ...(g.parent ? { parent: g.parent } : {}), + depth: g.depth, + box: { x: l, y: t, w: round2(r - l), h: round2(b - t) }, + members: g.members, + ...(childGroups.length ? { childGroups } : {}), + }); + } + } + + // Lanes (data-flow) + const sceneLanes: SceneLane[] = []; + const laneObstacles: Rect[] = []; + if (m.type === "data-flow") { + for (let k = 0; k < m.lanes.length; k++) { + const lane = m.lanes[k]!; + const [rt, rb] = gridRows[k]!; + const top = k === 0 ? 0 : round2(rt - rowGap / 2); + const bottom = k === m.lanes.length - 1 ? drawingH : round2(rb + rowGap / 2); + sceneLanes.push({ + id: lane.id, + label: lane.label, + box: { x: 0, y: top, w: drawingW, h: round2(bottom - top) }, + labelWidth: laneLabelW, + }); + if (k > 0) laneObstacles.push({ l: 0, r: drawingW, t: top - 0.5, b: top + 0.5 }); + const labelW = Math.min(laneLabelW - 12, measureText(lane.label, "lane")); + const midY = (rt + rb) / 2; + laneObstacles.push({ l: 0, r: labelW, t: midY - 8, b: midY + 8 }); + } + } + + // Group label obstacles + for (const g of sceneGroups) { + const gw = measureText(g.label, "mono"); + laneObstacles.push({ l: g.box.x + 12, r: g.box.x + 12 + gw, t: g.box.y + 8, b: g.box.y + 24 }); + } + + // Route edges using Basalt's exact derivedPorts + gutter/corridor lane solver + const sceneEdges = routeEdges(m, nodeById, gNodeMap, gridCols, gridRows, corridorPick); + + // Seat edge labels + const seated = seatSceneLabels(m, sceneEdges, [...gNodeMap.values()], groupRects, laneObstacles, { l: 0, t: 0, r: drawingW, b: drawingH }); + for (const e of sceneEdges) { + const s = seated.get(e.index); + const text = m.edges[e.index]?.label; + if (s && text) { + e.label = { + text, + box: s.box, + on: s.on, + t: labelArcFraction(e.pts, s.box), + }; + } + } + + return { + type: m.type, + id, + title: m.title, + width: drawingW, + height: drawingH, + pad, + ...(options.measuredBy ? { measuredBy: options.measuredBy } : {}), + nodes: sceneNodes, + groups: sceneGroups, + lanes: sceneLanes, + lifelines: [], + bands: [], + frames: [], + bars: [], + edges: sceneEdges, + }; +} + +function routeEdges( + m: Model, + nodeById: Map<string, SceneNode>, + gNodeMap: Map<string, GNode>, + gridCols: Array<[number, number]>, + gridRows: Array<[number, number]>, + corridorPick?: Map<number, string>, +): SceneEdge[] { + const trackOf = (n: MNode) => (m.type === "data-flow" ? n.col + 1 : n.col); + const tbInfo = turnBackLanes(m); + const dropped = new Set<number>(tbInfo.dropped); + + // Determine sides first so schema arrival offsets can be computed per target side + const derived = m.type === "schema" ? [] : derivedPorts(m); + const sides: Array<[DiagramSide, DiagramSide]> = m.edges.map((e, k) => { + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + if (m.type === "schema") { + if (a.col === b.col) { + const side: DiagramSide = a.col === m.cols && m.cols > 1 ? "left" : "right"; + return [side, side]; + } + const s1: DiagramSide = b.col > a.col ? "right" : "left"; + return [s1, opposite[s1]]; + } + const dp = derived[k]!; + return [dp.fromSide, dp.toSide]; + }); + + // One key, two statements (1.1): lines stating different card.to at one key arrive space-2 (8px) apart + const arrivals = new Map<number, number>(); + if (m.type === "schema") { + const at = new Map<string, number[]>(); + 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) * 8); + } + } + } + + const edgeMeta = m.edges.map((e, k) => { + const na = nodeById.get(e.from)!; + const nb = nodeById.get(e.to)!; + const [s1, s2] = sides[k]!; + let fromPort: ScenePort, toPort: ScenePort; + if (m.type === "schema") { + const r1 = na.rows?.[e.fromRow ?? 0]?.midY ?? (na.box.y + na.box.h / 2); + const r2 = (nb.rows?.[e.toRow ?? 0]?.midY ?? (nb.box.y + nb.box.h / 2)) + (arrivals.get(k) ?? 0); + fromPort = portForSideSlot(s1, (r1 - na.box.y) / na.box.h); + toPort = portForSideSlot(s2, (r2 - nb.box.y) / nb.box.h); + } else { + const dp = derived[k]!; + fromPort = portForSideSlot(s1, dp.fromSlot); + toPort = portForSideSlot(s2, dp.toSlot); + } + const p1 = boxPortPoint(na.box, fromPort); + let p2 = boxPortPoint(nb.box, toPort); + // Keep straight lines strictly aligned on a single axis even when boxes differ slightly in height/width. + if (isH(s1) && isH(s2) && s1 !== s2 && Math.abs(p1.y - p2.y) <= 1.01) { + toPort = portForSideSlot(s2, (p1.y - nb.box.y) / nb.box.h); + p2 = boxPortPoint(nb.box, toPort); + } else if (!isH(s1) && !isH(s2) && s1 !== s2 && Math.abs(p1.x - p2.x) <= 1.01) { + toPort = portForSideSlot(s2, (p1.x - nb.box.x) / nb.box.w); + p2 = boxPortPoint(nb.box, toPort); + } + return { s1, s2, fromPort, toPort, p1, p2 }; + }); + + // Schema far keys through their corridors (mirroring diagram-core.ts) + const far = new Map<number, { corridor: string; first: { key: string; span: [number, number] } | null; y: number }>(); + if (m.type === "schema" && gridRows.length > 0) { + m.edges.forEach((e, k) => { + if (dropped.has(k)) return; + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + if (Math.abs(a.col - b.col) < 2) return; + const chosen = corridorPick?.get(k) ?? "top"; + const ti = sides[k]![0] === "right" ? a.col : a.col - 1; + const t1 = gridCols[ti - 1], t2 = gridCols[ti]; + far.set(k, { corridor: chosen, first: t1 && t2 ? { key: `c${ti}`, span: [t1[1], t2[0]] } : null, y: 0 }); + }); + } + + const corridorGroups = new Map<string, number[][]>(); + 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(edgeMeta[g[0]!]!.p2.y - edgeMeta[k]!.p2.y) < 0.5; + }); + if (bus) bus.push(k); + else if (groups.length >= 2) dropped.add(k); + else groups.push([k]); + corridorGroups.set(f.corridor, groups); + } + for (const k of [...far.keys()]) if (dropped.has(k)) far.delete(k); + + 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(edgeMeta[g[0]!]!.p1.x - edgeMeta[g[0]!]!.p2.x); + }; + const corridorY = (key: string, j: number, count: number): number => { + if (key === "top") return round2(gridRows[0]![0] - 16 - j * 12); + if (key === "bottom") return round2(gridRows[gridRows.length - 1]![1] + 16 + j * 12); + const g = Number(key.slice(1)); + return round2((gridRows[g - 1]![1] + gridRows[g]![0]) / 2 + (j - (count - 1) / 2) * 12); + }; + 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(); + + // Gutter jog clustering and lane permutation solver (mirrors diagram-core.ts) + const jogs = new Map<string, { span: [number, number]; vertical: boolean; members: Map<string, number[]> }>(); + const turnBacks = new Set<number>(); + const farLast = new Map<number, [number, number]>(); + 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; + const f = far.get(k); + if (f?.first) join(f.first.key, f.first.span, true, `far:${k}`, -(k + 1)); + const { s1, s2, p1, p2 } = edgeMeta[k]!; + const a = m.byId.get(e.from)!, b = m.byId.get(e.to)!; + let key: string | null = null, span: [number, number] | null = null, vertical = false; + if (s1 === s2) { + if (isH(s1)) { + const ti = s1 === "right" ? Math.max(trackOf(a), trackOf(b)) : Math.min(trackOf(a), trackOf(b)) - 1; + const t1 = gridCols[ti - 1], t2 = gridCols[ti]; + if (t1 && t2) { key = `c${ti}`; span = [t1[1], t2[0]]; vertical = true; } + } else { + const ri = s1 === "bottom" ? Math.max(a.row2, b.row2) : Math.min(a.row, b.row) - 1; + const r1 = gridRows[ri - 1], r2 = gridRows[ri]; + if (r1 && r2) { key = `r${ri}`; span = [r1[1], r2[0]]; vertical = false; } + } + if (key) turnBacks.add(k); + } else if (isH(s1) && isH(s2) && (f || Math.abs(p1.y - p2.y) > 0.5)) { + const ti = trackOf(b); + const leftSide = s2 === "left"; + const t1 = gridCols[(leftSide ? ti - 1 : ti) - 1]; + const t2 = gridCols[(leftSide ? ti : ti + 1) - 1]; + if (t1 && t2) { key = `c${leftSide ? ti - 1 : ti}`; span = [t1[1], t2[0]]; vertical = true; } + } else if (!isH(s1) && !isH(s2) && Math.abs(p1.x - p2.x) > 0.5) { + const topSide = s2 === "top"; + const ri = topSide ? b.row - 1 : b.row2; + const r1 = gridRows[ri - 1], r2 = gridRows[ri]; + if (r1 && r2) { key = `r${ri}`; span = [r1[1], r2[0]]; vertical = false; } + } + if (!key || !span) return; + 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<number, number>(); + const rawRoute = (k: number): Pt[] => { + const { s1, s2, p1, p2 } = edgeMeta[k]!; + const f = far.get(k); + if (f) { + const last = farLast.get(k); + const x1 = round2(lanes.get(-(k + 1)) ?? (f.first ? (f.first.span[0] + f.first.span[1]) / 2 : p1.x)); + const x2 = round2(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 out = (m.marks ? 24 : 16) + (m.type === "schema" && m.cols === 1 ? (tbInfo.lane.get(k) ?? 0) * 12 : 0); + const x = round2(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, p2]; + const x = round2(lanes.get(k) ?? (p1.x + p2.x) / 2); + return [p1, { x, y: p1.y }, { x, y: p2.y }, p2]; + } + if (!isH(s1) && !isH(s2)) { + if (s1 === s2) { + const y = round2(lanes.get(k) ?? (s1 === "bottom" ? Math.max(p1.y, p2.y) + 16 : Math.min(p1.y, p2.y) - 16)); + return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; + } + if (Math.abs(p1.x - p2.x) <= 0.5) return [p1, p2]; + const y = round2(lanes.get(k) ?? (p1.y + p2.y) / 2); + return [p1, { x: p1.x, y }, { x: p2.x, y }, p2]; + } + if (isH(s1)) return [p1, { x: p2.x, y: p1.y }, p2]; + return [p1, { x: p1.x, y: p2.y }, p2]; + }; + + const gNodes = [...gNodeMap.values()]; + const buildGLine = (k: number): GLine => { + const e = m.edges[k]!; + const meta = edgeMeta[k]!; + const pts = snapRouteToPorts(rawRoute(k), meta.p1, meta.p2, meta.s1, meta.s2); + return { i: k, from: e.from, to: e.to, kind: e.kind, pts, tip: pts[pts.length - 1]!, dir: dirOf(pts), width: e.kind === "main" ? 2 : 1 }; + }; + const buildAll = () => m.edges.flatMap((_, k) => (dropped.has(k) ? [] : [buildGLine(k)])); + let current: GLine[] | null = null; + const score = (members: Set<number>) => { + current ??= buildAll(); + const lines = current.map((l) => (members.has(l.i) ? buildGLine(l.i) : l)); + let through = 0; + for (const l of lines) { + if (!members.has(l.i)) continue; + if (gNodes.some((n) => segmentsOf(l.pts).some(([a, b]) => segmentThrough(a, b, n)))) through++; + } + return { lines, score: overlapsCount(lines, members) * 100000 + findCrossingsCount(lines, members) * 1000 + through }; + }; + + const edgeOf = (id: number) => (id < 0 ? -id - 1 : id); + const runOf = (members: number[], vertical: boolean): [number, number] => { + const vals = members.flatMap((id) => { + const k = edgeOf(id); + const { p1, p2 } = edgeMeta[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(...vals), Math.max(...vals)]; + }; + const clustersOf = (g: { span: [number, number]; vertical: boolean; members: Map<string, number[]> }) => { + const ports = [...g.members.values()].map((members) => ({ members, run: runOf(members, g.vertical) })).sort((a, b) => a.run[0] - b.run[0]); + const clusters: Array<typeof ports> = []; + for (const p of ports) { + const last = clusters[clusters.length - 1]; + if (last && last.some((q) => q.run[0] < p.run[1] + 32 && p.run[0] < q.run[1] + 32)) last.push(p); + else clusters.push([p]); + } + return clusters.filter((cluster) => !(cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k)))); + }; + type Cluster = ReturnType<typeof clustersOf>[number]; + const besideIn = (cluster: Cluster) => (i: number, j: number) => + cluster[i]!.run[0] < cluster[j]!.run[1] + 32 && cluster[j]!.run[0] < cluster[i]!.run[1] + 32; + 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; + + 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; + } + 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) { dropped.add(k); far.delete(k); } + gather(); + } + } + + 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 = 18; // foot (14) + radius-xs (4) + 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; + }; + + // Optimize interior corridor lane order + 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) { + 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 inGutter = new Set(groupsOf.flat().map(edgeOf)); + let best = groupsOf, bestScore = Infinity, bestLines: GLine[] | null = null; + for (const perm of permutations(groupsOf)) { + 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, laneAt(g.span, j, count)))); + current = bestLines; + } + } + + const out: SceneEdge[] = []; + m.edges.forEach((e, k) => { + if (dropped.has(k)) return; + const meta = edgeMeta[k]!; + const pts = snapRouteToPorts(rawRoute(k), meta.p1, meta.p2, meta.s1, meta.s2); + if (m.marks && e.card) { + const segs = segmentsOf(pts); + const segLen = ([a, b]: readonly [Pt, Pt]) => Math.hypot(b.x - a.x, b.y - a.y); + const need = segs.length === 1 ? 28 : 17.5; + if (segLen(segs[0]!) < need || segLen(segs[segs.length - 1]!) < need) return; + } + out.push({ + index: k, + from: e.from, + to: e.to, + fromRow: e.fromRow, + toRow: e.toRow, + fk: Boolean(e.fk), + ...(e.card ? { card: e.card } : {}), + kind: e.kind, + openTip: e.kind === "dashed", + fromPort: meta.fromPort, + toPort: meta.toPort, + pts, + }); + }); + return out; +} + +const clamp01 = (v: number): number => Math.max(0, Math.min(1, v)); + +function findActiveBar(bars: SceneBar[], who: string, msgNum: number, opening: boolean): SceneBar | undefined { + return bars + .filter((b) => b.participantId === who && b.toMsg >= msgNum && (opening ? b.fromMsg <= msgNum : b.fromMsg < msgNum || (b.fromMsg === msgNum && b.toMsg === msgNum))) + .sort((a, b) => b.depth - a.depth)[0]; +} + +function frameHeaderLabelBox(box: SceneBox, tabBox: SceneBox, label: string): SceneBox { + // Matches `.basalt-diagram-fhead` (gap: 12px) + `.basalt-diagram-flabel` (margin-inline-start: -6px, padding-inline: 6px). + const x = round2(tabBox.x + tabBox.w + 6); + const maxW = Math.max(16, box.x + box.w - x - 6); + const w = round2(Math.min(maxW, measureText(label, "label") + 12)); + return { x, y: round2(tabBox.y + 4), w, h: 16 }; +} + +function frameElseLabelBox(box: SceneBox, divY: number, divH: number, isAlt: boolean, label: string): SceneBox { + // Matches `.basalt-diagram-felse` (padding-inline-start: 12px, gap: 6px) + `.basalt-diagram-fword` (-6px, pad 6px) + `.basalt-diagram-flabel`. + const x = round2(box.x + 6); + const elseW = isAlt ? measureText("else", "mono") : 0; + const lblW = label ? measureText(label, "label") : 0; + const rawW = elseW + (isAlt && label ? 6 : 0) + lblW + 12; + const maxW = Math.max(16, box.w - 12); + const w = round2(Math.min(maxW, rawW)); + return { x, y: round2(divY + Math.max(0, (divH - 16) / 2)), w, h: 16 }; +} + +function layoutSequenceHeadless( + m: Model, + targetW: number, + pad: number, + id: string, + marksMode: "omit" | "embed", + resolveMark?: InteropMarkResolver, + measuredBy?: string, +): InteropScene { + const n = Math.max(1, m.nodes.length); + const gap = 20; + const colW = round2((targetW - (n - 1) * gap) / n); + const marksByNode = m.nodes.map((p) => resolveNodeMark(p, marksMode, resolveMark)); + let headH = 44; + m.nodes.forEach((p, idx) => { + headH = Math.max(headH, measureNodeHeight(p, colW, Boolean(marksByNode[idx])).h); + }); + + const sceneNodes: SceneNode[] = m.nodes.map((p, idx) => { + const x = round2(idx * (colW + gap)); + return { + id: p.id, + name: p.name, + kind: p.kind, + detailMono: false, + focal: p.focal, + col: p.col, + row: 1, + row2: 1, + shape: "participant", + short: p.short, + box: { x, y: 0, w: colW, h: headH }, + ...(marksByNode[idx] ? { mark: marksByNode[idx] } : {}), + }; + }); + + const cxById = new Map<string, number>(); + sceneNodes.forEach((p) => cxById.set(p.id, round2(p.box.x + p.box.w / 2))); + + let y = headH + 16; // steps padding-block-start: space-4 + const bands: SceneBand[] = []; + const frames: SceneFrame[] = []; + const frameStack: Array<{ frame: SceneFrame; a: number; b: number; topY: number; fis: number; fie: number }> = []; + const prevWasFrame = new Map<number, boolean>(); + const stepEntries: Array<{ n: number; from: string; to: string; kind: SceneEdge["kind"]; label: string; note?: string; y: number; selfSide?: "start" | "end" }> = []; + + for (const s of m.steps) { + if ("band" in s) { + prevWasFrame.set(frameStack.length, false); + bands.push({ text: s.band, y: round2(y), h: 36, w: round2(targetW) }); + y += 36; + } else if ("open" in s) { + if (prevWasFrame.get(frameStack.length)) y += 8; // sibling frame margin-block-start: space-2 + const parent = frameStack[frameStack.length - 1]; + const fis = parent && s.a === parent.a ? 1 : 0; + const fie = parent && s.b === parent.b ? 1 : 0; + const fx = round2((s.a - 1) * (colW + gap) + fis * 8); + const fw = round2((s.b - s.a + 1) * (colW + gap) - gap - (fis + fie) * 8); + const tabW = round2(measureText(s.open, "mono") + 24); + const box: SceneBox = { x: fx, y: round2(y), w: fw, h: 44 }; + const tabBox: SceneBox = { x: round2(fx + 1), y: round2(y + 1), w: tabW, h: 24 }; + const frame: SceneFrame = { + id: `f${frames.length}`, + operator: s.open, + label: s.label, + depth: s.depth, + ...(parent ? { parentId: parent.frame.id } : {}), + box, + tabBox, + ...(s.label ? { labelBox: frameHeaderLabelBox(box, tabBox, s.label) } : {}), + dividers: [], + }; + frames.push(frame); + frameStack.push({ frame, a: s.a, b: s.b, topY: y, fis, fie }); + prevWasFrame.set(frameStack.length, false); + y += 36; // frame header row (size-control-lg) + } else if ("otherwise" in s) { + const cur = frameStack[frameStack.length - 1]; + if (cur) { + const divY = round2(y); + const labelBox = (s.otherwise || cur.frame.operator === "alt") + ? frameElseLabelBox(cur.frame.box, divY, 28, cur.frame.operator === "alt", s.otherwise) + : undefined; + cur.frame.dividers.push({ y: divY, h: 28, label: s.otherwise, ...(labelBox ? { labelBox } : {}) }); + } + prevWasFrame.set(frameStack.length, false); + y += 28; // else branch header (size-control-sm) + } else if ("close" in s) { + const popped = frameStack.pop(); + y += 8; // frame bottom padding (space-2) + if (popped) popped.frame.box.h = round2(y - popped.topY); + prevWasFrame.set(frameStack.length, true); + } else if ("n" in s) { + prevWasFrame.set(frameStack.length, false); + const a = m.byId.get(s.from); + const self = s.from === s.to; + const selfSide: "start" | "end" | undefined = self ? (a && a.col === n ? "start" : "end") : undefined; + stepEntries.push({ n: s.n, from: s.from, to: s.to, kind: s.kind, label: s.label, note: s.note, y: round2(y + 28), selfSide }); + y += 56; + } + } + + const bottom = round2(Math.max(y, headH + 40)); + const lifelines: SceneLifeline[] = sceneNodes.map((p) => ({ + id: `life-${p.id}`, + participantId: p.id, + x: cxById.get(p.id)!, + y1: headH, + y2: bottom, + })); + const lifeByParticipant = new Map(lifelines.map((l) => [l.participantId, l])); + + // Activation bars (8px wide, shifted 4px toward end side per depth; 1-row self-call spans y-12..y+12) + const msgYByNum = new Map(stepEntries.map((s) => [s.n, s.y])); + const bars: SceneBar[] = []; + m.bars.forEach((bar: MBar, idx: number) => { + const who = m.byId.get(bar.who); + const lx = cxById.get(bar.who); + if (!who || lx === undefined) return; + const lastOne = who.i === m.nodes.length - 1 && m.nodes.length > 1; + const dir = lastOne ? -1 : 1; + const off = (bar.depth - 1) * 4 * dir; + const y1 = msgYByNum.get(bar.from) ?? headH + 16; + const y2 = msgYByNum.get(bar.to) ?? y1; + const one = bar.from === bar.to; + const top = round2(one ? y1 - 12 : y1); + const bot = round2(one ? y1 + 12 : y2); + bars.push({ + id: `bar-${bar.who}-${idx}`, + participantId: bar.who, + fromMsg: bar.from, + toMsg: bar.to, + depth: bar.depth, + box: { x: round2(lx - 4 + off), y: top, w: 8, h: round2(Math.max(1, bot - top)) }, + }); + }); + + const edges: SceneEdge[] = stepEntries.map((s) => { + const lf1 = lifeByParticipant.get(s.from)!; + const lf2 = lifeByParticipant.get(s.to)!; + const span1 = Math.max(1, lf1.y2 - lf1.y1); + const span2 = Math.max(1, lf2.y2 - lf2.y1); + let pts: Pt[]; + let fromPort: ScenePort; + let toPort: ScenePort; + let fromBarId: string | undefined; + let toBarId: string | undefined; + if (s.from === s.to) { + const out = s.selfSide === "start" ? -24 : 24; + const side: DiagramSide = s.selfSide === "start" ? "left" : "right"; + const yt = round2(s.y - 8); + const yb = round2(s.y + 8); + const bar = findActiveBar(bars, s.from, s.n, true); + const edgeX = bar ? round2(out > 0 ? bar.box.x + bar.box.w : bar.box.x) : lf1.x; + pts = [ + { x: edgeX, y: yt }, + { x: round2(lf1.x + out), y: yt }, + { x: round2(lf1.x + out), y: yb }, + { x: edgeX, y: yb }, + ]; + if (bar) { + fromBarId = bar.id; + toBarId = bar.id; + const bx = out > 0 ? 1 : 0; + fromPort = { x: bx, y: round6(clamp01((yt - bar.box.y) / bar.box.h)), side }; + toPort = { x: bx, y: round6(clamp01((yb - bar.box.y) / bar.box.h)), side }; + } else { + fromPort = { x: 0.5, y: round6(clamp01((yt - lf1.y1) / span1)), side }; + toPort = { x: 0.5, y: round6(clamp01((yb - lf2.y1) / span2)), side }; + } + } else { + const dirRight = lf2.x >= lf1.x; + const sb = findActiveBar(bars, s.from, s.n, false); + const rb = findActiveBar(bars, s.to, s.n, true); + const x1 = sb ? round2(dirRight ? sb.box.x + sb.box.w : sb.box.x) : lf1.x; + const x2 = rb ? round2(dirRight ? rb.box.x : rb.box.x + rb.box.w) : lf2.x; + pts = [{ x: x1, y: s.y }, { x: x2, y: s.y }]; + if (sb) { + fromBarId = sb.id; + fromPort = { x: dirRight ? 1 : 0, y: round6(clamp01((s.y - sb.box.y) / sb.box.h)), side: dirRight ? "right" : "left" }; + } else { + fromPort = { x: 0.5, y: round6(clamp01((s.y - lf1.y1) / span1)), side: dirRight ? "right" : "left" }; + } + if (rb) { + toBarId = rb.id; + toPort = { x: dirRight ? 0 : 1, y: round6(clamp01((s.y - rb.box.y) / rb.box.h)), side: dirRight ? "left" : "right" }; + } else { + toPort = { x: 0.5, y: round6(clamp01((s.y - lf2.y1) / span2)), side: dirRight ? "left" : "right" }; + } + } + const text = `${s.n} ${s.label}`; + const lw = Math.max(measureText(text, "label"), s.note ? measureText(s.note, "sans") : 0); + const lh = s.note ? 32 : 16; + const midX = s.from === s.to + ? (s.selfSide === "start" ? lf1.x - 24 - 10 - lw / 2 : lf1.x + 24 + 10 + lw / 2) + : (lf1.x + lf2.x) / 2; + const labelY = s.from === s.to ? round2(s.y - lh / 2) : round2(s.y - lh - 6); + return { + index: s.n - 1, + messageNumber: s.n, + from: s.from, + to: s.to, + sequence: true, + ...(fromBarId ? { fromBarId } : {}), + ...(toBarId ? { toBarId } : {}), + fk: false, + kind: s.kind, + openTip: s.kind === "dashed", + fromPort, + toPort, + pts, + selfSide: s.selfSide, + label: { + text, + note: s.note, + box: { x: round2(midX - lw / 2), y: labelY, w: round2(lw), h: lh }, + on: false, + t: 0.5, + }, + }; + }); + + return { + type: "sequence", + id, + title: m.title, + width: round2(targetW), + height: bottom, + pad, + ...(measuredBy ? { measuredBy } : {}), + nodes: sceneNodes, + groups: [], + lanes: [], + lifelines, + bands, + frames, + bars, + edges, + }; +} + +// ---- Live measured Geo -> InteropScene ---- + +function portFromBoxAndPoint(box: SceneBox, pt: Pt, exactRow: boolean): ScenePort { + const fx = box.w > 0 ? (pt.x - box.x) / box.w : 0.5; + const fy = box.h > 0 ? (pt.y - box.y) / box.h : 0.5; + const dLeft = Math.abs(pt.x - box.x); + const dRight = Math.abs(pt.x - (box.x + box.w)); + const dTop = Math.abs(pt.y - box.y); + const dBottom = Math.abs(pt.y - (box.y + box.h)); + const m = Math.min(dLeft, dRight, dTop, dBottom); + const clamp = (v: number) => round6(clamp01(v)); + const snap = (v: number) => { + if (exactRow) return clamp(v); + for (const s of [0, 0.25, 0.5, 0.75, 1]) if (Math.abs(v - s) < 0.015) return s; + return clamp(v); + }; + if (m === dLeft) return { x: 0, y: snap(fy), side: "left" }; + if (m === dRight) return { x: 1, y: snap(fy), side: "right" }; + if (m === dTop) return { x: snap(fx), y: 0, side: "top" }; + return { x: snap(fx), y: 1, side: "bottom" }; +} + +/** Converts a live figure's measured `Geo` (from diagram-core's `measureFigure`) into an InteropScene. */ +export function sceneFromMeasured( + spec: DiagramSpec, + geo: Geo, + extras: MeasuredExtras = {}, + options: InteropOptions = {}, +): InteropScene { + const placement = pickPlacementForMeasured(spec, geo, options.placement); + const m = buildModel(spec, { checks: false, placement }); + const pad = options.pad ?? 32; + const marksMode = options.marks ?? "omit"; + const id = options.diagramId ?? slugId(m.title || m.type); + + const gNodeById = new Map(geo.nodes.map((gn) => [gn.id, gn])); + const sceneNodes: SceneNode[] = m.nodes.map((n) => { + const gn = gNodeById.get(n.id); + const box: SceneBox = gn ? rectToBox(gn.rect) : { x: 0, y: 0, w: 144, h: 64 }; + const mark = resolveNodeMark(n, marksMode, options.resolveMark); + let rows: SceneTableRow[] | undefined; + let headerH: number | undefined; + if (n.shape === "table") { + headerH = 37; + const measuredYs = extras.tableRows?.[n.id]; + const cols = n.columns ?? []; + const rowH = cols.length > 0 && !measuredYs + ? round2((box.h - headerH - 8 - (n.more ? 24 : 0) - 2) / cols.length) + : 28; + rows = cols.map((c, idx) => { + const midY = measuredYs?.[idx] ?? round2(box.y + headerH! + 4 + idx * rowH + rowH / 2); + const ry = round2(midY - box.y - rowH / 2); + return { index: idx, name: c.name, key: c.key, type: c.type, refTable: c.ref?.table, y: ry, h: rowH, midY }; + }); + } + return { + id: n.id, + name: n.name, + kind: n.kind, + detail: n.detail, + detailMono: n.mono, + focal: n.focal, + col: n.col, + row: n.row, + row2: n.row2, + shape: n.shape, + group: n.group, + laneId: m.type === "data-flow" ? m.lanes[(n.lane ?? 1) - 1]?.id : undefined, + laneIndex: n.lane ? n.lane - 1 : undefined, + step: n.step, + columns: n.columns, + rows, + headerH, + more: n.more, + short: n.short, + box, + mark, + }; + }); + const nodeById = new Map(sceneNodes.map((n) => [n.id, n])); + + // Groups (outer-first, preserving nested depth 1 and 2) + const sceneGroups: SceneGroup[] = []; + if (m.type === "architecture") { + const extraById = new Map((extras.groups ?? []).map((g) => [g.id, g])); + // Compute fallback rects bottom-up so an outer group encloses its child groups cleanly when extras.groups is omitted. + const computedBox = new Map<string, SceneBox>(); + for (const g of [...m.groups].reverse()) { + const eg = extraById.get(g.id); + if (eg) { + computedBox.set(g.id, rectToBox(eg.rect)); + continue; + } + const rects: SceneBox[] = g.members.map((gid) => nodeById.get(gid)?.box).filter((x): x is SceneBox => Boolean(x)); + for (const child of m.groups.filter((k) => k.parent === g.id)) { + const cb = computedBox.get(child.id); + if (cb) rects.push(cb); + } + if (!rects.length) continue; + const l = round2(Math.min(...rects.map((x) => x.x)) - 16); + const r = round2(Math.max(...rects.map((x) => x.x + x.w)) + 16); + const t = round2(Math.min(...rects.map((x) => x.y)) - 32); + const b = round2(Math.max(...rects.map((x) => x.y + x.h)) + 16); + computedBox.set(g.id, { x: l, y: t, w: round2(r - l), h: round2(b - t) }); + } + for (const g of m.groups) { + const box = computedBox.get(g.id); + if (!box) continue; + const childGroups = m.groups.filter((k) => k.parent === g.id).map((k) => k.id); + sceneGroups.push({ + id: g.id, + label: g.label, + ...(g.parent ? { parent: g.parent } : {}), + depth: g.depth, + box, + members: g.members, + ...(childGroups.length ? { childGroups } : {}), + }); + } + } + + // Lanes + const sceneLanes: SceneLane[] = []; + if (m.type === "data-flow") { + const extraLanes = extras.lanes ?? []; + const extraById = new Map(extraLanes.map((l) => [l.id, l])); + const extraByIndex = new Map<number, MeasuredLane>(); + extraLanes.forEach((l, k) => extraByIndex.set(l.index ?? k, l)); + const rowBounds: Array<[number, number]> = m.lanes.map((lane, idx) => { + const el = extraById.get(lane.id) ?? extraByIndex.get(idx); + if (el) return [el.rect.t, el.rect.b]; + const members = sceneNodes.filter((n) => n.laneIndex === idx); + if (members.length) return [Math.min(...members.map((x) => x.box.y)), Math.max(...members.map((x) => x.box.y + x.box.h))]; + const est = idx * 96; + return [est, est + 56]; + }); + for (let k = 0; k < m.lanes.length; k++) { + const lane = m.lanes[k]!; + const [rt, rb] = rowBounds[k]!; + const top = k === 0 ? 0 : round2((rowBounds[k - 1]![1] + rt) / 2); + const bottom = k === m.lanes.length - 1 ? round2(geo.h) : round2((rb + rowBounds[k + 1]![0]) / 2); + sceneLanes.push({ id: lane.id, label: lane.label, box: { x: 0, y: top, w: round2(geo.w), h: round2(bottom - top) }, labelWidth: 120 }); + } + } + + // Sequence lifelines, bands, frames, activation bars, messages + if (m.type === "sequence") { + const lifelines: SceneLifeline[] = m.nodes.map((p, idx) => { + const lf = geo.lifelines[idx]; + const box = nodeById.get(p.id)!.box; + const x = round2(lf?.x ?? box.x + box.w / 2); + return { id: `life-${p.id}`, participantId: p.id, x, y1: round2(lf?.y1 ?? box.y + box.h), y2: round2(lf?.y2 ?? geo.h) }; + }); + const lifeByP = new Map(lifelines.map((l) => [l.participantId, l])); + const lineByNum = new Map(geo.lines.map((l) => [l.i, l])); + + const bands: SceneBand[] = []; + if (extras.bands?.length) { + for (const b of extras.bands) bands.push({ text: b.text, y: round2(b.rect.t), h: round2(b.rect.b - b.rect.t), w: round2(geo.w) }); + } else { + let curY = (sceneNodes[0]?.box.h ?? 44) + 16; + for (const s of m.steps) { + if ("band" in s) { + bands.push({ text: s.band, y: round2(curY), h: 36, w: round2(geo.w) }); + curY += 36; + } else if ("n" in s) { + const gl = lineByNum.get(s.n); + const msgCenterY = gl ? (gl.pts[0]!.y + gl.pts[gl.pts.length - 1]!.y) / 2 : curY + 28; + curY = Math.max(curY + 56, msgCenterY + 28); + } + } + } + + // Frames from live DOM measurements (or synthesized fallback when extras.frames was omitted) + const frames: SceneFrame[] = []; + if (extras.frames?.length) { + extras.frames.forEach((ef, idx) => { + const box = rectToBox(ef.rect); + const tabW = round2(measureText(ef.operator, "mono") + 24); + const tabBox: SceneBox = ef.tabRect + ? rectToBox(ef.tabRect) + : { x: round2(box.x + 1), y: round2(box.y + 1), w: tabW, h: 24 }; + const labelBox = ef.labelRect + ? rectToBox(ef.labelRect) + : ef.label + ? frameHeaderLabelBox(box, tabBox, ef.label) + : undefined; + frames.push({ + id: `f${idx}`, + operator: ef.operator, + label: ef.label, + depth: ef.depth, + ...(ef.parentIndex !== undefined ? { parentId: `f${ef.parentIndex}` } : {}), + box, + tabBox, + ...(labelBox ? { labelBox } : {}), + dividers: ef.dividers.map((d) => { + const divY = round2(d.y); + const divH = round2(d.h); + const dLabelBox = d.labelRect + ? rectToBox(d.labelRect) + : (d.label || ef.operator === "alt") + ? frameElseLabelBox(box, divY, divH, ef.operator === "alt", d.label) + : undefined; + return { y: divY, h: divH, label: d.label, ...(dLabelBox ? { labelBox: dLabelBox } : {}) }; + }), + }); + }); + } else if (m.steps.some((s) => "open" in s)) { + const stack: Array<{ frame: SceneFrame; a: number; b: number; firstMsgY?: number; lastMsgY?: number; fis: number; fie: number }> = []; + for (const s of m.steps) { + if ("open" in s) { + const parent = stack[stack.length - 1]; + const fis = parent && s.a === parent.a ? 1 : 0; + const fie = parent && s.b === parent.b ? 1 : 0; + const leftNode = sceneNodes[s.a - 1]; + const rightNode = sceneNodes[s.b - 1]; + const fx = round2((leftNode ? leftNode.box.x : 0) + fis * 8); + const fr = round2((rightNode ? rightNode.box.x + rightNode.box.w : geo.w) - fie * 8); + const tabW = round2(measureText(s.open, "mono") + 24); + const box: SceneBox = { x: fx, y: 0, w: round2(Math.max(40, fr - fx)), h: 44 }; + const tabBox: SceneBox = { x: round2(fx + 1), y: 1, w: tabW, h: 24 }; + const frame: SceneFrame = { + id: `f${frames.length}`, + operator: s.open, + label: s.label, + depth: s.depth, + ...(parent ? { parentId: parent.frame.id } : {}), + box, + tabBox, + ...(s.label ? { labelBox: frameHeaderLabelBox(box, tabBox, s.label) } : {}), + dividers: [], + }; + frames.push(frame); + stack.push({ frame, a: s.a, b: s.b, fis, fie }); + } else if ("otherwise" in s) { + const cur = stack[stack.length - 1]; + if (cur) { + const divY = round2((cur.lastMsgY ?? 0) + 28); + const labelBox = (s.otherwise || cur.frame.operator === "alt") + ? frameElseLabelBox(cur.frame.box, divY, 28, cur.frame.operator === "alt", s.otherwise) + : undefined; + cur.frame.dividers.push({ y: divY, h: 28, label: s.otherwise, ...(labelBox ? { labelBox } : {}) }); + } + } else if ("close" in s) { + const popped = stack.pop(); + if (popped) { + const topY = round2((popped.firstMsgY ?? 96) - 64); + const botY = round2((popped.lastMsgY ?? topY + 64) + 36); + popped.frame.box.y = topY; + popped.frame.box.h = round2(Math.max(44, botY - topY)); + popped.frame.tabBox.y = round2(topY + 1); + if (popped.frame.label) { + popped.frame.labelBox = frameHeaderLabelBox(popped.frame.box, popped.frame.tabBox, popped.frame.label); + } + } + } else if ("n" in s) { + const gl = lineByNum.get(s.n); + const my = gl ? (gl.pts[0]!.y + gl.pts[gl.pts.length - 1]!.y) / 2 : 0; + for (const entry of stack) { + if (entry.firstMsgY === undefined) entry.firstMsgY = my; + entry.lastMsgY = my; + } + } + } + } + + // Activation bars from geo.bars (paired 1:1 with m.bars) + const bars: SceneBar[] = []; + m.bars.forEach((bar: MBar, idx: number) => { + const measuredRect = geo.bars?.[idx]; + let box: SceneBox; + if (measuredRect) { + box = rectToBox(measuredRect); + } else { + const who = m.byId.get(bar.who); + const lf = lifeByP.get(bar.who); + const lx = lf?.x ?? 0; + const lastOne = who ? who.i === m.nodes.length - 1 && m.nodes.length > 1 : false; + const off = (bar.depth - 1) * 4 * (lastOne ? -1 : 1); + const g1 = lineByNum.get(bar.from), g2 = lineByNum.get(bar.to); + const y1 = g1 ? (g1.pts[0]!.y + g1.pts[g1.pts.length - 1]!.y) / 2 : 80; + const y2 = g2 ? (g2.pts[0]!.y + g2.pts[g2.pts.length - 1]!.y) / 2 : y1; + const one = bar.from === bar.to; + const top = round2(one ? y1 - 12 : y1); + const bot = round2(one ? y1 + 12 : y2); + box = { x: round2(lx - 4 + off), y: top, w: 8, h: round2(Math.max(1, bot - top)) }; + } + bars.push({ + id: `bar-${bar.who}-${idx}`, + participantId: bar.who, + fromMsg: bar.from, + toMsg: bar.to, + depth: bar.depth, + box, + }); + }); + + // Align opening/closing bar ends by at most 0.5px when a 2px main message's snapped Y sits 0.5px outside a 1px bar edge, + // so horizontal sequence edges stay strictly axis-aligned (dy = 0.00px) while remaining within <= 0.5px of geo.bars. + for (const s of m.steps) { + if (!("n" in s) || s.from === s.to) continue; + const gl = lineByNum.get(s.n); + if (!gl) continue; + const y = round2(gl.pts[0]!.y); + for (const bar of [findActiveBar(bars, s.from, s.n, false), findActiveBar(bars, s.to, s.n, true)]) { + if (!bar) continue; + if (y < bar.box.y && bar.box.y - y <= 0.51) { + const diff = round2(bar.box.y - y); + bar.box.y = y; + bar.box.h = round2(bar.box.h + diff); + } else if (y > bar.box.y + bar.box.h && y - (bar.box.y + bar.box.h) <= 0.51) { + bar.box.h = round2(y - bar.box.y); + } + } + } + + const edges: SceneEdge[] = []; + for (const s of m.steps) { + if (!("n" in s)) continue; + const gl = lineByNum.get(s.n); + const lf1 = lifeByP.get(s.from); + const lf2 = lifeByP.get(s.to); + if (!gl || !lf1 || !lf2) continue; + const span1 = Math.max(1, lf1.y2 - lf1.y1); + const span2 = Math.max(1, lf2.y2 - lf2.y1); + const self = s.from === s.to; + const a = m.byId.get(s.from); + const selfSide: "start" | "end" | undefined = self ? (a && a.col === m.nodes.length ? "start" : "end") : undefined; + let pts: Pt[]; + let fromPort: ScenePort; + let toPort: ScenePort; + let fromBarId: string | undefined; + let toBarId: string | undefined; + if (self) { + const side: DiagramSide = selfSide === "start" ? "left" : "right"; + const yt = round2(gl.pts[0]!.y); + const yb = round2(gl.pts[gl.pts.length - 1]!.y); + const outX = gl.pts.length >= 3 ? round2(gl.pts[1]!.x) : round2(lf1.x + (selfSide === "start" ? -24 : 24)); + const bar = findActiveBar(bars, s.from, s.n, true); + const edgeX = bar ? round2(selfSide === "start" ? bar.box.x : bar.box.x + bar.box.w) : lf1.x; + pts = [{ x: edgeX, y: yt }, { x: outX, y: yt }, { x: outX, y: yb }, { x: edgeX, y: yb }]; + if (bar) { + fromBarId = bar.id; + toBarId = bar.id; + const bx = selfSide === "start" ? 0 : 1; + fromPort = { x: bx, y: round6(clamp01((yt - bar.box.y) / bar.box.h)), side }; + toPort = { x: bx, y: round6(clamp01((yb - bar.box.y) / bar.box.h)), side }; + } else { + fromPort = { x: 0.5, y: round6(clamp01((yt - lf1.y1) / span1)), side }; + toPort = { x: 0.5, y: round6(clamp01((yb - lf2.y1) / span2)), side }; + } + } else { + const y = round2(gl.pts[0]!.y); + const dirRight = lf2.x >= lf1.x; + const sb = findActiveBar(bars, s.from, s.n, false); + const rb = findActiveBar(bars, s.to, s.n, true); + const x1 = sb ? round2(dirRight ? sb.box.x + sb.box.w : sb.box.x) : lf1.x; + const x2 = rb ? round2(dirRight ? rb.box.x : rb.box.x + rb.box.w) : lf2.x; + pts = [{ x: x1, y }, { x: x2, y }]; + if (sb) { + fromBarId = sb.id; + fromPort = { x: dirRight ? 1 : 0, y: round6(clamp01((y - sb.box.y) / sb.box.h)), side: dirRight ? "right" : "left" }; + } else { + fromPort = { x: 0.5, y: round6(clamp01((y - lf1.y1) / span1)), side: dirRight ? "right" : "left" }; + } + if (rb) { + toBarId = rb.id; + toPort = { x: dirRight ? 0 : 1, y: round6(clamp01((y - rb.box.y) / rb.box.h)), side: dirRight ? "left" : "right" }; + } else { + toPort = { x: 0.5, y: round6(clamp01((y - lf2.y1) / span2)), side: dirRight ? "left" : "right" }; + } + } + const text = `${s.n} ${s.label}`; + const lw = Math.max(measureText(text, "label"), s.note ? measureText(s.note, "sans") : 0); + const lh = s.note ? 32 : 16; + const midY = (pts[0]!.y + pts[pts.length - 1]!.y) / 2; + const midX = self ? (selfSide === "start" ? lf1.x - 34 - lw / 2 : lf1.x + 34 + lw / 2) : (lf1.x + lf2.x) / 2; + const labelY = self ? round2(midY - lh / 2) : round2(midY - lh - 6); + edges.push({ + index: s.n - 1, + messageNumber: s.n, + from: s.from, + to: s.to, + sequence: true, + ...(fromBarId ? { fromBarId } : {}), + ...(toBarId ? { toBarId } : {}), + fk: false, + kind: s.kind, + openTip: s.kind === "dashed", + fromPort, + toPort, + pts, + selfSide, + label: { text, note: s.note, box: { x: round2(midX - lw / 2), y: labelY, w: round2(lw), h: lh }, on: false, t: 0.5 }, + }); + } + + return { + type: "sequence", + id, + title: m.title, + width: round2(geo.w), + height: round2(geo.h), + pad, + ...(options.measuredBy ? { measuredBy: options.measuredBy } : {}), + nodes: sceneNodes, + groups: [], + lanes: [], + lifelines, + bands, + frames, + bars, + edges, + }; + } + + // Non-sequence edges from Geo.lines, using derivedPorts for non-schema so slots match exact 0.25/0.5/0.75 + const derived = m.type === "schema" ? [] : derivedPorts(m); + const labelByEdge = new Map(geo.labels.map((l) => [l.i, l])); + const edges: SceneEdge[] = []; + + for (const gl of geo.lines) { + const me = m.edges[gl.i]; + const src = nodeById.get(gl.from); + const dst = nodeById.get(gl.to); + if (!me || !src || !dst) continue; + + let fromPort: ScenePort; + let toPort: ScenePort; + if (m.type === "schema") { + // Exact FK column row center, preserving intentional ±4px arrival offsets when two cardinalities meet one key + const p0 = gl.pts[0]!; + const pN = gl.pts[gl.pts.length - 1]!; + fromPort = portFromBoxAndPoint(src.box, p0, true); + toPort = portFromBoxAndPoint(dst.box, pN, true); + if (me.fromRow !== undefined && src.rows?.[me.fromRow]) { + const r = src.rows[me.fromRow]!; + if (Math.abs(p0.y - r.midY) <= 1.5) { + fromPort = portForSideSlot(fromPort.side, (r.midY - src.box.y) / src.box.h); + } + } + if (me.toRow !== undefined && dst.rows?.[me.toRow]) { + const r = dst.rows[me.toRow]!; + if (Math.abs(pN.y - r.midY) <= 1.5) { + toPort = portForSideSlot(toPort.side, (r.midY - dst.box.y) / dst.box.h); + } + } + } else { + const dp = derived[gl.i]; + if (dp) { + fromPort = portForSideSlot(dp.fromSide, dp.fromSlot); + toPort = portForSideSlot(dp.toSide, dp.toSlot); + } else { + fromPort = portFromBoxAndPoint(src.box, gl.pts[0]!, false); + toPort = portFromBoxAndPoint(dst.box, gl.pts[gl.pts.length - 1]!, false); + } + } + + const startPt = boxPortPoint(src.box, fromPort); + let endPt = boxPortPoint(dst.box, toPort); + if (gl.pts.length === 2) { + if (isH(fromPort.side) && isH(toPort.side) && Math.abs(startPt.y - endPt.y) <= 1.5) { + toPort = portForSideSlot(toPort.side, (startPt.y - dst.box.y) / dst.box.h); + endPt = boxPortPoint(dst.box, toPort); + } else if (!isH(fromPort.side) && !isH(toPort.side) && Math.abs(startPt.x - endPt.x) <= 1.5) { + toPort = portForSideSlot(toPort.side, (startPt.x - dst.box.x) / dst.box.w); + endPt = boxPortPoint(dst.box, toPort); + } + } + const pts = snapRouteToPorts(gl.pts, startPt, endPt, fromPort.side, toPort.side); + const gLab = labelByEdge.get(gl.i); + let label: SceneLabel | undefined; + if (gLab) { + const lBox = rectToBox(gLab.box); + label = { text: gLab.text, box: lBox, on: gLab.on, t: labelArcFraction(pts, lBox) }; + } + edges.push({ + index: gl.i, + from: gl.from, + to: gl.to, + fromRow: me.fromRow, + toRow: me.toRow, + fk: Boolean(me.fk), + ...(me.card ? { card: me.card } : {}), + kind: gl.kind, + openTip: gl.kind === "dashed", + fromPort, + toPort, + pts, + label, + }); + } + + return { + type: m.type, + id, + title: m.title, + width: round2(geo.w), + height: round2(geo.h), + pad, + ...(options.measuredBy ? { measuredBy: options.measuredBy } : {}), + nodes: sceneNodes, + groups: sceneGroups, + lanes: sceneLanes, + lifelines: [], + bands: [], + frames: [], + bars: [], + edges, + }; +} + +function visibleTextOf(el: Element | null): string { + if (!el) return ""; + let out = ""; + for (const child of Array.from(el.childNodes)) { + if (child.nodeType === 3) { + out += child.textContent ?? ""; + } else if (child.nodeType === 1) { + const cls = (child as Element).getAttribute("class") ?? ""; + if (cls.includes("visually-hidden") || cls.includes("sr-only")) continue; + out += visibleTextOf(child as Element); + } + } + return out.trim(); +} + +/** Reads optional group, lane, band, frame, and table-row rects from a live diagram `<figure>` element. */ +export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): MeasuredExtras { + const drawing = fig.querySelector(`.${prefix}-drawing`); + if (!drawing) return {}; + const origin = drawing.getBoundingClientRect(); + const rectOf = (el: Element): Rect => { + const r = el.getBoundingClientRect(); + return { l: r.left - origin.left, t: r.top - origin.top, r: r.right - origin.left, b: r.bottom - origin.top }; + }; + + const groups: MeasuredGroup[] = []; + drawing.querySelectorAll(`.${prefix}-gbox`).forEach((el) => { + const id = el.getAttribute("data-group"); + if (!id || !el.getClientRects().length) return; + const label = el.querySelector(`:scope > .${prefix}-glabel`)?.textContent ?? ""; + const depth = Number(el.getAttribute("data-depth")) || 1; + groups.push({ id, label, depth, rect: rectOf(el) }); + }); + + const lanes: MeasuredLane[] = []; + drawing.querySelectorAll(`.${prefix}-lane`).forEach((el, idx) => { + if (!el.getClientRects().length) return; + const label = el.querySelector(`.${prefix}-lane-name`)?.textContent ?? ""; + lanes.push({ id: `lane-${idx}`, index: idx, label, rect: rectOf(el) }); + }); + + const bands: MeasuredBand[] = []; + drawing.querySelectorAll(`.${prefix}-band`).forEach((el) => { + if (!el.getClientRects().length) return; + bands.push({ text: el.textContent ?? "", rect: rectOf(el) }); + }); + + const frames: MeasuredFrame[] = []; + const frameIndexByEl = new Map<Element, number>(); + drawing.querySelectorAll(`.${prefix}-frame`).forEach((el) => { + if (!el.getClientRects().length) return; + const fbox = el.querySelector(`:scope > .${prefix}-fbox`); + if (!fbox || !fbox.getClientRects().length) return; + const opRaw = el.getAttribute("data-op"); + const operator: MeasuredFrame["operator"] = + opRaw === "loop" || opRaw === "alt" ? opRaw : "opt"; + const depth = Number(el.getAttribute("data-depth")) || 1; + const parentEl = el.parentElement?.closest(`.${prefix}-frame`) ?? null; + const parentIndex = parentEl ? frameIndexByEl.get(parentEl) : undefined; + const fhead = el.querySelector(`:scope > .${prefix}-fhead`); + const ftab = fhead?.querySelector(`.${prefix}-ftab`) ?? null; + const flabel = fhead?.querySelector(`.${prefix}-flabel`) ?? null; + const headLabelText = visibleTextOf(flabel); + const dividers: MeasuredFrameDivider[] = []; + el.querySelectorAll(`:scope > .${prefix}-felse`).forEach((elseEl) => { + if (!elseEl.getClientRects().length) return; + const r = rectOf(elseEl); + const fword = elseEl.querySelector(`.${prefix}-fword`); + const elabel = elseEl.querySelector(`.${prefix}-flabel`); + const label = visibleTextOf(elabel); + const parts: Rect[] = []; + if (fword && fword.getClientRects().length) parts.push(rectOf(fword)); + if (elabel && label && elabel.getClientRects().length) parts.push(rectOf(elabel)); + const labelRect = parts.length + ? { + l: Math.min(...parts.map((p) => p.l)), + t: Math.min(...parts.map((p) => p.t)), + r: Math.max(...parts.map((p) => p.r)), + b: Math.max(...parts.map((p) => p.b)), + } + : undefined; + dividers.push({ y: r.t, h: r.b - r.t, label, ...(labelRect ? { labelRect } : {}) }); + }); + const idx = frames.length; + frameIndexByEl.set(el, idx); + frames.push({ + operator, + label: headLabelText, + depth, + ...(parentIndex !== undefined ? { parentIndex } : {}), + rect: rectOf(fbox), + ...(ftab && ftab.getClientRects().length ? { tabRect: rectOf(ftab) } : {}), + ...(flabel && headLabelText && flabel.getClientRects().length ? { labelRect: rectOf(flabel) } : {}), + dividers, + }); + }); + + const tableRows: Record<string, number[]> = {}; + drawing.querySelectorAll(`.${prefix}-node[data-shape="table"]`).forEach((nodeEl) => { + const id = nodeEl.getAttribute("data-node"); + if (!id) return; + const ys: number[] = []; + nodeEl.querySelectorAll(`.${prefix}-row`).forEach((rowEl) => { + const r = rectOf(rowEl); + ys.push((r.t + r.b) / 2); + }); + if (ys.length) tableRows[id] = ys; + }); + + return { + groups: groups.length ? groups : undefined, + lanes: lanes.length ? lanes : undefined, + bands: bands.length ? bands : undefined, + frames: frames.length ? frames : undefined, + tableRows: Object.keys(tableRows).length ? tableRows : undefined, + }; +} diff --git a/packages/react/src/interop/types.ts b/packages/react/src/interop/types.ts new file mode 100644 index 00000000..e35d3759 --- /dev/null +++ b/packages/react/src/interop/types.ts @@ -0,0 +1,405 @@ +// Public and scene types for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314, 324, 327). +// Pure structural declarations: no third-party or Node types appear anywhere in this surface. +import type { + DiagramCardinality, + DiagramLineKind, + DiagramPlacement, + DiagramSide, + DiagramSpec, + DiagramType, + Geo, + MColumn, + Pt, + Rect, +} from "../diagram-core"; + +export type InteropFormat = "drawio" | "vsdx" | "lucid" | "lucid-json"; +export type InteropTheme = "light" | "dark" | "adaptive"; +export type InteropMarksMode = "omit" | "embed"; + +/** Resolves a bundled mark id to its SVG markup or `data:image/svg+xml,...` URI for the given ground theme. */ +export type InteropMarkResolver = (id: string, theme: "light" | "dark") => string | undefined; + +export interface InteropOptions { + /** Colour theme for the exported file. Default `"light"` (universal across tools); `"adaptive"` emits dual light/dark for draw.io. */ + theme?: InteropTheme; + /** Whether to embed service marks whose manifest terms allow diagram use. Default `"omit"`. */ + marks?: InteropMarksMode; + /** Supplies SVG data for bundled mark ids when `marks` is `"embed"`. */ + resolveMark?: InteropMarkResolver; + /** Target drawing width in CSS pixels for headless layout (default 1104; widens automatically when the figure's minimum width exceeds it). */ + width?: number; + /** Canvas padding around the drawing box in pixels (default 32). */ + pad?: number; + /** Deterministic diagram identifier written to the exported page/diagram element. */ + diagramId?: string; + /** Pre-computed placement(s) for `layout: "auto"` specs; defaults to `spec.placement` when present. */ + placement?: DiagramPlacement | DiagramPlacement[]; + /** Measurement engine recorded in exported file metadata (e.g. `"Chromium 146.0.7680.16"` or `"Basalt headless (approximate)"`). */ + measuredBy?: string; +} + +export interface MeasuredGroup { + id: string; + label: string; + depth?: number; + rect: Rect; +} + +export interface MeasuredLane { + id: string; + /** 0-based lane index matching the DOM order of `.diagram-lane` elements. */ + index?: number; + label: string; + rect: Rect; +} + +export interface MeasuredBand { + text: string; + rect: Rect; +} + +export interface MeasuredFrameDivider { + y: number; + h: number; + label: string; + labelRect?: Rect; +} + +export interface MeasuredFrame { + operator: "opt" | "loop" | "alt"; + label: string; + depth: number; + parentIndex?: number; + rect: Rect; + tabRect?: Rect; + labelRect?: Rect; + dividers: MeasuredFrameDivider[]; +} + +/** Optional DOM measurements that accompany `Geo` when exporting a live rendered figure. */ +export interface MeasuredExtras { + groups?: MeasuredGroup[]; + lanes?: MeasuredLane[]; + bands?: MeasuredBand[]; + frames?: MeasuredFrame[]; + /** Vertical midpoints of each table's column rows in drawing coordinates, keyed by table name. */ + tableRows?: Record<string, number[]>; +} + +export interface MeasuredInteropOptions extends InteropOptions { + extras?: MeasuredExtras; +} + +export interface SceneBox { + x: number; + y: number; + w: number; + h: number; +} + +export interface ScenePort { + /** Normalized horizontal position along the shape box, in `[0, 1]`. */ + x: number; + /** Normalized vertical position along the shape box, in `[0, 1]`. */ + y: number; + side: DiagramSide; +} + +export interface SceneMark { + id: string; + /** Raw SVG markup (or decoded from data URI) for light ground. */ + svgLight: string; + /** Raw SVG markup for dark ground. */ + svgDark: string; + /** Licence/trademark attribution from marks/manifest.json, when the mark carries one. */ + attribution?: string; +} + +export interface SceneTableRow { + index: number; + name: string; + key?: "PK" | "FK"; + type?: string; + refTable?: string; + /** Row top relative to the table's top edge, in pixels. */ + y: number; + /** Row height in pixels. */ + h: number; + /** Row vertical center in drawing coordinates. */ + midY: number; +} + +export interface SceneNode { + id: string; + name: string; + kind?: string; + detail?: string; + detailMono: boolean; + focal: boolean; + col: number; + row: number; + row2: number; + shape: "box" | "terminal" | "decision" | "table" | "participant"; + group?: string; + laneId?: string; + laneIndex?: number; + step?: number; + columns?: MColumn[]; + rows?: SceneTableRow[]; + headerH?: number; + more?: number; + short?: string; + box: SceneBox; + mark?: SceneMark; +} + +export interface SceneGroup { + id: string; + label: string; + parent?: string; + depth: number; + box: SceneBox; + members: string[]; + childGroups?: string[]; +} + +export interface SceneLane { + id: string; + label: string; + box: SceneBox; + labelWidth: number; +} + +export interface SceneLifeline { + id: string; + participantId: string; + x: number; + y1: number; + y2: number; +} + +export interface SceneBand { + text: string; + y: number; + h: number; + w: number; +} + +export interface SceneFrameDivider { + y: number; + h: number; + label: string; + labelBox?: SceneBox; +} + +export interface SceneFrame { + id: string; + operator: "opt" | "loop" | "alt"; + label: string; + depth: number; + parentId?: string; + box: SceneBox; + tabBox: SceneBox; + labelBox?: SceneBox; + dividers: SceneFrameDivider[]; +} + +export interface SceneBar { + id: string; + participantId: string; + fromMsg: number; + toMsg: number; + depth: number; + box: SceneBox; +} + +export interface SceneLabel { + text: string; + note?: string; + box: SceneBox; + on: boolean; + /** Fractional arc-length position along the edge polyline in `[0, 1]`. */ + t: number; +} + +export interface SceneEdge { + index: number; + from: string; + to: string; + /** When true, `from` and `to` name lifeline participant ids rather than node boxes. */ + sequence?: boolean; + /** When set on a sequence edge, that end glues to the activation bar box instead of the bare lifeline. */ + fromBarId?: string; + toBarId?: string; + /** For schema foreign keys: source and target column row indices. */ + fromRow?: number; + toRow?: number; + fk: boolean; + /** Schema crow's-foot cardinality at each end (replaces dot and arrow when present). */ + card?: { from: DiagramCardinality; to: DiagramCardinality }; + kind: DiagramLineKind; + openTip: boolean; + fromPort: ScenePort; + toPort: ScenePort; + /** Orthogonal polyline in drawing coordinates, already snapped to exact port coordinates. */ + pts: Pt[]; + label?: SceneLabel; + /** Sequence message number, when `sequence` is true. */ + messageNumber?: number; + /** Sequence self-call direction (`"start"` = left, `"end"` = right). */ + selfSide?: "start" | "end"; +} + +export interface InteropScene { + type: DiagramType; + id: string; + title: string; + width: number; + height: number; + pad: number; + measuredBy?: string; + nodes: SceneNode[]; + groups: SceneGroup[]; + lanes: SceneLane[]; + lifelines: SceneLifeline[]; + bands: SceneBand[]; + frames: SceneFrame[]; + bars: SceneBar[]; + edges: SceneEdge[]; +} + +// ---- Lucid Standard Import JSON contract (https://developer.lucid.co/docs/standard-import) ---- + +export interface LucidColorFill { + type: "color"; + color: string; +} + +export interface LucidImageFill { + type: "image"; + ref: string; + imageScale: "fit" | "fill" | "stretch" | "original" | "tile"; +} + +export interface LucidStroke { + color: string; + width: number; + style?: "solid" | "dashed" | "dotted"; +} + +export interface LucidBoundingBox { + x: number; + y: number; + w: number; + h: number; +} + +export interface LucidShapeStyle { + fill?: LucidColorFill | LucidImageFill; + stroke?: LucidStroke; + rounding?: number; + textColor?: string; +} + +export interface LucidCustomData { + key: string; + value: string; +} + +export interface LucidSwimLane { + title: string; + width: number; + headerFill: string; + laneFill: string; +} + +export interface LucidTableCell { + xPosition: number; + yPosition: number; + mergeCellsRight?: number; + mergeCellsDown?: number; + style?: { fill: LucidColorFill }; + text?: string; +} + +export interface LucidFieldSize { + index: number; + size: number; +} + +export interface LucidShape { + id: string; + type: string; + boundingBox: LucidBoundingBox; + style?: LucidShapeStyle; + text?: string; + magnetize?: boolean; + assistedLayout?: boolean; + containerTitle?: { text: string }; + vertical?: boolean; + titleBar?: { height: number; verticalText: boolean }; + lanes?: LucidSwimLane[]; + rowCount?: number; + colCount?: number; + cells?: LucidTableCell[]; + userSpecifiedRows?: LucidFieldSize[]; + userSpecifiedCols?: LucidFieldSize[]; + verticalBorder?: boolean; + horizontalBorder?: boolean; + customData?: LucidCustomData[]; + zIndex?: number; +} + +export type LucidEndpointStyle = + | "none" + | "arrow" + | "openArrow" + | "closedCircle" + | "exactlyOne" + | "zeroOrOne" + | "oneOrMore" + | "zeroOrMore"; + +export type LucidEndpoint = + | { type: "shapeEndpoint"; style: LucidEndpointStyle; shapeId: string; position: { x: number; y: number } } + | { type: "lineEndpoint"; style: LucidEndpointStyle; lineId: string; position: number } + | { type: "positionEndpoint"; style: LucidEndpointStyle; position: { x: number; y: number } }; + +export interface LucidLineText { + text: string; + position: number; + side: "middle" | "top" | "bottom"; +} + +export interface LucidLine { + id: string; + lineType: "straight" | "elbow" | "curved"; + endpoint1: LucidEndpoint; + endpoint2: LucidEndpoint; + stroke: LucidStroke; + elbowControlPoints?: Array<{ x: number; y: number }>; + text?: LucidLineText[]; + zIndex?: number; +} + +export interface LucidPage { + id: string; + title: string; + settings: { + fillColor: string; + infiniteCanvas: boolean; + autoTiling: boolean; + size: { type: "custom"; w: number; h: number }; + }; + shapes: LucidShape[]; + lines: LucidLine[]; +} + +export interface LucidDocument { + version: 1; + documentSettings: { units: "px" }; + pages: LucidPage[]; +} + +export type { DiagramCardinality, DiagramPlacement, DiagramSpec, Geo }; diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts new file mode 100644 index 00000000..3d73a610 --- /dev/null +++ b/packages/react/src/interop/vsdx.ts @@ -0,0 +1,1411 @@ +// Deterministic Microsoft Visio (.vsdx) OPC exporter (DECISIONS 311, 314, 324, 327). +// Conforms to [MS-VSDX] (http://schemas.microsoft.com/office/visio/2012/main). +// 96 CSS px = 1 inch; Visio page Y increases UPWARD from bottom-left. +// Every connector's BeginX/BeginY/EndX/EndY and Geometry MoveTo/LineTo coordinates are computed directly +// from each shape's exact rounded PinX/PinY/Width/Height and Connection row in Visio inches, guaranteeing +// zero port-to-waypoint drift (no joining jog in Visio, Lucidchart, or draw.io). +import type { DiagramCardinality, Pt } from "../diagram-core"; +import { paletteFor, round6, snapRouteToPorts } from "./scene"; +import type { InteropScene, InteropTheme, SceneNode } from "./types"; +import { makeDeterministicZip } from "./zip"; +import type { ZipEntry } from "./zip"; + +const DPI = 96; + +const VSDX_CARD: Record<DiagramCardinality, number> = { + one: 25, + "zero-or-one": 30, + "one-or-many": 28, + "zero-or-many": 29, +}; + +function escXml(s: string): string { + return String(s) + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, """); +} + +const f6 = (n: number): string => n.toFixed(6); +const n6 = (n: number): number => Number(n.toFixed(6)); +const pxToIn = (px: number): string => f6(px / DPI); +const ptToIn = (pt: number): string => f6(pt / 72); + +interface ConnEntry { + fx: number; + fy: number; + /** Exact local connection X and Y in Visio inches (computed directly so straight lines stay aligned to 0.000000 in). */ + cx: number; + cy: number; + /** Outward unit normal in Visio Y-up coordinates so Visio and Lucidchart know which edge the port leaves. */ + dirX: number; + dirY: number; + ix: number; +} + +function sideNormal(side: "top" | "right" | "bottom" | "left"): { dirX: number; dirY: number } { + if (side === "left") return { dirX: -1, dirY: 0 }; + if (side === "right") return { dirX: 1, dirY: 0 }; + if (side === "top") return { dirX: 0, dirY: 1 }; + return { dirX: 0, dirY: -1 }; +} + +interface PlacedShape { + sheetId: number; + pinX: number; + pinY: number; + wIn: number; + hIn: number; + conns: ConnEntry[]; +} + +/** Exact page-coordinate point (in Visio inches) of a Connection row on a placed shape. */ +function connectionPagePt(shape: PlacedShape, conn: ConnEntry): Pt { + const left = shape.pinX - n6(shape.wIn / 2); + const bottom = shape.pinY - n6(shape.hIn / 2); + return { x: n6(left + conn.cx), y: n6(bottom + conn.cy) }; +} + +export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): Uint8Array { + const singleTheme: "light" | "dark" = theme === "dark" ? "dark" : "light"; + const P = paletteFor(singleTheme); + // A light export has no page shape, so it sits on the importer's own canvas, white in Lucidchart and Visio: a backdrop + // in Basalt's #fafafa page colour shows there as a grey box. Dark exports paint their page, so backdrops match it. + const labelBg = singleTheme === "light" ? "#ffffff" : P.page; + const pad = scene.pad; + const canvasW = scene.width + pad * 2; + const canvasH = scene.height + pad * 2; + const pageWIn = n6(canvasW / DPI); + const pageHIn = n6(canvasH / DPI); + const toVisioX = (px: number): number => n6((px + pad) / DPI); + const toVisioY = (py: number): number => n6((canvasH - (py + pad)) / DPI); + + // Precompute exact Visio box geometry for every connectable shape, lifeline, and activation bar + // so straight-line Connection rows align to 0.000000 in across boxes of different heights/widths. + const geomByKey = new Map<string, { pinX: number; pinY: number; wIn: number; hIn: number }>(); + for (const lf of scene.lifelines) { + geomByKey.set(`life:${lf.participantId}`, { + pinX: toVisioX(lf.x), + pinY: toVisioY((lf.y1 + lf.y2) / 2), + wIn: n6(2 / DPI), + hIn: n6(Math.max(1, lf.y2 - lf.y1) / DPI), + }); + } + for (const bar of scene.bars) { + geomByKey.set(`bar:${bar.id}`, { + pinX: toVisioX(bar.box.x + bar.box.w / 2), + pinY: toVisioY(bar.box.y + bar.box.h / 2), + wIn: n6(bar.box.w / DPI), + hIn: n6(bar.box.h / DPI), + }); + } + for (const n of scene.nodes) { + geomByKey.set(`node:${n.id}`, { + pinX: toVisioX(n.box.x + n.box.w / 2), + pinY: toVisioY(n.box.y + n.box.h / 2), + wIn: n6(n.box.w / DPI), + hIn: n6(n.box.h / DPI), + }); + } + + // Allocate one dedicated Connection row per connector end (never sharing a port between two connectors, + // which causes Lucidchart's Visio importer to re-route or collapse segments). + const connsByKey = new Map<string, ConnEntry[]>(); + const allocConnIndex = ( + key: string, + fx: number, + fy: number, + side: "top" | "right" | "bottom" | "left", + exactCx?: number, + exactCy?: number, + ): number => { + const g = geomByKey.get(key); + const rfx = round6(Math.max(0, Math.min(1, fx))); + const rfy = round6(Math.max(0, Math.min(1, fy))); + const cx = exactCx !== undefined ? n6(exactCx) : n6(rfx * (g?.wIn ?? 0)); + const cy = exactCy !== undefined ? n6(exactCy) : n6((1 - rfy) * (g?.hIn ?? 0)); + let list = connsByKey.get(key); + if (!list) { list = []; connsByKey.set(key, list); } + const ix = list.length; + const { dirX, dirY } = sideNormal(side); + list.push({ fx: rfx, fy: rfy, cx, cy, dirX, dirY, ix }); + return ix; + }; + + // Lucidchart keeps a glued end exactly at a side's midpoint and at any point down a left or right side, but an end + // glued to a top or bottom side away from its midpoint lands about 1px left of its Connection row, and Lucid then + // draws a sideways step a quarter inch out from the box to rejoin the route (measured on the owner's round-3 + // imports: "HTTP + SSE" and "inference" in architecture-auto at 0.25, RunTask in architecture; every midpoint and + // every left or right port was within 0.1px). Such an end is left unglued, at its exact page coordinate, which + // Lucid has nothing to re-snap to; every other end stays glued to its own Connection row. + const lucidKeepsGlue = (key: string, side: "top" | "right" | "bottom" | "left", fx: number): boolean => + !key.startsWith("node:") || side === "left" || side === "right" || Math.abs(fx - 0.5) < 1e-4; + const boxPortPagePt = (g: { pinX: number; pinY: number; wIn: number; hIn: number }, fx: number, fy: number): Pt => ({ + x: n6(g.pinX - n6(g.wIn / 2) + n6(round6(Math.max(0, Math.min(1, fx))) * g.wIn)), + y: n6(g.pinY - n6(g.hIn / 2) + n6((1 - round6(Math.max(0, Math.min(1, fy)))) * g.hIn)), + }); + + const edgeConns = scene.edges.map((e) => { + const fromKey = e.sequence + ? (e.fromBarId && geomByKey.has(`bar:${e.fromBarId}`) ? `bar:${e.fromBarId}` : `life:${e.from}`) + : `node:${e.from}`; + const toKey = e.sequence + ? (e.toBarId && geomByKey.has(`bar:${e.toBarId}`) ? `bar:${e.toBarId}` : `life:${e.to}`) + : `node:${e.to}`; + const fromG = geomByKey.get(fromKey); + const toG = geomByKey.get(toKey); + const fromFx = e.sequence && !fromKey.startsWith("bar:") ? 0.5 : e.fromPort.x; + const toFx = e.sequence && !toKey.startsWith("bar:") ? 0.5 : e.toPort.x; + const fromFree = Boolean(fromG) && !lucidKeepsGlue(fromKey, e.fromPort.side, fromFx); + const toFree = Boolean(toG) && !lucidKeepsGlue(toKey, e.toPort.side, toFx); + const fromIx = fromFree ? -1 : allocConnIndex(fromKey, fromFx, e.fromPort.y, e.fromPort.side); + const fromPt = fromFree ? boxPortPagePt(fromG!, fromFx, e.fromPort.y) : undefined; + let toIx = -1; + let toPt: Pt | undefined; + if (e.pts.length === 2 && fromG && toG) { + // A straight line keeps its two ends on one axis to 0.000001 in, glued or free. + let startPage = fromPt; + if (!startPage) { + const fc = connsByKey.get(fromKey)![fromIx]!; + startPage = { x: n6(fromG.pinX - n6(fromG.wIn / 2) + fc.cx), y: n6(fromG.pinY - n6(fromG.hIn / 2) + fc.cy) }; + } + const horiz = Math.abs(e.pts[0]!.y - e.pts[1]!.y) <= Math.abs(e.pts[0]!.x - e.pts[1]!.x); + if (toFree) { + const edgePt = boxPortPagePt(toG, toFx, e.toPort.y); + toPt = horiz ? { x: edgePt.x, y: startPage.y } : { x: startPage.x, y: edgePt.y }; + } else if (horiz) { + const toBottom = toG.pinY - n6(toG.hIn / 2); + const exactCy = n6(startPage.y - toBottom); + const alignedFy = toG.hIn > 0 ? round6(1 - exactCy / toG.hIn) : e.toPort.y; + toIx = allocConnIndex(toKey, toFx, alignedFy, e.toPort.side, undefined, exactCy); + } else { + const toLeft = toG.pinX - n6(toG.wIn / 2); + const exactCx = n6(startPage.x - toLeft); + const alignedFx = toG.wIn > 0 ? round6(exactCx / toG.wIn) : toFx; + toIx = allocConnIndex(toKey, alignedFx, e.toPort.y, e.toPort.side, exactCx, undefined); + } + } else if (toFree) { + toPt = boxPortPagePt(toG!, toFx, e.toPort.y); + } else { + toIx = allocConnIndex(toKey, toFx, e.toPort.y, e.toPort.side); + } + return { fromKey, toKey, fromIx, toIx, fromPt, toPt }; + }); + + let nextId = 1; + const bgId = singleTheme === "dark" ? nextId++ : 0; + const groupSheetId = new Map<string, number>(); + for (const g of scene.groups) groupSheetId.set(g.id, nextId++); + const laneSheetIds = scene.lanes.map(() => nextId++); + const lifeSheetIds = scene.lifelines.map(() => nextId++); + const bandSheetIds = scene.bands.map(() => nextId++); + const frameSheetId = new Map<string, number>(); + for (const f of scene.frames) frameSheetId.set(f.id, nextId++); + const barSheetId = new Map<string, number>(); + for (const bar of scene.bars) barSheetId.set(bar.id, nextId++); + const nodeSheetId = new Map<string, number>(); + for (const n of scene.nodes) nodeSheetId.set(n.id, nextId++); + + const shapeXml: string[] = []; + const topLabelXml: string[] = []; + const connectXml: string[] = []; + const placed = new Map<string, PlacedShape>(); + const mediaFiles: Array<{ rId: string; fileName: string; svg: string }> = []; + const attributions: string[] = []; + + // 0. Dark-theme locked full-page surface-page background (Visio pages default to white) + if (bgId) { + shapeXml.push( + ` <Shape ID="${bgId}" NameU="PageBackground" Name="Page background" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(pageWIn / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(n6(pageHIn / 2))}"/>\n` + + ` <Cell N="Width" V="${f6(pageWIn)}"/>\n` + + ` <Cell N="Height" V="${f6(pageHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(pageWIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(pageHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FlipX" V="0"/>\n` + + ` <Cell N="FlipY" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${P.page}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="LockWidth" V="1"/>\n` + + ` <Cell N="LockHeight" V="1"/>\n` + + ` <Cell N="LockMoveX" V="1"/>\n` + + ` <Cell N="LockMoveY" V="1"/>\n` + + ` <Cell N="LockAspect" V="1"/>\n` + + ` <Cell N="LockDelete" V="1"/>\n` + + ` <Cell N="LockBegin" V="1"/>\n` + + ` <Cell N="LockEnd" V="1"/>\n` + + ` <Cell N="LockRotate" V="1"/>\n` + + ` <Cell N="LockCrop" V="1"/>\n` + + ` <Cell N="LockVtxEdit" V="1"/>\n` + + ` <Cell N="LockTextEdit" V="1"/>\n` + + ` <Cell N="LockFormat" V="1"/>\n` + + ` <Cell N="LockGroup" V="1"/>\n` + + ` <Cell N="LockCalcWH" V="1"/>\n` + + ` <Cell N="LockSelect" V="1"/>\n` + + ` <Cell N="LockCustProp" V="1"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="1"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(pageWIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(pageWIn)}" F="Width*1"/><Cell N="Y" V="${f6(pageHIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(pageHIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + } + + // 1. Architecture groups as real Visio Containers (supporting nested depth-2 containers via DEPENDSON) + for (const g of scene.groups) { + const id = groupSheetId.get(g.id)!; + const wIn = n6(g.box.w / DPI); + const hIn = n6(g.box.h / DPI); + const pinX = toVisioX(g.box.x + g.box.w / 2); + const pinY = toVisioY(g.box.y + g.box.h / 2); + const radIn = n6((g.depth > 1 ? 8 : 12) / DPI); + const memberIds = [ + ...g.members.map((mid) => nodeSheetId.get(mid)).filter((x): x is number => x !== undefined), + ...(g.childGroups ?? []).map((cid) => groupSheetId.get(cid)).filter((x): x is number => x !== undefined), + ]; + const parentGid = g.parent ? groupSheetId.get(g.parent) : undefined; + const deps: string[] = []; + if (parentGid !== undefined) deps.push(`DEPENDSON(4,Sheet.${parentGid}!SheetRef())`); + if (memberIds.length) deps.push(`DEPENDSON(1,${memberIds.map((mid) => `Sheet.${mid}!SheetRef()`).join(",")})`); + const relCell = deps.length + ? ` <Cell N="Relationships" V="0" F="SUM(${deps.join(",")})"/>\n` + : ""; + shapeXml.push( + ` <Shape ID="${id}" NameU="Group_${escXml(g.id)}" Name="${escXml(g.label)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FlipX" V="0"/>\n` + + ` <Cell N="FlipY" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(1)}"/>\n` + + ` <Cell N="LinePattern" V="2"/>\n` + + ` <Cell N="Rounding" V="${f6(radIn)}"/>\n` + + ` <Cell N="VerticalAlign" V="0"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(12)}"/>\n` + + ` <Cell N="TopMargin" V="${pxToIn(8)}"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + relCell + + ` <Section N="User">\n` + + ` <Row N="msvStructureType"><Cell N="Value" V="Container" U="STR"/></Row>\n` + + ` <Row N="msvSDContainerMargin"><Cell N="Value" V="${pxToIn(16)}"/></Row>\n` + + ` <Row N="msvSDContainerResize"><Cell N="Value" V="0"/></Row>\n` + + ` <Row N="msvSDContainerLocked"><Cell N="Value" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(g.label)}</Text>\n` + + ` </Shape>`, + ); + } + + // 2. Data-flow lanes (behind step cards) + for (let k = 0; k < scene.lanes.length; k++) { + const lane = scene.lanes[k]!; + const id = laneSheetIds[k]!; + const wIn = n6(lane.box.w / DPI); + const hIn = n6(lane.box.h / DPI); + const pinX = toVisioX(lane.box.x + lane.box.w / 2); + const pinY = toVisioY(lane.box.y + lane.box.h / 2); + const rightMargin = n6(Math.max(0, lane.box.w - lane.labelWidth) / DPI); + shapeXml.push( + ` <Shape ID="${id}" NameU="Lane_${escXml(lane.id)}" Name="${escXml(lane.label)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.divider}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="${k > 0 ? 1 : 0}"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(4)}"/>\n` + + ` <Cell N="RightMargin" V="${f6(rightMargin)}"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="${k > 0 ? 0 : 1}"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(lane.label)}</Text>\n` + + ` </Shape>`, + ); + } + + // 3. Sequence lifelines, phase bands, combined frames, and activation bars + for (let lfIdx = 0; lfIdx < scene.lifelines.length; lfIdx++) { + const lf = scene.lifelines[lfIdx]!; + const id = lifeSheetIds[lfIdx]!; + const wIn = n6(2 / DPI); + const hIn = n6(Math.max(1, lf.y2 - lf.y1) / DPI); + const pinX = toVisioX(lf.x); + const pinY = toVisioY((lf.y1 + lf.y2) / 2); + const key = `life:${lf.participantId}`; + const conns = connsByKey.get(key) ?? []; + placed.set(key, { sheetId: id, pinX, pinY, wIn, hIn, conns }); + + const connRowsXml = renderConnectionRows(conns, wIn, hIn); + shapeXml.push( + ` <Shape ID="${id}" NameU="Lifeline_${escXml(lf.participantId)}" Name="Lifeline ${escXml(lf.participantId)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="2"/>\n` + + ` <Cell N="ObjType" V="1"/>\n` + + connRowsXml + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="${f6(n6(wIn / 2))}" F="Width*0.5"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(n6(wIn / 2))}" F="Width*0.5"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + } + + for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) { + const band = scene.bands[bIdx]!; + const id = bandSheetIds[bIdx]!; + const wIn = n6(band.w / DPI); + const hIn = n6(band.h / DPI); + const pinX = toVisioX(band.w / 2); + const pinY = toVisioY(band.y + band.h / 2); + // Emit the band's divider line in the background layer and its word-sized page-colour plate in the top label layer + // so lifelines and activation bars never strike through the band words. + shapeXml.push( + ` <Shape ID="${id}" NameU="Band_${bIdx}" Name="${escXml(band.text)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.divider}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="${f6(n6(hIn / 2))}" F="Height*0.5"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="${f6(n6(hIn / 2))}" F="Height*0.5"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + const bandLblId = nextId++; + const bandLblW = Math.min(band.w - 16, Math.max(48, band.text.length * 6.8 + 20)); + const blwIn = n6(bandLblW / DPI); + const blhIn = n6(18 / DPI); + topLabelXml.push( + ` <Shape ID="${bandLblId}" NameU="BandLabel_${bIdx}" Name="${escXml(band.text)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(blwIn)}"/>\n` + + ` <Cell N="Height" V="${f6(blhIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(blwIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(blhIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${labelBg}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="0"/>\n` + + ` <Cell N="RightMargin" V="0"/>\n` + + ` <Cell N="TopMargin" V="0"/>\n` + + ` <Cell N="BottomMargin" V="0"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="1"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="1"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(blwIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(blwIn)}" F="Width*1"/><Cell N="Y" V="${f6(blhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(blhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(band.text)}</Text>\n` + + ` </Shape>`, + ); + } + + // 3b. Sequence frames (opt/loop/alt containers with corner operator tab and dashed branch dividers) + for (const f of scene.frames) { + const id = frameSheetId.get(f.id)!; + const wIn = n6(f.box.w / DPI); + const hIn = n6(f.box.h / DPI); + const pinX = toVisioX(f.box.x + f.box.w / 2); + const pinY = toVisioY(f.box.y + f.box.h / 2); + const radIn = n6((f.depth > 1 ? 4 : 12) / DPI); + const childFids = scene.frames.filter((c) => c.parentId === f.id).map((c) => frameSheetId.get(c.id)!); + const parentFid = f.parentId ? frameSheetId.get(f.parentId) : undefined; + const deps: string[] = []; + if (parentFid !== undefined) deps.push(`DEPENDSON(4,Sheet.${parentFid}!SheetRef())`); + if (childFids.length) deps.push(`DEPENDSON(1,${childFids.map((cid) => `Sheet.${cid}!SheetRef()`).join(",")})`); + const relCell = deps.length + ? ` <Cell N="Relationships" V="0" F="SUM(${deps.join(",")})"/>\n` + : ""; + shapeXml.push( + ` <Shape ID="${id}" NameU="Frame_${escXml(f.id)}" Name="${escXml(`${f.operator} ${f.label}`.trim())}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="Rounding" V="${f6(radIn)}"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + relCell + + ` <Section N="User">\n` + + ` <Row N="msvStructureType"><Cell N="Value" V="Container" U="STR"/></Row>\n` + + ` <Row N="msvSDContainerResize"><Cell N="Value" V="0"/></Row>\n` + + ` <Row N="msvSDContainerLocked"><Cell N="Value" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + + const tabId = nextId++; + const twIn = n6(f.tabBox.w / DPI); + const thIn = n6(f.tabBox.h / DPI); + const tPinX = toVisioX(f.tabBox.x + f.tabBox.w / 2); + const tPinY = toVisioY(f.tabBox.y + f.tabBox.h / 2); + topLabelXml.push( + ` <Shape ID="${tabId}" NameU="FrameTab_${escXml(f.id)}" Name="${escXml(f.operator)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(tPinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(tPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(twIn)}"/>\n` + + ` <Cell N="Height" V="${f6(thIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(twIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(thIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${labelBg}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${P.textPrimary}"/><Cell N="Style" V="1"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="1"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(twIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(twIn)}" F="Width*1"/><Cell N="Y" V="${f6(thIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(thIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(f.operator)}</Text>\n` + + ` </Shape>`, + ); + + if (f.label) { + const lblId = nextId++; + const lb = f.labelBox ?? { + x: f.tabBox.x + f.tabBox.w + 6, + y: f.tabBox.y + 4, + w: Math.min(Math.max(16, f.box.w - (f.tabBox.w + 12)), f.label.length * 7 + 12), + h: 16, + }; + const lwIn = n6(lb.w / DPI); + const lhIn = n6(Math.max(18, lb.h + 2) / DPI); + topLabelXml.push( + ` <Shape ID="${lblId}" NameU="FrameLabel_${escXml(f.id)}" Name="${escXml(f.label)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(toVisioX(lb.x + lb.w / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(toVisioY(lb.y + lb.h / 2))}"/>\n` + + ` <Cell N="Width" V="${f6(lwIn)}"/>\n` + + ` <Cell N="Height" V="${f6(lhIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(lwIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(lhIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${labelBg}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(4)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(4)}"/>\n` + + ` <Cell N="TopMargin" V="0"/>\n` + + ` <Cell N="BottomMargin" V="0"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="1"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(lwIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(lwIn)}" F="Width*1"/><Cell N="Y" V="${f6(lhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(lhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(f.label)}</Text>\n` + + ` </Shape>`, + ); + } + + f.dividers.forEach((div, k) => { + const divId = nextId++; + const divHIn = n6(2 / DPI); + shapeXml.push( + ` <Shape ID="${divId}" NameU="FrameDiv_${escXml(f.id)}_${k}" Name="Divider" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(toVisioY(div.y))}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(divHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(divHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="2"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="${f6(n6(divHIn / 2))}" F="Height*0.5"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(wIn)}" F="Width*1"/><Cell N="Y" V="${f6(n6(divHIn / 2))}" F="Height*0.5"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + if (div.label || f.operator === "alt") { + const elseId = nextId++; + const eb = div.labelBox ?? { + x: f.box.x + 6, + y: div.y + Math.max(0, (div.h - 16) / 2), + w: Math.min(Math.max(16, f.box.w - 12), ((f.operator === "alt" ? 4 : 0) + div.label.length) * 7 + 16), + h: 16, + }; + const ewIn = n6(eb.w / DPI); + const ehIn = n6(Math.max(18, eb.h + 2) / DPI); + const isAlt = f.operator === "alt"; + const charXml = isAlt + ? ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${P.textTertiary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` <Row IX="1"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>` + : ` <Row IX="0"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textSecondary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>`; + const txtXml = isAlt + ? `<cp IX="0"/><pp IX="0"/>else${div.label ? `<cp IX="1"/> ${escXml(div.label)}` : ""}` + : `<cp IX="0"/><pp IX="0"/>${escXml(div.label)}`; + topLabelXml.push( + ` <Shape ID="${elseId}" NameU="FrameElse_${escXml(f.id)}_${k}" Name="${escXml(div.label || "else")}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(toVisioX(eb.x + eb.w / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(toVisioY(eb.y + eb.h / 2))}"/>\n` + + ` <Cell N="Width" V="${f6(ewIn)}"/>\n` + + ` <Cell N="Height" V="${f6(ehIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(ewIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(ehIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${labelBg}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(4)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(4)}"/>\n` + + ` <Cell N="TopMargin" V="0"/>\n` + + ` <Cell N="BottomMargin" V="0"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + `${charXml}\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="1"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(ewIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(ewIn)}" F="Width*1"/><Cell N="Y" V="${f6(ehIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(ehIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text>${txtXml}</Text>\n` + + ` </Shape>`, + ); + } + }); + } + + // 3c. Sequence activation bars (connectable shapes over lifelines/frames, glued to message connectors) + for (const bar of scene.bars) { + const id = barSheetId.get(bar.id)!; + const key = `bar:${bar.id}`; + const g = geomByKey.get(key)!; + const conns = connsByKey.get(key) ?? []; + placed.set(key, { sheetId: id, pinX: g.pinX, pinY: g.pinY, wIn: g.wIn, hIn: g.hIn, conns }); + const connRowsXml = renderConnectionRows(conns, g.wIn, g.hIn); + shapeXml.push( + ` <Shape ID="${id}" NameU="Bar_${escXml(bar.id)}" Name="Activation ${escXml(bar.participantId)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(g.pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(g.pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(g.wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(g.hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(g.wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(g.hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${P.cardFill}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LineColor" V="${P.structure}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(0.75)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="Rounding" V="${f6(n6(2 / DPI))}"/>\n` + + ` <Cell N="ObjType" V="1"/>\n` + + connRowsXml + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(g.wIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(g.wIn)}" F="Width*1"/><Cell N="Y" V="${f6(g.hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(g.hIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` </Shape>`, + ); + } + + // 4. Node shapes + for (const n of scene.nodes) { + const id = nodeSheetId.get(n.id)!; + const wIn = n6(n.box.w / DPI); + const hIn = n6(n.box.h / DPI); + const pinX = toVisioX(n.box.x + n.box.w / 2); + const pinY = toVisioY(n.box.y + n.box.h / 2); + const key = `node:${n.id}`; + const conns = connsByKey.get(key) ?? []; + placed.set(key, { sheetId: id, pinX, pinY, wIn, hIn, conns }); + + const isFocal = n.focal; + const fill = isFocal ? P.focalFill : P.cardFill; + const stroke = isFocal + ? P.focalBorder + : scene.type === "flowchart" + ? P.structure + : P.cardBorder; + const radIn = n.shape === "decision" ? 0 : n.shape === "terminal" ? n6(hIn / 2) : n6(8 / DPI); + const horzAlign = n.shape === "decision" || n.shape === "terminal" || n.shape === "participant" ? 1 : 0; + const vertAlign = n.shape === "table" ? 0 : 1; + + if (n.shape === "table") { + // Schema table as a Visio Group: the outer Group holds the Connection rows so FK connectors glue + // directly to the table, while child shapes place the card frame, header divider, header name, + // each column row (aligned to exact row.y / row.h), and optional "+ N more" footer. + const connRowsXml = renderConnectionRows(conns, wIn, hIn); + const geomXml = buildNodeGeometryXml(n, wIn, hIn); + const childShapes: string[] = []; + const frameId = nextId++; + const nameColor = isFocal ? P.focalInk : P.textPrimary; + const kindColor = isFocal ? P.focalQuiet : P.textTertiary; + const detailColor = isFocal ? P.focalQuiet : P.textSecondary; + + // Child 0: card background + border + header divider + childShapes.push( + ` <Shape ID="${frameId}" NameU="TableFrame_${escXml(n.id)}" Name="${escXml(n.name)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="PinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${fill}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LineColor" V="${stroke}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(1)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="Rounding" V="${f6(radIn)}"/>\n` + + ` <Cell N="ObjType" V="1"/>\n` + + geomXml.replace(/^ /gm, " ") + + ` </Shape>`, + ); + + // Child 1: table header title + const headerHIn = n6((n.headerH ?? 37) / DPI); + const headerPinY = n6(hIn - headerHIn / 2); + const headerId = nextId++; + childShapes.push( + ` <Shape ID="${headerId}" NameU="TableHeader_${escXml(n.id)}" Name="${escXml(n.name)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(wIn / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(headerPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(headerHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(headerHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(12)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(12)}"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${nameColor}"/><Cell N="Style" V="1"/><Cell N="Size" V="${ptToIn(10.5)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(n.name)}</Text>\n` + + ` </Shape>`, + ); + + // Child 2..k: column rows positioned at exact row.y / row.h (matching FK Connection ports) + for (const row of n.rows ?? []) { + const rowHIn = n6(row.h / DPI); + const rowPinY = n6(hIn - (row.y + row.h / 2) / DPI); + const leftId = nextId++; + const keyPad = (row.key ?? "").padEnd(3, " "); + childShapes.push( + ` <Shape ID="${leftId}" NameU="Row_${escXml(n.id)}_${row.index}" Name="${escXml(row.name)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(wIn / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(rowPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(rowHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(rowHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(12)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(12)}"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${kindColor}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(8.5)}"/></Row>\n` + + ` <Row IX="1"><Cell N="Font" V="1"/><Cell N="Color" V="${nameColor}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(keyPad)}<cp IX="1"/>${escXml(row.name)}</Text>\n` + + ` </Shape>`, + ); + const rightText = row.refTable ? `→ ${row.refTable}` : row.type ?? ""; + if (rightText) { + const rightId = nextId++; + childShapes.push( + ` <Shape ID="${rightId}" NameU="RowType_${escXml(n.id)}_${row.index}" Name="${escXml(rightText)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(wIn / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(rowPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(rowHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(rowHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(12)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(12)}"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${row.refTable ? detailColor : kindColor}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(8.5)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="2"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(rightText)}</Text>\n` + + ` </Shape>`, + ); + } + } + + if (n.more) { + const lastRow = n.rows?.[n.rows.length - 1]; + const moreTop = lastRow ? lastRow.y + lastRow.h + 2 : (n.headerH ?? 37) + 4; + const moreHIn = n6(20 / DPI); + const morePinY = n6(hIn - (moreTop + 10) / DPI); + const moreId = nextId++; + childShapes.push( + ` <Shape ID="${moreId}" NameU="More_${escXml(n.id)}" Name="+ ${n.more} more" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(n6(wIn / 2))}"/>\n` + + ` <Cell N="PinY" V="${f6(morePinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(moreHIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(moreHIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(12)}"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="0"/><Cell N="Color" V="${kindColor}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(8.5)}"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text><cp IX="0"/><pp IX="0"/>${escXml(`+ ${n.more} more`)}</Text>\n` + + ` </Shape>`, + ); + } + + shapeXml.push( + ` <Shape ID="${id}" NameU="Node_${escXml(n.id)}" Name="${escXml(n.name)}" Type="Group">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FlipX" V="0"/>\n` + + ` <Cell N="FlipY" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="ObjType" V="1"/>\n` + + connRowsXml + + ` <Shapes>\n` + + `${childShapes.join("\n")}\n` + + ` </Shapes>\n` + + ` </Shape>`, + ); + continue; + } + + const { charRows, textRuns } = buildNodeTextRuns(n, P); + const connRowsXml = renderConnectionRows(conns, wIn, hIn); + const geomXml = buildNodeGeometryXml(n, wIn, hIn); + const parentGroupId = n.group ? groupSheetId.get(n.group) : undefined; + const memberRelCell = parentGroupId + ? ` <Cell N="Relationships" V="0" F="SUM(DEPENDSON(4,Sheet.${parentGroupId}!SheetRef()))"/>\n` + : ""; + + shapeXml.push( + ` <Shape ID="${id}" NameU="Node_${escXml(n.id)}" Name="${escXml(n.name)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(wIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(hIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FlipX" V="0"/>\n` + + ` <Cell N="FlipY" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${fill}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LineColor" V="${stroke}"/>\n` + + ` <Cell N="LineWeight" V="${ptToIn(1)}"/>\n` + + ` <Cell N="LinePattern" V="1"/>\n` + + ` <Cell N="Rounding" V="${f6(radIn)}"${n.shape === "terminal" ? ' F="Height*0.5"' : ""}/>\n` + + ` <Cell N="VerticalAlign" V="${vertAlign}"/>\n` + + ` <Cell N="LeftMargin" V="${pxToIn(n.shape === "terminal" ? 16 : n.shape === "participant" && n.mark ? 24 : 12)}"/>\n` + + ` <Cell N="RightMargin" V="${pxToIn(n.shape === "terminal" ? 16 : n.mark ? 24 : 12)}"/>\n` + + ` <Cell N="TopMargin" V="${pxToIn(8)}"/>\n` + + ` <Cell N="BottomMargin" V="${pxToIn(8)}"/>\n` + + ` <Cell N="ObjType" V="1"/>\n` + + memberRelCell + + ` <Section N="Character">\n` + + `${charRows.join("\n")}\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="${horzAlign}"/></Row>\n` + + ` </Section>\n` + + connRowsXml + + geomXml + + ` <Text>${textRuns.join("")}</Text>\n` + + ` </Shape>`, + ); + + if (n.mark) { + if (n.mark.attribution && !attributions.includes(n.mark.attribution)) attributions.push(n.mark.attribution); + const markId = nextId++; + const rId = `rId${mediaFiles.length + 1}`; + const fileName = `mark_${mediaFiles.length + 1}.svg`; + const useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark"; + mediaFiles.push({ rId, fileName, svg: useDarkForm ? n.mark.svgDark : n.mark.svgLight }); + const mw = n6(16 / DPI); + const mh = n6(16 / DPI); + const mPinX = toVisioX(n.box.x + n.box.w - 12 - 8); + const mPinY = toVisioY(n.box.y + 10 + 8); + shapeXml.push( + ` <Shape ID="${markId}" NameU="Mark_${escXml(n.id)}" Name="${escXml(n.mark.id)}" Type="Foreign">\n` + + ` <Cell N="PinX" V="${f6(mPinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(mPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(mw)}"/>\n` + + ` <Cell N="Height" V="${f6(mh)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(mw / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(mh / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="ImgOffsetX" V="0"/>\n` + + ` <Cell N="ImgOffsetY" V="0"/>\n` + + ` <Cell N="ImgWidth" V="${f6(mw)}" F="Width*1"/>\n` + + ` <Cell N="ImgHeight" V="${f6(mh)}" F="Height*1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="FillPattern" V="0"/>\n` + + ` <ForeignData ForeignType="Bitmap" CompressionType="SVG">\n` + + ` <Rel r:id="${rId}"/>\n` + + ` </ForeignData>\n` + + ` </Shape>`, + ); + } + } + + // 5. 1-D Connectors: ONE Shape per Basalt edge, snapped in Visio inches to exact Connection coordinates + for (let idx = 0; idx < scene.edges.length; idx++) { + const e = scene.edges[idx]!; + const ec = edgeConns[idx]!; + const fromPlaced = placed.get(ec.fromKey); + const toPlaced = placed.get(ec.toKey); + if (!fromPlaced || !toPlaced) continue; + const fromConn = ec.fromIx >= 0 ? fromPlaced.conns[ec.fromIx] : undefined; + const toConn = ec.toIx >= 0 ? toPlaced.conns[ec.toIx] : undefined; + + // Exact start and end in Visio inches: the placed shape's Connection row, or the free end's own page point + const p0: Pt = fromConn ? connectionPagePt(fromPlaced, fromConn) : ec.fromPt!; + const pN: Pt = toConn ? connectionPagePt(toPlaced, toConn) : ec.toPt!; + const rawVisioPts: Pt[] = e.pts.map((pt) => ({ x: toVisioX(pt.x), y: toVisioY(pt.y) })); + const vPts = snapRouteToPorts(rawVisioPts, p0, pN, e.fromPort.side, e.toPort.side); + + // On 6-point schema corridor routes, Lucidchart can collapse a short (< 27px) final horizontal stub + // into a diagonal across an intermediate table. When the target gutter has clearance, widen the final stub to ~35px. + if (e.fk && vPts.length === 6) { + const p3 = vPts[3]!, p4 = vPts[4]!, p5 = vPts[5]!; + const stubDx = p4.x - p5.x; + if (Math.abs(p4.y - p5.y) < 1e-4 && Math.abs(p3.x - p4.x) < 1e-4 && Math.abs(stubDx) > 1e-4 && Math.abs(stubDx) < 0.28) { + const candX = n6(p5.x + Math.sign(stubDx) * 0.36); + const yMin = Math.min(p3.y, p4.y), yMax = Math.max(p3.y, p4.y); + const clear = scene.nodes.every((nd) => { + const g = geomByKey.get(`node:${nd.id}`); + if (!g) return true; + const nL = g.pinX - g.wIn / 2 - 0.14; + const nR = g.pinX + g.wIn / 2 + 0.14; + const nB = g.pinY - g.hIn / 2; + const nT = g.pinY + g.hIn / 2; + return !(candX > nL && candX < nR && yMax > nB && yMin < nT); + }); + if (clear) { + vPts[3] = { x: candX, y: p3.y }; + vPts[4] = { x: candX, y: p4.y }; + } + } + } + + const wIn = n6(pN.x - p0.x); + const hIn = n6(pN.y - p0.y); + const pinX = n6((p0.x + pN.x) / 2); + const pinY = n6((p0.y + pN.y) / 2); + const locPinX = n6(wIn * 0.5); + const locPinY = n6(hIn * 0.5); + + const id = nextId++; + const isMain = e.kind === "main"; + const isDashed = e.kind === "dashed"; + const lineColor = isMain ? P.edgeMain : P.edgePlain; + const lineWeight = isMain ? ptToIn(1.5) : ptToIn(0.75); + const linePattern = isDashed ? 2 : 1; + const beginArrow = e.card ? VSDX_CARD[e.card.from] : e.fk ? 10 : 0; // crow's-foot codes 25/28/29/30, or 10 = filled circle dot for FK origin + const endArrow = e.card ? VSDX_CARD[e.card.to] : e.openTip ? 1 : 4; // crow's-foot codes, or 1 = open V, 4 = filled block triangle + // Visio Medium (2) crow's-foot markers import oversized in Lucidchart and collide across 28px table rows; Very Small (0) fits cleanly. + const arrowSize = e.card ? 0 : 2; + const radIn = n6((e.sequence && e.from === e.to ? 4 : 8) / DPI); + + // Bind aligned bend coordinates to Visio's 0 / Width*1 / Height*1 formulas so if an importer shifts an endpoint + // magnet by a few pixels, 3-point L-bends and end stubs stay strictly collinear instead of forming a small jog. + const geomRows = vPts.map((pt, k) => { + const isStart = k === 0; + const isEnd = k === vPts.length - 1; + const lx = isStart ? 0 : isEnd ? wIn : n6(pt.x - p0.x); + const ly = isStart ? 0 : isEnd ? hIn : n6(pt.y - p0.y); + const tag = isStart ? "MoveTo" : "LineTo"; + const fxAttr = isStart ? "" : isEnd ? ' F="Width*1"' : Math.abs(lx) < 1e-6 ? ' F="0"' : Math.abs(lx - wIn) < 1e-6 ? ' F="Width*1"' : ""; + const fyAttr = isStart ? "" : isEnd ? ' F="Height*1"' : Math.abs(ly) < 1e-6 ? ' F="0"' : Math.abs(ly - hIn) < 1e-6 ? ' F="Height*1"' : ""; + return ` <Row T="${tag}" IX="${k + 1}"><Cell N="X" V="${f6(lx)}"${fxAttr}/><Cell N="Y" V="${f6(ly)}"${fyAttr}/></Row>`; + }).join("\n"); + + const fromOneBased = ec.fromIx + 1; + const toOneBased = ec.toIx + 1; + + // Every edge label is its own shape in the top label layer, on a backdrop of the page's colour sized as Basalt + // sizes its plate (Lucid draws no backdrop under a connector's own text, so a line under it would strike the words): + // a label on a line is its words plus space-1 a side, already in its scene box; a sequence message's words carry + // space-1-5 a side (`.basalt-diagram-said`); a label beside a line is its words alone. One line is 16px tall. + if (e.label) { + const lblId = nextId++; + const lPinX = toVisioX(e.label.box.x + e.label.box.w / 2); + const lPinY = toVisioY(e.label.box.y + e.label.box.h / 2); + const platePadX = e.sequence ? 6 : 0; + const lwIn = n6((e.label.box.w + 2 * platePadX) / DPI); + const lhIn = n6(e.label.box.h / DPI); + const noteChar = e.label.note + ? `\n <Row IX="1"><Cell N="Font" V="0"/><Cell N="Color" V="${P.textTertiary}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(8.5)}"/></Row>` + : ""; + const txtXml = e.label.note + ? `<cp IX="0"/><pp IX="0"/>${escXml(e.label.text)}\n<cp IX="1"/><pp IX="0"/>${escXml(e.label.note)}` + : `<cp IX="0"/><pp IX="0"/>${escXml(e.label.text)}`; + topLabelXml.push( + ` <Shape ID="${lblId}" NameU="EdgeLabel_${e.index}" Name="${escXml(e.label.text)}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(lPinX)}"/>\n` + + ` <Cell N="PinY" V="${f6(lPinY)}"/>\n` + + ` <Cell N="Width" V="${f6(lwIn)}"/>\n` + + ` <Cell N="Height" V="${f6(lhIn)}"/>\n` + + ` <Cell N="LocPinX" V="${f6(n6(lwIn / 2))}" F="Width*0.5"/>\n` + + ` <Cell N="LocPinY" V="${f6(n6(lhIn / 2))}" F="Height*0.5"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FillForegnd" V="${labelBg}"/>\n` + + ` <Cell N="FillPattern" V="1"/>\n` + + ` <Cell N="LinePattern" V="0"/>\n` + + ` <Cell N="VerticalAlign" V="1"/>\n` + + ` <Cell N="LeftMargin" V="0"/>\n` + + ` <Cell N="RightMargin" V="0"/>\n` + + ` <Cell N="TopMargin" V="0"/>\n` + + ` <Cell N="BottomMargin" V="0"/>\n` + + ` <Cell N="ObjType" V="4"/>\n` + + ` <Section N="Character">\n` + + ` <Row IX="0"><Cell N="Font" V="1"/><Cell N="Color" V="${e.sequence ? P.textPrimary : P.edgePlain}"/><Cell N="Style" V="0"/><Cell N="Size" V="${ptToIn(9)}"/></Row>${noteChar}\n` + + ` </Section>\n` + + ` <Section N="Paragraph">\n` + + ` <Row IX="0"><Cell N="HorzAlign" V="1"/></Row>\n` + + ` </Section>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="0"/>\n` + + ` <Cell N="NoLine" V="1"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + ` <Row T="MoveTo" IX="1"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="2"><Cell N="X" V="${f6(lwIn)}" F="Width*1"/><Cell N="Y" V="0"/></Row>\n` + + ` <Row T="LineTo" IX="3"><Cell N="X" V="${f6(lwIn)}" F="Width*1"/><Cell N="Y" V="${f6(lhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="4"><Cell N="X" V="0"/><Cell N="Y" V="${f6(lhIn)}" F="Height*1"/></Row>\n` + + ` <Row T="LineTo" IX="5"><Cell N="X" V="0"/><Cell N="Y" V="0"/></Row>\n` + + ` </Section>\n` + + ` <Text>${txtXml}</Text>\n` + + ` </Shape>`, + ); + } + + const beginF = fromConn + ? ` F="PAR(PNT(Sheet.${fromPlaced.sheetId}!Connections.X${fromOneBased},Sheet.${fromPlaced.sheetId}!Connections.Y${fromOneBased}))"` + : ""; + const endF = toConn + ? ` F="PAR(PNT(Sheet.${toPlaced.sheetId}!Connections.X${toOneBased},Sheet.${toPlaced.sheetId}!Connections.Y${toOneBased}))"` + : ""; + + shapeXml.push( + ` <Shape ID="${id}" NameU="Connector_${e.index}" Name="Dynamic connector.${e.index}" Type="Shape">\n` + + ` <Cell N="PinX" V="${f6(pinX)}" F="GUARD((BeginX+EndX)/2)"/>\n` + + ` <Cell N="PinY" V="${f6(pinY)}" F="GUARD((BeginY+EndY)/2)"/>\n` + + ` <Cell N="Width" V="${f6(wIn)}" F="GUARD(EndX-BeginX)"/>\n` + + ` <Cell N="Height" V="${f6(hIn)}" F="GUARD(EndY-BeginY)"/>\n` + + ` <Cell N="LocPinX" V="${f6(locPinX)}" F="GUARD(Width*0.5)"/>\n` + + ` <Cell N="LocPinY" V="${f6(locPinY)}" F="GUARD(Height*0.5)"/>\n` + + ` <Cell N="Angle" V="0"/>\n` + + ` <Cell N="FlipX" V="0"/>\n` + + ` <Cell N="FlipY" V="0"/>\n` + + ` <Cell N="BeginX" V="${f6(p0.x)}"${beginF}/>\n` + + ` <Cell N="BeginY" V="${f6(p0.y)}"${beginF}/>\n` + + ` <Cell N="EndX" V="${f6(pN.x)}"${endF}/>\n` + + ` <Cell N="EndY" V="${f6(pN.y)}"${endF}/>\n` + + ` <Cell N="ObjType" V="2"/>\n` + + ` <Cell N="ShapeRouteStyle" V="1"/>\n` + + ` <Cell N="ConFixedCode" V="2"/>\n` + + ` <Cell N="ConLineRouteExt" V="1"/>\n` + + ` <Cell N="ConLineJumpCode" V="1"/>\n` + + ` <Cell N="LineColor" V="${lineColor}"/>\n` + + ` <Cell N="LineWeight" V="${lineWeight}"/>\n` + + ` <Cell N="LinePattern" V="${linePattern}"/>\n` + + ` <Cell N="Rounding" V="${f6(radIn)}"/>\n` + + ` <Cell N="BeginArrow" V="${beginArrow}"/>\n` + + (beginArrow ? ` <Cell N="BeginArrowSize" V="${arrowSize}"/>\n` : "") + + ` <Cell N="EndArrow" V="${endArrow}"/>\n` + + ` <Cell N="EndArrowSize" V="${arrowSize}"/>\n` + + ` <Section N="Geometry" IX="0">\n` + + ` <Cell N="NoFill" V="1"/>\n` + + ` <Cell N="NoLine" V="0"/>\n` + + ` <Cell N="NoShow" V="0"/>\n` + + `${geomRows}\n` + + ` </Section>\n` + + ` </Shape>`, + ); + + if (fromConn) { + connectXml.push( + ` <Connect FromSheet="${id}" FromCell="BeginX" FromPart="9" ToSheet="${fromPlaced.sheetId}" ToCell="Connections.X${fromOneBased}" ToPart="${100 + ec.fromIx}"/>`, + ); + } + if (toConn) { + connectXml.push( + ` <Connect FromSheet="${id}" FromCell="EndX" FromPart="12" ToSheet="${toPlaced.sheetId}" ToCell="Connections.X${toOneBased}" ToPart="${100 + ec.toIx}"/>`, + ); + } + } + + const svgDefaultType = mediaFiles.length + ? ` <Default Extension="svg" ContentType="image/svg+xml"/>\n` + : ""; + + const contentTypes = + `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` + + `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n` + + ` <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\n` + + ` <Default Extension="xml" ContentType="application/xml"/>\n` + + svgDefaultType + + ` <Override PartName="/visio/document.xml" ContentType="application/vnd.ms-visio.drawing.main+xml"/>\n` + + ` <Override PartName="/visio/pages/pages.xml" ContentType="application/vnd.ms-visio.pages+xml"/>\n` + + ` <Override PartName="/visio/pages/page1.xml" ContentType="application/vnd.ms-visio.page+xml"/>\n` + + `</Types>\n`; + + const rootRels = + `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` + + `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n` + + ` <Relationship Id="rId1" Type="http://schemas.microsoft.com/visio/2010/relationships/document" Target="visio/document.xml"/>\n` + + `</Relationships>\n`; + + const creator = scene.measuredBy + ? `Basalt Diagram Exporter (${scene.measuredBy})` + : "Basalt Diagram Exporter"; + const descLine = attributions.length + ? ` <Description>${escXml(attributions.join(" "))}</Description>\n` + : ""; + const docXml = + `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` + + `<VisioDocument xmlns="http://schemas.microsoft.com/office/visio/2012/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xml:space="preserve">\n` + + ` <DocumentProperties>\n` + + ` <Title>${escXml(scene.title || scene.id)}\n` + + ` ${escXml(creator)}\n` + + descLine + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `\n`; + + const docRels = + `\n` + + `\n` + + ` \n` + + `\n`; + + const pageName = escXml(scene.title || scene.id); + const pagesXml = + `\n` + + `\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `\n`; + + const pagesRels = + `\n` + + `\n` + + ` \n` + + `\n`; + + const connectsBlock = connectXml.length + ? ` \n${connectXml.join("\n")}\n \n` + : ""; + + // 6. Topmost label layer: all opaque page-colour plates (bands, frame tabs/labels/else, edge labels) + // emitted after lifelines, activation bars, and connectors so lines and bars never cut across words. + shapeXml.push(...topLabelXml); + + const page1Xml = + `\n` + + `\n` + + ` \n` + + `${shapeXml.join("\n")}\n` + + ` \n` + + connectsBlock + + `\n`; + + const entries: ZipEntry[] = [ + { name: "[Content_Types].xml", data: contentTypes }, + { name: "_rels/.rels", data: rootRels }, + { name: "visio/document.xml", data: docXml }, + { name: "visio/_rels/document.xml.rels", data: docRels }, + { name: "visio/pages/pages.xml", data: pagesXml }, + { name: "visio/pages/_rels/pages.xml.rels", data: pagesRels }, + { name: "visio/pages/page1.xml", data: page1Xml }, + ]; + + if (mediaFiles.length) { + const page1Rels = + `\n` + + `\n` + + mediaFiles.map((m) => ` `).join("\n") + + `\n\n`; + entries.push({ name: "visio/pages/_rels/page1.xml.rels", data: page1Rels }); + for (const m of mediaFiles) entries.push({ name: `visio/media/${m.fileName}`, data: m.svg }); + } + + return makeDeterministicZip(entries); +} + +function renderConnectionRows(conns: readonly ConnEntry[], wIn: number, hIn: number): string { + if (!conns.length) return ""; + const fmtF = (val: number, dim: number, fallback: number): string => { + const f = dim > 0 ? Math.max(0, Math.min(1, val / dim)) : fallback; + return Number(f.toFixed(8)).toString(); + }; + const rows = conns.map((c) => ( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` ` + )); + return `
\n${rows.join("\n")}\n
\n`; +} + +function buildNodeGeometryXml(n: SceneNode, wIn: number, hIn: number): string { + if (n.shape === "decision") { + const hw = n6(wIn / 2); + const hh = n6(hIn / 2); + return ( + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + ); + } + const rectGeom = + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n`; + if (n.shape === "table") { + const headerDivY = n6(Math.max(0, hIn - (n.headerH ?? 37) / DPI)); + return ( + rectGeom + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + ); + } + return rectGeom; +} + +function buildNodeTextRuns(n: SceneNode, P: ReturnType): { charRows: string[]; textRuns: string[] } { + const isFocal = n.focal; + const kindColor = isFocal ? P.focalQuiet : P.textTertiary; + const nameColor = isFocal ? P.focalInk : P.textPrimary; + const detailColor = isFocal ? P.focalQuiet : P.textSecondary; + const charRows: string[] = []; + const textRuns: string[] = []; + let cpIx = 0; + + if (n.kind) { + charRows.push(` `); + textRuns.push(`${escXml(n.kind)}\n`); + cpIx++; + } + charRows.push(` `); + textRuns.push(`${escXml(n.name)}${n.detail ? "\n" : ""}`); + cpIx++; + if (n.detail) { + charRows.push(` `); + textRuns.push(`${escXml(n.detail)}`); + } + return { charRows, textRuns }; +} diff --git a/packages/react/src/interop/zip.ts b/packages/react/src/interop/zip.ts new file mode 100644 index 00000000..e61e5adb --- /dev/null +++ b/packages/react/src/interop/zip.ts @@ -0,0 +1,126 @@ +// Zero-dependency deterministic store-mode ZIP writer (PKWARE APPNOTE / ISO 29500-2 OPC). +// Uses fixed DOS timestamp 1980-01-01 00:00:00 and compression method 0 (STORE) so the output is +// synchronous, runtime-independent (browser and Node produce identical bytes), and byte-identical on repeat. +// No module-scope allocations: the CRC-32 table and TextEncoder are created lazily on first call. + +export interface ZipEntry { + name: string; + data: string | Uint8Array; +} + +let crcTable: Uint32Array | undefined; +let encoder: TextEncoder | undefined; + +function getCrcTable(): Uint32Array { + if (!crcTable) { + const t = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = (c & 1) !== 0 ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + t[n] = c >>> 0; + } + crcTable = t; + } + return crcTable; +} + +function encodeUtf8(s: string): Uint8Array { + encoder ??= new TextEncoder(); + return encoder.encode(s); +} + +export function crc32(bytes: Uint8Array): number { + const table = getCrcTable(); + let c = 0xffffffff; + for (let i = 0; i < bytes.length; i++) c = table[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function writeU16(view: DataView, offset: number, value: number): void { + view.setUint16(offset, value & 0xffff, true); +} + +function writeU32(view: DataView, offset: number, value: number): void { + view.setUint32(offset, value >>> 0, true); +} + +/** Builds a deterministic ZIP archive (store mode, fixed 1980-01-01 timestamp) from `entries`. */ +export function makeDeterministicZip(entries: readonly ZipEntry[]): Uint8Array { + const locals: Uint8Array[] = []; + const centrals: Uint8Array[] = []; + let offset = 0; + + for (const entry of entries) { + const nameBytes = encodeUtf8(entry.name); + const raw = typeof entry.data === "string" ? encodeUtf8(entry.data) : entry.data; + const crc = crc32(raw); + const size = raw.length; + // Bit 11 (0x0800): UTF-8 filename flag when any non-ASCII byte appears in entry name. + let flags = 0; + for (let i = 0; i < nameBytes.length; i++) { + if (nameBytes[i]! >= 0x80) { flags = 0x0800; break; } + } + + const local = new Uint8Array(30 + nameBytes.length); + const lv = new DataView(local.buffer); + writeU32(lv, 0, 0x04034b50); // local file header signature + writeU16(lv, 4, 20); // version needed (2.0) + writeU16(lv, 6, flags); // general purpose bit flag + writeU16(lv, 8, 0); // compression method: 0 (STORE) + writeU16(lv, 10, 0x0000); // mod time: 00:00:00 + writeU16(lv, 12, 0x0021); // mod date: 1980-01-01 + writeU32(lv, 14, crc); + writeU32(lv, 18, size); + writeU32(lv, 22, size); + writeU16(lv, 26, nameBytes.length); + writeU16(lv, 28, 0); // extra field length + local.set(nameBytes, 30); + locals.push(local, raw); + + const central = new Uint8Array(46 + nameBytes.length); + const cv = new DataView(central.buffer); + writeU32(cv, 0, 0x02014b50); // central directory header signature + writeU16(cv, 4, 20); // version made by + writeU16(cv, 6, 20); // version needed + writeU16(cv, 8, flags); + writeU16(cv, 10, 0); // compression method: 0 (STORE) + writeU16(cv, 12, 0x0000); // mod time + writeU16(cv, 14, 0x0021); // mod date (1980-01-01) + writeU32(cv, 16, crc); + writeU32(cv, 20, size); + writeU32(cv, 24, size); + writeU16(cv, 28, nameBytes.length); + writeU16(cv, 30, 0); // extra length + writeU16(cv, 32, 0); // comment length + writeU16(cv, 34, 0); // disk number start + writeU16(cv, 36, 0); // internal attributes + writeU32(cv, 38, 0); // external attributes + writeU32(cv, 42, offset); // relative offset of local header + central.set(nameBytes, 46); + centrals.push(central); + + offset += local.length + raw.length; + } + + let centralSize = 0; + for (const c of centrals) centralSize += c.length; + + const eocd = new Uint8Array(22); + const ev = new DataView(eocd.buffer); + writeU32(ev, 0, 0x06054b50); // end of central dir signature + writeU16(ev, 4, 0); // disk number + writeU16(ev, 6, 0); // start disk + writeU16(ev, 8, entries.length); // entries on this disk + writeU16(ev, 10, entries.length); // total entries + writeU32(ev, 12, centralSize); // size of central dir + writeU32(ev, 16, offset); // offset of central dir + writeU16(ev, 20, 0); // comment length + + const total = offset + centralSize + eocd.length; + const out = new Uint8Array(total); + let pos = 0; + for (const part of locals) { out.set(part, pos); pos += part.length; } + for (const part of centrals) { out.set(part, pos); pos += part.length; } + out.set(eocd, pos); + return out; +} diff --git a/packages/react/test/bundle.test.mjs b/packages/react/test/bundle.test.mjs index e172562f..21e47270 100644 --- a/packages/react/test/bundle.test.mjs +++ b/packages/react/test/bundle.test.mjs @@ -8,7 +8,7 @@ import { test } from "node:test"; import { fileURLToPath } from "node:url"; import * as esbuild from "esbuild"; -import { MARGIN, TABLE, measureExport, measurePackage, measureStyles, runtimeExports } from "./export-sizes.mjs"; +import { MARGIN, TABLE, measureExport, measurePackage, measureStyles, measureSubpaths, runtimeExports } from "./export-sizes.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const pkg = path.join(here, ".."); @@ -559,11 +559,23 @@ test("every runtime export alone stays within 5% of its recorded minified size", assert.deepEqual(over.sort(), [], `an export grew past its recorded size: ${ADVICE}`); }); -test("the whole package up front and styles.css, minified and gzipped, stay within 5% of their recorded sizes", async () => { +test("the whole package up front, tracked subpaths, and styles.css, minified and gzipped, stay within 5% of their recorded sizes", async () => { const table = recorded(); const whole = await measurePackage(); const styles = measureStyles(); - for (const [label, now, was] of [["the whole package, minified", whole.bytes, table.package.bytes], ["the whole package, gzipped", whole.gzip, table.package.gzip], ["styles.css as shipped", styles.bytes, table.styles.bytes], ["styles.css, gzipped", styles.gzip, table.styles.gzip]]) { + const subpaths = await measureSubpaths(); + const pairs = [ + ["the whole package, minified", whole.bytes, table.package.bytes], + ["the whole package, gzipped", whole.gzip, table.package.gzip], + ["styles.css as shipped", styles.bytes, table.styles.bytes], + ["styles.css, gzipped", styles.gzip, table.styles.gzip], + ]; + for (const [name, was] of Object.entries(table.subpaths ?? {})) { + const now = subpaths[name]; + assert.ok(now, `subpath ${name} missing from measureSubpaths()`); + pairs.push([`subpath ${name}, minified`, now.bytes, was.bytes], [`subpath ${name}, gzipped`, now.gzip, was.gzip]); + } + for (const [label, now, was] of pairs) { assert.ok(now <= ceiling(was), `${label}: ${now} bytes against ${was} recorded (limit ${ceiling(was)}); ${ADVICE}`); } // The style sheets ship minified: no comment is left in them (a /*! legal comment would be the one kept). diff --git a/packages/react/test/diagram-interop-browser.test.mjs b/packages/react/test/diagram-interop-browser.test.mjs new file mode 100644 index 00000000..26ec1aa9 --- /dev/null +++ b/packages/react/test/diagram-interop-browser.test.mjs @@ -0,0 +1,342 @@ +// Browser tests for @srasyndicate/basalt/diagram-interop and basalt-diagram-export CLI (DECISIONS 311, 314, 324, 327). +// Separated from diagram-interop.test.mjs so Node-only validation runs without launching Chromium (tests-paused.md). +// Covers: +// - Live DOM measured Geo entry (exportMeasuredDiagram + readMeasuredExtras) on CIMIP Phase 1 and Batch B figures +// - B2 exact geometry: CLI default path vs live React components asserts <= 0.5px on every box and route point, +// while recording the approximate headless fallback's drift +// - Byte-identical repeat SHA-256 on one Chromium and Chromium version recorded in .drawio, .vsdx, and .lucid metadata +// - Native browser ESM execution (no process global) and readMeasuredExtras lane propagation +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, test } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { fixturePage, launch, pkg } from "./support.mjs"; +import { + assertValidDrawio, + assertValidLucid, + assertValidVsdx, + CLI, + readZipEntries, + sha256, +} from "./support-diagram-interop.mjs"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const CIMIP = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams.json"), "utf8")); +const CIMIP_B = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams-b.json"), "utf8")); +const interop = await import(pathToFileURL(path.join(pkg, "dist", "diagram-interop.js")).href); + +function compareLucidDocs(liveDoc, testDoc, key) { + const L = liveDoc.pages[0], H = testDoc.pages[0]; + assert.deepEqual(L.shapes.map((s) => s.id), H.shapes.map((s) => s.id), `${key}: shape ids match`); + assert.deepEqual(L.lines.map((l) => l.id), H.lines.map((l) => l.id), `${key}: line ids match`); + + let maxBoxDelta = 0, shapesOverHalfPx = 0; + const boxDeltas = {}; + for (const s of L.shapes) { + const h = H.shapes.find((x) => x.id === s.id); + const dx = Math.abs(s.boundingBox.x - h.boundingBox.x); + const dy = Math.abs(s.boundingBox.y - h.boundingBox.y); + const dw = Math.abs(s.boundingBox.w - h.boundingBox.w); + const dh = Math.abs(s.boundingBox.h - h.boundingBox.h); + const m = Math.max(dx, dy, dw, dh); + if (m > 0.5) shapesOverHalfPx++; + if (m > maxBoxDelta) maxBoxDelta = m; + boxDeltas[s.id] = { dx: +dx.toFixed(2), dy: +dy.toFixed(2), dw: +dw.toFixed(2), dh: +dh.toFixed(2) }; + } + + const shapeById = (page) => new Map(page.shapes.map((s) => [s.id, s])); + const lineById = (page) => new Map(page.lines.map((l) => [l.id, l])); + const epPt = (page, ep) => { + if (ep.type === "shapeEndpoint") { + const s = shapeById(page).get(ep.shapeId); + return { x: s.boundingBox.x + ep.position.x * s.boundingBox.w, y: s.boundingBox.y + ep.position.y * s.boundingBox.h }; + } + if (ep.type === "lineEndpoint") { + const l = lineById(page).get(ep.lineId); + const p1 = epPt(page, l.endpoint1), p2 = epPt(page, l.endpoint2); + return { x: p1.x + ep.position * (p2.x - p1.x), y: p1.y + ep.position * (p2.y - p1.y) }; + } + return ep.position; + }; + + const polyLength = (pts) => { + let len = 0; + for (let k = 1; k < pts.length; k++) len += Math.hypot(pts[k].x - pts[k - 1].x, pts[k].y - pts[k - 1].y); + return len; + }; + + let maxRouteDelta = 0, routesOverHalfPx = 0; + let maxLabelDelta = 0, labelsOverHalfPx = 0; + const routeDeltas = {}; + const labelDeltas = {}; + for (const l of L.lines.filter((x) => x.id.startsWith("edge_"))) { + const h = H.lines.find((x) => x.id === l.id); + const lp = [epPt(L, l.endpoint1), ...(l.elbowControlPoints ?? []), epPt(L, l.endpoint2)]; + const hp = [epPt(H, h.endpoint1), ...(h.elbowControlPoints ?? []), epPt(H, h.endpoint2)]; + let m = lp.length === hp.length ? 0 : Infinity; + if (lp.length === hp.length) { + for (let k = 0; k < lp.length; k++) { + m = Math.max(m, Math.abs(lp[k].x - hp[k].x), Math.abs(lp[k].y - hp[k].y)); + } + } + if (m > 0.5) routesOverHalfPx++; + if (Number.isFinite(m) && m > maxRouteDelta) maxRouteDelta = m; + routeDeltas[l.id] = Number.isFinite(m) ? +m.toFixed(2) : "point-count-mismatch"; + + const lt = l.text ?? [], ht = h.text ?? []; + assert.equal(lt.length, ht.length, `${key}: ${l.id} text count`); + if (lt.length > 0) { + const arc = polyLength(lp); + let lm = 0; + for (let k = 0; k < lt.length; k++) { + lm = Math.max(lm, Math.abs((lt[k].position ?? 0.5) - (ht[k].position ?? 0.5)) * arc); + } + if (lm > 0.5) labelsOverHalfPx++; + if (lm > maxLabelDelta) maxLabelDelta = lm; + labelDeltas[l.id] = +lm.toFixed(2); + } + } + + // Lifelines (x) and frame dividers (endpoints) + let maxGuideDelta = 0, guidesOverHalfPx = 0; + for (const l of L.lines.filter((x) => x.id.startsWith("life_") || x.id.startsWith("frame_div_"))) { + const h = H.lines.find((x) => x.id === l.id); + const lp1 = epPt(L, l.endpoint1), lp2 = epPt(L, l.endpoint2); + const hp1 = epPt(H, h.endpoint1), hp2 = epPt(H, h.endpoint2); + const m = Math.max( + Math.abs(lp1.x - hp1.x), Math.abs(lp1.y - hp1.y), + Math.abs(lp2.x - hp2.x), Math.abs(lp2.y - hp2.y), + ); + if (m > 0.5) guidesOverHalfPx++; + if (m > maxGuideDelta) maxGuideDelta = m; + } + + return { + shapesOverHalfPx, + maxBoxDelta: +maxBoxDelta.toFixed(2), + routesOverHalfPx, + maxRouteDelta: +maxRouteDelta.toFixed(2), + labelsOverHalfPx, + maxLabelDelta: +maxLabelDelta.toFixed(2), + guidesOverHalfPx, + maxGuideDelta: +maxGuideDelta.toFixed(2), + boxDeltas, + routeDeltas, + labelDeltas, + }; +} + +describe("live DOM measured Geo entry and B2 exact geometry (Chromium)", () => { + test("live React figures match single-figure CLI default path within <= 0.5px (boxes, routes, labels, frames, lifelines) and record headless fallback drift", async () => { + const autoArchPlaced = await interop.placeAutoDiagram(CIMIP_B.autoArchitecture); + const HOST = ` + import data from "./test/fixtures/cimip-diagrams.json"; + import dataB from "./test/fixtures/cimip-diagrams-b.json"; + import { buildModel, figureTree, measureFigure, syncAttributes } from "./dist/diagram-core.js"; + import { readMeasuredExtras } from "./dist/diagram-interop.js"; + const C = { architecture: B.ArchitectureDiagram, flowchart: B.FlowchartDiagram, "data-flow": B.DataFlowDiagram, sequence: B.SequenceDiagram, schema: B.SchemaDiagram }; + const all = { + ...data, + batchBArch: dataB.architecture, + batchBSeq: dataB.sequence, + batchBSchema: dataB.schema, + batchBAuto: ${JSON.stringify(autoArchPlaced)}, + }; + function Host() { + return
+ {Object.entries(all).map(([key, d]) => { const X = C[d.type]; const { type, ...props } = d; return ; })} +
; + } + createRoot(document.getElementById("root")).render(); + window.__measureAll = () => { + const out = {}; + for (const [key, spec] of Object.entries(all)) { + const fig = document.getElementById("fig-" + key); + const placements = spec.layout === "auto" && Array.isArray(spec.placement) ? spec.placement : [undefined]; + const base = (fig.getAttribute("aria-labelledby") || "dg").replace(/-title$/, ""); + const opts = { prefix: "basalt-diagram", base, hasSource: Boolean(spec.source), hiddenClass: "basalt-visually-hidden" }; + let chosen = null; + for (const placement of placements) { + const model = buildModel(spec, { checks: false, placement }); + if (model.unplaced) continue; + const res = measureFigure(fig, model, "basalt-diagram", base, { layout: "drawn" }, (d) => syncAttributes(fig, figureTree(model, d, opts))); + if (res?.dyn?.layout === "drawn" && res.geo) { chosen = { geo: res.geo, extras: readMeasuredExtras(fig, "basalt-diagram"), placement }; break; } + } + if (!chosen) { + const model = buildModel(spec, { checks: false, placement: placements[0] }); + const sizeTo = (least) => { if (least > 1104) fig.style.width = Math.ceil(least) + "px"; }; + const res = measureFigure(fig, model, "basalt-diagram", base, { layout: "drawn" }, (d) => syncAttributes(fig, figureTree(model, d, opts)), undefined, sizeTo); + chosen = { geo: res.geo, extras: readMeasuredExtras(fig, "basalt-diagram"), placement: placements[0] }; + } + out[key] = chosen; + } + return out; + }; + `; + const font = (file) => fs.readFileSync(path.join(pkg, "dist", "fonts", file)).toString("base64"); + const fontCss = `@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} html,body{margin:0;padding:0;background:var(--basalt-surface-page)}`; + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "basalt-interop-b2-")); + const browser = await launch(); + try { + const { page, errors } = await fixturePage(browser, HOST, { theme: "light", viewport: { width: 1280, height: 1200 }, standards: true }); + await page.addStyleTag({ content: fontCss }); + await page.evaluate(async () => { + await Promise.all([...document.fonts].map((f) => f.load())); + await document.fonts.ready; + }); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))))); + const measured = await page.evaluate(() => window.__measureAll()); + assert.deepEqual(errors, []); + + // Validate live measured export for all 5 CIMIP fixtures + Batch B nested groups, frames/bars, crow's foot + far keys, auto + const specsByKey = { + ...CIMIP, + batchBArch: CIMIP_B.architecture, + batchBSeq: CIMIP_B.sequence, + batchBSchema: CIMIP_B.schema, + batchBAuto: autoArchPlaced, + }; + const comparison = { defaultPath: {}, headlessFallback: {} }; + + for (const [key, spec] of Object.entries(specsByKey)) { + const { geo, extras, placement } = measured[key]; + assert.ok(geo && geo.lines.length > 0, `${key}: live Geo measured`); + assertValidDrawio(interop.exportMeasuredDiagram(spec, geo, "drawio", { extras, placement }), spec, `measured/${key}`); + assertValidVsdx(interop.exportMeasuredDiagram(spec, geo, "vsdx", { extras, placement }), spec, `measured/${key}`); + assertValidLucid(interop.exportMeasuredDiagram(spec, geo, "lucid", { extras, placement }), spec, `measured/${key}`); + + // Run the CLI on a single-figure JSON file so every figure is first in its run (guards B1 font-load race). + const singleIn = path.join(dir, `${key}.json`); + fs.writeFileSync(singleIn, JSON.stringify(spec)); + const outA = path.join(dir, `out-${key}-a`); + const cliArgs = [CLI, singleIn, "--to", "drawio,vsdx,lucid,lucid-json", "--width", "1104"]; + const rA = spawnSync(process.execPath, [...cliArgs, "--out", outA], { encoding: "utf8", timeout: 90000 }); + assert.equal(rA.status, 0, `${key}: ${rA.stderr}`); + + const stem = key.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); + // Verify repeat byte-identity on the first CIMIP figure and Batch B sequence + if (key === "architecture" || key === "batchBSeq") { + const outB = path.join(dir, `out-${key}-b`); + const rB = spawnSync(process.execPath, [...cliArgs, "--out", outB], { encoding: "utf8", timeout: 90000 }); + assert.equal(rB.status, 0, `${key} repeat: ${rB.stderr}`); + for (const ext of [".drawio", ".vsdx", ".lucid", ".lucid.json"]) { + assert.equal( + sha256(fs.readFileSync(path.join(outA, stem + ext))), + sha256(fs.readFileSync(path.join(outB, stem + ext))), + `CLI default repeat byte-identical on one Chromium: ${stem}${ext}`, + ); + } + } + + // Verify Chromium version + platform + Basalt version metadata in all three formats + const drawioXml = fs.readFileSync(path.join(outA, `${stem}.drawio`), "utf8"); + assertValidDrawio(drawioXml, spec, `cli-default/${key}`); + assert.match(drawioXml, new RegExp(`agent="Basalt Diagram Exporter \\(Chromium \\d+[^)]*, ${process.platform}, Basalt \\d+\\.\\d+\\.\\d+\\)"`), `${key}: draw.io records Chromium, platform, Basalt version`); + const vsdxBytes = fs.readFileSync(path.join(outA, `${stem}.vsdx`)); + assertValidVsdx(vsdxBytes, spec, `cli-default/${key}`); + assert.match(readZipEntries(vsdxBytes).get("visio/document.xml").toString("utf8"), new RegExp(`Basalt Diagram Exporter \\(Chromium \\d+[^<]*, ${process.platform}, Basalt \\d+\\.\\d+\\.\\d+\\)`), `${key}: vsdx records Chromium, platform, Basalt version`); + const lucidBytes = fs.readFileSync(path.join(outA, `${stem}.lucid`)); + assertValidLucid(lucidBytes, spec, `cli-default/${key}`); + const defaultDoc = JSON.parse(fs.readFileSync(path.join(outA, `${stem}.lucid.json`), "utf8")); + const nodeShapes = defaultDoc.pages[0].shapes.filter((s) => s.id.startsWith("node_")); + assert.ok(nodeShapes.length > 0); + for (const s of nodeShapes) { + assert.ok( + s.customData?.some((d) => d.key === "basalt_measured_by" && new RegExp(`^Chromium \\d+.*, ${process.platform}, Basalt \\d+\\.\\d+\\.\\d+$`).test(d.value)), + `${key}: lucid ${s.id} records Chromium, platform, Basalt version`, + ); + } + + // Compare CLI default path against live React component: assert <= 0.5px on boxes, routes, edge labels, lifelines, dividers (B1/B2) + const liveDoc = interop.exportMeasuredDiagram(spec, geo, "lucid-json", { extras, placement, diagramId: stem }); + const defDelta = compareLucidDocs(liveDoc, defaultDoc, `default/${key}`); + comparison.defaultPath[key] = defDelta; + assert.equal(defDelta.shapesOverHalfPx, 0, `${key}: default path box delta ${defDelta.maxBoxDelta}px > 0.5px`); + assert.equal(defDelta.routesOverHalfPx, 0, `${key}: default path route delta ${defDelta.maxRouteDelta}px > 0.5px`); + assert.equal(defDelta.labelsOverHalfPx, 0, `${key}: default path edge label delta ${defDelta.maxLabelDelta}px > 0.5px`); + assert.equal(defDelta.guidesOverHalfPx, 0, `${key}: default path lifeline/divider delta ${defDelta.maxGuideDelta}px > 0.5px`); + + // B2: on sequence frames, verify no page-filled frame label or else box covers a lifeline x outside Basalt's measured label rect + if (key === "batchBSeq") { + const pad = 32; + const lfXs = geo.lifelines.map((l) => l.x + pad); + for (let fi = 0; fi < (extras.frames?.length ?? 0); fi++) { + const ef = extras.frames[fi]; + if (ef.labelRect) { + const s = defaultDoc.pages[0].shapes.find((x) => x.id === `frame_label_f${fi}`); + assert.ok(s, `batchBSeq: frame_label_f${fi} present`); + for (const lx of lfXs) { + const inExport = lx >= s.boundingBox.x && lx <= s.boundingBox.x + s.boundingBox.w; + const inBasalt = lx >= ef.labelRect.l + pad && lx <= ef.labelRect.r + pad; + assert.equal(inExport, inBasalt, `batchBSeq: frame_label_f${fi} must not cover lifeline x=${lx} outside Basalt label rect`); + } + } + ef.dividers.forEach((div, k) => { + if (!div.labelRect) return; + const s = defaultDoc.pages[0].shapes.find((x) => x.id === `frame_else_f${fi}_${k}`); + assert.ok(s, `batchBSeq: frame_else_f${fi}_${k} present`); + for (const lx of lfXs) { + const inExport = lx >= s.boundingBox.x && lx <= s.boundingBox.x + s.boundingBox.w; + const inBasalt = lx >= div.labelRect.l + pad && lx <= div.labelRect.r + pad; + assert.equal(inExport, inBasalt, `batchBSeq: frame_else_f${fi}_${k} must not cover lifeline x=${lx} outside Basalt else rect`); + } + }); + } + } + + // Record approximate headless fallback drift + const headDoc = interop.diagramToLucidJson(spec, { width: 1104, diagramId: stem }); + comparison.headlessFallback[key] = compareLucidDocs(liveDoc, headDoc, `headless/${key}`); + } + if (process.env.PRINT_INTEROP_COMPARISON) { + process.stdout.write(`INTEROP_COMPARISON=${JSON.stringify(comparison)}\n`); + } + + // Measured lane rects keyed as lane-0..lane-5 propagate into sceneFromMeasured + const df = measured.dataFlow; + assert.equal(df.extras.lanes?.length, CIMIP.dataFlow.lanes.length); + const customLanes = df.extras.lanes.map((l, idx) => ({ + ...l, + rect: idx === 0 ? { l: 0, t: 0, r: df.geo.w, b: 140 } : { l: 0, t: 140 + idx * 90, r: df.geo.w, b: 200 + idx * 90 }, + })); + const docWithCustomLanes = interop.exportMeasuredDiagram(CIMIP.dataFlow, df.geo, "lucid-json", { extras: { ...df.extras, lanes: customLanes } }); + const swCustom = docWithCustomLanes.pages[0].shapes.find((s) => s.type === "swimLanes"); + assert.equal(swCustom.lanes[0].width, 185, "lane 0 bottom hits midpoint between lane 0 bottom (140) and lane 1 top (230) = 185"); + + // Native browser ESM check (no `process` global) + const rawPage = await browser.newPage(); + const interopSrc = fs.readFileSync(path.join(pkg, "dist", "diagram-interop.js"), "utf8"); + await rawPage.route("https://interop-browser-check.local/**", async (route) => { + if (route.request().url().endsWith("/diagram-interop.js")) { + await route.fulfill({ status: 200, contentType: "application/javascript; charset=utf-8", body: interopSrc }); + } else { + await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: "" }); + } + }); + await rawPage.goto("https://interop-browser-check.local/index.html"); + const browserOut = await rawPage.evaluate(async (spec) => { + const mod = await import("https://interop-browser-check.local/diagram-interop.js"); + return { + hasProcess: typeof globalThis.process !== "undefined", + drawioOk: mod.diagramToDrawio(spec).includes(" 0 && browserOut.lucidLen > 0, "vsdx and lucid work in native browser ESM"); + await rawPage.close(); + + await page.close(); + } finally { + await browser.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs new file mode 100644 index 00000000..d2c1a946 --- /dev/null +++ b/packages/react/test/diagram-interop.test.mjs @@ -0,0 +1,646 @@ +// Pure-Node tests for @srasyndicate/basalt/diagram-interop and basalt-diagram-export CLI (DECISIONS 311, 314, 324, 327). +// Runs with zero browser/Chromium launches (browser comparison and live DOM tests live in diagram-interop-browser.test.mjs). +// Covers: +// - Byte-identical SHA-256 determinism across all 5 CIMIP fixtures and all Batch B fixtures (crow's foot, +// far keys through corridors, nested groups, sequence frames + activation bars, automatic layout) +// - Official draw.io XSD validation (mxfile-1.0.xsd), Visio OPC + Connects + ConFixedCode=2, Lucid Standard Import JSON +// - Exact port axis-alignment invariant across every edge in every format (including RunTask negative fixture) +// - Marks on architecture cards, data-flow steps, and sequence participants against manifest terms +// - Frame header/else word-sized boxes, auto-layout direction, `measuredBy` metadata across formats, unplaced auto-layout error +// - CLI (--headless) determinism across TZ/LC_ALL, symlink execution, HTML script[data-diagram], Batch B auto-layout +// - Subpath isolation (outside root index, no "use client", no React/UI imports, lazy elkjs) +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, test } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { + assertValidDrawio, + assertValidLucid, + assertValidVsdx, + CLI, + pkg, + readForeignZipEntries, + readZipEntries, + repo, + sha256, +} from "./support-diagram-interop.mjs"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const CIMIP = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams.json"), "utf8")); +const CIMIP_KEYS = Object.keys(CIMIP); +const CIMIP_B = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams-b.json"), "utf8")); +const LAYOUT_FIXTURES = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "diagram-layout.json"), "utf8")).figures; +const interop = await import(pathToFileURL(path.join(pkg, "dist", "diagram-interop.js")).href); + +describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axis-alignment", () => { + for (const key of CIMIP_KEYS) { + const spec = CIMIP[key]; + + test(`${key}: byte-identical SHA-256 on repeat across all formats and themes`, () => { + for (const theme of ["light", "dark", "adaptive"]) { + const a = interop.diagramToDrawio(spec, { theme }); + const b = interop.diagramToDrawio(spec, { theme }); + assert.equal(sha256(a), sha256(b), `${key} drawio (${theme}) deterministic`); + } + for (const theme of ["light", "dark"]) { + assert.equal(sha256(interop.diagramToVsdx(spec, { theme })), sha256(interop.diagramToVsdx(spec, { theme })), `${key} vsdx (${theme})`); + assert.equal(sha256(interop.diagramToLucid(spec, { theme })), sha256(interop.diagramToLucid(spec, { theme })), `${key} lucid (${theme})`); + assert.equal( + JSON.stringify(interop.diagramToLucidJson(spec, { theme })), + JSON.stringify(interop.diagramToLucidJson(spec, { theme })), + `${key} lucid-json (${theme})`, + ); + } + }); + + test(`${key}: .drawio validates against mxfile-1.0.xsd and every edge is single, glued and port-aligned (light, dark, adaptive)`, () => { + for (const theme of ["light", "dark", "adaptive"]) { + const xml = interop.diagramToDrawio(spec, { theme }); + assertValidDrawio(xml, spec, `${key}/${theme}`); + if (theme === "adaptive") { + assert.match(xml, /adaptiveColors="auto"/); + assert.match(xml, /light-dark\(/); + } else { + assert.match(xml, /adaptiveColors="none"/); + assert.doesNotMatch(xml, /light-dark\(/); + } + } + }); + + test(`${key}: .vsdx OPC parts, Connects glue, ConFixedCode=2, dark PageBackground, and zero-jog Visio-inch port alignment`, () => { + for (const theme of ["light", "dark"]) { + const bytes = interop.diagramToVsdx(spec, { theme }); + assertValidVsdx(bytes, spec, `${key}/${theme}`); + const page1 = readZipEntries(bytes).get("visio/pages/page1.xml").toString("utf8"); + const firstShape = page1.match(/]*>([\s\S]*?)<\/Shape>/); + assert.ok(firstShape, `${key}/${theme}: first shape exists`); + if (theme === "dark") { + assert.equal(firstShape[1], "1", `${key}/dark: PageBackground is ID 1`); + assert.equal(firstShape[2], "PageBackground", `${key}/dark: first shape is PageBackground`); + assert.match(firstShape[3], //, `${key}/dark: surface-page fill #000000`); + assert.match(firstShape[3], //, `${key}/dark: PageBackground is locked`); + assert.match(firstShape[3], //, `${key}/dark: PageBackground move locked`); + } else { + assert.notEqual(firstShape[2], "PageBackground", `${key}/light: no dark background shape`); + } + } + }); + + test(`${key}: .lucid Standard Import JSON contract, dark fillColor and Lucid-unit port alignment`, () => { + for (const theme of ["light", "dark"]) { + const bytes = interop.diagramToLucid(spec, { theme }); + assertValidLucid(bytes, spec, `${key}/${theme}`); + const doc = JSON.parse(readZipEntries(bytes).get("document.json").toString("utf8")); + assert.equal(doc.pages[0].settings.fillColor, theme === "dark" ? "#000000" : "#fafafa", `${key}/${theme}: page fillColor`); + } + }); + } + + test("architecture RunTask (svc -> ecs) in .vsdx: a free Begin on svc's bottom at 0.25, End glued to its exact Connection row, proof-style 0.5px drift rejected", () => { + const runTaskGlue = (page1) => { + const svc = page1.match(/]*>([\s\S]*?)<\/Shape>/); + const ecs = page1.match(/]*>([\s\S]*?)<\/Shape>/); + const runTask = page1.match(/]*>([\s\S]*?)<\/Shape>/); + assert.ok(svc && ecs && runTask, "Node_svc, Node_ecs, and Connector_4 (RunTask) present"); + const cellV = (b, n) => Number(b.match(new RegExp(``)); + const endConn = page1.match(new RegExp(``)); + assert.ok(endConn, "RunTask End glued to Node_ecs"); + const connPt = (shapeBody, ix) => { + const row = shapeBody.match(new RegExp(`[\\s\\S]*?[\\s\\S]*?`)); + assert.ok(row, `Connection IX=${ix} present`); + const ox = cellV(shapeBody, "PinX") - cellV(shapeBody, "LocPinX"), oy = cellV(shapeBody, "PinY") - cellV(shapeBody, "LocPinY"); + const w = cellV(shapeBody, "Width"), h = cellV(shapeBody, "Height"); + const x = ox + Number(row[1]), y = oy + Number(row[3]); + return { x, y, fx: row[2] ? ox + w * Number(row[2]) : x, fy: row[4] ? oy + h * Number(row[4]) : y }; + }; + const svcEdge = { + x: cellV(svc[2], "PinX") - cellV(svc[2], "LocPinX") + 0.25 * cellV(svc[2], "Width"), + y: cellV(svc[2], "PinY") - cellV(svc[2], "LocPinY"), + }; + const from = beginConn ? connPt(svc[2], Number(beginConn[2]) - 100) : { ...svcEdge, fx: svcEdge.x, fy: svcEdge.y }; + const to = connPt(ecs[2], Number(endConn[2]) - 100); + const b = { x: cellV(runTask[2], "BeginX"), y: cellV(runTask[2], "BeginY") }, e = { x: cellV(runTask[2], "EndX"), y: cellV(runTask[2], "EndY") }; + const off = (p, c) => Math.max(Math.abs(p.x - c.x), Math.abs(p.y - c.y), Math.abs(p.x - c.fx), Math.abs(p.y - c.fy)); + return { runTask, begin: b, end: e, from, to, beginConn, beginOff: off(b, from), endOff: off(e, to) }; + }; + + const page1 = readZipEntries(interop.diagramToVsdx(CIMIP.architecture)).get("visio/pages/page1.xml").toString("utf8"); + const { runTask, begin, end, from, to, beginConn, beginOff, endOff } = runTaskGlue(page1); + assert.equal(beginConn, null, "RunTask leaves svc's bottom at 0.25, so its Begin is free at its exact point (Lucid moves a glued one about 1px)"); + assert.ok(beginOff <= 2e-6, `RunTask Begin (${begin.x},${begin.y}) on Node_svc bottom 0.25 edge (${from.x},${from.y})`); + assert.ok(endOff <= 2e-6, `RunTask End (${end.x},${end.y}) on its Connection row (${to.x},${to.y}; formula ${to.fx},${to.fy})`); + + const rows = [...runTask[2].matchAll(/<\/Row>/g)]; + assert.equal(rows.length, 3, "RunTask has exactly 3 geometry vertices"); + assert.equal(rows[1][2], "0.000000", "first bend stays strictly on X === 0"); + assert.equal(rows[1][3], rows[2][3], "final leg stays strictly horizontal into ECS"); + + const proof = fs.readFileSync(path.join(here, "fixtures", "runtask-jog-proof.vsdx")); + const proofEntries = readForeignZipEntries(proof); + const proofGlue = runTaskGlue(proofEntries.get("visio/pages/page1.xml").toString("utf8")); + assert.ok(proofGlue.beginOff > 0.005 && proofGlue.beginOff < 0.0055, `the proof's RunTask Begin is 0.5 px off its Connection row (${proofGlue.beginOff} in)`); + assert.throws(() => assertValidVsdx(proofEntries, CIMIP.architecture, "runtask-jog-proof"), /Connector_\d+: Begin .* != Connection/); + }); + + test("architecture-auto in .vsdx: HTTP + SSE and inference are free only at their off-centre top and bottom ends; every other end stays glued", async () => { + const placed = await interop.placeAutoDiagram(CIMIP_B.autoArchitecture); + const page1 = readZipEntries(interop.diagramToVsdx(placed)).get("visio/pages/page1.xml").toString("utf8"); + const shapes = [...page1.matchAll(/]*>([\s\S]*?)<\/Shape>/g)].map((m) => ({ id: m[1], nameU: m[2], body: m[3] })); + const label = (text) => { + const el = shapes.find((s) => s.nameU.startsWith("EdgeLabel_") && s.body.includes(`${text}`)); + assert.ok(el, `label ${text} present`); + return shapes.find((s) => s.nameU === `Connector_${el.nameU.slice("EdgeLabel_".length)}`); + }; + const glued = (c, part) => new RegExp(` s.nameU.startsWith("Connector_")); + const free = connectors.flatMap((c) => [glued(c, 9) ? [] : [`${c.nameU} Begin`], glued(c, 12) ? [] : [`${c.nameU} End`]].flat()); + assert.deepEqual(free.sort(), [`${sse.nameU} Begin`, `${inference.nameU} End`].sort(), "only those two ends are free"); + assertValidVsdx(interop.diagramToVsdx(placed), placed, "autoArchitecture/light"); + }); + + test("edge labels in .vsdx: a backdrop the colour of the page (white in light, on Lucid's and Visio's canvas) sized as Basalt sizes its plate", () => { + const unescape = (s) => s.replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); + for (const [key, spec] of [["architecture", CIMIP.architecture], ["sequence", CIMIP.sequence], ["dataFlow", CIMIP.dataFlow]]) { + for (const theme of ["light", "dark"]) { + const page1 = readZipEntries(interop.diagramToVsdx(spec, { theme })).get("visio/pages/page1.xml").toString("utf8"); + const labels = [...page1.matchAll(/]*>([\s\S]*?)<\/Shape>/g)]; + assert.ok(labels.length > 0, `${key}/${theme}: labels present`); + for (const [, name, body] of labels) { + const text = unescape(name); + const cell = (n) => body.match(new RegExp(` line.length * 7.2)); + const w = Math.round(Number(cell("Width")) * 96 * 100) / 100; + const h = Math.round(Number(cell("Height")) * 96 * 100) / 100; + const hasNote = //.test(body); + if (key === "sequence") { + if (!hasNote) assert.ok(Math.abs(w - (words + 12)) <= 0.02, `${key}/${theme} ${text}: words plus space-1-5 a side (${w} vs ${words + 12})`); + assert.equal(h, hasNote ? 32 : 16, `${key}/${theme} ${text}: ${hasNote ? 32 : 16}px tall`); + } else { + const pads = [words, words + 8].map((v) => Math.round(v * 100) / 100); + assert.ok(pads.some((v) => Math.abs(w - v) <= 0.02), `${key}/${theme} ${text}: its words (${pads[0]}) or its words plus space-1 a side (${pads[1]}), got ${w}`); + assert.equal(h, 16 * text.split("\n").length, `${key}/${theme} ${text}: 16px a line`); + } + } + } + } + }); +}); + +describe("Batch B parts in all three formats (DECISIONS 324, 327)", () => { + test("nested groups + two-line edge labels (cimip-diagrams-b architecture)", () => { + const spec = CIMIP_B.architecture; + for (const theme of ["light", "dark", "adaptive"]) { + const xml = interop.diagramToDrawio(spec, { theme }); + assertValidDrawio(xml, spec, `batch-b-arch/${theme}`); + assert.match(xml, /id="group-data"[^>]*parent="group-aws"/, "draw.io nested group parented in outer group"); + assert.match(xml, /SQL · NOTIFY<br\/>one transaction/, "draw.io two-line edge label"); + } + for (const theme of ["light", "dark"]) { + assertValidVsdx(interop.diagramToVsdx(spec, { theme }), spec, `batch-b-arch/${theme}`); + const lucid = interop.diagramToLucid(spec, { theme }); + assertValidLucid(lucid, spec, `batch-b-arch/${theme}`); + const doc = JSON.parse(readZipEntries(lucid).get("document.json").toString("utf8")); + assert.ok(doc.pages[0].lines.some((l) => l.text?.[0]?.text.includes("
")), "Lucid two-line edge label"); + } + }); + + test("sequence frames (opt, nested loop, alt with else divider) + activation bars glued to messages (cimip-diagrams-b sequence)", () => { + const spec = CIMIP_B.sequence; + for (const theme of ["light", "dark", "adaptive"]) { + const xml = interop.diagramToDrawio(spec, { theme }); + assertValidDrawio(xml, spec, `batch-b-seq/${theme}`); + // Nested loop frame (f1) is parented inside outer opt frame (f0) + assert.match(xml, /id="frame-f1"[^>]*parent="frame-f0"/, "nested loop frame parented inside opt frame"); + assert.match(xml, /id="frame-tab-f0" value="opt"/); + assert.match(xml, /id="frame-tab-f1" value="loop"/); + assert.match(xml, /id="frame-tab-f2" value="alt"/); + assert.match(xml, /id="frame-div-f2-0"/); + assert.match(xml, /Rejected or timed out/); + } + for (const theme of ["light", "dark"]) { + assertValidVsdx(interop.diagramToVsdx(spec, { theme }), spec, `batch-b-seq/${theme}`); + const lucid = interop.diagramToLucid(spec, { theme }); + assertValidLucid(lucid, spec, `batch-b-seq/${theme}`); + const doc = JSON.parse(readZipEntries(lucid).get("document.json").toString("utf8")); + const loopFrame = doc.pages[0].shapes.find((s) => s.id === "frame_f1"); + assert.ok(loopFrame?.customData?.some((d) => d.key === "basalt_parent_frame" && d.value === "f0"), "Lucid nested frame parent metadata"); + } + }); + + test("crow's-foot cardinality + far keys through top and interior corridors (cimip-diagrams-b schema)", () => { + const spec = CIMIP_B.schema; + // All 11 foreign keys in cimip-diagrams-b schema are drawn (including the 2 far keys: approvals -> incidents and approvals -> users) + const scene = interop.measureDiagramHeadless(spec); + assert.equal(scene.edges.length, 11, "all 11 foreign keys including both far keys are routed"); + const farIncident = scene.edges.find((e) => e.from === "approvals" && e.to === "incidents"); + const farUsers = scene.edges.find((e) => e.from === "approvals" && e.to === "users"); + assert.ok(farIncident && farIncident.pts.length === 6, "approvals -> incidents routed as 6-point corridor polyline"); + assert.ok(farUsers && farUsers.pts.length === 6, "approvals -> users routed as 6-point corridor polyline"); + assert.deepEqual(farIncident.card, { from: "zero-or-many", to: "one" }); + assert.deepEqual(farUsers.card, { from: "zero-or-many", to: "zero-or-one" }); + + for (const theme of ["light", "dark", "adaptive"]) { + const xml = interop.diagramToDrawio(spec, { theme }); + assertValidDrawio(xml, spec, `batch-b-schema/${theme}`); + assert.match(xml, /startArrow=ERoneToMany/); + assert.match(xml, /startArrow=ERzeroToOne/); + assert.match(xml, /startArrow=ERzeroToMany/); + assert.match(xml, /endArrow=ERmandOne/); + assert.match(xml, /endArrow=ERzeroToOne/); + } + for (const theme of ["light", "dark"]) { + const vsdx = interop.diagramToVsdx(spec, { theme }); + assertValidVsdx(vsdx, spec, `batch-b-schema/${theme}`); + const page1 = readZipEntries(vsdx).get("visio/pages/page1.xml").toString("utf8"); + assert.match(page1, //); + assert.match(page1, //); + assert.match(page1, //); + assert.match(page1, //); + assert.match(page1, //); + + const lucid = interop.diagramToLucid(spec, { theme }); + assertValidLucid(lucid, spec, `batch-b-schema/${theme}`); + const doc = JSON.parse(readZipEntries(lucid).get("document.json").toString("utf8")); + const styles = new Set(doc.pages[0].lines.flatMap((l) => [l.endpoint1.style, l.endpoint2.style])); + for (const s of ["exactlyOne", "zeroOrOne", "oneOrMore", "zeroOrMore"]) { + assert.ok(styles.has(s), `Lucid schema includes ${s}`); + } + } + }); + + test("automatic layout (autoArchitecture, autoFlowchart, autoSchema, nestedArchitecture) placed via placeAutoDiagram", async () => { + // Unplaced auto spec without placement fails clearly + assert.throws(() => interop.diagramToDrawio(CIMIP_B.autoArchitecture), /placeAutoDiagram/i); + + const autoCases = [ + ["autoArchitecture", CIMIP_B.autoArchitecture], + ["autoFlowchart", CIMIP_B.autoFlowchart], + ["autoSchema", CIMIP_B.autoSchema], + ["nestedArchitecture", LAYOUT_FIXTURES.nestedArchitecture], + ]; + for (const [name, rawSpec] of autoCases) { + const placed = await interop.placeAutoDiagram(rawSpec); + assert.ok(Array.isArray(placed.placement) && placed.placement.length >= 1, `${name}: placement generated`); + const drawioA = interop.diagramToDrawio(placed); + const drawioB = interop.diagramToDrawio(placed); + assert.equal(sha256(drawioA), sha256(drawioB), `${name}: drawio deterministic`); + assertValidDrawio(drawioA, placed, `auto/${name}`); + assertValidVsdx(interop.diagramToVsdx(placed), placed, `auto/${name}`); + assertValidLucid(interop.diagramToLucid(placed), placed, `auto/${name}`); + } + }); + + test("frame header labels and else rows are sized to their words and never cut uncovered lifelines (B2)", () => { + const seq = CIMIP_B.sequence; + const scene = interop.measureDiagramHeadless(seq); + const pad = scene.pad; + const drawio = interop.diagramToDrawio(seq); + const vsdxPage = readZipEntries(interop.diagramToVsdx(seq)).get("visio/pages/page1.xml").toString("utf8"); + const lucidDoc = interop.diagramToLucidJson(seq); + const page = lucidDoc.pages[0]; + + // Check Lucid shapes: every frame_label_* and frame_else_* matches labelBox width (not full frame width) + // and never covers a lifeline x outside its scene labelBox. + const lifelineXs = scene.lifelines.map((l) => l.x + pad); + for (const f of scene.frames) { + if (f.label && f.labelBox) { + const s = page.shapes.find((x) => x.id === `frame_label_${f.id}`); + assert.ok(s, `Lucid frame_label_${f.id} present`); + assert.ok(s.boundingBox.w < f.box.w - 40, `frame_label_${f.id} (${s.boundingBox.w}px) must be sized to words, not full frame (${f.box.w}px)`); + assert.ok(Math.abs(s.boundingBox.w - f.labelBox.w) <= 0.5, `Lucid frame_label_${f.id} matches labelBox width`); + assert.match(s.text, /font-weight:\s*500/, `Lucid frame_label_${f.id} uses weight 500`); + for (const lx of lifelineXs) { + const inExport = lx >= s.boundingBox.x && lx <= s.boundingBox.x + s.boundingBox.w; + const inScene = lx >= f.labelBox.x + pad && lx <= f.labelBox.x + pad + f.labelBox.w; + assert.equal(inExport, inScene, `Lucid frame_label_${f.id} lifeline x=${lx} coverage matches Basalt label rect`); + } + // Check draw.io frame-label-* geometry & weight + const mDrawio = drawio.match(new RegExp(`id="frame-label-${f.id}"[^>]*value="([^"]*)"[^>]*>\\s*]*width="([\\d.]+)"`)); + assert.ok(mDrawio, `draw.io frame-label-${f.id} present`); + assert.match(mDrawio[1], /font-weight:500/, `draw.io frame-label-${f.id} uses weight 500`); + assert.ok(Math.abs(Number(mDrawio[2]) - f.labelBox.w) <= 0.5, `draw.io frame-label-${f.id} matches labelBox width`); + // Check Visio FrameLabel_* width + const mVsdx = vsdxPage.match(new RegExp(`NameU="FrameLabel_${f.id}"[\\s\\S]*? { + if (!div.labelBox) return; + const s = page.shapes.find((x) => x.id === `frame_else_${f.id}_${k}`); + assert.ok(s, `Lucid frame_else_${f.id}_${k} present`); + assert.ok(s.boundingBox.w < f.box.w - 40, `frame_else_${f.id}_${k} (${s.boundingBox.w}px) must be sized to words, not full frame (${f.box.w}px)`); + for (const lx of lifelineXs) { + const inExport = lx >= s.boundingBox.x && lx <= s.boundingBox.x + s.boundingBox.w; + const inScene = lx >= div.labelBox.x + pad && lx <= div.labelBox.x + pad + div.labelBox.w; + assert.equal(inExport, inScene, `Lucid frame_else_${f.id}_${k} lifeline x=${lx} coverage matches Basalt label rect`); + } + const mDrawio = drawio.match(new RegExp(`id="frame-else-${f.id}-${k}"[^>]*>\\s*]*width="([\\d.]+)"`)); + assert.ok(mDrawio, `draw.io frame-else-${f.id}-${k} present`); + assert.ok(Math.abs(Number(mDrawio[1]) - div.labelBox.w) <= 0.5, `draw.io frame-else-${f.id}-${k} matches labelBox width`); + const mVsdx = vsdxPage.match(new RegExp(`NameU="FrameElse_${f.id}_${k}"[\\s\\S]*? x.id === "frame_tab_f0"); + assert.match(tab.text, /font-weight:\s*600/, "Lucid frame tab uses weight 600"); + }); + + test("headless auto-layout picks the first direction whose minimum width fits target width (Polish 2)", async () => { + const placed = await interop.placeAutoDiagram(CIMIP_B.autoArchitecture); + const at1104 = interop.measureDiagramHeadless(placed, { width: 1104 }); + const at1800 = interop.measureDiagramHeadless(placed, { width: 1800 }); + const cols1104 = Math.max(...at1104.nodes.map((n) => n.col)); + const cols1800 = Math.max(...at1800.nodes.map((n) => n.col)); + assert.ok(cols1104 < cols1800, `autoArchitecture at 1104px takes down (${cols1104} cols) while at 1800px takes right (${cols1800} cols)`); + }); + + test("measuredBy engine metadata is written across draw.io (XSD-valid), Visio Creator, and every Lucid node", () => { + const engine = "Chromium 146.0.7680.16, darwin, Basalt 0.1.0"; + const xml = interop.diagramToDrawio(CIMIP.architecture, { measuredBy: engine }); + assertValidDrawio(xml, CIMIP.architecture, "metadata-drawio"); + assert.match(xml, //); + + const vsdx = interop.diagramToVsdx(CIMIP.architecture, { measuredBy: engine }); + assertValidVsdx(vsdx, CIMIP.architecture, "metadata-vsdx"); + assert.match(readZipEntries(vsdx).get("visio/document.xml").toString("utf8"), /Basalt Diagram Exporter \(Chromium 146\.0\.7680\.16, darwin, Basalt 0\.1\.0\)<\/Creator>/); + + const lucid = interop.diagramToLucid(CIMIP.architecture, { measuredBy: engine }); + assertValidLucid(lucid, CIMIP.architecture, "metadata-lucid"); + const doc = JSON.parse(readZipEntries(lucid).get("document.json").toString("utf8")); + const nodeShapes = doc.pages[0].shapes.filter((s) => s.id.startsWith("node_")); + assert.ok(nodeShapes.length > 0); + for (const s of nodeShapes) { + assert.ok(s.customData?.some((d) => d.key === "basalt_measured_by" && d.value === engine), `Lucid ${s.id} carries basalt_measured_by`); + } + }); +}); + +describe("service marks embedding policy (architecture, data-flow steps, sequence participants)", () => { + const skillMarks = JSON.parse(fs.readFileSync(path.join(repo, "tools", "html-skill", "src", "marks.json"), "utf8")).marks; + const resolveMark = (id, theme) => (theme === "dark" ? skillMarks[id]?.onDark ?? skillMarks[id]?.onLight : skillMarks[id]?.onLight); + + test("isBundledMarkEmbeddable matches packages/react/marks/manifest.json for all 104 marks", () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pkg, "marks", "manifest.json"), "utf8")); + const allowedOwners = new Set(["Amazon Web Services, Inc.", "Microsoft Corporation", "Google LLC", "The Linux Foundation"]); + assert.equal(manifest.marks.length, 104); + for (const mk of manifest.marks) { + const expected = !mk.unofficial && allowedOwners.has(mk.owner); + assert.equal(interop.isBundledMarkEmbeddable(mk.id), expected, `mark policy mismatch for ${mk.id} (${mk.owner}, unofficial=${Boolean(mk.unofficial)})`); + } + }); + + test("default omits marks; marks='embed' includes official allowed marks and leaves out unofficial/restricted ones", () => { + const spec = { + type: "architecture", + title: "Marks test", + summary: "Test allowed vs disallowed marks.", + nodes: [ + { id: "ecs", name: "ECS service", col: 1, row: 1, mark: "aws-ecs-service" }, + { id: "k8s", name: "Kubernetes", col: 2, row: 1, mark: "kubernetes" }, + { id: "db", name: "Database", col: 3, row: 1, mark: "aws-database" }, + { id: "br", name: "Bedrock", col: 4, row: 1, mark: "aws-bedrock" }, + { id: "gh", name: "GitHub", col: 5, row: 1, mark: "github" }, + ], + edges: [ + { from: "ecs", to: "k8s" }, + { from: "k8s", to: "db" }, + { from: "db", to: "br" }, + { from: "br", to: "gh" }, + ], + }; + + const drawioOmit = interop.diagramToDrawio(spec, { resolveMark }); + assert.doesNotMatch(drawioOmit, /id="mark-/); + assert.equal([...readZipEntries(interop.diagramToVsdx(spec, { resolveMark })).keys()].filter((k) => k.startsWith("visio/media/")).length, 0); + assert.equal([...readZipEntries(interop.diagramToLucid(spec, { resolveMark })).keys()].filter((k) => k.startsWith("images/")).length, 0); + + const drawioEmbed = interop.diagramToDrawio(spec, { marks: "embed", resolveMark }); + assertValidDrawio(drawioEmbed, spec, "marks-embed"); + assert.match(drawioEmbed, /id="mark-ecs"/); + assert.match(drawioEmbed, /id="mark-k8s"/); + assert.match(drawioEmbed, /id="mark-db"/); + assert.doesNotMatch(drawioEmbed, /id="mark-br"/); + assert.doesNotMatch(drawioEmbed, /id="mark-gh"/); + + const drawioAdaptive = interop.diagramToDrawio(spec, { theme: "adaptive", marks: "embed", resolveMark }); + assertValidDrawio(drawioAdaptive, spec, "marks-embed-adaptive"); + assert.match(drawioAdaptive, /prefers-color-scheme%3Adark/, "adaptive draw.io embeds dual light/dark mark form"); + + const vsdxEmbed = readZipEntries(interop.diagramToVsdx(spec, { marks: "embed", resolveMark })); + assert.equal([...vsdxEmbed.keys()].filter((k) => k.startsWith("visio/media/")).length, 3); + assert.ok(vsdxEmbed.has("visio/pages/_rels/page1.xml.rels")); + assert.ok(interop.bundledMarkAttribution("kubernetes")?.includes("Apache-2.0")); + assert.match(vsdxEmbed.get("visio/document.xml").toString("utf8"), /Apache-2\.0/, "Kubernetes attribution in Visio document.xml"); + + const lucidEmbed = readZipEntries(interop.diagramToLucid(spec, { marks: "embed", resolveMark })); + assert.equal([...lucidEmbed.keys()].filter((k) => k.startsWith("images/")).length, 3); + const lucidDoc = JSON.parse(lucidEmbed.get("document.json").toString("utf8")); + const k8sMarkShape = lucidDoc.pages[0].shapes.find((s) => s.id === "mark_k8s"); + assert.ok(k8sMarkShape?.customData?.some((d) => d.key === "attribution" && d.value.includes("Apache-2.0")), "Kubernetes attribution in Lucid customData"); + }); + + test("marks on data-flow steps and sequence participants embed cleanly across all 3 formats", () => { + const dfSpec = { + type: "data-flow", + title: "Steps with marks", + summary: "Data-flow steps carrying allowed and restricted marks.", + lanes: [{ id: "aws", label: "AWS" }, { id: "k8s", label: "Cluster" }], + nodes: [ + { id: "s1", lane: "aws", name: "ECS task", col: 1, mark: "aws-ecs-service" }, + { id: "s2", lane: "k8s", name: "Kubernetes pod", col: 2, mark: "kubernetes" }, + { id: "s3", lane: "k8s", name: "GitHub hook", col: 3, mark: "github" }, + ], + edges: [{ from: "s1", to: "s2", kind: "main" }, { from: "s2", to: "s3" }], + }; + const dfDrawio = interop.diagramToDrawio(dfSpec, { marks: "embed", resolveMark }); + assertValidDrawio(dfDrawio, dfSpec, "df-marks"); + assert.match(dfDrawio, /id="mark-s1"/); + assert.match(dfDrawio, /id="mark-s2"/); + assert.doesNotMatch(dfDrawio, /id="mark-s3"/); + assert.equal([...readZipEntries(interop.diagramToVsdx(dfSpec, { marks: "embed", resolveMark })).keys()].filter((k) => k.startsWith("visio/media/")).length, 2); + assert.equal([...readZipEntries(interop.diagramToLucid(dfSpec, { marks: "embed", resolveMark })).keys()].filter((k) => k.startsWith("images/")).length, 2); + + const seqSpec = { + type: "sequence", + title: "Participants with marks", + summary: "Sequence participants carrying allowed and restricted marks.", + participants: [ + { id: "svc", kind: "ECS", name: "ECS service", focal: true, mark: "aws-ecs-service" }, + { id: "db", kind: "Database", name: "Database", mark: "aws-database" }, + { id: "gh", kind: "Git", name: "GitHub", mark: "github" }, + ], + steps: [ + { from: "svc", to: "db", kind: "main", label: "SELECT 1" }, + { from: "db", to: "gh", label: "webhook" }, + ], + }; + const seqDrawio = interop.diagramToDrawio(seqSpec, { marks: "embed", resolveMark }); + assertValidDrawio(seqDrawio, seqSpec, "seq-marks"); + assert.match(seqDrawio, /id="mark-svc"/); + assert.match(seqDrawio, /id="mark-db"/); + assert.doesNotMatch(seqDrawio, /id="mark-gh"/); + assert.match(seqDrawio, /padding-left:24px;padding-right:24px;/, "centered participant reserves 24px on both sides"); + assert.equal([...readZipEntries(interop.diagramToVsdx(seqSpec, { marks: "embed", resolveMark })).keys()].filter((k) => k.startsWith("visio/media/")).length, 2); + assert.equal([...readZipEntries(interop.diagramToLucid(seqSpec, { marks: "embed", resolveMark })).keys()].filter((k) => k.startsWith("images/")).length, 2); + }); +}); + +describe("basalt-diagram-export CLI (Node-only --headless mode)", () => { + test("exports JSON map, single JSON, Batch B auto-layout, and HTML script[data-diagram] deterministically", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "basalt-interop-cli-")); + try { + // 1. Multi-diagram JSON under two different TZ and LC_ALL environments + const outA = path.join(dir, "a"); + const outB = path.join(dir, "b"); + const r1 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--headless", "--to", "drawio,vsdx,lucid,lucid-json", "--out", outA], { + encoding: "utf8", + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + }); + assert.equal(r1.status, 0, r1.stderr); + assert.match(r1.stderr, /approximate/i, "--headless notes approximate geometry on stderr"); + assert.match( + r1.stdout, + /architecture\.lucid \(\d+ bytes\) — Lucid REST API only \(POST https:\/\/api\.lucid\.co\/v1\/documents with a token, type x-application\/vnd\.lucid\.standardImport; use \.vsdx to import through Lucid's own screen\)/, + ".lucid output line explains REST API only and points UI users to .vsdx", + ); + const rHelp = spawnSync(process.execPath, [CLI, "--help"], { encoding: "utf8" }); + assert.equal(rHelp.status, 0, rHelp.stderr); + assert.match(rHelp.stdout, /POST https:\/\/api\.lucid\.co\/v1\/documents/, "--help documents Lucid REST API endpoint"); + assert.match(rHelp.stdout, /x-application\/vnd\.lucid\.standardImport/, "--help documents Lucid Standard Import media type"); + assert.match(rHelp.stdout, /use \.vsdx/i, "--help points Lucid UI imports to .vsdx"); + const r2 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--headless", "--to", "drawio,vsdx,lucid,lucid-json", "--out", outB], { + encoding: "utf8", + env: { ...process.env, TZ: "Asia/Kolkata", LC_ALL: "de_DE.UTF-8" }, + }); + assert.equal(r2.status, 0, r2.stderr); + + const expectedStems = ["architecture", "flowchart", "data-flow", "sequence", "schema"]; + for (const stem of expectedStems) { + for (const ext of [".drawio", ".vsdx", ".lucid", ".lucid.json"]) { + const fa = fs.readFileSync(path.join(outA, stem + ext)); + const fb = fs.readFileSync(path.join(outB, stem + ext)); + assert.equal(sha256(fa), sha256(fb), `CLI repeat deterministic across TZ/LC_ALL: ${stem}${ext}`); + } + } + assert.match(fs.readFileSync(path.join(outA, "architecture.drawio"), "utf8"), /Basalt \d+\.\d+\.\d+ headless \(approximate\)/); + + // 1b. Symlink execution (as npm installs node_modules/.bin/basalt-diagram-export) + const symLink = path.join(dir, "basalt-diagram-export-link"); + fs.symlinkSync(CLI, symLink); + const symOut = path.join(dir, "from-symlink"); + const singleJson = path.join(dir, "one.json"); + fs.writeFileSync(singleJson, JSON.stringify(CIMIP.flowchart)); + const rSym = spawnSync(process.execPath, [symLink, singleJson, "--headless", "--to", "vsdx", "--out", symOut], { encoding: "utf8" }); + assert.equal(rSym.status, 0, rSym.stderr); + assert.ok(fs.existsSync(path.join(symOut, "one.vsdx")), "symlinked CLI wrote output file"); + + // 1c. Batch B fixtures (crow's foot, frames, nested groups, and layout="auto") via CLI --headless + const batchBIn = path.join(dir, "batch-b.json"); + fs.writeFileSync(batchBIn, JSON.stringify({ + architecture: CIMIP_B.architecture, + sequence: CIMIP_B.sequence, + schema: CIMIP_B.schema, + autoArchitecture: CIMIP_B.autoArchitecture, + autoFlowchart: CIMIP_B.autoFlowchart, + autoSchema: CIMIP_B.autoSchema, + })); + const batchBOut = path.join(dir, "batch-b-out"); + const rB = spawnSync(process.execPath, [CLI, batchBIn, "--headless", "--to", "drawio,vsdx,lucid", "--out", batchBOut], { encoding: "utf8" }); + assert.equal(rB.status, 0, rB.stderr); + for (const [key, stem] of [ + ["architecture", "architecture"], + ["sequence", "sequence"], + ["schema", "schema"], + ["autoArchitecture", "auto-architecture"], + ["autoFlowchart", "auto-flowchart"], + ["autoSchema", "auto-schema"], + ]) { + assertValidDrawio(fs.readFileSync(path.join(batchBOut, `${stem}.drawio`), "utf8"), CIMIP_B[key], `cli-batch-b/${key}`); + assertValidVsdx(fs.readFileSync(path.join(batchBOut, `${stem}.vsdx`)), CIMIP_B[key], `cli-batch-b/${key}`); + assertValidLucid(fs.readFileSync(path.join(batchBOut, `${stem}.lucid`)), CIMIP_B[key], `cli-batch-b/${key}`); + } + + // 2. HTML input with a real diagram + decoys inside comment and textarea + const decoy = JSON.stringify({ type: "architecture", title: "Decoy", summary: "No", nodes: [{ id: "x", name: "X", col: 1, row: 1 }], edges: [] }); + const htmlPath = path.join(dir, "page.html"); + fs.writeFileSync(htmlPath, ` + + +
+ `); + const htmlOut = path.join(dir, "from-html"); + const r3 = spawnSync(process.execPath, [CLI, htmlPath, "--headless", "--to", "drawio,vsdx", "--theme", "adaptive", "--out", htmlOut], { encoding: "utf8" }); + assert.equal(r3.status, 0, r3.stderr); + assert.deepEqual(fs.readdirSync(htmlOut).sort(), ["arch.drawio", "arch.vsdx"]); + assertValidDrawio(fs.readFileSync(path.join(htmlOut, "arch.drawio"), "utf8"), CIMIP.architecture, "cli-html-adaptive"); + assertValidVsdx(fs.readFileSync(path.join(htmlOut, "arch.vsdx")), CIMIP.architecture, "cli-html-vsdx"); + + // 3. Single file --out path + mismatched extension check + const exactOut = path.join(dir, "exact.drawio"); + const r4 = spawnSync(process.execPath, [CLI, singleJson, "--headless", "--to", "drawio", "--out", exactOut], { encoding: "utf8" }); + assert.equal(r4.status, 0, r4.stderr); + assert.ok(fs.existsSync(exactOut)); + + const mismatch = spawnSync(process.execPath, [CLI, singleJson, "--headless", "--to", "drawio", "--out", path.join(dir, "wrong.vsdx")], { encoding: "utf8" }); + assert.notEqual(mismatch.status, 0, "mismatched --out extension must fail"); + assert.match(mismatch.stderr, /extension does not match/i); + + // 4. Custom mark SVG file resolved relative to input file + warning when missing + fs.writeFileSync(path.join(dir, "logo.svg"), ``); + const customMarkSpec = { + type: "architecture", + title: "Custom marks", + summary: "Custom mark resolution.", + nodes: [ + { id: "ok", name: "Present", col: 1, row: 1, mark: { onLight: "logo.svg" } }, + { id: "miss", name: "Missing", col: 2, row: 1, mark: { onLight: "no-such.svg" } }, + ], + edges: [{ from: "ok", to: "miss" }], + }; + const customIn = path.join(dir, "custom.json"); + fs.writeFileSync(customIn, JSON.stringify(customMarkSpec)); + const customOut = path.join(dir, "custom-out"); + const rCustom = spawnSync(process.execPath, [CLI, customIn, "--headless", "--to", "drawio,vsdx", "--marks", "embed", "--out", customOut], { encoding: "utf8" }); + assert.equal(rCustom.status, 0, rCustom.stderr); + assert.match(rCustom.stderr, /warning: custom mark file "no-such\.svg" not found/i, "warns on missing custom mark file"); + const customDrawio = fs.readFileSync(path.join(customOut, "custom.drawio"), "utf8"); + assert.match(customDrawio, /id="mark-ok"/, "resolved custom SVG file embedded"); + assert.doesNotMatch(customDrawio, /id="mark-miss"/, "missing custom SVG skipped"); + + // 5. Flag validation errors + const bad = spawnSync(process.execPath, [CLI, singleJson, "--headless", "--to", "bogus"], { encoding: "utf8" }); + assert.notEqual(bad.status, 0); + const conflict = spawnSync(process.execPath, [CLI, singleJson, "--browser", "--headless"], { encoding: "utf8" }); + assert.notEqual(conflict.status, 0); + assert.match(conflict.stderr, /cannot be used together/i); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("subpath isolation", () => { + test("@srasyndicate/basalt/diagram-interop stays outside the root index, loads elkjs lazily, and carries no client directive or React imports", async () => { + const root = await import(pathToFileURL(path.join(pkg, "dist", "index.js")).href); + for (const name of ["diagramToDrawio", "diagramToVsdx", "diagramToLucid", "diagramToLucidJson", "exportMeasuredDiagram", "placeAutoDiagram"]) { + assert.equal(name in root, false, `${name} must not be on the root index`); + assert.equal(typeof interop[name], "function", `${name} is exported from diagram-interop`); + } + const source = fs.readFileSync(path.join(pkg, "dist", "diagram-interop.js"), "utf8"); + assert.doesNotMatch(source, /^"use client";/, "diagram-interop.js must not carry \"use client\""); + assert.doesNotMatch(source, /\bfrom\s*"(react|react-dom|@base-ui|@phosphor-icons|cmdk|shiki)/, "diagram-interop.js imports no UI libraries"); + assert.doesNotMatch(source, /elkjs/, "diagram-interop.js never bundles elkjs inline"); + assert.match(source, /import\(["']\.\/diagram-layout\.js["']\)/, "placeAutoDiagram dynamically imports ./diagram-layout.js"); + }); +}); diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index dd9dd295..0dad096c 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -426,6 +426,12 @@ "useToast": 3211, "useWaitMark": 303 }, + "subpaths": { + "diagram-interop": { + "bytes": 138715, + "gzip": 39659 + } + }, "package": { "bytes": 948167, "gzip": 316004 diff --git a/packages/react/test/export-sizes.mjs b/packages/react/test/export-sizes.mjs index 435b35aa..6f25cb2c 100644 --- a/packages/react/test/export-sizes.mjs +++ b/packages/react/test/export-sizes.mjs @@ -78,12 +78,28 @@ async function pool(items, width, work) { return out; } +/** Subpath entries measured separately from the root index (dynamic imports stay on demand). */ +export async function measureSubpaths() { + const entries = [["diagram-interop", "./dist/diagram-interop.js"]]; + const out = {}; + for (const [name, entry] of entries) { + const result = await esbuild.build({ + stdin: { contents: `import * as S from "${entry}"; console.log(S);`, resolveDir: pkg, loader: "js" }, + bundle: true, minify: true, format: "esm", write: false, external, plugins: [onDemand], logLevel: "silent", + }); + const bytes = result.outputFiles[0].contents; + out[name] = { bytes: bytes.length, gzip: gzip(bytes) }; + } + return out; +} + /** The whole table, measured now. */ export async function measureAll({ width = 4 } = {}) { const names = await runtimeExports(); const sizes = await pool(names, width, measureExport); return { exports: Object.fromEntries(names.map((name, i) => [name, sizes[i].bytes])), + subpaths: await measureSubpaths(), package: await measurePackage(), styles: measureStyles(), }; @@ -96,6 +112,11 @@ export function diff(before, after) { const lines = []; const row = (label, a, b) => { if (a !== b) lines.push(` ${label.padEnd(34)} ${a === undefined ? "new" : a.toLocaleString("en")} -> ${b === undefined ? "gone" : b.toLocaleString("en")} bytes${a && b ? ` (${b > a ? "+" : ""}${(((b - a) / a) * 100).toFixed(1)}%)` : ""}`); }; for (const name of new Set([...Object.keys(before.exports ?? {}), ...Object.keys(after.exports)])) row(name, before.exports?.[name], after.exports[name]); + for (const name of new Set([...Object.keys(before.subpaths ?? {}), ...Object.keys(after.subpaths ?? {})])) { + for (const key of ["bytes", "gzip"]) { + row(`subpath ${name}, ${key === "gzip" ? "gzipped" : "minified"}`, before.subpaths?.[name]?.[key], after.subpaths?.[name]?.[key]); + } + } for (const key of ["bytes", "gzip"]) { row(`whole package, up front, ${key === "gzip" ? "gzipped" : "minified"}`, before.package?.[key], after.package[key]); row(`styles.css, ${key === "gzip" ? "gzipped" : "minified as shipped"}`, before.styles?.[key], after.styles[key]); diff --git a/packages/react/test/fixtures/mxfile-1.0.xsd b/packages/react/test/fixtures/mxfile-1.0.xsd new file mode 100644 index 00000000..53277111 --- /dev/null +++ b/packages/react/test/fixtures/mxfile-1.0.xsd @@ -0,0 +1,671 @@ + + + + + + + + + + + + + + Root element of a draw.io file. Contains one or more diagram pages. + A minimal valid file has one diagram with at least the two structural + mxCell elements (id="0" and id="1"). + + + + + + + + + Host application identifier (e.g. "app.diagrams.net", "Electron"). + + + + + + ISO 8601 timestamp of last modification (e.g. "2024-01-15T10:30:00.000Z"). + + + + + + User agent or tool identifier that created the file. + + + + + + draw.io application version (e.g. "24.7.6"). + + + + + + Entity tag for caching and synchronization. + + + + + + Storage backend type. Common values: "device", "google", "dropbox", "onedrive", "github", "gitlab", "browser". + + + + + + If "true", diagram content is deflate-compressed and Base64-encoded. For AI generation, always use "false" (uncompressed XML). + + + + + + Number of diagram pages. Informational only; the actual count is determined by the number of diagram child elements. + + + + + + + + + + + Represents a single page/tab in the diagram. Each diagram has a unique + id and an optional display name. Contains either an mxGraphModel element + (uncompressed) or Base64-encoded compressed text content. + + + + + + + + + + Unique identifier for this diagram page. Must be unique within the file. + + + + + + Display name shown in the page tab. Defaults to "Page-N" if omitted. + + + + + + + + + + + The graph model containing all cells (shapes, edges, layers) and + canvas configuration. The dx/dy attributes control the scroll offset, + while pageWidth/pageHeight define the page dimensions. + + + + + + + + + + Horizontal scroll offset in pixels. Typical default: 0 or based on content. + + + + + Vertical scroll offset in pixels. + + + + + + + Page width in pixels. Common values: 850 (letter), 1169 (A4 landscape), 827 (A4 portrait). + + + + + Page height in pixels. Common values: 1100 (letter), 827 (A4 landscape), 1169 (A4 portrait). + + + + + Page scale factor. Default: 1. + + + + + + + Show grid. 1=visible, 0=hidden. Default: 1. + + + + + Grid cell size in pixels. Default: 10. + + + + + + + Enable alignment guides. Default: 1. + + + + + Show tooltips on hover. Default: 1. + + + + + Enable connection handles. Default: 1. + + + + + Show directional arrows on edges. Default: 1. + + + + + Enable collapse/expand of containers. Default: 1. + + + + + Show page boundaries. Default: 1. + + + + + Enable MathJax/LaTeX rendering in labels. Default: 0. + + + + + Global shadow for all shapes. Default: 0. Can be overridden per cell via style. + + + + + + + Canvas background color as hex (e.g. "#FFFFFF") or "none" for transparent. + + + + + JSON object for background image: {"src":"url","width":w,"height":h}. + + + + + + + Controls color adaptation for light/dark mode. Values: "auto", "simple", "none", "default". + + + + + + + + + + + Container for all cells in the diagram. Must contain at least two + structural mxCell elements: + 1. Root container: id="0", no parent attribute + 2. Default layer: id="1", parent="0" + + All visible diagram elements (shapes, edges) must have parent="1" + (or the id of another layer/group). + + Additional layers can be added as mxCell elements with parent="0". + Elements can be wrapped in UserObject/object for custom metadata. + + + + + + + + + + + + + + + + + + Universal cell element representing a vertex (shape), edge (connector), + or layer/group. The role is determined by the vertex/edge attributes. + + Cell roles: + - Root container: id="0", no parent, no vertex/edge + - Layer: parent="0", no vertex/edge (value = layer name) + - Vertex (shape): vertex="1", parent = layer or group id + - Edge (connector): edge="1", parent = layer or group id, + source/target = connected vertex ids + - Group/container: vertex="1" with child cells referencing it as parent + + Style string format: semicolon-separated key=value pairs. + Shape name can appear as first token without key (e.g. "ellipse;..."). + Example: "rounded=1;whiteSpace=wrap;html=1;fillColor=#DAE8FC;" + See style-reference.md for complete style documentation. + + + + + + + + + + Unique cell identifier within the diagram. Required for top-level mxCell, optional when nested in UserObject/object. Must be unique across all cells in the diagram. + + + + + ID of the parent cell. "0" for layers, "1" (or a layer/group id) for diagram elements. Omitted only for the root container (id="0"). + + + + + + + Cell label text. Can contain plain text or HTML (when style includes html=1). HTML labels support basic formatting: b, i, u, br, p, div, table, hr, font, span with inline styles. + + + + + + Style string: semicolon-separated key=value pairs defining visual appearance. + Format: "[shapeName;]key1=value1;key2=value2;..." + Example vertex: "rounded=1;whiteSpace=wrap;html=1;fillColor=#DAE8FC;" + Example edge: "edgeStyle=orthogonalEdgeStyle;endArrow=classic;html=1;" + See style-reference.md for all properties and values. + + + + + + + + Set to "1" for shape/vertex cells. Mutually exclusive with edge="1". + + + + + Set to "1" for connector/edge cells. Mutually exclusive with vertex="1". Should have source and/or target attributes. + + + + + Whether the cell can be connected to. Default: "1" for vertices, "0" for edges. Set to "0" to prevent connections. + + + + + + + ID of the source vertex for edges. Must reference a valid vertex id in the same diagram. + + + + + ID of the target vertex for edges. Must reference a valid vertex id in the same diagram. + + + + + + + Whether the container/group is collapsed. Only meaningful for container cells. + + + + + Whether the cell is visible. "0" = hidden, "1" = visible. Default: "1". + + + + + + + + + + + Wrapper element for cells with custom metadata attributes. + The UserObject/object carries the id and any custom key-value + attributes, while the nested mxCell contains the visual definition. + + Use "object" or "UserObject" interchangeably (both are supported). + The "label" attribute replaces mxCell's "value" for the display text. + + Custom attributes appear in the "Edit Data" dialog in draw.io and + can be used for data-driven diagrams, linking, and metadata. + + Example: + <UserObject id="3" label="Server" ip="192.168.1.1" status="active"> + <mxCell style="..." vertex="1" parent="1"> + <mxGeometry x="100" y="100" width="120" height="60" as="geometry"/> + </mxCell> + </UserObject> + + + + + + + + + + Unique identifier (same role as mxCell id). The nested mxCell should NOT have its own id. + + + + + Display label text (replaces mxCell value). Supports HTML when style includes html=1. + + + + + Hyperlink URL. Opens when the cell is clicked in the viewer. + + + + + Space-separated tags for filtering/categorization. + + + + + Tooltip text displayed on hover. + + + + + Enable placeholder substitution in labels. When "1", %attribute% in the label is replaced with attribute values. + + + + + + + + + + + + + + Defines the geometry (position, size, control points) for a cell. + + For vertices: + - x, y: absolute position of top-left corner (relative to parent) + - width, height: size in pixels + + For edges: + - When relative="1": x is position along edge (0.0=start, 1.0=end, + -1.0=before start), y is perpendicular offset in pixels + - Contains optional mxPoint children for source/target points + - Contains optional Array element with waypoints + + For edge labels (edge cells with relative="1"): + - x: position along edge (-1 to 1, where 0 = center) + - y: perpendicular offset in pixels + - mxPoint with as="offset" for additional pixel offset + + + + + + + + + + + + + + + + For vertices: x-coordinate of top-left corner (pixels, relative to parent). + For edges with relative="1": position along edge (-1.0 to 1.0, where 0 = center). + + + + + + + For vertices: y-coordinate of top-left corner (pixels, relative to parent). + For edges with relative="1": perpendicular offset in pixels. + + + + + + + + Width in pixels. Required for vertices. Typical values: 80-200. + + + + + Height in pixels. Required for vertices. Typical values: 40-120. + + + + + + + + When "1", x/y are relative coordinates (not absolute pixels). + Required for edge geometry. x ranges from -1.0 to 1.0 (position along edge), + y is perpendicular pixel offset. + + + + + + + + Always "geometry". Identifies this element as the cell's geometry property. + + + + + + + + + + + A 2D point used for edge endpoints or label offsets. + + The "as" attribute determines the role: + - "sourcePoint": starting point of an unconnected edge + - "targetPoint": ending point of an unconnected edge + - "offset": pixel offset for label positioning + - (no as): waypoint within an Array element + + + + + X coordinate in pixels. + + + + + Y coordinate in pixels. + + + + + + Point role: "sourcePoint", "targetPoint", or "offset". + + + + + + + + + + + Array of mxPoint elements representing intermediate waypoints + for edge routing. Points are in absolute coordinates and define + the path the edge follows between source and target. + + + + + + + + + Always "points". Identifies this array as the edge's waypoint list. + + + + + + + + + + + Stores alternate bounds for collapsible containers (swimlanes). + When a container is collapsed/expanded, the geometry swaps between + the normal bounds and these alternate bounds. Always appears with + as="alternateBounds" inside mxGeometry. + + + + + X coordinate of the alternate bounds. + + + + + Y coordinate of the alternate bounds. + + + + + Width of the alternate bounds. + + + + + Height of the alternate bounds. + + + + + Always "alternateBounds". Identifies this as the cell's alternate geometry. + + + + + + + + + + + + Boolean as integer: "0" = false, "1" = true. This is the standard boolean format in draw.io. + + + + + + + + + + + Boolean as string: "true" or "false". Used only for mxfile-level attributes like "compressed". + + + + + + + + + + + + Color value. Accepted formats: + - Hex with hash: "#RRGGBB" (e.g. "#FF0000") or "#RRGGBBAA" (with alpha) + - "none" for transparent/no color + - "default" to use the current theme's default color + + + + + + + + + + + Valid roles for mxPoint: sourcePoint, targetPoint, or offset. + + + + + + + + + diff --git a/packages/react/test/fixtures/runtask-jog-proof.vsdx b/packages/react/test/fixtures/runtask-jog-proof.vsdx new file mode 100644 index 00000000..9c383cf9 Binary files /dev/null and b/packages/react/test/fixtures/runtask-jog-proof.vsdx differ diff --git a/packages/react/test/support-diagram-interop.mjs b/packages/react/test/support-diagram-interop.mjs new file mode 100644 index 00000000..b04046fa --- /dev/null +++ b/packages/react/test/support-diagram-interop.mjs @@ -0,0 +1,661 @@ +// Shared pure-Node validators for @srasyndicate/basalt/diagram-interop tests (DECISIONS 311, 314, 324, 327). +// Imports no browser or Playwright modules so Node-only tests stay strictly browser-free. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import crypto from "node:crypto"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import zlib from "node:zlib"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +export const pkg = path.resolve(here, ".."); +export const repo = path.resolve(pkg, "..", ".."); +export const XSD = path.join(here, "fixtures", "mxfile-1.0.xsd"); +export const CLI = path.join(pkg, "bin", "basalt-diagram-export.mjs"); + +export const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex"); + +export function xmllint(xml, schema = null) { + const args = ["--noout"]; + if (schema) args.push("--schema", schema); + args.push("-"); + const res = spawnSync("xmllint", args, { input: xml, encoding: "utf8" }); + return { ok: res.status === 0, stderr: (res.stderr || "").trim() }; +} + +/** Minimal store-mode ZIP parser (verifies local/central headers, CRC-32, and fixed 1980-01-01 timestamps). */ +export function readZipEntries(bytes) { + const buf = Buffer.from(bytes); + let eocd = -1; + for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) { + if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; } + } + assert.ok(eocd >= 0, "ZIP EOCD signature missing"); + const entryCount = buf.readUInt16LE(eocd + 10); + const cdOffset = buf.readUInt32LE(eocd + 16); + const entries = new Map(); + let p = cdOffset; + for (let i = 0; i < entryCount; i++) { + assert.equal(buf.readUInt32LE(p), 0x02014b50, `central dir sig at entry ${i}`); + const method = buf.readUInt16LE(p + 10); + const modTime = buf.readUInt16LE(p + 12); + const modDate = buf.readUInt16LE(p + 14); + const compSize = buf.readUInt32LE(p + 20); + const uncompSize = buf.readUInt32LE(p + 24); + const nameLen = buf.readUInt16LE(p + 28); + const extraLen = buf.readUInt16LE(p + 30); + const commentLen = buf.readUInt16LE(p + 32); + const localOff = buf.readUInt32LE(p + 42); + const name = buf.subarray(p + 46, p + 46 + nameLen).toString("utf8"); + assert.equal(method, 0, `${name}: expected store method 0`); + assert.equal(modTime, 0x0000, `${name}: expected fixed DOS time 00:00:00`); + assert.equal(modDate, 0x0021, `${name}: expected fixed DOS date 1980-01-01`); + assert.equal(compSize, uncompSize, `${name}: store sizes must match`); + assert.equal(buf.readUInt32LE(localOff), 0x04034b50, `${name}: local header sig`); + const lNameLen = buf.readUInt16LE(localOff + 26); + const lExtraLen = buf.readUInt16LE(localOff + 28); + const dataStart = localOff + 30 + lNameLen + lExtraLen; + entries.set(name, buf.subarray(dataStart, dataStart + uncompSize)); + p += 46 + nameLen + extraLen + commentLen; + } + return entries; +} + +/** Reads any ZIP's entries (stored or deflated, any timestamps): for fixtures written by other tools, such as the RunTask proof. */ +export function readForeignZipEntries(bytes) { + const buf = Buffer.from(bytes); + let eocd = -1; + for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) { + if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; } + } + assert.ok(eocd >= 0, "ZIP EOCD signature missing"); + const entries = new Map(); + let p = buf.readUInt32LE(eocd + 16); + for (let i = 0, n = buf.readUInt16LE(eocd + 10); i < n; i++) { + const method = buf.readUInt16LE(p + 10); + const compSize = buf.readUInt32LE(p + 20); + const nameLen = buf.readUInt16LE(p + 28); + const localOff = buf.readUInt32LE(p + 42); + const name = buf.subarray(p + 46, p + 46 + nameLen).toString("utf8"); + const dataStart = localOff + 30 + buf.readUInt16LE(localOff + 26) + buf.readUInt16LE(localOff + 28); + const raw = buf.subarray(dataStart, dataStart + compSize); + assert.ok(method === 0 || method === 8, `${name}: method ${method}`); + entries.set(name, method === 8 ? zlib.inflateRawSync(raw) : raw); + p += 46 + nameLen + buf.readUInt16LE(p + 30) + buf.readUInt16LE(p + 32); + } + return entries; +} + +function walkSequenceSteps(steps, visit) { + for (const s of steps ?? []) { + if (!s || typeof s !== "object") continue; + visit(s); + if ("frame" in s) { + if (Array.isArray(s.branches)) { + for (const br of s.branches) walkSequenceSteps(br.steps, visit); + } else if (Array.isArray(s.steps)) { + walkSequenceSteps(s.steps, visit); + } + } + } +} + +export function expectedFrameCount(spec) { + if (spec.type !== "sequence") return 0; + let count = 0; + walkSequenceSteps(spec.steps, (s) => { if ("frame" in s) count++; }); + return count; +} + +export function expectedDividerCount(spec) { + if (spec.type !== "sequence") return 0; + let count = 0; + walkSequenceSteps(spec.steps, (s) => { + if ("frame" in s && Array.isArray(s.branches) && s.branches.length > 1) { + count += s.branches.length - 1; + } + }); + return count; +} + +export function expectedBarCount(spec) { + if (spec.type !== "sequence") return 0; + let count = 0; + walkSequenceSteps(spec.steps, (s) => { + if (!("band" in s) && !("frame" in s) && s.activate === true) count++; + }); + return count; +} + +export function expectedEdgeCount(spec) { + if (spec.type === "sequence") { + let count = 0; + walkSequenceSteps(spec.steps, (s) => { + if (!("band" in s) && !("frame" in s)) count++; + }); + return count; + } + if (spec.type === "schema") { + const byName = new Map(spec.tables.map((t) => [t.name, t])); + let n = 0; + for (const t of spec.tables) { + for (const c of t.columns) { + if (!c.references) continue; + const [tbl, col] = c.references.split("."); + const target = byName.get(tbl); + if (target && target.columns.some((x) => x.name === col)) n++; + } + } + return n; + } + return spec.edges.length; +} + +export function expectedLabelCount(spec) { + if (spec.type === "sequence") return expectedEdgeCount(spec); + if (spec.type === "schema") return 0; + return spec.edges.filter((e) => Boolean(e.label)).length; +} + +const schemaHasCardinality = (spec) => + spec.type === "schema" && spec.tables.some((t) => t.columns.some((c) => Boolean(c.cardinality))); + +const DRAWIO_CARDS = new Set(["ERmandOne", "ERzeroToOne", "ERoneToMany", "ERzeroToMany"]); +const VSDX_CARDS = new Set(["25", "28", "29", "30"]); +const LUCID_CARDS = new Set(["exactlyOne", "zeroOrOne", "oneOrMore", "zeroOrMore"]); + +/** Verifies every segment in `pts` is orthogonal and first/last segments are axis-aligned with `start` and `end`. */ +export function assertAxisAlignedRoute(pts, start, end, tol, label) { + assert.ok(pts.length >= 2, `${label}: at least 2 points`); + assert.ok(Math.abs(pts[0].x - start.x) <= tol && Math.abs(pts[0].y - start.y) <= tol, + `${label}: start (${pts[0].x},${pts[0].y}) != port (${start.x},${start.y}) [tol ${tol}]`); + const last = pts[pts.length - 1]; + assert.ok(Math.abs(last.x - end.x) <= tol && Math.abs(last.y - end.y) <= tol, + `${label}: end (${last.x},${last.y}) != port (${end.x},${end.y}) [tol ${tol}]`); + for (let i = 1; i < pts.length; i++) { + const dx = Math.abs(pts[i].x - pts[i - 1].x); + const dy = Math.abs(pts[i].y - pts[i - 1].y); + assert.ok(dx <= tol || dy <= tol, + `${label}: segment ${i - 1}->${i} (${pts[i - 1].x},${pts[i - 1].y})->(${pts[i].x},${pts[i].y}) is not axis-aligned (dx=${dx}, dy=${dy}, tol=${tol})`); + } +} + +/** Parses and validates draw.io XML structure, XSD conformance, glue, Batch B parts, and port axis-alignment. */ +export function assertValidDrawio(xml, spec, context) { + assert.ok(!xml.includes(" 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. The fix round after both reviews of 421348e8 sets them to the measured sizes again: core 38950 to 39600 (every room says all three forms, and a hung word's box grows by a short room's shortfall), search to 5700 (it places its top again on a resize and with the keyboard; an empty list holds no padding), command-list to 14700 (it keeps the taller of its two heights), notifications to 12950 (the bell's edge), pane to 1950 (the page column's room), chart to 34950 (the date line's reason), and code, diagram-zoom, filter, links, sheet, still-table, tab-bar and topbar each by under 150 bytes (the three forms of a room; the selection column's width however given). Merged with main at db0bc418 (#129 to #131), DECISIONS 336's caps are set to the measured sizes again: core 35800 to 38950 and its usage 3200 to 3650, toast 16200 to 16750, terminal to 12700 (13050 with the open items' ruling: both copy buttons draw their three glyphs once, so a refused copy shows the close with no markup written after), diagram-zoom 17600 to 17750 (its viewer's Close and Zoom out hung, and the foot's room). Raised in DECISIONS 336 (reserved room across every component, claude/reserved-room), each to its measured size: core 35550 to 38700 (the edge rule a ghost .btn hangs by at a head, its ring and touch hit area, the side insets by direction, the .panel-head and page section-head that hang their last button by themselves) and its usage 2950 to 3450 (how data-edge and --basalt-edge-room are written); search 4400 to 5200 (search.js, the held top), terminal 11950 to 12550 (the close glyph for a refused copy, the edge on both copies), links 2750 to 3300 (the first icon link hung, the card room, the 20px glyph), toast 16050 to 16650 (the 46px hit areas on touch), selection 1500 to 1650 and still-table 14650 to 15000 (the 44px select column), command-list 14000 to 14350 (the panel hugs, the room is page), menu 8950 to 9150 (the column every row keeps when any row has a check or a glyph), notifications 12450 to 12600, filter 17500 to 17600, forms 3500 to 3550, sheet 5400 to 5450, topbar-nav 7550 to 7600 and app-shell 5200 to 5250 (logical sides, the edge and the room); topbar's usage 3100 to 3200 (a bar's last ghost control takes data-edge); command-list's usage 2150 to 2300 (the panel hugs; the room is page, and only on the page); dialog-form's usage 1300 to 1350 (its Close is written data-icon-only data-edge=\"end\"). Raised in the polish ruling of 336 (the selection box keeps to the cell's line): selection 1650 to 1750 (the box's start margin, min(space-4, half the spare room): 1710 measured) and its usage 1150 to 1350 (the rule's sentence: 1313 measured).", + "$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. The fix round after both reviews of 421348e8 sets them to the measured sizes again: core 38950 to 39600 (every room says all three forms, and a hung word's box grows by a short room's shortfall), search to 5700 (it places its top again on a resize and with the keyboard; an empty list holds no padding), command-list to 14700 (it keeps the taller of its two heights), notifications to 12950 (the bell's edge), pane to 1950 (the page column's room), chart to 34950 (the date line's reason), and code, diagram-zoom, filter, links, sheet, still-table, tab-bar and topbar each by under 150 bytes (the three forms of a room; the selection column's width however given). Merged with main at db0bc418 (#129 to #131), DECISIONS 336's caps are set to the measured sizes again: core 35800 to 38950 and its usage 3200 to 3650, toast 16200 to 16750, terminal to 12700 (13050 with the open items' ruling: both copy buttons draw their three glyphs once, so a refused copy shows the close with no markup written after), diagram-zoom 17600 to 17750 (its viewer's Close and Zoom out hung, and the foot's room). Raised in DECISIONS 336 (reserved room across every component, claude/reserved-room), each to its measured size: core 35550 to 38700 (the edge rule a ghost .btn hangs by at a head, its ring and touch hit area, the side insets by direction, the .panel-head and page section-head that hang their last button by themselves) and its usage 2950 to 3450 (how data-edge and --basalt-edge-room are written); search 4400 to 5200 (search.js, the held top), terminal 11950 to 12550 (the close glyph for a refused copy, the edge on both copies), links 2750 to 3300 (the first icon link hung, the card room, the 20px glyph), toast 16050 to 16650 (the 46px hit areas on touch), selection 1500 to 1650 and still-table 14650 to 15000 (the 44px select column), command-list 14000 to 14350 (the panel hugs, the room is page), menu 8950 to 9150 (the column every row keeps when any row has a check or a glyph), notifications 12450 to 12600, filter 17500 to 17600, forms 3500 to 3550, sheet 5400 to 5450, topbar-nav 7550 to 7600 and app-shell 5200 to 5250 (logical sides, the edge and the room); topbar's usage 3100 to 3200 (a bar's last ghost control takes data-edge); command-list's usage 2150 to 2300 (the panel hugs; the room is page, and only on the page); dialog-form's usage 1300 to 1350 (its Close is written data-icon-only data-edge=\"end\"). Raised in the polish ruling of 336 (the selection box keeps to the cell's line): selection 1650 to 1750 (the box's start margin, min(space-4, half the spare room): 1710 measured) and its usage 1150 to 1350 (the rule's sentence: 1313 measured). Merging main (#130, #131) into claude/diagram-interop: diagram usage 4600 to 4850 (+5.4%: Batch B's diagram usage plus the basalt-diagram-export rule line, measured 4806), then 4850 to 5050 (noting that .lucid is for Lucid's REST API only and to use .vsdx in Lucid's UI, measured 4999).", "budgets": { "skillMd": 13050, "core": 39600 @@ -821,7 +821,7 @@ "kbd" ], "budget": 145450, - "usage": 4600, + "usage": 5050, "builds": [ "kbd" ] diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index eb31b43e..5d343dae 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -28,3 +28,4 @@ Boxes and the lines between them. `compose.mjs` writes the figure's words into t - **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`. +- **Export:** never hand-write `.drawio`, `.vsdx` or `.lucid`; author this diagram JSON and run `basalt-diagram-export --to drawio,vsdx,lucid` (in-repo: `node packages/react/bin/basalt-diagram-export.mjs` after `npm run build`). `.lucid` is for Lucid's REST API only (`POST https://api.lucid.co/v1/documents` with a token, type `x-application/vnd.lucid.standardImport`); to import through Lucid's own screen, use `.vsdx`.