From e3e06c774733988a3b518432fa5c599ce2e3f5b1 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:08 -0600 Subject: [PATCH 01/19] Diagram interop: @srasyndicate/basalt/diagram-interop subpath and CLI - Add the @srasyndicate/basalt/diagram-interop subpath outside the root index (diagramToDrawio, diagramToVsdx, diagramToLucid, diagramToLucidJson, exportMeasuredDiagram, readMeasuredExtras, isBundledMarkEmbeddable) with zero new runtime dependencies and 0 bytes added to still diagrams. - Cover all five Basalt diagram types (architecture, flowchart, data-flow, sequence, schema) with deterministic store-mode ZIP output, real containers/swimlanes/tables, single glued orthogonal connectors, attached labels, light/dark/adaptive themes, and manifest-gated mark embedding (default omit). - Snap connector endpoints and first/last waypoints directly to each shape's exact port coordinates in the target's own units (Visio inches, draw.io px, Lucid px), eliminating the RunTask joining jog seen in Lucidchart import. - Add the basalt-diagram-export CLI reading Basalt diagram JSON or HTML ` blocks from HTML, ignoring comments, textarea, code, pre, and template blocks. */ +export function extractDiagramsFromHtml(html) { + // Blank comments and non-live containers so examples inside comments/textarea/pre/code/template are ignored. + const masked = html + .replace(//g, (m) => " ".repeat(m.length)) + .replace(/<(textarea|pre|code|template)\b[^>]*>[\s\S]*?<\/\1>/gi, (m) => " ".repeat(m.length)); + + const out = []; + const re = /]*)>([\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 `).join("") + + ``; + const { html } = compose(body); + const launchOpts = fs.existsSync(launchPath) ? (await import(pathToFileURL(launchPath).href)).chromiumLaunchOptions() : {}; + const browser = await chromium.launch(launchOpts); + try { + const context = await browser.newContext({ viewport: { width: Math.max(width + 64, 1280), height: 1200 }, deviceScaleFactor: 2 }); + const page = await context.newPage(); + await page.setContent(html, { waitUntil: "load" }); + await page.evaluate(() => document.fonts.ready); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))))); + + // Inspect each figure's exact rendered DOM boxes + paths + const measured = await page.evaluate((count) => { + const results = []; + for (let idx = 0; idx < count; idx++) { + const fig = document.getElementById(`exp-${idx}`); + const drawing = fig.querySelector(".diagram-drawing"); + const o = drawing.getBoundingClientRect(); + const rectOf = (el) => { + const r = el.getBoundingClientRect(); + return { l: r.left - o.left, t: r.top - o.top, r: r.right - o.left, b: r.bottom - o.top }; + }; + const nodes = [...drawing.querySelectorAll(".diagram-node")].map((el, i) => ({ + id: el.dataset.node, + shape: el.dataset.shape, + i, + rect: rectOf(el), + })); + const lifelines = [...drawing.querySelectorAll(".diagram-life")].map((p) => { + const m = (p.getAttribute("d") || "").match(/M(-?[\d.]+)\s+(-?[\d.]+)V(-?[\d.]+)/); + return m ? { x: Number(m[1]), y1: Number(m[2]), y2: Number(m[3]) } : { x: 0, y1: 0, y2: 0 }; + }); + const lines = [...drawing.querySelectorAll(".diagram-edge")].map((g) => { + const lineEl = g.querySelector(".diagram-line"); + const tipEl = g.querySelector(".diagram-tip"); + const d = lineEl.getAttribute("d") || ""; + const pts = []; + for (const m of d.matchAll(/([MLQ])([^MLQ]*)/g)) { + const nums = m[2].trim().split(/[ ,]+/).map(Number); + if (m[1] === "Q") { pts.pop(); pts.push({ x: nums[0], y: nums[1] }); } + else pts.push({ x: nums[0], y: nums[1] }); + } + const tn = (tipEl.getAttribute("d") || "").match(/-?[\d.]+/g).map(Number); + const open = tipEl.hasAttribute("data-open"); + const tip = open ? { x: tn[2], y: tn[3] } : { x: tn[0], y: tn[1] }; + pts[pts.length - 1] = tip; + const a = pts[pts.length - 2] || pts[0], b = pts[pts.length - 1]; + const dir = Math.abs(a.x - b.x) < 0.01 ? (b.y > a.y ? "down" : "up") : (b.x > a.x ? "right" : "left"); + const kind = lineEl.getAttribute("data-kind") || "plain"; + return { i: Number(g.dataset.edge), from: g.dataset.from, to: g.dataset.to, kind, pts, tip, dir, width: kind === "main" ? 2 : 1 }; + }); + const labels = [...drawing.querySelectorAll(".diagram-label")].map((el) => ({ + i: Number(el.dataset.edge), + text: el.textContent, + box: rectOf(el), + on: el.hasAttribute("data-on"), + })); + const groups = [...drawing.querySelectorAll(".diagram-gbox")].map((el) => ({ + id: el.getAttribute("data-group"), + label: el.querySelector(".diagram-glabel")?.textContent || "", + rect: rectOf(el), + })); + const lanes = [...drawing.querySelectorAll(".diagram-lane")].map((el, k) => ({ + id: `lane-${k}`, + label: el.querySelector(".diagram-lane-name")?.textContent || "", + rect: rectOf(el), + })); + const bands = [...drawing.querySelectorAll(".diagram-band")].map((el) => ({ + text: el.textContent || "", + rect: rectOf(el), + })); + const tableRows = {}; + drawing.querySelectorAll('.diagram-node[data-shape="table"]').forEach((nodeEl) => { + const ys = [...nodeEl.querySelectorAll(".diagram-row")].map((r) => { + const rr = rectOf(r); + return (rr.t + rr.b) / 2; + }); + if (ys.length) tableRows[nodeEl.dataset.node] = ys; + }); + results.push({ + geo: { w: drawing.clientWidth, h: drawing.clientHeight, nodes, lines, lifelines, labels, crossings: [], through: [], unseated: [], outside: [], ox: 0, oy: 0 }, + extras: { groups, lanes, bands, tableRows }, + }); + } + return results; + }, items.length); + return measured; + } 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 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 === "--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}"`); + } + return { input, to, theme, marks, out, width, browser, help }; +} + +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 resolveMark = opts.marks === "embed" ? await createMarkResolver() : undefined; + const measuredList = opts.browser ? await measureInBrowser(items, opts.width) : null; + + const singleFileOut = + opts.out && + items.length === 1 && + opts.to.length === 1 && + /\.(drawio|vsdx|lucid|json)$/i.test(opts.out); + + 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 } = items[idx]; + const measured = measuredList ? measuredList[idx] : null; + const baseOpts = { theme: opts.theme, marks: opts.marks, resolveMark, width: opts.width, diagramId: name }; + + for (const format of opts.to) { + let data; + if (measured) { + 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 }); + } + } + + for (const w of written) { + process.stdout.write(`${path.relative(process.cwd(), w.path) || w.path} (${w.bytes} bytes)\n`); + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + 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 7ace96f1..bee71072 100644 --- a/packages/react/build.mjs +++ b/packages/react/build.mjs @@ -95,6 +95,19 @@ 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). +await esbuild.build({ + bundle: true, + format: "esm", + platform: "neutral", + target: "es2022", + logLevel: "warning", + entryPoints: [path.join(here, "src/diagram-interop.ts")], + outdir: dist, + external, +}); + // The root's map for the imports plugin (src/tooling/imports.ts): every name the root exports at run time, and the module that holds it, read from the barrel's source. // `export * from "./glyph-set"` is the one star, and glyph-set is itself a list of `export { X } from "./glyphs/x"`: each glyph maps to its own module. Every // `export` statement in the barrel must be one of the three forms below (`export { … } from "./x";`, `export type { … } from "./x";`, `export * from "./x";`, double @@ -135,7 +148,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", "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", "index.ts"].includes(f)).map((f) => path.join(here, "src", f)), ...fs.readdirSync(path.join(here, "src", "glyphs")).filter((f) => /\.ts$/.test(f)).map((f) => path.join(here, "src", "glyphs", f)), // The service marks (DECISIONS 292, 2.6): one module a mark under dist/marks, at @srasyndicate/basalt/marks/, never imported by the index, so an // app pays for the marks it imports and no others. Generated by marks/generate.mjs. @@ -199,7 +212,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"].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"].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 471bf516..c3b99b24 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -25,6 +25,10 @@ "types": "./dist/tooling/imports.d.ts", "default": "./dist/tooling/imports.js" }, + "./diagram-interop": { + "types": "./dist/diagram-interop.d.ts", + "default": "./dist/diagram-interop.js" + }, "./marks/*": { "types": "./dist/marks/*.d.ts", "default": "./dist/marks/*.js" @@ -35,8 +39,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" ], "scripts": { diff --git a/packages/react/src/diagram-interop.ts b/packages/react/src/diagram-interop.ts new file mode 100644 index 00000000..1b3e8629 --- /dev/null +++ b/packages/react/src/diagram-interop.ts @@ -0,0 +1,133 @@ +// @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314) +// 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 { DiagramSpec, Geo } from "./diagram-core"; +import { sceneToDrawio } from "./interop/drawio"; +import { sceneToLucid, sceneToLucidJson } from "./interop/lucid"; +import { isBundledMarkEmbeddable, layoutHeadless, readMeasuredExtras, sceneFromMeasured } from "./interop/scene"; +import { sceneToVsdx } from "./interop/vsdx"; +import type { + InteropFormat, + InteropMarkResolver, + InteropMarksMode, + InteropOptions, + InteropScene, + InteropTheme, + LucidBoundingBox, + LucidColorFill, + LucidCustomData, + LucidDocument, + LucidEndpoint, + LucidEndpointStyle, + LucidFieldSize, + LucidImageFill, + LucidLine, + LucidLineText, + LucidPage, + LucidShape, + LucidShapeStyle, + LucidStroke, + LucidSwimLane, + LucidTableCell, + MeasuredBand, + MeasuredExtras, + MeasuredGroup, + MeasuredInteropOptions, + MeasuredLane, + SceneBand, + SceneBox, + SceneEdge, + SceneGroup, + SceneLabel, + SceneLane, + SceneLifeline, + SceneMark, + SceneNode, + ScenePort, + SceneTableRow, +} from "./interop/types"; + +/** 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. */ +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`). */ +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`, 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 { isBundledMarkEmbeddable, layoutHeadless as measureDiagramHeadless, readMeasuredExtras }; + +export type { + 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, + MeasuredGroup, + MeasuredInteropOptions, + MeasuredLane, + SceneBand, + SceneBox, + SceneEdge, + 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..de35abf2 --- /dev/null +++ b/packages/react/src/interop/drawio.ts @@ -0,0 +1,540 @@ +// Deterministic draw.io (.drawio / mxGraphModel XML) exporter (DECISIONS 311, 314). +// Conforms strictly to mxfile-1.0.xsd: uncompressed XML, no XML comments, positive integer page sizes, +// real parent-child containers, 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 { 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"; + +function escXml(s: string): string { + return String(s) + .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]!; + let total = 0; + for (let i = 0; i < pts.length - 1; i++) { + total += Math.hypot(pts[i + 1]!.x - pts[i]!.x, pts[i + 1]!.y - pts[i]!.y); + } + 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 = Math.hypot(b.x - a.x, b.y - a.y); + 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]!; +} + +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(` `); + cells.push(` `); + + // Exact emitted world boxes for every connectable vertex (used to snap waypoints in draw.io's own coordinates) + const worldBoxByCell = new Map(); + + // 1. Groups (architecture containers, lowest z-order) + const groupBoxes = new Map(); + 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) }; + groupBoxes.set(g.id, box); + const style = cellStyle([ + "rounded=1", + "absoluteArcSize=1", + "arcSize=24", + "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( + ` \n` + + ` \n` + + ` `, + ); + } + + // 2. Data-flow horizontal lane containers (horizontal text in the 120px left label column) + const laneBoxes = new Map(); + 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( + ` \n` + + ` \n` + + ` `, + ); + } + + // 3. Sequence lifelines & phase bands (drawn behind participant headers and messages) + 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( + ` \n` + + ` \n` + + ` `, + ); + } + + 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( + ` \n` + + ` \n` + + ` `, + ); + } + + // 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 ? "padding-right:24px;" : ""; + + if (n.shape === "decision") { + return adaptive + ? `
${escXml(n.name)}
` + : `
${escXml(n.name)}
`; + } + const align = n.shape === "terminal" || n.shape === "participant" ? "text-align:center;" : ""; + const kindSpan = n.kind + ? adaptive + ? `
${escXml(n.kind)}
` + : `
${escXml(n.kind)}
` + : ""; + const namePad = !n.kind ? padMark : ""; + const nameSpan = adaptive + ? `
${escXml(n.name)}
` + : `
${escXml(n.name)}
`; + const detailFont = n.detailMono ? "Geist Mono,Consolas,monospace" : "Geist,Inter,Helvetica,Arial,sans-serif"; + const detailSpan = n.detail + ? adaptive + ? `
${escXml(n.detail)}
` + : `
${escXml(n.detail)}
` + : ""; + 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( + ` \n` + + ` \n` + + ` `, + ); + + 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 = + `` + + `` + + `` + + `` + + `` + + `
${row.key ? escXml(row.key) : ""}${escXml(row.name)}${escXml(rightWord)}
`; + 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( + ` \n` + + ` \n` + + ` `, + ); + } + + 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( + ` \n` + + ` \n` + + ` `, + ); + } + 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( + ` \n` + + ` \n` + + ` `, + ); + + // 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 useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark"; + const svg = useDarkForm ? n.mark.svgDark : n.mark.svgLight; + 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( + ` \n` + + ` \n` + + ` `, + ); + } + } + + // 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 + ? `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 + ? `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 ? 0 : round6(e.fromPort.x); + const exitY = e.fk && srcCellId.startsWith("row-") ? 0.5 : round6(e.fromPort.y); + const entryX = e.sequence ? 0 : round6(e.toPort.x); + const entryY = e.fk && dstCellId.startsWith("row-") ? 0.5 : 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 endArrow = e.openTip ? "open" : "block"; + const endFill = e.openTip ? 0 : 1; + + 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}`, + `endArrow=${endArrow}`, + `endFill=${endFill}`, + "endSize=6", + ...(e.fk ? ["startArrow=oval", "startFill=1", "startSize=6"] : ["startArrow=none", "startFill=0"]), + `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 \n` + + innerPts.map((p) => ` `).join("\n") + + `\n ` + : ""; + + const edgeId = `edge-${e.index}`; + cells.push( + ` \n` + + ` ${ptsXml}\n` + + ` \n` + + ` `, + ); + + 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 + ? ` ` + : ` `; + const lblBg = e.label.on || e.sequence + ? "labelBackgroundColor=default;defaultLabelBackgroundColor=page" + : "labelBackgroundColor=none"; + const lblValue = e.label.note + ? `
${escXml(e.label.text)}
` + + `
${escXml(e.label.note)}
` + : escXml(e.label.text); + 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( + ` \n` + + ` \n` + + `${offsetPt}\n` + + ` \n` + + ` `, + ); + } + } + + const bgAttr = adaptive ? "" : ` background="${P.page}"`; + const adaptiveAttr = adaptive ? ` adaptiveColors="auto"` : ` adaptiveColors="none"`; + + return ( + `\n` + + ` \n` + + ` \n` + + ` \n` + + `${cells.join("\n")}\n` + + ` \n` + + ` \n` + + ` \n` + + `\n` + ); +} diff --git a/packages/react/src/interop/lucid.ts b/packages/react/src/interop/lucid.ts new file mode 100644 index 00000000..d8cd9d1d --- /dev/null +++ b/packages/react/src/interop/lucid.ts @@ -0,0 +1,406 @@ +// Deterministic Lucid Standard Import (.lucid ZIP + document.json) exporter (DECISIONS 311, 314). +// Conforms to https://developer.lucid.co/docs/standard-import: +// - documentSettings.units = "px", rounding = 2 * px radius, explicit pt font-size on every text run +// - roundedRectangleContainer (assistedLayout: false, magnetize: true), swimLanes, table, decision, terminator +// - single glued lines (shapeEndpoint / lineEndpoint) with elbowControlPoints snapped in Lucid units +import type { Pt } from "../diagram-core"; +import { paletteFor, round2, round6, snapRouteToPorts } from "./scene"; +import type { + InteropScene, + InteropTheme, + LucidDocument, + LucidEndpoint, + LucidLine, + LucidLineText, + LucidShape, + LucidTableCell, + SceneBox, +} from "./types"; +import { makeDeterministicZip } from "./zip"; +import type { ZipEntry } from "./zip"; + +function escHtml(s: string): string { + return String(s) + .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(); + const lifeByParticipant = new Map(); + + // 1. Architecture group containers (lowest zIndex, 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) }; + 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: 24, // 12px radius * 2 + }, + magnetize: true, + assistedLayout: false, + containerTitle: { + text: `${escHtml(g.label)}`, + }, + zIndex: 0, + }); + } + + // 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: `${escHtml(band.text)}`, + position: 0.5, + side: "middle", + }, + ], + zIndex: 4, + }); + } + + // 4. Nodes (cards, flowchart shapes, participants, schema tables) + for (const n of scene.nodes) { + 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; + + if (n.shape === "table") { + const rows = n.rows ?? []; + const rowCount = 1 + rows.length + (n.more ? 1 : 0); + const colCount = 3; + const cells: LucidTableCell[] = []; + const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: n.headerH ?? 37 }]; + // Header row merged across all 3 columns + cells.push({ + xPosition: 0, + yPosition: 0, + mergeCellsRight: 2, + style: { fill: { type: "color", color: fill } }, + text: `

${escHtml(n.name)}

`, + }); + for (let r = 0; r < rows.length; r++) { + const row = rows[r]!; + const yPos = r + 1; + rowSizes.push({ index: yPos, size: round2(row.h) }); + const rightWord = row.refTable ? `→ ${row.refTable}` : row.type ?? ""; + cells.push( + { + xPosition: 0, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: row.key ? `

${escHtml(row.key)}

` : "", + }, + { + xPosition: 1, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: `

${escHtml(row.name)}

`, + }, + { + xPosition: 2, + yPosition: yPos, + style: { fill: { type: "color", color: fill } }, + text: rightWord + ? `

${escHtml(rightWord)}

` + : "", + }, + ); + } + if (n.more) { + const moreIdx = rows.length + 1; + rowSizes.push({ index: moreIdx, size: 24 }); + cells.push({ + xPosition: 0, + yPosition: moreIdx, + mergeCellsRight: 2, + style: { fill: { type: "color", color: fill } }, + text: `

${escHtml(`+ ${n.more} more`)}

`, + }); + } + 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: [ + { key: "basalt_id", value: n.id }, + { key: "basalt_col", value: String(n.col) }, + { key: "basalt_row", value: String(n.row) }, + ], + zIndex: 10, + }); + continue; + } + + const align = n.shape === "decision" || n.shape === "terminal" || n.shape === "participant" ? "center" : "left"; + const linesHtml: string[] = []; + if (n.kind) { + linesHtml.push(`

${escHtml(n.kind)}

`); + } + linesHtml.push(`

${escHtml(n.name)}

`); + if (n.detail) { + const ff = n.detailMono ? "'Geist Mono', 'Liberation Mono', monospace" : "'Geist', 'Liberation Sans', sans-serif"; + linesHtml.push(`

${escHtml(n.detail)}

`); + } + + 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: [ + { key: "basalt_id", value: n.id }, + { key: "basalt_col", value: String(n.col) }, + { key: "basalt_row", value: String(n.row) }, + ], + 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 }, + }, + 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 = pBox ? round2(pBox.x + pBox.w / 2) : 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 }); + lines.push({ + id: lineId, + lineType: "straight", + endpoint1: pBox + ? { type: "shapeEndpoint", style: "none", shapeId: lucidId("node", lf.participantId), position: { x: 0.5, 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, + }); + } + + // 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 pos1 = round6(e.fromPort.y); + const pos2 = round6(e.toPort.y); + startPt = { x: lf1.x, y: round2(lf1.y1 + pos1 * (lf1.y2 - lf1.y1)) }; + endPt = { x: lf2.x, y: round2(lf2.y1 + pos2 * (lf2.y2 - lf2.y1)) }; + endpoint1 = { type: "lineEndpoint", style: "none", lineId: lf1.lineId, position: pos1 }; + endpoint2 = { type: "lineEndpoint", style: e.openTip ? "openArrow" : "arrow", 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) }; + endpoint1 = { type: "shapeEndpoint", style: e.fk ? "closedCircle" : "none", shapeId: lucidId("node", e.from), position: { x: fx, y: fy } }; + endpoint2 = { type: "shapeEndpoint", style: e.openTip ? "openArrow" : "arrow", 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 texts: LucidLineText[] = [ + { + text: `${escHtml(e.label.text)}`, + position: e.label.t, + side: e.label.on ? "middle" : "top", + }, + ]; + if (e.label.note) { + texts.push({ + text: `${escHtml(e.label.note)}`, + 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..1bac54e0 --- /dev/null +++ b/packages/react/src/interop/scene.ts @@ -0,0 +1,1548 @@ +// Shared scene builder for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314). +// 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, groupReach } from "../diagram-core"; +import type { DiagramSide, DiagramSpec, GLine, GNode, Geo, MNode, Model, Pt, Rect } from "../diagram-core"; +import type { + InteropMarkResolver, + InteropOptions, + InteropScene, + MeasuredBand, + MeasuredExtras, + MeasuredGroup, + MeasuredLane, + SceneBand, + SceneBox, + SceneEdge, + 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 (matches packages/react/marks/manifest.json) ---- +// Official AWS, Azure, Google Cloud and Kubernetes (Apache-2.0) marks explicitly allow use in architecture diagrams. +// Unofficial edits (the 8 tile-removed AWS icons and third-party community drawings) and marks without diagram-use terms are excluded. + +const AWS_UNOFFICIAL_MARKS = [ + "aws-bedrock", + "aws-step-functions", + "aws-kinesis", + "aws-fargate", + "aws-secrets-manager", + "aws-cognito", + "aws-eks", + "aws-kms", +]; + +/** Whether a bundled Basalt mark id is permitted for embedding in exported diagrams by its manifest terms. */ +export function isBundledMarkEmbeddable(id: string): boolean { + if (!id) return false; + if (id === "kubernetes") return true; + if (id.startsWith("azure-") || id.startsWith("gcp-")) return true; + if (id.startsWith("aws-")) return !AWS_UNOFFICIAL_MARKS.includes(id); + return false; +} + +/** Extracts raw `...` 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("= 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 = { 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); + return Math.hypot(p.x - ex, p.y - cy) < rr - pad; + } + return p.x > l + pad && p.x < r - pad && p.y > t + pad && p.y < b - pad; +} + +function boxHitsShape(box: Rect, n: GNode): boolean { + if (!hit(box, n.rect)) return false; + if (n.shape !== "decision" && n.shape !== "terminal") return true; + const { l, t, r, b } = n.rect; + const cx = (l + r) / 2, cy = (t + b) / 2, hw = (r - l) / 2, hh = (b - t) / 2; + if (n.shape === "decision") { + const px = Math.max(box.l, Math.min(cx, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + return Math.abs(px - cx) / hw + Math.abs(py - cy) / hh < 1 - 1e-6; + } + const rr = Math.min(hh, hw); + if (hit(box, { l: l + rr, r: r - rr, t, b })) return true; + for (const ex of [l + rr, r - rr]) { + const px = Math.max(box.l, Math.min(ex, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); + if (Math.hypot(px - ex, py - cy) < rr - 0.01) return true; + } + return false; +} + +function segmentThrough(a: Pt, b: Pt, n: GNode): boolean { + const len = Math.hypot(b.x - a.x, b.y - a.y); + const steps = Math.max(2, Math.ceil(len / 2)); + for (let k = 1; k < steps; k++) { + const f = k / steps; + if (f * len < 1.5 || (1 - f) * len < 1.5) continue; + if (insideShape({ x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }, n, 1)) return true; + } + return false; +} + +function findCrossingsCount(lines: GLine[], only: Set): 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 { + 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(items: T[]): Generator { + 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 len = Math.hypot(pts[i]!.x - pts[i - 1]!.x, pts[i]!.y - pts[i - 1]!.y); + segLens.push(len); + total += len; + } + if (total <= 1e-6) return 0.5; + let bestDist = 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 d = Math.hypot(cx - px, cy - py); + if (d < bestDist) { + bestDist = d; + 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 }; +} + +// ---- 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 ? 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") least = n * table + (n - 1) * 48 + (oneColTurnBack ? 20 : 0); + 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): { 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 kindLines = n.kind ? Math.max(1, wrapText(n.kind, "mono", inner).lines) : 0; + const nameLines = Math.max(1, wrapText(n.name, "name", inner).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: 2 + 20 + kindLines * 16 + nameLines * 20 + detailGap + detailLines * 16 }; +} + +function seatSceneLabels( + m: Model, + edges: SceneEdge[], + gNodes: GNode[], + groupRects: Rect[], + laneObstacles: Rect[], + bounds: Rect, +): Map { + const placed: Rect[] = []; + const out = new Map(); + 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 w = measureText(text, "label"); + const hgt = 16; + 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; +} + +/** Computes a complete deterministic InteropScene from Basalt's DiagramSpec headlessly (no DOM or browser). */ +export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): InteropScene { + const m = buildModel(spec, { checks: false }); + const pad = options.pad ?? 32; + const marksMode = options.marks ?? "omit"; + const hasMarks = marksMode === "embed" && m.nodes.some((n) => Boolean(resolveNodeMark(n, marksMode, options.resolveMark))); + const mins = computeMinimums(m, hasMarks); + const targetW = Math.max(options.width ?? 1104, mins.least); + const id = options.diagramId ?? slugId(m.title || m.type); + + if (m.type === "sequence") { + return layoutSequenceHeadless(m, targetW, pad, id); + } + + // Grid geometry + let padTop = 0, padRight = 0, padBottom = 0, padLeft = 0; + if (m.type === "architecture" && m.groups.length > 0) { + const members = m.groups.flatMap((g) => g.members.map((gid) => m.byId.get(gid)!)); + if (members.some((n) => n.row === 1)) padTop = 32; + if (members.some((n) => n.col === m.cols)) padRight = 16; + if (members.some((n) => n.row2 === m.rows)) padBottom = 16; + if (members.some((n) => n.col === 1)) padLeft = 16; + } + if (m.type === "schema" && m.cols === 1 && m.edges.length > 0) { + padRight = 20; + } + + const colGap = m.type === "data-flow" || m.type === "schema" ? 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 + const nodeMeasured = new Map(); + const rowHeights = new Array(m.rows).fill(m.type === "data-flow" ? 56 : 0); + + for (const n of m.nodes) { + const mark = resolveNodeMark(n, marksMode, options.resolveMark); + const meas = measureNodeHeight(n, trackW, Boolean(mark)); + 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]) + 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 += rowHeights[r - 1]!; + spanH += (n.row2 - n.row) * rowGap; + if (meas.h > spanH) { + rowHeights[n.row2 - 1] = rowHeights[n.row2 - 1]! + (meas.h - spanH); + } + } + } + + const gridRows: Array<[number, number]> = []; + let curY = padTop; + for (let r = 0; r < m.rows; r++) { + const rh = Math.max(40, rowHeights[r]!); + gridRows.push([round2(curY), round2(curY + rh)]); + curY += rh + rowGap; + } + 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(); + const gNodeMap = new Map(); + + 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) + const sceneGroups: SceneGroup[] = []; + const groupRects: Rect[] = []; + if (m.type === "architecture") { + for (const g of m.groups) { + const mem = g.members.map((gid) => m.byId.get(gid)!).filter(Boolean); + if (!mem.length) continue; + const c1 = Math.min(...mem.map((n) => n.col)); + const c2 = Math.max(...mem.map((n) => n.col)); + const r1 = Math.min(...mem.map((n) => n.row)); + const r2 = Math.max(...mem.map((n) => n.row2)); + const l = round2(gridCols[c1 - 1]![0] - 16); + const r = round2(gridCols[c2 - 1]![1] + 16); + const t = round2(gridRows[r1 - 1]![0] - 32); + const b = round2(gridRows[r2 - 1]![1] + 16); + groupRects.push({ l, t, r, b }); + sceneGroups.push({ id: g.id, label: g.label, box: { x: l, y: t, w: round2(r - l), h: round2(b - t) }, members: g.members }); + } + } + + // 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 lane solver + const sceneEdges = routeEdges(m, nodeById, gNodeMap, gridCols, gridRows); + + // 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, + nodes: sceneNodes, + groups: sceneGroups, + lanes: sceneLanes, + lifelines: [], + bands: [], + edges: sceneEdges, + }; +} + +function routeEdges( + m: Model, + nodeById: Map, + gNodeMap: Map, + gridCols: Array<[number, number]>, + gridRows: Array<[number, number]>, +): SceneEdge[] { + const trackOf = (n: MNode) => (m.type === "data-flow" ? n.col + 1 : n.col); + const dropped = new Set(); + if (m.type === "schema") { + m.edges.forEach((e, k) => { + if (Math.abs(m.byId.get(e.from)!.col - m.byId.get(e.to)!.col) > 1) dropped.add(k); + }); + } + + // Determine sides and exact fractional ports + const derived = m.type === "schema" ? [] : derivedPorts(m); + const edgeMeta = m.edges.map((e, k) => { + const a = m.byId.get(e.from)!; + const b = m.byId.get(e.to)!; + const na = nodeById.get(e.from)!; + const nb = nodeById.get(e.to)!; + let s1: DiagramSide, s2: DiagramSide, fromPort: ScenePort, toPort: ScenePort; + if (m.type === "schema") { + if (a.col === b.col) { + const side: DiagramSide = a.col === m.cols && m.cols > 1 ? "left" : "right"; + s1 = side; s2 = side; + } else { + s1 = b.col > a.col ? "right" : "left"; + s2 = opposite[s1]; + } + 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); + 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]!; + s1 = dp.fromSide; s2 = dp.toSide; + 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 }; + }); + + // Gutter jog clustering and lane permutation solver (mirrors diagram-core.ts) + const jogs = new Map }>(); + const turnBacks = new Set(); + + m.edges.forEach((e, k) => { + if (dropped.has(k)) return; + 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) && 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 (!jogs.has(key)) jogs.set(key, { span, vertical, members: new Map() }); + const portKey = `${e.to}.${s2}.${Math.round(vertical ? p2.y : p2.x)}`; + const g = jogs.get(key)!; + if (!g.members.has(portKey)) g.members.set(portKey, []); + g.members.get(portKey)!.push(k); + }); + + const lanes = new Map(); + const rawRoute = (k: number): Pt[] => { + const { s1, s2, p1, p2 } = edgeMeta[k]!; + if (isH(s1) && isH(s2)) { + if (s1 === s2) { + const x = round2(lanes.get(k) ?? (s1 === "right" ? Math.max(p1.x, p2.x) + 16 : Math.min(p1.x, p2.x) - 16)); + 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) => { + 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 runOf = (members: number[], vertical: boolean): [number, number] => { + const vals = members.flatMap((k) => { const { p1, p2 } = edgeMeta[k]!; return vertical ? [p1.y, p2.y] : [p1.x, p2.x]; }); + return [Math.min(...vals), Math.max(...vals)]; + }; + + for (const [, g] of jogs) { + const ports = [...g.members.values()].map((members) => ({ members, run: runOf(members, g.vertical) })).sort((a, b) => a.run[0] - b.run[0]); + const clusters: Array = []; + 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]); + } + for (const cluster of clusters) { + if (cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k))) continue; + const groupsOf = cluster.map((c) => c.members); + const count = groupsOf.length; + const step = (g.span[1] - g.span[0]) / (count + 1); + const inGutter = new Set(groupsOf.flat()); + 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, g.span[0] + step * (j + 1)))); + const tried = score(inGutter); + if (tried.score < bestScore) { bestScore = tried.score; best = perm; bestLines = tried.lines; } + } + best.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); + current = bestLines; + } + } + + 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); + out.push({ + index: k, + from: e.from, + to: e.to, + fromRow: e.fromRow, + toRow: e.toRow, + fk: Boolean(e.fk), + kind: e.kind, + openTip: e.kind === "dashed", + fromPort: meta.fromPort, + toPort: meta.toPort, + pts, + }); + }); + return out; +} + +function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: string): InteropScene { + const n = Math.max(1, m.nodes.length); + const gap = 20; + const colW = round2((targetW - (n - 1) * gap) / n); + let headH = 44; + for (const p of m.nodes) headH = Math.max(headH, measureNodeHeight(p, colW, false).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 }, + }; + }); + + const cxById = new Map(); + 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 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) { + bands.push({ text: s.band, y: round2(y), h: 36, w: round2(targetW) }); + y += 36; + } else { + 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])); + + 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; + 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); + pts = [ + { x: lf1.x, y: yt }, + { x: round2(lf1.x + out), y: yt }, + { x: round2(lf1.x + out), y: yb }, + { x: lf1.x, y: yb }, + ]; + fromPort = { x: 0.5, y: round4((yt - lf1.y1) / span1), side }; + toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + } else { + const dirRight = lf2.x >= lf1.x; + pts = [{ x: lf1.x, y: s.y }, { x: lf2.x, y: s.y }]; + fromPort = { x: 0.5, y: round4((s.y - lf1.y1) / span1), side: dirRight ? "right" : "left" }; + toPort = { x: 0.5, y: round4((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, + 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, + nodes: sceneNodes, + groups: [], + lanes: [], + lifelines, + bands, + 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(Math.max(0, Math.min(1, 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 m = buildModel(spec, { checks: false }); + 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 + const sceneGroups: SceneGroup[] = []; + if (m.type === "architecture") { + const extraById = new Map((extras.groups ?? []).map((g) => [g.id, g])); + for (const g of m.groups) { + const eg = extraById.get(g.id); + if (eg) { + sceneGroups.push({ id: g.id, label: g.label, box: rectToBox(eg.rect), members: g.members }); + } else { + const mem = g.members.map((gid) => nodeById.get(gid)).filter((x): x is SceneNode => Boolean(x)); + if (!mem.length) continue; + const l = round2(Math.min(...mem.map((x) => x.box.x)) - 16); + const r = round2(Math.max(...mem.map((x) => x.box.x + x.box.w)) + 16); + const t = round2(Math.min(...mem.map((x) => x.box.y)) - 32); + const b = round2(Math.max(...mem.map((x) => x.box.y + x.box.h)) + 16); + sceneGroups.push({ id: g.id, label: g.label, box: { x: l, y: t, w: round2(r - l), h: round2(b - t) }, members: g.members }); + } + } + } + + // Lanes + const sceneLanes: SceneLane[] = []; + if (m.type === "data-flow") { + const extraById = new Map((extras.lanes ?? []).map((l) => [l.id, l])); + const rowBounds: Array<[number, number]> = m.lanes.map((lane, idx) => { + const el = extraById.get(lane.id); + 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, 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(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 { + 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); + } + } + } + + const edges: SceneEdge[] = []; + for (const s of m.steps) { + if ("band" 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; + if (self) { + const out = selfSide === "start" ? -24 : 24; + const side: DiagramSide = selfSide === "start" ? "left" : "right"; + const yt = round2(gl.pts[0]!.y); + const yb = round2(gl.pts[gl.pts.length - 1]!.y); + pts = [{ x: lf1.x, y: yt }, { x: round2(lf1.x + out), y: yt }, { x: round2(lf1.x + out), y: yb }, { x: lf1.x, y: yb }]; + fromPort = { x: 0.5, y: round4((yt - lf1.y1) / span1), side }; + toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + } else { + const y = round2(gl.pts[0]!.y); + const dirRight = lf2.x >= lf1.x; + pts = [{ x: lf1.x, y }, { x: lf2.x, y }]; + fromPort = { x: 0.5, y: round4((y - lf1.y1) / span1), side: dirRight ? "right" : "left" }; + toPort = { x: 0.5, y: round4((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, + 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, nodes: sceneNodes, groups: [], lanes: [], lifelines, bands, 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 + 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]!; + 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]!; + 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), + 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, + nodes: sceneNodes, + groups: sceneGroups, + lanes: sceneLanes, + lifelines: [], + bands: [], + edges, + }; +} + +/** Reads optional group, lane, band, and table-row rects from a live diagram `
` 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(`.${prefix}-glabel`)?.textContent ?? ""; + groups.push({ id, label, 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}`, 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 tableRows: Record = {}; + 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, + 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..d1a31569 --- /dev/null +++ b/packages/react/src/interop/types.ts @@ -0,0 +1,319 @@ +// Public and scene types for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314). +// Pure structural declarations: no third-party or Node types appear anywhere in this surface. +import type { DiagramLineKind, 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; +} + +export interface MeasuredGroup { + id: string; + label: string; + rect: Rect; +} + +export interface MeasuredLane { + id: string; + label: string; + rect: Rect; +} + +export interface MeasuredBand { + text: string; + rect: Rect; +} + +/** Optional DOM measurements that accompany `Geo` when exporting a live rendered figure. */ +export interface MeasuredExtras { + groups?: MeasuredGroup[]; + lanes?: MeasuredLane[]; + bands?: MeasuredBand[]; + /** Vertical midpoints of each table's column rows in drawing coordinates, keyed by table name. */ + tableRows?: Record; +} + +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; +} + +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; + box: SceneBox; + members: 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 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; + /** For schema foreign keys: source and target column row indices. */ + fromRow?: number; + toRow?: number; + fk: boolean; + 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; + nodes: SceneNode[]; + groups: SceneGroup[]; + lanes: SceneLane[]; + lifelines: SceneLifeline[]; + bands: SceneBand[]; + 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"; + +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 { DiagramSpec, Geo }; diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts new file mode 100644 index 00000000..77f17cdb --- /dev/null +++ b/packages/react/src/interop/vsdx.ts @@ -0,0 +1,875 @@ +// Deterministic Microsoft Visio (.vsdx) OPC exporter (DECISIONS 311, 314). +// 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 { 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; + +function escXml(s: string): string { + return String(s) + .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; + ix: number; +} + +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); + 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 so straight-line Connection rows + // align to 0.000000 in across boxes of different heights/widths (e.g. schema tables and sequence lifelines). + const geomByKey = new Map(); + 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 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), + }); + } + + // Collect deduplicated Connection rows required on each target shape/lifeline + const connsByKey = new Map(); + const getConnIndex = (key: string, fx: number, fy: number, 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 existing = list.find((c) => Math.abs(c.cx - cx) < 1e-6 && Math.abs(c.cy - cy) < 1e-6); + if (existing) return existing.ix; + const ix = list.length; + list.push({ fx: rfx, fy: rfy, cx, cy, ix }); + return ix; + }; + + const edgeConns = scene.edges.map((e) => { + const fromKey = e.sequence ? `life:${e.from}` : `node:${e.from}`; + const toKey = e.sequence ? `life:${e.to}` : `node:${e.to}`; + const fromG = geomByKey.get(fromKey); + const toG = geomByKey.get(toKey); + const fromFx = e.sequence ? 0.5 : e.fromPort.x; + const toFx = e.sequence ? 0.5 : e.toPort.x; + const fromIx = getConnIndex(fromKey, fromFx, e.fromPort.y); + let toIx: number; + if (e.pts.length === 2 && fromG && toG) { + const fc = connsByKey.get(fromKey)![fromIx]!; + const startPageX = n6(fromG.pinX - n6(fromG.wIn / 2) + fc.cx); + const startPageY = 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 (horiz) { + const toBottom = toG.pinY - n6(toG.hIn / 2); + const exactCy = n6(startPageY - toBottom); + const alignedFy = toG.hIn > 0 ? round6(1 - exactCy / toG.hIn) : e.toPort.y; + toIx = getConnIndex(toKey, toFx, alignedFy, undefined, exactCy); + } else { + const toLeft = toG.pinX - n6(toG.wIn / 2); + const exactCx = n6(startPageX - toLeft); + const alignedFx = toG.wIn > 0 ? round6(exactCx / toG.wIn) : toFx; + toIx = getConnIndex(toKey, alignedFx, e.toPort.y, exactCx, undefined); + } + } else { + toIx = getConnIndex(toKey, toFx, e.toPort.y); + } + return { fromKey, toKey, fromIx, toIx }; + }); + + let nextId = 1; + const shapeXml: string[] = []; + const connectXml: string[] = []; + const placed = new Map(); + const mediaFiles: Array<{ rId: string; fileName: string; svg: string }> = []; + + // 1. Architecture groups (behind nodes) + for (const g of scene.groups) { + const id = nextId++; + 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(12 / DPI); + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${escXml(g.label)}\n` + + `
`, + ); + } + + // 2. Data-flow lanes (behind step cards) + for (let k = 0; k < scene.lanes.length; k++) { + const lane = scene.lanes[k]!; + const id = nextId++; + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${escXml(lane.label)}\n` + + `
`, + ); + } + + // 3. Sequence lifelines & phase bands + for (const lf of scene.lifelines) { + const id = nextId++; + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + connRowsXml + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
`, + ); + } + + for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) { + const band = scene.bands[bIdx]!; + const id = nextId++; + 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); + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${escXml(band.text)}\n` + + `
`, + ); + } + + // 4. Node shapes + for (const n of scene.nodes) { + const id = nextId++; + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + geomXml.replace(/^ /gm, " ") + + ` `, + ); + + // Child 1: table header title + const headerHIn = n6((n.headerH ?? 37) / DPI); + const headerPinY = n6(hIn - headerHIn / 2); + const headerId = nextId++; + childShapes.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${escXml(n.name)}\n` + + `
`, + ); + + // 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${escXml(keyPad)}${escXml(row.name)}\n` + + `
`, + ); + const rightText = row.refTable ? `→ ${row.refTable}` : row.type ?? ""; + if (rightText) { + const rightId = nextId++; + childShapes.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${escXml(rightText)}\n` + + `
`, + ); + } + } + + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${escXml(`+ ${n.more} more`)}\n` + + `
`, + ); + } + + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + connRowsXml + + ` \n` + + `${childShapes.join("\n")}\n` + + ` \n` + + ` `, + ); + continue; + } + + const { charRows, textRuns } = buildNodeTextRuns(n, P); + const connRowsXml = renderConnectionRows(conns, wIn, hIn); + const geomXml = buildNodeGeometryXml(n, wIn, hIn); + + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `${charRows.join("\n")}\n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + connRowsXml + + geomXml + + ` ${textRuns.join("")}\n` + + `
`, + ); + + if (n.mark) { + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` `, + ); + } + } + + // 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 = fromPlaced.conns[ec.fromIx]!; + const toConn = toPlaced.conns[ec.toIx]!; + + // Exact start and end in Visio inches from the placed shape's Connection rows (eliminates RunTask jog) + const p0 = connectionPagePt(fromPlaced, fromConn); + const pN = connectionPagePt(toPlaced, toConn); + 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); + + 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.fk ? 10 : 0; // 10 = filled circle dot for FK origin + const endArrow = e.openTip ? 1 : 4; // 1 = open V, 4 = filled block triangle + const radIn = n6((e.sequence && e.from === e.to ? 4 : 8) / DPI); + + const geomRows = vPts.map((pt, k) => { + const lx = k === 0 ? 0 : k === vPts.length - 1 ? wIn : n6(pt.x - p0.x); + const ly = k === 0 ? 0 : k === vPts.length - 1 ? hIn : n6(pt.y - p0.y); + const tag = k === 0 ? "MoveTo" : "LineTo"; + return ` `; + }).join("\n"); + + const fromOneBased = ec.fromIx + 1; + const toOneBased = ec.toIx + 1; + + let textBlockXml = ""; + let textXml = ""; + if (e.label) { + const lcx = n6(toVisioX(e.label.box.x + e.label.box.w / 2) - p0.x); + const lcy = n6(toVisioY(e.label.box.y + e.label.box.h / 2) - p0.y); + const lw = n6((e.label.box.w + 12) / DPI); + const lh = n6(((e.label.note ? 34 : e.label.box.h) + 4) / DPI); + const noteChar = e.label.note + ? `\n ` + : ""; + textBlockXml = + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${noteChar}\n` + + `
\n` + + `
\n` + + ` \n` + + `
\n`; + textXml = e.label.note + ? ` ${escXml(e.label.text)}\n${escXml(e.label.note)}\n` + : ` ${escXml(e.label.text)}\n`; + } + + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + (beginArrow ? ` \n` : "") + + ` \n` + + ` \n` + + textBlockXml + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + `${geomRows}\n` + + `
\n` + + textXml + + `
`, + ); + + connectXml.push( + ` `, + ` `, + ); + } + + const svgDefaultType = mediaFiles.length + ? ` \n` + : ""; + + const contentTypes = + `\n` + + `\n` + + ` \n` + + ` \n` + + svgDefaultType + + ` \n` + + ` \n` + + ` \n` + + `\n`; + + const rootRels = + `\n` + + `\n` + + ` \n` + + `\n`; + + const docXml = + `\n` + + `\n` + + ` \n` + + ` ${escXml(scene.title || scene.id)}\n` + + ` Basalt Diagram Exporter\n` + + ` \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` + : ""; + + 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 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; +} From f92f416f50fd3172b3bf969804b75ae747cdbb26 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:13 -0600 Subject: [PATCH 02/19] HTML skill: export diagrams via basalt-diagram-export instead of hand-writing XML - Record the rule in SKILL.md and diagram.md usage notes to author Basalt diagram JSON and run basalt-diagram-export rather than hand-writing .drawio, .vsdx or .lucid files. - Keep both SKILL.md (12,557 / 12,650 B) and diagram.md (4,011 / 4,300 B) within their byte caps and rebuild the packaged usage part. Co-Authored-By: Gemini 4 Neon --- .agent/skills/basalt-html/SKILL.md | 7 ++++--- .agent/skills/basalt-html/parts/usage/diagram.md | 1 + tools/html-skill/src/usage/diagram.md | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index 6f9b321a..5cfeb8cf 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -9,9 +9,9 @@ Standalone HTML that looks and behaves like Basalt: one file, no network, dark a ## Use it -1. Pick the modules from the index below, then print their usage in one call, always with core: `node .agent/skills/basalt-html/compose.mjs --usage core table status callout`. Core is the layout, type, panel and button classes every page uses. Each usage also names the modules it needs and the classes, attributes and tags that bring it in. `--usage` alone prints the index. -2. Write the **body** to a file such as `report.body.html`: the HTML that goes inside ``, with the classes the usage names. The same file may carry `` (else the first `<h1>` is the title), your own `<style>`, and head tags: `<meta name="description">`, `og:`/`twitter:` meta, `<link rel="icon" href="data:…">` or `canonical` (any other meta or link is refused); the script adds `Basalt.init()` unless your own `<script>` calls it. -3. Run `node .agent/skills/basalt-html/compose.mjs report.body.html` (writes `report.html`; `--out <page.html>` names it). It wraps the body in the doctype, meta and theme bootstrap, inlines Geist, and adds the core CSS and script plus only the modules your classes, attributes and tags use, and the icons you name in quotes. It prints what it added, and one warning line for each module added. `--no-fonts` skips Geist (only for a file a tool reads, never a file a person opens), `--lang fr` sets the language, `--all` adds every module. +1. Pick the modules from the index below, then print their usage in one call, always with core: `node .agent/skills/basalt-html/compose.mjs --usage core table status callout`. Core is the layout, type, panel and button classes every page uses. Each usage names the modules it needs and its triggers. `--usage` alone prints the index. +2. Write the **body** (e.g. `report.body.html`): what goes inside `<body>`, with the classes from usage. It may carry `<title>` (else the 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). It wraps the body in doctype, meta and theme bootstrap, inlines Geist, and adds core CSS/JS plus only the modules you use and the icons you name in quotes. It prints what it added, and one warning line for each module added. `--no-fonts` skips Geist (tools only, never for readers), `--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. `examples/static.body.html`, `sales.body.html` (reports) and `interactive.body.html` (inputs, tabs, a palette) are bodies to copy. Never open or paste `parts/`: it is minified output. @@ -104,4 +104,5 @@ Your own CSS goes in a `<style>` in the body (moved to the head, after Basalt's) - **No** CDN, framework, web font request, glow, gradient, dot grid, outer frame around the page, bounce, press scale beyond `.btn`'s .98, red fill, or decorative colour. Danger is red text with a red hairline. - **Brand SVG file** (from `brand/`): paste it with `data-brand` on its `<svg>`; compose hides it and drops its title. The link round it needs `aria-label`. - **A dot between words** is `.dot-sep`, never an `aria-hidden` dot with a hidden comma; a value and its unit need a space between them (`--usage core`). +- **Export diagrams:** never hand-write `.drawio`, `.vsdx` or `.lucid`; author diagram JSON and run `basalt-diagram-export`. - 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, GithubLogo, XLogo, LinkedinLogo, InstagramLogo, YoutubeLogo, EnvelopeSimple, TerminalWindow. Check, close, chevrons, copy, plus, minus, search: core glyphs (`data-glyph`), not icons. A script that names one writes it as a quoted string (`icon: 'Trash'`). Need another icon? Add its name to tools/html-skill/src/icons.json and rebuild. Never draw one, never use an emoji. diff --git a/.agent/skills/basalt-html/parts/usage/diagram.md b/.agent/skills/basalt-html/parts/usage/diagram.md index e50d6a93..3dff1cd9 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram.md +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -27,3 +27,4 @@ Boxes and the lines between them. `compose.mjs` writes the figure's words into t - **Run:** `"run": true` on a sequence adds "Play the run", a dot through every message. - **Mark:** `"mark": "aws-ecs-service"` on an architecture node, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: `<!-- 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`. diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index e50d6a93..3dff1cd9 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -27,3 +27,4 @@ Boxes and the lines between them. `compose.mjs` writes the figure's words into t - **Run:** `"run": true` on a sequence adds "Play the run", a dot through every message. - **Mark:** `"mark": "aws-ecs-service"` on an architecture node, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: `<!-- 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`. From 394707ee6a7ff4bb999f18c58dbddfaf078a8592 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:14 -0600 Subject: [PATCH 03/19] Diagram interop: tests, official mxfile-1.0.xsd fixture and packed-package checks - Add packages/react/test/diagram-interop.test.mjs covering all five CIMIP fixtures across .drawio, .vsdx and .lucid: byte-identical SHA-256 determinism, mxfile-1.0.xsd validation, Visio OPC parts / Connects glue / ConFixedCode=2, Lucid Standard Import JSON contract, exact port axis-alignment (including the RunTask L-bend invariant), live Chromium exportMeasuredDiagram, manifest mark terms, CLI inputs, and subpath isolation. - Extend scripts/verify-packages.mjs to verify dist/diagram-interop.{js,d.ts}, bin/basalt-diagram-export.mjs, TypeScript types and runtime smoke checks in an external packed consumer. Co-Authored-By: Gemini 4 Neon <noreply@google.com> --- packages/react/test/diagram-interop.test.mjs | 646 ++++++++++++++++++ packages/react/test/fixtures/mxfile-1.0.xsd | 671 +++++++++++++++++++ scripts/verify-packages.mjs | 7 +- 3 files changed, 1323 insertions(+), 1 deletion(-) create mode 100644 packages/react/test/diagram-interop.test.mjs create mode 100644 packages/react/test/fixtures/mxfile-1.0.xsd diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs new file mode 100644 index 00000000..4a522880 --- /dev/null +++ b/packages/react/test/diagram-interop.test.mjs @@ -0,0 +1,646 @@ +// Tests for @srasyndicate/basalt/diagram-interop and basalt-diagram-export CLI (DECISIONS 311, 314). +// Covers: +// - Byte-identical SHA-256 determinism for all 5 CIMIP fixtures across .drawio, .vsdx, .lucid and Lucid JSON +// - Official draw.io XSD validation (mxfile-1.0.xsd) across all 5 figures and light/dark/adaptive themes +// - Visio .vsdx OPC parts, XML well-formedness, Connects glue, ConFixedCode=2, and zero-drift port snapping +// - Lucid Standard Import JSON contract (containers, swimLanes, tables, lineEndpoints, elbowControlPoints, labels) +// - Exact port axis-alignment invariant for every first and last segment (fixes the RunTask jog) across all 5 figures x 3 formats +// - Live DOM measured Geo entry (exportMeasuredDiagram + readMeasuredExtras) on all 5 CIMIP React figures +// - Mark terms policy against packages/react/marks/manifest.json (default omit; embed only manifest-permitted marks) +// - CLI end-to-end (single JSON, multi-diagram JSON, HTML script[data-diagram], flags, errors) +// - Subpath isolation (outside root index, no "use client", no React/third-party deps) +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import crypto from "node:crypto"; +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"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(pkg, "..", ".."); +const CIMIP = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams.json"), "utf8")); +const CIMIP_KEYS = Object.keys(CIMIP); +const XSD = path.join(here, "fixtures", "mxfile-1.0.xsd"); +const CLI = path.join(pkg, "bin", "basalt-diagram-export.mjs"); +const interop = await import(pathToFileURL(path.join(pkg, "dist", "diagram-interop.js")).href); + +const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex"); + +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). */ +function readZipEntries(bytes) { + const buf = Buffer.from(bytes); + // Find EOCD + 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; +} + +function expectedEdgeCount(spec) { + if (spec.type === "sequence") return spec.steps.filter((s) => !("band" in s)).length; + 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 target = byName.get(c.references.split(".")[0]); + if (target && Math.abs(target.col - t.col) <= 1) n++; + } + } + return n; + } + return spec.edges.length; +} + +function expectedLabelCount(spec) { + if (spec.type === "sequence") return spec.steps.filter((s) => !("band" in s)).length; + if (spec.type === "schema") return 0; + return spec.edges.filter((e) => Boolean(e.label)).length; +} + +/** Verifies every segment in `pts` is orthogonal and first/last segments are axis-aligned with `start` and `end`. */ +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, labels, and port axis-alignment. */ +function assertValidDrawio(xml, spec, context) { + assert.ok(!xml.includes("<!--"), `${context}: no XML comments allowed in draw.io`); + const xsd = xmllint(xml, XSD); + assert.ok(xsd.ok, `${context}: mxfile-1.0.xsd failed: ${xsd.stderr}`); + + // Parse all mxCell elements and their mxGeometry + const cellBlocks = [...xml.matchAll(/<mxCell\b([^>]*?)(?:\/>|>([\s\S]*?)<\/mxCell>)/g)]; + const vertices = new Map(); + const edges = []; + const edgeLabels = []; + + const attr = (s, name) => s.match(new RegExp(`\\b${name}="([^"]*)"`))?.[1]; + const styleVal = (style, key) => style.match(new RegExp(`(?:^|;)${key}=([^;]+)`))?.[1]; + + for (const [, attrs, body = ""] of cellBlocks) { + const id = attr(attrs, "id"); + const parent = attr(attrs, "parent"); + const style = attr(attrs, "style") ?? ""; + const isVertex = attr(attrs, "vertex") === "1"; + const isEdge = attr(attrs, "edge") === "1"; + if (isVertex) { + const geoAttrs = body.match(/<mxGeometry\b([^>]*)/)?.[1] ?? ""; + const isEdgeLabel = style.includes("edgeLabel"); + if (isEdgeLabel) { + edgeLabels.push({ id, parent, value: attr(attrs, "value") ?? "" }); + } else { + vertices.set(id, { + id, + parent, + x: Number(attr(geoAttrs, "x") ?? 0), + y: Number(attr(geoAttrs, "y") ?? 0), + w: Number(attr(geoAttrs, "width") ?? 0), + h: Number(attr(geoAttrs, "height") ?? 0), + style, + }); + } + } else if (isEdge) { + const pts = [...body.matchAll(/<mxPoint\b([^>]*)\/>/g)] + .filter((m) => !attr(m[1], "as")) + .map((m) => ({ x: Number(attr(m[1], "x")), y: Number(attr(m[1], "y")) })); + edges.push({ + id, + parent, + source: attr(attrs, "source"), + target: attr(attrs, "target"), + style, + innerPts: pts, + }); + } + } + + // Compute world box of any vertex by walking parent chain + const worldBox = (id) => { + const v = vertices.get(id); + assert.ok(v, `${context}: missing vertex ${id}`); + let x = v.x, y = v.y, cur = v.parent; + while (cur && cur !== "1" && cur !== "0") { + const p = vertices.get(cur); + assert.ok(p, `${context}: missing parent container ${cur}`); + x += p.x; + y += p.y; + cur = p.parent; + } + return { x, y, w: v.w, h: v.h }; + }; + + assert.equal(edges.length, expectedEdgeCount(spec), `${context}: exact single connector count`); + + const labelParents = new Set(edgeLabels.map((l) => l.parent)); + const expectedLabels = expectedLabelCount(spec); + assert.ok(labelParents.size >= expectedLabels, `${context}: ${labelParents.size} labelled edges < ${expectedLabels} expected`); + for (const l of edgeLabels) { + assert.ok(edges.some((e) => e.id === l.parent), `${context}: edgeLabel ${l.id} parent ${l.parent} must be an edge`); + } + + for (const e of edges) { + assert.ok(e.source && e.target, `${context}: edge ${e.id} must be glued to source and target`); + const sb = worldBox(e.source); + const tb = worldBox(e.target); + const ex = Number(styleVal(e.style, "exitX")); + const ey = Number(styleVal(e.style, "exitY")); + const nx = Number(styleVal(e.style, "entryX")); + const ny = Number(styleVal(e.style, "entryY")); + assert.ok(Number.isFinite(ex) && Number.isFinite(ey) && Number.isFinite(nx) && Number.isFinite(ny), + `${context}: edge ${e.id} missing explicit fractional port coordinates`); + assert.equal(styleVal(e.style, "exitPerimeter"), "0", `${context}: edge ${e.id} exitPerimeter=0`); + assert.equal(styleVal(e.style, "entryPerimeter"), "0", `${context}: edge ${e.id} entryPerimeter=0`); + const start = { x: sb.x + ex * sb.w, y: sb.y + ey * sb.h }; + const end = { x: tb.x + nx * tb.w, y: tb.y + ny * tb.h }; + assertAxisAlignedRoute([start, ...e.innerPts, end], start, end, 0.02, `${context} drawio ${e.id}`); + } +} + +/** Parses and validates Visio .vsdx OPC archive, XML well-formedness, glue, ConFixedCode=2, and Visio-inch port alignment. */ +function assertValidVsdx(bytes, spec, context) { + const entries = readZipEntries(bytes); + const required = [ + "[Content_Types].xml", + "_rels/.rels", + "visio/document.xml", + "visio/_rels/document.xml.rels", + "visio/pages/pages.xml", + "visio/pages/_rels/pages.xml.rels", + "visio/pages/page1.xml", + ]; + for (const name of required) { + assert.ok(entries.has(name), `${context}: missing OPC part ${name}`); + const check = xmllint(entries.get(name).toString("utf8")); + assert.ok(check.ok, `${context}: invalid XML in ${name}: ${check.stderr}`); + } + + const page1 = entries.get("visio/pages/page1.xml").toString("utf8"); + // Extract top-level <Shape> blocks cleanly even when a Type="Group" contains nested <Shape> children. + const topShapes = []; + const tagRe = /<Shape\b([^>]*)>|<\/Shape>/g; + let depth = 0, startIdx = -1, openEnd = -1, openAttrs = ""; + for (const m of page1.matchAll(tagRe)) { + if (m[0].startsWith("</Shape")) { + depth--; + if (depth === 0 && startIdx >= 0) { + topShapes.push({ attrs: openAttrs, body: page1.slice(openEnd, m.index) }); + startIdx = -1; + } + } else { + if (depth === 0) { + startIdx = m.index; + openEnd = m.index + m[0].length; + openAttrs = m[1] ?? ""; + } + depth++; + } + } + const byId = new Map(); + const connectors = []; + + const attrVal = (s, name) => s.match(new RegExp(`\\b${name}="([^"]+)"`))?.[1]; + const cellVal = (body, name) => body.match(new RegExp(`<Cell N="${name}" V="([^"]+)"`))?.[1]; + const cellFormula = (body, name) => body.match(new RegExp(`<Cell N="${name}"[^>]*F="([^"]+)"`))?.[1]; + + for (const { attrs, body } of topShapes) { + const id = attrVal(attrs, "ID"); + const nameU = attrVal(attrs, "NameU") ?? ""; + // Only inspect cells/connections belonging directly to the top-level shape (before any nested <Shapes>) + const ownBody = body.split("<Shapes>")[0] ?? body; + const objType = cellVal(ownBody, "ObjType"); + const conns = [...ownBody.matchAll(/<Row T="Connection" IX="(\d+)">[\s\S]*?<Cell N="X" V="([^"]+)"[\s\S]*?<Cell N="Y" V="([^"]+)"/g)] + .map((m) => ({ ix: Number(m[1]), x: Number(m[2]), y: Number(m[3]) })); + const rec = { + id, + nameU, + objType, + pinX: Number(cellVal(ownBody, "PinX")), + pinY: Number(cellVal(ownBody, "PinY")), + w: Number(cellVal(ownBody, "Width")), + h: Number(cellVal(ownBody, "Height")), + locPinX: Number(cellVal(ownBody, "LocPinX")), + locPinY: Number(cellVal(ownBody, "LocPinY")), + conns, + body: ownBody, + }; + byId.set(id, rec); + if (objType === "2") connectors.push(rec); + } + + const connects = [...page1.matchAll(/<Connect FromSheet="(\d+)" FromCell="([^"]+)" FromPart="(\d+)" ToSheet="(\d+)" ToCell="([^"]+)" ToPart="(\d+)"\/>/g)] + .map((m) => ({ fromSheet: m[1], fromCell: m[2], fromPart: Number(m[3]), toSheet: m[4], toCell: m[5], toPart: Number(m[6]) })); + + assert.equal(connectors.length, expectedEdgeCount(spec), `${context}: exact single 1-D connector count`); + assert.equal(connects.length, connectors.length * 2, `${context}: 2 Connect records per connector`); + + let labelledCount = 0; + for (const c of connectors) { + assert.equal(cellVal(c.body, "ShapeRouteStyle"), "1", `${context} ${c.nameU}: ShapeRouteStyle=1`); + assert.equal(cellVal(c.body, "ConFixedCode"), "2", `${context} ${c.nameU}: ConFixedCode=2`); + if (c.body.includes("<Text>")) labelledCount++; + + const beginConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 9); + const endConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 12); + assert.ok(beginConn && endConn, `${context} ${c.nameU}: missing Begin/End Connect elements`); + assert.match(cellFormula(c.body, "BeginX") ?? "", new RegExp(`Sheet\\.${beginConn.toSheet}!Connections\\.X${beginConn.toPart - 99}\\b`)); + assert.match(cellFormula(c.body, "EndX") ?? "", new RegExp(`Sheet\\.${endConn.toSheet}!Connections\\.X${endConn.toPart - 99}\\b`)); + + const fromShape = byId.get(beginConn.toSheet); + const toShape = byId.get(endConn.toSheet); + assert.ok(fromShape && toShape, `${context} ${c.nameU}: glued shapes exist`); + const fc = fromShape.conns.find((r) => r.ix === beginConn.toPart - 100); + const tc = toShape.conns.find((r) => r.ix === endConn.toPart - 100); + assert.ok(fc && tc, `${context} ${c.nameU}: Connection rows exist for ToPart`); + + const startPort = { + x: fromShape.pinX - fromShape.locPinX + fc.x, + y: fromShape.pinY - fromShape.locPinY + fc.y, + }; + const endPort = { + x: toShape.pinX - toShape.locPinX + tc.x, + y: toShape.pinY - toShape.locPinY + tc.y, + }; + const bx = Number(cellVal(c.body, "BeginX")); + const by = Number(cellVal(c.body, "BeginY")); + const ex = Number(cellVal(c.body, "EndX")); + const ey = Number(cellVal(c.body, "EndY")); + assert.ok(Math.abs(bx - startPort.x) <= 2e-6 && Math.abs(by - startPort.y) <= 2e-6, + `${context} ${c.nameU}: Begin (${bx},${by}) != Connection (${startPort.x},${startPort.y})`); + assert.ok(Math.abs(ex - endPort.x) <= 2e-6 && Math.abs(ey - endPort.y) <= 2e-6, + `${context} ${c.nameU}: End (${ex},${ey}) != Connection (${endPort.x},${endPort.y})`); + + const geomRows = [...c.body.matchAll(/<Row T="(MoveTo|LineTo)" IX="\d+"><Cell N="X" V="([^"]+)"\/><Cell N="Y" V="([^"]+)"\/><\/Row>/g)] + .map((m) => ({ x: bx + Number(m[2]), y: by + Number(m[3]) })); + assertAxisAlignedRoute(geomRows, startPort, endPort, 2e-5, `${context} vsdx ${c.nameU}`); + } + assert.equal(labelledCount, expectedLabelCount(spec), `${context}: all labelled edges have connector <Text>`); +} + +/** Validates Lucid Standard Import ZIP + document.json contract and port axis-alignment. */ +function assertValidLucid(bytes, spec, context) { + const entries = readZipEntries(bytes); + assert.ok(entries.has("document.json"), `${context}: .lucid must contain document.json at root`); + const doc = JSON.parse(entries.get("document.json").toString("utf8")); + assert.equal(doc.version, 1, `${context}: version === 1`); + assert.equal(doc.documentSettings?.units, "px", `${context}: units === px`); + assert.equal(doc.pages.length, 1, `${context}: 1 page`); + const page = doc.pages[0]; + assert.ok(page.settings.size.w > 0 && page.settings.size.h > 0, `${context}: positive canvas size`); + + const shapeById = new Map(page.shapes.map((s) => [s.id, s])); + const lineById = new Map(page.lines.map((l) => [l.id, l])); + + if (spec.type === "architecture" && spec.groups?.length) { + const containers = page.shapes.filter((s) => s.type === "roundedRectangleContainer"); + assert.equal(containers.length, spec.groups.length, `${context}: group container count`); + for (const c of containers) { + assert.equal(c.assistedLayout, false, `${context}: assistedLayout must be false`); + assert.equal(c.magnetize, true, `${context}: magnetize must be true`); + } + } + if (spec.type === "data-flow") { + const sw = page.shapes.find((s) => s.type === "swimLanes"); + assert.ok(sw, `${context}: data-flow emits swimLanes`); + assert.equal(sw.vertical, false, `${context}: horizontal swimLanes`); + assert.equal(sw.lanes.length, spec.lanes.length, `${context}: lane count`); + const sum = sw.lanes.reduce((a, l) => a + l.width, 0); + assert.ok(Math.abs(sum - sw.boundingBox.h) <= 0.1, `${context}: lane widths (${sum}) sum to boundingBox.h (${sw.boundingBox.h})`); + } + if (spec.type === "schema") { + const tables = page.shapes.filter((s) => s.type === "table"); + assert.equal(tables.length, spec.tables.length, `${context}: native table count`); + for (const t of tables) assert.equal(t.verticalBorder, false, `${context}: verticalBorder false`); + } + if (spec.type === "flowchart") { + assert.ok(page.shapes.some((s) => s.type === "decision"), `${context}: flowchart decision shape`); + assert.ok(page.shapes.some((s) => s.type === "terminator"), `${context}: flowchart terminator shape`); + } + + const edgeLines = page.lines.filter((l) => l.id.startsWith("edge_")); + assert.equal(edgeLines.length, expectedEdgeCount(spec), `${context}: exact single connector count`); + + const endpointPt = (ep) => { + if (ep.type === "shapeEndpoint") { + const s = shapeById.get(ep.shapeId); + assert.ok(s, `${context}: endpoint shapeId ${ep.shapeId} exists`); + 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 targetLine = lineById.get(ep.lineId); + assert.ok(targetLine, `${context}: endpoint lineId ${ep.lineId} exists`); + const p1 = endpointPt(targetLine.endpoint1); + const p2 = endpointPt(targetLine.endpoint2); + return { x: p1.x + ep.position * (p2.x - p1.x), y: p1.y + ep.position * (p2.y - p1.y) }; + } + return ep.position; + }; + + let labelled = 0; + for (const line of edgeLines) { + assert.ok(line.endpoint1.type === "shapeEndpoint" || line.endpoint1.type === "lineEndpoint", `${context} ${line.id}: endpoint1 glued`); + assert.ok(line.endpoint2.type === "shapeEndpoint" || line.endpoint2.type === "lineEndpoint", `${context} ${line.id}: endpoint2 glued`); + if (spec.type === "schema") assert.equal(line.endpoint1.style, "closedCircle", `${context} ${line.id}: FK dot`); + if (line.text?.length) labelled++; + const start = endpointPt(line.endpoint1); + const end = endpointPt(line.endpoint2); + const pts = [start, ...(line.elbowControlPoints ?? []), end]; + assertAxisAlignedRoute(pts, start, end, 0.02, `${context} lucid ${line.id}`); + } + assert.equal(labelled, expectedLabelCount(spec), `${context}: all labelled edges carry Line.text`); +} + +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, and zero-jog Visio-inch port alignment`, () => { + for (const theme of ["light", "dark"]) { + const bytes = interop.diagramToVsdx(spec, { theme }); + assertValidVsdx(bytes, spec, `${key}/${theme}`); + } + }); + + test(`${key}: .lucid Standard Import JSON contract and Lucid-unit port alignment`, () => { + for (const theme of ["light", "dark"]) { + const bytes = interop.diagramToLucid(spec, { theme }); + assertValidLucid(bytes, spec, `${key}/${theme}`); + } + }); + } + + test("architecture RunTask (svc -> ecs) in .vsdx is a clean 3-point L-bend with 0.000000 in port delta", () => { + const entries = readZipEntries(interop.diagramToVsdx(CIMIP.architecture)); + const page1 = entries.get("visio/pages/page1.xml").toString("utf8"); + const runTask = page1.match(/<Shape ID="\d+" NameU="Connector_4"[^>]*>([\s\S]*?)<\/Shape>/)?.[1]; + assert.ok(runTask, "Connector_4 (RunTask) present"); + const rows = [...runTask.matchAll(/<Row T="(MoveTo|LineTo)" IX="\d+"><Cell N="X" V="([^"]+)"\/><Cell N="Y" V="([^"]+)"\/><\/Row>/g)]; + assert.equal(rows.length, 3, "RunTask has exactly 3 geometry vertices (no extra joining jog)"); + assert.equal(rows[0][2], "0.000000", "MoveTo X === 0"); + assert.equal(rows[0][3], "0.000000", "MoveTo Y === 0"); + assert.equal(rows[1][2], "0.000000", "first bend stays strictly on X === 0 (no horizontal jog below cimip service)"); + assert.equal(rows[1][3], rows[2][3], "final leg stays strictly horizontal into ECS"); + }); +}); + +describe("live DOM measured Geo entry (exportMeasuredDiagram)", () => { + test("exports all five CIMIP figures from live Chromium-measured Geo with exact port alignment across all formats", async () => { + const HOST = ` + import data from "./test/fixtures/cimip-diagrams.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 }; + function Host() { + return <main style={{ maxWidth: 1104, margin: "0 auto", padding: 16, display: "grid", gap: 64 }}> + {Object.entries(data).map(([key, d]) => { const X = C[d.type]; const { type, ...props } = d; return <X key={key} id={"fig-" + key} {...props} />; })} + </main>; + } + createRoot(document.getElementById("root")).render(<Host />); + window.__measureAll = () => { + const out = {}; + for (const [key, spec] of Object.entries(data)) { + const fig = document.getElementById("fig-" + key); + const model = buildModel(spec, { checks: false }); + const base = (fig.getAttribute("aria-labelledby") || "dg").replace(/-title$/, ""); + const opts = { prefix: "basalt-diagram", base, hasSource: Boolean(spec.source), hiddenClass: "basalt-visually-hidden" }; + const res = measureFigure(fig, model, "basalt-diagram", base, { layout: "drawn" }, (d) => syncAttributes(fig, figureTree(model, d, opts))); + out[key] = { geo: res.geo, extras: readMeasuredExtras(fig, "basalt-diagram") }; + } + 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} body{margin:0;background:var(--basalt-surface-page)}`; + + 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(() => document.fonts.ready); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))))); + const measured = await page.evaluate(() => window.__measureAll()); + assert.deepEqual(errors, []); + for (const key of CIMIP_KEYS) { + const { geo, extras } = measured[key]; + assert.ok(geo && geo.lines.length > 0, `${key}: live Geo measured`); + const drawio = interop.exportMeasuredDiagram(CIMIP[key], geo, "drawio", { extras }); + const vsdx = interop.exportMeasuredDiagram(CIMIP[key], geo, "vsdx", { extras }); + const lucid = interop.exportMeasuredDiagram(CIMIP[key], geo, "lucid", { extras }); + assertValidDrawio(drawio, CIMIP[key], `measured/${key}`); + assertValidVsdx(vsdx, CIMIP[key], `measured/${key}`); + assertValidLucid(lucid, CIMIP[key], `measured/${key}`); + } + await page.close(); + } finally { + await browser.close(); + } + }); +}); + +describe("service marks embedding policy (manifest terms)", () => { + 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 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); + 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: "br", name: "Bedrock", col: 3, row: 1, mark: "aws-bedrock" }, + { id: "gh", name: "GitHub", col: 4, row: 1, mark: "github" }, + ], + edges: [ + { from: "ecs", to: "k8s" }, + { from: "k8s", to: "br" }, + { from: "br", to: "gh" }, + ], + }; + + // Default: omit + 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); + + // Embed: only aws-ecs-service and kubernetes (NOT unofficial aws-bedrock or restricted github) + 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.doesNotMatch(drawioEmbed, /id="mark-br"/); + assert.doesNotMatch(drawioEmbed, /id="mark-gh"/); + + const vsdxEmbed = readZipEntries(interop.diagramToVsdx(spec, { marks: "embed", resolveMark })); + assert.equal([...vsdxEmbed.keys()].filter((k) => k.startsWith("visio/media/")).length, 2); + assert.ok(vsdxEmbed.has("visio/pages/_rels/page1.xml.rels")); + + const lucidEmbed = readZipEntries(interop.diagramToLucid(spec, { marks: "embed", resolveMark })); + assert.equal([...lucidEmbed.keys()].filter((k) => k.startsWith("images/")).length, 2); + }); +}); + +describe("basalt-diagram-export CLI", () => { + test("exports JSON map, single JSON, and HTML script[data-diagram] (ignoring comments/textarea decoys) deterministically", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "basalt-interop-cli-")); + try { + // 1. Multi-diagram JSON (all 5 CIMIP fixtures) + 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"), "--to", "drawio,vsdx,lucid", "--out", outA], { encoding: "utf8" }); + assert.equal(r1.status, 0, r1.stderr); + const r2 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--to", "drawio,vsdx,lucid", "--out", outB], { encoding: "utf8" }); + 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"]) { + 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: ${stem}${ext}`); + } + } + + // 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, `<!doctype html><html><body> + <!-- <figure class="diagram"><script type="application/json" data-diagram>${decoy}</script></figure> --> + <textarea><script type="application/json" data-diagram>${decoy}</script></textarea> + <figure class="diagram" id="fig-arch"><script type="application/json" data-diagram>${JSON.stringify(CIMIP.architecture)}</script></figure> + </body></html>`); + const htmlOut = path.join(dir, "from-html"); + const r3 = spawnSync(process.execPath, [CLI, htmlPath, "--to", "drawio,vsdx", "--theme", "adaptive", "--out", htmlOut], { encoding: "utf8" }); + assert.equal(r3.status, 0, r3.stderr); + const files = fs.readdirSync(htmlOut).sort(); + assert.deepEqual(files, ["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 + const singleJson = path.join(dir, "one.json"); + fs.writeFileSync(singleJson, JSON.stringify(CIMIP.flowchart)); + const exactOut = path.join(dir, "exact.drawio"); + const r4 = spawnSync(process.execPath, [CLI, singleJson, "--to", "drawio", "--out", exactOut], { encoding: "utf8" }); + assert.equal(r4.status, 0, r4.stderr); + assert.ok(fs.existsSync(exactOut)); + + // 4. Error handling on unknown format + const bad = spawnSync(process.execPath, [CLI, singleJson, "--to", "bogus"], { encoding: "utf8" }); + assert.notEqual(bad.status, 0); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("subpath isolation", () => { + test("@srasyndicate/basalt/diagram-interop stays outside the root index 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"]) { + 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"); + }); +}); 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 @@ +<?xml version="1.0" encoding="UTF-8"?> +<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" + elementFormDefault="unqualified"> + + <!-- + draw.io mxFile XML Schema + Version: 1.0 + + This schema describes the structure of draw.io / .drawio files. + It is intended for use by AI systems to validate generated diagram files. + + Notes: + - Style strings (e.g. "rounded=1;whiteSpace=wrap;html=1;") are typed as + xs:string. The style syntax is documented separately in + style-reference.md. + - mxCell is intentionally generic: vertex/edge/connectable determine the role. + - The first two mxCell elements in root are structural: id="0" (root container) + and id="1" (default layer). All diagram elements must reference these. + - IDs must be unique within a diagram. Any string is valid, but typically + short alphanumeric strings or numeric IDs are used. + - For compressed diagrams, the diagram element contains Base64-encoded, + deflate-compressed XML instead of an mxGraphModel child element. + - mxGeometry child elements (mxPoint, Array, mxRectangle) may appear in + any order. The schema uses xs:choice to reflect this flexibility. + + Companion document: style-reference.md + --> + + <!-- ================================================================== --> + <!-- Root: mxfile --> + <!-- ================================================================== --> + <xs:element name="mxfile" type="mxfileType" /> + + <xs:complexType name="mxfileType"> + <xs:annotation> + <xs:documentation> + 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"). + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element name="diagram" type="diagramType" maxOccurs="unbounded" /> + </xs:sequence> + <!-- Identifies the application that created/modified the file --> + <xs:attribute name="host" type="xs:string"> + <xs:annotation> + <xs:documentation>Host application identifier (e.g. "app.diagrams.net", "Electron").</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- ISO 8601 timestamp of last modification --> + <xs:attribute name="modified" type="xs:string"> + <xs:annotation> + <xs:documentation>ISO 8601 timestamp of last modification (e.g. "2024-01-15T10:30:00.000Z").</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- User agent string of the creating application --> + <xs:attribute name="agent" type="xs:string"> + <xs:annotation> + <xs:documentation>User agent or tool identifier that created the file.</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- draw.io application version --> + <xs:attribute name="version" type="xs:string"> + <xs:annotation> + <xs:documentation>draw.io application version (e.g. "24.7.6").</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- Entity tag for caching/sync --> + <xs:attribute name="etag" type="xs:string"> + <xs:annotation> + <xs:documentation>Entity tag for caching and synchronization.</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- Storage type: "device", "google", "dropbox", "onedrive", "github", "gitlab", "browser" --> + <xs:attribute name="type" type="xs:string"> + <xs:annotation> + <xs:documentation>Storage backend type. Common values: "device", "google", "dropbox", "onedrive", "github", "gitlab", "browser".</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- Whether diagram content is compressed --> + <xs:attribute name="compressed" type="booleanString" default="false"> + <xs:annotation> + <xs:documentation>If "true", diagram content is deflate-compressed and Base64-encoded. For AI generation, always use "false" (uncompressed XML).</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- Number of pages (informational, not enforced) --> + <xs:attribute name="pages" type="xs:string"> + <xs:annotation> + <xs:documentation>Number of diagram pages. Informational only; the actual count is determined by the number of diagram child elements.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- diagram: One page/tab in the diagram --> + <!-- ================================================================== --> + <xs:complexType name="diagramType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:choice> + <!-- Uncompressed: mxGraphModel as child element --> + <xs:element name="mxGraphModel" type="mxGraphModelType" /> + </xs:choice> + <!-- Unique identifier for this page (omitted in some older files) --> + <xs:attribute name="id" type="xs:string"> + <xs:annotation> + <xs:documentation>Unique identifier for this diagram page. Must be unique within the file.</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- Display name shown in the page tab --> + <xs:attribute name="name" type="xs:string"> + <xs:annotation> + <xs:documentation>Display name shown in the page tab. Defaults to "Page-N" if omitted.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- mxGraphModel: Canvas configuration and cells --> + <!-- ================================================================== --> + <xs:complexType name="mxGraphModelType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element name="root" type="rootType" /> + </xs:sequence> + + <!-- Canvas scroll offset (pixels) --> + <xs:attribute name="dx" type="xs:double"> + <xs:annotation> + <xs:documentation>Horizontal scroll offset in pixels. Typical default: 0 or based on content.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="dy" type="xs:double"> + <xs:annotation> + <xs:documentation>Vertical scroll offset in pixels.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Page dimensions --> + <xs:attribute name="pageWidth" type="xs:positiveInteger" default="850"> + <xs:annotation> + <xs:documentation>Page width in pixels. Common values: 850 (letter), 1169 (A4 landscape), 827 (A4 portrait).</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="pageHeight" type="xs:positiveInteger" default="1100"> + <xs:annotation> + <xs:documentation>Page height in pixels. Common values: 1100 (letter), 827 (A4 landscape), 1169 (A4 portrait).</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="pageScale" type="xs:double" default="1"> + <xs:annotation> + <xs:documentation>Page scale factor. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Grid --> + <xs:attribute name="grid" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Show grid. 1=visible, 0=hidden. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="gridSize" type="xs:positiveInteger" default="10"> + <xs:annotation> + <xs:documentation>Grid cell size in pixels. Default: 10.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Display options --> + <xs:attribute name="guides" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Enable alignment guides. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="tooltips" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Show tooltips on hover. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="connect" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Enable connection handles. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="arrows" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Show directional arrows on edges. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="fold" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Enable collapse/expand of containers. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="page" type="booleanInt" default="1"> + <xs:annotation> + <xs:documentation>Show page boundaries. Default: 1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="math" type="booleanInt" default="0"> + <xs:annotation> + <xs:documentation>Enable MathJax/LaTeX rendering in labels. Default: 0.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="shadow" type="booleanInt" default="0"> + <xs:annotation> + <xs:documentation>Global shadow for all shapes. Default: 0. Can be overridden per cell via style.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Background --> + <xs:attribute name="background" type="colorType"> + <xs:annotation> + <xs:documentation>Canvas background color as hex (e.g. "#FFFFFF") or "none" for transparent.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="backgroundImage" type="xs:string"> + <xs:annotation> + <xs:documentation>JSON object for background image: {"src":"url","width":w,"height":h}.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Color adaptation for light/dark mode --> + <xs:attribute name="adaptiveColors" type="xs:string"> + <xs:annotation> + <xs:documentation>Controls color adaptation for light/dark mode. Values: "auto", "simple", "none", "default".</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- root: Container for all mxCell elements --> + <!-- ================================================================== --> + <xs:complexType name="rootType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:choice maxOccurs="unbounded"> + <xs:element name="mxCell" type="mxCellType" /> + <xs:element name="UserObject" type="UserObjectType" /> + <xs:element name="object" type="UserObjectType" /> + </xs:choice> + </xs:sequence> + </xs:complexType> + + <!-- ================================================================== --> + <!-- mxCell: Universal element for vertices, edges, and layers --> + <!-- ================================================================== --> + <xs:complexType name="mxCellType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element name="mxGeometry" type="mxGeometryType" minOccurs="0" /> + </xs:sequence> + + <!-- + Identification: required for top-level mxCell elements, but optional + when mxCell is nested inside a UserObject/object (the parent element + carries the id in that case). + --> + <xs:attribute name="id" type="xs:string"> + <xs:annotation> + <xs: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.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="parent" type="xs:string"> + <xs:annotation> + <xs:documentation>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").</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Content --> + <xs:attribute name="value" type="xs:string"> + <xs:annotation> + <xs:documentation>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.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="style" type="xs:string"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Type flags (determine the cell's role) --> + <xs:attribute name="vertex" type="booleanInt"> + <xs:annotation> + <xs:documentation>Set to "1" for shape/vertex cells. Mutually exclusive with edge="1".</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="edge" type="booleanInt"> + <xs:annotation> + <xs:documentation>Set to "1" for connector/edge cells. Mutually exclusive with vertex="1". Should have source and/or target attributes.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="connectable" type="booleanInt"> + <xs:annotation> + <xs:documentation>Whether the cell can be connected to. Default: "1" for vertices, "0" for edges. Set to "0" to prevent connections.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Edge connections (only when edge="1") --> + <xs:attribute name="source" type="xs:string"> + <xs:annotation> + <xs:documentation>ID of the source vertex for edges. Must reference a valid vertex id in the same diagram.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="target" type="xs:string"> + <xs:annotation> + <xs:documentation>ID of the target vertex for edges. Must reference a valid vertex id in the same diagram.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Container state --> + <xs:attribute name="collapsed" type="booleanInt"> + <xs:annotation> + <xs:documentation>Whether the container/group is collapsed. Only meaningful for container cells.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="visible" type="booleanInt"> + <xs:annotation> + <xs:documentation>Whether the cell is visible. "0" = hidden, "1" = visible. Default: "1".</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- UserObject / object: Wrapper for custom attributes --> + <!-- ================================================================== --> + <xs:complexType name="UserObjectType"> + <xs:annotation> + <xs:documentation> + 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> + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element name="mxCell" type="mxCellType" /> + </xs:sequence> + + <!-- Standard attributes --> + <xs:attribute name="id" type="xs:string" use="required"> + <xs:annotation> + <xs:documentation>Unique identifier (same role as mxCell id). The nested mxCell should NOT have its own id.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="label" type="xs:string"> + <xs:annotation> + <xs:documentation>Display label text (replaces mxCell value). Supports HTML when style includes html=1.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="link" type="xs:string"> + <xs:annotation> + <xs:documentation>Hyperlink URL. Opens when the cell is clicked in the viewer.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="tags" type="xs:string"> + <xs:annotation> + <xs:documentation>Space-separated tags for filtering/categorization.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="tooltip" type="xs:string"> + <xs:annotation> + <xs:documentation>Tooltip text displayed on hover.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="placeholders" type="booleanInt"> + <xs:annotation> + <xs:documentation>Enable placeholder substitution in labels. When "1", %attribute% in the label is replaced with attribute values.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- + UserObject allows arbitrary additional attributes for custom metadata. + XSD supports this via anyAttribute: + --> + <xs:anyAttribute processContents="lax" /> + </xs:complexType> + + <!-- ================================================================== --> + <!-- mxGeometry: Position, size, and control points --> + <!-- ================================================================== --> + <xs:complexType name="mxGeometryType"> + <xs:annotation> + <xs:documentation> + 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 + </xs:documentation> + </xs:annotation> + <xs:choice minOccurs="0" maxOccurs="unbounded"> + <!-- Source/target points for edges, offset points for labels --> + <xs:element name="mxPoint" type="mxPointType" /> + <!-- Waypoints for edges --> + <xs:element name="Array" type="ArrayType" /> + <!-- Alternate bounds for collapsible containers (swimlanes) --> + <xs:element name="mxRectangle" type="mxRectangleType" /> + </xs:choice> + + <!-- Position (for vertices: absolute, for edges with relative=1: relative) --> + <xs:attribute name="x" type="xs:double"> + <xs:annotation> + <xs:documentation> + 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). + </xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="y" type="xs:double"> + <xs:annotation> + <xs:documentation> + For vertices: y-coordinate of top-left corner (pixels, relative to parent). + For edges with relative="1": perpendicular offset in pixels. + </xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Size (primarily for vertices) --> + <xs:attribute name="width" type="xs:double"> + <xs:annotation> + <xs:documentation>Width in pixels. Required for vertices. Typical values: 80-200.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="height" type="xs:double"> + <xs:annotation> + <xs:documentation>Height in pixels. Required for vertices. Typical values: 40-120.</xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- + relative="1" for edges: coordinates are relative along the edge path. + Used for label positioning on edges. + --> + <xs:attribute name="relative" type="booleanInt"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + </xs:attribute> + + <!-- Type marker (always "geometry") --> + <xs:attribute name="as" type="xs:string" fixed="geometry"> + <xs:annotation> + <xs:documentation>Always "geometry". Identifies this element as the cell's geometry property.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- mxPoint: A single point (source/target/offset) --> + <!-- ================================================================== --> + <xs:complexType name="mxPointType"> + <xs:annotation> + <xs:documentation> + 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 + </xs:documentation> + </xs:annotation> + <xs:attribute name="x" type="xs:double"> + <xs:annotation> + <xs:documentation>X coordinate in pixels.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="y" type="xs:double"> + <xs:annotation> + <xs:documentation>Y coordinate in pixels.</xs:documentation> + </xs:annotation> + </xs:attribute> + <!-- as="sourcePoint" | "targetPoint" | "offset" --> + <xs:attribute name="as" type="mxPointAsType"> + <xs:annotation> + <xs:documentation>Point role: "sourcePoint", "targetPoint", or "offset".</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- Array: List of points (waypoints for edges) --> + <!-- ================================================================== --> + <xs:complexType name="ArrayType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:sequence> + <xs:element name="mxPoint" type="mxPointType" minOccurs="0" maxOccurs="unbounded" /> + </xs:sequence> + <!-- as="points" for waypoints --> + <xs:attribute name="as" type="xs:string" fixed="points"> + <xs:annotation> + <xs:documentation>Always "points". Identifies this array as the edge's waypoint list.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- mxRectangle: Alternate bounds for collapsible containers --> + <!-- ================================================================== --> + <xs:complexType name="mxRectangleType"> + <xs:annotation> + <xs:documentation> + 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. + </xs:documentation> + </xs:annotation> + <xs:attribute name="x" type="xs:double"> + <xs:annotation> + <xs:documentation>X coordinate of the alternate bounds.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="y" type="xs:double"> + <xs:annotation> + <xs:documentation>Y coordinate of the alternate bounds.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="width" type="xs:double"> + <xs:annotation> + <xs:documentation>Width of the alternate bounds.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="height" type="xs:double"> + <xs:annotation> + <xs:documentation>Height of the alternate bounds.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="as" type="xs:string" fixed="alternateBounds"> + <xs:annotation> + <xs:documentation>Always "alternateBounds". Identifies this as the cell's alternate geometry.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:complexType> + + <!-- ================================================================== --> + <!-- Helper types --> + <!-- ================================================================== --> + + <!-- draw.io uses "0"/"1" instead of true/false for most boolean values --> + <xs:simpleType name="booleanInt"> + <xs:annotation> + <xs:documentation>Boolean as integer: "0" = false, "1" = true. This is the standard boolean format in draw.io.</xs:documentation> + </xs:annotation> + <xs:restriction base="xs:string"> + <xs:enumeration value="0" /> + <xs:enumeration value="1" /> + </xs:restriction> + </xs:simpleType> + + <!-- Some attributes use "true"/"false" as strings --> + <xs:simpleType name="booleanString"> + <xs:annotation> + <xs:documentation>Boolean as string: "true" or "false". Used only for mxfile-level attributes like "compressed".</xs:documentation> + </xs:annotation> + <xs:restriction base="xs:string"> + <xs:enumeration value="true" /> + <xs:enumeration value="false" /> + </xs:restriction> + </xs:simpleType> + + <!-- Color type: hex color, "none", or "default" --> + <xs:simpleType name="colorType"> + <xs:annotation> + <xs:documentation> + 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 + </xs:documentation> + </xs:annotation> + <xs:restriction base="xs:string"> + <xs:pattern value="(#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?|none|default)" /> + </xs:restriction> + </xs:simpleType> + + <!-- Valid values for mxPoint "as" attribute --> + <xs:simpleType name="mxPointAsType"> + <xs:annotation> + <xs:documentation>Valid roles for mxPoint: sourcePoint, targetPoint, or offset.</xs:documentation> + </xs:annotation> + <xs:restriction base="xs:string"> + <xs:enumeration value="sourcePoint" /> + <xs:enumeration value="targetPoint" /> + <xs:enumeration value="offset" /> + </xs:restriction> + </xs:simpleType> + +</xs:schema> diff --git a/scripts/verify-packages.mjs b/scripts/verify-packages.mjs index b8401dce..fabe2f09 100644 --- a/scripts/verify-packages.mjs +++ b/scripts/verify-packages.mjs @@ -21,7 +21,7 @@ try { archives.push(path.join(out, packed.filename)); packedPackages.push({ packed, manifest: JSON.parse(fs.readFileSync(path.join(repo, workspace, "package.json"), "utf8")) }); const files = new Set(packed.files.map((file) => file.path)); - for (const required of workspace.endsWith("react") ? ["dist/index.js", "dist/index.d.ts", "dist/testing/headroom.js", "dist/testing/headroom.d.ts", "dist/tooling/phosphor.js", "dist/tooling/phosphor.d.ts", "dist/tooling/imports.js", "dist/tooling/imports.d.ts", "dist/head/theme.js", "dist/head/loops.js", "dist/styles.css", "dist/fonts.css", "dist/fonts/OFL.txt", "dist/fonts/Geist-Variable.woff2", "dist/fonts/GeistMono-Variable.woff2", "dist/marks/aws-ecs-service.js", "dist/marks/aws-ecs-service.d.ts", "THIRD-PARTY-MARKS.md"] : ["dist/css/tokens.css", "dist/css/accents.css", "dist/css/shadcn.css", "dist/js/tokens.js", "dist/js/tokens.d.ts", "dist/js/breakpoints.js", "dist/js/durations.js", "dist/js/durations.d.ts", "dist/json/tokens.json"]) assert.ok(files.has(required), `${packed.name} is missing ${required}`); + for (const required of workspace.endsWith("react") ? ["dist/index.js", "dist/index.d.ts", "dist/testing/headroom.js", "dist/testing/headroom.d.ts", "dist/tooling/phosphor.js", "dist/tooling/phosphor.d.ts", "dist/tooling/imports.js", "dist/tooling/imports.d.ts", "dist/diagram-interop.js", "dist/diagram-interop.d.ts", "bin/basalt-diagram-export.mjs", "dist/head/theme.js", "dist/head/loops.js", "dist/styles.css", "dist/fonts.css", "dist/fonts/OFL.txt", "dist/fonts/Geist-Variable.woff2", "dist/fonts/GeistMono-Variable.woff2", "dist/marks/aws-ecs-service.js", "dist/marks/aws-ecs-service.d.ts", "THIRD-PARTY-MARKS.md"] : ["dist/css/tokens.css", "dist/css/accents.css", "dist/css/shadcn.css", "dist/js/tokens.js", "dist/js/tokens.d.ts", "dist/js/breakpoints.js", "dist/js/durations.js", "dist/js/durations.d.ts", "dist/json/tokens.json"]) assert.ok(files.has(required), `${packed.name} is missing ${required}`); } // Next.js is in the lockfile (geist's peer), so the server-component check below installs the version the repository already resolves, offline. const nextVersion = JSON.parse(fs.readFileSync(path.join(repo, "package-lock.json"), "utf8")).packages["node_modules/next"].version; @@ -40,6 +40,7 @@ try { run("npm", ["ci", "--offline", "--ignore-scripts", "--no-audit", "--no-fund"], consumer); fs.writeFileSync(path.join(consumer, "index.tsx"), `import { Form, Field, Input, Combobox, Slider, Button, Sheet, Text, MorphIcon, CloseGlyph, Stage, PairedArt, FramedArt, type TableDensity } from '@srasyndicate/basalt'; import { checkHeadroom, type HeadroomResult } from '@srasyndicate/basalt/testing'; +import { diagramToDrawio, diagramToVsdx, diagramToLucid, diagramToLucidJson, exportMeasuredDiagram, type InteropOptions } from '@srasyndicate/basalt/diagram-interop'; import { BASALT_PHOSPHOR_WEIGHTS, phosphorWeightsEsbuild, phosphorWeightsRollup, type PhosphorWeight } from '@srasyndicate/basalt/phosphor'; import { PlayIcon } from '@phosphor-icons/react'; import { tokens } from '@srasyndicate/basalt-tokens'; @@ -59,6 +60,9 @@ const check: Promise<HeadroomResult> = checkHeadroom({ newContext: async () => { // The opt-in Phosphor weights plugin is build tooling with its own types; the weight list is required. const weights: readonly PhosphorWeight[] = [...BASALT_PHOSPHOR_WEIGHTS, 'regular']; const plugins = [phosphorWeightsEsbuild({ weights }), phosphorWeightsRollup({ weights })]; +const interopOpts: InteropOptions = { theme: 'adaptive', marks: 'omit' }; +const sampleArch = { type: 'architecture' as const, title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }; +const interopChecks: [string, Uint8Array, Uint8Array, number, typeof exportMeasuredDiagram] = [diagramToDrawio(sampleArch, interopOpts), diagramToVsdx(sampleArch), diagramToLucid(sampleArch), diagramToLucidJson(sampleArch).version, exportMeasuredDiagram]; // @ts-expect-error the weights are required phosphorWeightsEsbuild({}); // @ts-expect-error a weight is one of Phosphor's six @@ -89,6 +93,7 @@ const app = <Form<{name: string}> onFormSubmit={value => value.name.toUpperCase( fs.writeFileSync(path.join(consumer, "smoke.mjs"), `import assert from 'node:assert/strict'; import fs from 'node:fs'; import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Button, CodeBlock, Pagination, Avatar, MorphIcon, CloseGlyph, preloadCodeLanguages } from '@srasyndicate/basalt'; import { tokens, accents } from '@srasyndicate/basalt-tokens'; assert.ok(tokens.dark['text-primary'].hex); assert.equal(accents.cobalt.dark.hex, '#77a2fc'); assert.equal(accents.cobalt.light.oklch, 'oklch(0.47 0.17 264)'); assert.match(renderToStaticMarkup(createElement(Button, null, 'Deploy')), /Deploy/); assert.doesNotMatch(renderToStaticMarkup(createElement(CodeBlock, {code:'const answer = 42;',language:'ts'})), /syntax-keyword/); await preloadCodeLanguages(['ts']); assert.match(renderToStaticMarkup(createElement(CodeBlock, {code:'const answer = 42;',language:'ts'})), /syntax-keyword/); for (const f of fs.readdirSync(new URL('.', import.meta.resolve('@srasyndicate/basalt')))) if (f.endsWith('.js')) assert.doesNotMatch(fs.readFileSync(new URL(f, import.meta.resolve('@srasyndicate/basalt')), 'utf8'), /^import[^;]*from\s*"shiki/m, f + ' imports Shiki statically'); const pages = renderToStaticMarkup(createElement(Pagination, {page:500000,pageCount:1000000})); assert.ok(pages.length < 10000); assert.match(renderToStaticMarkup(createElement(Avatar,{name:'Bailey Jones'})), /BJ/); assert.match(renderToStaticMarkup(createElement(MorphIcon,{glyph:CloseGlyph})), /data-icon="close"/); for (const name of ['styles.css','components.css','fonts.css']) assert.ok(fs.statSync(import.meta.resolve('@srasyndicate/basalt/'+name).replace('file://','')).size > 0); const read = (f) => fs.readFileSync(new URL(f, import.meta.resolve('@srasyndicate/basalt')), 'utf8'); assert.doesNotMatch(read('index.js'), /^"use client"/, 'the entry is a barrel: a Server Component imports plain values from it'); assert.match(read('button.js'), /^"use client"/); assert.match(read('menu.js'), /^"use client"/); assert.doesNotMatch(read('time-format.js'), /^"use client"/); const testing = await import('@srasyndicate/basalt/testing'); assert.equal(typeof testing.checkHeadroom, 'function'); assert.equal(typeof testing.measureHeadroom, 'function'); assert.equal('checkHeadroom' in await import('@srasyndicate/basalt'), false, 'the headroom helper is not in the root export'); const phosphor = await import('@srasyndicate/basalt/phosphor'); assert.deepEqual(phosphor.BASALT_PHOSPHOR_WEIGHTS, ['bold', 'fill']); assert.throws(() => phosphor.phosphorWeightsEsbuild({}), /weights/); assert.equal(phosphor.phosphorWeightsRollup({ weights: ['bold'] }).transform('x', '/a/b.js'), null); +const interop = await import('@srasyndicate/basalt/diagram-interop'); assert.equal('diagramToDrawio' in await import('@srasyndicate/basalt'), false, 'diagram-interop stays outside the root export'); assert.match(interop.diagramToDrawio({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }), /<mxfile compressed="false">/); assert.ok(interop.diagramToVsdx({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }).length > 0); console.log('Packed consumer: runtime, server rendering, exact token types, exports, fonts and RSC boundary pass.');`); process.stdout.write(run(process.execPath, ["smoke.mjs"], consumer)); // A React Server Component, built by Next.js (A5-18): what the package holds that is neither a component nor a hook must be callable on the server. Each From 2b55ca125dda509a824e2248de9fe7efb38e36ba Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:32:27 -0600 Subject: [PATCH 04/19] Diagram export: dark Visio page, Visio containers, Lucid table rows, measured lanes, marks from the manifest From Opus's code review of the converter (DECISIONS 327). - B3: a dark .vsdx starts with a locked, full-page surface-page shape (PageBackground, ID 1), so lines and lane words no longer sit on Visio's white page. .lucid keeps pages[].settings.fillColor: Lucid's Standard Import reference (Pages, Page Settings) documents fillColor as the canvas background colour, so it needs no shape. - Polish 2: measured lanes carry their DOM index, and sceneFromMeasured falls back to it when the model's lane id isn't there, so a measured lane rect reaches the scene instead of an estimate from its cards. - Polish 3: a .vsdx group is a Visio container (User.msvStructureType "Container", Relationships DEPENDSON(1, members) on the group and DEPENDSON(4, group) on each member), so moving it moves its services. - Polish 4: a .lucid table's userSpecifiedRows are taken from the scene's row positions and sum to the table's height, so FK ends sit on their rows' centres. - Polish 5: the embeddable marks and their attributions are read from marks/manifest.json's terms at build time (the same 87 of 104 as the hard-coded list); the Kubernetes attribution goes into the .vsdx document description and the .lucid image's customData. Adaptive .drawio carries both mark forms behind prefers-color-scheme. - Polish 7: the subpath is built with NODE_ENV defined, so it runs as native browser ESM without `process`. (It still bundles its own diagram-core: see the round's report.) - Polish 8: Math.hypot replaced by exact sums on axis-aligned segments and Math.sqrt (correctly rounded in every engine) elsewhere. The light .drawio samples are byte-identical to before. diagram-core.ts is unchanged. Co-Authored-By: Gemini Neon <noreply@google.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/react/build.mjs | 16 +++++ packages/react/src/diagram-interop.ts | 4 +- packages/react/src/interop/drawio.ts | 31 +++++++-- packages/react/src/interop/lucid.ts | 25 ++++++- packages/react/src/interop/scene.ts | 95 +++++++++++++++++---------- packages/react/src/interop/types.ts | 4 ++ packages/react/src/interop/vsdx.ts | 94 ++++++++++++++++++++++++-- 7 files changed, 217 insertions(+), 52 deletions(-) diff --git a/packages/react/build.mjs b/packages/react/build.mjs index bee71072..c597152b 100644 --- a/packages/react/build.mjs +++ b/packages/react/build.mjs @@ -97,6 +97,17 @@ await esbuild.build({ // 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", @@ -106,6 +117,11 @@ await esbuild.build({ entryPoints: [path.join(here, "src/diagram-interop.ts")], outdir: dist, external, + define: { + "process.env.NODE_ENV": '"production"', + __BASALT_EMBEDDABLE_MARKS__: JSON.stringify(JSON.stringify(embeddableMarks)), + __BASALT_MARK_ATTRIBUTIONS__: JSON.stringify(JSON.stringify(markAttributions)), + }, }); // The root's map for the imports plugin (src/tooling/imports.ts): every name the root exports at run time, and the module that holds it, read from the barrel's source. diff --git a/packages/react/src/diagram-interop.ts b/packages/react/src/diagram-interop.ts index 1b3e8629..8e4f5dd5 100644 --- a/packages/react/src/diagram-interop.ts +++ b/packages/react/src/diagram-interop.ts @@ -5,7 +5,7 @@ import type { DiagramSpec, Geo } from "./diagram-core"; import { sceneToDrawio } from "./interop/drawio"; import { sceneToLucid, sceneToLucidJson } from "./interop/lucid"; -import { isBundledMarkEmbeddable, layoutHeadless, readMeasuredExtras, sceneFromMeasured } from "./interop/scene"; +import { bundledMarkAttribution, isBundledMarkEmbeddable, layoutHeadless, readMeasuredExtras, sceneFromMeasured } from "./interop/scene"; import { sceneToVsdx } from "./interop/vsdx"; import type { InteropFormat, @@ -87,7 +87,7 @@ export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: Inter throw new Error(`diagram-interop: unknown format "${String(format)}" (expected drawio, vsdx, lucid or lucid-json)`); } -export { isBundledMarkEmbeddable, layoutHeadless as measureDiagramHeadless, readMeasuredExtras }; +export { bundledMarkAttribution, isBundledMarkEmbeddable, layoutHeadless as measureDiagramHeadless, readMeasuredExtras }; export type { DiagramSpec, diff --git a/packages/react/src/interop/drawio.ts b/packages/react/src/interop/drawio.ts index de35abf2..084f3d99 100644 --- a/packages/react/src/interop/drawio.ts +++ b/packages/react/src/interop/drawio.ts @@ -23,17 +23,19 @@ function cellStyle(parts: string[]): string { 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 += Math.hypot(pts[i + 1]!.x - pts[i]!.x, pts[i + 1]!.y - pts[i]!.y); - } + 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 = Math.hypot(b.x - a.x, b.y - a.y); + 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 }; @@ -43,6 +45,18 @@ function pointAtArcFraction(pts: readonly Pt[], t: number): Pt { 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"; @@ -376,8 +390,13 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" // 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 useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark"; - const svg = useDarkForm ? n.mark.svgDark : n.mark.svgLight; + 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([ diff --git a/packages/react/src/interop/lucid.ts b/packages/react/src/interop/lucid.ts index d8cd9d1d..09584554 100644 --- a/packages/react/src/interop/lucid.ts +++ b/packages/react/src/interop/lucid.ts @@ -142,7 +142,11 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li const rowCount = 1 + rows.length + (n.more ? 1 : 0); const colCount = 3; const cells: LucidTableCell[] = []; - const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: n.headerH ?? 37 }]; + // 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, @@ -154,7 +158,13 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li for (let r = 0; r < rows.length; r++) { const row = rows[r]!; const yPos = r + 1; - rowSizes.push({ index: yPos, size: round2(row.h) }); + 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( { @@ -181,7 +191,9 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li } if (n.more) { const moreIdx = rows.length + 1; - rowSizes.push({ index: moreIdx, size: 24 }); + 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, @@ -190,6 +202,12 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li 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)); @@ -269,6 +287,7 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li fill: { type: "image", ref: fileName, imageScale: "fit" }, stroke: { color: transparentFill, width: 0 }, }, + ...(n.mark.attribution ? { customData: [{ key: "attribution", value: n.mark.attribution }] } : {}), zIndex: 15, }); } diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts index 1bac54e0..14f9bf78 100644 --- a/packages/react/src/interop/scene.ts +++ b/packages/react/src/interop/scene.ts @@ -84,28 +84,43 @@ export function paletteFor(theme: "light" | "dark"): ThemePalette { }; } -// ---- Mark terms allowlist (matches packages/react/marks/manifest.json) ---- -// Official AWS, Azure, Google Cloud and Kubernetes (Apache-2.0) marks explicitly allow use in architecture diagrams. -// Unofficial edits (the 8 tile-removed AWS icons and third-party community drawings) and marks without diagram-use terms are excluded. - -const AWS_UNOFFICIAL_MARKS = [ - "aws-bedrock", - "aws-step-functions", - "aws-kinesis", - "aws-fargate", - "aws-secrets-manager", - "aws-cognito", - "aws-eks", - "aws-kms", -]; +// ---- 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 its manifest terms. */ +/** 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; - if (id === "kubernetes") return true; - if (id.startsWith("azure-") || id.startsWith("gcp-")) return true; - if (id.startsWith("aws-")) return !AWS_UNOFFICIAL_MARKS.includes(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. */ @@ -138,11 +153,14 @@ function resolveNodeMark(n: MNode, mode: "omit" | "embed", resolver?: InteropMar const svgLight = rawLight ? decodeSvgMarkup(rawLight) : undefined; const svgDark = rawDark ? decodeSvgMarkup(rawDark) : svgLight; if (!svgLight || !svgDark) return undefined; - return { id: n.mark.id, svgLight, svgDark }; + return { id: n.mark.id, svgLight, svgDark, attribution: bundledMarkAttribution(n.mark.id) }; } if (n.mark.onLight) { - const svgLight = decodeSvgMarkup(n.mark.onLight); - const svgDark = n.mark.onDark ? decodeSvgMarkup(n.mark.onDark) : svgLight; + 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 }; } @@ -251,7 +269,8 @@ function insideShape(p: Pt, n: GNode, pad: number): boolean { if (n.shape === "terminal") { const rr = Math.min(hw, hh); const ex = Math.min(Math.max(p.x, l + rr), r - rr); - return Math.hypot(p.x - ex, p.y - cy) < rr - pad; + 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; } @@ -269,18 +288,20 @@ function boxHitsShape(box: Rect, n: GNode): boolean { if (hit(box, { l: l + rr, r: r - rr, t, b })) return true; for (const ex of [l + rr, r - rr]) { const px = Math.max(box.l, Math.min(ex, box.r)), py = Math.max(box.t, Math.min(cy, box.b)); - if (Math.hypot(px - ex, py - cy) < rr - 0.01) return true; + 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 len = Math.hypot(b.x - a.x, b.y - a.y); + 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 + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }, n, 1)) return true; + if (insideShape({ x: a.x + dx * f, y: a.y + dy * f }, n, 1)) return true; } return false; } @@ -418,12 +439,14 @@ function labelArcFraction(pts: readonly Pt[], box: SceneBox): number { let total = 0; const segLens: number[] = []; for (let i = 1; i < pts.length; i++) { - const len = Math.hypot(pts[i]!.x - pts[i - 1]!.x, pts[i]!.y - pts[i - 1]!.y); + 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 bestDist = Infinity; + let bestDist2 = Infinity; let bestAlong = total / 2; let acc = 0; for (let i = 1; i < pts.length; i++) { @@ -432,9 +455,10 @@ function labelArcFraction(pts: readonly Pt[], box: SceneBox): number { 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 d = Math.hypot(cx - px, cy - py); - if (d < bestDist) { - bestDist = d; + 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]!; @@ -1306,9 +1330,12 @@ export function sceneFromMeasured( // Lanes const sceneLanes: SceneLane[] = []; if (m.type === "data-flow") { - const extraById = new Map((extras.lanes ?? []).map((l) => [l.id, l])); + 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); + 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))]; @@ -1518,7 +1545,7 @@ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): Mea 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}`, label, rect: rectOf(el) }); + lanes.push({ id: `lane-${idx}`, index: idx, label, rect: rectOf(el) }); }); const bands: MeasuredBand[] = []; diff --git a/packages/react/src/interop/types.ts b/packages/react/src/interop/types.ts index d1a31569..955e2a17 100644 --- a/packages/react/src/interop/types.ts +++ b/packages/react/src/interop/types.ts @@ -32,6 +32,8 @@ export interface MeasuredGroup { export interface MeasuredLane { id: string; + /** 0-based lane index matching the DOM order of `.diagram-lane` elements. */ + index?: number; label: string; rect: Rect; } @@ -75,6 +77,8 @@ export interface SceneMark { 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 { diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts index 77f17cdb..8685ece3 100644 --- a/packages/react/src/interop/vsdx.ts +++ b/packages/react/src/interop/vsdx.ts @@ -130,19 +130,81 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): }); 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 nodeSheetId = new Map<string, number>(); + for (const n of scene.nodes) nodeSheetId.set(n.id, nextId++); + const shapeXml: string[] = []; const connectXml: string[] = []; const placed = new Map<string, PlacedShape>(); const mediaFiles: Array<{ rId: string; fileName: string; svg: string }> = []; + const attributions: string[] = []; - // 1. Architecture groups (behind nodes) + // 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 (User.msvStructureType="Container" + Relationships) for (const g of scene.groups) { - const id = nextId++; + 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(12 / DPI); + const memberIds = g.members.map((mid) => nodeSheetId.get(mid)).filter((x): x is number => x !== undefined); + const relCell = memberIds.length + ? ` <Cell N="Relationships" V="0" F="SUM(DEPENDSON(1,${memberIds.map((mid) => `Sheet.${mid}!SheetRef()`).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` + @@ -163,6 +225,13 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` <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` + @@ -187,7 +256,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): // 2. Data-flow lanes (behind step cards) for (let k = 0; k < scene.lanes.length; k++) { const lane = scene.lanes[k]!; - const id = nextId++; + 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); @@ -229,8 +298,9 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): } // 3. Sequence lifelines & phase bands - for (const lf of scene.lifelines) { - const id = nextId++; + 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); @@ -268,7 +338,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) { const band = scene.bands[bIdx]!; - const id = nextId++; + const id = bandSheetIds[bIdx]!; const wIn = n6(band.w / DPI); const hIn = n6(band.h / DPI); const pinX = toVisioX(band.w / 2); @@ -309,7 +379,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): // 4. Node shapes for (const n of scene.nodes) { - const id = nextId++; + 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); @@ -505,6 +575,10 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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` + @@ -529,6 +603,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` <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` + @@ -542,6 +617,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ); 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`; @@ -710,12 +786,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` <Relationship Id="rId1" Type="http://schemas.microsoft.com/visio/2010/relationships/document" Target="visio/document.xml"/>\n` + `</Relationships>\n`; + 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` + ` Basalt Diagram Exporter\n` + + descLine + ` \n` + ` \n` + ` \n` + From 7cb998c528b166e65bc5842f683433629698c800 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:32:40 -0600 Subject: [PATCH 05/19] basalt-diagram-export: works through npm's .bin link; packaged --browser; custom mark files; --out checks From Opus's code review of the converter (DECISIONS 327). - B1: the main-module check compares real paths, so the CLI runs when npm links it as node_modules/.bin/basalt-diagram-export (a symlink). package-lock.json records the package's bin. verify-packages.mjs puts the bin in the packed consumer's lock entry (so `npm ci` links it, as a real install does), runs the CLI through the link, and checks it wrote .drawio, .vsdx and .lucid, a dark draw.io background and the dark .vsdx page shape. It also prints an assertion's message now, which the catch used to swallow. - --browser from a packed install (and polish 6): the harness serves only the package's own dist (styles.css, the Geist files, diagram-core.js, diagram-interop.js) to headless Chromium, so it no longer needs the repo's HTML skill. Playwright is not a dependency: without it the CLI exits with "npm install -D playwright && npx playwright install chromium", which verify-packages checks. - Polish 9: a custom mark's file path is read relative to the input file; a missing file, a non-SVG file or a remote URL is a warning on stderr, not a silent omission. - Polish 10: --out with a file extension needs one diagram and one format, and the extension must match the format. - The skill and diagram.md give the in-repo form of the command (node packages/react/bin/basalt-diagram-export.mjs after npm run build). SKILL.md is 12,642 of its 12,650 B. - Polish 11: f92f416f also reworded steps 1 to 3 of SKILL.md to make room for the export rule; that commit didn't say so. They were shortened: step 1's "the classes, attributes and tags that bring it in" became "its triggers", step 3's "the modules your classes, attributes and tags use" became "the modules you use", and "only for a file a tool reads, never a file a person opens" became "tools only, never for readers". Co-Authored-By: Gemini Neon Co-Authored-By: Claude Opus 5.5 --- .agent/skills/basalt-html/SKILL.md | 2 +- .../skills/basalt-html/parts/usage/diagram.md | 2 +- package-lock.json | 3 + packages/react/bin/basalt-diagram-export.mjs | 352 ++++++++++-------- scripts/verify-packages.mjs | 35 +- tools/html-skill/src/usage/diagram.md | 2 +- 6 files changed, 246 insertions(+), 150 deletions(-) diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index 5cfeb8cf..2e1f2117 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -104,5 +104,5 @@ Your own CSS goes in a `` + + `` + + `
` + + ``; + + const context = await browser.newContext({ viewport: { width: Math.max(width + 128, 1280), height: 1200 }, deviceScaleFactor: 2 }); const page = await context.newPage(); - await page.setContent(html, { waitUntil: "load" }); - await page.evaluate(() => document.fonts.ready); - await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))))); - - // Inspect each figure's exact rendered DOM boxes + paths - const measured = await page.evaluate((count) => { - const results = []; - for (let idx = 0; idx < count; idx++) { - const fig = document.getElementById(`exp-${idx}`); - const drawing = fig.querySelector(".diagram-drawing"); - const o = drawing.getBoundingClientRect(); - const rectOf = (el) => { - const r = el.getBoundingClientRect(); - return { l: r.left - o.left, t: r.top - o.top, r: r.right - o.left, b: r.bottom - o.top }; - }; - const nodes = [...drawing.querySelectorAll(".diagram-node")].map((el, i) => ({ - id: el.dataset.node, - shape: el.dataset.shape, - i, - rect: rectOf(el), - })); - const lifelines = [...drawing.querySelectorAll(".diagram-life")].map((p) => { - const m = (p.getAttribute("d") || "").match(/M(-?[\d.]+)\s+(-?[\d.]+)V(-?[\d.]+)/); - return m ? { x: Number(m[1]), y1: Number(m[2]), y2: Number(m[3]) } : { x: 0, y1: 0, y2: 0 }; - }); - const lines = [...drawing.querySelectorAll(".diagram-edge")].map((g) => { - const lineEl = g.querySelector(".diagram-line"); - const tipEl = g.querySelector(".diagram-tip"); - const d = lineEl.getAttribute("d") || ""; - const pts = []; - for (const m of d.matchAll(/([MLQ])([^MLQ]*)/g)) { - const nums = m[2].trim().split(/[ ,]+/).map(Number); - if (m[1] === "Q") { pts.pop(); pts.push({ x: nums[0], y: nums[1] }); } - else pts.push({ x: nums[0], y: nums[1] }); - } - const tn = (tipEl.getAttribute("d") || "").match(/-?[\d.]+/g).map(Number); - const open = tipEl.hasAttribute("data-open"); - const tip = open ? { x: tn[2], y: tn[3] } : { x: tn[0], y: tn[1] }; - pts[pts.length - 1] = tip; - const a = pts[pts.length - 2] || pts[0], b = pts[pts.length - 1]; - const dir = Math.abs(a.x - b.x) < 0.01 ? (b.y > a.y ? "down" : "up") : (b.x > a.x ? "right" : "left"); - const kind = lineEl.getAttribute("data-kind") || "plain"; - return { i: Number(g.dataset.edge), from: g.dataset.from, to: g.dataset.to, kind, pts, tip, dir, width: kind === "main" ? 2 : 1 }; - }); - const labels = [...drawing.querySelectorAll(".diagram-label")].map((el) => ({ - i: Number(el.dataset.edge), - text: el.textContent, - box: rectOf(el), - on: el.hasAttribute("data-on"), - })); - const groups = [...drawing.querySelectorAll(".diagram-gbox")].map((el) => ({ - id: el.getAttribute("data-group"), - label: el.querySelector(".diagram-glabel")?.textContent || "", - rect: rectOf(el), - })); - const lanes = [...drawing.querySelectorAll(".diagram-lane")].map((el, k) => ({ - id: `lane-${k}`, - label: el.querySelector(".diagram-lane-name")?.textContent || "", - rect: rectOf(el), - })); - const bands = [...drawing.querySelectorAll(".diagram-band")].map((el) => ({ - text: el.textContent || "", - rect: rectOf(el), - })); - const tableRows = {}; - drawing.querySelectorAll('.diagram-node[data-shape="table"]').forEach((nodeEl) => { - const ys = [...nodeEl.querySelectorAll(".diagram-row")].map((r) => { - const rr = rectOf(r); - return (rr.t + rr.b) / 2; - }); - if (ys.length) tableRows[nodeEl.dataset.node] = ys; - }); - results.push({ - geo: { w: drawing.clientWidth, h: drawing.clientHeight, nodes, lines, lifelines, labels, crossings: [], through: [], unseated: [], outside: [], ox: 0, oy: 0 }, - extras: { groups, lanes, bands, tableRows }, - }); + 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; } - return results; - }, items.length); + 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 measured = await page.evaluate(() => window.__measureAll()); + if (pageErrors.length) { + throw new Error(`basalt-diagram-export: --browser page error: ${pageErrors.join("; ")}`); + } return measured; } finally { await browser.close(); @@ -361,14 +400,26 @@ async function main() { process.exit(1); } - const resolveMark = opts.marks === "embed" ? await createMarkResolver() : undefined; - const measuredList = opts.browser ? await measureInBrowser(items, opts.width) : null; + 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; - const singleFileOut = - opts.out && - items.length === 1 && - opts.to.length === 1 && - /\.(drawio|vsdx|lucid|json)$/i.test(opts.out); + const resolveMark = opts.marks === "embed" ? createMarkResolver(path.dirname(inputPath)) : undefined; + const measuredList = opts.browser ? await measureInBrowser(items, opts.width) : null; const outDir = singleFileOut ? path.dirname(path.resolve(opts.out)) @@ -383,7 +434,7 @@ async function main() { for (const format of opts.to) { let data; - if (measured) { + if (measured?.geo) { 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") { @@ -406,7 +457,16 @@ async function main() { } } -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { +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/scripts/verify-packages.mjs b/scripts/verify-packages.mjs index fabe2f09..a566b46b 100644 --- a/scripts/verify-packages.mjs +++ b/scripts/verify-packages.mjs @@ -34,7 +34,8 @@ try { packages[""] = { name: manifest.name, version: manifest.version, dependencies: manifest.dependencies }; for (let index = 0; index < packedPackages.length; index++) { const { packed, manifest: pkg } = packedPackages[index]; - packages[`node_modules/${pkg.name}`] = { version: pkg.version, resolved: `file:${archives[index]}`, integrity: packed.integrity, dependencies: pkg.dependencies, peerDependencies: pkg.peerDependencies }; + // `bin` is in the lock entry as npm writes it, so `npm ci` links node_modules/.bin as a real install does (B1: the CLI run through that link). + packages[`node_modules/${pkg.name}`] = { version: pkg.version, resolved: `file:${archives[index]}`, integrity: packed.integrity, dependencies: pkg.dependencies, peerDependencies: pkg.peerDependencies, ...(pkg.bin ? { bin: pkg.bin } : {}) }; } fs.writeFileSync(path.join(consumer, "package-lock.json"), JSON.stringify({ name: manifest.name, version: manifest.version, lockfileVersion: 3, requires: true, packages })); run("npm", ["ci", "--offline", "--ignore-scripts", "--no-audit", "--no-fund"], consumer); @@ -96,6 +97,37 @@ const phosphor = await import('@srasyndicate/basalt/phosphor'); assert.deepEqual const interop = await import('@srasyndicate/basalt/diagram-interop'); assert.equal('diagramToDrawio' in await import('@srasyndicate/basalt'), false, 'diagram-interop stays outside the root export'); assert.match(interop.diagramToDrawio({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }), //); assert.ok(interop.diagramToVsdx({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }).length > 0); console.log('Packed consumer: runtime, server rendering, exact token types, exports, fonts and RSC boundary pass.');`); process.stdout.write(run(process.execPath, ["smoke.mjs"], consumer)); + // Run the installed CLI through its node_modules/.bin symlink (guards B1: symlinked bin must execute and write files). + const binPath = path.join(consumer, "node_modules", ".bin", "basalt-diagram-export"); + assert.ok(fs.existsSync(binPath), "packed install is missing node_modules/.bin/basalt-diagram-export"); + const sampleSpec = { + type: "architecture", + title: "Packed CLI check", + summary: "Verifies the installed bin.", + nodes: [ + { id: "a", name: "ECS service", col: 1, row: 1, mark: "aws-ecs-service" }, + { id: "b", name: "Kubernetes", col: 2, row: 1, mark: "kubernetes" }, + ], + edges: [{ from: "a", to: "b", kind: "main", label: "HTTP" }], + }; + const cliIn = path.join(consumer, "sample.json"); + const cliOut = path.join(consumer, "cli-out"); + fs.writeFileSync(cliIn, JSON.stringify(sampleSpec)); + run(process.execPath, [binPath, cliIn, "--to", "drawio,vsdx,lucid", "--theme", "dark", "--marks", "embed", "--out", cliOut], consumer); + for (const ext of [".drawio", ".vsdx", ".lucid"]) { + const f = path.join(cliOut, `sample${ext}`); + assert.ok(fs.existsSync(f) && fs.statSync(f).size > 0, `installed bin did not write ${f}`); + } + assert.match(fs.readFileSync(path.join(cliOut, "sample.drawio"), "utf8"), /background="#000000"/, "dark drawio background"); + assert.match(fs.readFileSync(path.join(cliOut, "sample.vsdx")).toString("latin1"), /PageBackground/, "dark vsdx PageBackground"); + // Without Playwright installed in the consumer, --browser fails cleanly with an actionable install message. + let browserErr = ""; + try { + run(process.execPath, [binPath, cliIn, "--browser", "--to", "drawio", "--out", cliOut], consumer); + } catch (err) { + browserErr = `${err.stdout || ""}${err.stderr || ""}`; + } + assert.match(browserErr, /playwright/i, "packed --browser without Playwright must name playwright in its error"); // A React Server Component, built by Next.js (A5-18): what the package holds that is neither a component nor a hook must be callable on the server. Each // page is static, so a call that throws ("Attempted to call formatStamp() from the server but formatStamp is on the client") fails the build, and a constant // that arrives as a client reference (CONFIRM_MS / 1000 is NaN, with no error) shows in the page's HTML. The components still come through as components. @@ -135,6 +167,7 @@ export default async function Page() { } catch (error) { if (error.stdout) process.stderr.write(error.stdout); if (error.stderr) process.stderr.write(error.stderr); + if (!error.stdout && !error.stderr) process.stderr.write(`${error.message}\n`); throw new Error("Packed consumer verification failed; see the compiler or installer output above."); } finally { fs.rmSync(consumer, { recursive: true, force: true }); diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index 3dff1cd9..25d8a6d2 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -27,4 +27,4 @@ Boxes and the lines between them. `compose.mjs` writes the figure's words into t - **Run:** `"run": true` on a sequence adds "Play the run", a dot through every message. - **Mark:** `"mark": "aws-ecs-service"` on an architecture node, 16px in the card's top end corner, the owner's file and colours; the card's words still name the service. Your own: `{ "onLight": "logo.svg", "onDark": "logo-dark.svg" }`, read into the page. A page drawing from script names its marks: ``. - **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`. +- **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`). From 6ea8ac58d2565825db0c1b21a2c47262ca57c02a Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:33:09 -0600 Subject: [PATCH 06/19] Diagram interop tests: the RunTask proof as a failing fixture, dark page, containers, rows, CLI link and environments From Opus's code review of the converter (DECISIONS 327). - Polish 1: the RunTask test works out Begin and End against the Connection rows they are glued to (value and formula) and requires 2e-6 in. The proof .vsdx that jogged in Lucid is a fixture (test/fixtures/runtask-jog-proof.vsdx, read with a general ZIP reader): the test requires its RunTask Begin to be 0.5 px off and assertValidVsdx to reject it. - assertValidVsdx also checks every Connection row's F formula against its V, and that each architecture group is a Visio container listing its members and listed by them (checked after the glue, so the proof fails on its glue first). - B3: a dark .vsdx's first shape is the locked surface-page PageBackground; a light one has none. .lucid's page fillColor is #000000 dark and #fafafa light. - Polish 4: a .lucid table's rows sum to its height and every FK end is within 0.5 px of a row's centre. - B1: the CLI run through a symlink writes its file. - Polish 8: the two CLI runs use different TZ and LC_ALL (UTC/C and Asia/Kolkata/de_DE.UTF-8) and must agree byte for byte. - Polish 9 and 10: a custom mark file is embedded, a missing one warns; an --out extension that doesn't match the format fails. - Polish 5: aws-database (distinct light and dark forms) is embedded and adaptive draw.io carries both forms; the Kubernetes attribution lands in the .vsdx and the .lucid. Written, not run (browser tests are paused, DECISIONS 330): in the live DOM test, the headless-vs-live comparison (it records every box's and route point's difference, printed with PRINT_INTEROP_COMPARISON=1, and asserts nothing yet: B2 lands after batch B), polish 2's measured lane reaching the scene, and polish 7's native-browser import with no `process`; and the packaged --browser CLI test. Co-Authored-By: Gemini Neon Co-Authored-By: Claude Opus 5.5 --- packages/react/test/diagram-interop.test.mjs | 339 ++++++++++++++++-- .../test/fixtures/runtask-jog-proof.vsdx | Bin 0 -> 5965 bytes 2 files changed, 306 insertions(+), 33 deletions(-) create mode 100644 packages/react/test/fixtures/runtask-jog-proof.vsdx diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs index 4a522880..7e59dc83 100644 --- a/packages/react/test/diagram-interop.test.mjs +++ b/packages/react/test/diagram-interop.test.mjs @@ -17,6 +17,7 @@ import os from "node:os"; import path from "node:path"; import { describe, test } from "node:test"; import { fileURLToPath, pathToFileURL } from "node:url"; +import zlib from "node:zlib"; import { fixturePage, launch, pkg } from "./support.mjs"; @@ -77,6 +78,31 @@ function readZipEntries(bytes) { return entries; } +/** Reads any ZIP's entries (stored or deflated, any timestamps): for fixtures written by other tools, such as the RunTask proof. */ +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 expectedEdgeCount(spec) { if (spec.type === "sequence") return spec.steps.filter((s) => !("band" in s)).length; if (spec.type === "schema") { @@ -212,7 +238,7 @@ function assertValidDrawio(xml, spec, context) { /** Parses and validates Visio .vsdx OPC archive, XML well-formedness, glue, ConFixedCode=2, and Visio-inch port alignment. */ function assertValidVsdx(bytes, spec, context) { - const entries = readZipEntries(bytes); + const entries = bytes instanceof Map ? bytes : readZipEntries(bytes); const required = [ "[Content_Types].xml", "_rels/.rels", @@ -262,8 +288,8 @@ function assertValidVsdx(bytes, spec, context) { // Only inspect cells/connections belonging directly to the top-level shape (before any nested ) const ownBody = body.split("")[0] ?? body; const objType = cellVal(ownBody, "ObjType"); - const conns = [...ownBody.matchAll(/[\s\S]*? ({ ix: Number(m[1]), x: Number(m[2]), y: Number(m[3]) })); + const conns = [...ownBody.matchAll(/[\s\S]*?[\s\S]*?/g)] + .map((m) => ({ ix: Number(m[1]), x: Number(m[2]), fx: m[3], y: Number(m[4]), fy: m[5] })); const rec = { id, nameU, @@ -277,6 +303,13 @@ function assertValidVsdx(bytes, spec, context) { conns, body: ownBody, }; + // Verify every Connection row's F formula (Width*fx, Height*fy) agrees with its V value within 2e-6 in. + for (const c of conns) { + const mFx = c.fx?.match(/^Width\*([\d.]+)$/); + const mFy = c.fy?.match(/^Height\*([\d.]+)$/); + if (mFx) assert.ok(Math.abs(rec.w * Number(mFx[1]) - c.x) <= 2e-6, `${context} ${nameU} Conn ${c.ix} X formula drift`); + if (mFy) assert.ok(Math.abs(rec.h * Number(mFy[1]) - c.y) <= 2e-6, `${context} ${nameU} Conn ${c.ix} Y formula drift`); + } byId.set(id, rec); if (objType === "2") connectors.push(rec); } @@ -328,6 +361,22 @@ function assertValidVsdx(bytes, spec, context) { assertAxisAlignedRoute(geomRows, startPort, endPort, 2e-5, `${context} vsdx ${c.nameU}`); } assert.equal(labelledCount, expectedLabelCount(spec), `${context}: all labelled edges have connector `); + + // Verify architecture groups are real Visio Containers (User.msvStructureType="Container" + Relationships DEPENDSON). + if (spec.type === "architecture" && spec.groups?.length) { + for (const g of spec.groups) { + const gShape = [...byId.values()].find((s) => s.nameU === `Group_${g.id}`); + assert.ok(gShape, `${context}: Group_${g.id} shape present`); + assert.match(gShape.body, //, `${context}: Group_${g.id} has User.msvStructureType=Container`); + const members = spec.nodes.filter((n) => n.group === g.id); + for (const m of members) { + const mShape = [...byId.values()].find((s) => s.nameU === `Node_${m.id}`); + assert.ok(mShape, `${context}: member Node_${m.id} present`); + assert.match(gShape.body, new RegExp(`DEPENDSON\\(1,(?:Sheet\\.\\d+!SheetRef\\(\\),)*Sheet\\.${mShape.id}!SheetRef\\(\\)[,)]`), `${context}: container lists member ${m.id}`); + assert.match(mShape.body, new RegExp(`DEPENDSON\\(4,Sheet\\.${gShape.id}!SheetRef\\(\\)\\)`), `${context}: member ${m.id} points to container ${g.id}`); + } + } + } } /** Validates Lucid Standard Import ZIP + document.json contract and port axis-alignment. */ @@ -363,7 +412,11 @@ function assertValidLucid(bytes, spec, context) { if (spec.type === "schema") { const tables = page.shapes.filter((s) => s.type === "table"); assert.equal(tables.length, spec.tables.length, `${context}: native table count`); - for (const t of tables) assert.equal(t.verticalBorder, false, `${context}: verticalBorder false`); + for (const t of tables) { + assert.equal(t.verticalBorder, false, `${context}: verticalBorder false`); + const rowSum = (t.userSpecifiedRows ?? []).reduce((a, r) => a + r.size, 0); + assert.ok(Math.abs(rowSum - t.boundingBox.h) <= 0.05, `${context} ${t.id}: userSpecifiedRows sum (${rowSum}) != boundingBox.h (${t.boundingBox.h})`); + } } if (spec.type === "flowchart") { assert.ok(page.shapes.some((s) => s.type === "decision"), `${context}: flowchart decision shape`); @@ -396,7 +449,22 @@ function assertValidLucid(bytes, spec, context) { for (const line of edgeLines) { assert.ok(line.endpoint1.type === "shapeEndpoint" || line.endpoint1.type === "lineEndpoint", `${context} ${line.id}: endpoint1 glued`); assert.ok(line.endpoint2.type === "shapeEndpoint" || line.endpoint2.type === "lineEndpoint", `${context} ${line.id}: endpoint2 glued`); - if (spec.type === "schema") assert.equal(line.endpoint1.style, "closedCircle", `${context} ${line.id}: FK dot`); + if (spec.type === "schema") { + assert.equal(line.endpoint1.style, "closedCircle", `${context} ${line.id}: FK dot`); + // Verify every FK endpoint lands at the vertical center of one of its table's Lucid rows (within 0.5px). + for (const ep of [line.endpoint1, line.endpoint2]) { + const tbl = shapeById.get(ep.shapeId); + const yLocal = ep.position.y * tbl.boundingBox.h; + let acc = 0; + let minCenterDiff = Infinity; + for (const r of tbl.userSpecifiedRows ?? []) { + const center = acc + r.size / 2; + minCenterDiff = Math.min(minCenterDiff, Math.abs(yLocal - center)); + acc += r.size; + } + assert.ok(minCenterDiff <= 0.51, `${context} ${line.id} on ${ep.shapeId}: FK y=${yLocal.toFixed(2)} off nearest Lucid row center by ${minCenterDiff.toFixed(2)}px`); + } + } if (line.text?.length) labelled++; const start = endpointPt(line.endpoint1); const end = endpointPt(line.endpoint2); @@ -441,32 +509,77 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi } }); - test(`${key}: .vsdx OPC parts, Connects glue, ConFixedCode=2, and zero-jog Visio-inch port alignment`, () => { + 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 and Lucid-unit port alignment`, () => { + 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 is a clean 3-point L-bend with 0.000000 in port delta", () => { - const entries = readZipEntries(interop.diagramToVsdx(CIMIP.architecture)); - const page1 = entries.get("visio/pages/page1.xml").toString("utf8"); - const runTask = page1.match(/]*>([\s\S]*?)<\/Shape>/)?.[1]; - assert.ok(runTask, "Connector_4 (RunTask) present"); - const rows = [...runTask.matchAll(/<\/Row>/g)]; - assert.equal(rows.length, 3, "RunTask has exactly 3 geometry vertices (no extra joining jog)"); - assert.equal(rows[0][2], "0.000000", "MoveTo X === 0"); - assert.equal(rows[0][3], "0.000000", "MoveTo Y === 0"); - assert.equal(rows[1][2], "0.000000", "first bend stays strictly on X === 0 (no horizontal jog below cimip service)"); + test("architecture RunTask (svc -> ecs) in .vsdx glues Begin/End to exact Connection rows and rejects proof-style 0.5px drift", () => { + // RunTask's Begin and End against the Connection rows they are glued to, worked out from page1.xml alone (value and, where written, formula). + 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(beginConn && endConn, "RunTask glued from Node_svc 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 from = connPt(svc[2], Number(beginConn[2]) - 100), 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, 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, beginOff, endOff } = runTaskGlue(page1); + assert.ok(beginOff <= 2e-6, `RunTask Begin (${begin.x},${begin.y}) on its Connection row (${from.x},${from.y}; formula ${from.fx},${from.fy})`); + 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"); + + // Negative fixture: the proof .vsdx that jogged in Lucid (DECISIONS 314). Its geometry was already an L-bend; its BeginX sat 0.5 px + // (0.0052 in) off the cimip service's Connection row, which is what Lucid re-glued and drew as the jog. It must fail. + 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/); }); }); @@ -478,7 +591,7 @@ describe("live DOM measured Geo entry (exportMeasuredDiagram)", () => { 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 }; function Host() { - return
+ return
{Object.entries(data).map(([key, d]) => { const X = C[d.type]; const { type, ...props } = d; return ; })}
; } @@ -517,6 +630,96 @@ describe("live DOM measured Geo entry (exportMeasuredDiagram)", () => { assertValidVsdx(vsdx, CIMIP[key], `measured/${key}`); assertValidLucid(lucid, CIMIP[key], `measured/${key}`); } + + // Comparison: headless vs live at the same drawing width (records exact box & route deltas without asserting 0.5px yet; B2 lands after Batch B). + const comparison = {}; + for (const key of CIMIP_KEYS) { + const { geo, extras } = measured[key]; + const liveDoc = interop.exportMeasuredDiagram(CIMIP[key], geo, "lucid-json", { extras }); + const headDoc = interop.diagramToLucidJson(CIMIP[key], { width: geo.w }); + const L = liveDoc.pages[0], H = headDoc.pages[0]; + assert.deepEqual(L.shapes.map((s) => s.id), H.shapes.map((s) => s.id), `${key}: live vs headless shape ids match`); + assert.deepEqual(L.lines.map((l) => l.id), H.lines.map((l) => l.id), `${key}: live vs headless 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) }; + } + let maxRouteDelta = 0, routesOverHalfPx = 0; + const routeDeltas = {}; + for (const l of L.lines.filter((x) => x.id.startsWith("edge_"))) { + const h = H.lines.find((x) => x.id === l.id); + const lp = l.elbowControlPoints ?? [], hp = h.elbowControlPoints ?? []; + 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"; + } + comparison[key] = { + liveW: geo.w, liveH: geo.h, + headlessW: H.settings.size.w - 64, headlessH: H.settings.size.h - 64, + shapesOverHalfPx, maxBoxDelta: +maxBoxDelta.toFixed(2), + routesOverHalfPx, maxRouteDelta: +maxRouteDelta.toFixed(2), + boxDeltas, routeDeltas, + }; + } + if (process.env.PRINT_INTEROP_COMPARISON) { + process.stdout.write(`HEADLESS_VS_LIVE=${JSON.stringify(comparison)}\n`); + } + + // Polish 2: measured lane rects keyed as lane-0..lane-5 (readMeasuredExtras' format) must reach 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"); + const docDefaultLanes = interop.exportMeasuredDiagram(CIMIP.dataFlow, df.geo, "lucid-json", { extras: df.extras }); + const swDefault = docDefaultLanes.pages[0].shapes.find((s) => s.type === "swimLanes"); + assert.notEqual(swCustom.lanes[0].width, swDefault.lanes[0].width, "measured lane-0..N rects must change exported swimlane geometry"); + assert.equal(swCustom.lanes[0].width, 185, "lane 0 bottom hits midpoint between lane 0 bottom (140) and lane 1 top (230) = 185"); + + // Polish 7: dist/diagram-interop.js runs directly in a browser without any `process` global defined. + 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(); @@ -545,12 +748,14 @@ describe("service marks embedding policy (manifest terms)", () => { 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: "br", name: "Bedrock", col: 3, row: 1, mark: "aws-bedrock" }, - { id: "gh", name: "GitHub", col: 4, row: 1, mark: "github" }, + { 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: "br" }, + { from: "k8s", to: "db" }, + { from: "db", to: "br" }, { from: "br", to: "gh" }, ], }; @@ -561,20 +766,32 @@ describe("service marks embedding policy (manifest terms)", () => { 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); - // Embed: only aws-ecs-service and kubernetes (NOT unofficial aws-bedrock or restricted github) + // Embed: official allowed marks only (NOT unofficial aws-bedrock or restricted github) 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"/); + // Adaptive draw.io embeds prefers-color-scheme dual-form SVG for marks with distinct light/dark forms (aws-database) + 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, 2); + assert.equal([...vsdxEmbed.keys()].filter((k) => k.startsWith("visio/media/")).length, 3); assert.ok(vsdxEmbed.has("visio/pages/_rels/page1.xml.rels")); + // Kubernetes attribution from manifest.json lands in Visio DocumentProperties Description and Lucid customData + 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, 2); + 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"); }); }); @@ -582,23 +799,39 @@ describe("basalt-diagram-export CLI", () => { test("exports JSON map, single JSON, and HTML script[data-diagram] (ignoring comments/textarea decoys) deterministically", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "basalt-interop-cli-")); try { - // 1. Multi-diagram JSON (all 5 CIMIP fixtures) + // 1. Multi-diagram JSON under two different TZ and LC_ALL environments (Polish 8: cross-TZ/locale determinism) 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"), "--to", "drawio,vsdx,lucid", "--out", outA], { encoding: "utf8" }); + const r1 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--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); - const r2 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--to", "drawio,vsdx,lucid", "--out", outB], { encoding: "utf8" }); + const r2 = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--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"]) { + 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: ${stem}${ext}`); + assert.equal(sha256(fa), sha256(fb), `CLI repeat deterministic across TZ/LC_ALL: ${stem}${ext}`); } } + // 1b. B1: invoking the CLI through a symlink (as npm installs node_modules/.bin/basalt-diagram-export) executes and writes files + 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, "--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"); + // 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"); @@ -615,21 +848,61 @@ describe("basalt-diagram-export CLI", () => { 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 - const singleJson = path.join(dir, "one.json"); - fs.writeFileSync(singleJson, JSON.stringify(CIMIP.flowchart)); + // 3. Single file --out path (valid + Polish 10 mismatched extension check) const exactOut = path.join(dir, "exact.drawio"); const r4 = spawnSync(process.execPath, [CLI, singleJson, "--to", "drawio", "--out", exactOut], { encoding: "utf8" }); assert.equal(r4.status, 0, r4.stderr); assert.ok(fs.existsSync(exactOut)); - // 4. Error handling on unknown format + const mismatch = spawnSync(process.execPath, [CLI, singleJson, "--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. Polish 9: 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, "--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. Error handling on unknown format const bad = spawnSync(process.execPath, [CLI, singleJson, "--to", "bogus"], { encoding: "utf8" }); assert.notEqual(bad.status, 0); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); + + test("packaged --browser harness measures through dist/ alone (no repo HTML skill dependency)", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "basalt-interop-browser-")); + try { + const outDir = path.join(dir, "out"); + const res = spawnSync(process.execPath, [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--browser", "--to", "drawio,vsdx,lucid", "--out", outDir], { encoding: "utf8", timeout: 90000 }); + assert.equal(res.status, 0, res.stderr); + for (const [key, stem] of [["architecture", "architecture"], ["flowchart", "flowchart"], ["dataFlow", "data-flow"], ["sequence", "sequence"], ["schema", "schema"]]) { + assertValidDrawio(fs.readFileSync(path.join(outDir, `${stem}.drawio`), "utf8"), CIMIP[key], `cli-browser/${key}`); + assertValidVsdx(fs.readFileSync(path.join(outDir, `${stem}.vsdx`)), CIMIP[key], `cli-browser/${key}`); + assertValidLucid(fs.readFileSync(path.join(outDir, `${stem}.lucid`)), CIMIP[key], `cli-browser/${key}`); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); }); describe("subpath isolation", () => { 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 0000000000000000000000000000000000000000..9c383cf982a3014b70ffaf1d1bb68bf8150d737f GIT binary patch literal 5965 zcmZ`-1z1$w+8sc;8|m(D=|*A@k&te1h@plMX@sGMQW?5aq`L$}aA*|i6hXRM>Ywl4 z|G(dr|K4++v-dvFbKbSjyWVy7bN15JLVG|4006L%7ZbqwE8o!#a-@$60FWYkQ)M?W z#2yT>)PL!2?`6*K=j!q_|rrUc)@t5!WyNDuIE|d;_G@QH24(b8^5eW(!e5e z)q_2TMWFu_zYBffZ)h?imieffq}m+! zVy|lLnqzi_RQC_ID*Q3ZTaYZ#q5uH6$llV^-o;CR|F715bQsAJ9_GQT>`xnuoSW8h zPfMBs}~wxPGspDY!>bPSjsac$*8@^&75mN9L%kn`QQ zDr}*hA4ubs(O8!BhKf{FZo+tLqMowGMiez1g>nYvtro5;8FNTf_KWdt$Ms$cNRaM9 zf8cLhq7{#%;ydefE6GL>53Lz*Fy!P{@dh||tiL`lCH_tat%wc1@y(yt_wX)u_~Cfk zw6q-?LX9nvR=kJ)XNGX{P8UyPcBE(k00}ZfACMQwO~B60*4q`SiofL0kgVu7Cx{oZ ze@Xs&50;Ea6RF@6Dn8iQ6JrDN;V_$}u!_$9?6BL(K>B5~{Zwj$@y(O{!*Dy_8(Jwz z-GOXd>y+aNlo)dP-_v9cchw!gUohhKsqaYYSzB;sY}&wNd?fmfMDmq7Pru4%okB7f1kc`QyW zV1Z1H;pat%z>wpSapacXPQes3f1irx+n{9^=wY*~(C*{Nl+agk*W7n4crMZ|`mdV& z-F8d?gIs`sp9sLHGW_{9$UQRg2(-EDZHP17e zKP!Y!ZxY&wtPBORN_79K&_9*B~Is$V5*d9 zu%ts*u<(QBDO^gQTbRmyTo=8KAg9-#E-9^XlYS5*J}f5%>m0va59yltJoAAoxsO9A zUfHYlo74OGgB6i*1!iY6r(yM?X?`-iCa!01hxy)Fz5l$TFMbB5Ei<3mHMq1}9s{^k zyQhhz49>G?k7`?9EW2uCf*TsRN}-hKKh73Xcm%Q_k^N-q20wW|LMz@Xvk5!diiqC* znK0P_f2syDSr6nAMgFgZ-K`z%y#)Tz{-w%@WS}$h^NZZSA@4iy)v$KO_I~x8i!V-i z7A#Gpu7P)pa5>#x8U-qSdERu%Y$w0ZgZ)xUo(34d9PXJi&a1(N!egH2(!04GbSap} znp+()HiBA0i3O3P(Y91U4^^qb&zy_`jyz8kqar3LDD>@qm-^T-l}C#$l+J*+I}#*r zr^cxz?Yb9SYK|uU@!bebsL-i_TaEjXRhNyZhWb!A1yu$?gOk#B3RDd-ZS#{UL>@H@ z9}7gowvArmQ41417}y-hiejXfBOnq~Bj&*j6H7#x>@?rilm}W`8KE)0G^FtH`#MHp z%3aY}E1P+k;yq9rh+5GfIbQyyjk~&dl@Dy4YFFUb_jZBJDEB?JDJ0YG&7p1jtTK$QVyxXuXR2gz1#ztm$V`N{OBo=Au z<&}c^rxL2FV>l>|xSVudF;NSEZxVERZhRK$6m`Wsgq>qbf50C696K>G1Fq4T1h98M zX2sX4xMXFUK@ZOpw~v!adxl-?$*bdF%g~oM@4KLwVu=>17KP8l|0dEijVx+T`X>WJ zJ74rSGt-Q)0RPIa%B@EJ90($ei=aHxO^+`aJ=qiigymfV{>+!8Ed3WP0RV8f@}IRP z^q1ClvrK(6nkhn-u6QJ~q2rlpR-dyf3+uksZ$c_`(#sY=N20M-z1B`F0*o3W!8`3a zmOiXqW-i#VT4rqq*CaF`H*u`pC#I$=8&g%sX%NC5gnIWO05PBt77Aq#5|pJ6pw6M2 zMdONDuv!_>1tef52vT4FKAQO&Astb|8D&kRPLe{b@+Evu(xRP;fMuUzWZ`l4l|>XY zgmjQTo$%{0Y`^0eWdq%Qj|s{a&nlg}6xfi2ed1Uk3bUkGW7tjwCsO9+&@(OPm$s>ESKFw%L$`FN|ZSiFbHdFPw9u5s*PvYyalj_^nc>Vz56AN0Ii7F1hJA zXVD^yfIN@+WO8RHBxUm=fthAVb8uWAsETQ*$2HMk>P@2UC|IUkx9RdrfZsX6q9);Y z-An|{7eTyK`^761aDoUKJ6lk#`H}V8D>E}GRl^X6If4Q^<8n=|W8x;9qf%b`nf_CA zfpZQ#+a)hY4v}CJTeSA*VBemy9P*@4r!mv7RD9g%X)*FSHWV@VPww zw<9Z|!$UNpa<{~?kN5feK@{>S`&c;NwlQ(i-k}zm<~>0`pMuHcD<#sMu_mzYEsIIIN+Ids4T?&S4ndMt%w|_5BdN(nK_DO)Ez*DZ1uALJaz`JyoY4BC0lE zOop!3v=OQo@?27m{yKi|2USrC07Kx|zn3)aPG2UHoCeo;RX?TnyO{CI1Ote0Zi8P% z(M7v5ueV9alcEtXZz+U?iTTYbg?OapPq_Lbv$H|-b^b-pN^5+i2Fx){bfs%DGcR4b z$4fLc*c`fn@@lL|KA_=xU>ywwO8DJ=ke$%Gf>0k0E}z8YuC@2LP+$z7IIEjM-Z;=m zFQbj>VwH5W?i#u!%M-X^i@(x(k^H1;k>q5HPm#mzGKp%e&NeV&g=#oM+InmRdt6pv zcp-gi^_krB(;EFRI4-?{59y}gk0M4DtTR!n5zruv5O0juB)RqvBDxuwit)6-%I;c? zlP_dqjNMfa2y4Sm=ByU#-V#iP4%s)bRQ%R4K_3aK(pzs}u$WAy<##tQWek4Y7-ll? zv4G-d&{>2@<_bLMJX*Ir{JJ7HMdH|+NZynlg9j?|Vj!WM=gX3IvF@jesXM{ns#4hO zOh+6trNstMhqKJrtz*xt{D^^+QS3xO#&m^x4i!;Gq6(D!9~9|lh@y{fOGGeNDIy5> zhW^+l#U>ltezry@g3OIagxYeu>_nu&32P^*PmZ0Z!%x_dIdhY zt>2$^rBr?Y?cC0{KO+^$t#2G=patCM%@93I;>(qe9=O8W7iU+vIXz01xJF59U6@ z7Mvw)dgiDVg-{5Z%;8Zi4pRx+QlBS3q@(fzsUxOqqt~wUfFd`n%o+O;G5sUVzr*e1&WZ)s!_lB#=J4I ztP-;f$>#mtS4{y06TQsqjA}sz8&%57KkR6rIB+A5=tp z+qb>JWOj%|FO5Oi3@1y?<3nGt^ErUK*bU<1wDoWNDB~73a23BljiXo%rk86lI+G81 zL-f+}=!P)G@)aHrjxKpFw}L^)`)PpU5E|}3?!0ppyyLk%`WAmPt*NpX_BH7;caJ-# zzScXG@Wr`A{y`cFQ)+a`cq9cRF-xSH6;uWCS3a}1O11IGvNGs?A7-Gcdm3$gdSzja z5oD&l|H>mPiM7}O*mUOMz2N)tlQw0Kh>#3vPaR*CU~C--K&AjfQSK*{3D#?}wzR+a zOxwn%bhijQwAu;73by8H{3HTK)AU~cCCjVsS|S3GxZLSmbgeqZjd7W?$x5TDix$d2 zHkar^os671y7P;!))KJPdPA#cuBo!viFeY;Q6DTHPu60#kffkIH?}xSb>y{t{lXLO zjd#;Kjb4RqLE6sl2RulRs=-AL8=>tf?GU_hJ-l@nFwaJGzbg}j1In2yt0|-;B4@^9 zVU==<#(Aw}Oft9qr7PNxB~d)B(>Ig zA-840;FRQ=o6H^m(cqZ+E4b4UkqvXa^}G1&iVhP|$>YvX{ao}(LJ>cd3fHwhcU)4- zclS*UN$i~=ZZry{uzS4EO+GrSqI481==jtRirrGf=`SB#lR4A`oK4v9ns@aMWEm;d z#(BPr=WZ#C3!BiKOy*R?h>u6 z1+-VYPn3}lH);uQ@b|n}O-2x`;N0MNCv_6?b1`suXpeA7jlbNzWL#)`?AGLwxL0_! z;!0JBX52j*hVD;SNYk9@>f)PtI}X#5vnl0|+{#StNy%(kO{r6TMCh&srg}hibC}J_ zkP}SRDc!b$gF!`h^lf^zw34P68)T2oQJGGn+l*x-VX(qB7xI-U zS|crfZHMAvT5SQUOzPqgpH!CV$*`SDrR1on8VmlThZEW-&mo>Q)JeoM!-*adtq4lH zdImelxl%TywTFOGZ`gO8aMFm0SJ@EG@c!5#;}S0~b5>`3R?6Ft zyWBz!oG`9drf)@8-#v-5fJ{f5j{XCDaC5-Kc7pCUc4Cv1TB==&l#!@E6fiL%`msmld zCDywvh;6)0<>aCos!W>ecYORED#pznJiplN9I)6>$dp|KI+eNT0q=n4#u1&)W$zUy zK$fsP_L@O-wFpd{s9^c7gW{Qhe-KD5?75#FZlh%TS*33sUCqgx#bl880ptp8L=zT%R2Q@P30+%iWBBaoF? zK=N8?)3$4GVIEBFxuw|{;TTc?{KDKu>@#6yOL=Ki>|wd0N5J!IlK*Bw$Mjj1HJ8{D z;}czYZe>_1Uv8;rF^0pR^Yg_RN@ zxCg_K)2g_-r2x4#g_Amnx3@Sy$gnJ*BzVX3RqI$S(2v?t2kvkswa2{PX zBXMbbC6|gDJektku0*M;HBi4dAR09OeD-^-cvn@$q-aMQNU9U$?>i0wkH_s5KU@Hg z56tQZxi%E1EdWK@GK%31pzB#DU|nm5gSW&mr}Ow_!$i7+uf*^kINf;C;lR0EYtPY%VL0pWD|me`Sc9h=K7WrO0OkR z70~A5Bhmfn@CD|%=tD4s@DS&BXu4V`sAPcu?yn;E(EoP)2e0;x8)-@INrFf>Qth literal 0 HcmV?d00001 From bcbca1f6a1bcce224673fb89020d23e8cd1701c5 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:43:58 -0600 Subject: [PATCH 07/19] Add diagram Batch B scene model, corridors, frames, bars, nested groups, and auto-layout placement Co-Authored-By: Gemini 4 Neon --- packages/react/build.mjs | 1 + packages/react/src/diagram-interop.ts | 42 +- packages/react/src/interop/scene.ts | 984 ++++++++++++++++++++++---- packages/react/src/interop/types.ts | 86 ++- 4 files changed, 959 insertions(+), 154 deletions(-) diff --git a/packages/react/build.mjs b/packages/react/build.mjs index cc463508..38dfe52c 100644 --- a/packages/react/build.mjs +++ b/packages/react/build.mjs @@ -117,6 +117,7 @@ await esbuild.build({ 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)), diff --git a/packages/react/src/diagram-interop.ts b/packages/react/src/diagram-interop.ts index 8e4f5dd5..a9e56b5d 100644 --- a/packages/react/src/diagram-interop.ts +++ b/packages/react/src/diagram-interop.ts @@ -1,13 +1,14 @@ -// @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314) +// @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 { DiagramSpec, Geo } from "./diagram-core"; +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, @@ -32,12 +33,17 @@ import type { LucidTableCell, MeasuredBand, MeasuredExtras, + MeasuredFrame, + MeasuredFrameDivider, MeasuredGroup, MeasuredInteropOptions, MeasuredLane, SceneBand, + SceneBar, SceneBox, SceneEdge, + SceneFrame, + SceneFrameDivider, SceneGroup, SceneLabel, SceneLane, @@ -48,6 +54,31 @@ import type { 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 { + 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); @@ -90,6 +121,8 @@ export function exportMeasuredDiagram(spec: DiagramSpec, geo: Geo, format: Inter export { bundledMarkAttribution, isBundledMarkEmbeddable, layoutHeadless as measureDiagramHeadless, readMeasuredExtras }; export type { + DiagramCardinality, + DiagramPlacement, DiagramSpec, Geo, InteropFormat, @@ -116,12 +149,17 @@ export type { LucidTableCell, MeasuredBand, MeasuredExtras, + MeasuredFrame, + MeasuredFrameDivider, MeasuredGroup, MeasuredInteropOptions, MeasuredLane, SceneBand, + SceneBar, SceneBox, SceneEdge, + SceneFrame, + SceneFrameDivider, SceneGroup, SceneLabel, SceneLane, diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts index 07eab226..38eb3b30 100644 --- a/packages/react/src/interop/scene.ts +++ b/packages/react/src/interop/scene.ts @@ -1,20 +1,25 @@ -// Shared scene builder for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314). +// 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, groupReach } from "../diagram-core"; -import type { DiagramSide, DiagramSpec, GLine, GNode, Geo, MNode, Model, Pt, Rect } from "../diagram-core"; +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, @@ -480,6 +485,54 @@ function headBox(tip: Pt, dir: "up" | "down" | "left" | "right"): Rect { 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[]): 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"]; + for (const dir of order) { + const cand = raw.find((p) => p.direction === dir); + if (cand && !buildModel(spec, { checks: false, placement: cand }).unplaced) return cand; + } + return raw.find((p) => !buildModel(spec, { checks: false, placement: p }).unplaced) ?? raw[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 } { @@ -496,7 +549,7 @@ function computeMinimums(m: Model, hasMarks: boolean): { track: number; table: n continue; } const pad = n.shape === "terminal" ? 40 : 24; - const seat = hasMarks && n.mark ? 24 : 0; + 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); @@ -508,13 +561,21 @@ function computeMinimums(m: Model, hasMarks: boolean): { track: number; table: n 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") least = n * table + (n - 1) * 48 + (oneColTurnBack ? 20 : 0); - else if (m.type === "sequence") least = n * track + (n - 1) * 20; + 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): { h: number; rows?: SceneTableRow[]; headerH?: number } { +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; @@ -564,8 +625,9 @@ function measureNodeHeight(n: MNode, trackW: number, hasMark: boolean): { h: num } if (n.shape === "participant") { const inner = Math.max(40, trackW - 26); - const kindLines = n.kind ? Math.max(1, wrapText(n.kind, "mono", inner).lines) : 0; - const nameLines = Math.max(1, wrapText(n.name, "name", inner).lines); + 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. @@ -576,7 +638,7 @@ function measureNodeHeight(n: MNode, trackW: number, hasMark: boolean): { h: num 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: 2 + 20 + kindLines * 16 + nameLines * 20 + detailGap + detailLines * 16 }; + return { h: Math.max(minH, 2 + 20 + kindLines * 16 + nameLines * 20 + detailGap + detailLines * 16) }; } function seatSceneLabels( @@ -616,8 +678,9 @@ function seatSceneLabels( for (const edge of order) { const text = m.edges[edge.index]!.label!; - const w = measureText(text, "label"); - const hgt = 16; + 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; @@ -695,9 +758,35 @@ function seatSceneLabels( 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 m = buildModel(spec, { checks: false }); + const placement = pickPlacement(spec, options.placement); + 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 marksMode = options.marks ?? "omit"; const hasMarks = marksMode === "embed" && m.nodes.some((n) => Boolean(resolveNodeMark(n, marksMode, options.resolveMark))); @@ -706,23 +795,24 @@ export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): const id = options.diagramId ?? slugId(m.title || m.type); if (m.type === "sequence") { - return layoutSequenceHeadless(m, targetW, pad, id); + 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 members = m.groups.flatMap((g) => g.members.map((gid) => m.byId.get(gid)!)); - if (members.some((n) => n.row === 1)) padTop = 32; - if (members.some((n) => n.col === m.cols)) padRight = 16; - if (members.some((n) => n.row2 === m.rows)) padBottom = 16; - if (members.some((n) => n.col === 1)) padLeft = 16; + 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) { - padRight = 20; + const tb = turnBackLanes(m); + padRight = (m.marks ? 28 : 20) + (tb.lanes > 1 ? 12 : 0); } - const colGap = m.type === "data-flow" || m.type === "schema" ? 48 : 64; + 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; @@ -747,38 +837,81 @@ export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): } } - // Measure each node height and compute row track heights + // Measure each node height and compute row track heights (applying portFloors for multi-port boxes) + const floors = portFloors(m); const nodeMeasured = new Map(); 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 meas = measureNodeHeight(n, trackW, Boolean(mark)); + 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]) - 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 += rowHeights[r - 1]!; - spanH += (n.row2 - n.row) * rowGap; - if (meas.h > spanH) { - rowHeights[n.row2 - 1] = rowHeights[n.row2 - 1]! + (meas.h - spanH); + 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); - const gridRows: Array<[number, number]> = []; - let curY = padTop; - for (let r = 0; r < m.rows; r++) { - const rh = Math.max(40, rowHeights[r]!); - gridRows.push([round2(curY), round2(curY + rh)]); - curY += rh + rowGap; + // Schema far keys (|a.col - b.col| >= 2): choose corridors once on the unpadded grid, then widen used gaps/margins. + let corridorPick: Map | undefined; + if (m.type === "schema" && gridRows.length > 0) { + const picked = new Map(); + const used = new Set(); + 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); @@ -827,23 +960,32 @@ export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): gNodeMap.set(n.id, { id: n.id, rect: boxToRect(box), shape: n.shape, i: n.i }); } - // Groups (architecture) + // 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 mem = g.members.map((gid) => m.byId.get(gid)!).filter(Boolean); - if (!mem.length) continue; - const c1 = Math.min(...mem.map((n) => n.col)); - const c2 = Math.max(...mem.map((n) => n.col)); - const r1 = Math.min(...mem.map((n) => n.row)); - const r2 = Math.max(...mem.map((n) => n.row2)); - const l = round2(gridCols[c1 - 1]![0] - 16); - const r = round2(gridCols[c2 - 1]![1] + 16); - const t = round2(gridRows[r1 - 1]![0] - 32); - const b = round2(gridRows[r2 - 1]![1] + 16); + 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, box: { x: l, y: t, w: round2(r - l), h: round2(b - t) }, members: g.members }); + 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 } : {}), + }); } } @@ -875,8 +1017,8 @@ export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): 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 lane solver - const sceneEdges = routeEdges(m, nodeById, gNodeMap, gridCols, gridRows); + // 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 }); @@ -900,11 +1042,14 @@ export function layoutHeadless(spec: DiagramSpec, options: InteropOptions = {}): width: drawingW, height: drawingH, pad, + ...(options.measuredBy ? { measuredBy: options.measuredBy } : {}), nodes: sceneNodes, groups: sceneGroups, lanes: sceneLanes, lifelines: [], bands: [], + frames: [], + bars: [], edges: sceneEdges, }; } @@ -915,38 +1060,60 @@ function routeEdges( gNodeMap: Map, gridCols: Array<[number, number]>, gridRows: Array<[number, number]>, + corridorPick?: Map, ): SceneEdge[] { const trackOf = (n: MNode) => (m.type === "data-flow" ? n.col + 1 : n.col); - const dropped = new Set(); + const tbInfo = turnBackLanes(m); + const dropped = new Set(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(); if (m.type === "schema") { + const at = new Map(); m.edges.forEach((e, k) => { - if (Math.abs(m.byId.get(e.from)!.col - m.byId.get(e.to)!.col) > 1) dropped.add(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); + } + } } - // Determine sides and exact fractional ports - const derived = m.type === "schema" ? [] : derivedPorts(m); const edgeMeta = m.edges.map((e, k) => { - const a = m.byId.get(e.from)!; - const b = m.byId.get(e.to)!; const na = nodeById.get(e.from)!; const nb = nodeById.get(e.to)!; - let s1: DiagramSide, s2: DiagramSide, fromPort: ScenePort, toPort: ScenePort; + const [s1, s2] = sides[k]!; + let fromPort: ScenePort, toPort: ScenePort; if (m.type === "schema") { - if (a.col === b.col) { - const side: DiagramSide = a.col === m.cols && m.cols > 1 ? "left" : "right"; - s1 = side; s2 = side; - } else { - s1 = b.col > a.col ? "right" : "left"; - s2 = opposite[s1]; - } 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); + 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]!; - s1 = dp.fromSide; s2 = dp.toSide; fromPort = portForSideSlot(s1, dp.fromSlot); toPort = portForSideSlot(s2, dp.toSlot); } @@ -963,52 +1130,123 @@ function routeEdges( return { s1, s2, fromPort, toPort, p1, p2 }; }); + // Schema far keys through their corridors (mirroring diagram-core.ts) + const far = new Map(); + 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(); + 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 }>(); const turnBacks = new Set(); + const farLast = new Map(); + const join = (key: string, span: [number, number], vertical: boolean, port: string, id: number) => { + if (!jogs.has(key)) jogs.set(key, { span, vertical, members: new Map() }); + const g = jogs.get(key)!; + if (!g.members.has(port)) g.members.set(port, []); + g.members.get(port)!.push(id); + }; - m.edges.forEach((e, k) => { - if (dropped.has(k)) return; - 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 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) turnBacks.add(k); - } else if (isH(s1) && isH(s2) && Math.abs(p1.y - p2.y) > 0.5) { - const ti = trackOf(b); - const leftSide = s2 === "left"; - const t1 = 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 (!jogs.has(key)) jogs.set(key, { span, vertical, members: new Map() }); - const portKey = `${e.to}.${s2}.${Math.round(vertical ? p2.y : p2.x)}`; - const g = jogs.get(key)!; - if (!g.members.has(portKey)) g.members.set(portKey, []); - g.members.get(portKey)!.push(k); - }); + 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(); 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 x = round2(lanes.get(k) ?? (s1 === "right" ? Math.max(p1.x, p2.x) + 16 : Math.min(p1.x, p2.x) - 16)); + 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]; @@ -1048,12 +1286,18 @@ function routeEdges( 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((k) => { const { p1, p2 } = edgeMeta[k]!; return vertical ? [p1.y, p2.y] : [p1.x, p2.x]; }); + 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)]; }; - - for (const [, g] of jogs) { + const clustersOf = (g: { span: [number, number]; vertical: boolean; members: Map }) => { const ports = [...g.members.values()].map((members) => ({ members, run: runOf(members, g.vertical) })).sort((a, b) => a.run[0] - b.run[0]); const clusters: Array = []; for (const p of ports) { @@ -1061,19 +1305,98 @@ function routeEdges( 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]); } - for (const cluster of clusters) { - if (cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k))) continue; + return clusters.filter((cluster) => !(cluster.length === 1 && cluster[0]!.members.every((k) => turnBacks.has(k)))); + }; + type Cluster = ReturnType[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 step = (g.span[1] - g.span[0]) / (count + 1); - const inGutter = new Set(groupsOf.flat()); + 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, g.span[0] + step * (j + 1)))); + perm.forEach((members, j) => members.forEach((k) => lanes.set(k, laneAt(g.span, j, count)))); const tried = score(inGutter); if (tried.score < bestScore) { bestScore = tried.score; best = perm; bestLines = tried.lines; } } - best.forEach((members, j) => members.forEach((k) => lanes.set(k, g.span[0] + step * (j + 1)))); + best.forEach((members, j) => members.forEach((k) => lanes.set(k, laneAt(g.span, j, count)))); current = bestLines; } } @@ -1083,6 +1406,12 @@ function routeEdges( 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, @@ -1090,6 +1419,7 @@ function routeEdges( 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, @@ -1100,12 +1430,31 @@ function routeEdges( return out; } -function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: string): InteropScene { +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 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; - for (const p of m.nodes) headH = Math.max(headH, measureNodeHeight(p, colW, false).h); + 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)); @@ -1121,6 +1470,7 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri shape: "participant", short: p.short, box: { x, y: 0, w: colW, h: headH }, + ...(marksByNode[idx] ? { mark: marksByNode[idx] } : {}), }; }); @@ -1129,13 +1479,50 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri 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(); 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 frame: SceneFrame = { + id: `f${frames.length}`, + operator: s.open, + label: s.label, + depth: s.depth, + ...(parent ? { parentId: parent.frame.id } : {}), + box: { x: fx, y: round2(y), w: fw, h: 44 }, + tabBox: { x: round2(fx + 1), y: round2(y + 1), w: tabW, h: 24 }, + 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) cur.frame.dividers.push({ y: round2(y), h: 28, label: s.otherwise }); + 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; @@ -1154,6 +1541,31 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri })); 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)!; @@ -1162,24 +1574,50 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri 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: lf1.x, y: yt }, + { x: edgeX, y: yt }, { x: round2(lf1.x + out), y: yt }, { x: round2(lf1.x + out), y: yb }, - { x: lf1.x, y: yb }, + { x: edgeX, y: yb }, ]; - fromPort = { x: 0.5, y: round4((yt - lf1.y1) / span1), side }; - toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + 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: round4((yt - lf1.y1) / span1), side }; + toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + } } else { const dirRight = lf2.x >= lf1.x; - pts = [{ x: lf1.x, y: s.y }, { x: lf2.x, y: s.y }]; - fromPort = { x: 0.5, y: round4((s.y - lf1.y1) / span1), side: dirRight ? "right" : "left" }; - toPort = { x: 0.5, y: round4((s.y - lf2.y1) / span2), side: dirRight ? "left" : "right" }; + 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: round4((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: round4((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); @@ -1194,6 +1632,8 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri from: s.from, to: s.to, sequence: true, + ...(fromBarId ? { fromBarId } : {}), + ...(toBarId ? { toBarId } : {}), fk: false, kind: s.kind, openTip: s.kind === "dashed", @@ -1218,11 +1658,14 @@ function layoutSequenceHeadless(m: Model, targetW: number, pad: number, id: stri width: round2(targetW), height: bottom, pad, + ...(measuredBy ? { measuredBy } : {}), nodes: sceneNodes, groups: [], lanes: [], lifelines, bands, + frames, + bars, edges, }; } @@ -1237,7 +1680,7 @@ function portFromBoxAndPoint(box: SceneBox, pt: Pt, exactRow: boolean): ScenePor 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(Math.max(0, Math.min(1, v))); + 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; @@ -1256,7 +1699,8 @@ export function sceneFromMeasured( extras: MeasuredExtras = {}, options: InteropOptions = {}, ): InteropScene { - const m = buildModel(spec, { checks: false }); + 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); @@ -1307,23 +1751,43 @@ export function sceneFromMeasured( }); const nodeById = new Map(sceneNodes.map((n) => [n.id, n])); - // Groups + // 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])); - for (const g of m.groups) { + // Compute fallback rects bottom-up so an outer group encloses its child groups cleanly when extras.groups is omitted. + const computedBox = new Map(); + for (const g of [...m.groups].reverse()) { const eg = extraById.get(g.id); if (eg) { - sceneGroups.push({ id: g.id, label: g.label, box: rectToBox(eg.rect), members: g.members }); - } else { - const mem = g.members.map((gid) => nodeById.get(gid)).filter((x): x is SceneNode => Boolean(x)); - if (!mem.length) continue; - const l = round2(Math.min(...mem.map((x) => x.box.x)) - 16); - const r = round2(Math.max(...mem.map((x) => x.box.x + x.box.w)) + 16); - const t = round2(Math.min(...mem.map((x) => x.box.y)) - 32); - const b = round2(Math.max(...mem.map((x) => x.box.y + x.box.h)) + 16); - sceneGroups.push({ id: g.id, label: g.label, box: { x: l, y: t, w: round2(r - l), h: round2(b - t) }, members: g.members }); + 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 } : {}), + }); } } @@ -1351,12 +1815,12 @@ export function sceneFromMeasured( } } - // Sequence lifelines, bands, messages + // 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(box.x + box.w / 2); + 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])); @@ -1379,6 +1843,126 @@ export function sceneFromMeasured( } } + // 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 }; + frames.push({ + id: `f${idx}`, + operator: ef.operator, + label: ef.label, + depth: ef.depth, + ...(ef.parentIndex !== undefined ? { parentId: `f${ef.parentIndex}` } : {}), + box, + tabBox, + dividers: ef.dividers.map((d) => ({ y: round2(d.y), h: round2(d.h), label: d.label })), + }); + }); + } 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 frame: SceneFrame = { + id: `f${frames.length}`, + operator: s.open, + label: s.label, + depth: s.depth, + ...(parent ? { parentId: parent.frame.id } : {}), + box: { x: fx, y: 0, w: round2(Math.max(40, fr - fx)), h: 44 }, + tabBox: { x: round2(fx + 1), y: 1, w: tabW, h: 24 }, + 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); + cur.frame.dividers.push({ y: divY, h: 28, label: s.otherwise }); + } + } 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); + } + } 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; @@ -1394,20 +1978,46 @@ export function sceneFromMeasured( let pts: Pt[]; let fromPort: ScenePort; let toPort: ScenePort; + let fromBarId: string | undefined; + let toBarId: string | undefined; if (self) { - const out = selfSide === "start" ? -24 : 24; const side: DiagramSide = selfSide === "start" ? "left" : "right"; const yt = round2(gl.pts[0]!.y); const yb = round2(gl.pts[gl.pts.length - 1]!.y); - pts = [{ x: lf1.x, y: yt }, { x: round2(lf1.x + out), y: yt }, { x: round2(lf1.x + out), y: yb }, { x: lf1.x, y: yb }]; - fromPort = { x: 0.5, y: round4((yt - lf1.y1) / span1), side }; - toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + 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; - pts = [{ x: lf1.x, y }, { x: lf2.x, y }]; - fromPort = { x: 0.5, y: round4((y - lf1.y1) / span1), side: dirRight ? "right" : "left" }; - toPort = { x: 0.5, y: round4((y - lf2.y1) / span2), side: dirRight ? "left" : "right" }; + 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); @@ -1421,6 +2031,8 @@ export function sceneFromMeasured( from: s.from, to: s.to, sequence: true, + ...(fromBarId ? { fromBarId } : {}), + ...(toBarId ? { toBarId } : {}), fk: false, kind: s.kind, openTip: s.kind === "dashed", @@ -1432,7 +2044,23 @@ export function sceneFromMeasured( }); } - return { type: "sequence", id, title: m.title, width: round2(geo.w), height: round2(geo.h), pad, nodes: sceneNodes, groups: [], lanes: [], lifelines, bands, edges }; + 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 @@ -1449,18 +2077,22 @@ export function sceneFromMeasured( let fromPort: ScenePort; let toPort: ScenePort; if (m.type === "schema") { - // Exact FK column row center + // 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]!; - fromPort = portForSideSlot(fromPort.side, (r.midY - src.box.y) / src.box.h); + 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]!; - toPort = portForSideSlot(toPort.side, (r.midY - dst.box.y) / dst.box.h); + 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]; @@ -1498,6 +2130,7 @@ export function sceneFromMeasured( fromRow: me.fromRow, toRow: me.toRow, fk: Boolean(me.fk), + ...(me.card ? { card: me.card } : {}), kind: gl.kind, openTip: gl.kind === "dashed", fromPort, @@ -1514,16 +2147,34 @@ export function sceneFromMeasured( 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, }; } -/** Reads optional group, lane, band, and table-row rects from a live diagram `
` element. */ +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 `
` element. */ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): MeasuredExtras { const drawing = fig.querySelector(`.${prefix}-drawing`); if (!drawing) return {}; @@ -1537,8 +2188,9 @@ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): Mea drawing.querySelectorAll(`.${prefix}-gbox`).forEach((el) => { const id = el.getAttribute("data-group"); if (!id || !el.getClientRects().length) return; - const label = el.querySelector(`.${prefix}-glabel`)?.textContent ?? ""; - groups.push({ id, label, rect: rectOf(el) }); + 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[] = []; @@ -1554,6 +2206,41 @@ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): Mea bands.push({ text: el.textContent ?? "", rect: rectOf(el) }); }); + const frames: MeasuredFrame[] = []; + const frameIndexByEl = new Map(); + 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 === "par" ? 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 dividers: MeasuredFrameDivider[] = []; + el.querySelectorAll(`:scope > .${prefix}-felse`).forEach((elseEl) => { + if (!elseEl.getClientRects().length) return; + const r = rectOf(elseEl); + const label = visibleTextOf(elseEl.querySelector(`.${prefix}-flabel`)); + dividers.push({ y: r.t, h: r.b - r.t, label }); + }); + const idx = frames.length; + frameIndexByEl.set(el, idx); + frames.push({ + operator, + label: visibleTextOf(flabel), + depth, + ...(parentIndex !== undefined ? { parentIndex } : {}), + rect: rectOf(fbox), + ...(ftab && ftab.getClientRects().length ? { tabRect: rectOf(ftab) } : {}), + dividers, + }); + }); + const tableRows: Record = {}; drawing.querySelectorAll(`.${prefix}-node[data-shape="table"]`).forEach((nodeEl) => { const id = nodeEl.getAttribute("data-node"); @@ -1570,6 +2257,7 @@ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): Mea 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 index 955e2a17..43af778c 100644 --- a/packages/react/src/interop/types.ts +++ b/packages/react/src/interop/types.ts @@ -1,6 +1,17 @@ -// Public and scene types for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314). +// 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 { DiagramLineKind, DiagramSide, DiagramSpec, DiagramType, Geo, MColumn, Pt, Rect } from "../diagram-core"; +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"; @@ -22,11 +33,16 @@ export interface InteropOptions { 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; } @@ -43,11 +59,28 @@ export interface MeasuredBand { rect: Rect; } +export interface MeasuredFrameDivider { + y: number; + h: number; + label: string; +} + +export interface MeasuredFrame { + operator: "opt" | "loop" | "alt" | "par"; + label: string; + depth: number; + parentIndex?: number; + rect: Rect; + tabRect?: 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; } @@ -122,8 +155,11 @@ export interface SceneNode { export interface SceneGroup { id: string; label: string; + parent?: string; + depth: number; box: SceneBox; members: string[]; + childGroups?: string[]; } export interface SceneLane { @@ -148,6 +184,32 @@ export interface SceneBand { w: number; } +export interface SceneFrameDivider { + y: number; + h: number; + label: string; +} + +export interface SceneFrame { + id: string; + operator: "opt" | "loop" | "alt" | "par"; + label: string; + depth: number; + parentId?: string; + box: SceneBox; + tabBox: 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; @@ -163,10 +225,15 @@ export interface SceneEdge { 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; @@ -187,11 +254,14 @@ export interface InteropScene { width: number; height: number; pad: number; + measuredBy?: string; nodes: SceneNode[]; groups: SceneGroup[]; lanes: SceneLane[]; lifelines: SceneLifeline[]; bands: SceneBand[]; + frames: SceneFrame[]; + bars: SceneBar[]; edges: SceneEdge[]; } @@ -277,7 +347,15 @@ export interface LucidShape { zIndex?: number; } -export type LucidEndpointStyle = "none" | "arrow" | "openArrow" | "closedCircle"; +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 } } @@ -320,4 +398,4 @@ export interface LucidDocument { pages: LucidPage[]; } -export type { DiagramSpec, Geo }; +export type { DiagramCardinality, DiagramPlacement, DiagramSpec, Geo }; From 145b9f9a5bfafdd40704a102e87c4d4d1f64f382 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:50:53 -0600 Subject: [PATCH 08/19] Emit Batch B crow's-foot, frames, bars, nested groups, and metadata in draw.io, Visio, and Lucid Co-Authored-By: Gemini 4 Neon --- packages/react/src/interop/drawio.ts | 242 ++++++++++++++++++--- packages/react/src/interop/lucid.ts | 194 ++++++++++++++--- packages/react/src/interop/vsdx.ts | 300 +++++++++++++++++++++++++-- 3 files changed, 662 insertions(+), 74 deletions(-) diff --git a/packages/react/src/interop/drawio.ts b/packages/react/src/interop/drawio.ts index 084f3d99..0bb40fc5 100644 --- a/packages/react/src/interop/drawio.ts +++ b/packages/react/src/interop/drawio.ts @@ -1,12 +1,25 @@ -// Deterministic draw.io (.drawio / mxGraphModel XML) exporter (DECISIONS 311, 314). +// 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, one glued orthogonal edge per Basalt edge, attached edgeLabel children, +// 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 { Pt } from "../diagram-core"; +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 = { + 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, "&") @@ -76,15 +89,20 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" // Exact emitted world boxes for every connectable vertex (used to snap waypoints in draw.io's own coordinates) const worldBoxByCell = new Map(); - // 1. Groups (architecture containers, lowest z-order) + // 1. Groups (architecture containers, outer-first so nested depth-2 groups parent inside depth-1) const groupBoxes = new Map(); 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) }; - groupBoxes.set(g.id, box); + 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=24", + `arcSize=${arcSize}`, "whiteSpace=wrap", "html=1", "container=1", @@ -106,8 +124,8 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" "fontStyle=0", ]); cells.push( - ` \n` + - ` \n` + + ` \n` + + ` \n` + ` `, ); } @@ -146,7 +164,7 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" ); } - // 3. Sequence lifelines & phase bands (drawn behind participant headers and messages) + // 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); @@ -204,13 +222,159 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" ); } + // 3b. Sequence frames (opt/loop/alt/par containers with corner operator tab and dashed branch dividers) + const frameBoxes = new Map(); + 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( + ` \n` + + ` \n` + + ` `, + ); + + 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( + ` \n` + + ` \n` + + ` `, + ); + + if (f.label) { + const lblX = round2(tabRelX + tabW + 8); + const lblW = round2(Math.max(40, worldBox.w - lblX - 8)); + const lblStyle = cellStyle([ + "text", + "html=1", + "strokeColor=none", + `fillColor=${col("page")}`, + "align=left", + "verticalAlign=middle", + "spacingLeft=4", + "spacingRight=4", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + ]); + cells.push( + ` \n` + + ` \n` + + ` `, + ); + } + + 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( + ` \n` + + ` \n` + + ` `, + ); + if (div.label || f.operator === "alt") { + const elseVal = f.operator === "alt" + ? `else` + + (div.label ? ` ${escXml(div.label)}` : "") + : escXml(div.label); + const elseStyle = cellStyle([ + "text", + "html=1", + "strokeColor=none", + `fillColor=${col("page")}`, + "align=left", + "verticalAlign=middle", + "spacingLeft=4", + "spacingRight=4", + `fontColor=${col("textSecondary")}`, + "fontFamily=Geist, Inter, Helvetica, Arial", + "fontSize=12", + ]); + cells.push( + ` \n` + + ` \n` + + ` `, + ); + } + }); + } + + // 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( + ` \n` + + ` \n` + + ` `, + ); + } + // 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 ? "padding-right:24px;" : ""; + const padMark = n.mark + ? (n.shape === "participant" ? "padding-left:24px;padding-right:24px;" : "padding-right:24px;") + : ""; if (n.shape === "decision") { return adaptive @@ -420,12 +584,12 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" // 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 - ? `life-${e.from}` + ? (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 - ? `life-${e.to}` + ? (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}`; @@ -435,10 +599,14 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" if (!srcBox || !dstBox) continue; // Exact exit/entry fractional ports on the referenced cell - const exitX = e.sequence ? 0 : round6(e.fromPort.x); - const exitY = e.fk && srcCellId.startsWith("row-") ? 0.5 : round6(e.fromPort.y); - const entryX = e.sequence ? 0 : round6(e.toPort.x); - const entryY = e.fk && dstCellId.startsWith("row-") ? 0.5 : round6(e.toPort.y); + 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) }; @@ -450,8 +618,21 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" const isDashed = e.kind === "dashed"; const strokeColor = isMain ? col("edgeMain") : col("edgePlain"); const strokeWidth = isMain ? 2 : 1; - const endArrow = e.openTip ? "open" : "block"; - const endFill = e.openTip ? 0 : 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", @@ -462,10 +643,7 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" "html=1", `strokeColor=${strokeColor}`, `strokeWidth=${strokeWidth}`, - `endArrow=${endArrow}`, - `endFill=${endFill}`, - "endSize=6", - ...(e.fk ? ["startArrow=oval", "startFill=1", "startSize=6"] : ["startArrow=none", "startFill=0"]), + ...arrowParts, `exitX=${exitX}`, `exitY=${exitY}`, "exitDx=0", @@ -516,10 +694,11 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" const lblBg = e.label.on || e.sequence ? "labelBackgroundColor=default;defaultLabelBackgroundColor=page" : "labelBackgroundColor=none"; + const mainTextHtml = escXml(e.label.text).replace(/\n/g, "
"); const lblValue = e.label.note - ? `
${escXml(e.label.text)}
` + + ? `
${mainTextHtml}
` + `
${escXml(e.label.note)}
` - : escXml(e.label.text); + : mainTextHtml; const lblStyle = cellStyle([ "edgeLabel", "html=1", @@ -542,11 +721,22 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light" } } + 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 ( - `\n` + + `\n` + ` \n` + ` \n` + ` \n` + diff --git a/packages/react/src/interop/lucid.ts b/packages/react/src/interop/lucid.ts index 09584554..d76ce3d3 100644 --- a/packages/react/src/interop/lucid.ts +++ b/packages/react/src/interop/lucid.ts @@ -1,15 +1,18 @@ -// Deterministic Lucid Standard Import (.lucid ZIP + document.json) exporter (DECISIONS 311, 314). +// 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 -// - roundedRectangleContainer (assistedLayout: false, magnetize: true), swimLanes, table, decision, terminator +// - 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 { Pt } from "../diagram-core"; +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, @@ -19,6 +22,13 @@ import type { import { makeDeterministicZip } from "./zip"; import type { ZipEntry } from "./zip"; +const LUCID_CARD: Record = { + one: "exactlyOne", + "zero-or-one": "zeroOrOne", + "one-or-many": "oneOrMore", + "zero-or-many": "zeroOrMore", +}; + function escHtml(s: string): string { return String(s) .replace(/&/g, "&") @@ -50,9 +60,11 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li const shapeBoxById = new Map(); const lifeByParticipant = new Map(); - // 1. Architecture group containers (lowest zIndex, assistedLayout: false keeps Basalt's grid) + // 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", @@ -60,14 +72,15 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li style: { fill: { type: "color", color: transparentFill }, stroke: { color: P.structure, width: 1, style: "dashed" }, - rounding: 24, // 12px radius * 2 + rounding: g.depth > 1 ? 16 : 24, // 8px radius-md for nested, 12px radius-lg for outer }, magnetize: true, assistedLayout: false, containerTitle: { text: `${escHtml(g.label)}`, }, - zIndex: 0, + customData: groupData, + zIndex: g.depth - 1, }); } @@ -121,7 +134,8 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li } // 4. Nodes (cards, flowchart shapes, participants, schema tables) - for (const n of scene.nodes) { + 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); @@ -136,6 +150,12 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li 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) }, + ...(nodeIdx === 0 && scene.measuredBy ? [{ key: "basalt_measured_by", value: scene.measuredBy }] : []), + ]; if (n.shape === "table") { const rows = n.rows ?? []; @@ -232,11 +252,7 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li ], verticalBorder: false, horizontalBorder: true, - customData: [ - { key: "basalt_id", value: n.id }, - { key: "basalt_col", value: String(n.col) }, - { key: "basalt_row", value: String(n.row) }, - ], + customData: nodeCustomData, zIndex: 10, }); continue; @@ -267,11 +283,7 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li boundingBox: box, style: shapeStyle, text: linesHtml.join(""), - customData: [ - { key: "basalt_id", value: n.id }, - { key: "basalt_col", value: String(n.col) }, - { key: "basalt_row", value: String(n.row) }, - ], + customData: nodeCustomData, zIndex: 10, }); @@ -297,15 +309,16 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li for (const lf of scene.lifelines) { const lineId = lucidId("life", lf.participantId); const pBox = shapeBoxById.get(lf.participantId); - const lx = pBox ? round2(pBox.x + pBox.w / 2) : round2(lf.x + pad); + 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: 0.5, y: 1 } } + ? { 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" }, @@ -313,6 +326,111 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li }); } + // 5b. Sequence frames (opt/loop/alt/par 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: `

${escHtml(f.operator)}

`, + zIndex: 7 + f.depth, + }); + if (f.label) { + const lblX = round2(tabBox.x + tabBox.w + 8); + const lblW = round2(Math.max(40, box.x + box.w - lblX - 8)); + shapes.push({ + id: lucidId("frame_label", f.id), + type: "rectangle", + boundingBox: { x: lblX, y: round2(tabBox.y + 2), w: lblW, h: 20 }, + style: { + fill: { type: "color", color: P.page }, + stroke: { color: transparentFill, width: 0 }, + textColor: P.textSecondary, + }, + text: `

${escHtml(f.label)}

`, + 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 txt = f.operator === "alt" + ? `else` + + (div.label ? ` ${escHtml(div.label)}` : "") + : `${escHtml(div.label)}`; + shapes.push({ + id: lucidId("frame_else", `${f.id}_${k}`), + type: "rectangle", + boundingBox: { x: round2(box.x + 12), y: round2(divY + 4), w: round2(Math.max(40, box.w - 24)), h: 20 }, + style: { + fill: { type: "color", color: P.page }, + stroke: { color: transparentFill, width: 0 }, + textColor: P.textSecondary, + }, + text: `

${txt}

`, + zIndex: 8 + f.depth, + }); + } + }); + } + + // 5c. Sequence activation bars (rectangles above lifelines/frames, glued to message endpoints) + const barBoxById = new Map(); + 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; @@ -324,12 +442,29 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li const lf1 = lifeByParticipant.get(e.from); const lf2 = lifeByParticipant.get(e.to); if (!lf1 || !lf2) continue; - const pos1 = round6(e.fromPort.y); - const pos2 = round6(e.toPort.y); - startPt = { x: lf1.x, y: round2(lf1.y1 + pos1 * (lf1.y2 - lf1.y1)) }; - endPt = { x: lf2.x, y: round2(lf2.y1 + pos2 * (lf2.y2 - lf2.y1)) }; - endpoint1 = { type: "lineEndpoint", style: "none", lineId: lf1.lineId, position: pos1 }; - endpoint2 = { type: "lineEndpoint", style: e.openTip ? "openArrow" : "arrow", lineId: lf2.lineId, position: pos2 }; + 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); @@ -340,8 +475,10 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li 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) }; - endpoint1 = { type: "shapeEndpoint", style: e.fk ? "closedCircle" : "none", shapeId: lucidId("node", e.from), position: { x: fx, y: fy } }; - endpoint2 = { type: "shapeEndpoint", style: e.openTip ? "openArrow" : "arrow", shapeId: lucidId("node", e.to), position: { x: tx, y: ty } }; + 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) })); @@ -368,9 +505,10 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li } if (e.label) { + const labelHtml = escHtml(e.label.text).replace(/\n/g, "
"); const texts: LucidLineText[] = [ { - text: `${escHtml(e.label.text)}`, + text: `${labelHtml}`, position: e.label.t, side: e.label.on ? "middle" : "top", }, diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts index 8685ece3..ee769ec7 100644 --- a/packages/react/src/interop/vsdx.ts +++ b/packages/react/src/interop/vsdx.ts @@ -1,10 +1,10 @@ -// Deterministic Microsoft Visio (.vsdx) OPC exporter (DECISIONS 311, 314). +// 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 { Pt } from "../diagram-core"; +import type { DiagramCardinality, Pt } from "../diagram-core"; import { paletteFor, round6, snapRouteToPorts } from "./scene"; import type { InteropScene, InteropTheme, SceneNode } from "./types"; import { makeDeterministicZip } from "./zip"; @@ -12,6 +12,13 @@ import type { ZipEntry } from "./zip"; const DPI = 96; +const VSDX_CARD: Record = { + one: 25, + "zero-or-one": 30, + "one-or-many": 28, + "zero-or-many": 29, +}; + function escXml(s: string): string { return String(s) .replace(/&/g, "&") @@ -61,8 +68,8 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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 so straight-line Connection rows - // align to 0.000000 in across boxes of different heights/widths (e.g. schema tables and sequence lifelines). + // 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(); for (const lf of scene.lifelines) { geomByKey.set(`life:${lf.participantId}`, { @@ -72,6 +79,14 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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), @@ -81,7 +96,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): }); } - // Collect deduplicated Connection rows required on each target shape/lifeline + // Collect deduplicated Connection rows required on each target shape/lifeline/bar const connsByKey = new Map(); const getConnIndex = (key: string, fx: number, fy: number, exactCx?: number, exactCy?: number): number => { const g = geomByKey.get(key); @@ -99,12 +114,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): }; const edgeConns = scene.edges.map((e) => { - const fromKey = e.sequence ? `life:${e.from}` : `node:${e.from}`; - const toKey = e.sequence ? `life:${e.to}` : `node:${e.to}`; + 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 ? 0.5 : e.fromPort.x; - const toFx = e.sequence ? 0.5 : e.toPort.x; + 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 fromIx = getConnIndex(fromKey, fromFx, e.fromPort.y); let toIx: number; if (e.pts.length === 2 && fromG && toG) { @@ -136,6 +155,10 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const laneSheetIds = scene.lanes.map(() => nextId++); const lifeSheetIds = scene.lifelines.map(() => nextId++); const bandSheetIds = scene.bands.map(() => nextId++); + const frameSheetId = new Map(); + for (const f of scene.frames) frameSheetId.set(f.id, nextId++); + const barSheetId = new Map(); + for (const bar of scene.bars) barSheetId.set(bar.id, nextId++); const nodeSheetId = new Map(); for (const n of scene.nodes) nodeSheetId.set(n.id, nextId++); @@ -193,17 +216,24 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ); } - // 1. Architecture groups as real Visio Containers (User.msvStructureType="Container" + Relationships) + // 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(12 / DPI); - const memberIds = g.members.map((mid) => nodeSheetId.get(mid)).filter((x): x is number => x !== undefined); - const relCell = memberIds.length - ? ` \n` + 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 + ? ` \n` : ""; shapeXml.push( ` \n` + @@ -297,7 +327,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ); } - // 3. Sequence lifelines & phase bands + // 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]!; @@ -377,6 +407,233 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ); } + // 3b. Sequence frames (opt/loop/alt/par 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 + ? ` \n` + : ""; + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + relCell + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
`, + ); + + 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); + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${escXml(f.operator)}\n` + + `
`, + ); + + if (f.label) { + const lblId = nextId++; + const lblX = f.tabBox.x + f.tabBox.w + 8; + const lblW = Math.max(40, f.box.x + f.box.w - lblX - 8); + const lwIn = n6(lblW / DPI); + const lhIn = n6(20 / DPI); + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${escXml(f.label)}\n` + + `
`, + ); + } + + f.dividers.forEach((div, k) => { + const divId = nextId++; + const divHIn = n6(2 / DPI); + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
`, + ); + if (div.label || f.operator === "alt") { + const elseId = nextId++; + const elseW = Math.max(40, f.box.w - 24); + const ewIn = n6(elseW / DPI); + const ehIn = n6(20 / DPI); + const isAlt = f.operator === "alt"; + const charXml = isAlt + ? ` \n` + + ` ` + : ` `; + const txtXml = isAlt + ? `else${div.label ? ` ${escXml(div.label)}` : ""}` + : `${escXml(div.label)}`; + shapeXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `${charXml}\n` + + `
\n` + + `
\n` + + ` \n` + + `
\n` + + ` ${txtXml}\n` + + `
`, + ); + } + }); + } + + // 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + connRowsXml + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
`, + ); + } + // 4. Node shapes for (const n of scene.nodes) { const id = nodeSheetId.get(n.id)!; @@ -598,8 +855,8 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -678,8 +935,8 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const lineColor = isMain ? P.edgeMain : P.edgePlain; const lineWeight = isMain ? ptToIn(1.5) : ptToIn(0.75); const linePattern = isDashed ? 2 : 1; - const beginArrow = e.fk ? 10 : 0; // 10 = filled circle dot for FK origin - const endArrow = e.openTip ? 1 : 4; // 1 = open V, 4 = filled block triangle + 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 const radIn = n6((e.sequence && e.from === e.to ? 4 : 8) / DPI); const geomRows = vPts.map((pt, k) => { @@ -786,6 +1043,9 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + `\n`; + const creator = scene.measuredBy + ? `Basalt Diagram Exporter (${scene.measuredBy})` + : "Basalt Diagram Exporter"; const descLine = attributions.length ? ` ${escXml(attributions.join(" "))}\n` : ""; @@ -794,7 +1054,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): `\n` + ` \n` + ` ${escXml(scene.title || scene.id)}\n` + - ` Basalt Diagram Exporter\n` + + ` ${escXml(creator)}\n` + descLine + ` \n` + ` \n` + From 66880bda2da5f39e2713772561107bc47604ab1b Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:01:09 -0600 Subject: [PATCH 09/19] Default CLI to exact browser measurement via optional playwright peer with approximate headless fallback Co-Authored-By: Gemini 4 Neon --- dependencies.allowed.json | 2 + package-lock.json | 6 + packages/react/bin/basalt-diagram-export.mjs | 182 ++++++++++++++----- packages/react/package.json | 6 + scripts/verify-packages.mjs | 49 ++++- 5 files changed, 192 insertions(+), 53 deletions(-) diff --git a/dependencies.allowed.json b/dependencies.allowed.json index b0a0ed36..d097218e 100644 --- a/dependencies.allowed.json +++ b/dependencies.allowed.json @@ -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 327). 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", "react": ">=19", "react-dom": ">=19" } diff --git a/package-lock.json b/package-lock.json index 93dba05c..f68e6ac3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7258,8 +7258,14 @@ "typescript": "7.0.2" }, "peerDependencies": { + "playwright": ">=1.40.0", "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 index 14c064fb..5056053b 100755 --- a/packages/react/bin/basalt-diagram-export.mjs +++ b/packages/react/bin/basalt-diagram-export.mjs @@ -1,13 +1,16 @@ #!/usr/bin/env node -// basalt-diagram-export (DECISIONS 311, 314) +// basalt-diagram-export (DECISIONS 311, 314, 324, 327) // Deterministically exports Basalt diagram JSON (or `` + - `
` + + `
` + ``; - const context = await browser.newContext({ viewport: { width: Math.max(width + 128, 1280), height: 1200 }, deviceScaleFactor: 2 }); + 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()); @@ -315,11 +350,11 @@ async function measureInBrowser(items, width) { 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 measured = await page.evaluate(() => window.__measureAll()); + const results = await page.evaluate(() => window.__measureAll()); if (pageErrors.length) { - throw new Error(`basalt-diagram-export: --browser page error: ${pageErrors.join("; ")}`); + throw new Error(`basalt-diagram-export: browser page error: ${pageErrors.join("; ")}`); } - return measured; + return { measuredBy, results }; } finally { await browser.close(); } @@ -333,12 +368,14 @@ function parseArgs(argv) { 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"); @@ -370,7 +407,28 @@ function parseArgs(argv) { if (!input) input = arg; else throw new Error(`basalt-diagram-export: unexpected argument "${arg}"`); } - return { input, to, theme, marks, out, width, browser, help }; + 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() { @@ -418,8 +476,25 @@ async function main() { } const singleFileOut = looksLikeFileOut; + items = await prepareItems(items); + const resolveMark = opts.marks === "embed" ? createMarkResolver(path.dirname(inputPath)) : undefined; - const measuredList = opts.browser ? await measureInBrowser(items, opts.width) : null; + 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; + process.stderr.write( + `basalt-diagram-export: warning: ${err.message}; falling back to approximate headless geometry\n`, + ); + } + } const outDir = singleFileOut ? path.dirname(path.resolve(opts.out)) @@ -428,13 +503,28 @@ async function main() { const written = []; for (let idx = 0; idx < items.length; idx++) { - const { name, spec } = items[idx]; + const { name, spec, placements } = items[idx]; const measured = measuredList ? measuredList[idx] : null; - const baseOpts = { theme: opts.theme, marks: opts.marks, resolveMark, width: opts.width, diagramId: name }; + const useMeasured = Boolean(measured?.geo); + const engineLabel = useMeasured ? measuredBy : HEADLESS_ENGINE; + if (measuredList && !useMeasured) { + process.stderr.write( + `basalt-diagram-export: warning: "${name}" did not fit drawn in Chromium; falling back to approximate headless geometry\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 (measured?.geo) { + 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") { diff --git a/packages/react/package.json b/packages/react/package.json index 95f9ddbd..808d573c 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -63,9 +63,15 @@ "test": "node ../../scripts/test-react.mjs" }, "peerDependencies": { + "playwright": ">=1.40.0", "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/scripts/verify-packages.mjs b/scripts/verify-packages.mjs index 1ea58997..7ff60e8e 100644 --- a/scripts/verify-packages.mjs +++ b/scripts/verify-packages.mjs @@ -1,7 +1,7 @@ // Build first. Test the packed artifacts in a fresh consumer outside the monorepo, so missing // exports, declarations, assets and accidental reliance on workspace resolution are caught. import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -34,8 +34,16 @@ try { packages[""] = { name: manifest.name, version: manifest.version, dependencies: manifest.dependencies }; for (let index = 0; index < packedPackages.length; index++) { const { packed, manifest: pkg } = packedPackages[index]; - // `bin` is in the lock entry as npm writes it, so `npm ci` links node_modules/.bin as a real install does (B1: the CLI run through that link). - packages[`node_modules/${pkg.name}`] = { version: pkg.version, resolved: `file:${archives[index]}`, integrity: packed.integrity, dependencies: pkg.dependencies, peerDependencies: pkg.peerDependencies, ...(pkg.bin ? { bin: pkg.bin } : {}) }; + // `bin` and `peerDependenciesMeta` are copied as npm writes them, so `npm ci` links node_modules/.bin and keeps optional peers optional. + packages[`node_modules/${pkg.name}`] = { + version: pkg.version, + resolved: `file:${archives[index]}`, + integrity: packed.integrity, + dependencies: pkg.dependencies, + peerDependencies: pkg.peerDependencies, + ...(pkg.peerDependenciesMeta ? { peerDependenciesMeta: pkg.peerDependenciesMeta } : {}), + ...(pkg.bin ? { bin: pkg.bin } : {}), + }; } fs.writeFileSync(path.join(consumer, "package-lock.json"), JSON.stringify({ name: manifest.name, version: manifest.version, lockfileVersion: 3, requires: true, packages })); run("npm", ["ci", "--offline", "--ignore-scripts", "--no-audit", "--no-fund"], consumer); @@ -97,6 +105,12 @@ const phosphor = await import('@srasyndicate/basalt/phosphor'); assert.deepEqual const interop = await import('@srasyndicate/basalt/diagram-interop'); assert.equal('diagramToDrawio' in await import('@srasyndicate/basalt'), false, 'diagram-interop stays outside the root export'); assert.match(interop.diagramToDrawio({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }), //); assert.ok(interop.diagramToVsdx({ type: 'architecture', title: 'T', summary: 'S', nodes: [{ id: 'a', name: 'A', col: 1, row: 1 }], edges: [] }).length > 0); console.log('Packed consumer: runtime, server rendering, exact token types, exports, fonts and RSC boundary pass.');`); process.stdout.write(run(process.execPath, ["smoke.mjs"], consumer)); + // Remove Playwright and elkjs from the consumer so we test the packed CLI's no-Playwright fallback, + // strict --browser error, and bundled dist/diagram-elk.js auto-layout without launching Chromium. + fs.rmSync(path.join(consumer, "node_modules", "playwright"), { recursive: true, force: true }); + fs.rmSync(path.join(consumer, "node_modules", "playwright-core"), { recursive: true, force: true }); + fs.rmSync(path.join(consumer, "node_modules", "elkjs"), { recursive: true, force: true }); + // Run the installed CLI through its node_modules/.bin symlink (guards B1: symlinked bin must execute and write files). const binPath = path.join(consumer, "node_modules", ".bin", "basalt-diagram-export"); assert.ok(fs.existsSync(binPath), "packed install is missing node_modules/.bin/basalt-diagram-export"); @@ -113,14 +127,23 @@ console.log('Packed consumer: runtime, server rendering, exact token types, expo const cliIn = path.join(consumer, "sample.json"); const cliOut = path.join(consumer, "cli-out"); fs.writeFileSync(cliIn, JSON.stringify(sampleSpec)); - run(process.execPath, [binPath, cliIn, "--to", "drawio,vsdx,lucid", "--theme", "dark", "--marks", "embed", "--out", cliOut], consumer); + // Default mode without Playwright installed falls back to headless layout and warns on stderr that geometry is approximate. + const fallbackRun = spawnSync( + process.execPath, + [binPath, cliIn, "--to", "drawio,vsdx,lucid", "--theme", "dark", "--marks", "embed", "--out", cliOut], + { cwd: consumer, encoding: "utf8" }, + ); + assert.equal(fallbackRun.status, 0, `packed default fallback failed: ${fallbackRun.stderr}`); + assert.match(fallbackRun.stderr, /approximate/i, "default CLI fallback without Playwright must warn that geometry is approximate"); for (const ext of [".drawio", ".vsdx", ".lucid"]) { const f = path.join(cliOut, `sample${ext}`); assert.ok(fs.existsSync(f) && fs.statSync(f).size > 0, `installed bin did not write ${f}`); } - assert.match(fs.readFileSync(path.join(cliOut, "sample.drawio"), "utf8"), /background="#000000"/, "dark drawio background"); + const drawioOut = fs.readFileSync(path.join(cliOut, "sample.drawio"), "utf8"); + assert.match(drawioOut, /background="#000000"/, "dark drawio background"); + assert.match(drawioOut, /Basalt headless \(approximate\)/, "drawio records approximate engine metadata"); assert.match(fs.readFileSync(path.join(cliOut, "sample.vsdx")).toString("latin1"), /PageBackground/, "dark vsdx PageBackground"); - // Without Playwright installed in the consumer, --browser fails cleanly with an actionable install message. + // Without Playwright installed in the consumer, strict --browser fails cleanly with an actionable install message. let browserErr = ""; try { run(process.execPath, [binPath, cliIn, "--browser", "--to", "drawio", "--out", cliOut], consumer); @@ -128,9 +151,21 @@ console.log('Packed consumer: runtime, server rendering, exact token types, expo browserErr = `${err.stdout || ""}${err.stderr || ""}`; } assert.match(browserErr, /playwright/i, "packed --browser without Playwright must name playwright in its error"); + // Automatic layout via the packed CLI with no elkjs installed (uses packaged dist/diagram-elk.js). + const autoSpec = { + type: "architecture", + layout: "auto", + title: "Packed auto CLI check", + summary: "Verifies automatic layout through the installed bin.", + nodes: [{ id: "a", name: "Alpha" }, { id: "b", name: "Beta" }, { id: "c", name: "Gamma" }], + edges: [{ from: "a", to: "b", kind: "main" }, { from: "b", to: "c" }], + }; + const autoIn = path.join(consumer, "auto.json"); + fs.writeFileSync(autoIn, JSON.stringify(autoSpec)); + run(process.execPath, [binPath, autoIn, "--headless", "--to", "drawio", "--out", cliOut], consumer); + assert.ok(fs.existsSync(path.join(cliOut, "auto.drawio")) && fs.statSync(path.join(cliOut, "auto.drawio")).size > 0, "packed CLI exported auto layout without elkjs"); // elkjs is a build input of the package, not a dependency (the decider's ruling 2 on the batch B re-check): the package ships its one copy, // dist/diagram-elk.js, so a consumer with no elkjs installed places an automatic figure. - fs.rmSync(path.join(consumer, "node_modules", "elkjs"), { recursive: true, force: true }); fs.writeFileSync(path.join(consumer, "place.mjs"), `import assert from 'node:assert/strict'; import fs from 'node:fs'; assert.ok(!fs.existsSync(new URL('./node_modules/elkjs', import.meta.url)), 'no elkjs in the consumer'); const { placeDiagram } = await import('@srasyndicate/basalt/diagram-layout'); From 7be7d09a7f98dd10f5ab67192f7bacde23f2b05d Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:01:14 -0600 Subject: [PATCH 10/19] Split Node and browser interop tests, cover Batch B and B2 exact geometry, tighten port precision Co-Authored-By: Gemini 4 Neon --- packages/react/src/interop/scene.ts | 8 +- packages/react/src/interop/vsdx.ts | 10 +- .../test/diagram-interop-browser.test.mjs | 239 +++++ packages/react/test/diagram-interop.test.mjs | 913 ++++++------------ .../react/test/support-diagram-interop.mjs | 604 ++++++++++++ 5 files changed, 1125 insertions(+), 649 deletions(-) create mode 100644 packages/react/test/diagram-interop-browser.test.mjs create mode 100644 packages/react/test/support-diagram-interop.mjs diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts index 38eb3b30..66691bb1 100644 --- a/packages/react/src/interop/scene.ts +++ b/packages/react/src/interop/scene.ts @@ -1596,8 +1596,8 @@ function layoutSequenceHeadless( 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: round4((yt - lf1.y1) / span1), side }; - toPort = { x: 0.5, y: round4((yb - lf2.y1) / span2), side }; + 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; @@ -1610,13 +1610,13 @@ function layoutSequenceHeadless( 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: round4((s.y - lf1.y1) / span1), side: dirRight ? "right" : "left" }; + 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: round4((s.y - lf2.y1) / span2), side: dirRight ? "left" : "right" }; + toPort = { x: 0.5, y: round6(clamp01((s.y - lf2.y1) / span2)), side: dirRight ? "left" : "right" }; } } const text = `${s.n} ${s.label}`; diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts index ee769ec7..0fe06efc 100644 --- a/packages/react/src/interop/vsdx.ts +++ b/packages/react/src/interop/vsdx.ts @@ -1132,12 +1132,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): return makeDeterministicZip(entries); } -function renderConnectionRows(conns: readonly ConnEntry[], _wIn: number, _hIn: number): string { +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` + ` \n` + ` \n` + 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..5227fc83 --- /dev/null +++ b/packages/react/test/diagram-interop-browser.test.mjs @@ -0,0 +1,239 @@ +// 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_KEYS = Object.keys(CIMIP); +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; + }; + + let maxRouteDelta = 0, routesOverHalfPx = 0; + const routeDeltas = {}; + 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"; + } + + return { + shapesOverHalfPx, + maxBoxDelta: +maxBoxDelta.toFixed(2), + routesOverHalfPx, + maxRouteDelta: +maxRouteDelta.toFixed(2), + boxDeltas, + routeDeltas, + }; +} + +describe("live DOM measured Geo entry and B2 exact geometry (Chromium)", () => { + test("live React figures match CLI default path within <= 0.5px, record headless fallback drift, and cover Batch B", async () => { + 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 }; + 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 model = buildModel(spec, { checks: false }); + const base = (fig.getAttribute("aria-labelledby") || "dg").replace(/-title$/, ""); + const opts = { prefix: "basalt-diagram", base, hasSource: Boolean(spec.source), hiddenClass: "basalt-visually-hidden" }; + 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); + out[key] = { geo: res.geo, extras: readMeasuredExtras(fig, "basalt-diagram") }; + } + 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(() => 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 + const specsByKey = { ...CIMIP, batchBArch: CIMIP_B.architecture, batchBSeq: CIMIP_B.sequence, batchBSchema: CIMIP_B.schema }; + for (const [key, spec] of Object.entries(specsByKey)) { + const { geo, extras } = measured[key]; + assert.ok(geo && geo.lines.length > 0, `${key}: live Geo measured`); + assertValidDrawio(interop.exportMeasuredDiagram(spec, geo, "drawio", { extras }), spec, `measured/${key}`); + assertValidVsdx(interop.exportMeasuredDiagram(spec, geo, "vsdx", { extras }), spec, `measured/${key}`); + assertValidLucid(interop.exportMeasuredDiagram(spec, geo, "lucid", { extras }), spec, `measured/${key}`); + } + + // Run CLI default path (no --headless, no --browser) on the 5 CIMIP fixtures and assert <= 0.5px vs live React + const cliOutA = path.join(dir, "default-a"); + const cliOutB = path.join(dir, "default-b"); + const cliArgs = [CLI, path.join(here, "fixtures", "cimip-diagrams.json"), "--to", "drawio,vsdx,lucid,lucid-json", "--width", "1104"]; + const rA = spawnSync(process.execPath, [...cliArgs, "--out", cliOutA], { encoding: "utf8", timeout: 90000 }); + assert.equal(rA.status, 0, rA.stderr); + const rB = spawnSync(process.execPath, [...cliArgs, "--out", cliOutB], { encoding: "utf8", timeout: 90000 }); + assert.equal(rB.status, 0, rB.stderr); + + const stems = { architecture: "architecture", flowchart: "flowchart", dataFlow: "data-flow", sequence: "sequence", schema: "schema" }; + const comparison = { defaultPath: {}, headlessFallback: {} }; + for (const key of CIMIP_KEYS) { + const stem = stems[key]; + for (const ext of [".drawio", ".vsdx", ".lucid", ".lucid.json"]) { + assert.equal( + sha256(fs.readFileSync(path.join(cliOutA, stem + ext))), + sha256(fs.readFileSync(path.join(cliOutB, stem + ext))), + `CLI default repeat byte-identical on one Chromium: ${stem}${ext}`, + ); + } + // Verify Chromium version metadata in all three formats + const drawioXml = fs.readFileSync(path.join(cliOutA, `${stem}.drawio`), "utf8"); + assertValidDrawio(drawioXml, CIMIP[key], `cli-default/${key}`); + assert.match(drawioXml, /agent="Basalt Diagram Exporter \(Chromium \d+/, `${key}: draw.io records Chromium version`); + const vsdxBytes = fs.readFileSync(path.join(cliOutA, `${stem}.vsdx`)); + assertValidVsdx(vsdxBytes, CIMIP[key], `cli-default/${key}`); + assert.match(readZipEntries(vsdxBytes).get("visio/document.xml").toString("utf8"), /Basalt Diagram Exporter \(Chromium \d+/, `${key}: vsdx records Chromium version`); + const lucidBytes = fs.readFileSync(path.join(cliOutA, `${stem}.lucid`)); + assertValidLucid(lucidBytes, CIMIP[key], `cli-default/${key}`); + const defaultDoc = JSON.parse(fs.readFileSync(path.join(cliOutA, `${stem}.lucid.json`), "utf8")); + assert.ok( + defaultDoc.pages[0].shapes.some((s) => s.customData?.some((d) => d.key === "basalt_measured_by" && /^Chromium \d+/.test(d.value))), + `${key}: lucid records Chromium version`, + ); + + // Compare CLI default path against live React component: assert <= 0.5px on every box and route point (B2) + const { geo, extras } = measured[key]; + const liveDoc = interop.exportMeasuredDiagram(CIMIP[key], geo, "lucid-json", { extras }); + 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`); + + // Record approximate headless fallback drift + const headDoc = interop.diagramToLucidJson(CIMIP[key], { width: geo.w }); + 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 index 7e59dc83..8eaca425 100644 --- a/packages/react/test/diagram-interop.test.mjs +++ b/packages/react/test/diagram-interop.test.mjs @@ -1,479 +1,41 @@ -// Tests for @srasyndicate/basalt/diagram-interop and basalt-diagram-export CLI (DECISIONS 311, 314). +// 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 for all 5 CIMIP fixtures across .drawio, .vsdx, .lucid and Lucid JSON -// - Official draw.io XSD validation (mxfile-1.0.xsd) across all 5 figures and light/dark/adaptive themes -// - Visio .vsdx OPC parts, XML well-formedness, Connects glue, ConFixedCode=2, and zero-drift port snapping -// - Lucid Standard Import JSON contract (containers, swimLanes, tables, lineEndpoints, elbowControlPoints, labels) -// - Exact port axis-alignment invariant for every first and last segment (fixes the RunTask jog) across all 5 figures x 3 formats -// - Live DOM measured Geo entry (exportMeasuredDiagram + readMeasuredExtras) on all 5 CIMIP React figures -// - Mark terms policy against packages/react/marks/manifest.json (default omit; embed only manifest-permitted marks) -// - CLI end-to-end (single JSON, multi-diagram JSON, HTML script[data-diagram], flags, errors) -// - Subpath isolation (outside root index, no "use client", no React/third-party deps) +// - 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 +// - `par` sequence frames, `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 crypto from "node:crypto"; 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 zlib from "node:zlib"; -import { fixturePage, launch, pkg } from "./support.mjs"; +import { + assertValidDrawio, + assertValidLucid, + assertValidVsdx, + CLI, + pkg, + readForeignZipEntries, + readZipEntries, + repo, + sha256, +} from "./support-diagram-interop.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); -const repo = path.resolve(pkg, "..", ".."); const CIMIP = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "cimip-diagrams.json"), "utf8")); const CIMIP_KEYS = Object.keys(CIMIP); -const XSD = path.join(here, "fixtures", "mxfile-1.0.xsd"); -const CLI = path.join(pkg, "bin", "basalt-diagram-export.mjs"); +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); -const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex"); - -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). */ -function readZipEntries(bytes) { - const buf = Buffer.from(bytes); - // Find EOCD - 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. */ -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 expectedEdgeCount(spec) { - if (spec.type === "sequence") return spec.steps.filter((s) => !("band" in s)).length; - 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 target = byName.get(c.references.split(".")[0]); - if (target && Math.abs(target.col - t.col) <= 1) n++; - } - } - return n; - } - return spec.edges.length; -} - -function expectedLabelCount(spec) { - if (spec.type === "sequence") return spec.steps.filter((s) => !("band" in s)).length; - if (spec.type === "schema") return 0; - return spec.edges.filter((e) => Boolean(e.label)).length; -} - -/** Verifies every segment in `pts` is orthogonal and first/last segments are axis-aligned with `start` and `end`. */ -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, labels, and port axis-alignment. */ -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. 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).", + "$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. 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": 35800 @@ -821,7 +821,7 @@ "kbd" ], "budget": 145450, - "usage": 4850, + "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 a6049b80..5d343dae 100644 --- a/.agent/skills/basalt-html/parts/usage/diagram.md +++ b/.agent/skills/basalt-html/parts/usage/diagram.md @@ -28,4 +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`). +- **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`. diff --git a/packages/react/bin/basalt-diagram-export.mjs b/packages/react/bin/basalt-diagram-export.mjs index 9d8c0db5..45419a2f 100755 --- a/packages/react/bin/basalt-diagram-export.mjs +++ b/packages/react/bin/basalt-diagram-export.mjs @@ -48,6 +48,14 @@ function usage() { " --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"); } @@ -556,12 +564,15 @@ async function main() { } 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 }); + written.push({ path: outPath, bytes: typeof data === "string" ? Buffer.byteLength(data) : data.byteLength, format }); } } for (const w of written) { - process.stdout.write(`${path.relative(process.cwd(), w.path) || w.path} (${w.bytes} bytes)\n`); + 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`); } } diff --git a/packages/react/src/diagram-interop.ts b/packages/react/src/diagram-interop.ts index a9e56b5d..a0d9451c 100644 --- a/packages/react/src/diagram-interop.ts +++ b/packages/react/src/diagram-interop.ts @@ -91,19 +91,30 @@ export function diagramToVsdx(spec: DiagramSpec, options: InteropOptions = {}): return sceneToVsdx(scene, options.theme ?? "light"); } -/** Exports a Basalt diagram spec to a deterministic Lucid Standard Import `.lucid` ZIP archive. */ +/** + * 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`). */ +/** + * 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`, or Lucid JSON. */ +/** + * 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; diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs index e9b8666a..c5224dba 100644 --- a/packages/react/test/diagram-interop.test.mjs +++ b/packages/react/test/diagram-interop.test.mjs @@ -455,6 +455,16 @@ describe("basalt-diagram-export CLI (Node-only --headless mode)", () => { }); 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" }, diff --git a/tools/html-skill/src/modules.json b/tools/html-skill/src/modules.json index 4ffbc93d..e6877d2a 100644 --- a/tools/html-skill/src/modules.json +++ b/tools/html-skill/src/modules.json @@ -1,5 +1,5 @@ { - "$comment": "Which parts of the skill's CSS and JS a page gets. The core is always in. A module is in when the page's body has one of its classes, attributes or tags, matches one of its text patterns, or is named in a comment, and when another module needs it (requires). Modules are added in the order listed here, which is the order of the source files' cascade. classes: every class the module's CSS styles (the test checks them against the CSS and against SKILL.md). budget: the most bytes its minified CSS and JS may reach together. budgets: skillMd (SKILL.md, the context an agent pays: never above what it was), core (the CSS and JS of every page). icons: Phosphor names the module's script draws itself. Raised in the first parity PR (the owner's \"bring up the parity\"): forms (the number-input, search-clear and file-input chrome), disclosure (the native details marker), status (the accent reader and the forced-colours badge border), spinner (a fixed 16px ring), and the new number, range and accent modules. skillMd rose 10555 to 10900 for the new rules (number field, native chrome, the braille rule, the accent). Raised in the second parity PR (popup rows, levels and the segment's pill): segment 1400 to 3700 (the shared sliding pill: its script, 1.5 KB, and its CSS with the pill's two fallbacks), rows 3600 to 4300 (#27's plate-in-a-row geometry, the plate per level, the glide's shared plate and the forced-colours lit row, net of the removed bar), palette 9400 to 11300 (the glide's script, 2.4 KB: it follows the lit row, travels on a pointer, snaps on a key, and fades in place on leaving). The art module (DECISIONS 101 and 104) is the token groups only some pages name, taken out of the core so the core stays under its cap: the chart roles and lengths, the art colours, the aspect ratios and the stage headroom, in both themes (2087 bytes at 2100; it grows only when a token of those groups is added). A page gets it when its body names one of them, a var() in its own style included. The every-module page has no cap of its own (owner, DECISIONS 79): each part is capped, and a page carries only the parts it uses. usage: the most bytes of a module's usage text (src/usage/NAME.md; core.usage for core.md), which compose.mjs --usage prints on demand. It is context an agent pays only for the modules its page uses, so it is capped per part as SKILL.md and the CSS and script are (DECISIONS 79 and 109). Each is set a little above what its text was when the usage moved out of SKILL.md (DECISIONS 109); raising one needs a reason in the PR, and a rise of 40 to 50% is the owner's. textWords: each text pattern said in words, which compose.mjs --usage prints instead of the regular expression (one for each entry of text, in order). builds: modules a module requires whose markup its script writes, so --usage prints a line saying so instead of their usage text (the palette builds its own rows and key chips). The council's clarity check of the usage texts (all three: not yet clear) raised eight caps because the texts gained what an agent had to guess: callout 200 to 700 (the icon and one wrapper div around the title and body as markup, the four status icons, the role React's Callout renders), palette 1100 to 1300 (an item shown whole, keys as an array, keywords), stats 450 to 800 (a snippet of the figures and of the dl), tabs 500 to 650 (the unselected panels), code 250 to 450 (the markup and what each token class means), segment 150 to 300 (a click does not switch it), progress 150 to 350 (the empty span that paints the fill), theme 250 to 400 (leave the button empty), and accent 250 to 300. Topbar went down, 700 to 500, as its build detail was cut. Raised in the usage PR (the council's clarity check): palette 11300 to 11450 (the module grew 11283 to 11448, +165, about 1.5%), for the guard that makes a string `keys` warn and draw no chip instead of throwing in `keys.filter`, which the palette's usage already promised. Round 2 of the clarity check: tabs 650 to 750 (the panel's top space shown in the snippet, and that the script selects a tab on click). Raised in the site-icons and status PR (skill-parity part A, DECISIONS 106 and 107): status 1650 to 1900 (the neutral, pending and running marks, the badge's real border, and the forced-colours disc, net of the red danger word it drops) and its usage 400 to 1000 (every status in words, the word alone, running, forced colours); rows 4300 to 4450 (the profile list's seat rule and the status parts on a lit row) and its usage 300 to 600 (the profile list, with the one mistake: never an empty element for the seat). New: the links module (2671 bytes: the social row, the new-tab arrow's CSS and the script that draws it; budget 2750) and its usage (1746 bytes; cap 1850), which carries the social link, the glyph set, icon only and the new tab. Dropping Regular halves icons.json. Added in the overlay PR (skill-parity-4, batch 7 step 2, DECISIONS 108): the shared plate leaves palette.js for a glide module (the palette, a menu and the notification centre all call it), so the palette's cap went down, 11450 to 9250, and rows 4450 to 3850 (the plate's CSS moved to glide); and the overlay layer comes in as seven modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: popover (the native popup shell), menu, dialog (the dialog and alert dialog), sheet (on every side, the top one the site header's narrow menu), tooltip, toast and notifications (the centre). skillMd is unchanged in its cap (the eight new index lines fit within it); the core is unchanged in bytes. Added in the figures and charts PR (skill-parity-5, batch 7 step 3, DECISIONS 108): four modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: meter (React's Meter, CSS only, 2581 bytes), dlist (the description list, CSS only, 1265), terminal (the code block's transcript: its CSS, 3242, and the script that draws the gutter, the copy button and the replay, 4824) and chart (React's TimeChart and ChartGroup: 7313 of CSS and 23262 of script, which port chart.tsx's scale, layout, lane, labels, sentences, keyboard and table; it needs the art tokens, the table and the kbd chips, and a page without a chart carries none of it). Stats grew for the source line (budget 700 to 850, 798 bytes; its usage 800 to 950, 675 to 899 bytes, +33%, under the owner's 40 to 50%). skillMd is unchanged in its cap (four index lines fit within it); the core is unchanged in bytes. Added in the forms and selection PR (skill-parity-6, batch 7 step 4, DECISIONS 108): six modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: select (React's Select: the native select's closed trigger in every browser and, where `appearance: base-select` is shipped, the styled list with its two-line rows; a small script that says which input lit a row, 7740 bytes before it, choice (Checkbox, Radio, RadioGroup and Switch as styled native inputs; CSS only, with the first-frame rule), choice-card (ChoiceCard; CSS only), toggle (the pressed toggle's plate and check seat on .btn; CSS only), selection (a table's checkbox column: its fixed width and the script that sets aria-selected, the mixed header box and the count) and loops (the page-level hold on every loop with its switch: the held look and the script that stores it). The select's styles left forms, whose budget fell 3650 to 3250. skillMd rose 8621 to the size of its six new index lines, within its cap; the core is unchanged in bytes; compose adds the stored-hold line to the head of a page that has the loops module. Revised in the same PR (the lead's review of the build): the select gains select.js (one row is lit at a time, by whichever of the pointer and the keys moved last), and choice, toggle, selection and loops carry the first-frame rule, so a state a script sets on load (a mixed header box, the stored hold) paints at once with no crossfade. Added in the navigation and layout PR (skill-parity-7, batch 7 step 5, DECISIONS 108): five modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: glyph (Basalt's core glyphs drawn by name, at rest and selected, from a table the build works out from the drawn set; a page carries only the glyphs it names, and the drawing of a core glyph from data-glyph left the sheet module, which draws none now), nav (React's Nav: the sidebar's, the narrow menu's and More's rows, with the shared hugging pill), topbar-nav (the site header's links, one action and narrow menu, built by script from the bar's markup), app-shell (the shell, its sidebar and rail, and the app header) and tab-bar (the phone tab bar). The topbar module became the site header's bar (React's SiteHeader, DECISIONS 108: 56px with its line inside, the 44 by 44 brand target, the narrow-screen buttons, the derived sticky offset), budget 1600 to 3200 because its rules gained the app header's shared smoke, and its usage 500 to 750 (+50%) for the lockup's markup (the links, action and menu are topbar-nav's usage). Glide 3700 to 3950: the navigation's pill is a shape inside the row that the plate follows (about 200 bytes). The core's usage 2000 to 2100 (+5%): h2 is the Section step, the prose column's measure, and a link already 44px tall needs no margin. skillMd rose 9317 to 9863 for five index lines, under its cap; the core CSS grew 38 bytes (the layout tokens replace raw lengths, the gutter is one derived property, h2, .prose and .lead follow foundations) and the core script is unchanged. A module's media query writes %bp-md%, %bp-lg% or %bp-container% and the build substitutes the breakpoint tokens. Added in the tables and filters PR (skill-parity-8, batch 7 step 6, DECISIONS 108): the existing table module gains React's table additions (DECISIONS 95: the row header, \"Not observed\", the row density and the scroll hint with its small script), budget 1400 to 3000 (it was 1134 bytes of CSS; it is 2168 of CSS and 693 of script) and its usage 700 to 950 (+36%); and two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: still-table (React's Table with `columns`: the fixed layout from a colgroup, the whole header cell as the sort button with its reserved seat, aria-sort, the pinned columns and their divider, the empty row; 4767 of CSS and 3264 of script, budget 8200) and filter (React's MultiSelect and FilterResult: the chips, the trigger and checklist with the search band from ten values, Clear held in place, the one debounced result line, and the narrowing of a table by `data-column`; 8240 of CSS and 7978 of script, budget 16400; it needs the popover, glide, glyph and choice modules). The core is unchanged in bytes. skillMd rose 9863 to 10128 for two index lines and the CaretUpDown icon's name, within its cap. Added in the commands PR (skill-parity-9, batch 7 step 7, DECISIONS 103 and 108): one new module a page carries only when it uses it, command-list (React's CommandList: the command panel set in the page, list plus preview, the push; it extends the palette and needs rows, kbd and glide; 5229 of CSS and 8734 of script, budget 14000, usage 2150). Two-line rows come to the existing modules: rows 3850 to 5350 (the described row's grid and description line, the push's chevron: 1481 bytes of CSS, the same rules React's menu rows carry), palette 9250 to 9900 (its rows are one function the list shares, with the description and the two-tier ranking of title matches over keyword and description matches; +636) and its usage 1300 to 1350, rows' usage 600 to 800, and glide 3950 to 4000 (a host that is idle counts as having no lit row, +54). skillMd rose 10128 to 10259 for one index line, within its cap; the core's CSS grew 24 bytes (.split.aside takes size-list-width in place of its raw 20rem: the same 320px, so no pixel moves) and the core script is unchanged. Added in the art PR (skill-parity-10, batch 7 step 8, DECISIONS 104 and 108): two modules a page carries only when it uses them, each with its own cap and usage cap set a little above its size: stage (React's Stage and PairedArt: full-bleed art under the site header, the pull-up by the sticky offset, the headroom, the paired art that follows the page's theme, and the forced-colours and print rules; CSS only, 1179 bytes) and framed-art (React's FramedArt: the figure, its rim and radius, the reserved box, the placeholder and the failed alt, the caption and credit; 2208 bytes of CSS and the 733-byte script that sets the frame's phase); both need the art tokens. The bar stays smoked over a stage: React clears it only over a stage that passed the headroom test helper, and a page has no test run (DECISIONS 108's note), so the skill builds no clear state. skillMd rose 10259 to 10500 for two index lines, within its cap; the core is unchanged in bytes. The callout gained the status rim in the same PR (DECISIONS 82, D8's status callouts): success, warning and danger draw their border in the status colour at 45% mixed in sRGB over the callout's own level, one solid colour on every side, and CanvasText in forced colours with the icon; the status colour is now one property the icon and the rim read. Its budget rose 900 to 1150 (the module is 1089 bytes, from 792: +297, about 37%); its usage is unchanged. Added in the overlays-and-the-rest PR (skill-parity-11, batch 7 step 9, DECISIONS 90 and 108): the last two parts of D8's part 5, each a module a page carries only when it uses it, with its own cap and usage cap set a little above its size: combobox (React's Combobox: the input with its caret button inside, the popup of the menu's rows with the glide's shared plate and two-line options, the filtering, the keys, the hidden value, the empty message and the check; 4342 of CSS and 6423 of script, budget 10900, usage 2150; it needs forms, popover and glide, and builds the last two) and sparkline (React's Sparkline: the label and latest value, the line, the axis, the empty sentence and the loading line that breathes; 1609 of CSS and 1874 of script, budget 3600, usage 950). The combobox copies the menu's row rules, as the select's list does, because React's Combobox renders MenuItem rows (a 40px hit area, a 36px plate) and the skill's .row is the palette's 44px: it carries no menu script. popover.js gains the combobox popup in the list of popups that keep focus where it is (+21 bytes, within its cap). skillMd rose 10500 to 10724 for two index lines, within its cap; the core is unchanged in bytes. Added in the motion-rules PR (DECISIONS 136 and 139): one module, ambient (a page's one ambient loop: CSS 828 bytes, script 433, budget 1300, usage 800), taken out of loops so the hold's own module grows only by the icon toggle's glyph swap (loops 2000 to 2200, +10%; its usage 1300 to 1650 for the icon form and the new settings-row sentence, +27%); and the chart's entrance (`entrance: true`: the marks' animations, their conditions and the redraw that restarts them at the elapsed time, 23262 to 25299 bytes of script; budget 30700 to 32800, +7%, usage 2500 to 2950, +18%). The core grew by the three tokens (27704 to 27862 bytes of CSS, under its cap). its stage usage gained the ambient art's line (1650 to 1750, +6%). skillMd rose 10724 to the size of the ambient index line, within its cap. Raised again in the motion-rules amendment (DECISIONS 143): chart 32800 to 33800 (script 25299 to 26375 bytes, +4%; +10% over the 30700 it began with) for the glide a new data set makes mid-entrance, print settling it, and `Basalt.pageChange()`; its usage 2950 to 3150 (+26% over the 2500 it began with). Raised in the second motion-rules amendment (DECISIONS 148): chart 33800 to 34400 (script 26375 to 26970 bytes: a line and its markers glide from their drawn geometry, and `beforeprint` settles the entrance; +12% over the 30700 it began with); topbar-nav 6900 to 7500 (+8.7%: the narrow menu's pause row, its CSS and 275 bytes of script, DECISIONS 148 item 2); loops usage 1650 to 1800 (+38% over the 1300 it began with, for the icon form's `title` and the menu row). Raised in the audit-design-b PR (DECISIONS 138 and 139): still-table 8200 to 13400 (+63%: the module was 7927 bytes and is 13311; the cut cell's plate, its focus stops and its dismissal, ported from React's cell-peek.ts, are 4273 bytes of script and 1111 of CSS; a still table that truncates needs them). The same PR: core usage 2100 to 2250 (+7%: the skip link, one bullet), forms usage 350 to 480 (+37%: the required mark), still-table usage 1950 to 2150 (+10%: the cut cell and the width rule), notifications usage 1050 to 1100 (+5%: the 44px entry on touch). The skip link's rim and radius took the core 30457 to 30609 bytes, under its cap (the rules that hang it under the bar are the topbar module's: 3200 to 3600, +12.5%); core 30720 to 31050 (+1.1%, DECISIONS 147: also the bar's links left out of the rule: the pseudo-element that makes a short standalone link a 44 by 44 target), skip-link script in the topbar module (3200 to 4150 over this PR, +30%: the rules that hang the link under the bar, 3600, and the script that reads the bar's real edge, 4150), sparkline 3600 to 4050 (+12.5%: React's ticker structure, so the value copies once on its line, and in forced colours the strips go and the number is plain text), forms budget 3250 to 3500 (+7.7%: the necessity word), notifications 9050 to 9250 (+2.2%: the 44px entry). Raised in the audit-design-b PR's E2 port (DECISIONS 138 and 139: the core set draws check, close, the chevrons, copy, plus, minus and search wherever a component draws them): the modules that drew a Phosphor icon for one of those now carry the core glyph's whole SVG, written in at build time (`%glyph-svg:name%`, the markup the glyph module's `_.glyph(name)` returns, so no module needs the glyph module and a page pays for nothing it does not use), and the Phosphor path of the same icon leaves the page. Each module's own bytes rose by that markup, and a page's total moved by what the Phosphor path it no longer carries saves: menu 8600 to 8900 (+303), combobox 10900 to 11200 (+303), copy 1900 to 2400 (+640), terminal 8100 to 8850 (+761), toast 13850 to 14150 (+325), number 2900 to 3400 (+557), filter 16400 to 17050 (+785), palette 9900 to 10450 (+536); the command list shares the palette's search drawing and fell 20 bytes. Set in integration-nov15, where the type-layout, motion-rules and audit-design-b branches meet: the combined tree measured SKILL.md 10959 bytes (each side's cap was 10900: both added index lines), core 31192 bytes (caps 30720 and 31050: the page-row and display rules, the three motion tokens and the skip link and 44px target rules all land in the core CSS) and core usage 2348 bytes (caps 2300 and 2250: type-layout's line and the skip-link bullet), so each is set to the measured bytes rounded up to the next 50: skillMd 10900 to 11000, core 31050 to 31200, core usage 2300 to 2350. Raised in the audit-design PR (decisions 138 and 139, parts A, D and C11): core 30720 to 31600 (+2.9%: the more-contrast block and its three aliases, and the field boundary token, every page carries as React does; the shadow-pill token is gone; the script gained `reserve`, 240 bytes), segment 3700 to 4100 and tabs 2300 to 2700 (the chosen label is 600 against 400, its width reserved by a span that carries its own copy, drawn unseen at 600; the pill's drop shadow is gone), and the segment's usage 300 to 380 (the weight and the glyph-only button). Raised again in the audit-design-a amendment (decision 145): core 31600 to 32300 (reserve() also reserves a label that is not plain text), segment 4100 to 5100 and tabs 2700 to 3500 (the second copy of such a label, and an icon drawn in both its forms), glyph 1100 to 1300 (a glyph in a segment or tab is drawn in both forms). Raised in the second audit-design-a amendment (decision 149): core 32300 to 32800 (reserve() builds the second copy of a label without any id, name, reference or hidden control, and does not copy a frame or media), segment 5100 to 5400 and its usage 380 to 500 (the 600 is on the label, the one-line rule and the usage text); the still-table cap is back at 8200, as the wash is on every cell again. Return 3 of the audit-design-a build (decision 149): tabs 3500 to 3700 (a tab the script has not reserved is 600 itself when selected, and one it declined is marked; the same two lines are in segment, which stays under 5400). Raised in the audit-fix-c2 PR (engineering, no pixel changes): toast 13850 to 14350 (the module was 13789 bytes and is 14288, +499, 3.6%) for F6, which focuses the Notifications region and Shift+Tab or Escape from it (or from the first toast) leaves it for where focus came from (and keeps a dialog's focus trap from wrapping it), as Base UI's viewport does in React, and for placing the region from focus (in the modal that holds it, or in the body), so a toast is never under a backdrop or in an inert modal whatever order the modals opened in (A3-09); the palette module grew 9864 to 9897 of its 9900 so that a palette opened over a modal sits inside it; topbar 3200 to 3250 (3123 to 3233, +110) for the scroll margin on what the bar holds, so a Tab into the bar from a scrolled page does not scroll the page (React's rule from PR #66); stage usage 1650 to 1750 (1580 to 1713, +8%) for the art's new place in the markup, after the content (A1-09), the stage's own CSS rising 1179 to 1208 within its 1250. skillMd rose 10724 to 10876 for the sentence that says a body may carry head tags, within its 10900. compose.mjs, the tool an agent runs, has no cap here (it is never in a page): it grew 21673 to 38153 bytes for the tokenizer that reads a body as HTML does and the head tags. Raised in the site-parts PR (DECISIONS 146, round 39), which folds each new part into the module it belongs with, so SKILL.md gains no index line (it has 41 bytes under its cap and a new module needs about 100): topbar 4150 to 17600 (+13450: the site footer and its disclosures, the lockup by pixel density, and a bar that arrives or leaves and returns, with its observer; a page that has a .topbar and no footer carries them too: the alternative, a module for each, needs its own index line and so SKILL.md bytes) and its usage 950 to 2900 (the footer's markup, the lockup's and the phase's); theme 650 to 4550 (the three-word theme choice: its CSS 2230 bytes and its script, 2277, with arrows, storage and the system listener) and its usage 400 to 1150 (the choice's markup written in full, so the right word is chosen before any script); segment 3700 to 3800 (a radio group's checked state besides a pressed button); stage 1250 to 2150 (its first script, 768 bytes, for fit and anchor) and its usage 1750 to 2000; framed-art 3000 to 3900 (drawn art in the frame: fit, anchor, no scaling strokes) and its usage 1250 to 1400. SKILL.md rose 10959 to 10992 (the topbar and theme index lines name .site-footer and .theme-choice). The head's theme line also writes data-theme-choice. Raised in site-parts return 2 (DECISIONS 146 B1 and B4): theme 4550 to 5350 (+800: the icon form of the theme choice, [data-theme-menu], whose button shows the theme in use, is named for the choice and opens the page's own .menu of three radio rows, in the theme script's 3073 bytes; the menu and popover modules are the page's, brought by its markup, so no module line was added and SKILL.md is 10993 of 11000) and its usage 1150 to 2200 (+91%: the menu's markup is written in full, and the deprecated toggle is said once); app-shell usage 2000 to 2100 and topbar-nav usage 1900 to 1950 (the theme control leaves the bar's text; the tools and the end cluster come in). The two example bodies still carry the deprecated data-theme-toggle. Return 2, F3 (DECISIONS 146 F): stage 2150 to 2250 (script 842 bytes: slice is the stage's default, as a frame's, and a drawing's own preserveAspectRatio stands unless the stage names data-fit or data-anchor) and its usage 2000 to 2150. framed-art 3900 to 4000 (a drawing's own preserveAspectRatio stands unless the figure names data-fit or data-anchor, +101 bytes). Return 3: theme 5350 to 5900 (script +569 bytes: who wrote data-theme, so System follows the system's change live and a theme the page set by hand, or a .dark or .light root, survives it). Raised in the controls port (DECISIONS 154): skillMd 11000 to 11200 for two index lines (link-tabs and option-chips, 214 bytes together), and core 31200 to 31600 for the nine tokens the port adds to every page's token CSS (the control rungs 44 to 64, two container widths, the confirm hold and the amount's opacity, 311 bytes). New modules (DECISIONS 154): link-tabs 2700 (its sizes, the 640 container step, the forced-colours underline, and the select that replaces the row under 720 with its 590-byte script, A15; it requires the select module), option-chips 5700 (the chip's states each written for a native radio inside a label, which needs :has on every one, plus the 1 KB script that keeps an aria-disabled chip reachable and never chosen). Return 3 (DECISIONS 154 conformance): link-tabs 2700 to 3100 and its usage 1650 to 1850 (the select's height for each row size, and a script that reads aria-current when it is needed and watches it move: 3,048 bytes), option-chips 5700 to 6700 (each state written twice, as a state attribute and as :has(), so no browser needs :has(): 4,975 CSS and 1,623 script). Return 4 (DECISIONS 158, Q2): link-tabs 3100 to 4300 and its usage 1850 to 2400 (the \"Go to\" label drawn at the select's start with its measured clearance, the select's accessible name kept as the words and the chosen page's, and the key hold that keeps a letter or an arrow on the closed select from navigating: 4,174 bytes, CSS 2,951 and script 1,223). Raised in the links-and-rows port (DECISIONS 152; the owner's approval is the lead's to confirm): the new link-rows module (5050 bytes of CSS, 50 of them for Castle's big-row arrow stepping colour over duration-fast, return 1, 1500 of usage: the directory's and the big rows' CSS, whose arrow is a core glyph drawn as a mask, and their tokens, size-row taken out of the core like type-layout's), disclosure 1550 to 3500 (Show all: the track, the clip and the settle, 1.5 KB of script and 1.8 KB of CSS), copy 2400 to 3500 (the form with words: the one cell and its script). SKILL.md rose 10959 to 10997 for one line, within its 11000 cap. Raised in the charts port PR (DECISIONS 153, D7a): chart 34400 to 34650 (script 26970 to 27270 bytes, +1.1% on the 34283 it was: `Basalt.trailingMean`, the trend maths React exports as `trailingMean`, 300 bytes), its usage 3150 to 3350 (+6%: one line for it). The tokens the batch adds (chart-lit-top, -mid and -base in both themes, size-chart-plot-sm, size-chart-row, size-meter-marker and radius-2xs) took the art module 2087 to 2546 bytes (budget 2100 to 2600, +24%: the chart tokens are its group) and the core 31192 to 31250 (cap 31200 to 31300, +0.3%: radius-2xs). Only D7a names a skill module in the charts ballot; the lit marks, the headline frame, the phase chart, the share bar, the coverage strip, the marks row and the range meter are React-only in this batch. Added in the overlays-and-search PR (DECISIONS 155, D10b and D13a): the sheet gains React's head, body and foot (the 44px close, the 20/28 title over a 13px count, the divider and the safe areas; its CSS 3.6 to 5.2 KB, budget 4050 to 5250, +30%) and its usage 1050 to 1450 (+38%: the anatomy and the step's focus, two bullets); and one new module a page carries only when it uses it, search (React's SearchDialog: the form, the field's -2 outline, the count line, the fixed-height results area and the rows with their picture slots and full-bleed hover wash; CSS only, 4368 bytes, budget 4400, usage 2050; it requires the dialog). The dialog's title draws no ring when script focuses it. skillMd rose 10959 to 11079 for the search line (the sheet's line is unchanged: its usage carries the anatomy), so its cap rose 11000 to 11100 (+0.9%). The core's CSS grew 31192 to 31421 bytes for the six new size tokens (the wide dialog, the search trigger and the logo and picture slots of a search result): its cap rose 31200 to 31450 (+0.8%). The two 44px values (the sheet's close and the search field) are local to their modules, with a lint exception that says they join the controls batch's size token (DECISIONS 154). Set in integration-nov15b, where audit-design-a, audit-fix-c2, site-parts, port-controls, port-links-rows, port-charts and port-overlays-search meet: the combined tree measured SKILL.md 11560 bytes (the caps were 11000, 11100 and 11200: each side added index lines), core 34086 bytes (caps 31300 to 33550: every side's rules land in the core CSS and script), topbar 17660 (17600 from site-parts, plus audit-fix-c2's skip-link and focus work), number 3453 (3400), palette 11379 (11000, audit-fix-c2's hosted scrim plus the core search glyph), dialog 5120 (5100), toast 15692 (15400) and stage usage 2248 (2150), each over every side's cap, so each is set to the measured bytes rounded up to the next 50: skillMd 11200 to 11600, core 33550 to 34100, topbar 17600 to 17700, number 3400 to 3500, palette 11000 to 11400, dialog 5100 to 5150, toast 15400 to 15700, stage usage 2150 to 2250. The segment cap is the base's 5400 plus port-controls' 100 (5500), unchanged by the merge. Raised in integration-nov15b, join 2 (a link tab takes the selected state, DECISIONS 138 A, 145, 149 and 154's D12 row): link-tabs 4300 to 5750 (+34%: the module was 4174 bytes and is 5736; the 600 against 400, the reserved width and the second copy of a composed label, an icon drawn in both its forms, the same rules a tab carries, 1,530 bytes of CSS and script) and its usage 2400 to 2550 (+6%: one bullet). The cap is the measured bytes rounded up to the next 50; a module that needs the tab's rules carries them as the segment and tabs modules do, so a page without link tabs pays nothing. Raised in the panels, art and parts port (DECISIONS 162): table 3000 to 3150 and its usage 950 to 1450 (the flat form and the two-line cell), stage 2250 to 2600 and its usage 2250 to 3100 (the closing block: its held art, forced colours and print; its section gap is type-layout's --basalt-section-gap, which a page with data-closing brings), the new app-tile 4300 (a 120-point polygon clip and the hairline's mask of the same outline), captioned 2000 and period 1400; skillMd 11600 to 11950 for one index line each for captioned, app-tile and period (358 bytes; the file is 11918). Raised in the logs, status and forms port (DECISIONS 162): core 34100 to 34200 (the new size-field-label-inline token, 80px, is written into every page's tokens: 25 bytes); dlist 1300 to 1900 and its usage 950 to 1060 (the stacked form, R9 and R10: a title over its text, 20px between entries, no divider; one usage line). Raised in audit-fix-c6 (the owner's cap, raised by the builder and for the owner to confirm): glyph 1300 to 1900, for redrawing a glyph when its ancestor's aria-current or data-current moves (the lists that hold glyphs are watched). Raised in the colour-ink-ladder build (DECISIONS 166): core 34200 to 34350 (the four lifted dark inks are four new primitives, each written into every page's tokens: the core measured 34307). Raised in the audit-2-design build (DECISIONS 167, Q7a): disclosure 3500 to 3800 (the core chevron drawn as a mask in place of two borders: the module measured 3755). Joined in the integration of c7 (#86) and c10 (#91): option-chips 6750 to 6850 (c7's reset resync and c10's data-ready together measure 6839). Raised in table-sort-3 (DECISIONS 257 and 261, the owner's pick: three sort states, the arrow after the label, explainers on column titles): still-table 13400 to 14650 (+9.3%: the module was 13343 bytes and is 14602; the end-aligned label's move by a transform, its right-to-left sign and the indicator that waits for it on a fine pointer, 912 bytes of CSS; the third state, the sort from the table's own order and a .explainer kept out of the button, 347 bytes of script) and its usage 2150 to 2250 (2197: the third state and the own order); the new explainer module 5850 (5842: a manual native popover opened from the sort button on hover, keyboard focus and a long press, placed above the header or beside it, 1752 bytes of CSS and 4090 of script; a page without explainers pays nothing) and its usage 900; skillMd 12250 to 12400 for the explainer's index line (113 bytes; the file is 12352). Each cap is the measured bytes rounded up to the next 50. Raised in table-sort-3's fix pass (Astra's review): explainer 5850 to 6900 (+18%: 5842 to 6864 bytes; the gap between the header and the card kept while a pointer crosses it, the close when its header leaves the view whatever has focus, the dismissal held until pointer and focus have both left, and its page-wide listeners and timers scoped to an open card and stopped when the table leaves the page, 1,022 bytes of script). Raised in cimip-gaps-2 batch B5 (the touch sizes under 720 whatever the pointer: each coarse-pointer target rule also answers a window under 720, about 20 bytes a rule; forms merged its three into one and stays under 3500): select 9000 to 9100 (measured 9064), selection 1480 to 1500 (1486), filter 17450 to 17500 (17473), option-chips 6850 to 6900 (6853), menu 8900 to 8950 (8902). B5 fix pass 1 (Astra): core 34550 to 34950 (measured 34911: 30762 CSS and 4149 JS) for stacked links in a column, each giving up the side of its 44px box that meets a neighbour, so a tap on a link's words is always that link's; core had 12 bytes free. DECISIONS 274 (the owner's pick: under 720 the toast stack hangs from the bar): toast 15700 to 16050 (measured 16035; 8 bytes were free; the stack's direction became one sign variable, trimming 585 of the 920 bytes the phone form first took). B5 merged with main (5ad5345a): main's own core measured 34930 against its 34550 cap before B5; with B5 (the touch sizes under 720 and stacked links in a column) it is 35331, so core is 35350; nav 5350 to 5400 (measured 5364: B4's nav plus the touch size under 720). The full run after the stream (DECISIONS 246): the site footer's links keep their own flex column under 720, as React's, out of the bare-link touch rule (26 bytes), so core is 35400 (measured 35357); sheet 5250 to 5400 (measured 5368: React's B5 ring room, ported: the held actions reach space-1-5 above their band, clipped, and the body keeps space-1-5 at each end). Raised for diagram motion and service marks (DECISIONS 292): skillMd 12550 to 12650 for the diagram-motion module's one line; diagram 87200 to 91000 for what a still diagram now carries (a card's mark and its seat, the pending frame, the comparison that writes a drawing only when it changed, and the print rule), and its usage 2600 to 4300 for the decision's four lines and the list of mark ids; the new diagram-motion module (the motion engine, its stylesheet and the motion tokens, in a page only when a diagram is animated) at 26200. Raised when the diagram tests were first run (DECISIONS 298): diagram 91000 to 91250 and diagram-motion 26200 to 26850. Raised in batch A of the diagrams backlog (DECISIONS 301): diagram 91250 to 92400, for the engine fixes it bundles (a decision kept no taller than it is wide, labels on whole pixels, slots beside a straight line, a one-column schema's turn-back); the skill keeps the development checks a production React build now drops. Raised again in that batch's review fixes: diagram 92400 to 92650, for the drawn layout refusing two lines laid on one another (Neon's blocking finding 1 on #126). Fix round 1 of #124 had already taken them to 91205 and 26621 with the tests unrun; this round added 1 byte (every focal node prints its fill; a one-form mark's dark form falls back to its light one) and 180 (the entrance keeps its own clock when it is drawn again while paused). DECISIONS 320 (versions and release notes): the release module is new (budget 15900 at first, usage 2400); topbar, app-shell and tab-bar gain the version link's classes (budgets: topbar 17700 to 19900, app-shell 4300 to 5200 with the rail's tooltip for it, tab-bar 4850 to 5200), their usage caps rising 2900 to 3100, 2600 to 2850 and 2250 to 2400 for its one line each; skillMd rose 12650 to 12800 for the release module's line and .version-link in topbar's. The code review of round 68 adds data-focus-self to the popover module (its Tab walk; budget 4950 to 5600, usage cap 950 to 1100) and logical start and end for its alignment; the release module's header grid and the Sources panel's touch rows take it to 16900. The spacing sweep of round 68 (DECISIONS 326: Copy link's words on the edge, the callout's last change, its reference column, the last release, the touch rows' end and the whole code chip) takes the release module to 17400. The ruling on where a release ends (DECISIONS 331: no padding under the last change in a release, a release-ending fold's hang, an arrived change keeping its padding, the panel holding its first margin, Build details 44 on touch and a closed Fixed panel taking no room) takes it to 19000. The code recheck of round 68 (recheck 5) has the popover's Tab walk follow Safari's own rule (Tab skips links on Apple's WebKit, Option-Tab reaches them): popover 5600 to 5900. The pixel recheck of round 68 has the Sources panel's touch rows keep their 20px lines with the link's box as hit area, space-3 rows and space-6 between two linked values (recheck-pixels 4), and the release's whole header take the arrival's plate: release 19000 to 19600. Merging #127 (stages, DECISIONS 316 and 328) into the versioning branch: both had raised skillMd from 12650 to 12800 for their own module's line, and together they came to 12886; SKILL.md was tightened in its wording (no rule dropped) to stay within 12800. Raised in 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. 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).", + "$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. 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": 35800 @@ -821,7 +821,7 @@ "kbd" ], "budget": 145450, - "usage": 4850, + "usage": 5050, "builds": [ "kbd" ] diff --git a/tools/html-skill/src/usage/diagram.md b/tools/html-skill/src/usage/diagram.md index a6049b80..5d343dae 100644 --- a/tools/html-skill/src/usage/diagram.md +++ b/tools/html-skill/src/usage/diagram.md @@ -28,4 +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`). +- **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`. From 44f5e8ee8c822e044e36a818fd64d846135aa4bd Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:39:32 -0600 Subject: [PATCH 16/19] Fix Lucidchart VSDX import: connector routing, line hops, opaque top-layer labels, and compact crow's feet Addresses all four defects from the owner's Lucidchart .vsdx import: 1. Disable line jumps (LineJumpCode=0 on PageSheet, ConLineJumpCode=1 on connectors), allocate one dedicated Connection row per connector end with outward DirX/DirY normals, and bind aligned bend coordinates to Visio 0/Width*1/Height*1 formulas so Lucidchart keeps orthogonal legs straight without small port-shift steps. 2. Emit every edge label, sequence band label, frame tab, frame header label, and else row as a word-sized opaque page-colour shape (FillPattern=1, NoFill=0, NoLine=1) painted after lifelines, activation bars, and connectors so lines and bars never cut through words. 3. Shrink Visio crow's-foot arrow size to Very Small (0) so markers fit 28px table rows cleanly, and widen short (< 27px) 6-point schema corridor final stubs to ~35px when clear so Lucidchart keeps the corridor orthogonal instead of collapsing it into a diagonal. Co-Authored-By: Gemini 4 Neon --- packages/react/src/interop/vsdx.ts | 235 ++++++++++++++++++++------ packages/react/test/export-sizes.json | 4 +- 2 files changed, 185 insertions(+), 54 deletions(-) diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts index 603b5b6a..7e5cd867 100644 --- a/packages/react/src/interop/vsdx.ts +++ b/packages/react/src/interop/vsdx.ts @@ -38,9 +38,19 @@ interface ConnEntry { /** 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; @@ -96,9 +106,17 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): }); } - // Collect deduplicated Connection rows required on each target shape/lifeline/bar + // 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(); - const getConnIndex = (key: string, fx: number, fy: number, exactCx?: number, exactCy?: number): number => { + 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))); @@ -106,10 +124,9 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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 existing = list.find((c) => Math.abs(c.cx - cx) < 1e-6 && Math.abs(c.cy - cy) < 1e-6); - if (existing) return existing.ix; const ix = list.length; - list.push({ fx: rfx, fy: rfy, cx, cy, ix }); + const { dirX, dirY } = sideNormal(side); + list.push({ fx: rfx, fy: rfy, cx, cy, dirX, dirY, ix }); return ix; }; @@ -124,7 +141,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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 fromIx = getConnIndex(fromKey, fromFx, e.fromPort.y); + const fromIx = allocConnIndex(fromKey, fromFx, e.fromPort.y, e.fromPort.side); let toIx: number; if (e.pts.length === 2 && fromG && toG) { const fc = connsByKey.get(fromKey)![fromIx]!; @@ -135,15 +152,15 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const toBottom = toG.pinY - n6(toG.hIn / 2); const exactCy = n6(startPageY - toBottom); const alignedFy = toG.hIn > 0 ? round6(1 - exactCy / toG.hIn) : e.toPort.y; - toIx = getConnIndex(toKey, toFx, alignedFy, undefined, exactCy); + toIx = allocConnIndex(toKey, toFx, alignedFy, e.toPort.side, undefined, exactCy); } else { const toLeft = toG.pinX - n6(toG.wIn / 2); const exactCx = n6(startPageX - toLeft); const alignedFx = toG.wIn > 0 ? round6(exactCx / toG.wIn) : toFx; - toIx = getConnIndex(toKey, alignedFx, e.toPort.y, exactCx, undefined); + toIx = allocConnIndex(toKey, alignedFx, e.toPort.y, e.toPort.side, exactCx, undefined); } } else { - toIx = getConnIndex(toKey, toFx, e.toPort.y); + toIx = allocConnIndex(toKey, toFx, e.toPort.y, e.toPort.side); } return { fromKey, toKey, fromIx, toIx }; }); @@ -163,6 +180,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): for (const n of scene.nodes) nodeSheetId.set(n.id, nextId++); const shapeXml: string[] = []; + const topLabelXml: string[] = []; const connectXml: string[] = []; const placed = new Map(); const mediaFiles: Array<{ rId: string; fileName: string; svg: string }> = []; @@ -373,6 +391,8 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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( ` \n` + ` \n` + @@ -386,8 +406,37 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + + ` \n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + `
`, + ); + 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( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + ` \n` + - ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + ` \n` + `
\n` + ` \n` + @@ -396,11 +445,14 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + `
\n` + `
\n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + `
\n` + ` ${escXml(band.text)}\n` + `
`, @@ -462,7 +514,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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); - shapeXml.push( + topLabelXml.push( ` \n` + ` \n` + ` \n` + @@ -508,7 +560,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): }; const lwIn = n6(lb.w / DPI); const lhIn = n6(Math.max(18, lb.h + 2) / DPI); - shapeXml.push( + topLabelXml.push( ` \n` + ` \n` + ` \n` + @@ -517,14 +569,14 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + - ` \n` + ` \n` + `
\n` + ` \n` + @@ -532,6 +584,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): `
\n` + ` \n` + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + ` ${escXml(f.label)}\n` + ` `, ); @@ -581,7 +643,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const txtXml = isAlt ? `else${div.label ? ` ${escXml(div.label)}` : ""}` : `${escXml(div.label)}`; - shapeXml.push( + topLabelXml.push( ` \n` + ` \n` + ` \n` + @@ -590,14 +652,14 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + - ` \n` + ` \n` + `
\n` + `${charXml}\n` + @@ -605,6 +667,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): `
\n` + ` \n` + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + ` ${txtXml}\n` + ` `, ); @@ -933,12 +1005,36 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const fromConn = fromPlaced.conns[ec.fromIx]!; const toConn = toPlaced.conns[ec.toIx]!; - // Exact start and end in Visio inches from the placed shape's Connection rows (eliminates RunTask jog) + // Exact start and end in Visio inches from the placed shape's Connection rows const p0 = connectionPagePt(fromPlaced, fromConn); const pN = connectionPagePt(toPlaced, toConn); 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); @@ -954,45 +1050,77 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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 lx = k === 0 ? 0 : k === vPts.length - 1 ? wIn : n6(pt.x - p0.x); - const ly = k === 0 ? 0 : k === vPts.length - 1 ? hIn : n6(pt.y - p0.y); - const tag = k === 0 ? "MoveTo" : "LineTo"; - return ` `; + 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 ` `; }).join("\n"); const fromOneBased = ec.fromIx + 1; const toOneBased = ec.toIx + 1; - let textBlockXml = ""; - let textXml = ""; + // Emit every edge label as a dedicated word-sized opaque page-colour shape in the top label layer + // (Lucidchart ignores TextBkgnd on connectors, so inline connector text gets struck through by lines/lifelines). if (e.label) { - const lcx = n6(toVisioX(e.label.box.x + e.label.box.w / 2) - p0.x); - const lcy = n6(toVisioY(e.label.box.y + e.label.box.h / 2) - p0.y); - const lw = n6((e.label.box.w + 12) / DPI); - const lh = n6(((e.label.note ? 34 : e.label.box.h) + 4) / DPI); + 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 lwIn = n6((e.label.box.w + 8) / DPI); + const lhIn = n6(((e.label.note ? 32 : Math.max(18, e.label.box.h)) + 4) / DPI); const noteChar = e.label.note ? `\n ` : ""; - textBlockXml = - ` \n` + - ` \n` + - ` \n` + - ` \n` + - ` \n` + - ` \n` + - ` \n` + + const txtXml = e.label.note + ? `${escXml(e.label.text)}\n${escXml(e.label.note)}` + : `${escXml(e.label.text)}`; + topLabelXml.push( + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + `
\n` + ` ${noteChar}\n` + `
\n` + `
\n` + ` \n` + - `
\n`; - textXml = e.label.note - ? ` ${escXml(e.label.text)}\n${escXml(e.label.note)}\n` - : ` ${escXml(e.label.text)}\n`; + `
\n` + + `
\n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + + `
\n` + + ` ${txtXml}\n` + + `
`, + ); } shapeXml.push( @@ -1014,22 +1142,21 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + ` \n` + - (beginArrow ? ` \n` : "") + + (beginArrow ? ` \n` : "") + ` \n` + - ` \n` + - textBlockXml + + ` \n` + `
\n` + ` \n` + ` \n` + ` \n` + `${geomRows}\n` + `
\n` + - textXml + ` `, ); @@ -1100,8 +1227,8 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -1117,6 +1244,10 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ? ` \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` + @@ -1159,8 +1290,8 @@ function renderConnectionRows(conns: readonly ConnEntry[], wIn: number, hIn: num ` \n` + ` \n` + ` \n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + ` \n` + ` ` )); diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index c3b8d4c2..3084a61c 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -428,8 +428,8 @@ }, "subpaths": { "diagram-interop": { - "bytes": 133770, - "gzip": 38790 + "bytes": 138213, + "gzip": 39380 } }, "package": { From 1a572a50b677bafd06d9354de9011064e4732ef2 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:39:38 -0600 Subject: [PATCH 17/19] Assert VSDX no-jump flags, unique ports, compact crow's-foot size, and top-layer opaque labels Updates assertValidVsdx to verify LineJumpCode=0, ConLineJumpCode=1, unique per-connector Connection ports, compact crow's-foot BeginArrowSize/EndArrowSize=0, and opaque FillPattern=1 EdgeLabel_*/FrameTab_*/FrameLabel_*/FrameElse_*/BandLabel_* shapes painted above connectors and activation bars. Co-Authored-By: Gemini 4 Neon --- packages/react/test/diagram-interop.test.mjs | 2 +- .../react/test/support-diagram-interop.mjs | 37 +++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs index c5224dba..57ed2b60 100644 --- a/packages/react/test/diagram-interop.test.mjs +++ b/packages/react/test/diagram-interop.test.mjs @@ -129,7 +129,7 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi assert.ok(beginOff <= 2e-6, `RunTask Begin (${begin.x},${begin.y}) on its Connection row (${from.x},${from.y}; formula ${from.fx},${from.fy})`); 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)]; + 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"); diff --git a/packages/react/test/support-diagram-interop.mjs b/packages/react/test/support-diagram-interop.mjs index 3aa87c1e..cfbec32b 100644 --- a/packages/react/test/support-diagram-interop.mjs +++ b/packages/react/test/support-diagram-interop.mjs @@ -387,15 +387,16 @@ export function assertValidVsdx(bytes, spec, context) { assert.equal(connects.length, connectors.length * 2, `${context}: 2 Connect records per connector`); const expectCard = schemaHasCardinality(spec); - let labelledCount = 0; let gluedToBar = 0; + const usedPorts = new Set(); for (const c of connectors) { assert.equal(cellVal(c.body, "ShapeRouteStyle"), "1", `${context} ${c.nameU}: ShapeRouteStyle=1`); assert.equal(cellVal(c.body, "ConFixedCode"), "2", `${context} ${c.nameU}: ConFixedCode=2`); - if (c.body.includes("")) labelledCount++; if (expectCard) { assert.ok(VSDX_CARDS.has(cellVal(c.body, "BeginArrow")), `${context} ${c.nameU}: Visio crow's-foot BeginArrow`); assert.ok(VSDX_CARDS.has(cellVal(c.body, "EndArrow")), `${context} ${c.nameU}: Visio crow's-foot EndArrow`); + assert.equal(cellVal(c.body, "BeginArrowSize"), "0", `${context} ${c.nameU}: compact crow's-foot BeginArrowSize=0`); + assert.equal(cellVal(c.body, "EndArrowSize"), "0", `${context} ${c.nameU}: compact crow's-foot EndArrowSize=0`); } const beginConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 9); @@ -429,11 +430,39 @@ export function assertValidVsdx(bytes, spec, context) { assert.ok(Math.abs(ex - endPort.x) <= 2e-6 && Math.abs(ey - endPort.y) <= 2e-6, `${context} ${c.nameU}: End (${ex},${ey}) != Connection (${endPort.x},${endPort.y})`); - const geomRows = [...c.body.matchAll(/<\/Row>/g)] + const geomRows = [...c.body.matchAll(/<\/Row>/g)] .map((m) => ({ x: bx + Number(m[2]), y: by + Number(m[3]) })); assertAxisAlignedRoute(geomRows, startPort, endPort, 2e-5, `${context} vsdx ${c.nameU}`); } - assert.equal(labelledCount, expectedLabelCount(spec), `${context}: all labelled edges have connector `); + + for (const c of connectors) { + assert.equal(cellVal(c.body, "ConLineJumpCode"), "1", `${context} ${c.nameU}: ConLineJumpCode=1`); + const beginConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 9); + const endConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 12); + for (const k of [beginConn, endConn]) { + const portKey = `${k.toSheet}:${k.toPart}`; + assert.ok(!usedPorts.has(portKey), `${context} ${c.nameU}: port ${portKey} shared by multiple connectors`); + usedPorts.add(portKey); + } + } + + const pagesXml = entries.get("visio/pages/pages.xml").toString("utf8"); + assert.match(pagesXml, //, `${context}: Visio PageSheet disables line jumps (LineJumpCode=0)`); + + // Every edge label is emitted as a dedicated opaque page-colour EdgeLabel_* shape AFTER all connectors/bars + const shapeOrder = topShapes.map((s) => attrVal(s.attrs, "NameU") ?? ""); + const lastConnectorIdx = shapeOrder.reduce((acc, n, i) => (n.startsWith("Connector_") ? i : acc), -1); + const lastBarIdx = shapeOrder.reduce((acc, n, i) => (n.startsWith("Bar_") ? i : acc), -1); + const edgeLabels = [...byId.values()].filter((s) => s.nameU.startsWith("EdgeLabel_")); + assert.equal(edgeLabels.length, expectedLabelCount(spec), `${context}: all labelled edges have opaque EdgeLabel_* shapes`); + for (const el of edgeLabels) { + assert.equal(cellVal(el.body, "FillPattern"), "1", `${context} ${el.nameU}: opaque page-colour backdrop`); + assert.ok(shapeOrder.indexOf(el.nameU) > lastConnectorIdx, `${context} ${el.nameU}: painted above connectors`); + } + for (const fl of [...byId.values()].filter((s) => /^(FrameTab_|FrameLabel_|FrameElse_|BandLabel_)/.test(s.nameU))) { + assert.equal(cellVal(fl.body, "FillPattern"), "1", `${context} ${fl.nameU}: opaque page-colour backdrop`); + assert.ok(shapeOrder.indexOf(fl.nameU) > lastBarIdx, `${context} ${fl.nameU}: painted above activation bars`); + } // Architecture groups (including nested depth-2 containers) if (spec.type === "architecture" && spec.groups?.length) { From 65b0dd7bdd147ffa1106a749724e97a91d3e6b76 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:27:44 -0600 Subject: [PATCH 18/19] Free the off-centre top and bottom ends Lucid moves, and size label backdrops as Basalt's plates The owner's round-3 Lucid imports show a 1px sideways step a quarter inch from a box wherever a line is glued to a top or bottom side away from its midpoint (HTTP + SSE and inference in architecture-auto, RunTask in architecture). Measured on his screenshots, Lucid lands those ends about 1px left of their Connection rows; every midpoint and every left or right port lands within 0.1px. Those ends are now free at their exact page point, with no Connect and no glue formula; every other end stays glued. Edge labels: a backdrop in the page's colour (white in light, the colour of Lucid's and Visio's canvas; #000 in dark, which paints its page), sized as Basalt sizes its plate: words plus space-1 a side on a line, words plus space-1-5 a side for a sequence message, words alone beside a line, 16px a line. Co-Authored-By: Gemini Neon Co-Authored-By: Claude Opus 5.5 --- packages/react/src/interop/vsdx.ts | 106 ++++++++++++++++++-------- packages/react/test/export-sizes.json | 4 +- 2 files changed, 77 insertions(+), 33 deletions(-) diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts index 7e5cd867..3d73a610 100644 --- a/packages/react/src/interop/vsdx.ts +++ b/packages/react/src/interop/vsdx.ts @@ -70,6 +70,9 @@ function connectionPagePt(shape: PlacedShape, conn: ConnEntry): Pt { 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; @@ -130,6 +133,19 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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}`) @@ -141,28 +157,40 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): 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 fromIx = allocConnIndex(fromKey, fromFx, e.fromPort.y, e.fromPort.side); - let toIx: number; + 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) { - const fc = connsByKey.get(fromKey)![fromIx]!; - const startPageX = n6(fromG.pinX - n6(fromG.wIn / 2) + fc.cx); - const startPageY = n6(fromG.pinY - n6(fromG.hIn / 2) + fc.cy); + // 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 (horiz) { + 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(startPageY - toBottom); + 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(startPageX - toLeft); + 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 }; + return { fromKey, toKey, fromIx, toIx, fromPt, toPt }; }); let nextId = 1; @@ -429,7 +457,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -523,7 +551,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -569,7 +597,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -652,7 +680,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -1002,12 +1030,12 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const fromPlaced = placed.get(ec.fromKey); const toPlaced = placed.get(ec.toKey); if (!fromPlaced || !toPlaced) continue; - const fromConn = fromPlaced.conns[ec.fromIx]!; - const toConn = toPlaced.conns[ec.toIx]!; + 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 from the placed shape's Connection rows - const p0 = connectionPagePt(fromPlaced, fromConn); - const pN = connectionPagePt(toPlaced, toConn); + // 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); @@ -1070,14 +1098,17 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): const fromOneBased = ec.fromIx + 1; const toOneBased = ec.toIx + 1; - // Emit every edge label as a dedicated word-sized opaque page-colour shape in the top label layer - // (Lucidchart ignores TextBkgnd on connectors, so inline connector text gets struck through by lines/lifelines). + // 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 lwIn = n6((e.label.box.w + 8) / DPI); - const lhIn = n6(((e.label.note ? 32 : Math.max(18, e.label.box.h)) + 4) / DPI); + 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 ` : ""; @@ -1093,7 +1124,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -1123,6 +1154,13 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ); } + 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( ` \n` + ` \n` + @@ -1134,10 +1172,10 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` \n` + ` \n` + ` \n` + - ` \n` + - ` \n` + - ` \n` + - ` \n` + + ` \n` + + ` \n` + + ` \n` + + ` \n` + ` \n` + ` \n` + ` \n` + @@ -1160,10 +1198,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"): ` `, ); - connectXml.push( - ` `, - ` `, - ); + if (fromConn) { + connectXml.push( + ` `, + ); + } + if (toConn) { + connectXml.push( + ` `, + ); + } } const svgDefaultType = mediaFiles.length diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index 3084a61c..218f8e41 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -428,8 +428,8 @@ }, "subpaths": { "diagram-interop": { - "bytes": 138213, - "gzip": 39380 + "bytes": 138715, + "gzip": 39659 } }, "package": { From fca5f348869d05bbee306910b1a1eea6bc7d8eb8 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:27:47 -0600 Subject: [PATCH 19/19] Test which .vsdx ends are free, and label backdrops' colour and size Every free end must sit off-centre on a box's top or bottom with no formula, and no glued end may; architecture-auto frees exactly HTTP + SSE's Begin and inference's End; every edge label is opaque in the page's colour and sized to its words with Basalt's padding. Co-Authored-By: Gemini Neon Co-Authored-By: Claude Opus 5.5 --- packages/react/test/diagram-interop.test.mjs | 66 +++++++++++++-- .../react/test/support-diagram-interop.mjs | 82 +++++++++++++------ 2 files changed, 115 insertions(+), 33 deletions(-) diff --git a/packages/react/test/diagram-interop.test.mjs b/packages/react/test/diagram-interop.test.mjs index 57ed2b60..d2c1a946 100644 --- a/packages/react/test/diagram-interop.test.mjs +++ b/packages/react/test/diagram-interop.test.mjs @@ -100,7 +100,7 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi }); } - test("architecture RunTask (svc -> ecs) in .vsdx glues Begin/End to exact Connection rows and rejects proof-style 0.5px drift", () => { + 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>/); @@ -109,7 +109,7 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi const cellV = (b, n) => Number(b.match(new RegExp(``)); const endConn = page1.match(new RegExp(``)); - assert.ok(beginConn && endConn, "RunTask glued from Node_svc to Node_ecs"); + 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`); @@ -118,15 +118,21 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi 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 from = connPt(svc[2], Number(beginConn[2]) - 100), to = connPt(ecs[2], Number(endConn[2]) - 100); + 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, beginOff: off(b, from), endOff: off(e, to) }; + 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, beginOff, endOff } = runTaskGlue(page1); - assert.ok(beginOff <= 2e-6, `RunTask Begin (${begin.x},${begin.y}) on its Connection row (${from.x},${from.y}; formula ${from.fx},${from.fy})`); + 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)]; @@ -140,6 +146,54 @@ describe("all five CIMIP fixtures: determinism, schemas, glue and exact port axi 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)", () => { diff --git a/packages/react/test/support-diagram-interop.mjs b/packages/react/test/support-diagram-interop.mjs index cfbec32b..b04046fa 100644 --- a/packages/react/test/support-diagram-interop.mjs +++ b/packages/react/test/support-diagram-interop.mjs @@ -384,7 +384,7 @@ export function assertValidVsdx(bytes, spec, context) { .map((m) => ({ fromSheet: m[1], fromCell: m[2], fromPart: Number(m[3]), toSheet: m[4], toCell: m[5], toPart: Number(m[6]) })); assert.equal(connectors.length, expectedEdgeCount(spec), `${context}: exact single 1-D connector count`); - assert.equal(connects.length, connectors.length * 2, `${context}: 2 Connect records per connector`); + assert.ok(connects.length <= connectors.length * 2, `${context}: at most 2 Connect records per connector`); const expectCard = schemaHasCardinality(spec); let gluedToBar = 0; @@ -401,45 +401,72 @@ export function assertValidVsdx(bytes, spec, context) { const beginConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 9); const endConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 12); - assert.ok(beginConn && endConn, `${context} ${c.nameU}: missing Begin/End Connect elements`); - assert.match(cellFormula(c.body, "BeginX") ?? "", new RegExp(`Sheet\\.${beginConn.toSheet}!Connections\\.X${beginConn.toPart - 99}\\b`)); - assert.match(cellFormula(c.body, "EndX") ?? "", new RegExp(`Sheet\\.${endConn.toSheet}!Connections\\.X${endConn.toPart - 99}\\b`)); - - const fromShape = byId.get(beginConn.toSheet); - const toShape = byId.get(endConn.toSheet); - assert.ok(fromShape && toShape, `${context} ${c.nameU}: glued shapes exist`); - if (fromShape.nameU.startsWith("Bar_") || toShape.nameU.startsWith("Bar_")) gluedToBar++; - const fc = fromShape.conns.find((r) => r.ix === beginConn.toPart - 100); - const tc = toShape.conns.find((r) => r.ix === endConn.toPart - 100); - assert.ok(fc && tc, `${context} ${c.nameU}: Connection rows exist for ToPart`); - - const startPort = { - x: fromShape.pinX - fromShape.locPinX + fc.x, - y: fromShape.pinY - fromShape.locPinY + fc.y, - }; - const endPort = { - x: toShape.pinX - toShape.locPinX + tc.x, - y: toShape.pinY - toShape.locPinY + tc.y, - }; const bx = Number(cellVal(c.body, "BeginX")); const by = Number(cellVal(c.body, "BeginY")); const ex = Number(cellVal(c.body, "EndX")); const ey = Number(cellVal(c.body, "EndY")); - assert.ok(Math.abs(bx - startPort.x) <= 2e-6 && Math.abs(by - startPort.y) <= 2e-6, - `${context} ${c.nameU}: Begin (${bx},${by}) != Connection (${startPort.x},${startPort.y})`); - assert.ok(Math.abs(ex - endPort.x) <= 2e-6 && Math.abs(ey - endPort.y) <= 2e-6, - `${context} ${c.nameU}: End (${ex},${ey}) != Connection (${endPort.x},${endPort.y})`); + + let startPort = { x: bx, y: by }; + if (beginConn) { + assert.match(cellFormula(c.body, "BeginX") ?? "", new RegExp(`Sheet\\.${beginConn.toSheet}!Connections\\.X${beginConn.toPart - 99}\\b`)); + const fromShape = byId.get(beginConn.toSheet); + assert.ok(fromShape, `${context} ${c.nameU}: glued source shape exists`); + if (fromShape.nameU.startsWith("Bar_")) gluedToBar++; + const fc = fromShape.conns.find((r) => r.ix === beginConn.toPart - 100); + assert.ok(fc, `${context} ${c.nameU}: source Connection row exists for ToPart`); + startPort = { x: fromShape.pinX - fromShape.locPinX + fc.x, y: fromShape.pinY - fromShape.locPinY + fc.y }; + assert.ok(Math.abs(bx - startPort.x) <= 2e-6 && Math.abs(by - startPort.y) <= 2e-6, + `${context} ${c.nameU}: Begin (${bx},${by}) != Connection (${startPort.x},${startPort.y})`); + } + let endPort = { x: ex, y: ey }; + if (endConn) { + assert.match(cellFormula(c.body, "EndX") ?? "", new RegExp(`Sheet\\.${endConn.toSheet}!Connections\\.X${endConn.toPart - 99}\\b`)); + const toShape = byId.get(endConn.toSheet); + assert.ok(toShape, `${context} ${c.nameU}: glued target shape exists`); + if (toShape.nameU.startsWith("Bar_")) gluedToBar++; + const tc = toShape.conns.find((r) => r.ix === endConn.toPart - 100); + assert.ok(tc, `${context} ${c.nameU}: target Connection row exists for ToPart`); + endPort = { x: toShape.pinX - toShape.locPinX + tc.x, y: toShape.pinY - toShape.locPinY + tc.y }; + assert.ok(Math.abs(ex - endPort.x) <= 2e-6 && Math.abs(ey - endPort.y) <= 2e-6, + `${context} ${c.nameU}: End (${ex},${ey}) != Connection (${endPort.x},${endPort.y})`); + } const geomRows = [...c.body.matchAll(/<\/Row>/g)] .map((m) => ({ x: bx + Number(m[2]), y: by + Number(m[3]) })); assertAxisAlignedRoute(geomRows, startPort, endPort, 2e-5, `${context} vsdx ${c.nameU}`); } + // Lucidchart moves an end glued to a box's top or bottom away from the side's midpoint about 1px and steps the line + // to rejoin it (the owner's round-3 imports), so exactly those ends are free, at their exact point with no formula; + // every other end is glued. + const nodes = [...byId.values()].filter((s) => s.nameU.startsWith("Node_")); + const offCentreTopBottom = (shape, x, y) => { + const left = shape.pinX - shape.locPinX, bottom = shape.pinY - shape.locPinY; + const onTopOrBottom = Math.abs(y - bottom) <= 2e-6 || Math.abs(y - (bottom + shape.h)) <= 2e-6; + return onTopOrBottom && x >= left - 2e-6 && x <= left + shape.w + 2e-6 && Math.abs(x - shape.pinX) > 1e-4; + }; + for (const c of connectors) { + for (const [end, part, cx, cy] of [["Begin", 9, "BeginX", "BeginY"], ["End", 12, "EndX", "EndY"]]) { + const k = connects.find((r) => r.fromSheet === c.id && r.fromPart === part); + const x = Number(cellVal(c.body, cx)), y = Number(cellVal(c.body, cy)); + if (k) { + const shape = byId.get(k.toSheet); + if (shape.nameU.startsWith("Node_")) { + assert.ok(!offCentreTopBottom(shape, x, y), `${context} ${c.nameU}: ${end} glued off-centre on ${shape.nameU}'s top or bottom, which Lucid moves`); + } + } else { + assert.equal(cellFormula(c.body, cx), undefined, `${context} ${c.nameU}: free ${end} has no glue formula`); + assert.ok(nodes.some((n) => offCentreTopBottom(n, x, y)), `${context} ${c.nameU}: ${end} (${x},${y}) is free but not off-centre on a box's top or bottom`); + } + } + } + for (const c of connectors) { assert.equal(cellVal(c.body, "ConLineJumpCode"), "1", `${context} ${c.nameU}: ConLineJumpCode=1`); const beginConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 9); const endConn = connects.find((k) => k.fromSheet === c.id && k.fromPart === 12); for (const k of [beginConn, endConn]) { + if (!k) continue; const portKey = `${k.toSheet}:${k.toPart}`; assert.ok(!usedPorts.has(portKey), `${context} ${c.nameU}: port ${portKey} shared by multiple connectors`); usedPorts.add(portKey); @@ -449,14 +476,15 @@ export function assertValidVsdx(bytes, spec, context) { const pagesXml = entries.get("visio/pages/pages.xml").toString("utf8"); assert.match(pagesXml, //, `${context}: Visio PageSheet disables line jumps (LineJumpCode=0)`); - // Every edge label is emitted as a dedicated opaque page-colour EdgeLabel_* shape AFTER all connectors/bars + // Every edge label is emitted as a dedicated EdgeLabel_* shape AFTER all connectors/bars const shapeOrder = topShapes.map((s) => attrVal(s.attrs, "NameU") ?? ""); const lastConnectorIdx = shapeOrder.reduce((acc, n, i) => (n.startsWith("Connector_") ? i : acc), -1); const lastBarIdx = shapeOrder.reduce((acc, n, i) => (n.startsWith("Bar_") ? i : acc), -1); const edgeLabels = [...byId.values()].filter((s) => s.nameU.startsWith("EdgeLabel_")); - assert.equal(edgeLabels.length, expectedLabelCount(spec), `${context}: all labelled edges have opaque EdgeLabel_* shapes`); + assert.equal(edgeLabels.length, expectedLabelCount(spec), `${context}: all labelled edges have EdgeLabel_* shapes`); for (const el of edgeLabels) { assert.equal(cellVal(el.body, "FillPattern"), "1", `${context} ${el.nameU}: opaque page-colour backdrop`); + assert.match(el.body, //, `${context} ${el.nameU}: backdrop geometry filled`); assert.ok(shapeOrder.indexOf(el.nameU) > lastConnectorIdx, `${context} ${el.nameU}: painted above connectors`); } for (const fl of [...byId.values()].filter((s) => /^(FrameTab_|FrameLabel_|FrameElse_|BandLabel_)/.test(s.nameU))) {