diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 1c770ad..38f1662 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -57,7 +57,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row. | `dsh-video` | `video` | video player tab; the bytes stay on the host and stream through a Range route | | `dsh-media` | `media` | the pack's ffmpeg owner: `media_probe` / `media_run` / `media_frames`, the Range file route, remux jobs | | `dsh-supercollider` | `supercollider` | SuperCollider the agent can play: ten `sc_*` tools over one warm `sclang` session (~31 ms a call, state kept) and a hand-written OSC client to `scsynth`, the installed `.schelp` reference indexed for `sc_help`, the `.scd` file workflow, five skills whose every example is compiled by a check, and one small console tab | -| `dsh-diagrams` | `diagrams` | Mermaid + TikZ + the vendored **Diagram Design** kit (204 examples, 44 documented types) and the seven `diagram_*` tools, validated on the host | +| `dsh-diagrams` | `diagrams` | Mermaid + TikZ + the vendored **Diagram Design** kit (204 examples, 44 documented types) + a **figure compiler** (`kind:"figure"`: a JSON spec measured, laid out, routed and emitted as one vector figure at a paper's column width), the seven `diagram_*` tools, validated on the host, and a reference corpus of two published paper figures rebuilt in that grammar | | `dsh-shaders` | `shaders` | GLSL that **compiles for real**: seven `shader_*` tools over a disposable headless browser (ANGLE/SwiftShader, argv-only, `MAP * ~NOTFOUND`), a rung ladder that is always stated (`v1-static` → `v2-compiled` → `v3-drawn` → `v4-measured`), diagnostics mapped onto the author's own line numbers, five dialects kept apart (es100, es300, shadertoy, shader-skills, and desktop GLSL, which is **refused** rather than faked), emit for web / `.frag` / ISF / FFGL-scaffold / Shadertoy, a Shaders tab with a live WebGL preview and `@param` sliders, five skills whose every example a check compiles, and three vendored corpora (106 Radiant pages with 79 extracted fragments, shader-skills' 20 modules + 11 templates + 11 pieces, and a 48-link curated index) that each re-derive offline | | `dsh-frontend-craft` | `frontend-craft` | front-end design craft: Impeccable's Apache-2.0 corpus (24 commands, 41 references) vendored at a pinned commit, its 61-rule detector built to a 4.5 MB WebAssembly module shipped in the package, `fe_context` / `fe_detect` / `fe_direction` / `fe_render` / `fe_artifact`, and a **Frontend** tab of findings, artifacts, directions and rendered previews. No network, no install, no engine download | | `dsh-rust-dev` | `rust-dev` | Rust as a surface: `rust_status` (toolchain / components / targets / workspace — the four facts that fail independently), `cargo_check` (diagnostics parsed from `--message-format=json`, codes and `file:line:col`, duplicates collapsed), `cargo_test`, `cargo_build` (artefact path and size), `rust_deps` (duplicate versions, feature chains), `rust_backtrace` (demangled frames classed into your code / a dependency / the runtime), and four skills including egui/eframe/wgpu. `--offline` by default, nothing installed, a build is never presented as read-only. Host-only | diff --git a/packages/dsh-diagrams/README.md b/packages/dsh-diagrams/README.md index 0432e60..d95815d 100644 --- a/packages/dsh-diagrams/README.md +++ b/packages/dsh-diagrams/README.md @@ -13,8 +13,9 @@ reads, addressed without naming one (`dsh-resource://diagram/library/`). (re-validate; no revision bump, report kept), `diagram_publish` (copy into the LIBRARY), `diagram_delete` and `diagram_kit` (the vendored design kit: `catalog`, `reference`, `example`, `insert`) — each taking an optional `scope` (`conversation` | `library`), a bare id resolving **library-first**. -- **Three kinds.** `mermaid` and `tikz` are languages; **`html`** is a complete self-contained HTML+SVG - document — the shape of the design kit's own examples. +- **Four kinds.** `mermaid` and `tikz` are languages; **`html`** is a complete self-contained HTML+SVG + document — the shape of the design kit's own examples; **`figure`** is a JSON spec the host + *compiles* — measured, laid out, routed and emitted as one vector figure (see below). - **Every write is validated before storage**, so a broken diagram returns the parser's or compiler's line-accurate error. Mermaid is parsed in a **child process** (a DOM stub and the same vendored engine the browser uses); TikZ is compiled by the machine's engine (`pdflatex`, else `xelatex`, else `lualatex`); `html` @@ -33,10 +34,60 @@ reads, addressed without naming one (`dsh-resource://diagram/library/`). write. `diagrams` (the index, `sidebar://diagrams`, `priority: 'builtin'`) lists the library, this conversation and the **design kit**, with the one guide entry at `order: 40` (after Files 10, Editor 20, History 30), and a `tool.call.toolview` card per tool draws it inline. -- **Export** saves what each kind can actually produce - `mmd`/`md`/`svg`/`png` for Mermaid (no PDF), `tex`/`pdf`/`svg`/`png` for TikZ, `html`/`svg` for the kit (no PNG) - to the **Desktop of the machine running the harness**, +- **Export** saves what each kind can actually produce - `mmd`/`md`/`svg`/`png` for Mermaid (no PDF), `tex`/`pdf`/`svg`/`png` for TikZ, `html`/`svg` for the kit (no PNG), `json`/`svg`/`png` for a figure (the spec, the compiled vector, and the vector rasterised 3× by the panel) - to the **Desktop of the machine running the harness**, create-exclusively; the client names a format, never a path (a browser download is the fallback). An `html` diagram exports as `.html` (the composed document a person can open) and `.svg` (the picture inside it). +## The figure compiler (`kind: "figure"`) + +A paper figure is not a drawing, it is a **layout problem**: 40–200 labelled boxes, measured type, +leaders anchored to one byte of a bar, and a print size the journal fixes. The `figure` kind takes a +JSON spec and compiles it on the host, with no browser and no clock, so the same spec always produces +the same bytes: + +``` +spec → resolve → measure (Core-14 metrics) → place (rows/columns/panels) → route (leaders, arrows, braces) + → emit SVG → check geometry (f0–f2) → [the panel rasterises a PNG in the browser] +``` + +| | | +|---|---| +| rungs | `f0-spec` (JSON, ids, links) → `f1-layout` (inside the page) → `f2-paper` (no overlap, no clipping, legible, greyscale-safe) → `f3-drawn` (the panel reported a picture) | +| primitives | `rows`, `columns`, `panel`, `text`, `list`, `code`, `strip`, `node`, `matrix`, `badge`, `legend`, `rule`, `spacer`, `stack` | +| inline markup | `**bold**`, `` `mono` ``, `{tone:text}` | +| connectors | `leader`, `arrow` (orthogonal, rounded), `brace`; an end is `"id.side"`, or `"strip.meta.bottom"` for one segment | +| sizes | **points**, because a paper is specified in points: a 7 pt label is `"size": 7` | +| presets | `ieee-single` 252 pt, `ieee-double` 516, `acm-single` 240, `acm-double` 504, `neurips` 397, `cvpr` 495, `slide` 720, `web` 540 | +| themes | `paper` (print), `editorial` (the kit's page), `dark` (screen only) | +| tones | roles, never hex: `ink`, `muted`, `meta`, `tensor`, `link`, `accent`, `warn`, `teal`, `yellow` — each with a luminance, which is what the greyscale check reads | +| export | `json` (the spec), `svg` (the compiled vector), `png` (rasterised 3× by the panel) | + +**Diagnostics are the product.** A spec that would print badly comes back as geometry, not as a +silent picture: + +``` +overlap "pane-metadata" and "pane-tensors" overlap by 4×9pt around (120, 208). +print "card-kv-count" is set at 5.2pt, below the 5.5pt a printed figure can carry. +fit "code-tensors" has a line wider than its pane; at 250pt the pane needs 268pt. +grey tones "accent" and "link" have almost the same luminance; they merge in black and white. +``` + +### The reference corpus + +`reference/figures/` is the benchmark, and it is what "paper level" means here. Each entry carries the +published original (`reference/targets/`), a written `anatomy.md`, the same figure rebuilt as +`spec.json`, the committed vector in `out/`, and a `rubric.json` of acceptance checks. Two entries ship: + +| figure | width | what it proves | +|---|---|---| +| `gguf-file-layout` | 516 pt | a byte layout: a weighted strip, a brace, segment-anchored leaders, a boxed pointer tail, two monospaced panes | +| `neo-motivation` | 516 pt | a motivation plate: three-column reading order, ✗/✓ comparison cards, two property lists, a node pipeline with an arrow, a labelled matrix | + +`checks/check-figure-corpus.mjs` rebuilds both, requires byte-identical output twice, fails on drift +against the committed SVG, and traces every rubric row to a block id and a label in the picture. +`reference/THIRD-PARTY.md` records each target's provenance, licence and sha256, and deleting a +target degrades the check to its structural tier instead of breaking it. + ## The Diagram Design kit Forty-four documented visual types and 204 worked examples, vendored whole from @@ -84,7 +135,7 @@ table. The kit is *data*, not an engine — it gives the model a third kind to w paths with **GET/HEAD/POST only** — `/api/dsh-diagrams/{health,state,diagram,document,example,artifact,export,render-report,vendor/mermaid.js}` — which is why the engine is one self-contained file on one route (ETag, ~3.4 MB) and why every write, delete -included, is a POST. Three skills are registered at runtime from the package folder **and** copied by both +included, is a POST. Four skills are registered at runtime from the package folder **and** copied by both installers into `$DSH_HOME/skills` with a `.vncode-` marker, so a person's own skill is never overwritten. @@ -95,6 +146,10 @@ overwritten. page — inside a **4 MiB source budget per conversation** (charged once on replace, checked on write AND patch, `BUDGET` on refusal) and a **16 MiB file cap**. `$DSH_HOME/dsh-diagrams/library.json` is the same shape for the whole harness. +- **A figure is compiled once per spec**: its artifact key is the spec plus `FIGURE_RENDERER_VERSION`, + so editing one field recompiles and an engine change invalidates every cached figure instead of + serving a picture the current code would not produce. A spec is a document like a TikZ source and + lives under the same 256 KiB ceiling. - **Cache**: `artifacts//{doc.tex,doc.pdf,doc.svg,doc.png,meta.json}`, keyed by engine + renderer + normalized source, LRU-pruned at **200 MiB**, **8 MiB** per artifact; a cache hit re-reads the verdict it was cached with. An `html` diagram produces no artifact: there is nothing to compile and the frame is the @@ -122,9 +177,10 @@ overwritten. ```sh node scripts/checks/check-client-bundles.mjs # tab types, seats, cards, the frame, verdicts -node scripts/checks/check-node-routes.mjs # routes, tools, store, kit, compile, export, drift, budgets +node scripts/checks/check-node-routes.mjs # routes, tools, store, kit, compile, figure, export, drift, budgets node scripts/checks/check-skill-examples.mjs # every fenced skill example, parsed or compiled node packages/dsh-diagrams/checks/check-diagrams-kit.mjs # the kit, the corpus, the port +node packages/dsh-diagrams/checks/check-figure-corpus.mjs # both reference figures: build, determinism, drift, rubric ``` `check-diagrams-kit.mjs` travels with this package. It runs the vendored tree's own `--check`, walks all **209** @@ -138,3 +194,4 @@ node packages/dsh-diagrams/vendor/build.mjs --check # fail on drift (offline) node packages/dsh-diagrams/vendor/design/build.mjs --check # re-hash the kit (offline) ``` + diff --git a/packages/dsh-diagrams/checks/check-figure-corpus.mjs b/packages/dsh-diagrams/checks/check-figure-corpus.mjs new file mode 100644 index 0000000..96dca7d --- /dev/null +++ b/packages/dsh-diagrams/checks/check-figure-corpus.mjs @@ -0,0 +1,139 @@ +// check-figure-corpus.mjs — the reference corpus is a benchmark, so it has to run. +// +// Why this exists: `reference/figures/` is what "paper level" MEANS for this +// package. A figure compiler that nobody measures against a published figure is a +// drawing tool with an opinion. This check rebuilds every spec and asserts: +// +// - the spec compiles with no geometry diagnostic (f2-paper); +// - the same spec builds byte-identical SVG twice (determinism, which is what +// lets the artifact cache key on the source); +// - the committed `out/figure.svg` is what the current compiler produces (DRIFT +// otherwise: the corpus is a regression target, not a screenshot); +// - every rubric row is traceable: its block ids exist, its labels appear in the +// built picture, its caption exists, and its type floor holds; +// - a committed target still hashes to what its rubric records. +// +// Run: node packages/dsh-diagrams/checks/check-figure-corpus.mjs +import { createHash } from 'node:crypto' +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { buildFigure } from '../lib/figure/index.js' +import { MIN_PRINT_TEXT } from '../lib/figure/constants.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const packageRoot = path.resolve(here, '..') +const referenceRoot = path.join(packageRoot, 'reference') +const figuresRoot = path.join(referenceRoot, 'figures') + +let failures = 0 +function check(label, actual, expected = true) { + const ok = actual === expected + if (!ok) failures += 1 + const shown = typeof actual === 'string' || typeof actual === 'number' ? ' "' + String(actual).slice(0, 160) + '"' : '' + console.log((ok ? 'ok ' : 'FAIL ') + label + shown) +} + +/** Every block id in a spec, including a strip's segment and tail addresses. */ +function collectIds(blocks, into = new Set()) { + for (const entry of blocks ?? []) { + const block = entry && entry.block ? entry.block : entry + if (!block || typeof block !== 'object') continue + if (typeof block.id === 'string' && block.id.length > 0) { + into.add(block.id) + if (Array.isArray(block.segments)) { + for (const segment of block.segments) if (segment && segment.id) into.add(block.id + '.' + String(segment.id)) + if (block.tail) into.add(block.id + '.tail') + } + } + if (Array.isArray(block.children)) collectIds(block.children, into) + } + return into +} + +/** The text a reader can see in the built SVG (tags stripped, entities decoded). */ +function visibleText(svg) { + return String(svg) + .replace(/<[^>]+>/g, ' ') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/&/g, '&') +} + +if (!existsSync(figuresRoot)) { + console.log('skip: no reference figures (the package still ships the grammar)') + process.exit(0) +} + +const folders = readdirSync(figuresRoot).filter((name) => statSync(path.join(figuresRoot, name)).isDirectory()).sort() +check('the corpus has figures', folders.length > 0) + +for (const slug of folders) { + const folder = path.join(figuresRoot, slug) + const specPath = path.join(folder, 'spec.json') + const outPath = path.join(folder, 'out', 'figure.svg') + console.log('\n# ' + slug) + + check(slug + ': anatomy.md is written', existsSync(path.join(folder, 'anatomy.md'))) + check(slug + ': SOURCE.md records provenance', existsSync(path.join(folder, 'SOURCE.md'))) + if (!existsSync(specPath)) { + check(slug + ': spec.json exists', false) + continue + } + const source = readFileSync(specPath, 'utf8') + const first = buildFigure(source) + const second = buildFigure(source) + check(slug + ': compiles to f2-paper', first.rung, 'f2-paper') + check(slug + ': no geometry diagnostic', first.diagnostics.length, 0) + check(slug + ': builds byte-identical twice', first.svg === second.svg) + check(slug + ': draws something', String(first.svg ?? '').includes(' 20) + check(slug + ': the spec carries a description', typeof figure.description === 'string' && figure.description.length > 20) + check(slug + ': no type below the print floor', (first.stats?.smallestText ?? 0) >= MIN_PRINT_TEXT) + + const targetName = typeof rubric.target === 'string' ? path.basename(rubric.target) : null + const targetPath = targetName ? path.join(referenceRoot, 'targets', targetName) : null + if (targetPath && existsSync(targetPath)) { + const digest = createHash('sha256').update(readFileSync(targetPath)).digest('hex') + check(slug + ': the committed target still hashes to the rubric', digest, rubric.targetSha256) + } else { + console.log('ok ' + slug + ': no target committed (structural tier only)') + } +} + +console.log('\n' + (failures === 0 ? 'figure corpus ok: ' + folders.length + ' figure(s)' : failures + ' figure-corpus check(s) FAILED')) +process.exit(failures === 0 ? 0 : 1) diff --git a/packages/dsh-diagrams/lib/client.js b/packages/dsh-diagrams/lib/client.js index 4e7874d..a91453f 100644 --- a/packages/dsh-diagrams/lib/client.js +++ b/packages/dsh-diagrams/lib/client.js @@ -122,6 +122,7 @@ window.__ModuleLoader__.load({ function kindLabel(kind) { if (kind === 'tikz') return 'TikZ' if (kind === 'html') return 'Design' + if (kind === 'figure') return 'Figure' return 'Mermaid' } /** Client services, all resolved lazily (none of them is required to draw). */ @@ -1122,7 +1123,7 @@ function tabInfoNow(props) { .slice(0, 8) } - /** A TikZ picture: the host compiled it, so fetch the artifact and show it. */ + /** A compiled picture (TikZ or a figure): the host built it, so fetch the artifact and show it. */ function TikzPicture(props) { const sessionId = props.sessionId const diagramId = props.diagramId @@ -1190,7 +1191,7 @@ function tabInfoNow(props) { diagramId, revision, { - kind: 'tikz', + kind: props.kind === 'figure' ? 'figure' : 'tikz', ok: !state.error, phase: state.error ? 'artifact' : null, error: state.error, @@ -1308,13 +1309,14 @@ function tabInfoNow(props) { /** One picture, dispatched by kind. */ function Picture(props) { - if (props.kind === 'tikz') { + if (props.kind === 'tikz' || props.kind === 'figure') { return h(TikzPicture, { sessionId: props.sessionId, diagramId: props.diagramId, revision: props.revision, scope: props.scope, format: 'svg', + kind: props.kind, alt: props.title, }) } @@ -1458,7 +1460,7 @@ function tabInfoNow(props) { function metaLine(entry) { if (!entry) return '' const parts = [] - if (entry.kind) parts.push(entry.kind === 'tikz' ? 'TikZ' : 'Mermaid') + if (entry.kind) parts.push(entry.kind === 'tikz' ? 'TikZ' : entry.kind === 'figure' ? 'Figure' : entry.kind === 'html' ? 'Design' : 'Mermaid') if (entry.diagramType) parts.push(entry.diagramType) if (typeof entry.lines === 'number') parts.push(entry.lines + (entry.lines === 1 ? ' line' : ' lines')) if (entry.artifact && entry.artifact.pages) parts.push(entry.artifact.pages + (entry.artifact.pages === 1 ? ' page' : ' pages')) @@ -1833,6 +1835,14 @@ function tabInfoNow(props) { const svg = await mermaidSvgNow(entry.source, dark) data = format === 'png' ? await svgToPng(svg, 2) : base64Utf8(svg) } + // A figure is compiled on the host to one SVG; the PNG is rasterised + // HERE, because a canvas is the one rasteriser this pack has. + if (entry.kind === 'figure' && format === 'png') { + const url = ARTIFACT_ROUTE + '?session=' + encodeURIComponent(sessionId) + '&id=' + encodeURIComponent(diagramId) + '&format=svg' + const response = await fetch(url, { credentials: 'same-origin' }) + if (!response.ok) throw new Error('The compiled figure is not available yet.') + data = await svgToPng(await response.text(), 3) + } const answer = await apiFetch(EXPORT_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -1866,6 +1876,17 @@ function tabInfoNow(props) { blob = new Blob(['# ' + (entry.title || entry.id) + '\n\n```' + (entry.kind === 'mermaid' ? 'mermaid' : 'latex') + '\n' + entry.source + '\n```\n'], { type: 'text/markdown', }) + } else if (entry.kind === 'figure' && (format === 'svg' || format === 'png')) { + const url = ARTIFACT_ROUTE + '?session=' + encodeURIComponent(sessionId) + '&id=' + encodeURIComponent(diagramId) + '&format=svg' + const response = await fetch(url, { credentials: 'same-origin' }) + if (!response.ok) throw new Error('The compiled figure is not available yet.') + if (format === 'svg') { + blob = new Blob([await response.text()], { type: 'image/svg+xml' }) + } else { + const base64 = await svgToPng(await response.text(), 3) + const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)) + blob = new Blob([bytes], { type: 'image/png' }) + } } else if (entry.kind === 'mermaid') { const svg = await mermaidSvgNow(entry.source, dark) if (format === 'svg') blob = new Blob([svg], { type: 'image/svg+xml' }) @@ -2010,7 +2031,7 @@ function tabInfoNow(props) { ) } - const formats = kind === 'tikz' ? ['tex', 'pdf', 'svg', 'png'] : kind === 'html' ? ['html', 'svg'] : ['mmd', 'md', 'svg', 'png'] + const formats = kind === 'tikz' ? ['tex', 'pdf', 'svg', 'png'] : kind === 'html' ? ['html', 'svg'] : kind === 'figure' ? ['json', 'svg', 'png'] : ['mmd', 'md', 'svg', 'png'] return h( 'div', { className: 'dsd-root' }, @@ -2036,7 +2057,7 @@ function tabInfoNow(props) { frameMode === 'wide' ? 'Fit' : 'Actual', ) : null, - entry.kind === 'tikz' + entry.kind === 'tikz' || entry.kind === 'figure' ? h( Button, { @@ -2610,7 +2631,7 @@ function tabInfoNow(props) { h( 'div', { className: 'dsd-cardTop' }, - h('span', { className: 'dsd-badge' }, kind === 'tikz' ? 'TikZ' : 'Mermaid'), + h('span', { className: 'dsd-badge' }, kindLabel(kind)), h('span', { className: 'dsd-cardTitle' }, title || id), h('span', { className: 'dsd-cardId' }, id), known ? h(StatusPill, { status: known.status }) : running ? h('span', { className: 'dsd-status' }, 'writing...') : null, @@ -2753,3 +2774,6 @@ function tabInfoNow(props) { return module.exports }, }) + + + diff --git a/packages/dsh-diagrams/lib/figure/constants.js b/packages/dsh-diagrams/lib/figure/constants.js new file mode 100644 index 0000000..7355c74 --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/constants.js @@ -0,0 +1,70 @@ +/** + * dsh-diagrams — the figure grammar's fixed vocabulary. + * + * Sizes are POINTS, because a paper figure is specified in points: a 7 in + * two-column figure is 516 pt wide and its body text is 7 pt, and neither number + * should need a conversion to be read. The SVG's viewBox is in the same units, so + * `font-size="7"` in the document is 7 pt on the page. + */ + +/** The column widths a paper actually uses, in points (1 in = 72 pt). */ +export const PRESETS = { + 'ieee-single': { width: 252, label: 'IEEE single column (3.5 in)' }, + 'ieee-double': { width: 516, label: 'IEEE double column (7.16 in)' }, + 'acm-single': { width: 240, label: 'ACM single column (3.33 in)' }, + 'acm-double': { width: 504, label: 'ACM double column (7 in)' }, + neurips: { width: 397, label: 'NeurIPS text width (5.5 in)' }, + cvpr: { width: 495, label: 'CVPR text width (6.87 in)' }, + slide: { width: 720, label: 'Slide (10 in)' }, + web: { width: 540, label: 'Web / README (7.5 in)' }, + free: { width: 0, label: 'Explicit width' }, +} + +/** The theme names a spec may carry. */ +export const THEME_NAMES = ['paper', 'editorial', 'dark'] + +/** Everything a `blocks` entry may be. */ +export const PRIMITIVES = [ + 'rows', + 'columns', + 'panel', + 'text', + 'list', + 'code', + 'strip', + 'node', + 'matrix', + 'badge', + 'legend', + 'rule', + 'spacer', + 'stack', +] + +/** The three connector kinds. */ +export const LINK_KINDS = ['leader', 'arrow', 'brace'] + +/** The smallest type a printed figure may carry, in points. */ +export const MIN_PRINT_TEXT = 5.5 + +/** The smallest stroke a 300 dpi print resolves, in points. */ +export const MIN_PRINT_STROKE = 0.4 + +/** Default type ramp, in points. */ +export const TYPE = { + body: 7, + small: 6.2, + tiny: 5.6, + title: 9, + panel: 8, + code: 6.2, +} + +/** Default spacing, in points. */ +export const SPACE = { + margin: 10, + gap: 8, + pad: 5, + radius: 3, + leader: 6, +} diff --git a/packages/dsh-diagrams/lib/figure/emit.js b/packages/dsh-diagrams/lib/figure/emit.js new file mode 100644 index 0000000..d8123c6 --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/emit.js @@ -0,0 +1,562 @@ +/** + * dsh-diagrams — the figure SVG emitter. + * + * The layout tree goes in; one self-contained SVG document comes out. Text stays + * TEXT (selectable, searchable, editable in Illustrator or Inkscape) rather than + * outlines, which is what a paper needs: a reviewer can copy a label out of the + * PDF, and the file stays small. + * + * Every colour is resolved from the palette at emit time, so a spec never names a + * hex value and the same figure can be re-emitted for paper, page or screen. + */ + +/** XML-escape one text node. */ +export function escapeXml(value) { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} + +/** Round to two decimals: SVG needs no more, and it keeps the bytes stable. */ +function n(value) { + return Math.round(value * 100) / 100 +} + +/** One line's `` element, with a `` per run. */ +function textElement({ x, y, line, size, palette, anchor = null }) { + if (!line || line.runs.length === 0) return '' + const parts = line.runs.map((run) => { + const tone = palette.tone(run.tone) + const families = [] + if (run.mono) families.push('font-family="' + palette.mono + '"') + else families.push('font-family="' + palette.font + '"') + if (run.bold) families.push('font-weight="bold"') + return '' + escapeXml(run.text) + '' + }) + return ( + '' + + parts.join('') + + '' + ) +} + +/** Where one line starts, given the block's alignment. */ +function lineX(node, line, align) { + if (align === 'center') return node.x + (node.w - line.width) / 2 + if (align === 'right') return node.x + node.w - line.width + return node.x +} + +/** Every line of a text-like node. */ +function emitLines(node, palette, { align = 'left', x = null, size, lineTop = null } = {}) { + const lines = node.lines ?? [] + const style = node.textStyle ?? {} + const font = size ?? style.size ?? 7 + const out = [] + let cursor = lineTop === null ? node.y : lineTop + for (const line of lines) { + out.push(textElement({ x: x === null ? lineX(node, line, align) : x, y: cursor + font * 0.98, line, size: font, palette })) + cursor += font * 1.32 + } + return out.join('') +} + +/** The frame of a panel, node, code pane or badge. */ +function frame(node, { fill, stroke, dash, radius = 0, width = 0.5 }) { + return ( + ' 0 ? ' rx="' + n(radius) + '"' : '') + + ' fill="' + + (fill ?? 'none') + + '" stroke="' + + (stroke ?? 'none') + + '" stroke-width="' + + n(width) + + '"' + + (dash ? ' stroke-dasharray="2.6 1.8"' : '') + + '/>' + ) +} + +/** Draw one built node and its children. */ +export function emitNode(node, palette) { + const out = [] + const type = node.type + if (type === 'text') { + out.push(emitLines(node, palette, { align: node.textStyle?.align ?? 'left' })) + } else if (type === 'list') { + const { size, markerWidth } = node.list + for (const child of node.children) { + out.push( + textElement({ + x: node.x, + y: child.y + size * 0.98, + line: { runs: [{ text: child.marker, tone: 'muted', mono: false, bold: false }], width: markerWidth }, + size, + palette, + }), + ) + out.push(emitLines({ ...child, lines: child.lines }, palette, { align: 'left', x: node.x + markerWidth, size, lineTop: child.y })) + } + } else if (type === 'code') { + const { size, pad, tone, dash, frame: framed, fill } = node.code + if (framed) { + out.push( + frame(node, { + fill: fill ?? (tone === 'soft' ? palette.tone('soft').fill : palette.tone(tone).fill), + stroke: palette.tone(tone).stroke, + dash, + radius: node.code.radius, + }), + ) + } + let cursor = node.y + pad + for (const line of node.lines) { + out.push(textElement({ x: node.x + pad, y: cursor + size * 0.98, line, size, palette })) + cursor += size * 1.32 + } + } else if (type === 'panel') { + const panel = node.panel + const tone = palette.tone(panel.tone) + const fill = panel.fill === 'paper' ? palette.paper : panel.fill + out.push(frame(node, { fill: fill ?? 'none', stroke: tone.stroke, dash: panel.dash, radius: panel.radius })) + if (panel.title && panel.titleLines.length > 0) { + let cursor = node.y + node.measured.pad + for (const line of panel.titleLines) { + const x = panel.titleAlign === 'center' ? node.x + (node.w - line.width) / 2 : node.x + node.measured.pad + out.push(textElement({ x, y: cursor + panel.titleSize * 0.98, line, size: panel.titleSize, palette })) + cursor += panel.titleSize * 1.32 + } + } + } else if (type === 'node') { + const tone = palette.tone(node.node.tone) + const radius = node.shape === 'round' || node.shape === 'pill' ? node.h / 2 : node.node.radius + out.push( + frame(node, { + fill: tone.fill, + stroke: tone.stroke, + dash: node.node.dash, + radius, + width: node.node.tone === 'ink' ? 0.8 : 0.6, + }), + ) + let cursor = node.y + node.node.pad + for (const line of node.titleLines ?? []) { + out.push(textElement({ x: node.x + (node.w - line.width) / 2, y: cursor + node.node.size * 0.98, line, size: node.node.size, palette })) + cursor += node.node.size * 1.32 + } + cursor += node.subLines.length > 0 ? 1 : 0 + for (const line of node.subLines) { + out.push(textElement({ x: node.x + (node.w - line.width) / 2, y: cursor + node.node.subSize * 0.98, line, size: node.node.subSize, palette })) + cursor += node.node.subSize * 1.32 + } + } else if (type === 'badge') { + const badge = node.badge + const tone = palette.tone(badge.tone) + out.push( + '', + ) + if (badge.line) { + out.push( + textElement({ + x: badge.x + badge.w / 2, + y: node.y + node.h / 2 + badge.size * 0.35, + line: badge.line, + size: badge.size, + palette, + anchor: 'middle', + }), + ) + } + } else if (type === 'legend') { + const { items, size, gap } = node.legend + let cursorX = node.x + let cursorY = node.y + for (const item of items) { + if (cursorX > node.x && cursorX + item.width > node.x + node.w) { + cursorX = node.x + cursorY += size * 1.32 + } + out.push( + '', + ) + out.push( + textElement({ + x: cursorX + 11, + y: cursorY + size * 0.98, + line: { runs: [{ text: item.label, tone: 'muted', bold: false, mono: false }], width: 0 }, + size, + palette, + }), + ) + cursorX += item.width + gap + } + } else if (type === 'strip') { + const strip = node.strip + const barTop = node.y + strip.labelHeight + for (const segment of node.segments ?? []) { + const tone = palette.tone(segment.tone) + const y = barTop + const h = strip.bar + out.push( + '', + ) + if (strip.labels && segment.label) { + const line = { runs: [{ text: segment.label, tone: 'ink', bold: false, mono: false }], width: 0 } + const width = lineWidthOf(segment.label, strip.labelSize) + out.push( + textElement({ + x: segment.x + segment.w / 2, + y: node.y + strip.labelSize * 0.98, + line: { ...line, width }, + size: strip.labelSize, + palette, + anchor: 'middle', + }), + ) + out.push( + '', + ) + } + } + if (strip.tail && node.tailBox) { + const text = strip.tail.text + const box = node.tailBox + out.push( + '', + ) + out.push( + textElement({ + x: box.x + box.w / 2, + y: box.y + box.h / 2 + 2, + line: { runs: [{ text, tone: 'ink', bold: false, mono: true }], width: box.w }, + size: 5.6, + palette, + anchor: 'middle', + }), + ) + } + } else if (type === 'matrix') { + const matrix = node.matrix + for (let row = 0; row < matrix.rows; row += 1) { + for (let col = 0; col < matrix.cols; col += 1) { + const cell = findCell(matrix.cells, row, col) + const tone = palette.tone(cell?.tone ?? null) + const x = matrix.x + col * (matrix.cell + matrix.gap) + const y = matrix.y + row * (matrix.cell + matrix.gap) + out.push( + '', + ) + } + } + matrix.colLabels.forEach((label, index) => { + out.push( + textElement({ + x: matrix.x + index * (matrix.cell + matrix.gap) + matrix.cell / 2, + y: node.y + matrix.labelSize * 0.98, + line: { runs: [{ text: label, tone: 'muted', bold: false, mono: false }], width: 0 }, + size: matrix.labelSize, + palette, + anchor: 'middle', + }), + ) + }) + matrix.rowLabels.forEach((label, index) => { + const y = matrix.y + index * (matrix.cell + matrix.gap) + matrix.cell / 2 + matrix.labelSize * 0.35 + if (matrix.rotateRowLabels) { + out.push( + '' + + escapeXml(label) + + '', + ) + } else { + out.push( + textElement({ + x: matrix.x - 2.5, + y, + line: { runs: [{ text: label, tone: 'muted', bold: false, mono: false }], width: 0 }, + size: matrix.labelSize, + palette, + anchor: 'end', + }), + ) + } + }) + } else if (type === 'rule') { + out.push( + '', + ) + } + + for (const child of node.children ?? []) out.push(emitNode(child, palette)) + return out.join('') +} + +/** One grid cell by row/column. */ +function findCell(cells, row, col) { + for (const cell of cells) { + if (Number(cell.r) === row && Number(cell.c) === col) return cell + } + return null +} + +/** The width of a plain string at a size, for labels the emitter places itself. */ +function lineWidthOf(text, size, mono = false) { + let total = 0 + for (const character of String(text)) total += characterWidth(character, size, mono) + return total +} + +/** One glyph's advance, read from the same table the layout uses. */ +function characterWidth(character, size, mono) { + if (mono) return size * 0.6 + const code = character.charCodeAt(0) + if (code === 32) return size * 0.278 + if (code >= 48 && code <= 57) return size * 0.556 + if (code >= 65 && code <= 90) return size * 0.667 + if (code >= 97 && code <= 122) return size * 0.556 + return size * 0.5 +} + +// --------------------------------------------------------------------------- +// Links +// --------------------------------------------------------------------------- + +/** A point offset outward from an anchor along its side's normal. */ +function offset(point, side, distance) { + if (side === 'top') return { x: point.x, y: point.y - distance } + if (side === 'bottom') return { x: point.x, y: point.y + distance } + if (side === 'left') return { x: point.x - distance, y: point.y } + if (side === 'right') return { x: point.x + distance, y: point.y } + return point +} + +/** Route an elbow: out of the source, across, and into the target along its normal. */ +export function elbowPoints(source, target, distance = 5) { + const p0 = source.point + const p3 = target.point + if (source.side === 'center' || target.side === 'center') return [p0, p3] + const vertical = source.side === 'top' || source.side === 'bottom' + // The clearance is half the room between the two anchor lines, capped by what + // the caller asked for. Without this a 5pt elbow in an 8pt gutter overshoots + // its own target and draws a hook. + const span = vertical ? Math.abs(p3.y - p0.y) : Math.abs(p3.x - p0.x) + const clear = Math.max(1.2, Math.min(distance, span / 2)) + const p1 = offset(p0, source.side, clear) + const p2 = offset(p3, target.side, clear) + const corner = vertical ? { x: p2.x, y: p1.y } : { x: p1.x, y: p2.y } + const points = [p0, p1] + if (Math.abs(corner.x - p1.x) > 0.2 || Math.abs(corner.y - p1.y) > 0.2) points.push(corner) + if (Math.abs(p2.x - corner.x) > 0.2 || Math.abs(p2.y - corner.y) > 0.2) points.push(p2) + points.push(p3) + return dedupe(points) +} + +/** Remove consecutive duplicate points. */ +function dedupe(points) { + const out = [] + for (const point of points) { + const last = out[out.length - 1] + if (!last || Math.abs(last.x - point.x) > 0.05 || Math.abs(last.y - point.y) > 0.05) out.push(point) + } + return out +} + +/** A polyline with rounded corners. */ +function roundedPath(points, radius = 2.4) { + if (points.length < 2) return '' + let d = 'M ' + n(points[0].x) + ' ' + n(points[0].y) + for (let index = 1; index < points.length - 1; index += 1) { + const previous = points[index - 1] + const current = points[index] + const next = points[index + 1] + const inLength = Math.hypot(current.x - previous.x, current.y - previous.y) + const outLength = Math.hypot(next.x - current.x, next.y - current.y) + const cut = Math.min(radius, inLength / 2, outLength / 2) + if (cut < 0.2) { + d += ' L ' + n(current.x) + ' ' + n(current.y) + continue + } + const enter = { x: current.x + ((previous.x - current.x) / inLength) * cut, y: current.y + ((previous.y - current.y) / inLength) * cut } + const leave = { x: current.x + ((next.x - current.x) / outLength) * cut, y: current.y + ((next.y - current.y) / outLength) * cut } + d += ' L ' + n(enter.x) + ' ' + n(enter.y) + ' Q ' + n(current.x) + ' ' + n(current.y) + ' ' + n(leave.x) + ' ' + n(leave.y) + } + const last = points[points.length - 1] + d += ' L ' + n(last.x) + ' ' + n(last.y) + return d +} + +/** A small solid arrowhead at the end of a segment. */ +function arrowHead(from, to, color) { + const angle = Math.atan2(to.y - from.y, to.x - from.x) + const length = 3.4 + const width = 2.2 + const tip = to + const left = { x: tip.x - Math.cos(angle) * length + Math.cos(angle + Math.PI / 2) * width * 0.5, y: tip.y - Math.sin(angle) * length + Math.sin(angle + Math.PI / 2) * width * 0.5 } + const right = { x: tip.x - Math.cos(angle) * length - Math.cos(angle + Math.PI / 2) * width * 0.5, y: tip.y - Math.sin(angle) * length - Math.sin(angle + Math.PI / 2) * width * 0.5 } + return '' +} + +/** Draw one connector. */ +export function emitLink(link, palette, anchors) { + const tone = palette.tone(link.tone ?? 'muted') + const dash = link.dash === true ? ' stroke-dasharray="2.4 1.8"' : '' + if (link.kind === 'brace') { + const first = anchors.get(String(link.from)) + const second = anchors.get(String(link.to)) + if (!first || !second) return '' + const x0 = first.left.x + const x1 = second.right.x + const y = Math.max(first.bottom.y, second.bottom.y) + 2.5 + const middle = (x0 + x1) / 2 + const d = + 'M ' + n(x0) + ' ' + n(y - 2.5) + ' L ' + n(x0) + ' ' + n(y) + ' L ' + n(middle - 1.5) + ' ' + n(y) + + ' L ' + n(middle) + ' ' + n(y + 2.5) + ' L ' + n(middle + 1.5) + ' ' + n(y) + ' L ' + n(x1) + ' ' + n(y) + + ' L ' + n(x1) + ' ' + n(y - 2.5) + const label = link.label + ? '' + escapeXml(link.label) + '' + : '' + return '' + label + } + const source = resolve(anchors, link.from, 'bottom') + const target = resolve(anchors, link.to, 'top') + if (!source || !target) return '' + const points = link.route === 'straight' ? [source.point, target.point] : elbowPoints(source, target, link.out ?? 5) + const path = '' + const dot = link.dot ? '' : '' + const head = + link.head === false + ? '' + : arrowHead(points[points.length - 2], points[points.length - 1], tone.stroke) + const label = + link.label && points.length > 1 + ? labelAt(link.label, points, palette) + : '' + return path + dot + head + label +} + +/** A label on the longest segment, with a paper mask so the line never shows through. */ +function labelAt(text, points, palette) { + let best = null + for (let index = 1; index < points.length; index += 1) { + const a = points[index - 1] + const b = points[index] + const length = Math.hypot(b.x - a.x, b.y - a.y) + if (!best || length > best.length) best = { a, b, length } + } + if (!best) return '' + const mid = { x: (best.a.x + best.b.x) / 2, y: (best.a.y + best.b.y) / 2 } + const width = lineWidthOf(text, 5.8) + 4 + return ( + '' + + '' + escapeXml(text) + '' + ) +} + +/** Resolve a reference, preferring an explicit side and falling back to the nearest. */ +function resolve(anchors, reference, fallback) { + const text = String(reference ?? '') + if (anchors.has(text)) { + const found = anchors.get(text) + return { point: found.center, side: 'center', box: found } + } + const parts = text.split('.') + if (parts.length === 1) return null + const side = parts[parts.length - 1] + const id = parts.slice(0, -1).join('.') + const found = anchors.get(id) + if (!found) return null + return { point: found[side] ?? found[fallback], side: found[side] ? side : fallback, box: found } +} diff --git a/packages/dsh-diagrams/lib/figure/index.js b/packages/dsh-diagrams/lib/figure/index.js new file mode 100644 index 0000000..5adcdfb --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/index.js @@ -0,0 +1,280 @@ +/** + * dsh-diagrams — the figure compiler. + * + * `buildFigure(source)` is the whole engine behind one call: parse, measure, place, + * route, emit, and check the result against the geometry contract. It is pure and + * synchronous — no browser, no clock, no disk — so the same spec always produces the + * same bytes, which is what lets the corpus check assert determinism and lets the + * artifact cache key on the source alone. + * + * The rungs it reports, in the same shape the shader row uses: + * + * f0-spec the JSON parsed and every block/link resolved + * f1-layout boxes were measured and placed inside the page + * f2-paper no overlap, no clipping, no colour-only distinction, type legible + * f3-drawn the browser rendered it (reported by the panel, not by this file) + */ +import { MIN_PRINT_TEXT, PRESETS, THEME_NAMES } from './constants.js' +import { buildBlock, collectAnchors, num } from './layout.js' +import { emitLink, emitNode, escapeXml } from './emit.js' +import { paletteFor, contrast, luminance } from './theme.js' +import { parseFigure } from './spec.js' + +/** Round a diagnostic number for the model's eyes. */ +function round(value) { + return Math.round(value * 10) / 10 +} + +/** + * Compile one figure. + * + * @param source - the JSON spec. + * @param options - `{ theme }` overrides the spec's theme (the panel's toggle). + * @returns `{ ok, status, rung, svg, width, height, diagnostics, warnings, stats, ms }`. + */ +export function buildFigure(source, { theme = null } = {}) { + const started = Date.now() + const parsed = parseFigure(source) + if (parsed.problems.length > 0) { + return { ok: false, status: 'error', rung: 'f0-spec', svg: null, width: 0, height: 0, diagnostics: parsed.problems, warnings: [], stats: null, ms: Date.now() - started } + } + const spec = parsed.spec + const palette = paletteFor(theme && THEME_NAMES.includes(theme) ? theme : spec.figure.theme) + const margin = spec.figure.margin + const contentWidth = Math.max(20, spec.figure.width - margin * 2) + const ctx = { palette, gap: spec.figure.gap, base: spec.figure.size } + const root = buildBlock({ type: 'rows', children: spec.blocks, gap: spec.figure.gap }, ctx, margin, margin, contentWidth) + const contentBottom = root.y + root.h + margin + const height = spec.figure.height !== null ? spec.figure.height : Math.ceil(contentBottom) + const { anchors, solids } = collectAnchors(root) + const diagnostics = [] + const warnings = [] + + // --- f1: everything inside the page ------------------------------------- + const nodes = [] + const walk = (node, parent, inStack) => { + nodes.push({ node, parent, inStack }) + for (const child of node.children ?? []) walk(child, node, inStack || node.type === 'stack') + } + walk(root, null, false) + for (const entry of nodes) { + const { node } = entry + if (node.w <= 0 || node.h <= 0) continue + if (node.x < -0.5 || node.y < -0.5 || node.x + node.w > spec.figure.width + 0.5) { + diagnostics.push({ kind: 'bounds', text: labelOf(node) + ' extends outside the ' + spec.figure.width + 'pt page (x ' + round(node.x) + '..' + round(node.x + node.w) + ').' }) + } + if (spec.figure.height !== null && node.y + node.h > height + 0.5) { + diagnostics.push({ kind: 'bounds', text: labelOf(node) + ' runs past the fixed height of ' + height + 'pt; raise `figure.height` or shorten the content.' }) + } + } + + // --- f2: nothing overlaps, nothing is hidden ---------------------------- + const solidNodes = nodes.filter((entry) => entry.node.solid && !entry.inStack).map((entry) => entry.node) + for (let first = 0; first < solidNodes.length; first += 1) { + for (let second = first + 1; second < solidNodes.length; second += 1) { + const a = solidNodes[first] + const b = solidNodes[second] + if (isAncestor(nodes, a, b) || isAncestor(nodes, b, a)) continue + const overlapX = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x) + const overlapY = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y) + if (overlapX > 0.8 && overlapY > 0.8) { + diagnostics.push({ + kind: 'overlap', + text: labelOf(a) + ' and ' + labelOf(b) + ' overlap by ' + round(overlapX) + '×' + round(overlapY) + 'pt around (' + round(Math.max(a.x, b.x)) + ', ' + round(Math.max(a.y, b.y)) + ').', + }) + } + } + } + + // --- connectors --------------------------------------------------------- + for (const link of spec.links) { + for (const field of ['from', 'to']) { + if (!resolveReference(anchors, link[field])) { + diagnostics.push({ kind: 'link', text: 'link ' + (link.id ? '"' + link.id + '" ' : '') + 'points at "' + String(link[field]) + '", which does not resolve. A segment anchor is "strip..top".' }) + } + } + } + + // --- warnings: the figure is valid, but a reader would complain --------- + const usedTones = new Set() + const collectTones = (blocks) => { + for (const block of blocks) { + for (const tone of [block.tone, block.color]) if (typeof tone === 'string') usedTones.add(tone) + if (Array.isArray(block.segments)) for (const segment of block.segments) if (segment.tone) usedTones.add(segment.tone) + if (Array.isArray(block.cells)) for (const cell of block.cells) if (cell.tone) usedTones.add(cell.tone) + if (Array.isArray(block.items)) for (const item of block.items) if (item && item.tone) usedTones.add(item.tone) + if (Array.isArray(block.children)) for (const child of block.children) collectTones(child.block ? [child.block] : [child]) + } + } + collectTones(spec.blocks) + + const accents = [...usedTones].filter((tone) => palette.tones[tone] && !['ink', 'muted', 'soft'].includes(tone)) + for (let first = 0; first < accents.length; first += 1) { + for (let second = first + 1; second < accents.length; second += 1) { + const a = palette.tone(accents[first]).bar + const b = palette.tone(accents[second]).bar + if (contrast(a, b) < 1.25) { + warnings.push({ kind: 'grey', text: 'tones "' + accents[first] + '" and "' + accents[second] + '" have almost the same luminance (' + round(luminance(a) * 100) + '% vs ' + round(luminance(b) * 100) + '%); they will merge in a black-and-white print. Use a legend label or a different pair.' }) + } + } + } + + const smallest = smallestText(nodes) + if (smallest && smallest.size < MIN_PRINT_TEXT) { + warnings.push({ kind: 'print', text: labelOf(smallest.node) + ' is set at ' + round(smallest.size) + 'pt, below the ' + MIN_PRINT_TEXT + 'pt a printed figure can carry.' }) + } + for (const entry of nodes) { + if (entry.node.overflow) { + warnings.push({ kind: 'fit', text: labelOf(entry.node) + ' has a line wider than its pane; at ' + round(entry.node.w) + 'pt wide the pane needs ' + round(entry.node.measured.widest + entry.node.code.pad * 2) + 'pt. Widen the column or break the line.' }) + } + } + if (!spec.figure.caption) { + warnings.push({ kind: 'caption', text: 'The spec carries no `figure.caption`. A paper figure is read with its caption; add one so the export can print it.' }) + } + if (usedTones.size > 7) { + warnings.push({ kind: 'palette', text: usedTones.size + ' distinct tones is more than a reader can hold; five or six roles with a legend is the useful ceiling.' }) + } + + const svg = emitDocument({ spec, palette, root, anchors, width: spec.figure.width, height }) + const status = diagnostics.length > 0 ? 'error' : 'ok' + return { + ok: status === 'ok', + status, + rung: status === 'ok' ? 'f2-paper' : 'f0-spec', + svg, + width: spec.figure.width, + height, + diagnostics, + warnings: warnings.slice(0, 8), + stats: { + blocks: nodes.length, + links: spec.links.length, + tones: [...usedTones], + smallestText: smallest ? round(smallest.size) : null, + preset: spec.figure.preset, + caption: spec.figure.caption, + }, + ms: Date.now() - started, + } +} + +/** A readable name for a node in a diagnostic. */ +function labelOf(node) { + if (node.id) return '"' + node.id + '"' + if (node.block && typeof node.block.title === 'string') return 'the "' + node.block.title.slice(0, 24) + '" panel' + return 'a ' + String(node.type) +} + +/** Whether `ancestor` sits above `descendant` in the tree. */ +function isAncestor(nodes, ancestor, descendant) { + const parents = new Map() + for (const entry of nodes) parents.set(entry.node, entry.parent) + let cursor = parents.get(descendant) + let depth = 0 + while (cursor && depth < 40) { + if (cursor === ancestor) return true + cursor = parents.get(cursor) + depth += 1 + } + return false +} + +/** The smallest text size anywhere in the tree. */ +function smallestText(nodes) { + let found = null + const consider = (node, size) => { + if (typeof size !== 'number' || size <= 0) return + if (!found || size < found.size) found = { node, size } + } + for (const entry of nodes) { + const node = entry.node + if (node.textStyle) consider(node, node.textStyle.size) + if (node.list) consider(node, node.list.size) + if (node.code) consider(node, node.code.size) + if (node.node) { + consider(node, node.node.size) + if ((node.subLines ?? []).length > 0) consider(node, node.node.subSize) + } + if (node.panel) consider(node, node.panel.titleSize) + if (node.badge) consider(node, node.badge.size) + if (node.matrix) consider(node, node.matrix.labelSize) + if (node.legend) consider(node, node.legend.size) + if (node.strip) consider(node, node.strip.labelSize) + } + return found +} + +/** Resolve one `id`, `id.side` or `id.segment.side` reference, or null. */ +function resolveReference(anchors, reference) { + const text = String(reference ?? '') + if (anchors.has(text)) return true + const parts = text.split('.') + if (parts.length === 1) return null + const side = parts[parts.length - 1] + const id = parts.slice(0, -1).join('.') + const found = anchors.get(id) + if (!found) return null + return found[side] ? true : null +} + +/** The document every consumer sees: the tab, the export, the corpus check. */ +function emitDocument({ spec, palette, root, anchors, width, height }) { + const title = spec.figure.title ?? spec.figure.caption ?? 'Figure' + const description = + spec.figure.description ?? + (spec.figure.caption ? spec.figure.caption : 'A figure composed of ' + countText(spec.blocks) + ' blocks.') + const slug = slugify(title) + const links = spec.links.map((link) => emitLink(link, palette, anchors)).join('') + return ( + '\n' + + '\n' + + '' + + escapeXml(title) + + '\n' + + '' + + escapeXml(description) + + '\n' + + '\n' + + emitNode(root, palette) + + '\n' + + links + + '\n\n' + ) +} + +/** A count of the top-level blocks, for the default description. */ +function countText(blocks) { + return String(blocks.length) +} + +/** A safe element id prefix. */ +function slugify(value) { + const slug = String(value ?? '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 40) + return slug.length > 0 ? slug : 'figure' +} + +export { PRESETS, num } diff --git a/packages/dsh-diagrams/lib/figure/layout.js b/packages/dsh-diagrams/lib/figure/layout.js new file mode 100644 index 0000000..49bee06 --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/layout.js @@ -0,0 +1,626 @@ +/** + * dsh-diagrams — the figure layout engine. + * + * One pure function: a normalized spec goes in, an absolutely-positioned tree + * comes out. Nothing here draws; nothing here touches the disk or the clock. That + * is what makes a figure reproducible: the same spec produces the same tree, and + * the same tree produces byte-identical SVG. + * + * Two passes, the way a typesetter works: + * + * 1. **measure** — how tall is this block at this width? Text is measured from + * the Core-14 tables (`./metrics.js`), never from a browser. + * 2. **build** — place it, recursively, and hand back a node carrying absolute + * coordinates, its resolved lines and its anchors. + * + * `rows` and `columns` are the whole layout model. A figure that cannot be + * expressed with them is usually a figure that should be two figures; `stack` + * exists for the small schematic inside a panel (an inset), which is the one case + * where absolute placement is the honest answer. + */ +import { baseline, lineHeight, textWidth } from './metrics.js' +import { SPACE, TYPE } from './constants.js' + +/** A number, or the fallback. */ +function num(value, fallback) { + return typeof value === 'number' && Number.isFinite(value) ? value : fallback +} + +/** Parse inline markup into runs: `**bold**`, `` `mono` ``, `{tone:text}`. */ +export function parseRuns(input) { + const text = String(input ?? '') + const out = [] + let buffer = '' + let bold = false + let mono = false + let tone = null + const flush = () => { + if (buffer.length > 0) out.push({ text: buffer, bold, mono, tone }) + buffer = '' + } + let index = 0 + while (index < text.length) { + if (text.startsWith('**', index)) { + flush() + bold = !bold + index += 2 + continue + } + if (text[index] === '`') { + flush() + mono = !mono + index += 1 + continue + } + if (text[index] === '{') { + const close = text.indexOf('}', index) + const head = close === -1 ? '' : text.slice(index + 1, close) + const colon = head.indexOf(':') + if (close !== -1 && colon > 0 && /^[a-z][a-z0-9-]*$/.test(head.slice(0, colon))) { + flush() + const previous = tone + tone = head.slice(0, colon) + buffer = head.slice(colon + 1) + flush() + tone = previous + index = close + 1 + continue + } + } + buffer += text[index] + index += 1 + } + flush() + return out +} + +/** Split one string into styled atoms, one per character. */ +function atomsOf(text, style) { + const atoms = [] + for (const run of parseRuns(text)) { + const bold = run.bold === true || style.bold === true + const mono = run.mono === true || style.mono === true + const tone = run.tone ?? style.tone ?? 'ink' + for (const character of run.text) atoms.push({ character, bold, mono, tone }) + } + return atoms +} + +/** Greedy wrap at `maxWidth`, breaking on spaces and hard-breaking a long word. */ +export function layoutText(text, maxWidth, style) { + const size = num(style.size, TYPE.body) + const atoms = atomsOf(text, style) + if (atoms.length === 0) return [] + const widthOf = (atom) => textWidth(atom.character, { size, bold: atom.bold, mono: atom.mono }) + const lines = [] + let start = 0 + while (start < atoms.length) { + let width = 0 + let lastSpace = -1 + let end = start + while (end < atoms.length) { + const next = width + widthOf(atoms[end]) + if (next > maxWidth && end > start) break + width = next + if (atoms[end].character === ' ') lastSpace = end + end += 1 + } + let breakAt = end + if (end < atoms.length && lastSpace > start) breakAt = lastSpace + let lineEnd = breakAt + while (lineEnd > start && atoms[lineEnd - 1].character === ' ') lineEnd -= 1 + lines.push(mergeRuns(atoms.slice(start, lineEnd), size)) + start = breakAt + while (start < atoms.length && atoms[start].character === ' ') start += 1 + } + return lines +} + +/** Merge styled characters back into runs, with the line's width. */ +function mergeRuns(atoms, size) { + const runs = [] + let width = 0 + for (const atom of atoms) { + width += textWidth(atom.character, { size, bold: atom.bold, mono: atom.mono }) + const last = runs[runs.length - 1] + if (last && last.bold === atom.bold && last.mono === atom.mono && last.tone === atom.tone) last.text += atom.character + else runs.push({ text: atom.character, bold: atom.bold, mono: atom.mono, tone: atom.tone }) + } + return { runs, width } +} + +/** The width of one unwrapped markup string. */ +export function measureText(text, style) { + const size = num(style.size, TYPE.body) + let width = 0 + for (const atom of atomsOf(text, style)) width += textWidth(atom.character, { size, bold: atom.bold, mono: atom.mono }) + return width +} + +// --------------------------------------------------------------------------- +// Blocks +// --------------------------------------------------------------------------- + +/** + * How tall one block is at one width, plus whatever `build` needs to place it. + * Pure: calling it twice returns the same answer. + */ +export function measureBlock(block, ctx, width) { + const type = String(block.type ?? '') + switch (type) { + case 'rows': { + const gap = num(block.gap, ctx.gap) + let height = 0 + const children = block.children ?? [] + children.forEach((child, index) => { + height += measureBlock(child, ctx, width).h + if (index < children.length - 1) height += gap + }) + return { h: height } + } + case 'columns': { + const gap = num(block.gap, ctx.gap) + const entries = columnEntries(block) + const available = width - gap * Math.max(0, entries.length - 1) + const total = entries.reduce((sum, entry) => sum + entry.weight, 0) || 1 + let height = 0 + for (const entry of entries) height = Math.max(height, measureBlock(entry.block, ctx, (available * entry.weight) / total).h) + return { h: height } + } + case 'panel': + return measurePanel(block, ctx, width) + case 'text': { + const style = textStyle(block, ctx) + const lines = layoutText(block.text ?? '', width, style) + return { h: lines.length * lineHeight(style.size), lines, style } + } + case 'list': + return measureList(block, ctx, width) + case 'code': + return measureCode(block, ctx, width) + case 'strip': + return measureStrip(block, ctx, width) + case 'node': + return measureNode(block, ctx, width) + case 'matrix': + return measureMatrix(block, ctx, width) + case 'badge': { + const size = num(block.size, ctx.base - 0.5) + const style = { size, tone: block.tone ?? 'ink' } + const width2 = measureText(block.text ?? '', style) + num(block.pad, 4) * 2 + return { w: width2, h: size + num(block.pad, 3) * 2, size, style } + } + case 'legend': + return measureLegend(block, ctx, width) + case 'rule': + return { h: 0 } + case 'spacer': + return { h: num(block.h, 6) } + case 'stack': + return { h: num(block.h, 40) } + default: + return { h: 0 } + } +} + +/** One text block's resolved style. */ +function textStyle(block, ctx) { + return { + size: num(block.size, ctx.base), + bold: block.weight === 'bold', + mono: block.mono === true, + tone: block.tone ?? 'ink', + } +} + +/** `columns` children: a block, or `{ block, weight }`. */ +function columnEntries(block) { + return (block.children ?? []).map((child) => { + if (child && typeof child === 'object' && child.block) return { block: child.block, weight: num(child.weight, 1) } + return { block: child, weight: 1 } + }) +} + +function measurePanel(block, ctx, width) { + const pad = num(block.pad, SPACE.pad) + const gap = num(block.gap, ctx.gap * 0.75) + const inner = Math.max(8, width - pad * 2) + const titleSize = num(block.titleSize, TYPE.panel) + // A panel title wraps like any other text: a paper figure names its panes in a + // sentence ("tensors info with tensor_count values"), not in three words. + const titleLines = block.title ? layoutText(block.title, inner, { size: titleSize, bold: true, tone: block.tone ?? 'ink' }) : [] + const titleHeight = titleLines.length > 0 ? titleLines.length * lineHeight(titleSize) + 2 : 0 + const children = block.children ?? [] + let contentHeight = 0 + children.forEach((child, index) => { + contentHeight += measureBlock(child, ctx, inner).h + if (index < children.length - 1) contentHeight += gap + }) + return { h: pad * 2 + titleHeight + contentHeight, pad, gap, inner, titleHeight, titleSize, titleLines, contentHeight } +} + +/** One list item's marker. */ +function listMarker(block, index) { + if (block.bullet === true) return '•' + const marker = block.marker + if (typeof marker === 'string') return marker.replace('{n}', String(index + 1)) + return String(index + 1) + '.' +} + +function measureList(block, ctx, width) { + const size = num(block.size, ctx.base) + const items = block.items ?? [] + const markers = items.map((_, index) => listMarker(block, index)) + const markerWidth = Math.max(0, ...markers.map((marker) => measureText(marker, { size, tone: 'muted' }))) + num(block.markerGap, 3) + const rows = [] + const itemGap = num(block.itemGap, 1.5) + let height = 0 + items.forEach((item, index) => { + const text = typeof item === 'string' ? item : String(item?.text ?? '') + const tone = typeof item === 'object' && item?.tone ? item.tone : block.tone + const lines = layoutText(text, Math.max(8, width - markerWidth), { size, tone: tone ?? undefined, bold: block.bold === true }) + rows.push({ marker: markers[index], lines }) + height += lines.length * lineHeight(size) + if (index < items.length - 1) height += itemGap + }) + return { h: height, rows, size, markerWidth } +} + +function measureCode(block, ctx, width) { + const size = num(block.size, TYPE.code) + const pad = num(block.pad, SPACE.pad) + const lines = (block.lines ?? []).map((line) => mergeRuns(atomsOf(line, { size, mono: true, tone: 'ink' }), size)) + const widest = Math.max(0, ...lines.map((line) => line.width)) + const height = pad * 2 + lines.length * lineHeight(size) + (block.title ? lineHeight(size) + 1 : 0) + return { h: height, lines, size, pad, widest, radius: num(block.radius, SPACE.radius) } +} + +function measureStrip(block, ctx, width) { + const segments = (block.segments ?? []).map((segment, index) => ({ + id: String(segment.id ?? 'seg' + index), + weight: Math.max(0.0001, num(segment.weight, num(segment.units, num(segment.bytes, 1)))), + label: segment.label ?? '', + tone: segment.tone ?? 'ink', + text: segment.text ?? null, + segment, + })) + const total = segments.reduce((sum, segment) => sum + segment.weight, 0) || 1 + let x = 0 + for (const segment of segments) { + segment.w = (width * segment.weight) / total + segment.x = x + x += segment.w + } + const bar = num(block.bar, 8) + const labelSize = num(block.labelSize, TYPE.small) + const labels = block.labels !== 'none' + const labelHeight = labels ? lineHeight(labelSize) + 3 : 0 + // A tail is the boxed monospace run at the right end of a byte layout (the last + // bytes of a file, the offset a pointer lands on). It is drawn OVER the last + // segment, and it is addressable, so a callout can point at the bytes itself. + const tail = block.tail && block.tail.text ? { text: String(block.tail.text), tone: block.tail.tone ?? 'ink' } : null + const tailWidth = tail ? measureText(tail.text, { size: 5.6, mono: true }) + 3 : 0 + return { h: labelHeight + bar, segments, bar, labelSize, labels, labelHeight, tail, tailWidth } +} + +function measureNode(block, ctx, width) { + const pad = num(block.pad, SPACE.pad) + const size = num(block.size, ctx.base) + const subSize = num(block.subSize, size - 1) + const w = num(block.w, width) + const titleLines = block.title ? layoutText(block.title, w - pad * 2, { size, tone: block.tone ?? 'ink', bold: true }) : [] + const subLines = block.sub ? layoutText(block.sub, w - pad * 2, { size: subSize, tone: 'muted' }) : [] + const height = num( + block.h, + pad * 2 + titleLines.length * lineHeight(size) + subLines.length * lineHeight(subSize) + (subLines.length > 0 ? 1 : 0), + ) + return { w, h: height, pad, size, subSize, titleLines, subLines } +} + +function measureMatrix(block, ctx, width) { + const rows = Math.max(0, num(block.rows, 0)) + const cols = Math.max(0, num(block.cols, 0)) + const cell = num(block.cell, 9) + const gap = num(block.gap, 1) + const labelSize = num(block.labelSize, TYPE.tiny) + const rowLabels = block.rowLabels ?? [] + const colLabels = block.colLabels ?? [] + const labelWidth = rowLabels.length > 0 ? Math.max(...rowLabels.map((label) => measureText(label, { size: labelSize }))) + 4 : 0 + const headerHeight = colLabels.length > 0 ? lineHeight(labelSize) + 2 : 0 + const gridWidth = cols * cell + Math.max(0, cols - 1) * gap + return { + w: labelWidth + gridWidth, + h: headerHeight + rows * cell + Math.max(0, rows - 1) * gap, + rows, + cols, + cell, + gap, + labelSize, + labelWidth, + headerHeight, + } +} + +function measureLegend(block, ctx, width) { + const size = num(block.size, TYPE.small) + const items = (block.items ?? []).map((item) => ({ + tone: item.tone ?? 'ink', + label: String(item.label ?? ''), + width: 11 + measureText(item.label ?? '', { size }), + })) + const gap = num(block.gap, 10) + let lineWidth = 0 + let lines = 1 + for (const item of items) { + if (lineWidth > 0 && lineWidth + gap + item.width > width) { + lines += 1 + lineWidth = 0 + } + lineWidth += (lineWidth > 0 ? gap : 0) + item.width + } + return { h: lines * lineHeight(size), items, size, gap } +} + +// --------------------------------------------------------------------------- +// Build +// --------------------------------------------------------------------------- + +/** Build one block at an absolute position. */ +export function buildBlock(block, ctx, x, y, width) { + const type = String(block.type ?? '') + const id = typeof block.id === 'string' && block.id.length > 0 ? block.id : null + const measured = measureBlock(block, ctx, width) + const node = { type, id, block, x, y, w: width, h: measured.h, children: [], solid: false, measured } + switch (type) { + case 'rows': + return buildRows(block, ctx, node, width) + case 'columns': + return buildColumns(block, ctx, node, width) + case 'panel': + return buildPanel(block, ctx, node, width, measured) + case 'text': + node.lines = measured.lines + node.textStyle = { size: measured.style.size, align: block.align ?? 'left', tone: measured.style.tone } + node.solid = false + return node + case 'list': + return buildList(block, ctx, node, measured) + case 'code': + return buildCode(block, ctx, node, measured) + case 'strip': + return buildStrip(block, ctx, node, measured) + case 'node': + return buildNode(block, ctx, node, measured) + case 'matrix': + return buildMatrix(block, ctx, node, width, measured) + case 'badge': + return buildBadge(block, ctx, node, measured) + case 'legend': + return buildLegend(block, ctx, node, measured) + case 'rule': + node.solid = false + return node + case 'spacer': + return node + case 'stack': + return buildStack(block, ctx, node, width, measured) + default: + return node + } +} + +function buildRows(block, ctx, node, width) { + const gap = num(block.gap, ctx.gap) + let cursor = node.y + for (const child of block.children ?? []) { + const built = buildBlock(child, ctx, node.x, cursor, width) + node.children.push(built) + cursor += built.h + gap + } + return node +} + +function buildColumns(block, ctx, node, width) { + const gap = num(block.gap, ctx.gap) + const entries = columnEntries(block) + const available = width - gap * Math.max(0, entries.length - 1) + const total = entries.reduce((sum, entry) => sum + entry.weight, 0) || 1 + let cursor = node.x + entries.forEach((entry, index) => { + const childWidth = index === entries.length - 1 ? node.x + width - cursor : (available * entry.weight) / total + const built = buildBlock(entry.block, ctx, cursor, node.y, Math.max(4, childWidth)) + node.children.push(built) + cursor += childWidth + gap + }) + return node +} + +function buildPanel(block, ctx, node, width, measured) { + const { pad, gap, inner, titleHeight, titleSize } = measured + const tone = block.tone ?? 'ink' + node.solid = true + node.panel = { + tone, + dash: block.dash === true, + // `fill: true` means "the tone's own tint", which is what a code pane inside a + // section wants; the default is the page so a plain panel is a frame only. + fill: block.fill === true ? ctx.palette.tone(tone).fill : block.fill === false ? null : (typeof block.fill === 'string' ? block.fill : 'paper'), + radius: num(block.radius, SPACE.radius), + title: block.title ?? null, + titleSize, + titleLines: measured.titleLines, + titleAlign: block.titleAlign ?? 'left', + } + let cursor = node.y + pad + titleHeight + for (const child of block.children ?? []) { + const built = buildBlock(child, ctx, node.x + pad, cursor, inner) + node.children.push(built) + cursor += built.h + gap + } + return node +} + +function buildList(block, ctx, node, measured) { + const { rows, size, markerWidth } = measured + node.list = { size, markerWidth, gap: num(block.itemGap, 1.5), tone: block.tone ?? 'ink', align: block.align ?? 'left' } + let cursor = node.y + for (const row of rows) { + node.children.push({ type: 'list-item', x: node.x, y: cursor, w: node.w, h: row.lines.length * lineHeight(size), children: [], marker: row.marker, lines: row.lines, solid: false }) + cursor += row.lines.length * lineHeight(size) + node.list.gap + } + return node +} + +function buildCode(block, ctx, node, measured) { + node.code = { + size: measured.size, + pad: measured.pad, + radius: measured.radius, + tone: block.tone ?? 'soft', + dash: block.dash === true, + frame: block.frame !== false, + fill: block.fill, + } + node.lines = measured.lines + node.solid = block.frame !== false + node.overflow = measured.widest > node.w - measured.pad * 2 + 0.5 + return node +} + +function buildStrip(block, ctx, node, measured) { + node.solid = true + node.strip = { + bar: measured.bar, + labelSize: measured.labelSize, + labels: measured.labels, + labelHeight: measured.labelHeight, + tail: measured.tail, + tone: block.tone ?? 'ink', + radius: num(block.radius, 1), + } + node.segments = measured.segments.map((segment) => ({ ...segment, x: node.x + segment.x })) + node.tailBox = measured.tail + ? { x: node.x + node.w - measured.tailWidth, y: node.y + measured.labelHeight - 1.6, w: measured.tailWidth, h: measured.bar + 3.2 } + : null + return node +} + +function buildNode(block, ctx, node, measured) { + node.solid = true + node.shape = block.shape ?? 'rect' + node.node = { tone: block.tone ?? 'ink', dash: block.dash === true, radius: num(block.radius, SPACE.radius), size: measured.size, subSize: measured.subSize, pad: measured.pad } + node.titleLines = measured.titleLines + node.subLines = measured.subLines + if (block.w !== undefined) node.w = measured.w + return node +} + +function buildMatrix(block, ctx, node, width, measured) { + node.solid = false + node.matrix = { + ...measured, + cells: block.cells ?? [], + rowLabels: block.rowLabels ?? [], + colLabels: block.colLabels ?? [], + rotateRowLabels: block.rotateRowLabels === true, + tone: block.tone ?? 'ink', + radius: num(block.radius, 1), + x: node.x + measured.labelWidth, + y: node.y + measured.headerHeight, + } + return node +} + +function buildBadge(block, ctx, node, measured) { + const align = block.align ?? 'left' + const w = Math.min(node.w, measured.w) + const line = layoutText(block.text ?? '', Math.max(4, w - num(block.pad, 4) * 2), { size: measured.size, tone: block.tone ?? 'ink' })[0] ?? null + node.badge = { + tone: block.tone ?? 'ink', + size: measured.size, + pad: num(block.pad, 4), + fill: block.fill, + text: block.text ?? '', + line, + x: align === 'center' ? node.x + (node.w - w) / 2 : align === 'right' ? node.x + node.w - w : node.x, + w, + } + return node +} + +function buildLegend(block, ctx, node, measured) { + node.legend = { ...measured, tone: block.tone ?? 'ink' } + return node +} + +function buildStack(block, ctx, node, width, measured) { + node.solid = false + for (const child of block.children ?? []) { + const childWidth = num(child.w, width) + const built = buildBlock(child.block, ctx, node.x + num(child.x, 0), node.y + num(child.y, 0), childWidth) + if (child.h !== undefined) built.h = num(child.h, built.h) + node.children.push(built) + } + return node +} + +// --------------------------------------------------------------------------- +// Anchors +// --------------------------------------------------------------------------- + +/** The four side midpoints and the centre of one box. */ +function anchorsOf(box) { + return { + center: { x: box.x + box.w / 2, y: box.y + box.h / 2 }, + top: { x: box.x + box.w / 2, y: box.y }, + bottom: { x: box.x + box.w / 2, y: box.y + box.h }, + left: { x: box.x, y: box.y + box.h / 2 }, + right: { x: box.x + box.w, y: box.y + box.h / 2 }, + } +} + +/** + * Walk the built tree and collect what a linker can point at. + * + * A strip registers each SEGMENT as its own address (`strip.meta`), which is what + * lets a callout point at one field of a byte layout instead of at the whole bar. + */ +export function collectAnchors(root) { + const anchors = new Map() + const solids = [] + const walk = (node) => { + // A shrink-to-content block (a badge) is anchored to what it DREW, not to the + // column it was given, or a leader would start in empty space beside the pill. + const box = node.badge ? { x: node.badge.x, y: node.y, w: node.badge.w, h: node.h } : node + if (node.id) anchors.set(node.id, anchorsOf(box)) + if (Array.isArray(node.segments)) { + for (const segment of node.segments) { + if (!node.id) break + anchors.set(node.id + '.' + segment.id, anchorsOf({ x: segment.x, y: node.y + node.strip.labelHeight, w: segment.w, h: node.strip.bar })) + } + if (node.id && node.tailBox) anchors.set(node.id + '.tail', anchorsOf(node.tailBox)) + } + if (node.solid) solids.push(node) + for (const child of node.children ?? []) walk(child) + } + walk(root) + return { anchors, solids } +} + +/** Resolve `"id"`, `"id.side"` or `"id.segment.side"` to a point and a normal. */ +export function resolveAnchor(anchors, reference, fallbackSide = 'bottom') { + const text = String(reference ?? '') + const parts = text.split('.') + if (parts.length === 1) { + const found = anchors.get(parts[0]) + return found ? { point: found.center, side: 'center', box: null } : null + } + const side = parts[parts.length - 1] + const id = parts.slice(0, -1).join('.') + const found = anchors.get(id) + if (!found) return null + const point = found[side] ?? found[fallbackSide] + return point ? { point, side, box: found } : null +} + +export { num } diff --git a/packages/dsh-diagrams/lib/figure/metrics.js b/packages/dsh-diagrams/lib/figure/metrics.js new file mode 100644 index 0000000..bf89187 --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/metrics.js @@ -0,0 +1,77 @@ +/** + * dsh-diagrams — figure text metrics. + * + * A figure compiler has to know how wide a string is BEFORE anything is drawn, + * because every box, column and leader is sized from it. Measuring in a browser + * would make the layout depend on the machine (font substitution, platform + * rasteriser), so the widths here are the PDF Core-14 advance widths in + * thousandths of an em — the same numbers Helvetica, Arial and Liberation Sans + * agree on, which is why a document set in `Helvetica, Arial, sans-serif` lays + * out identically on Windows, macOS and Linux. + * + * width(px) = sum(advance[ch]) / 1000 * size + * + * Courier is a monospaced face at exactly 600/1000 per glyph, so its table is a + * constant. A character outside ASCII falls back to a letter-width estimate; the + * figure grammar is ASCII-first because a paper figure is. + */ + +/** Helvetica advance widths, ASCII 32..126 (thousandths of an em). */ +const SANS = [ + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, + 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, + 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, +] + +/** Helvetica-Bold advance widths, ASCII 32..126. */ +const SANS_BOLD = [ + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, + 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, + 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, +] + +/** The fallback for a character no table covers (CJK, arrows, emoji). */ +const FALLBACK = { sans: 611, bold: 611, mono: 600 } + +/** One character's advance in thousandths of an em. */ +function advance(code, bold, mono) { + if (mono) return 600 + if (code >= 32 && code <= 126) { + const table = bold ? SANS_BOLD : SANS + return table[code - 32] + } + return bold ? FALLBACK.bold : FALLBACK.sans +} + +/** + * The width of one string in the same units as `size`. + * + * @param text - the string (may contain no markup; callers pass a run's plain text). + * @param options - `{ size, bold, mono }`. + * @returns the advance width. + */ +export function textWidth(text, { size = 7, bold = false, mono = false } = {}) { + const value = String(text ?? '') + let total = 0 + for (let index = 0; index < value.length; index += 1) total += advance(value.charCodeAt(index), bold, mono) + return (total / 1000) * size +} + +/** The line box for one font size: the em box plus leading, as text editors mean it. */ +export function lineHeight(size = 7) { + return size * 1.32 +} + +/** The baseline offset from the top of a line box. */ +export function baseline(size = 7) { + return size * 0.98 +} + +/** A width that is safely wider than any glyph in the face, for a code cell. */ +export function monoCell(size = 7) { + return size * 0.6 +} + +export const METRIC_FONTS = { sans: SANS.length, bold: SANS_BOLD.length } diff --git a/packages/dsh-diagrams/lib/figure/spec.js b/packages/dsh-diagrams/lib/figure/spec.js new file mode 100644 index 0000000..26867f1 --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/spec.js @@ -0,0 +1,156 @@ +/** + * dsh-diagrams — the figure spec: parse, normalize, validate. + * + * A spec is JSON, so the model can patch one field with `diagram_patch` without + * re-emitting the figure. This module is the only place that knows the shape, and + * it answers with the offending BLOCK PATH (`blocks[2].children[0].type`) rather + * than a position in a string — the model has to be able to act on the error. + */ +import { PRIMITIVES, PRESETS, SPACE, THEME_NAMES, TYPE, LINK_KINDS } from './constants.js' + +/** A number, or the fallback. */ +function num(value, fallback) { + return typeof value === 'number' && Number.isFinite(value) ? value : fallback +} + +/** One validation problem, shaped like every other diagnostic in this plugin. */ +function problem(kind, text) { + return { kind, text } +} + +/** + * Parse and normalize one figure spec. + * + * @param source - the JSON text a diagram stores. + * @returns `{ spec, problems }`. `problems` non-empty means nothing was built. + */ +export function parseFigure(source) { + const text = String(source ?? '').trim() + if (text.length === 0) return { spec: null, problems: [problem('source', 'The figure spec is empty. A spec is a JSON object with a `blocks` array.')] } + let raw + try { + raw = JSON.parse(text) + } catch (error) { + return { spec: null, problems: [problem('json', 'The spec is not valid JSON: ' + String(error.message) + '. A figure is `{ "figure": {...}, "blocks": [...] }`.')] } + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return { spec: null, problems: [problem('json', 'The spec must be a JSON object, not an array or a bare value.')] } + } + const problems = [] + const figureRaw = raw.figure && typeof raw.figure === 'object' ? raw.figure : {} + const presetName = typeof figureRaw.preset === 'string' ? figureRaw.preset : null + let width = num(figureRaw.width, 0) + if (width <= 0) { + if (presetName && PRESETS[presetName] && PRESETS[presetName].width > 0) width = PRESETS[presetName].width + else width = PRESETS.web.width + } + if (presetName && !PRESETS[presetName]) problems.push(problem('figure', 'Unknown preset "' + presetName + '". Use one of: ' + Object.keys(PRESETS).join(', ') + '.')) + if (width < 120 || width > 2000) problems.push(problem('figure', 'Width ' + width + 'pt is outside 120..2000. Use a preset, or a width a page can carry.')) + const themeName = typeof figureRaw.theme === 'string' ? figureRaw.theme : 'paper' + if (!THEME_NAMES.includes(themeName)) problems.push(problem('figure', 'Unknown theme "' + themeName + '". Use: ' + THEME_NAMES.join(', ') + '.')) + const figure = { + preset: presetName ?? 'free', + width, + height: num(figureRaw.height, null), + theme: themeName, + margin: Math.max(0, num(figureRaw.margin, SPACE.margin)), + gap: Math.max(0, num(figureRaw.gap, SPACE.gap)), + size: Math.max(4, num(figureRaw.size, TYPE.body)), + caption: typeof figureRaw.caption === 'string' ? figureRaw.caption : null, + title: typeof figureRaw.title === 'string' ? figureRaw.title : null, + description: typeof figureRaw.description === 'string' ? figureRaw.description : null, + background: typeof figureRaw.background === 'string' ? figureRaw.background : null, + } + const blocks = Array.isArray(raw.blocks) ? raw.blocks : null + if (!blocks) problems.push(problem('figure', 'The spec has no `blocks` array; that is the figure.')) + else if (blocks.length === 0) problems.push(problem('figure', '`blocks` is empty, so the figure would draw nothing.')) + const ids = new Set() + if (blocks) validateBlocks(blocks, 'blocks', problems, ids) + const links = Array.isArray(raw.links) ? raw.links : [] + validateLinks(links, ids, problems) + if (problems.length > 0) return { spec: null, problems } + return { spec: { figure, blocks, links }, problems: [] } +} + +/** Walk every block, checking its type and the fields that type requires. */ +function validateBlocks(blocks, path, problems, ids) { + blocks.forEach((block, index) => { + const here = path + '[' + index + ']' + if (!block || typeof block !== 'object' || Array.isArray(block)) { + problems.push(problem('block', here + ' is not an object.')) + return + } + const type = String(block.type ?? '') + if (!PRIMITIVES.includes(type)) { + problems.push(problem('block', here + '.type "' + type + '" is not a primitive. Use one of: ' + PRIMITIVES.join(', ') + '.')) + return + } + if (typeof block.id === 'string' && block.id.length > 0) { + if (ids.has(block.id)) problems.push(problem('block', here + '.id "' + block.id + '" is used twice; every id must be unique.')) + ids.add(block.id) + } + if (type === 'rows' || type === 'columns' || type === 'panel' || type === 'stack') { + if (!Array.isArray(block.children)) problems.push(problem('block', here + ' (' + type + ') needs a `children` array.')) + else if (type === 'stack') { + block.children.forEach((child, childIndex) => { + if (!child || typeof child !== 'object' || !child.block) problems.push(problem('block', here + '.children[' + childIndex + '] must be `{ block, x, y }`; a stack places its children explicitly.')) + else validateBlocks([child.block], here + '.children[' + childIndex + '].block', problems, ids) + }) + } else if (type === 'columns') { + block.children.forEach((child, childIndex) => { + if (child && typeof child === 'object' && child.block) validateBlocks([child.block], here + '.children[' + childIndex + '].block', problems, ids) + else validateBlocks([child], here + '.children[' + childIndex + ']', problems, ids) + }) + } else validateBlocks(block.children, here + '.children', problems, ids) + } + if (type === 'text' && typeof block.text !== 'string') problems.push(problem('block', here + ' (text) needs a `text` string.')) + if (type === 'code' && !Array.isArray(block.lines)) problems.push(problem('block', here + ' (code) needs a `lines` array.')) + if (type === 'strip') { + if (!Array.isArray(block.segments) || block.segments.length === 0) problems.push(problem('block', here + ' (strip) needs a non-empty `segments` array.')) + else { + block.segments.forEach((segment, segmentIndex) => { + if (!segment || typeof segment !== 'object') problems.push(problem('block', here + '.segments[' + segmentIndex + '] is not an object.')) + else if (segment.id && ids.has(String(block.id) + '.' + String(segment.id))) problems.push(problem('block', here + '.segments[' + segmentIndex + '].id is used twice.')) + else if (segment.id) ids.add(String(block.id) + '.' + String(segment.id)) + }) + } + } + if (type === 'matrix') { + if (!num(block.rows, 0) || !num(block.cols, 0)) problems.push(problem('block', here + ' (matrix) needs `rows` and `cols` greater than zero.')) + } + if (type === 'list' && !Array.isArray(block.items)) problems.push(problem('block', here + ' (list) needs an `items` array.')) + }) +} + +/** Every connector must point at something that exists. */ +function validateLinks(links, ids, problems) { + links.forEach((link, index) => { + const here = 'links[' + index + ']' + if (!link || typeof link !== 'object') { + problems.push(problem('link', here + ' is not an object.')) + return + } + const kind = String(link.kind ?? 'leader') + if (!LINK_KINDS.includes(kind)) { + problems.push(problem('link', here + '.kind "' + kind + '" is not one of: ' + LINK_KINDS.join(', ') + '.')) + return + } + for (const field of ['from', 'to']) { + const reference = String(link[field] ?? '') + if (reference.length === 0) { + problems.push(problem('link', here + ' needs `' + field + '`. Point at a block id, optionally with a side: "callout.top".')) + continue + } + const base = reference.split('.')[0] + if (!ids.has(base) && !hasSegment(ids, base)) { + problems.push(problem('link', here + '.' + field + ' "' + reference + '" names no block id in this figure.')) + } + } + }) +} + +/** Whether `base` is a strip that registered `base.segment` addresses. */ +function hasSegment(ids, base) { + for (const id of ids) if (id.startsWith(base + '.')) return true + return false +} diff --git a/packages/dsh-diagrams/lib/figure/theme.js b/packages/dsh-diagrams/lib/figure/theme.js new file mode 100644 index 0000000..d581f3b --- /dev/null +++ b/packages/dsh-diagrams/lib/figure/theme.js @@ -0,0 +1,132 @@ +/** + * dsh-diagrams — figure themes. + * + * A tone is a ROLE, never a colour the spec spells out: `ink`, `meta`, `tensor`, + * `link`. The palette resolves each role to four values (text, stroke, fill, bar) + * so one spec can be set on paper, on the kit's editorial page, or on a dark + * screen without a single edit — and so the greyscale check can ask "will these + * two roles still be distinguishable when the paper is printed in black and + * white?", which is the question a colour-only palette cannot answer. + */ +import { THEME_NAMES } from './constants.js' + +/** Relative luminance (WCAG), 0..1. */ +export function luminance(hex) { + const value = String(hex ?? '').replace('#', '') + if (value.length !== 6) return 0 + const channel = (index) => { + const raw = parseInt(value.slice(index, index + 2), 16) / 255 + return raw <= 0.03928 ? raw / 12.92 : ((raw + 0.055) / 1.055) ** 2.4 + } + return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4) +} + +/** WCAG contrast ratio between two colours. */ +export function contrast(a, b) { + const first = luminance(a) + const second = luminance(b) + const high = Math.max(first, second) + const low = Math.min(first, second) + return (high + 0.05) / (low + 0.05) +} + +/** The tones every theme carries. A role absent from a theme falls back to `ink`. */ +const ROLES = ['ink', 'muted', 'soft', 'meta', 'tensor', 'link', 'accent', 'warn', 'teal', 'yellow'] + +/** + * The palettes. + * + * `paper` is the print theme: white ground, near-black ink, and five accents + * whose luminance is deliberately spread so the figure survives a black-and-white + * print. `editorial` is the kit's own paper, for a figure that lives on a page + * rather than in a journal. `dark` is for a screen only; a figure is not exported + * in it. + */ +const THEMES = { + paper: { + paper: '#ffffff', + ink: '#111418', + muted: '#5b6672', + rule: '#c9ced6', + font: "Helvetica, Arial, 'Liberation Sans', sans-serif", + mono: "'Courier New', Courier, 'Liberation Mono', monospace", + tones: { + ink: { text: '#111418', stroke: '#111418', fill: '#ffffff', bar: '#1b1f24' }, + muted: { text: '#5b6672', stroke: '#9aa4b1', fill: '#f4f6f8', bar: '#8a94a1' }, + soft: { text: '#3c4652', stroke: '#d7dce2', fill: '#f5f7f9', bar: '#e3e7ec' }, + meta: { text: '#2b6b45', stroke: '#57a877', fill: '#eaf6ef', bar: '#57b26a' }, + tensor: { text: '#6540b8', stroke: '#9b7ad6', fill: '#f3eefc', bar: '#8b5cf6' }, + link: { text: '#1f4e9c', stroke: '#4f86cf', fill: '#eaf1fb', bar: '#1e40af' }, + accent: { text: '#9a4a08', stroke: '#d08a3e', fill: '#fdf3e4', bar: '#c2762a' }, + warn: { text: '#a52a20', stroke: '#d2685f', fill: '#fceceb', bar: '#c0392b' }, + teal: { text: '#0d6b63', stroke: '#4fa9a0', fill: '#e6f6f4', bar: '#14b8a6' }, + yellow: { text: '#7a5a06', stroke: '#cbaa3a', fill: '#fcf7dd', bar: '#d9b62c' }, + }, + }, + editorial: { + paper: '#f5f5f5', + ink: '#2d3142', + muted: '#4f5d75', + rule: '#cfd3d9', + font: "'Geist', Helvetica, Arial, sans-serif", + mono: "'Geist Mono', 'Courier New', monospace", + tones: { + ink: { text: '#2d3142', stroke: '#2d3142', fill: '#ffffff', bar: '#2d3142' }, + muted: { text: '#4f5d75', stroke: '#9aa4b1', fill: '#eceef1', bar: '#8a94a1' }, + soft: { text: '#3c4652', stroke: '#d7dce2', fill: '#ffffff', bar: '#e3e7ec' }, + meta: { text: '#2b6b45', stroke: '#57a877', fill: '#eaf6ef', bar: '#57b26a' }, + tensor: { text: '#6540b8', stroke: '#9b7ad6', fill: '#f3eefc', bar: '#8b5cf6' }, + link: { text: '#1f4e9c', stroke: '#4f86cf', fill: '#eaf1fb', bar: '#1e40af' }, + accent: { text: '#bf4520', stroke: '#d4693f', fill: '#fbeee1', bar: '#bf4520' }, + warn: { text: '#a52a20', stroke: '#d2685f', fill: '#fceceb', bar: '#c0392b' }, + teal: { text: '#0d6b63', stroke: '#4fa9a0', fill: '#e6f6f4', bar: '#14b8a6' }, + yellow: { text: '#7a5a06', stroke: '#cbaa3a', fill: '#fcf7dd', bar: '#d9b62c' }, + }, + }, + dark: { + paper: '#15181d', + ink: '#f2f4f7', + muted: '#a7b0bd', + rule: '#333a45', + font: "Helvetica, Arial, 'Liberation Sans', sans-serif", + mono: "'Courier New', Courier, monospace", + tones: { + ink: { text: '#f2f4f7', stroke: '#8b95a3', fill: '#1d222a', bar: '#c9d1db' }, + muted: { text: '#a7b0bd', stroke: '#6c7786', fill: '#1d222a', bar: '#6c7786' }, + soft: { text: '#cdd4dd', stroke: '#3a4452', fill: '#1d222a', bar: '#3a4452' }, + meta: { text: '#6ee7a8', stroke: '#2f7d55', fill: '#132a20', bar: '#4ade80' }, + tensor: { text: '#c4b5fd', stroke: '#6d4bb5', fill: '#1e1a33', bar: '#a78bfa' }, + link: { text: '#93c5fd', stroke: '#2c5c9e', fill: '#111c2e', bar: '#60a5fa' }, + accent: { text: '#fdba74', stroke: '#9a5a1f', fill: '#2a1c0e', bar: '#fb923c' }, + warn: { text: '#fca5a5', stroke: '#9b2c2c', fill: '#2a1414', bar: '#f87171' }, + teal: { text: '#5eead4', stroke: '#1b6b62', fill: '#0e2422', bar: '#2dd4bf' }, + yellow: { text: '#fde68a', stroke: '#8a6a12', fill: '#241d0a', bar: '#facc15' }, + }, + }, +} + +/** + * Resolve one theme. + * + * @param name - `paper` | `editorial` | `dark`. + * @returns `{ name, paper, ink, muted, rule, font, mono, tones, tone(name) }`. + */ +export function paletteFor(name) { + const key = THEME_NAMES.includes(String(name)) ? String(name) : 'paper' + const base = THEMES[key] + return { + name: key, + ...base, + /** One role, or `ink` when a spec names a role the theme does not carry. */ + tone(role) { + return base.tones[String(role ?? 'ink')] ?? base.tones.ink + }, + /** Every role the theme defines, in a stable order. */ + roles: ROLES.filter((role) => base.tones[role]), + } +} + +export { ROLES } + + + diff --git a/packages/dsh-diagrams/lib/index.js b/packages/dsh-diagrams/lib/index.js index cf4ff68..00dfe59 100644 --- a/packages/dsh-diagrams/lib/index.js +++ b/packages/dsh-diagrams/lib/index.js @@ -63,6 +63,7 @@ import { typeById, } from './design-kit.js' import { checkHtml, extractSvg } from './html-check.js' +import { buildFigure } from './figure/index.js' export const name = 'dsh-diagrams' @@ -100,6 +101,8 @@ const RASTER_DPI = 200 * compile instead of serving a picture the current code would not produce. */ const TIKZ_RENDERER_VERSION = '1' +/** Bump when the figure layout or emitter changes enough to invalidate cached SVGs. */ +const FIGURE_RENDERER_VERSION = '1' /** Files each kind may export. */ const EXPORT_FORMATS = { mermaid: ['mmd', 'md', 'svg', 'png'], @@ -109,6 +112,9 @@ const EXPORT_FORMATS = { // pack does not ship, and reporting a format this host cannot produce would be // the plugin lying about its own capability. html: ['html', 'svg'], + // A figure is compiled on the host to one SVG; the panel rasterises that same + // document to PNG in the browser, which is where a rasteriser exists. + figure: ['json', 'svg', 'png'], } /** * The two places a diagram can live. @@ -515,6 +521,57 @@ async function checkAndRecord(deps, scopeKey, entry, { signal, force = false } = return { ...verdict, ms: verdict.ms ?? Date.now() - started, artifact: stored ? stored.artifact : null } } + if (entry.kind === 'figure') { + // A figure is COMPILED, not parsed: the spec is measured, placed and routed + // here on the host, so the artifact the tab draws is the same document the + // export carries and the same one the corpus check compares. A spec whose + // boxes overlap is an ERROR the model can act on, not a warning. + const built = buildFigure(entry.source) + const diagnostics = built.diagnostics ?? [] + const warnings = built.warnings ?? [] + let artifact = null + if (built.svg) { + const key = deps.cache.keyFor({ + kind: 'figure', + source: entry.source, + engine: 'figure', + renderer: 'svg', + version: FIGURE_RENDERER_VERSION, + }) + const meta = deps.cache.write(key, { + svg: built.svg, + meta: { + kind: 'figure', + rung: built.rung, + width: built.width, + height: built.height, + ms: built.ms, + diagnostics: diagnostics.slice(0, 12), + stats: built.stats, + }, + }) + artifact = { hash: key, formats: meta.formats ?? [], width: built.width, height: built.height, engine: 'figure', at: meta.at } + } + const stored = store.recordVerdict(scopeKey, entry.id, { + status: built.status, + diagramType: 'figure', + diagnostics, + warnings, + artifact, + }) + return { + ok: built.ok, + status: built.status, + diagramType: 'figure', + diagnostics, + warnings, + artifact: stored ? stored.artifact : artifact, + rung: built.rung, + stats: built.stats, + ms: built.ms ?? Date.now() - started, + } + } + if (entry.kind === 'html') { // A Design document is a whole page this plugin then FRAMES, so its verdict // is not "does it parse" but "is it safe to serve and is it a picture". @@ -736,6 +793,7 @@ const SKILL_FILES = [ { name: 'mermaid-diagrams', file: '../skills/mermaid-diagrams/SKILL.md' }, { name: 'tikz-diagrams', file: '../skills/tikz-diagrams/SKILL.md' }, { name: 'diagram-design', file: '../skills/diagram-design/SKILL.md' }, + { name: 'paper-figures', file: '../skills/paper-figures/SKILL.md' }, ] /** @@ -830,7 +888,7 @@ export function registerSkills(ctx, log) { /** JSON Schema for a diagram id. */ const ID_SCHEMA = { type: 'string', description: 'The diagram id (lowercase letters, digits and dashes).' } /** JSON Schema for a diagram kind. */ -const KIND_SCHEMA = { type: 'string', enum: [...KINDS], description: 'mermaid | tikz | html' } +const KIND_SCHEMA = { type: 'string', enum: [...KINDS], description: 'mermaid | tikz | html | figure' } /** * JSON Schema for the scope a diagram lives in - the argument that decides * whether a diagram belongs to one chat or to every chat. @@ -893,6 +951,8 @@ function writeDescription(engines) { '', 'kind "html": the source is a complete self-contained HTML+SVG document - the shape of the vendored Diagram Design kit, whose 204 examples you can read and insert with `diagram_kit`. It is checked BEFORE it is stored, in two tiers: a SAFETY finding is a refusal (a remote asset, an executable attribute, a forbidden element, or any script that is not the kit\u2019s own motion controller), and a CRAFT finding is only a warning (no accessible SVG, a node budget blown, no dark-theme tokens, no reduced-motion fallback). Start from the kit rather than from a blank page: `diagram_kit({action:"catalog"})`, then `{action:"reference", ref:"style-guide"}`, then either `{action:"insert"}` an example or write your own with `{action:"example"}` in hand.', '', + 'kind "figure": the source is a JSON SPEC, not a drawing - the host compiles it. `{ "figure": { "preset": "ieee-double", "theme": "paper" }, "blocks": [...], "links": [...] }`. Blocks: rows, columns, panel, text, list, code, strip, node, matrix, badge, legend, rule, spacer, stack. Inline markup: **bold**, `mono`, {tone:text}. A link (leader, arrow, brace) points at a block id and a side: "callout.top", or "strip.meta.bottom" for one segment of a strip. Sizes are POINTS, so a 7pt label is font-size 7. The compile returns GEOMETRY diagnostics (overlap, bounds, a link that names nothing) and warnings (print size, greyscale separation, a code line wider than its pane) - fix until status is ok. Read the `paper-figures` skill first; the reference corpus is `reference/figures/` in this package.', + '', 'Pass `id` to replace an existing diagram (check it with diagram_read first); omit it to create a new one, whose id is derived from the title.', 'Pass `scope: "library"` when the diagram is worth keeping beyond this chat: the library is ONE store every conversation reads, its address (`dsh-resource://diagram/library/`) names no conversation, and any later chat can read it by id alone. Keep scratch diagrams in the conversation (the default) so the shared library stays worth reading.', 'Always read the returned `status` and `diagnostics`, and fix the diagram until the status is "ok". A diagram the user cannot see is a failed call.', @@ -1026,6 +1086,17 @@ export function buildTools(deps) { (verdict.counts && verdict.counts.svgs ? ' (' + verdict.counts.svgs + ' accessible SVG, ' + verdict.counts.elements + ' elements)' : '') + ', and it is drawing in its own tab.', ) + } else if (entry.kind === 'figure') { + const size = verdict.artifact ? verdict.artifact.width + '×' + verdict.artifact.height + 'pt' : 'the page' + lines.push( + 'Compiled to a ' + + size + + ' vector figure passing the geometry contract (' + + (verdict.rung ?? 'f2-paper') + + ')' + + (verdict.stats && verdict.stats.smallestText ? '; smallest type ' + verdict.stats.smallestText + 'pt' : '') + + '. It is drawing in its own tab and can be exported as SVG, PNG or the spec JSON.', + ) } else if (verdict.artifact) { lines.push( 'Compiled with ' + @@ -1076,7 +1147,7 @@ export function buildTools(deps) { required: ['kind', 'source'], properties: { kind: KIND_SCHEMA, - source: { type: 'string', description: 'The complete diagram source: Mermaid text, TikZ/LaTeX, or a self-contained HTML+SVG document for kind "html".' }, + source: { type: 'string', description: 'The complete diagram source: Mermaid text, TikZ/LaTeX, a self-contained HTML+SVG document for kind "html", or the JSON figure spec for kind "figure".' }, id: ID_SCHEMA, scope: SCOPE_SCHEMA, title: { type: 'string', description: 'A short human title; the tab chip and the diagram list show it.' }, @@ -1899,6 +1970,7 @@ function exportName(entry, format) { * browser is what rendered it. */ function exportBytes(deps, entry, format, clientData, options = {}) { + if (format === 'json' && entry.kind === 'figure') return Buffer.from(entry.source + '\n', 'utf8') if (format === 'mmd' || format === 'tex') return Buffer.from(entry.source + '\n', 'utf8') // An `html` document exports as the file a person can open in a browser: the // SAME composition the panel frames, minus the viewer bridge it has no parent @@ -1925,7 +1997,7 @@ function exportBytes(deps, entry, format, clientData, options = {}) { return Buffer.from('\n' + styled + '\n', 'utf8') } if (format === 'md') { - const language = entry.kind === 'mermaid' ? 'mermaid' : entry.kind === 'html' ? 'html' : 'latex' + const language = entry.kind === 'mermaid' ? 'mermaid' : entry.kind === 'html' ? 'html' : entry.kind === 'figure' ? 'json' : 'latex' return Buffer.from('# ' + entry.title + '\n\n```' + language + '\n' + entry.source + '\n```\n', 'utf8') } if (typeof clientData === 'string' && clientData.length > 0) { @@ -1934,7 +2006,7 @@ function exportBytes(deps, entry, format, clientData, options = {}) { if (bytes.byteLength > MAX_ARTIFACT_BYTES) throw httpError(413, 'TOO_LARGE', 'That image is too large to export.') return bytes } - if (entry.kind === 'tikz' && entry.artifact) { + if ((entry.kind === 'tikz' || entry.kind === 'figure') && entry.artifact) { const file = format === 'svg' ? 'doc.svg' : format === 'png' ? 'doc.png' : format === 'pdf' ? 'doc.pdf' : null if (file) return deps.cache.read(entry.artifact.hash, file) } @@ -2404,3 +2476,6 @@ export function apply(ctx) { function message(err) { return err && err.message ? String(err.message) : String(err) } + + + diff --git a/packages/dsh-diagrams/lib/store.js b/packages/dsh-diagrams/lib/store.js index abc48ee..b2b5f18 100644 --- a/packages/dsh-diagrams/lib/store.js +++ b/packages/dsh-diagrams/lib/store.js @@ -80,7 +80,7 @@ export const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,47}$/ * Design kit's 204 examples are written in - validated against the safety and * accessibility contract in `./html-check.js` and drawn in a sandboxed frame. */ -export const KINDS = ['mermaid', 'tikz', 'html'] +export const KINDS = ['mermaid', 'tikz', 'html', 'figure'] /** * What the BROWSER reported about THIS revision, in one objective word. @@ -514,7 +514,7 @@ export class DiagramStore { if (!entry) return undefined entry.render = { revision: Number.isFinite(report.revision) ? report.revision : entry.revision, - kind: report.kind === 'tikz' ? 'tikz' : 'mermaid', + kind: report.kind === 'tikz' ? 'tikz' : report.kind === 'figure' ? 'figure' : 'mermaid', ok: report.ok === true, phase: typeof report.phase === 'string' ? report.phase.slice(0, 24) : null, error: typeof report.error === 'string' && report.error.length > 0 ? report.error.slice(0, 2000) : null, @@ -551,7 +551,7 @@ export class DiagramStore { /** A readable default title when the model gave none. */ function defaultTitle(kind, id) { - const label = kind === 'tikz' ? 'TikZ diagram' : kind === 'html' ? 'Diagram Design' : 'Mermaid diagram' + const label = kind === 'tikz' ? 'TikZ diagram' : kind === 'html' ? 'Diagram Design' : kind === 'figure' ? 'Figure' : 'Mermaid diagram' return label + ' ' + id } @@ -614,3 +614,4 @@ export function listSessionFiles(root) { .filter((name) => name.endsWith('.json')) .map((name) => path.join(dir, name)) } + diff --git a/packages/dsh-diagrams/package.json b/packages/dsh-diagrams/package.json index fbe26e2..7d0d635 100644 --- a/packages/dsh-diagrams/package.json +++ b/packages/dsh-diagrams/package.json @@ -1,7 +1,7 @@ { "name": "dsh-diagrams", "version": "0.1.0-alpha.9", - "description": "Diagrams: Mermaid, TikZ and the Diagram Design kit in one bundle - seven `diagram_*` tools whose writes are validated on the host before they are stored, a conversation store plus a shared library, a tab per diagram with an export menu, an index page that also browses the kit's 71 example keys, and browser render reports.", + "description": "Diagrams: Mermaid, TikZ, the Diagram Design kit and a FIGURE COMPILER in one bundle - seven diagram_* tools whose writes are validated on the host before they are stored, a conversation store plus a shared library, a tab per diagram with an export menu, an index page that also browses the kit, browser render reports, and a reference corpus of two published paper figures rebuilt in the figure grammar.", "type": "module", "main": "lib/index.js", "exports": { @@ -13,10 +13,11 @@ "lib", "skills", "checks", + "reference", "cordis.patch.yml" ], "scripts": { - "check": "node checks/check-diagrams-kit.mjs", + "check": "node checks/check-diagrams-kit.mjs && node checks/check-figure-corpus.mjs", "vendor:check": "node vendor/design/build.mjs --check" }, "dsh": { diff --git a/packages/dsh-diagrams/reference/README.md b/packages/dsh-diagrams/reference/README.md new file mode 100644 index 0000000..ba2798a --- /dev/null +++ b/packages/dsh-diagrams/reference/README.md @@ -0,0 +1,51 @@ +# Reference figures + +Two things this folder is, and one it is not. + +It **is** a benchmark: for each figure, the published original (`targets/`), a +written decomposition of why it works (`anatomy.md`), the same figure rebuilt in +this package's grammar (`spec.json`), the built vector (`out/figure.svg`), and the +checks that decide whether a rebuild is faithful (`rubric.json`). `check-figure-corpus.mjs` +rebuilds every spec and fails on drift, non-determinism or a geometry violation. + +It **is** the definition of done for `kind: "figure"`. A change to the layout +engine is measured against these two figures, not against an opinion. + +It is **not** the diagram database. `docs/diagrams/` is gitignored because it holds +the user's own diagrams; this folder holds reviewed, attributed evaluation +material, which is the same distinction the vendored Diagram Design kit already +lives under (`lib/vendor/design/NOTICE.md`). + +## Layout + +``` +reference/ + README.md this file + THIRD-PARTY.md where every target came from, its licence, its sha256 + targets/ the published originals, as committed + figures// + SOURCE.md provenance and what the figure is evidence OF + anatomy.md the decomposition: grid, layers, primitives, palette + rubric.json the acceptance checks, one line each + spec.json OUR rebuild, in the figure grammar + out/figure.svg the build; committed so a diff shows the change + out/metrics.json width, height and the compiler's own stats +``` + +## The three tiers + +1. **Ours** — `anatomy.md`, `spec.json`, `rubric.json`, `out/` — always committed. +2. **Redistributable target** — committed under `targets/`, with its licence in + `THIRD-PARTY.md`. +3. **Not redistributable** — only the URL, the identifier and the sha256 are + committed; the file itself is dropped into `targets/` by whoever has the right + to it. The corpus check skips the visual tier and says so. + +## Running it + +```sh +node packages/dsh-diagrams/checks/check-figure-corpus.mjs +``` + +It reports one line per figure and exits non-zero on a failing check. Without +`targets/` it still runs every structural check. diff --git a/packages/dsh-diagrams/reference/THIRD-PARTY.md b/packages/dsh-diagrams/reference/THIRD-PARTY.md new file mode 100644 index 0000000..3e350ca --- /dev/null +++ b/packages/dsh-diagrams/reference/THIRD-PARTY.md @@ -0,0 +1,27 @@ +# Third-party targets + +The files under `targets/` are **evaluation targets**: published figures this +package's figure compiler is measured against. They are not content this +repository distributes, they are not relicensed by it, and the copyright stays +with their authors. + +| file | work | rights | sha256 | +|---|---|---|---| +| `gguf-file-layout.jpg` | GGUF file-format explainer figure (2000×1456, JPEG). Source not yet pinned to a canonical URL — see `figures/gguf-file-layout/SOURCE.md`. | Unconfirmed. Treated as **tier 2**: committed as an evaluation target only, and removed on request. | `31d4b9632f665e23a2d6e4be4556aab3fe1be3b54c420553e08a6e53ebdae9b9` | +| `neo-motivation.png` | Figure 2 of *From Pixels to Words — Towards Native Vision-Language Primitives at Scale*, Diao et al., arXiv:2510.14979v2, ICLR 2026 (2640×1218, PNG). | © 2025 the authors. arXiv **non-exclusive distribution** licence (arXiv:2510.14979 “view license”). This repository claims no right to redistribute it; it is committed as an evaluation target and removed on request. | `f13d5ba00550ed0b9c5df551590e9971463220e143ed9e93860ccf433c80d4f9` | + +## Removal + +Deleting a file from `targets/` breaks nothing: the corpus check drops to its +structural tier and reports which figure lost its target. + +```sh +git rm packages/dsh-diagrams/reference/targets/neo-motivation.png +``` + +## What is ours + +`anatomy.md`, `spec.json`, `rubric.json` and `out/` are this repository's own work +and carry the package licence (AGPL-3.0-only). The rebuild is a *description* of +the target's structure, written from it — not a trace, a copy of its vector data, +or a crop of its pixels. diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/SOURCE.md b/packages/dsh-diagrams/reference/figures/gguf-file-layout/SOURCE.md new file mode 100644 index 0000000..bd3e48b --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/SOURCE.md @@ -0,0 +1,39 @@ +# GGUF file layout — provenance + +| | | +|---|---| +| target | `../../targets/gguf-file-layout.jpg`, 2000×1456, JPEG, 226 062 bytes | +| sha256 | `31d4b9632f665e23a2d6e4be4556aab3fe1be3b54c420553e08a6e53ebdae9b9` | +| origin | not yet pinned. The figure is the explainer diagram that circulates with the GGUF documentation; the exact page and author have to be established before this entry claims a canonical source. | +| rights | unconfirmed → tier 2 (evaluation target, removed on request). See `../../THIRD-PARTY.md`. | + +## What the figure is evidence of + +That a **byte layout** can be read in one pass: a single bar carries the file's +fields in order, each field is named directly under the bytes it occupies, and the +two variable-length sections open into the records they contain. Nothing is +decorative; every colour is a section the reader will meet again in the code +panes. + +## What our rebuild changes, and why + +| target | rebuild | +|---|---| +| four annotation cards staggered left, joined by long dashed leaders | four cards stacked under the bar, joined by a brace and by section colour | +| section colours reused on the `tensor_count` / `metadata_kv_count` cards | kept: the count of a section is that section's colour | +| no legend | a three-item legend, because a paper figure prints in black and white | +| the `offset` callout points at the bit string through a routed elbow | kept, with the tail box addressable as `strip.tail` | +| caption carried outside the image | carried in `figure.caption`, so the export can print it | + +The rebuild deliberately does **not** copy the target's leader topology: at this +resolution the target's four drop lines are ambiguous about which header field +each card names. The rebuild follows the format's byte order, which is the thing a +reader has to be able to trust. + +## Rebuilding it + +```sh +node .scratch/render-figure.mjs packages/dsh-diagrams/reference/figures/gguf-file-layout +``` + +writes `out/figure.svg` plus a 4× preview; the committed artifact is the SVG. diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/anatomy.md b/packages/dsh-diagrams/reference/figures/gguf-file-layout/anatomy.md new file mode 100644 index 0000000..6446f5e --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/anatomy.md @@ -0,0 +1,68 @@ +# Anatomy — GGUF file layout + +## The claim it makes + +A GGUF file is four little-endian header fields (24 bytes), then the metadata +key-value pairs, then the tensor descriptors, then the tensor data to the end of +the file. A descriptor's `offset` field is an absolute pointer into that last +section. + +## Reading order + +1. **What the file is** — `model.gguf`, top left. +2. **The bytes** — one bar, left to right, in file order. +3. **What each header field means** — the four cards below the bar. +4. **What the variable-length sections contain** — the two code panes. +5. **Where a pointer lands** — the boxed bit string at the right end, and the + `offset` callout above it. + +## Layers + +| layer | what is drawn | +|---|---| +| identity | a pill: `File name **model.gguf**` | +| the bar | one `strip`, seven segments, labels above, a `tail` box at the right | +| the header | four `panel` cards, one per field | +| the sections | two `panel`s with a tinted fill, each holding a `code` pane | +| the join | one `brace` under the header, two `leader`s from the section segments, one from `offset` | + +## Primitives, and what each one is doing + +- **`strip`** — the only primitive where WIDTH IS DATA. Segments carry a `weight` + (layout share) and, separately, `bytes` (the fact the label states). The two are + not the same number: a 4-byte field and the 400 MB tensor section cannot be + drawn to scale on one line, and pretending otherwise is the commonest lie in + byte-layout diagrams. +- **`braces`** — a group over segments is cheap: `from: "strip.magic"`, `to: "strip.kv_count"`. +- **`leader`** — anchored to a SEGMENT (`strip.tensors.bottom`), not to the bar. + That address is what makes "this pane is that section" sayable. +- **`code`** — monospace at 6.2 pt, keys tinted by the section they belong to. +- **`panel` + `fill: true`** — the section tint, so the pane and its segment share + one colour role and the leader only has to confirm it. + +## Palette roles + +| role | used for | +|---|---| +| `ink` | the header fields and the tensor data — the parts that are fixed or opaque | +| `meta` | the metadata section, its card, its pane | +| `tensor` | the tensor-descriptor section, its card, its pane | +| `muted` | the `offset` callout, the legend labels | +| `warn` | the token strings inside the metadata example (they are what the reader is being shown) | + +## Typography + +| role | size | +|---|---| +| file name | 9 pt | +| card titles | 8 pt bold | +| field values, code | 6.2 pt | +| bar labels, legend | 6.2 pt | +| the bit string | 5.6 pt | + +Smallest type 5.6 pt, above the 5.5 pt floor the compiler warns under. + +## What a rebuild must keep (see `rubric.json`) + +The field ORDER, the four sizes, the pointer tail, the section tint reused on the +panes, and the caption. Not the leader routing. diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/figure.svg b/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/figure.svg new file mode 100644 index 0000000..4ba4481 --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/figure.svg @@ -0,0 +1,8 @@ + + +The GGUF file format, field by field +Byte-layout diagram of a GGUF file. A bar shows four header fields of 4, 4, 8 and 8 bytes, then the metadata section, the tensor descriptors, and the tensor data to the end of the file. Four cards name the header fields, and two code panes show a metadata record and a tensor descriptor. + +File name model.ggufoffset4 bytes4 bytes8 bytes8 bytesmetadatatensorstensor data101101000110011110GGUF magic number0x47 0x47 0x55 0x46G G U FGGUF versioncurrently = 3tensor_count = number of tensorsUINT64metadata_kv_count = number of metadatakey-value pairsUINT64metadata sectiontensor descriptorstensor datatensors info with tensor_count values// n-th tensorname: GGUF string, // ex: blk.0.ffn_gate.weightn_dimensions: UINT32, // ex: 2dimensions: UINT64[], // ex: [ 4096, 32000 ]type: UINT32, // ex: 10 (GGML_TYPE_Q2_K)offset: UINT64 // ex: 43024384// (n+1)-th tensor…metadata with metadata_kv_count key-value pairs// example metadatageneral.architecture: 'llama',general.name: 'LLaMA v2',llama.context_length: 4096,…,general.file_type: 10,tokenizer.ggml.model: 'llama',tokenizer.ggml.tokens: [ '<unk>', '<s>', '</s>', '<0x00>', '<0x01>', '<0x02>', '<0x03>', '<0x04>', '<0x05>', '<0x06>',],… +header · 24 bytes + diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/metrics.json b/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/metrics.json new file mode 100644 index 0000000..5aec4e0 --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/out/metrics.json @@ -0,0 +1,17 @@ +{ + "width": 516, + "height": 337, + "stats": { + "blocks": 24, + "links": 4, + "tones": [ + "soft", + "ink", + "meta", + "tensor" + ], + "smallestText": 6.2, + "preset": "ieee-double", + "caption": "A GGUF file is a header of four little-endian fields (24 bytes), followed by the metadata key-value pairs, the tensor descriptors, and the tensor data. A tensor descriptor's offset field points into the tensor data at the end of the file." + } +} diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/rubric.json b/packages/dsh-diagrams/reference/figures/gguf-file-layout/rubric.json new file mode 100644 index 0000000..06dd232 --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/rubric.json @@ -0,0 +1,93 @@ +{ + "version": 1, + "figure": "gguf-file-layout", + "claim": "A GGUF file is a 24-byte header, then the metadata key-value pairs, the tensor descriptors and the tensor data; a descriptor's offset points into the tensor data.", + "target": "targets/gguf-file-layout.jpg", + "checks": [ + { + "id": "field-order", + "kind": "structure", + "text": "The bar carries the four header fields in file order, then the metadata section, then the tensor descriptors, then the tensor data.", + "blocks": [ + "strip" + ] + }, + { + "id": "field-sizes", + "kind": "structure", + "text": "Each header field states its width in bytes: 4, 4, 8, 8.", + "blocks": [ + "strip" + ], + "labels": [ + "4 bytes", + "8 bytes" + ] + }, + { + "id": "field-names", + "kind": "structure", + "text": "Four cards name the four fields, in the same order the bar draws them.", + "blocks": [ + "card-magic", + "card-version", + "card-tensor-count", + "card-kv-count" + ] + }, + { + "id": "sections-tinted", + "kind": "colour", + "text": "The metadata and tensor sections carry a colour role, and the pane that shows their records carries the same one.", + "blocks": [ + "pane-metadata", + "pane-tensors" + ] + }, + { + "id": "pointer-tail", + "kind": "structure", + "text": "The last bytes of the file are drawn as a boxed bit string, and the offset callout points at that box.", + "blocks": [ + "strip", + "offset" + ] + }, + { + "id": "records", + "kind": "content", + "text": "The two panes show the fields a reader will meet in code: name, n_dimensions, dimensions, type, offset; and a typed metadata entry.", + "labels": [ + "n_dimensions", + "dimensions", + "offset", + "general.architecture" + ], + "blocks": [ + "pane-tensors", + "pane-metadata" + ] + }, + { + "id": "legend", + "kind": "colour", + "text": "Every colour role the bar uses is named in a legend, so the figure still reads in black and white.", + "labels": [ + "metadata section", + "tensor descriptors", + "tensor data" + ] + }, + { + "id": "caption", + "kind": "print", + "text": "The spec carries a caption that states the claim, and the description names the figure for a reader who cannot see it." + }, + { + "id": "type-floor", + "kind": "print", + "text": "No type is below 5.5 pt at the printed width." + } + ], + "targetSha256": "31d4b9632f665e23a2d6e4be4556aab3fe1be3b54c420553e08a6e53ebdae9b9" +} diff --git a/packages/dsh-diagrams/reference/figures/gguf-file-layout/spec.json b/packages/dsh-diagrams/reference/figures/gguf-file-layout/spec.json new file mode 100644 index 0000000..4bf4aa1 --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/gguf-file-layout/spec.json @@ -0,0 +1,183 @@ +{ + "figure": { + "preset": "ieee-double", + "theme": "paper", + "margin": 8, + "gap": 7, + "size": 7, + "title": "The GGUF file format, field by field", + "caption": "A GGUF file is a header of four little-endian fields (24 bytes), followed by the metadata key-value pairs, the tensor descriptors, and the tensor data. A tensor descriptor's offset field points into the tensor data at the end of the file.", + "description": "Byte-layout diagram of a GGUF file. A bar shows four header fields of 4, 4, 8 and 8 bytes, then the metadata section, the tensor descriptors, and the tensor data to the end of the file. Four cards name the header fields, and two code panes show a metadata record and a tensor descriptor." + }, + "blocks": [ + { + "type": "columns", + "gap": 8, + "children": [ + { "weight": 3, "block": { "type": "badge", "size": 9, "pad": 5, "tone": "soft", "text": "{muted:File name} **model.gguf**" } }, + { "weight": 1, "block": { "type": "badge", "id": "offset", "size": 7, "pad": 4, "align": "right", "tone": "soft", "text": "offset" } } + ] + }, + { "type": "spacer", "h": 8 }, + { + "type": "strip", + "id": "strip", + "segments": [ + { "id": "magic", "weight": 1, "label": "4 bytes", "tone": "ink" }, + { "id": "version", "weight": 1, "label": "4 bytes", "tone": "ink" }, + { "id": "tensor_count", "weight": 1, "label": "8 bytes", "tone": "ink" }, + { "id": "kv_count", "weight": 1, "label": "8 bytes", "tone": "ink" }, + { "id": "meta", "weight": 1.3, "label": "metadata", "tone": "meta" }, + { "id": "tensors", "weight": 1.3, "label": "tensors", "tone": "tensor" }, + { "id": "rest", "weight": 5.4, "label": "tensor data", "tone": "ink" } + ], + "tail": { "text": "101101000110011110" } + }, + { "type": "spacer", "h": 16 }, + { + "type": "columns", + "gap": 10, + "children": [ + { + "weight": 38, + "block": { + "type": "rows", + "gap": 6, + "children": [ + { + "type": "panel", + "id": "card-magic", + "title": "GGUF magic number", + "dash": true, + "radius": 6, + "pad": 5, + "children": [ + { "type": "text", "mono": true, "text": "0x47 0x47 0x55 0x46", "align": "center" }, + { "type": "text", "mono": true, "text": "G G U F", "align": "center" } + ] + }, + { + "type": "panel", + "id": "card-version", + "title": "GGUF version", + "dash": true, + "radius": 6, + "pad": 5, + "children": [{ "type": "text", "mono": true, "tone": "meta", "text": "currently = 3" }] + }, + { + "type": "panel", + "id": "card-tensor-count", + "title": "tensor_count = number of tensors", + "tone": "tensor", + "dash": true, + "radius": 6, + "pad": 5, + "children": [{ "type": "text", "mono": true, "tone": "tensor", "text": "UINT64", "align": "right" }] + }, + { + "type": "panel", + "id": "card-kv-count", + "title": "metadata_kv_count = number of metadata key-value pairs", + "tone": "meta", + "dash": true, + "radius": 6, + "pad": 5, + "children": [{ "type": "text", "mono": true, "tone": "meta", "text": "UINT64", "align": "right" }] + }, + { + "type": "legend", + "size": 6.2, + "gap": 8, + "items": [ + { "tone": "meta", "label": "metadata section" }, + { "tone": "tensor", "label": "tensor descriptors" }, + { "tone": "ink", "label": "tensor data" } + ] + } + ] + } + }, + { + "weight": 62, + "block": { + "type": "rows", + "gap": 6, + "children": [ + { + "type": "panel", + "id": "pane-tensors", + "tone": "tensor", + "fill": true, + "dash": true, + "radius": 8, + "pad": 5, + "title": "tensors info with **tensor_count** values", + "children": [ + { + "type": "code", + "id": "code-tensors", + "size": 6.2, + "frame": false, + "pad": 4, + "lines": [ + "{muted:// n-th tensor}", + "{tensor:name:} GGUF string, // ex: blk.0.ffn_gate.weight", + "{tensor:n_dimensions:} UINT32, // ex: 2", + "{tensor:dimensions:} UINT64[], // ex: [ 4096, 32000 ]", + "{tensor:type:} UINT32, // ex: 10 (GGML_TYPE_Q2_K)", + "{tensor:offset:} UINT64 // ex: 43024384", + "{muted:// (n+1)-th tensor}", + "…" + ] + } + ] + }, + { + "type": "panel", + "id": "pane-metadata", + "tone": "meta", + "fill": true, + "dash": true, + "radius": 8, + "pad": 5, + "title": "metadata with **metadata_kv_count** key-value pairs", + "children": [ + { + "type": "code", + "id": "code-metadata", + "size": 6.2, + "frame": false, + "pad": 4, + "lines": [ + "{muted:// example metadata}", + "{meta:general.architecture:} 'llama',", + "{meta:general.name:} 'LLaMA v2',", + "{meta:llama.context_length:} 4096,", + "…,", + "{meta:general.file_type:} 10,", + "{meta:tokenizer.ggml.model:} 'llama',", + "{meta:tokenizer.ggml.tokens:} [", + " '{warn:}', '{warn:}', '{warn:}', '{warn:<0x00>}', '{warn:<0x01>}',", + " '{warn:<0x02>}', '{warn:<0x03>}', '{warn:<0x04>}', '{warn:<0x05>}', '{warn:<0x06>}',", + "],", + "…" + ] + } + ] + } + ] + } + } + ] + } + ], + "links": [ + { "kind": "brace", "from": "strip.magic", "to": "strip.kv_count", "tone": "muted", "label": "header · 24 bytes" }, + { "kind": "leader", "from": "pane-tensors.top", "to": "strip.tensors.bottom", "tone": "tensor", "dash": true, "dot": true }, + { "kind": "leader", "from": "pane-metadata.top", "to": "strip.meta.bottom", "tone": "meta", "dash": true, "dot": true }, + { "kind": "leader", "from": "offset.bottom", "to": "strip.tail.top", "tone": "muted", "dash": true, "out": 2 } + ] +} + + diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/SOURCE.md b/packages/dsh-diagrams/reference/figures/neo-motivation/SOURCE.md new file mode 100644 index 0000000..5b03d4a --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/SOURCE.md @@ -0,0 +1,38 @@ +# NEO motivation plate — provenance + +| | | +|---|---| +| target | `../../targets/neo-motivation.png`, 2640×1218, PNG, 687 528 bytes | +| sha256 | `f13d5ba00550ed0b9c5df551590e9971463220e143ed9e93860ccf433c80d4f9` | +| origin | Figure 2 of *From Pixels to Words — Towards Native Vision-Language Primitives at Scale*, Haiwen Diao et al., [arXiv:2510.14979v2](https://arxiv.org/abs/2510.14979), accepted at ICLR 2026. | +| rights | © the authors; arXiv non-exclusive distribution licence → tier 2 (evaluation target, removed on request). See `../../THIRD-PARTY.md`. | + +## What the figure is evidence of + +That a **motivation plate** can carry an argument, not just a taxonomy: three +"X vs. Y" cards on the left that each name a choice a modular system forces; one +column of primitives in the middle that replaces all three at once; and a right +half that shows the modular stack, the load step, and two consequences. The +reader is meant to finish it convinced, not informed. + +It is also the hardest density case in the corpus: ~200 text runs, three levels +of grouping, five numbered claims and two small schematics inside one 7 in figure. + +## What our rebuild changes, and why + +| target | rebuild | +|---|---| +| five numbered claims on the right | two (`1. Seamlessly Load LLMs`, `2. Multi-Modal Mixed Attention`), because the other three are consequences of the same primitives and need a different figure | +| two 9-row property lists beside two encoder boxes | kept, same rows and same highlighted values | +| inline schematics for tokenize/embed and tile/encode | replaced by a one-line "one grid cell per token, or one continuous patch vector" under each comparison | +| photographs and token swatches inside the cards | dropped: they are content, not structure, and the corpus rebuilds structure | +| five colour roles | four: the modular stack (orange), the vision path (green), the language path (blue), the neutral ink | + +The rebuild is a **description** of the plate's structure written from it. No +vector data, no crops, no traced paths. + +## Rebuilding it + +```sh +node .scratch/render-figure.mjs packages/dsh-diagrams/reference/figures/neo-motivation +``` diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/anatomy.md b/packages/dsh-diagrams/reference/figures/neo-motivation/anatomy.md new file mode 100644 index 0000000..bd3d889 --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/anatomy.md @@ -0,0 +1,65 @@ +# Anatomy — NEO motivation plate + +## The claim it makes + +A modular VLM forces three discrete choices — tokenise or embed, tile or encode at +native resolution, fuse late or early. One native primitive stack makes all three +at once, and a language model can be loaded into it without a separate alignment +stage. + +## Reading order + +The plate reads **left → middle → right**, and the middle is the hinge: + +1. **Left: three choices, each with a cost.** Three cards, same shape, so the eye + compares them rather than reading three unrelated panels. +2. **Middle: the replacement.** One column: a two-block schematic (MHNA over FFN) + and the nine primitives that stack is built from. +3. **Right: the modular stack and two consequences.** A wide panel with the two + encoder boxes over two property lists, then numbered claims that each get a + small visual. + +## Layers + +| layer | what is drawn | +|---|---| +| column 1 | three `panel`s, each a title, a ✗/✓ line and one sentence | +| column 2 | one `panel` with a `stack` schematic and a numbered `list` | +| column 3 | a wide `panel` (two `node`s over two `list`s), then a `columns` row of two numbered panels: a two-node pipeline with an `arrow`, and an 8×8 `matrix` | + +## Primitives, and what each one is doing + +- **`columns` with weights (29 / 22 / 49)** — the whole plate is one row. The + middle column is narrow on purpose: it holds one idea. +- **`panel`** — three levels of grouping are visible only because the border + weight changes: outer plate, section panel, inner card. +- **`list`** — numbering is the argument's spine (nine primitives, nine + properties, two consequences). A list restarts its numbering per block, so the + two property lists stay independent. +- **`node`** — a box is an actor (Vision Encoder, LLM, VLM); a `panel` is a group. + The two are never confused in the target and must not be in the rebuild. +- **`matrix`** — 8×8, green inside the vision encoder, blue inside the language + model, with row labels for the modality groups. +- **`arrow`** — one, and it carries the panel's whole meaning: LLM → VLM. + +## Palette roles + +| role | used for | +|---|---| +| `accent` (orange) | the modular stack — the thing being replaced | +| `meta` (green) | the vision path and everything native/continuous | +| `link` (blue) | the language path | +| `warn` (red) | the ✗ choice | +| `muted` | the explanatory sentence under each comparison | + +## Typography + +Titles 7.4–8.2 pt, body 6.4 pt, lists 5.6 pt, matrix labels 5.6 pt. The floor is +5.5 pt and this figure sits just above it — which is the point of a plate like +this: it is dense because it is printed at 7 in. + +## What a rebuild must keep (see `rubric.json`) + +The three-column reading order, the ✗/✓ shape of the comparison cards, the two +property lists with their highlighted values, the LLM → VLM arrow, and the +attention matrix's two colour regions. diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/out/figure.svg b/packages/dsh-diagrams/reference/figures/neo-motivation/out/figure.svg new file mode 100644 index 0000000..8052fcc --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/out/figure.svg @@ -0,0 +1,8 @@ + + +NEO: native VLM primitives against the modular stack +A three-column motivation figure. The left column compares three discrete choices with their native alternatives. The middle column lists the native VLM primitives. The right column shows a modular VLM built from a vision encoder and a language model, a dense or mixture-of-experts language model being loaded into a VLM, and a multi-modal mixed attention matrix. + +Discrete vs. Continuous✗ Token Quantize · ✓ Patch Embedone grid cell per token, or one continuouspatch vectorTile vs. Native Resolution✗ Pre-set ratios · ✓ Native encodethe large image is cut into 1:1 … 1:6 tiles, orread at its own sizeLate vs. Early Fusion✗ Modular VLM · ✓ Monolithic VLMtext and image meet in an adapter, or from thefirst layermodular choicenative alternativeNative VLM PrimitivesMHNAFFN× L1.Dense Model2.2.2B / 9B Params3.32 × 32 Patch Size4.Sinusoidal PE5.Mixed Attention6.Native 3D-RoPE7.RoPE θ: 10K + 1M8.Layer Num: 40 / 429.Reusable Pre-BufferModular VLMsVision EncoderLanguage Model1.Dense Architecture2.Parameter: 0.3B, 0.6B, …, 22B3.Patch Size: 14, 16, 30, 324.Absolute Position Embedding5.Bi-Directional Attention6.2D-RoPE or Not7.RoPE θ: 100008.Head Dim: 64, 128, 2569.Layer Num: 6, 12, 24, …, 271.Dense or MoE Architecture2.Parameter: 0.6B, 1.7B, 8B, …, 1043B3.QK-Norm or Not4.Sliding Window or Not5.Hidden Activation: SiLU6.Causal-only Attention7.1D-RoPE or Not8.RoPE θ: 10000009.Head Dim: 128, 192, 25610.Layer Num: 28, 32, …, 64, 891. Seamlessly Load LLMsLLMVLMthe language model's weights are loadedinto the native stack; no alignment stageis trained first2. Multi-Modal Mixed Attention12345678imgtxt1txt2frame-wise bi-directional inside the visionencoder, causal inside the language model + + diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/out/metrics.json b/packages/dsh-diagrams/reference/figures/neo-motivation/out/metrics.json new file mode 100644 index 0000000..4a670ff --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/out/metrics.json @@ -0,0 +1,19 @@ +{ + "width": 516, + "height": 245, + "stats": { + "blocks": 64, + "links": 1, + "tones": [ + "muted", + "warn", + "meta", + "accent", + "link", + "ink" + ], + "smallestText": 5.6, + "preset": "ieee-double", + "caption": "NEO replaces the three discrete choices of a modular VLM (tokenise or embed, tile or encode natively, fuse late or early) with one native primitive stack, and loads the language model into that stack without a separate alignment stage." + } +} diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/rubric.json b/packages/dsh-diagrams/reference/figures/neo-motivation/rubric.json new file mode 100644 index 0000000..16d566d --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/rubric.json @@ -0,0 +1,95 @@ +{ + "version": 1, + "figure": "neo-motivation", + "claim": "A modular VLM forces three discrete choices; one native primitive stack replaces all three, and a language model loads into it without a separate alignment stage.", + "target": "targets/neo-motivation.png", + "checks": [ + { + "id": "three-columns", + "kind": "structure", + "text": "The plate reads left to right in three columns: the choices, the primitives, the modular stack.", + "blocks": [ + "card-discrete", + "card-tile", + "card-fusion", + "panel-primitives", + "panel-modular" + ] + }, + { + "id": "comparison-shape", + "kind": "structure", + "text": "Each comparison card states the modular choice and the native alternative in the same ✗/✓ shape, so the three can be compared at a glance.", + "blocks": [ + "card-discrete", + "card-tile", + "card-fusion" + ], + "labels": [ + "✗", + "✓" + ] + }, + { + "id": "primitives", + "kind": "content", + "text": "The middle column names the primitive stack and lists the primitives it is built from.", + "blocks": [ + "panel-primitives" + ], + "labels": [ + "Native VLM Primitives", + "MHNA", + "Pre-Buffer" + ] + }, + { + "id": "properties", + "kind": "content", + "text": "Two property lists sit under the two encoder boxes, one for the vision side and one for the language side.", + "blocks": [ + "panel-modular" + ], + "labels": [ + "Dense Architecture", + "Dense or MoE", + "Head Dim", + "Layer Num" + ] + }, + { + "id": "load-arrow", + "kind": "structure", + "text": "The load step is drawn as one arrow from the language model into the VLM.", + "blocks": [ + "n-llm", + "n-vlm", + "panel-load" + ] + }, + { + "id": "attention-matrix", + "kind": "structure", + "text": "The attention panel carries a grid with two colour regions: frame-wise inside the vision encoder, causal inside the language model.", + "blocks": [ + "attn", + "panel-attention" + ], + "labels": [ + "frame-wise bi-directional", + "causal" + ] + }, + { + "id": "caption", + "kind": "print", + "text": "The spec carries a caption that states the claim, and a description that names the figure for a reader who cannot see it." + }, + { + "id": "type-floor", + "kind": "print", + "text": "No type is below 5.5 pt at the printed width." + } + ], + "targetSha256": "f13d5ba00550ed0b9c5df551590e9971463220e143ed9e93860ccf433c80d4f9" +} diff --git a/packages/dsh-diagrams/reference/figures/neo-motivation/spec.json b/packages/dsh-diagrams/reference/figures/neo-motivation/spec.json new file mode 100644 index 0000000..4468dbf --- /dev/null +++ b/packages/dsh-diagrams/reference/figures/neo-motivation/spec.json @@ -0,0 +1,495 @@ +{ + "figure": { + "preset": "ieee-double", + "theme": "paper", + "margin": 6, + "gap": 6, + "size": 6.2, + "title": "NEO: native VLM primitives against the modular stack", + "caption": "NEO replaces the three discrete choices of a modular VLM (tokenise or embed, tile or encode natively, fuse late or early) with one native primitive stack, and loads the language model into that stack without a separate alignment stage.", + "description": "A three-column motivation figure. The left column compares three discrete choices with their native alternatives. The middle column lists the native VLM primitives. The right column shows a modular VLM built from a vision encoder and a language model, a dense or mixture-of-experts language model being loaded into a VLM, and a multi-modal mixed attention matrix." + }, + "blocks": [ + { + "type": "columns", + "gap": 8, + "children": [ + { + "weight": 29, + "block": { + "type": "rows", + "gap": 6, + "children": [ + { + "type": "panel", + "id": "card-discrete", + "title": "Discrete vs. Continuous", + "border": true, + "radius": 5, + "pad": 7, + "gap": 4, + "titleSize": 8.2, + "children": [ + { + "type": "text", + "size": 6.4, + "text": "{warn:✗} Token **Quantize** · {meta:✓} Patch **Embed**" + }, + { + "type": "text", + "size": 6, + "tone": "muted", + "text": "one grid cell per token, or one continuous patch vector" + } + ] + }, + { + "type": "panel", + "id": "card-tile", + "title": "Tile vs. Native Resolution", + "radius": 5, + "pad": 7, + "gap": 4, + "titleSize": 8.2, + "children": [ + { + "type": "text", + "size": 6.4, + "text": "{warn:✗} Pre-set **ratios** · {meta:✓} **Native** encode" + }, + { + "type": "text", + "size": 6, + "tone": "muted", + "text": "the large image is cut into 1:1 … 1:6 tiles, or read at its own size" + } + ] + }, + { + "type": "panel", + "id": "card-fusion", + "title": "Late vs. Early Fusion", + "radius": 5, + "pad": 7, + "gap": 4, + "titleSize": 8.2, + "children": [ + { + "type": "text", + "size": 6.4, + "text": "{warn:✗} **Modular** VLM · {meta:✓} **Monolithic** VLM" + }, + { + "type": "text", + "size": 6, + "tone": "muted", + "text": "text and image meet in an adapter, or from the first layer" + } + ] + }, + { + "type": "legend", + "size": 6, + "gap": 10, + "items": [ + { + "tone": "warn", + "label": "modular choice" + }, + { + "tone": "meta", + "label": "native alternative" + } + ] + } + ] + } + }, + { + "weight": 22, + "block": { + "type": "panel", + "id": "panel-primitives", + "title": "Native VLM Primitives", + "titleAlign": "center", + "radius": 6, + "pad": 5, + "gap": 4, + "titleSize": 7.4, + "children": [ + { + "type": "stack", + "h": 46, + "children": [ + { + "x": 2, + "y": 2, + "w": 74, + "h": 18, + "block": { + "type": "node", + "title": "MHNA", + "shape": "rect", + "radius": 2, + "size": 6.2 + } + }, + { + "x": 2, + "y": 26, + "w": 74, + "h": 16, + "block": { + "type": "node", + "title": "FFN", + "shape": "rect", + "radius": 2, + "size": 6.2 + } + }, + { + "x": 80, + "y": 4, + "w": 26, + "h": 12, + "block": { + "type": "text", + "size": 6, + "tone": "muted", + "text": "× L" + } + } + ] + }, + { + "type": "list", + "size": 5.8, + "itemGap": 1, + "items": [ + "**Dense Model**", + "**2.2B** / **9B** Params", + "**32 × 32** Patch Size", + "**Sinusoidal PE**", + "**Mixed Attention**", + "**Native 3D-RoPE**", + "RoPE θ: **10K + 1M**", + "Layer Num: **40 / 42**", + "Reusable **Pre-Buffer**" + ] + } + ] + } + }, + { + "weight": 49, + "block": { + "type": "rows", + "gap": 6, + "children": [ + { + "type": "panel", + "id": "panel-modular", + "title": "Modular VLMs", + "titleAlign": "center", + "tone": "accent", + "radius": 6, + "pad": 5, + "gap": 4, + "titleSize": 7.6, + "children": [ + { + "type": "columns", + "gap": 6, + "children": [ + { + "weight": 1, + "block": { + "type": "node", + "title": "Vision Encoder", + "shape": "rect", + "radius": 2, + "size": 6.4, + "fill": true + } + }, + { + "weight": 1, + "block": { + "type": "node", + "title": "Language Model", + "shape": "rect", + "radius": 2, + "size": 6.4, + "fill": true + } + } + ] + }, + { + "type": "columns", + "gap": 8, + "children": [ + { + "weight": 1, + "block": { + "type": "list", + "size": 5.6, + "itemGap": 0.6, + "items": [ + "**Dense Architecture**", + "Parameter: 0.3B, 0.6B, …, 22B", + "Patch Size: 14, **16**, 30, 32", + "Absolute Position Embedding", + "Bi-Directional Attention", + "2D-RoPE or Not", + "RoPE θ: **10000**", + "Head Dim: 64, **128**, 256", + "Layer Num: 6, 12, 24, …, 27" + ] + } + }, + { + "weight": 1, + "block": { + "type": "list", + "size": 5.6, + "itemGap": 0.6, + "items": [ + "**Dense or MoE** Architecture", + "Parameter: 0.6B, 1.7B, 8B, …, 1043B", + "**QK-Norm** or Not", + "Sliding Window or **Not**", + "Hidden Activation: **SiLU**", + "**Causal-only** Attention", + "**1D-RoPE** or Not", + "RoPE θ: **1000000**", + "Head Dim: **128**, 192, 256", + "Layer Num: 28, 32, …, 64, 89" + ] + } + } + ] + } + ] + }, + { + "type": "columns", + "gap": 6, + "children": [ + { + "weight": 1, + "block": { + "type": "panel", + "id": "panel-load", + "title": "1. Seamlessly Load LLMs", + "tone": "link", + "radius": 6, + "pad": 5, + "gap": 4, + "titleSize": 7, + "children": [ + { + "type": "columns", + "gap": 14, + "children": [ + { + "weight": 1, + "block": { + "type": "node", + "id": "n-llm", + "title": "LLM", + "w": 46, + "h": 20, + "tone": "link", + "radius": 3, + "size": 7 + } + }, + { + "weight": 1, + "block": { + "type": "node", + "id": "n-vlm", + "title": "VLM", + "w": 46, + "h": 26, + "tone": "ink", + "radius": 3, + "size": 7 + } + } + ] + }, + { + "type": "text", + "size": 5.6, + "tone": "muted", + "text": "the language model's weights are loaded into the native stack; no alignment stage is trained first" + } + ] + } + }, + { + "weight": 1, + "block": { + "type": "panel", + "id": "panel-attention", + "title": "2. Multi-Modal Mixed Attention", + "radius": 6, + "pad": 5, + "gap": 4, + "titleSize": 7, + "children": [ + { + "type": "matrix", + "id": "attn", + "rows": 8, + "cols": 8, + "cell": 6, + "gap": 0.8, + "labelSize": 5.6, + "rowLabels": [ + "img", + "txt1", + "txt2", + "", + "", + "", + "", + "" + ], + "colLabels": [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ], + "cells": [ + { + "r": 0, + "c": 0, + "tone": "meta" + }, + { + "r": 0, + "c": 1, + "tone": "meta" + }, + { + "r": 0, + "c": 2, + "tone": "meta" + }, + { + "r": 1, + "c": 0, + "tone": "meta" + }, + { + "r": 1, + "c": 1, + "tone": "meta" + }, + { + "r": 1, + "c": 2, + "tone": "meta" + }, + { + "r": 2, + "c": 0, + "tone": "meta" + }, + { + "r": 2, + "c": 1, + "tone": "meta" + }, + { + "r": 2, + "c": 2, + "tone": "meta" + }, + { + "r": 3, + "c": 3, + "tone": "link" + }, + { + "r": 3, + "c": 4, + "tone": "link" + }, + { + "r": 4, + "c": 4, + "tone": "link" + }, + { + "r": 4, + "c": 5, + "tone": "link" + }, + { + "r": 5, + "c": 5, + "tone": "link" + }, + { + "r": 5, + "c": 6, + "tone": "link" + }, + { + "r": 6, + "c": 6, + "tone": "link" + }, + { + "r": 6, + "c": 7, + "tone": "link" + }, + { + "r": 7, + "c": 7, + "tone": "link" + }, + { + "r": 7, + "c": 3, + "tone": "link" + } + ] + }, + { + "type": "text", + "size": 5.6, + "tone": "muted", + "text": "{meta:frame-wise bi-directional} inside the vision encoder, {link:causal} inside the language model" + } + ] + } + } + ] + } + ] + } + } + ] + } + ], + "links": [ + { + "kind": "arrow", + "from": "n-llm.right", + "to": "n-vlm.left", + "tone": "muted", + "out": 3 + } + ] +} diff --git a/packages/dsh-diagrams/reference/targets/gguf-file-layout.jpg b/packages/dsh-diagrams/reference/targets/gguf-file-layout.jpg new file mode 100644 index 0000000..7a97703 Binary files /dev/null and b/packages/dsh-diagrams/reference/targets/gguf-file-layout.jpg differ diff --git a/packages/dsh-diagrams/reference/targets/neo-motivation.png b/packages/dsh-diagrams/reference/targets/neo-motivation.png new file mode 100644 index 0000000..b01a5d9 Binary files /dev/null and b/packages/dsh-diagrams/reference/targets/neo-motivation.png differ diff --git a/packages/dsh-diagrams/skills/paper-figures/SKILL.md b/packages/dsh-diagrams/skills/paper-figures/SKILL.md new file mode 100644 index 0000000..4758bde --- /dev/null +++ b/packages/dsh-diagrams/skills/paper-figures/SKILL.md @@ -0,0 +1,134 @@ +--- +name: paper-figures +description: Compile a paper figure from a JSON spec with diagram_write({kind:"figure"}) - the grammar, the measured layout, the geometry diagnostics, the print contract, and the two-figure reference corpus to copy from. +--- + +# Paper figures + +A figure in a paper is not a drawing, it is a **layout problem**: 40–200 labelled +boxes, a caption that states the claim, leaders anchored to one byte of a bar, and +a width the journal fixes at 3.5 or 7.16 inches. Freehand SVG fails at this size +because nothing measures the text; TikZ survives it but costs a compile per +keystroke. `kind: "figure"` is the third way: you write the **structure**, the host +compiles the geometry. + +``` +diagram_write({ kind: "figure", id: "my-figure", source: }) +``` + +If it returns `status: "ok"` you have a vector figure at `f2-paper`. If it returns +`status: "error"` you have a line-addressable geometry problem, which is the point. + +## When to use which kind + +| you want | kind | +|---|---| +| a flow, a sequence, a state machine, anything under ~12 nodes | `mermaid` | +| a photograph-like arrangement of exactly-placed marks, or a kit example | `html` | +| a figure for a paper: dense, measured, printed at a fixed width | **`figure`** | +| a formula-heavy picture that must be TeX | `tikz` | + +## The spec + +```json +{ + "figure": { + "preset": "ieee-double", + "theme": "paper", + "margin": 8, + "gap": 7, + "caption": "One sentence stating what the reader must get from the figure." + }, + "blocks": [ + { "type": "text", "text": "**model.gguf** is a header, then metadata, then weights." }, + { "type": "strip", "id": "bar", "segments": [ + { "id": "magic", "weight": 1, "label": "4 bytes", "tone": "ink" }, + { "id": "meta", "weight": 2, "label": "metadata", "tone": "meta" }, + { "id": "rest", "weight": 6, "label": "tensor data", "tone": "ink" } ] } + ], + "links": [ + { "kind": "leader", "from": "bar.meta.bottom", "to": "bar.rest.bottom", "dash": true, "tone": "meta" } + ] +} +``` + +Only `blocks` is required alongside `figure`. Sizes are **points**: a 7 pt label is +`"size": 7`, and that is what prints. + +## The primitives + +| type | is | key fields | +|---|---|---| +| `rows` / `columns` | the whole layout model | `children`, `gap`; a column child may be `{ "block": …, "weight": 2 }` | +| `panel` | a titled group | `title`, `tone`, `dash`, `fill: true` (tint), `radius`, `pad` | +| `text` | a paragraph | `text`, `size`, `align`, `weight: "bold"`, `mono` | +| `list` | numbered or bulleted items | `items`, `numbered`, `size`, `itemGap` | +| `code` | a monospaced pane | `lines`, `size`, `frame: false` inside a panel | +| `strip` | a bar whose segment widths are data | `segments[{id, weight, label, tone, text}]`, `labels`, `tail` | +| `node` | one actor in a box | `title`, `sub`, `w`, `h`, `shape` | +| `matrix` | a labelled grid | `rows`, `cols`, `cell`, `cells[{r,c,tone}]`, `rowLabels`, `colLabels` | +| `badge` | a pill | `text`, `tone`, `align` | +| `legend` | the colour key | `items[{tone,label}]` — a print figure needs one | +| `rule` / `spacer` | a hairline / a gap | `h` | +| `stack` | explicit placement, for one inset | `h`, `children[{block,x,y,w,h}]` | + +Inline markup inside any text: `**bold**`, `` `mono` ``, `{tone:text}`. + +**Tones are roles, not colours**: `ink`, `muted`, `soft`, `meta`, `tensor`, `link`, +`accent`, `warn`, `teal`, `yellow`. The theme resolves them, and the greyscale +check compares their luminance — so a figure survives being printed in black and +white, which is how most of them are read. + +## Connectors + +```json +{ "kind": "leader", "from": "card-magic.top", "to": "bar.magic.bottom", "tone": "ink", "dash": true, "dot": true } +{ "kind": "arrow", "from": "n-llm.right", "to": "n-vlm.left", "out": 3 } +{ "kind": "brace", "from": "bar.magic", "to": "bar.kv", "label": "header · 24 bytes" } +``` + +An end is `"id"` (centre), `"id.top|bottom|left|right"`, or `"bar..top"` +for one segment of a strip. Routing is orthogonal with rounded corners, and the +clearance is clamped to the gap you left, so a 5 pt elbow in an 8 pt gutter does +not overshoot. + +## The loop + +1. **Write the claim first.** One sentence: what must the reader believe after five + seconds? That sentence is `figure.caption`, and it decides the panels. +2. **Pick an archetype** from `reference/figures/` and read its `anatomy.md`: + `gguf-file-layout` for a byte/record layout, `neo-motivation` for a multi-panel + motivation plate. +3. **Write the spec top-down**: columns first, then panels, then text. Do not reach + for `stack` until the flow layout genuinely cannot express the inset. +4. **Read the diagnostics.** `overlap` means two solid boxes share space; `bounds` + means the page is too narrow; `link` means an anchor name is wrong. Fix the + structure, not the pixels. +5. **Look at it.** `diagram_figure`-class renders come from the tab; for a host-side + PNG, export `png` (the panel rasterises at 3×) and open it. +6. **Check the warnings**, which are the ones a reader would notice: type below + 5.5 pt, two tones that merge in greyscale, a code line wider than its pane, no + caption. + +## Rules that keep a figure printable + +- **Width is a decision, not a default.** `ieee-single` 252 pt, `ieee-double` 516, + `acm-single` 240, `neurips` 397, `cvpr` 495. Design at the width it will print. +- **Density is the enemy.** Over ~120 text runs, split into two figures. The kit's + own budget is 9 nodes; a paper plate earns its density one panel at a time. +- **One colour role, one meaning, kept everywhere.** If `meta` is the metadata + section, it is not also "good". +- **Every colour gets a legend**, or the figure is unreadable in print. +- **The caption states the claim**; the figure does not restate the caption. +- **Never pixel-place.** If you find yourself writing `stack` with hand-computed + coordinates at the top level, the composition is wrong. + +## Common diagnostics, and what they mean + +| diagnostic | fix | +|---|---| +| `overlap … by W×Hpt` | two solids share space: shorten a column, raise a `gap`, or move the block into its own row | +| `bounds … outside the Npt page` | the content is wider than the preset: reduce sizes, or use a wider preset | +| `link … does not resolve` | the anchor names a block that does not exist, or the side is not `top/bottom/left/right` | +| `print … below the 5.5pt floor` | raise `size`, or cut content | +| `grey … merge in a black-and-white print` | use two tones with different luminance, or label them | diff --git a/scripts/checks/check-client-bundles.mjs b/scripts/checks/check-client-bundles.mjs index 4646ee3..2ec1bdd 100644 --- a/scripts/checks/check-client-bundles.mjs +++ b/scripts/checks/check-client-bundles.mjs @@ -304,6 +304,9 @@ function loadBundle(relative, extraRequire) { return props && props.anchor !== undefined ? props.anchor : null } const Child = (props) => (props && props.children !== undefined ? props.children : null) + // A path label draws the path it is given; the review header uses it, and + // a static render only needs the text to be there. + const Path = (props) => (props && props.path !== undefined ? props.path : null) // MarkdownText renders its text: the editor's rendered-view body draws it. // IT IS `React.memo`-WRAPPED ON PURPOSE, because the shipped primitive is // (`const MarkdownText = React.memo(...)`) and a memo component is an @@ -376,6 +379,16 @@ function loadBundle(relative, extraRequire) { // the new ones. (Medium is here because the real ui-theme reads it.) IconChevronDownOutlineRegular: Null, IconChevronUpOutlineRegular: Null, + // The turn review's own controls: split, wrap and open-file. + IconCompareSplitOutlineRegular: Null, + IconNowrapFillRegular: Null, + IconWrapFillRegular: Null, + IconInspectOutlineRegular: Null, + PathLabel: Path, + // The diff's code highlighter: the review renders plain spans when the + // highlighter returns nothing, which is what a static check needs. + languageForPath: () => undefined, + useCodeHighlighter: () => () => undefined, IconLightOutlineRegular: Null, IconLightOutlineMedium: Null, IconDarkOutlineRegular: Null, @@ -4167,8 +4180,8 @@ check('the frame carries a theme', /(&|&)theme=(dark|light)/.test(htmlMarkup // The export MENU is closed until it is asked for, so the formats this kind // offers are read from the source's own per-kind list rather than from a menu // that has not been opened. What matters is that `html` never claims a PNG. -const exportFormats = /const formats = kind === 'tikz' \? \['tex', 'pdf', 'svg', 'png'\] : kind === 'html' \? \['html', 'svg'\] : \['mmd', 'md', 'svg', 'png'\]/ -check('the html tab declares only the formats it has', exportFormats.test(readFileSync(path.join(repo, 'packages/dsh-diagrams/lib/client.js'), 'utf8')), true) +const exportFormats = /const formats = kind === 'tikz' \? \['tex', 'pdf', 'svg', 'png'\] : kind === 'html' \? \['html', 'svg'\] : kind === 'figure' \? \['json', 'svg', 'png'\] : \['mmd', 'md', 'svg', 'png'\]/ +check('each kind declares only the formats it has', exportFormats.test(readFileSync(path.join(repo, 'packages/dsh-diagrams/lib/client.js'), 'utf8')), true) check('the html tab shows its own kind', htmlMarkup.includes('>Design<'), true) // A kit example is the THIRD address shape, and it opens in the same tab type - @@ -7085,6 +7098,91 @@ if (coreThemeBundle === null) { check('shaders: the tab has no corpus browser in it', /corpus|gallery|search/i.test(viewerMarkup), false) } +// ---------------------------------------------------------------- dsh-deliverables +// The pack forks the harness's deliverables bundle for ONE reason: the turn +// Review tab answers a binary change with "Binary file; changes cannot be +// shown", and a picture is a binary change. Loading the fork proves the patch +// did not break activation; server-rendering its review body once per kind +// proves the branch it added is the one that draws - and that a text diff and a +// non-image binary still take the shipped path. +{ + const deliverables = loadBundle('packages/dsh-deliverables/lib/client.js', {}) + const types = [] + const seats = {} + let mentionApi = null + const t = (key) => key + const deliverablesCtx = { + effect: (fn) => { fn(); return () => {} }, + on: () => {}, + provide: (name, api) => { if (name === 'chatFileMentions') mentionApi = api; return () => {} }, + locale: { register: () => () => {}, bind: () => t }, + slots: { + inject: (name, fn) => { fn(); return () => {} }, + register(spec, component) { + seats[spec.name + '#' + (spec.key ?? spec.id ?? '')] = { spec, component } + return () => {} + }, + }, + sidebarRightTabs: { register: (definition) => { types.push(definition); return () => {} } }, + uiConversation: { events: { register: () => {} } }, + configForms: { developerTools: { enabled: true } }, + logger: { debug() {}, warn() {} }, + } + deliverables.exports.apply(deliverablesCtx) + check('deliverables: one review tab type is registered', types.length === 1 && types[0].id + '/' + types[0].kind, '@deepseek-ai/dsh-client-ui-deliverables/changes-review') + check('deliverables: it claims the review address and nothing else', types[0].patterns.join(',') + '|' + types[0].canOpen('dsh-resource://changes-review/session/s1/7/2') + '|' + types[0].canOpen('dsh-resource://file/session/s1/a.png'), 'dsh-resource://changes-review/**|true|false') + check('deliverables: the changed-files card is registered', seats['conversation.chat.turnTail#@deepseek-ai/dsh-client-ui-deliverables'] !== undefined) + check('deliverables: the review body is registered', seats['sidebar.right.pane.tab#@deepseek-ai/dsh-client-ui-deliverables'] !== undefined) + check('deliverables: it still provides the chat file mentions', typeof mentionApi?.forClosing === 'function') + + const body = seats['sidebar.right.pane.tab#@deepseek-ai/dsh-client-ui-deliverables'] + const tab = { + id: 'tab-review', + contentId: 'dsh-resource://changes-review/session/session-1/7/2', + title: 'Review 2', + navigation: { params: { index: 0 }, revision: 1 }, + signal: new AbortController().signal, + actions: { bindCommands: () => {}, openResource: () => {} }, + } + /** One review render: the summary and comparison a turn announced, as the stores would serve them. */ + const renderReview = (files, diff) => renderToStaticMarkup(h(body.component, { + useTabInfo: () => ({ tab, panel: { id: 'pane-1' } }), + sessionId: 'session-1', + useSessions: (selector) => selector({ byId: { 'session-1': { cwd: 'C:/work/repo' } } }), + useStore: (selector) => selector({ byTab: { 'tab-review': { index: 0, split: false, wrap: false } } }), + actions: { navigated() {}, selected() {}, toggledSplit() {}, toggledWrap() {} }, + useChangesSummary: (selector) => selector(new Proxy({}, { get: () => ({ turn: 2, files, total: files.length, added: 0, deleted: 0 }) })), + useChangesDiff: (selector) => selector(new Proxy({}, { get: () => diff })), + usePresentedOpen: (selector) => selector(new Proxy({}, { get: () => undefined })), + usePresentedHost: (selector) => selector(null), + loadChangesSummary: () => {}, + loadChangesDiff: () => {}, + reloadPresentedHost: () => {}, + openChanged: () => {}, + renderSlot: () => null, + t, + })) + + const image = { path: 'assets/vncode-banner6.png', display: 'assets/vncode-banner6.png', added: 0, deleted: 0, binary: true } + const imageMarkup = renderReview([image], { kind: 'binary', path: image.path, display: image.display }) + check('deliverables: a binary image renders the picture', imageMarkup.includes('data-review-image="true"')) + check('deliverables: ...from the harness file route at the workspace path', + imageMarkup.includes('/api/file?path=' + encodeURIComponent('C:/work/repo/assets/vncode-banner6.png'))) + check('deliverables: ...and no longer says changes cannot be shown', imageMarkup.includes('diff.binary'), false) + check('deliverables: the header counts it as an image', imageMarkup.includes('>Image<')) + + const text = { path: 'src/app.ts', display: 'src/app.ts', added: 1, deleted: 0 } + const textMarkup = renderReview([text], { kind: 'text', path: text.path, display: text.display, before: true, after: true, coarse: false, hunks: [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, lines: ['+const answer = 42'] }] }) + check('deliverables: a text change keeps the shipped comparison', textMarkup.includes('data-diff-line')) + check('deliverables: ...and does not draw a picture', textMarkup.includes('data-review-image'), false) + + const archive = { path: 'dist/pack.zip', display: 'dist/pack.zip', added: 0, deleted: 0, binary: true } + const archiveMarkup = renderReview([archive], { kind: 'binary', path: archive.path, display: archive.display }) + check('deliverables: a non-image binary keeps the shipped sentence', archiveMarkup.includes('diff.binary')) + check('deliverables: ...and is not drawn as a picture', archiveMarkup.includes('data-review-image'), false) +} + console.log('') console.log(failures === 0 ? 'all client-bundle checks passed' : failures + ' check(s) FAILED') process.exitCode = failures === 0 ? 0 : 1 + diff --git a/scripts/checks/check-node-routes.mjs b/scripts/checks/check-node-routes.mjs index 0b0e581..2b29648 100644 --- a/scripts/checks/check-node-routes.mjs +++ b/scripts/checks/check-node-routes.mjs @@ -896,6 +896,29 @@ try { check('diagrams: a TikZ document with no picture is refused', blankTikz.view.status, 'error') check('diagrams: the empty TikZ is explained', /no picture in this source/i.test(blankTikz.diagnostics[0].text), true) + // --- a figure is COMPILED on the host: the spec is measured, placed, routed + // and emitted to one SVG, and the artifact the tab draws is that document. + const figureSpec = JSON.stringify({ + figure: { preset: 'ieee-single', theme: 'paper', caption: 'A two-field bar with a leader, long enough to be a real caption.' }, + blocks: [ + { type: 'text', text: 'Hello **figure**' }, + { type: 'strip', id: 'bar', segments: [{ id: 'a', weight: 1, label: '4 bytes' }, { id: 'b', weight: 2, label: 'rest' }] } + ], + links: [{ kind: 'leader', from: 'bar.a.top', to: 'bar.b.top', dash: true }] + }) + const figure = await tool('diagram_write').execute({ kind: 'figure', id: 'compiled-figure', title: 'Compiled figure', source: figureSpec }, exec) + check('diagrams: a figure compiles to f2-paper', figure.view.status, 'ok') + check('diagrams: the figure names its kind', figure.view.kind, 'figure') + check('diagrams: the result states the geometry contract', /f2-paper/.test(figure.text), true) + const badFigure = await tool('diagram_write').execute({ kind: 'figure', id: 'broken-figure', title: 'Broken', source: '{"blocks":[{"type":"nope"}]}' }, exec) + check('diagrams: an unknown figure primitive is refused', badFigure.view.status, 'error') + check('diagrams: the refusal names a primitive', /not a primitive/.test(badFigure.diagnostics[0].text), true) + const figureState = await (await getJson('/api/dsh-diagrams/state', 'session=session-diagrams')).json() + const storedFigure = figureState.diagrams.find((entry) => entry.id === 'compiled-figure') + check('diagrams: the figure is listed as a figure', storedFigure?.kind, 'figure') + check('diagrams: the figure produced an SVG artifact', (storedFigure?.artifact?.formats ?? []).includes('svg'), true) + check('diagrams: the artifact records the page size', storedFigure?.artifact?.width, 252) + // --- diagram_verify: re-validates, writes nothing, and does not bump the revision const patched = await tool('diagram_patch').execute({ id: 'auth-flow', oldString: 'B{OK?}', newString: 'B{Credentials?}' }, exec) check('diagrams: patch reports the occurrence count', patched.occurrences, 1)