Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento/type: a word processor, wired to the platform (#384)

nyblnetbd7799c2600f
diff --git a/.claude/launch.json b/.claude/launch.json
index 1a71bad6..e6bca1d6 100644
--- a/.claude/launch.json
+++ b/.claude/launch.json
@@ -182,6 +182,21 @@
"/Users/andy/devel/bento/.worktrees/type/.testserve"
],
"port": 5190
+ },
+ {
+ "name": "serve-type-built",
+ "comment": "LOOPBACK ONLY, see serve-built. Serves the shippable single-file build for collab/dormancy verification.",
+ "runtimeExecutable": "python3",
+ "runtimeArgs": [
+ "-m",
+ "http.server",
+ "5189",
+ "--bind",
+ "127.0.0.1",
+ "--directory",
+ "type/dist-single"
+ ],
+ "port": 5189
}
]
-}
\ No newline at end of file
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2b4118c5..b9d20c67 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -732,6 +732,112 @@ jobs:
# against a WCAG AA floor of 4.5.
run: node scripts/test-type-theme.mjs
+ - name: bento/dash CRDT convergence
+ # The big one: randomised concurrent edits across N replicas, asserted
+ # to converge. It has caught every ordering bug in the engine, and the
+ # two it did not catch were found by widening it.
+ run: node scripts/test-dash-sync.ts
+
+ - name: relay protocol — one wire format, two clients
+ # dash's online.ts is a PORT of the transport slides uses (now in
+ # kernel/). The two files are separate text that nobody diffs, and ONE
+ # DEPLOYED WORKER verifies both: it pins the room id to a key and walks
+ # an owner→invite→member signature chain. If one client's idea of
+ # `inv.${pub}.${role}.${exp}` drifts, the symptom is not a red test — it
+ # is one app's users silently unable to join the other's rooms, on a
+ # relay that cannot be rolled back independently of the shells already
+ # in people's files. This diffs only what goes on the wire.
+ #
+ # Written by the bento/dash work; taken here because the kernel lift is
+ # the change it guards, and it should not land after the move it exists
+ # to check. The rig FOLLOWS the twin (kernel first, then slides) and
+ # FAILS if it finds no transport at all, rather than silently comparing
+ # two empty lists — which is how its own first version passed.
+ run: node scripts/test-relay-protocol.ts
+
+ - name: Type blocks rig
+ # Lists and tables are runs of flat blocks assembled at render;
+ # this pins the grouping, including the level clamp that once opened a
+ # billion list elements and killed the process.
+ run: node scripts/test-type-blocks.ts
+
+ - name: Type layout rig
+ # Paragraph spacing, indents and page setup, and that a page break
+ # is honoured by the paginator rather than merely stored.
+ run: node scripts/test-type-layout.ts
+
+ - name: Type image rig
+ # Pictures embed or reference, and an atomic block is measured as one
+ # box so pagination cannot break a page through the middle of it.
+ run: node scripts/test-type-image.ts
+
+ - name: Type link rig
+ # Link marks round-trip, and the href allow-list holds: a document is
+ # untrusted input, and javascript: reached the page from one once.
+ run: node scripts/test-type-link.ts
+
+ - name: Type find rig
+ # Find and replace across blocks, including the offsets that shift
+ # when a replacement changes a block's length.
+ run: node scripts/test-type-find.ts
+
+ - name: Type toc rig
+ # Section numbering is DERIVED, never stored, so inserting a heading
+ # renumbers everything and nothing drifts.
+ run: node scripts/test-type-toc.ts
+
+ - name: Type xref rig
+ # Captions and cross-references are atoms at an offset, so renumbering
+ # is invisible to the redline.
+ run: node scripts/test-type-xref.ts
+
+ - name: Type cite rig
+ # Citations and the bibliography — a citation is an atom, so
+ # restyling one is not an edit to the sentence around it.
+ run: node scripts/test-type-cite.ts
+
+ - name: Type math rig
+ # Formulas: the TeX source is the model and inline math is a mark, so
+ # a formula survives the render→read round trip intact.
+ run: node scripts/test-type-math.ts
+
+ - name: Type comments rig
+ # Threads keep their anchors through edits, splits and merges, and
+ # editing or deleting a message never moves the text it points at.
+ run: node scripts/test-type-comments.ts
+
+ - name: Type track rig
+ # Tracked changes as ins/del marks: accept-all gives the text as
+ # edited, reject-all the text as it was, and display modes never touch
+ # the model.
+ run: node scripts/test-type-track.ts
+
+ - name: Type font rig
+ # Per-selection typeface and size, and the CSS allow-list that keeps a
+ # font stack from opening a second declaration in a style attribute.
+ run: node scripts/test-type-font.ts
+
+ - name: Type styles rig
+ # Named paragraph styles, and the additivity rule: a document with no
+ # doc.styles must render byte-identically to before the feature.
+ run: node scripts/test-type-styles.ts
+
+ - name: Type move rig
+ # Reordering moves whole UNITS, so a drag can never tear a table in
+ # half or drop a paragraph between two bullets.
+ run: node scripts/test-type-move.ts
+
+ - name: Type embed rig
+ # Embedded Bento artifacts, and the render boundary that refuses a
+ # script rather than sanitising one.
+ run: node scripts/test-type-embed.ts
+
+ - name: Type chrome rig
+ # Where controls live: nothing in two menus, no inserts in the
+ # overflow, and every element the chrome reaches for actually exists —
+ # a null lookup there has silently broken the boot twice.
+ run: node scripts/test-type-chrome.ts
+
- name: Clipboard embedded-font rig
run: |
slides/node_modules/.bin/esbuild scripts/test-clipboard.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-clipboard.mjs"
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 48643e39..d66b0b55 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,81 @@ Decision. Why. Pointers.
---
+## 2026-08-19 — Cross-app embedding: static render + source, never a second renderer
+
+**Decision.** One block/element shape, `bento/embed`, shared by every app in both
+directions (a Dash chart in a Type contract, a Type doc in a Spaces page, either
+in a Slides deck):
+
+```
+{ kind:'embed', app:'bento/dash', doc:{…}|'asset:…', view:'<svg…>', w, h, caption? }
+```
+
+Three tiers, and the ORDER is the design. `view` — a static render — is always
+present, so the embed paints in any app with zero extra code, thumbnails, and
+prints. `doc` — the source — is always present, so it round-trips: open in Dash,
+edit, come back. A live sandboxed iframe is OPT-IN per embed, never the default.
+
+**Why.** Embedding the other app's renderer means shipping every renderer in
+every file to cover the matrix (each is 100KB+) and living with version skew
+between the embedded copy and the real app. The static render is what makes a
+self-contained file self-contained; the source is what stops it being a
+screenshot. A Bento file IS a runnable page, so `srcdoc` genuinely works for a
+live chart — but it is opt-in because most embeds do not need it and every one
+of them would cost the file a full shell.
+
+Constraints this inherits, not new ones: format additivity (PLATFORM §3) means
+an app that does not know `bento/dash` still shows the render plus an "open
+in…" affordance, never a hole; the splice contract (§2) means the payload can
+never carry a bare `</script>`, so it is escaped like `#bento-doc` or stored as
+an asset; and since every document is untrusted input, a live iframe is
+sandboxed with no same-origin. Default to data + render — embedding a 500KB
+shell per chart is how a contract becomes 3MB.
+
+**Status.** The SHAPE is settled here so the apps do not each invent one. The
+shared definition belongs in the kernel and is therefore a serialized kernel
+change of its own (PARALLEL-WORK §1): it has not been made. bento/type
+implements the consumer side in its own app zone against this shape, so the
+kernel lift is a move, not a redesign.
+
+**Pointers.** `type/src/embed.ts`, `docs/PLATFORM.md` §2–§3.
+
+---
+
+## 2026-08-24 — The tree moved to `home/`, and the identifiers moved with it
+
+**Decision.** `tray/` is now `home/`, `applicationId` and
+`PRODUCT_BUNDLE_IDENTIFIER` are `page.bento.home`, and the update channel is
+`https://bento.page/releases/home/manifest.json`. This supersedes the scope
+paragraph and the bundle-identifier bullet in the rename entry above.
+
+**Why the earlier decision was right when it was made, and wrong to keep.** It
+was written while `tray/ios` (#315) and the Android work were both open in
+`tray/`; moving the tree under them would have turned two mergeable branches
+into conflict resolution. That was a real cost and a correct call at the time.
+Both landed, and the reason expired.
+
+The bundle-identifier bullet expired differently. Its argument was explicitly
+conditional — changing the id "creates a different one that cannot update the
+installed copy". There was no installed copy, no App Store Connect record and no
+Play listing. Those three facts are what made it free, and all three stop being
+true at first publish. **This was the last moment the identifiers could move.**
+
+**What did NOT move, and why the line is there.** Rename what the outside world
+sees or what becomes permanent on publish; leave what is internal and guarded:
+
+- **The IndexedDB name stays `bento-tray`** (`home/webext/src/db.js`).
+ `scripts/test-webext-background.ts` asserts it — a deliberate guard against
+ silently orphaning every stored grant. Nobody outside the extension ever sees
+ it, so renaming it would have meant editing a gate to let a cosmetic change
+ through.
+- **`bento-tray://` (iOS) and `.bento-tray.invalid` (Android)** stay. They are
+ per-document origins, settled in their own entries, and invisible.
+
+**The cost, stated.** Every path reference moved: 18 files outside the tree, 35
+inside it, plus the Kotlin package `page.bento.tray` → `page.bento.home` and the
+`tray-icon`/`tray-logo`/`ic_tray_mark` assets. That churn is what the original
+entry warned about, and it was the price of not carrying a dead name forever.
## 2026-08-25 — The tray hosts are called `bento/home`
**Decision.** All three hosts are named **`bento/home`** — lowercase, with the
diff --git a/scripts/lib/ts-resolve-hooks.mjs b/scripts/lib/ts-resolve-hooks.mjs
index b942cbc3..f897b691 100644
--- a/scripts/lib/ts-resolve-hooks.mjs
+++ b/scripts/lib/ts-resolve-hooks.mjs
@@ -28,8 +28,25 @@
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
+import { access } from 'node:fs/promises';
-const esbuild = await import('../../slides/node_modules/esbuild/lib/main.js');
+// esbuild is taken from whichever app workspace has it installed, NOT from a
+// hardcoded one. Pinning it to slides/ meant every rig using this hook failed
+// in a worktree where only another app's dependencies were installed — an
+// environment difference reported as a test failure, which is the most
+// expensive kind of false alarm: it looks exactly like a real regression.
+const CANDIDATES = ['slides', 'type', 'spaces', 'dash'];
+let esbuild;
+for (const app of CANDIDATES) {
+ const url = new URL(`../../${app}/node_modules/esbuild/lib/main.js`, import.meta.url);
+ try { await access(fileURLToPath(url)); esbuild = await import(url.href); break; } catch { /* next */ }
+}
+if (!esbuild) {
+ throw new Error(
+ `esbuild not found in any of: ${CANDIDATES.map(a => `${a}/node_modules`).join(', ')}. ` +
+ `Run \`npm install\` in one of those app directories.`,
+ );
+}
export async function resolve(specifier, context, nextResolve) {
try {
diff --git a/scripts/test-relay-protocol.ts b/scripts/test-relay-protocol.ts
new file mode 100644
index 00000000..3ef8fe02
--- /dev/null
+++ b/scripts/test-relay-protocol.ts
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// ONE RELAY, ONE WIRE FORMAT, TWO CLIENTS — asserted rather than hoped.
+//
+// `dash/src/sync/online.ts` says of itself that it is "A PORT of
+// slides/src/sync/online.ts, deliberately close to the original". That transport
+// has since moved into `kernel/src/sync/online.ts`, so the port's twin now lives
+// in the kernel — and the two files are still separate text that nobody diffs.
+//
+// WHY THEY ARE STILL SEPARATE, so the next person does not "fix" it in an
+// afternoon: dash's `OnlineTransport` is parameterised by `DashDoc` and dash's
+// `SyncStateJSON` and takes a differently-shaped hooks object, because
+// `DashSync` is not a `SyncEngine` subclass — dash runs a different CRDT engine
+// on purpose (sparse per-row state, so an untouched row costs nothing in the
+// saved file; the kernel engine would put O(rows) in every workbook). Making one
+// call the other is a genericisation of the transport over the doc and state
+// types, not a facade, and it is the kind of change that breaks relay auth
+// quietly.
+//
+// WHAT MUST NOT FORK IS THE PROTOCOL. A deployed worker verifies these exact
+// strings: it pins the room id to a public key, walks an owner→invite→member
+// signature chain, and drops any persisted frame without a valid signature. If
+// one client's idea of `inv.${pub}.${role}.${exp}` ever drifts from the other's,
+// the symptom is not a failing test — it is one app's users silently unable to
+// join the other's rooms, discovered in production, on a relay that cannot be
+// rolled back independently of the shells already in people's files.
+//
+// So this rig diffs the two files on the things that go ON THE WIRE, and
+// nothing else. Comments, types, field order and structure are free to differ —
+// they already do, by design.
+
+import { existsSync, readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, join } from 'node:path'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const DASH = join(root, 'dash/src/sync/online.ts')
+
+/**
+ * The twin moves. It was `slides/src/sync/online.ts`; a kernel refactor is
+ * lifting it to `kernel/src/sync/online.ts` and leaving slides a facade. This
+ * guard follows it rather than pinning one path, so it keeps working across
+ * that move instead of going quiet on the exact day the code is most likely to
+ * drift. If neither is a real transport (both facades, or the layout changed
+ * again), the rig SAYS SO and fails — a protocol guard that silently finds
+ * nothing to compare is worse than no guard, because the green tick is a lie.
+ */
+const TWINS = ['kernel/src/sync/online.ts', 'slides/src/sync/online.ts']
+const twin = TWINS.map((p) => join(root, p)).find((p) => {
+ if (!existsSync(p)) return false
+ // a facade re-exports; a transport has the wire in it
+ return readFileSync(p, 'utf8').includes('ECDSA')
+})
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+if (!twin) {
+ console.log('FAIL neither kernel/src/sync/online.ts nor slides/src/sync/online.ts')
+ console.log(' holds a transport to compare against. The relay protocol is')
+ console.log(' now guarded by nothing. Point TWINS at wherever it went.')
+ process.exit(1)
+}
+console.log(`comparing dash against ${twin.slice(root.length + 1)}\n`)
+const kernel = readFileSync(twin, 'utf8')
+const dash = readFileSync(DASH, 'utf8')
+
+/** Source with comments removed — a wire constant inside a comment is prose. */
+const code = (s: string): string =>
+ s.replace(/\/\*[\s\S]*?\*\//g, '').split('\n')
+ .filter((l) => !l.trim().startsWith('//')).join('\n')
+
+const kCode = code(kernel)
+const dCode = code(dash)
+
+/** Every match of `re`, deduped and sorted — order and count are free to differ. */
+const all = (src: string, re: RegExp): string[] =>
+ [...new Set([...src.matchAll(re)].map((m) => m[0]))].sort()
+
+const same = (re: RegExp, what: string): void => {
+ const k = all(kCode, re)
+ const d = all(dCode, re)
+ ok(k.length > 0, `${what}: the twin actually contains some (guard is live)`)
+ ok(JSON.stringify(k) === JSON.stringify(d),
+ `${what} are identical in both clients${JSON.stringify(k) === JSON.stringify(d) ? '' : `\n twin: ${JSON.stringify(k)}\n dash: ${JSON.stringify(d)}`}`)
+}
+
+console.log('the signature chain the relay verifies')
+// `inv.${pub}.${role}.${exp}` — an owner blessing an invite key.
+// `rev.${pub}` — an owner revoking one. `${i}.${d}` — a frame signature.
+same(/`(inv|rev|mem|own)\.[^`]*`/g, 'signature texts')
+
+console.log('\nthe crypto')
+same(/name: '[A-Za-z-]+'/g, 'algorithm names')
+same(/namedCurve: '[^']+'/g, 'curve')
+same(/hash: '[^']+'/g, 'hash')
+
+console.log('\nthe wire')
+// The possession proof in the query string, and the frame envelope keys.
+same(/[?&](tok|room|pub|sig|inv|role|exp)=/g, 'query parameters')
+same(/'(ping|pong)'/g, 'keepalive frames')
+
+console.log('\nthe timings a relay and a client have to agree about')
+const num = (src: string, name: string): string | null => {
+ const m = new RegExp(`${name}\\s*=\\s*([0-9_]+)`).exec(src)
+ return m ? m[1].replace(/_/g, '') : null
+}
+for (const c of ['PING_MS', 'PONG_GRACE_MS', 'MAX_BACKOFF_MS', 'BASE_BACKOFF_MS']) {
+ const k = num(kCode, c)
+ const d = num(dCode, c)
+ if (k === null && d === null) continue
+ ok(k === d, `${c} agrees (twin ${k}, dash ${d})`)
+}
+
+console.log('\nthe room id, which the relay pins to a key')
+// The room URL is built inline: `${syncHost()}/d/w${b64u.enc(commit)}` for a
+// key-committed room. Both the PATH SEGMENT and the `w`/`r` letter matter —
+// they are what the worker routes and pins on. Get either wrong on one side and
+// that client cannot join rooms the other creates.
+//
+// (An earlier version of this check looked for `'w' +` and found NOTHING in
+// either file, because the prefix lives inside a template literal. The
+// guard-is-live assertion above is what caught it; without that, this rig would
+// have compared two empty lists and reported a confident green.)
+same(/room: `[^`]*`/g, 'room URL template')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) {
+ console.log(`
+The two clients have drifted on something that goes on the wire. That is not a
+style difference: one deployed relay verifies both, so whichever side moved has
+locked its users out of rooms created by the other. Reconcile the strings above
+before shipping either shell.`)
+ process.exit(1)
+}
diff --git a/scripts/test-type-blocks.ts b/scripts/test-type-blocks.ts
new file mode 100644
index 00000000..65ba0606
--- /dev/null
+++ b/scripts/test-type-blocks.ts
@@ -0,0 +1,210 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type block grouping — lists and tables. node scripts/test-type-blocks.ts
+//
+// A list ITEM is a block; the list itself is not in the model. Runs of adjacent
+// `ul`/`ol` blocks are grouped into real <ul>/<ol> elements at render time,
+// nested by `level`. That keeps the document flat, which the redline (aligns on
+// block ids), the caret (blockId + offset) and pagination (measures line boxes
+// through a tree walker) all depend on.
+//
+// Everything interesting therefore lives in ONE pure function, groupBlocks, and
+// two consumers that must agree: the editor builds DOM from its tokens, print
+// builds a string. A list that nests on screen and not on paper is the failure
+// this rig exists to prevent — print already had it, scanning its own output
+// backwards for the last open tag and finding one it had closed.
+
+import { groupBlocks } from '../type/src/render.ts';
+import { parseDoc, emptyDoc, MAX_LIST_LEVEL, MAX_TABLE_COLS, type Block, type BlockKind } from '../type/src/model.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const b = (kind: BlockKind, text: string, level?: number): Block =>
+ ({ id: `${kind}-${text}-${level ?? 0}`, kind, text, ...(level ? { level } : {}) });
+
+/** the token stream as a compact string, so expectations read like the output */
+const shape = (body: Block[]) => groupBlocks(body).map(t =>
+ t.t === 'open' ? `<${t.kind}>` : t.t === 'close' ? `</${t.kind}>`
+ : t.t === 'table' ? `[table ${t.rows.length}x${t.rows[0]?.length ?? 0}${t.head ? ' head' : ''}]`
+ : t.block.text).join(' ');
+
+/** every open has a matching close, in the right order */
+function wellFormed(body: Block[]): boolean {
+ const stack: string[] = [];
+ for (const t of groupBlocks(body)) {
+ if (t.t === 'open') stack.push(t.kind);
+ else if (t.t === 'close') { if (stack.pop() !== t.kind) return false; }
+ }
+ return stack.length === 0;
+}
+
+H('a run of items becomes one list');
+{
+ const body = [b('para', 'before'), b('ul', 'a'), b('ul', 'b'), b('para', 'after')];
+ ok(shape(body) === 'before <ul> a b </ul> after', shape(body));
+ ok(wellFormed(body), 'well formed');
+}
+
+H('nesting by level');
+{
+ const body = [b('ul', 'a'), b('ul', 'a1', 1), b('ul', 'a2', 1), b('ul', 'c')];
+ ok(shape(body) === '<ul> a <ul> a1 a2 </ul> c </ul>', shape(body));
+ ok(wellFormed(body), 'well formed');
+}
+
+H('a change of kind at the same depth starts a new list');
+{
+ // bullets and numbers are different lists even when equally indented —
+ // without this they would share one <ul> and the numbers would vanish
+ const body = [b('ul', 'a'), b('ol', '1')];
+ ok(shape(body) === '<ul> a </ul> <ol> 1 </ol>', shape(body));
+ ok(wellFormed(body), 'well formed');
+}
+
+H('a nested list of the other kind');
+{
+ const body = [b('ol', '1'), b('ul', 'bullet', 1), b('ol', '2')];
+ ok(shape(body) === '<ol> 1 <ul> bullet </ul> 2 </ol>', shape(body));
+ ok(wellFormed(body), 'well formed');
+}
+
+H('unwinding several levels at once');
+{
+ const body = [b('ul', 'a'), b('ul', 'deep', 3), b('para', 'out')];
+ const s = shape(body);
+ ok(s === '<ul> a <ul> <ul> <ul> deep </ul> </ul> </ul> </ul> out', s);
+ ok(wellFormed(body), 'every level is closed before the paragraph');
+}
+
+H('a list that starts indented, and one that ends the document');
+{
+ ok(wellFormed([b('ul', 'orphan', 2)]), 'an item with no parent item still closes');
+ ok(wellFormed([b('para', 'p'), b('ul', 'last')]), 'a trailing list is closed at the end');
+ ok(shape([]) === '', 'an empty document yields nothing');
+}
+
+H('non-list blocks are untouched');
+{
+ const body = [b('h1', 'T'), b('para', 'p'), b('quote', 'q')];
+ ok(shape(body) === 'T p q', shape(body));
+ ok(groupBlocks(body).every(t => t.t === 'block'), 'no list tokens at all');
+}
+
+H('the parser accepts lists and clamps the level');
+{
+ const doc = emptyDoc();
+ const json = JSON.stringify({
+ ...doc,
+ body: [
+ { id: 'a', kind: 'ul', text: 'item' },
+ { id: 'b', kind: 'ol', text: 'num', level: 2 },
+ { id: 'c', kind: 'ul', text: 'deep', level: 99 },
+ { id: 'd', kind: 'para', text: 'p', level: 3 },
+ ],
+ });
+ const r = parseDoc(json);
+ ok(r.ok, 'a document with lists parses');
+ if (r.ok) {
+ ok(r.doc.body[0].kind === 'ul' && r.doc.body[1].kind === 'ol', 'both list kinds survive');
+ ok(r.doc.body[1].level === 2, 'a valid level survives');
+ ok(r.doc.body[2].level === MAX_LIST_LEVEL,
+ `a runaway level is clamped to ${MAX_LIST_LEVEL} (got ${r.doc.body[2].level})`);
+ ok(r.doc.body[3].level === undefined, 'a level on a paragraph is dropped, not kept as dead data');
+ ok(r.repaired.some(x => /clamped/.test(x)), 'and the clamp is reported, not silent');
+ }
+}
+
+H('a level is never trusted to be sane');
+{
+ // Generators produce these; the renderer must not be the thing that notices.
+ for (const lv of [-1, 0.5, 1e9]) {
+ const body = [b('ul', 'x'), { ...b('ul', 'y'), level: lv } as Block];
+ ok(wellFormed(body), `level ${lv} still produces balanced output`);
+ }
+}
+
+
+// ───────────────────────────────────────────────────────────────── tables
+//
+// A CELL is a block too, and for a sharper reason than list items: the redline
+// aligns on block ids, so per-cell blocks give per-cell review. A table as one
+// block would report "the payment table changed" when a single figure moved.
+
+const cell = (table: string, cols: number, text: string, head?: boolean): Block =>
+ ({ id: `${table}-${text}`, kind: 'cell', text, cell: { table, cols, ...(head ? { head: true } : {}) } });
+
+H('cells group into a grid');
+{
+ const body = [
+ b('para', 'before'),
+ cell('t1', 2, 'a'), cell('t1', 2, 'b'), cell('t1', 2, 'c'), cell('t1', 2, 'd'),
+ b('para', 'after'),
+ ];
+ ok(shape(body) === 'before [table 2x2] after', shape(body));
+}
+
+H('a header row is recognised');
+{
+ const body = [cell('t', 2, 'H1', true), cell('t', 2, 'H2', true), cell('t', 2, 'a'), cell('t', 2, 'b')];
+ const tok = groupBlocks(body).find(t => t.t === 'table')!;
+ ok(tok.t === 'table' && tok.head === true, 'head is taken from the first cell');
+ ok(tok.t === 'table' && tok.rows.length === 2 && tok.rows[0].length === 2, '2x2 including the header');
+}
+
+H('two tables side by side stay separate');
+{
+ const body = [cell('t1', 1, 'a'), cell('t2', 1, 'b')];
+ ok(shape(body) === '[table 1x1] [table 1x1]', shape(body));
+}
+
+H('a short final row is kept, not dropped');
+{
+ // five cells in a three-column table: the model can say this and the reader
+ // must still see every cell they wrote
+ const body = [cell('t', 3, 'a'), cell('t', 3, 'b'), cell('t', 3, 'c'), cell('t', 3, 'd'), cell('t', 3, 'e')];
+ const tok = groupBlocks(body).find(t => t.t === 'table')!;
+ ok(tok.t === 'table' && tok.rows.length === 2, 'two rows');
+ ok(tok.t === 'table' && tok.rows[1].length === 2, 'the last row holds the two remaining cells');
+ const all = tok.t === 'table' ? tok.rows.flat().map(x => x.text).join('') : '';
+ ok(all === 'abcde', `no cell is lost (${all})`);
+}
+
+H('a disagreement about the column count is settled by majority');
+{
+ // one cell edited by a tool that got `cols` wrong must not reshape the table
+ const body = [cell('t', 3, 'a'), cell('t', 3, 'b'), cell('t', 3, 'c'),
+ { ...cell('t', 3, 'd'), cell: { table: 't', cols: 7 } } as Block,
+ cell('t', 3, 'e'), cell('t', 3, 'f')];
+ const tok = groupBlocks(body).find(t => t.t === 'table')!;
+ ok(tok.t === 'table' && tok.rows[0].length === 3, `majority wins (got ${tok.t === 'table' ? tok.rows[0].length : '?'})`);
+}
+
+H('a table interrupted by a paragraph is two tables');
+{
+ const body = [cell('t', 1, 'a'), b('para', 'interrupt'), cell('t', 1, 'b')];
+ ok(shape(body) === '[table 1x1] interrupt [table 1x1]',
+ `same id, but not adjacent — ${shape(body)}`);
+}
+
+H('the parser repairs a cell it cannot place');
+{
+ const doc = emptyDoc();
+ const r = parseDoc(JSON.stringify({ ...doc, body: [
+ { id: 'ok', kind: 'cell', text: 'fine', cell: { table: 't', cols: 2 } },
+ { id: 'noref', kind: 'cell', text: 'orphan' },
+ { id: 'wide', kind: 'cell', text: 'huge', cell: { table: 't2', cols: 999 } },
+ ] }));
+ ok(r.ok, 'it still parses');
+ if (r.ok) {
+ ok(r.doc.body[0].kind === 'cell', 'a good cell survives');
+ ok(r.doc.body[1].kind === 'para', 'a cell with no placement becomes a paragraph');
+ ok(r.doc.body[2].cell?.cols === MAX_TABLE_COLS, `runaway columns clamped to ${MAX_TABLE_COLS}`);
+ ok(r.repaired.length >= 2, 'and both repairs are reported');
+ }
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-chrome.ts b/scripts/test-type-chrome.ts
new file mode 100644
index 00000000..cf40feab
--- /dev/null
+++ b/scripts/test-type-chrome.ts
@@ -0,0 +1,181 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Where a control LIVES — the gate for it.
+//
+// node scripts/test-type-chrome.ts
+//
+// The app reached a state where "Cross-reference" was in the Insert menu AND
+// in ⋯, "Equation block" was an action while "Formula" was an insert, and
+// "Page break here" was an action competing with the breakBefore checkbox that
+// does the same thing. None of it was decided; each feature picked a home as it
+// landed, and the result reads as carelessness to anyone using it.
+//
+// The rule, from slides:
+//
+// Insert — anything that PUTS SOMETHING IN the document. One home.
+// ⋯ — document-level actions you do occasionally: snapshot, review,
+// sign, print, import, about.
+// panel — every property.
+// bar — only what is reached for mid-sentence.
+//
+// This is a SOURCE-level check on purpose. Booting the app to read its live
+// registry would need a DOM, and the thing being guarded is a fact about how
+// the features register themselves — which is visible in the text, and stays
+// visible when a feature is added by someone who never runs the app.
+
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+const SRC = join(import.meta.dirname, '..', 'type', 'src');
+
+let checks = 0, bad = 0;
+const ok = (cond: boolean, msg: string) => {
+ checks++;
+ if (cond) { console.log(` ok ${msg}`); return; }
+ bad++; console.log(` FAIL ${msg}`);
+};
+
+// A label is written `label: t('X')`, `label: () => t('X')`, or
+// `get label() { return <anything with t('X') in it>; }` — the last of which
+// can be a TERNARY, because a toggle's label depends on its state:
+//
+// get label() { return hidden() ? t('Show comments') : t('Hide comments'); }
+//
+// So: find where the label starts, cut to the next key of the object literal,
+// and take EVERY t('…') in between. Matching only the first one silently
+// dropped every toggle in the app — which the coverage assertion below caught,
+// and which is the only reason this comment exists.
+const labelsIn = (block: string): string[] => {
+ const start = block.search(/(?:get )?label\s*[(:]/);
+ if (start < 0) return [];
+ const rest = block.slice(start);
+ // the next sibling key ends the label region; `run:` always follows
+ const end = rest.search(/\n\s*(?:get\s+)?(?:run|order|icon|id|title)\s*[(:]/);
+ const region = end < 0 ? rest : rest.slice(0, end);
+ return [...region.matchAll(/t\(\s*'([^']+)'/g)].map(m => m[1]);
+};
+
+// Registration calls are found by scanning forward to the balanced close. A
+// naive /registerTool\({[^}]*}\)/ stops at the first nested `}` — which every
+// one of these has, in a getter or an arrow body — and silently matches
+// nothing useful. Counting braces is the difference between a gate and a
+// decoration.
+const callsOf = (src: string, fn: string): string[] => {
+ const out: string[] = [];
+ let i = 0;
+ for (;;) {
+ const at = src.indexOf(`${fn}({`, i);
+ if (at < 0) break;
+ let depth = 0, j = at + fn.length + 1;
+ for (; j < src.length; j++) {
+ if (src[j] === '{') depth++;
+ else if (src[j] === '}' && --depth === 0) { j++; break; }
+ }
+ out.push(src.slice(at, j));
+ i = j;
+ }
+ return out;
+};
+
+const inserts = new Map<string, string>(); // label -> file
+const actions = new Map<string, string>();
+
+for (const f of readdirSync(SRC).filter(n => n.endsWith('.ts'))) {
+ const src = readFileSync(join(SRC, f), 'utf8');
+ for (const call of callsOf(src, 'registerTool')) {
+ if (!/group:\s*'insert'/.test(call)) continue;
+ for (const l of labelsIn(call)) inserts.set(l, f);
+ }
+ for (const call of callsOf(src, 'registerMenuItem')) {
+ for (const l of labelsIn(call)) actions.set(l, f);
+ }
+}
+
+// The ⋯ menu is not built only from the registry: main.ts ships a handful of
+// buttons in its own markup (snapshot, review, sign, print, about) and labels
+// them by id. Scanning only registerMenuItem saw ONE ⋯ entry where the running
+// app shows seven, so the rule would have been enforced against a seventh of
+// the menu.
+const main = readFileSync(join(SRC, 'main.ts'), 'utf8');
+// Slice to </header>, NOT to the first </div>: the menu contains
+// `<div class="t-menu-sep"></div>` separators, so the first close tag after
+// id="moreMenu" belongs to a separator two buttons in. Cutting there found ms
+// and mc and stopped — five of the seven ⋯ entries were invisible to a gate
+// whose whole job is to see all of them. Same mistake as the one callsOf()
+// above is written to avoid, made again twenty lines later.
+const menuMarkup = main.slice(main.indexOf('id="moreMenu"'), main.indexOf('</header>'));
+for (const m of menuMarkup.matchAll(/<button id="([a-z]+)"/g)) {
+ const id = m[1];
+ const lbl = main.match(new RegExp(`label\\('${id}',[^;]*?t\\(\\s*'([^']+)'`, 's'));
+ if (lbl) actions.set(lbl[1], 'main.ts');
+}
+
+console.log(`\ninsert menu: ${[...inserts.keys()].join(', ')}`);
+console.log(`⋯ menu: ${[...actions.keys()].join(', ')}\n`);
+
+// The gate must be able to FAIL. If the scan finds nothing it would pass every
+// assertion below while proving nothing at all — the most comfortable kind of
+// broken test.
+ok(inserts.size >= 5, `the scan actually found insert tools (${inserts.size})`);
+ok(actions.size >= 4, `the scan actually found ⋯ actions (${actions.size})`);
+
+// 1. Nothing lives in two places.
+const norm = (s: string) => s.replace(/[…\.]+$/, '').replace(/\s*\(.*\)$/, '').trim().toLowerCase();
+const insertNorm = new Map([...inserts].map(([l, f]) => [norm(l), f]));
+for (const [label, file] of actions) {
+ const clash = insertNorm.get(norm(label));
+ ok(clash === undefined,
+ `"${label}" (${file}) is not also an Insert tool${clash ? ` — duplicated from ${clash}` : ''}`);
+}
+
+// 2. ⋯ holds no INSERTS. A verb that puts something in the document belongs in
+// the Insert menu, whatever it is called.
+const INSERTY = /^(insert|add|new)\b|\b(block|equation|reference|citation|caption|picture|image|table|formula)\b/i;
+const IMPORT_OK = /^import\b/i; // importing a bibliography is document-level
+for (const [label, file] of actions) {
+ ok(!INSERTY.test(label) || IMPORT_OK.test(label),
+ `⋯ item "${label}" (${file}) is not an insert wearing an action's clothes`);
+}
+
+// 3. ⋯ holds no PROPERTIES. "Do not number this heading" and "Page break here"
+// were both properties of the block under the caret: they have a STATE, and
+// an action can only offer to flip it, never show it.
+const PROPERTYISH = /^(do not|don't|toggle)\b|\bthis (heading|paragraph|block)\b|^page break/i;
+for (const [label, file] of actions) {
+ ok(!PROPERTYISH.test(label),
+ `⋯ item "${label}" (${file}) is not a property of the selection`);
+}
+
+console.log('\n— every element the chrome reaches for actually exists —');
+{
+ // byId() is `document.getElementById(id) as T` — it returns null for a
+ // missing id and the cast hides that from tsc. label() then dereferences it
+ // and the whole boot dies AFTER the page has rendered its paper, so the app
+ // looks fine and simply never publishes window.bento.
+ //
+ // This has now happened twice: once when buttons moved into the ⋯ menu, and
+ // again when two of them were REMOVED from it and their label() calls were
+ // left behind. Both times the symptom was a working-looking page.
+ const src = readFileSync(join(SRC, 'main.ts'), 'utf8');
+
+ const declared = new Set<string>();
+ for (const m of src.matchAll(/\bid="([A-Za-z][\w-]*)"/g)) declared.add(m[1]);
+ // ids created in script rather than in the template
+ for (const m of src.matchAll(/\.id\s*=\s*'([^']+)'/g)) declared.add(m[1]);
+ for (const m of src.matchAll(/\.id\s*=\s*`([^`$]+)`/g)) declared.add(m[1]);
+
+ const referenced = new Map<string, string>();
+ for (const re of [/\blabel\(\s*'([^']+)'/g, /\bbyId(?:<[^>]*>)?\(\s*'([^']+)'/g]) {
+ for (const m of src.matchAll(re)) referenced.set(m[1], m[0].split('(')[0]);
+ }
+
+ ok(declared.size > 5, `the scan found the template's ids (${declared.size})`);
+ ok(referenced.size > 5, `and the lookups (${referenced.size})`);
+ for (const [id, how] of referenced) {
+ ok(declared.has(id), `${how}('${id}') refers to an element that exists`);
+ }
+}
+
+console.log(`\n${checks - bad}/${checks} checks passed`);
+if (bad) process.exit(1);
diff --git a/scripts/test-type-cite.ts b/scripts/test-type-cite.ts
new file mode 100644
index 00000000..cb04c1f4
--- /dev/null
+++ b/scripts/test-type-cite.ts
@@ -0,0 +1,451 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type citations + bibliography rig.
+//
+// node scripts/test-type-cite.ts (Node ≥ 23.6 strips types natively)
+//
+// WHAT THIS PROVES. Three properties, and each one is a bug that would only
+// show up in somebody's finished thesis:
+//
+// 1. THE BIBTEX READER IS TOTAL. It is fed a real .bib, and then a broken
+// one — unclosed braces, a stray @, an entry with no key, a duplicate
+// key, a field that is not `name = value`. It must never throw, and it
+// must SAY what it did not import. A parser that throws loses the whole
+// paste; one that stays quiet loses one source, which is worse, because
+// nobody notices until a reference list is one line short.
+//
+// 2. THE OUTPUT IS DERIVED AND STABLE. Numbers come from first appearance,
+// the author–year list is alphabetical, and neither is stored. So the
+// same input must give byte-identical output, twice in a row and after
+// the entry map is rebuilt in a different insertion order — otherwise
+// two readers of one file see different numbers, and "see [4]" points at
+// the wrong work.
+//
+// 3. A MISSING ENTRY IS LOUD. A citation whose source is gone renders
+// "[?key]" in both styles and is listed as missing. Silence here is the
+// one failure a reviewer cannot catch by reading.
+//
+// Everything under test is pure, so this rig exercises exactly the code the
+// browser runs — no DOM, no stubs.
+
+import { parseBibtex, decodeTex } from '../type/src/cite/bibtex.ts';
+import {
+ bibliography, citationText, collectCites, familyName, inTextAuthors, initials,
+ parseNames, referenceText, resolve, sortKey,
+ type CitedBlock,
+} from '../type/src/cite/format.ts';
+import {
+ readBibliography, readCiteRef, readStyle, validKey,
+ type BibEntry, type Bibliography, type CiteStyle,
+} from '../type/src/cite/types.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+const eq = (got: unknown, want: unknown, m: string) =>
+ ok(JSON.stringify(got) === JSON.stringify(want), `${m}${JSON.stringify(got) === JSON.stringify(want) ? '' : `\n got ${JSON.stringify(got)}\n want ${JSON.stringify(want)}`}`);
+
+const map = (r: ReturnType<typeof parseBibtex>): Bibliography =>
+ Object.fromEntries(r.entries.map(e => [e.key, e.entry]));
+
+// ─────────────────────────────────────────────────── a small real library
+
+const LIB = String.raw`
+% a .bib usually opens with junk like this
+@string{cj = "The Computer Journal"}
+@preamble{ "\newcommand{\noop}[1]{}" }
+
+@book{knuth1984,
+ author = {Knuth, Donald E.},
+ title = {The {TeX}book},
+ publisher = {Addison-Wesley},
+ address = {Reading, MA},
+ edition = {1st},
+ year = 1984
+}
+
+@article{knuth1984lit,
+ author = {Knuth, Donald E.},
+ title = {Literate Programming},
+ journal = cj,
+ volume = {27},
+ number = {2},
+ pages = {97--111},
+ year = {1984},
+ doi = {10.1093/comjnl/27.2.97}
+}
+
+@inproceedings{lamport1982,
+ author = {Lamport, Leslie and Shostak, Robert and Pease, Marshall},
+ title = {The {B}yzantine Generals Problem},
+ booktitle = {Proceedings of PODC},
+ address = {New York},
+ pages = {382-401},
+ year = {1982}
+}
+
+@techreport{inria1998,
+ author = {M\"{u}ller, J\o rgen and Bo\ss{}, Ren\'ee},
+ title = {On \'Etale Sites},
+ institution = {INRIA},
+ address = {Rocquencourt},
+ number = {RR-42},
+ year = {1998}
+}
+
+@misc{bento2026,
+ author = {Bento Project,},
+ title = {Self-contained office documents},
+ howpublished = {Web},
+ url = {https://bento.page},
+ year = {2026}
+}
+`;
+
+const lib = parseBibtex(LIB);
+const BIB = map(lib);
+
+H('every supported entry type parses');
+{
+ eq(lib.entries.map(e => e.key),
+ ['knuth1984', 'knuth1984lit', 'lamport1982', 'inria1998', 'bento2026'],
+ 'all five entries, in file order');
+ eq(lib.entries.map(e => e.entry.type),
+ ['book', 'article', 'inproceedings', 'techreport', 'misc'],
+ '@book @article @inproceedings @techreport @misc keep their types');
+ eq(BIB.knuth1984.publisher, 'Addison-Wesley', '@book keeps its publisher');
+ eq(BIB.knuth1984lit.journal, 'The Computer Journal', '@article resolves the @string macro for its journal');
+ eq(BIB.knuth1984lit.pages, '97–111', '`--` in a page range becomes an en dash');
+ eq(BIB.lamport1982.booktitle, 'Proceedings of PODC', '@inproceedings keeps its booktitle');
+ eq(BIB.inria1998.institution, 'INRIA', '@techreport keeps its institution');
+ eq(BIB.inria1998.number, 'RR-42', 'and its report number');
+ eq(BIB.bento2026.url, 'https://bento.page', '@misc keeps its url');
+ eq(BIB.knuth1984.year, '1984', 'a bare number is a value, no braces needed');
+ ok(lib.skipped.every(s => !/knuth|lamport|inria|bento/.test(s)),
+ `a clean library reports nothing lost — ${JSON.stringify(lib.skipped)}`);
+}
+
+H('a type this app does not model still cites');
+{
+ const r = parseBibtex('@phdthesis{t1, author={Ada Lovelace}, title={A Thesis}, year={1843}}');
+ eq(r.entries[0]?.entry.type, 'misc', '@phdthesis is imported as @misc');
+ eq(r.entries[0]?.entry.title, 'A Thesis', 'with its fields intact');
+ ok(r.skipped.some(s => s.includes('phdthesis')), 'and the substitution is reported, not silent');
+ const c = parseBibtex('@conference{c1, title={Talk}, year={2000}}');
+ eq(c.entries[0]?.entry.type, 'inproceedings', '@conference is an alias for @inproceedings');
+}
+
+H('brace-quoted titles keep their capitals');
+{
+ const r = map(parseBibtex(String.raw`
+ @book{a, title = {The {TeX}book}}
+ @article{b, title = {{DNA} sequencing and {RNA}}}
+ @misc{c, title = {A study of {the Baltic Sea} in {W}inter}}
+ `));
+ eq(r.a.title, 'The TeXbook', 'protective braces come off, TeX stays TeX');
+ eq(r.b.title, 'DNA sequencing and RNA', 'a leading brace group is not mistaken for the value delimiter');
+ eq(r.c.title, 'A study of the Baltic Sea in Winter', 'nested groups unwrap without losing a character');
+ // The reason this is safe: we never case-fold a title, so the protection is
+ // structural rather than semantic — the braces come off and nothing else moves.
+ eq(r.a.title, decodeTex('The {TeX}book'), 'the decoder alone accounts for it');
+}
+
+H('accent commands become real characters');
+{
+ const cases: Array<[string, string]> = [
+ [String.raw`M\"uller`, 'Müller'],
+ [String.raw`M\"{u}ller`, 'Müller'],
+ [String.raw`Ren\'ee`, 'Renée'],
+ [String.raw`Ren\'{e}e`, 'Renée'],
+ [String.raw`\`a la carte`, 'à la carte'],
+ [String.raw`c\^ote`, 'côte'],
+ [String.raw`ma\~nana`, 'mañana'],
+ [String.raw`\c{c}edilla`, 'çedilla'],
+ [String.raw`\v{s}koda`, 'škoda'],
+ [String.raw`\={a}`, 'ā'],
+ [String.raw`\.z`, 'ż'],
+ [String.raw`\u{a}`, 'ă'],
+ [String.raw`\H{o}`, 'ő'],
+ [String.raw`\k{a}`, 'ą'],
+ [String.raw`\r{a}`, 'å'],
+ [String.raw`Wei\ss{}bier`, 'Weißbier'],
+ [String.raw`\o rsted`, 'ørsted'],
+ [String.raw`\AA ngstr\"om`, 'Ångström'],
+ [String.raw`\ae ther and \oe uvre`, 'æther and œuvre'],
+ [String.raw`\L \'od\'z`, 'Łódź'], // the space after \L terminates the command, as in TeX
+ [String.raw`\'{\i}sla`, 'ísla'],
+ [String.raw`a--b`, 'a–b'],
+ [String.raw`a---b`, 'a—b'],
+ ['``quoted\'\'', '“quoted”'],
+ [String.raw`AT\&T 50\% \$5 a\_b`, 'AT&T 50% $5 a_b'],
+ [String.raw`\textbf{bold} and \emph{italic}`, 'bold and italic'],
+ [String.raw`P\'erez\nolinebreak`, 'Pérez'],
+ [String.raw`a~b`, 'a b'],
+ ];
+ for (const [src, want] of cases) eq(decodeTex(src), want, `${src.replace(/\\/g, '\\')} → ${want}`);
+ eq(BIB.inria1998.author, 'Müller, Jørgen and Boß, Renée', 'accents survive the whole parse, not just the decoder');
+ eq(BIB.inria1998.title, 'On Étale Sites', 'and so does a title-leading accent');
+}
+
+H('a malformed .bib does not throw, and says what it skipped');
+{
+ const bad = String.raw`
+@book{good1, title = {Fine}, year = {2000}}
+@book{good1, title = {A second entry with the same key}}
+@book{, title = {No key at all}}
+@article{broken, title = {Never closed
+@
+@nonsense
+@misc{ugly, this is not a field, title = {Still here}}
+@book{good2, title = {After the wreckage}}
+`;
+ let r: ReturnType<typeof parseBibtex> | undefined;
+ let threw = '';
+ try { r = parseBibtex(bad); } catch (e) { threw = String(e); }
+ ok(!threw, `it returned rather than throwing${threw ? ` — ${threw}` : ''}`);
+ const keys = (r?.entries ?? []).map(e => e.key);
+ eq(keys, ['good1', 'ugly', 'good2'],
+ 'it kept every entry it could read — including the ones AFTER the unterminated @article');
+ ok(r!.skipped.some(s => s.includes('good1') && s.includes('kept the first')),
+ 'the duplicate key is reported, and the FIRST definition wins');
+ ok(r!.skipped.some(s => s.includes('no citation key')), 'the keyless entry is reported');
+ ok(r!.skipped.some(s => s.includes('never closed')), 'the unterminated entry is reported');
+ ok(r!.skipped.some(s => s.includes('reading continued')),
+ 'and the scan resumes after it rather than abandoning the rest of the file');
+ ok(r!.skipped.some(s => s.includes('stray "@"')), 'the stray @ is reported');
+ ok(r!.skipped.some(s => s.includes('ugly') && s.includes('field = value')),
+ 'the junk inside an otherwise-good entry is reported and the entry survives');
+ eq(map(r!).ugly.title, 'Still here', 'and the good field beside the junk is kept');
+
+ // the pathological shapes, which must each return rather than hang or blow the stack
+ for (const [label, src] of [
+ ['empty input', ''],
+ ['no @ anywhere', 'just some prose about Knuth'],
+ ['only an @', '@'],
+ ['a wall of open braces', '@book{k, title = {' + '{'.repeat(5000)],
+ ['a wall of backslashes', '@book{k, title = {' + '\\'.repeat(5000) + '}}'],
+ ['an unterminated quote', '@book{k, title = "never closed}'],
+ ['a lone close brace', '}}}}'],
+ ['a nul byte', '@book{k, title = {ab}}'],
+ ] as Array<[string, string]>) {
+ let out = '', bang = '';
+ try { out = JSON.stringify(parseBibtex(src)).slice(0, 0); } catch (e) { bang = String(e); }
+ ok(!bang && out === '', `${label}: returned a result${bang ? ` — ${bang}` : ''}`);
+ }
+ eq(map(parseBibtex('@book{k, title = {ab‮c}}')).k?.title, 'ab c'.replace(' ', ''),
+ 'control characters and bidi overrides are stripped from a value');
+ eq(parseBibtex(undefined).entries.length, 0, 'a non-string input is nothing to read, not a crash');
+}
+
+H('pasted BibTeX cannot become markup');
+{
+ const r = map(parseBibtex(
+ '@misc{x, title = {<script>alert(1)</script>}, author = {O"Brien & Sons,}, url = {javascript:alert(1)}}'));
+ eq(r.x.title, '<script>alert(1)</script>',
+ 'angle brackets stay ORDINARY CHARACTERS here — escaping is the renderer\'s job, at the DOM seam');
+ ok(!validKey('<img src=x>'), 'a key that could be mistaken for markup is not a valid key');
+ ok(!validKey('a b'), 'nor is one with a space, which is how keys are packed into one attribute');
+ ok(validKey('knuth1984'), 'an ordinary key is fine');
+ ok(validKey('van-der-waals:1873'), 'and so are the punctuation marks real keys use');
+}
+
+H('@string macros and concatenation');
+{
+ const r = map(parseBibtex(String.raw`
+ @string{acm = "ACM"}
+ @string{tocs = acm # " Transactions on Computer Systems"}
+ @article{a, journal = tocs, month = jul, title = "Quoted " # "and joined"}
+ @article{b, journal = nosuchmacro}
+ `));
+ eq(r.a.journal, 'ACM Transactions on Computer Systems', 'a macro built from another macro resolves');
+ eq(r.a.title, 'Quoted and joined', 'two quoted strings concatenate with #');
+ eq(r.a.month, 'July', 'the built-in month macros are defined');
+ eq(r.b.journal, 'nosuchmacro', 'an undefined macro is used as written rather than losing the field');
+}
+
+// ────────────────────────────────────────────────────────────────── names
+
+H('names decompose both ways round');
+{
+ const n = (s: string) => parseNames(s).names;
+ eq(n('Donald E. Knuth')[0], { last: 'Knuth', first: 'Donald E.', von: '', jr: '' }, 'First von Last');
+ eq(n('Knuth, Donald E.')[0], { last: 'Knuth', first: 'Donald E.', von: '', jr: '' }, 'von Last, First');
+ eq(n('Ludwig van Beethoven')[0], { last: 'Beethoven', first: 'Ludwig', von: 'van', jr: '' }, 'a particle joins the surname');
+ eq(n('de la Vega, Jr., Maria')[0], { last: 'Vega', first: 'Maria', von: 'de la', jr: 'Jr.' }, 'von Last, Jr, First');
+ eq(familyName(n('Ludwig van Beethoven')[0]), 'van Beethoven', 'and the family name keeps it');
+ eq(n('Bento Project,')[0], { last: 'Bento Project', first: '', von: '', jr: '' },
+ 'a trailing comma marks an institutional author, which is never initialised');
+ eq(initials('Donald E.'), 'D. E.', 'initials');
+ eq(initials('Jean-Paul'), 'J.-P.', 'hyphenated given names keep the hyphen');
+ eq(parseNames('A. One and B. Two and others').etAl, true, '"and others" sets et al.');
+ eq(parseNames(undefined).names.length, 0, 'a missing author field is no names, not a crash');
+}
+
+H('two authors versus many — the et al. rules');
+{
+ const mk = (author: string): BibEntry => ({ type: 'article', author, title: 'T', year: '1999' });
+ eq(inTextAuthors(mk('Knuth, Donald E.')), 'Knuth', 'one author is named');
+ eq(inTextAuthors(mk('Knuth, Donald E. and Lamport, Leslie')), 'Knuth & Lamport',
+ 'two authors are both named, joined with &');
+ eq(inTextAuthors(mk('Knuth, D. and Lamport, L. and Pease, M.')), 'Knuth et al.',
+ 'three or more collapse to et al. from the first citation (APA 7)');
+ eq(inTextAuthors(mk('Knuth, D. and others')), 'Knuth et al.', '"and others" collapses too');
+ eq(inTextAuthors({ type: 'misc', title: 'A work with no author' }), 'A work with no author',
+ 'with no author at all the title stands in');
+
+ const six = 'A, One and B, Two and C, Three and D, Four and E, Five and F, Six';
+ const seven = `${six} and G, Seven`;
+ ok(referenceText(mk(six), 'numeric').startsWith('O. A, T. B, T. C, F. D, F. E, and S. F,'),
+ 'IEEE lists six authors in full');
+ ok(referenceText(mk(seven), 'numeric').startsWith('O. A et al.,'),
+ 'and gives up at seven — the style\'s own ceiling, not ours');
+ ok(referenceText(mk('Knuth, D. and Lamport, L.'), 'author-year').startsWith('Knuth, D., & Lamport, L.'),
+ 'APA joins two with ", &"');
+ ok(referenceText(mk(six), 'author-year').includes(', & S. F') === false,
+ 'APA reference-list names are inverted, so the last one is "F, S." not "S. F"');
+}
+
+// ──────────────────────────────────────────────────────── styles and order
+
+/** A body citing: [knuth1984], then [lamport1982 + knuth1984lit], then a
+ * missing key, then inria1998 — deliberately NOT alphabetical order. */
+const BODY: CitedBlock[] = [
+ { id: 'b1', cites: [{ at: 30, keys: ['knuth1984'] }] },
+ { id: 'b2', cites: [{ at: 12, keys: ['lamport1982', 'knuth1984lit'] }, { at: 4, keys: ['bento2026'] }] },
+ { id: 'b3', cites: [{ at: 0, keys: ['ghost1999'] }, { at: 9, keys: ['inria1998'], locator: 'p. 34' }] },
+];
+
+/** A citation by where it sits, so the checks below cannot drift when the
+ * fixture is edited — indexing into `cites` silently pointed at the wrong
+ * citation once, because b2's list is written out of offset order on purpose. */
+const cite = (blockId: string, at: number) =>
+ BODY.find(b => b.id === blockId)!.cites!.find(c => c.at === at)!;
+
+H('citations are collected in document order, and offsets sort within a block');
+{
+ eq(collectCites(BODY).map(s => `${s.blockId}@${s.ref.at}`),
+ ['b1@30', 'b2@4', 'b2@12', 'b3@0', 'b3@9'],
+ 'block order outside, offset order inside — b2\'s citation at 4 comes before the one at 12');
+}
+
+H('numeric (IEEE-ish)');
+{
+ const res = resolve(BODY, BIB, 'numeric');
+ eq(res.number, { knuth1984: 1, bento2026: 2, lamport1982: 3, knuth1984lit: 4, inria1998: 5 },
+ 'numbered by FIRST APPEARANCE, so [1] is the first reference a reader meets');
+ eq(citationText(cite('b1', 30), res, BIB), '[1]', 'a single citation');
+ eq(citationText(cite('b2', 12), res, BIB), '[3], [4]', 'a multi-key citation lists each number');
+ eq(citationText(cite('b3', 9), res, BIB), '[5, p. 34]', 'a locator rides inside the bracket');
+ const lines = bibliography(res, BIB);
+ eq(lines.map(l => l.label), ['[1]', '[2]', '[3]', '[4]', '[5]'], 'the list is labelled and in citation order');
+ eq(lines[0].text, 'D. E. Knuth, The TeXbook, 1st ed. Reading, MA: Addison-Wesley, 1984.',
+ '@book: title unquoted, edition, place: publisher, year');
+ eq(lines[3].text,
+ 'D. E. Knuth, "Literate Programming," The Computer Journal, vol. 27, no. 2, pp. 97–111, 1984. ' +
+ '[Online]. Available: https://doi.org/10.1093/comjnl/27.2.97',
+ '@article: quoted title with the comma inside the quotes, then journal, vol, no, pages, year');
+ eq(lines[2].text, 'L. Lamport, R. Shostak, and M. Pease, "The Byzantine Generals Problem," ' +
+ 'in Proceedings of PODC, New York, pp. 382–401, 1982.',
+ '@inproceedings: "in <booktitle>", and a plain hyphen page range is normalised to an en dash');
+ eq(lines[4].text, 'J. Müller and R. Boß, "On Étale Sites," INRIA, Rocquencourt, Tech. Rep. RR-42, 1998.',
+ '@techreport: institution, address, report number');
+ eq(lines[1].text, 'Bento Project, "Self-contained office documents," Web, 2026. ' +
+ '[Online]. Available: https://bento.page',
+ '@misc: howpublished and the online availability note');
+}
+
+H('author–year (APA-ish)');
+{
+ const res = resolve(BODY, BIB, 'author-year');
+ eq(res.number, {}, 'nothing is numbered');
+ eq(res.order, ['bento2026', 'knuth1984lit', 'knuth1984', 'lamport1982', 'inria1998'],
+ 'the list is alphabetical by author, not by first appearance — and two works ' +
+ 'by one author in one year are ordered by TITLE, so Literate Programming ' +
+ 'precedes The TeXbook');
+ eq(res.suffix, { knuth1984lit: 'a', knuth1984: 'b' },
+ 'the disambiguating letters follow that order: 1984a is the one printed first');
+ eq(citationText(cite('b1', 30), res, BIB), '(Knuth, 1984b)', 'and the citation carries the letter');
+ eq(citationText(cite('b2', 12), res, BIB), '(Knuth, 1984a; Lamport et al., 1982)',
+ 'a multi-key citation is joined with "; " IN LIST ORDER, not click order');
+ eq(citationText(cite('b3', 9), res, BIB), '(Müller & Boß, 1998, p. 34)', 'the locator follows the year');
+ eq(citationText({ at: 0, keys: ['knuth1984'], suppressAuthor: true }, res, BIB), '(1984b)',
+ 'suppressAuthor is for a sentence that already said "Knuth"');
+ const lines = bibliography(res, BIB);
+ eq(lines.map(l => l.label), ['', '', '', '', ''], 'an author–year list carries no labels');
+ eq(lines[2].text, 'Knuth, D. E. (1984b). The TeXbook (1st ed.). Addison-Wesley.', '@book');
+ eq(lines[1].text, 'Knuth, D. E. (1984a). Literate Programming. The Computer Journal, 27(2), 97–111. ' +
+ 'https://doi.org/10.1093/comjnl/27.2.97', '@article, with volume(issue) and the DOI as a URL');
+ eq(lines[3].text, 'Lamport, L., Shostak, R., & Pease, M. (1982). The Byzantine Generals Problem. ' +
+ 'In Proceedings of PODC (pp. 382–401).', '@inproceedings');
+ eq(lines[4].text, 'Müller, J., & Boß, R. (1998). On Étale Sites (Report No. RR-42). INRIA.', '@techreport');
+ eq(referenceText({ type: 'book', author: 'Nobody, N.', title: 'Undated' }, 'author-year'),
+ 'Nobody, N. (n.d.). Undated.', 'a work with no year is n.d., not blank');
+}
+
+H('a citation to a missing entry degrades VISIBLY');
+{
+ for (const style of ['numeric', 'author-year'] as CiteStyle[]) {
+ const res = resolve(BODY, BIB, style);
+ eq(res.missing, ['ghost1999'], `${style}: the missing key is reported`);
+ // The marker keeps the style's own wrapper — "(…)" in author–year — so it
+ // reads as a citation that went wrong rather than as loose stray text.
+ eq(citationText(cite('b3', 0), res, BIB), style === 'numeric' ? '[?ghost1999]' : '([?ghost1999])',
+ `${style}: it renders as [?key] — with the key, so the author knows WHICH source went`);
+ ok(!res.order.includes('ghost1999'), `${style}: and it takes no slot in the reference list`);
+ }
+ const res = resolve(BODY, BIB, 'numeric');
+ eq(citationText({ at: 0, keys: ['knuth1984', 'ghost1999'] }, res, BIB), '[1], [?ghost1999]',
+ 'one bad key in a group does not take the good one down with it');
+}
+
+H('nothing is stored — the same input always gives the same output');
+{
+ const before = JSON.stringify({ BODY, BIB });
+ const a = JSON.stringify(bibliography(resolve(BODY, BIB, 'numeric'), BIB));
+ const b = JSON.stringify(bibliography(resolve(BODY, BIB, 'numeric'), BIB));
+ eq(a, b, 'twice in a row, byte-identical');
+ eq(JSON.stringify({ BODY, BIB }), before, 'and resolving mutated neither the body nor the entries');
+
+ // the entry map rebuilt in the opposite insertion order must not move the list
+ const flipped: Bibliography = {};
+ for (const k of Object.keys(BIB).reverse()) flipped[k] = BIB[k];
+ eq(JSON.stringify(resolve(BODY, flipped, 'author-year').order),
+ JSON.stringify(resolve(BODY, BIB, 'author-year').order),
+ 'the alphabetical order does not depend on the map\'s insertion order');
+ eq(JSON.stringify(resolve(BODY, flipped, 'numeric').number),
+ JSON.stringify(resolve(BODY, BIB, 'numeric').number),
+ 'and neither do the numbers');
+
+ // and it must not depend on the reader's locale, which is why sortKey exists
+ eq(sortKey('Ångström'), 'angstrom', 'the sort key folds diacritics rather than asking the locale');
+ eq(sortKey('van der Waals'), 'van der waals', 'and lowercases without dropping the particle');
+
+ // switching style is a preference, not an edit
+ const numbered = JSON.stringify(BODY);
+ resolve(BODY, BIB, 'author-year');
+ eq(JSON.stringify(BODY), numbered, 'resolving in the other style leaves the document alone');
+}
+
+H('reading a document that was written by something else');
+{
+ eq(readBibliography(undefined), {}, 'an older file has no bibliography, and that is not an error');
+ eq(readStyle(undefined), 'numeric', 'nor a style');
+ eq(readStyle('cslJSON'), 'numeric', 'an unknown style falls back rather than rendering nothing');
+ eq(readBibliography({ 'ok1': { type: 'book', title: 'Kept' },
+ 'bad key': { type: 'book', title: 'Dropped' },
+ 'ok2': 'not an object' }),
+ { ok1: { type: 'book', title: 'Kept' } },
+ 'an unusable key or value is dropped, the rest survives');
+ eq(readBibliography({ x: { type: 'nonsense', title: 'T', abstract: 'unmodelled' } }),
+ { x: { type: 'misc', title: 'T' } },
+ 'an unknown type reads as misc and an unmodelled field is not carried');
+ eq(readCiteRef({ at: 999, keys: ['knuth1984'] }, 10)?.at, 10,
+ 'an offset past the end of the text is clamped to it');
+ eq(readCiteRef({ at: 2, keys: [] }, 10), undefined, 'a citation with no keys is not a citation');
+ eq(readCiteRef({ at: 2, keys: ['ok', 'has space'] }, 10)?.keys, ['ok'], 'and unusable keys are dropped from it');
+ eq(readCiteRef('nonsense', 10), undefined, 'and garbage is rejected without throwing');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-comments.ts b/scripts/test-type-comments.ts
new file mode 100644
index 00000000..c900a2a1
--- /dev/null
+++ b/scripts/test-type-comments.ts
@@ -0,0 +1,505 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type comments rig. node scripts/test-type-comments.ts
+//
+// The one thing a comment must never do is drift. A comment sitting one clause
+// away from the sentence it is about is worse than no comment, because it is
+// confidently wrong — so most of this rig is one assertion said many ways:
+//
+// block.text.slice(th.from, th.to) == the words the comment was about
+//
+// EVERY OFFSET IS DERIVED FROM THE TEXT, never typed. The redline rig learned
+// this the hard way (its first fixture hand-counted two offsets wrong and
+// reported a failure against correct code); a rig with a wrong expectation is
+// worse than no rig, and here it would be worse still, because the thing under
+// test IS arithmetic over offsets and a hand-counted expectation is just a
+// second, unreviewed implementation of it.
+
+import {
+ readThreads, writeThreads, newThread, addReply, setResolved, unresolvedCount,
+ orderThreads, reconcileThreads, shiftAnchor, textEdit, shiftThreads,
+ splitThreads, mergeThreads, commentsOnEdit, commentsOnSplit, commentsOnMerge,
+ editMessage, deleteMessage,
+ type CommentThread,
+} from '../type/src/comments.ts';
+import { emptyDoc, parseDoc, spliceText, type Block, type TypeDoc } from '../type/src/model.ts';
+import { buildPrintDocument } from '../type/src/print.ts';
+import type { Metrics } from '../type/src/paginate.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+// ───────────────────────────────────────────────────────────────── fixture
+
+const P2 = 'Payment is due within 30 days of invoice, without set-off.';
+const TERM = '30 days'; // what the comment is about
+const CLAUSE = 'the laws of Sweden'; // a second anchor, in another block
+
+function fixture(): TypeDoc {
+ const doc = emptyDoc();
+ doc.title = 'Master Services Agreement';
+ doc.body = [
+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.' },
+ { id: 'p2', kind: 'para', text: P2, marks: [{ t: 'b', from: P2.indexOf(TERM), to: P2.indexOf(TERM) + TERM.length }] },
+ { id: 'p3', kind: 'para', text: 'This agreement is governed by the laws of Sweden.' },
+ ] as Block[];
+ return doc;
+}
+
+/** Anchor a comment on the first occurrence of `term` in a block. Derived. */
+function commentOn(doc: TypeDoc, blockId: string, term: string, text: string,
+ id: string, at = '2026-01-01T09:00:00.000Z'): CommentThread {
+ const blk = doc.body.find(b => b.id === blockId)!;
+ const from = blk.text.indexOf(term);
+ if (from < 0) throw new Error(`fixture error: ${JSON.stringify(term)} is not in ${blockId}`);
+ const th = newThread(blk, from, from + term.length, 'counsel', text, id, at);
+ writeThreads(doc, [...readThreads(doc), th]);
+ return th;
+}
+
+/** What a thread currently points at, in the live document. */
+const anchored = (doc: TypeDoc, id: string): string | null => {
+ const th = readThreads(doc).find(x => x.id === id);
+ if (!th || th.orphan) return null;
+ const blk = doc.body.find(b => b.id === th.block);
+ return blk ? blk.text.slice(th.from, th.to) : null;
+};
+
+const thread = (doc: TypeDoc, id: string) => readThreads(doc).find(x => x.id === id)!;
+
+/**
+ * Edit a block's text the way the editor does — splice the block, then hand the
+ * before/after text to the hook the core will call. Deliberately routed through
+ * commentsOnEdit rather than the pure shift, so the prefix/suffix RECOVERY of
+ * the splice is under test too: the editor rebuilds whole blocks from the DOM
+ * and never reports a splice, so that recovery is the real code path.
+ */
+function edit(doc: TypeDoc, blockId: string, at: number, removed: number, added: string): void {
+ const i = doc.body.findIndex(b => b.id === blockId);
+ const prev = doc.body[i];
+ const next = spliceText(prev, at, removed, added);
+ doc.body[i] = next;
+ commentsOnEdit(doc, blockId, prev.text, next.text);
+}
+
+// ───────────────────────────────────────────────────────── the anchor moves
+
+H('an insertion BEFORE the anchor');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ ok(anchored(doc, 'c1') === TERM, `it starts on ${JSON.stringify(TERM)}`);
+
+ const PRE = 'Unless otherwise agreed, ';
+ edit(doc, 'p2', 0, 0, PRE);
+ ok(doc.body[1].text.startsWith(PRE), 'the text really did change');
+ ok(anchored(doc, 'c1') === TERM,
+ `the comment still points at ${JSON.stringify(TERM)} (got ${JSON.stringify(anchored(doc, 'c1'))})`);
+ // and it moved by exactly the inserted length — the offsets, not just the slice
+ const th = thread(doc, 'c1');
+ ok(th.from === doc.body[1].text.indexOf(TERM),
+ 'its offset is the term\'s new position, derived from the text');
+}
+
+H('an insertion INSIDE the anchor');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Business days or calendar days?', 'c1');
+ // "30 days" → "30 calendar days": the comment was about the whole period, so
+ // it must GROW to cover the words that were added into it
+ const inside = P2.indexOf(TERM) + '30 '.length;
+ edit(doc, 'p2', inside, 0, 'calendar ');
+ ok(doc.body[1].text.includes('30 calendar days'), 'the text really did change');
+ ok(anchored(doc, 'c1') === '30 calendar days',
+ `the anchor grew to cover the insertion (got ${JSON.stringify(anchored(doc, 'c1'))})`);
+ ok(!thread(doc, 'c1').orphan, 'and it is not orphaned');
+}
+
+H('an insertion AFTER the anchor');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Check against the MSA.', 'c1');
+ const before = thread(doc, 'c1');
+ edit(doc, 'p2', doc.body[1].text.length, 0, ' Time is of the essence.');
+ const after = thread(doc, 'c1');
+ ok(anchored(doc, 'c1') === TERM, 'the anchor is untouched');
+ ok(after.from === before.from && after.to === before.to,
+ 'and its offsets did not move at all');
+}
+
+H('an edit that straddles the anchor');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Too long.', 'c1');
+ // rewrite "within 30 days of" as "within sixty (60) days of" — the anchor is
+ // clipped to what survives rather than dropped, exactly as a bold run is
+ const SPAN = 'within 30 days';
+ edit(doc, 'p2', P2.indexOf(SPAN), SPAN.length, 'within sixty (60) days');
+ const th = thread(doc, 'c1');
+ ok(!th.orphan, 'a partly-rewritten anchor survives');
+ const now = anchored(doc, 'c1')!;
+ ok(doc.body[1].text.slice(th.from, th.to) === now && now.length > 0,
+ `it still covers real text (${JSON.stringify(now)})`);
+ ok(doc.body[1].text.includes(now), 'which is text that is actually in the block');
+}
+
+H('the anchored text is DELETED outright');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ const from = P2.indexOf(TERM);
+ edit(doc, 'p2', from, TERM.length, '');
+ ok(!doc.body[1].text.includes(TERM), 'the words are gone from the text');
+
+ const th = thread(doc, 'c1');
+ ok(th !== undefined, 'the thread is NOT dropped');
+ ok(th.orphan === true, 'it is marked orphaned');
+ ok(th.quote === TERM, `and it still says what it was about (${JSON.stringify(th.quote)})`);
+ ok(th.messages[0].text === 'Is thirty days market standard?', 'the conversation survives intact');
+ ok(anchored(doc, 'c1') === null, 'it points at nothing rather than at whatever moved in');
+
+ // the wrong answer, stated as a test: a live range would now cover the words
+ // that flowed into those offsets
+ const wouldHaveBeen = doc.body[1].text.slice(from, from + TERM.length);
+ ok(wouldHaveBeen !== TERM && wouldHaveBeen.length > 0,
+ `keeping the offsets live would have pointed it at ${JSON.stringify(wouldHaveBeen)}`);
+
+ // THE BUG THIS RIG FOUND. The frozen from/to still fit inside the shortened
+ // block, so a version of reconcileThreads that re-derived `orphan` from
+ // geometry alone un-orphaned this thread on the very next read and pointed it
+ // at the text above. Detachment by deletion has to be remembered, not guessed.
+ ok(thread(doc, 'c1').orphan === true, 'and it is STILL orphaned when read again');
+ const round = readThreads(JSON.parse(JSON.stringify(doc)) as TypeDoc).find(x => x.id === 'c1')!;
+ ok(round.orphan === true, 'including after a save and reload');
+}
+
+H('the anchored words are REPLACED rather than deleted');
+{
+ // Replacing text is not deleting it, and the anchor follows the replacement —
+ // the same thing a bold run does, which is the point of sharing `shift`. The
+ // comment was about that spot, and that spot now says something else, which
+ // is exactly what the commenter needs to see.
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ edit(doc, 'p2', P2.indexOf(TERM), TERM.length, 'sixty days');
+ ok(thread(doc, 'c1').orphan !== true, 'a replaced anchor is not orphaned');
+ ok(anchored(doc, 'c1') === 'sixty days',
+ `it covers the replacement (${JSON.stringify(anchored(doc, 'c1'))})`);
+ ok(thread(doc, 'c1').quote === TERM, 'and still records what it was originally about');
+}
+
+H('a comment on a block that no longer exists');
+{
+ const doc = fixture();
+ commentOn(doc, 'p3', CLAUSE, 'Governing law should be England.', 'c1');
+ ok(anchored(doc, 'c1') === CLAUSE, 'it starts on the governing-law clause');
+
+ doc.body = doc.body.filter(b => b.id !== 'p3'); // the clause is struck out
+ const th = thread(doc, 'c1');
+ ok(th !== undefined, 'the thread survives the block');
+ ok(th.orphan === true, 'and is orphaned rather than dangling');
+ ok(th.block === 'p3', 'it remembers WHICH block it was on');
+ ok(th.quote === CLAUSE, 'and what it was about');
+
+ // A missing block detaches a thread only for as long as the block is
+ // missing: the repair pass writes nothing back, so putting the paragraph
+ // back — a rejected redline does exactly this — reattaches the comment.
+ ok(JSON.stringify(doc).includes('"orphan"') === false,
+ 'the detachment was never written into the file');
+ doc.body.push({ id: 'p3', kind: 'para', text: 'This agreement is governed by the laws of Sweden.' } as Block);
+ ok(thread(doc, 'c1').orphan !== true, 'restoring the block reattaches it');
+ ok(anchored(doc, 'c1') === CLAUSE, 'and it points at the same words again');
+}
+
+H('a paragraph split and a paragraph merge');
+{
+ // the split is a real editing move that changes no words, so no comment on
+ // either side of the cut may be lost by it
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'early', 'c1');
+ commentOn(doc, 'p2', 'set-off', 'late', 'c2');
+ const cut = P2.indexOf('without');
+ const head = spliceText(doc.body[1], cut, P2.length - cut, '');
+ const tail: Block = { id: 'p2b', kind: 'para', text: P2.slice(cut) };
+ doc.body.splice(1, 1, head, tail);
+ commentsOnSplit(doc, 'p2', cut, P2.length, 'p2b');
+
+ ok(thread(doc, 'c1').block === 'p2', 'a comment before the cut stays with the head');
+ ok(anchored(doc, 'c1') === TERM, 'still on its words');
+ ok(thread(doc, 'c2').block === 'p2b', 'a comment after the cut moves to the tail');
+ ok(anchored(doc, 'c2') === 'set-off', `still on its words (${JSON.stringify(anchored(doc, 'c2'))})`);
+
+ // and merging them back restores both
+ const at = doc.body[1].text.length;
+ doc.body.splice(1, 2, { ...doc.body[1], text: doc.body[1].text + doc.body[2].text });
+ commentsOnMerge(doc, 'p2', 'p2b', at);
+ ok(anchored(doc, 'c1') === TERM && anchored(doc, 'c2') === 'set-off',
+ 'merging the paragraphs back leaves both comments on their words');
+ ok(doc.body[1].text === P2, 'and the text is what it started as');
+}
+
+H('a straddling comment goes to the side holding more of its text');
+{
+ const threads: CommentThread[] = [
+ { id: 'a', block: 's', from: 0, to: 10, quote: '', messages: [{ id: 'm', author: 'x', at: '', text: 'q' }] },
+ { id: 'b', block: 's', from: 10, to: 30, quote: '', messages: [{ id: 'm', author: 'x', at: '', text: 'q' }] },
+ ];
+ // cut at 14: `a` is 10 chars ahead of it, `b` is 16 chars behind it
+ const out = splitThreads(threads, 's', 14, 40, 'tail');
+ ok(out[0].block === 's' && out[0].to === 10, 'wholly-before stays put');
+ ok(out[1].block === 'tail', 'the straddler goes to the side with more of it');
+ ok(out[1].from === 0 && out[1].to === 30 - 14, 'rebased onto the tail');
+ const out2 = splitThreads(threads, 's', 26, 40, 'tail');
+ ok(out2[1].block === 's' && out2[1].to === 26, 'and to the head when the head holds more, clipped to the cut');
+}
+
+H('the arithmetic is inline.ts\'s, not a second copy of it');
+{
+ // shiftAnchor is a thin wrapper over the same `shift` marks use, so the two
+ // must agree on every edge. Asserted directly, because the day they diverge
+ // is the day a highlight and the bold under it stop lining up.
+ const a = { from: 10, to: 20 };
+ ok(shiftAnchor(a, 0, 0, 5, 45)!.from === 15, 'insertion before pushes the start');
+ ok(shiftAnchor(a, 10, 0, 5, 45)!.from === 10, 'insertion exactly AT the start joins the range (sticky start)');
+ ok(shiftAnchor(a, 10, 0, 5, 45)!.to === 25, '…and carries the end');
+ ok(shiftAnchor(a, 20, 0, 5, 45)!.to === 20, 'insertion exactly AT the end does NOT join it');
+ ok(shiftAnchor(a, 10, 10, 0, 30) === null, 'deleting the whole range yields nothing to point at');
+ ok(shiftAnchor(a, 0, 40, 0, 0) === null, 'and so does deleting everything');
+
+ const e = textEdit('Payment is due within 30 days.', 'Payment is due within 60 days.');
+ ok(e !== null && e.removed === 1 && e.added === '6',
+ `the recovered splice is MINIMAL, not "the paragraph changed" (${JSON.stringify(e)})`);
+ ok(textEdit('same', 'same') === null, 'no change is reported as no edit');
+}
+
+// ────────────────────────────────────────────────────────────── thread logic
+
+H('a reply thread');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ let th = thread(doc, 'c1');
+ ok(th.messages.length === 1, 'a new comment is one message');
+ ok(th.messages[0].author === 'counsel', 'attributed to whoever wrote it');
+
+ th = addReply(th, 'client', 'Sixty is what we agreed last time.');
+ th = addReply(th, 'counsel', 'Then sixty it is.');
+ writeThreads(doc, readThreads(doc).map(x => x.id === 'c1' ? th : x));
+
+ const back = thread(doc, 'c1');
+ ok(back.messages.length === 3, `three messages after two replies (${back.messages.length})`);
+ ok(back.messages.map(m => m.author).join() === 'counsel,client,counsel',
+ 'in the order they were written, with their authors');
+ ok(back.messages[2].text === 'Then sixty it is.', 'and their text survives the round trip');
+ ok(addReply(back, 'client', ' ').messages.length === 3, 'an empty reply is not a reply');
+ ok(back.messages.every(m => m.id) && new Set(back.messages.map(m => m.id)).size === 3,
+ 'every message has its own id');
+}
+
+H('editing a message');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ let th = thread(doc, 'c1');
+ th = addReply(th, 'client', 'Sixty is what we agreed last time.');
+ const before = { block: th.block, from: th.from, to: th.to, quote: th.quote };
+ const firstId = th.messages[0].id, replyId = th.messages[1].id;
+
+ const edited = editMessage(th, firstId, 'Is THIRTY days market standard, or sixty?');
+ ok(edited.messages[0].text === 'Is THIRTY days market standard, or sixty?', 'the text changes');
+ ok(edited.messages[0].id === firstId && edited.messages[0].author === 'counsel',
+ 'id and author are untouched by an edit');
+ ok(edited.messages[1].text === 'Sixty is what we agreed last time.',
+ 'the OTHER message in the thread is untouched');
+ ok(edited.block === before.block && edited.from === before.from && edited.to === before.to
+ && edited.quote === before.quote,
+ 'the thread\'s anchor (block/from/to/quote) is byte-identical after the edit — ' +
+ 'an edit changes what was SAID, never what it was said ABOUT');
+
+ writeThreads(doc, readThreads(doc).map(x => x.id === 'c1' ? edited : x));
+ ok(anchored(doc, 'c1') === TERM, 'and the live anchor still resolves to the same words');
+
+ ok(editMessage(th, replyId, ' ') === th, 'an edit to nothing but whitespace is refused, not a blank');
+ ok(editMessage(th, 'no-such-id', 'x') === th, 'editing a message that is not in the thread is a no-op');
+}
+
+H('deleting a message: some remain');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ let th = thread(doc, 'c1');
+ th = addReply(th, 'client', 'Sixty is what we agreed last time.');
+ th = addReply(th, 'counsel', 'Then sixty it is.');
+ const replyId = th.messages[1].id;
+
+ const after = deleteMessage(th, replyId);
+ ok(after !== null, 'the thread survives — two messages are still in it');
+ if (after) {
+ ok(after.messages.length === 2, `down to two messages (${after.messages.length})`);
+ ok(after.messages.map(m => m.text).join('|') === 'Is thirty days market standard?|Then sixty it is.',
+ 'the deleted message is gone; the other two keep their order');
+ ok(after.block === th.block && after.from === th.from && after.to === th.to,
+ 'the anchor is untouched by deleting a reply');
+ }
+}
+
+H('deleting the last message removes the whole thread');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ commentOn(doc, 'p3', CLAUSE, 'Governing law should be England.', 'c2');
+ const th1 = thread(doc, 'c1');
+ ok(th1.messages.length === 1, 'c1 starts as a single message, nothing to reply with yet');
+
+ const gone = deleteMessage(th1, th1.messages[0].id);
+ ok(gone === null, 'deleting the only message returns null — no empty-shell thread');
+
+ // the caller (comments.ts mutateThread) is what actually removes it from
+ // the map; exercise that end-to-end via the same doc-level plumbing a UI
+ // action would use.
+ writeThreads(doc, readThreads(doc).filter(x => x.id !== 'c1'));
+ ok(readThreads(doc).find(x => x.id === 'c1') === undefined, 'c1 is gone from the document entirely');
+ ok(readThreads(doc).find(x => x.id === 'c2') !== undefined, 'and c2, a different thread, is untouched');
+ ok(anchored(doc, 'c2') === CLAUSE, 'c2 still resolves to its own words');
+ ok(!JSON.stringify(doc).includes('Is thirty days market standard?'),
+ 'the deleted conversation does not linger anywhere in the saved bytes');
+}
+
+H('resolve and unresolve');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ commentOn(doc, 'p3', CLAUSE, 'Governing law?', 'c2');
+ ok(unresolvedCount(readThreads(doc)) === 2, 'two open to start with');
+
+ const resolved = setResolved(thread(doc, 'c1'), true);
+ writeThreads(doc, readThreads(doc).map(x => x.id === 'c1' ? resolved : x));
+ ok(thread(doc, 'c1').resolved === true, 'it resolves');
+ ok(unresolvedCount(readThreads(doc)) === 1, 'and the count follows');
+ ok(anchored(doc, 'c1') === TERM, 'a resolved comment keeps its anchor — it is not a delete');
+
+ const reopened = setResolved(thread(doc, 'c1'), false);
+ writeThreads(doc, readThreads(doc).map(x => x.id === 'c1' ? reopened : x));
+ ok(thread(doc, 'c1').resolved === undefined, 'and it reopens, with the flag GONE, not false');
+ ok(unresolvedCount(readThreads(doc)) === 2, 'back to two open');
+ ok(JSON.stringify(reopened).includes('resolved') === false,
+ 'so a reopened thread serializes exactly as one that was never resolved');
+}
+
+H('the order the panel shows');
+{
+ const doc = fixture();
+ // deliberately created out of every order that matters
+ commentOn(doc, 'p3', CLAUSE, 'last block, open', 'c-p3', '2026-01-01T09:00:00.000Z');
+ commentOn(doc, 'p2', 'set-off', 'later in p2, open', 'c-p2b', '2026-01-01T08:00:00.000Z');
+ commentOn(doc, 'p2', TERM, 'earlier in p2, open', 'c-p2a', '2026-01-01T10:00:00.000Z');
+ commentOn(doc, 'p1', 'parties', 'first block, RESOLVED', 'c-p1', '2026-01-01T07:00:00.000Z');
+ writeThreads(doc, readThreads(doc).map(x => x.id === 'c-p1' ? setResolved(x, true) : x));
+ // and one that has lost its text entirely
+ commentOn(doc, 'p1', 'follows', 'orphan, open', 'c-orph', '2026-01-01T06:00:00.000Z');
+ edit(doc, 'p1', doc.body[0].text.indexOf('follows'), 'follows'.length, '');
+
+ const order = orderThreads(readThreads(doc), doc.body).map(x => x.id);
+ ok(order.join() === 'c-p2a,c-p2b,c-p3,c-orph,c-p1',
+ `unresolved in document order, then detached, then resolved (${order.join(' ')})`);
+
+ const list = orderThreads(readThreads(doc), doc.body);
+ const firstResolvedAt = list.findIndex(x => x.resolved);
+ ok(list.slice(0, firstResolvedAt).every(x => !x.resolved), 'nothing resolved appears above anything open');
+ ok(unresolvedCount(list) === 4, 'the count is the open ones, orphans included — they still want a human');
+
+ // deterministic: two readers of one file must see the same list
+ const again = orderThreads([...list].reverse(), doc.body).map(x => x.id);
+ ok(again.join() === order.join(), 'and the order does not depend on the input order');
+}
+
+// ─────────────────────────────────────────────────── the file, and the paper
+
+H('comments are saved in the file, and an older build still opens it');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'Is thirty days market standard?', 'c1');
+ const json = JSON.stringify(doc);
+ ok(json.includes('Is thirty days market standard?'), 'the conversation is in the saved bytes');
+
+ // FORMAT ADDITIVITY: parseDoc has no idea what `comments` is, and the unknown
+ // field rides through untouched — which is the same thing as an older build
+ // opening a newer file, since that build's parseDoc is this one minus the
+ // comment code.
+ const parsed = parseDoc(json);
+ ok(parsed.ok, 'it parses');
+ if (parsed.ok) {
+ ok(readThreads(parsed.doc).length === 1, 'and the thread is still there after a round trip');
+ ok(anchored(parsed.doc, 'c1') === TERM, 'still anchored on its words');
+ ok(parsed.repaired.length === 0, `and nothing was reported as repaired (${parsed.repaired.join('; ')})`);
+ }
+
+ // a file a generator got wrong: repaired, never crashed
+ const junk = JSON.parse(json);
+ junk.comments = {
+ ok1: { id: 'ok1', block: 'p2', from: 9e9, to: -3, quote: 'x', messages: [{ text: 'runaway offsets' }] },
+ ok2: { id: 'ok2', block: 'nope', from: 0, to: 2, quote: 'y', messages: [{ text: 'no such block' }] },
+ bad: { id: 'bad', block: 'p2', from: 0, to: 2, quote: 'z', messages: [] },
+ worse: 'not an object at all',
+ };
+ const rough = readThreads(junk as TypeDoc);
+ ok(rough.length === 2, `a thread with no conversation in it is the only one dropped (${rough.length})`);
+ ok(rough.find(x => x.id === 'ok1')!.orphan === true,
+ 'a garbage range orphans rather than being "repaired" into the whole paragraph');
+ ok(rough.find(x => x.id === 'ok2')!.orphan === true, 'a missing block orphans');
+}
+
+H('a comment can never reach the printed page');
+{
+ const doc = fixture();
+ commentOn(doc, 'p2', TERM, 'CONFIDENTIAL REVIEWER NOTE: push back hard on this.', 'c1');
+ const metrics: Metrics = { ms: 0, pages: [{ n: 1, start: 0, end: Infinity, notes: [], reserved: 0 }] };
+ const withComments = buildPrintDocument(doc, metrics);
+
+ ok(!withComments.includes('CONFIDENTIAL REVIEWER NOTE'), 'the comment text is not in the print output');
+ ok(!withComments.includes('counsel'), 'nor is the commenter\'s name');
+ ok(!/t-cmt/.test(withComments), 'nor any comment markup');
+
+ // the strong form: print cannot TELL the difference. print.ts renders blocks
+ // from text + marks + notes and never reads doc.comments, so there is no path
+ // from a comment to the paper that a future edit could forget to close.
+ const clean = fixture();
+ ok(buildPrintDocument(clean, metrics) === withComments,
+ 'the printed bytes are identical to the same document with no comments at all');
+ ok(withComments.includes(TERM), 'and the commented WORDS still print, unmarked');
+}
+
+// ───────────────────────────────── the pure movers, exercised without a doc
+
+H('the pure movers stand alone');
+{
+ const base: CommentThread[] = [
+ { id: 'a', block: 'b1', from: 4, to: 9, quote: 'quick', messages: [{ id: 'm', author: 'x', at: '', text: 'q' }] },
+ ];
+ const TXT = 'The quick brown fox';
+ const NEW = 'The very quick brown fox';
+ const e = textEdit(TXT, NEW)!;
+ const moved = shiftThreads(base, 'b1', e.at, e.removed, e.added.length, NEW.length);
+ // "very " is inserted at exactly the anchor's start, so the STICKY START rule
+ // above applies and the range takes it in — the same thing the bold under it
+ // would do. Derived from the text either way, never hand-counted.
+ ok(NEW.slice(moved[0].from, moved[0].to) === 'very quick',
+ `sticky start: the anchor reads "very quick" (${JSON.stringify(NEW.slice(moved[0].from, moved[0].to))})`);
+ ok(TXT.slice(base[0].from, base[0].to) === 'quick', 'and the original still read "quick"');
+ ok(shiftThreads(base, 'other', 0, 0, 99, 999)[0].from === 4, 'an edit in another block moves nothing');
+
+ const merged = mergeThreads(base, 'b0', 'b1', 100);
+ ok(merged[0].block === 'b0' && merged[0].from === 104 && merged[0].to === 109,
+ 'a merge rebases the anchor onto the surviving block');
+ ok(reconcileThreads(base, [{ id: 'b1', kind: 'para', text: TXT } as Block])[0].orphan === undefined,
+ 'reconcile leaves a good anchor alone');
+ ok(reconcileThreads(base, [{ id: 'b1', kind: 'para', text: 'Th' } as Block])[0].orphan === true,
+ 'and orphans one the text is now too short for');
+ ok(reconcileThreads([{ ...base[0], orphan: true }], [{ id: 'b1', kind: 'para', text: TXT } as Block])[0].orphan === true,
+ 'an orphan flag is never cleared by the repair pass — only undo brings a thread back');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-embed.ts b/scripts/test-type-embed.ts
new file mode 100644
index 00000000..233d936a
--- /dev/null
+++ b/scripts/test-type-embed.ts
@@ -0,0 +1,95 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Embedded Bento artifacts — the shape, and the boundary.
+//
+// node scripts/test-type-embed.ts
+//
+// The boundary is the point. An embed exists to carry MARKUP PRODUCED
+// ELSEWHERE into this document, which makes it the most attractive place in
+// the whole format to hide a script: it is the one field whose job is to hold
+// someone else's HTML. Every document is untrusted input — a hand-written
+// #bento-doc block, a file mailed to you, a sync op — so the static render is
+// checked before it is ever put in the page.
+
+import { register } from 'node:module';
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+
+const { safeView, readArtifact, embedHtml, APPS } = await import('../type/src/embed.ts');
+
+let checks = 0, bad = 0;
+const ok = (cond: boolean, msg: string) => {
+ checks++;
+ if (cond) console.log(` ok ${msg}`);
+ else { bad++; console.log(` FAIL ${msg}`); }
+};
+
+console.log('\n— a plain chart is allowed through —');
+{
+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50">'
+ + '<rect x="2" y="2" width="20" height="46" fill="#c66"/><text x="4" y="20">Q1</text></svg>';
+ ok(safeView(svg) === svg, 'an ordinary svg survives unchanged');
+ ok(safeView(' ' + svg + '\n') === svg, 'and is trimmed, not rejected, for whitespace');
+}
+
+console.log('\n— what must never reach the page —');
+const REFUSE: Array<[string, string]> = [
+ ['<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>', 'a script element'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><rect onload="alert(1)"/></svg>', 'an onload handler'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><rect ONMOUSEOVER="x()"/></svg>', 'a handler in capitals'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><b>hi</b></foreignObject></svg>', 'foreignObject'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><iframe src="x"></iframe></svg>', 'an iframe'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><image href="https://evil/x.png"/></svg>', 'a remote image'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><a xlink:href="javascript:alert(1)">x</a></svg>', 'a javascript: link'],
+ ['<svg xmlns="http://www.w3.org/2000/svg"><style>*{x:y}</style></svg>', 'a style element (it would leak document-wide)'],
+ ['<div>not an svg at all</div>', 'markup that is not an svg'],
+ ['<img src=x onerror=alert(1)>', 'an img with a handler'],
+];
+for (const [src, what] of REFUSE) ok(safeView(src) === null, `refused: ${what}`);
+
+console.log('\n— refusing is not the same as losing —');
+{
+ const b = { id: 'e1', kind: 'embed', text: '',
+ embed: { app: 'bento/dash', view: '<svg><script>x</script></svg>', doc: { format: 'bento/dash' } } };
+ const html = embedHtml(b as never);
+ ok(!html.includes('<script'), 'the refused markup is NOT in the output');
+ ok(html.includes('could not be displayed safely'), 'and the reader is told why');
+ ok((b as { embed: { doc: unknown } }).embed.doc !== undefined, 'while the SOURCE is still there to open elsewhere');
+}
+
+console.log('\n— reading another app\'s file —');
+{
+ const artifact =
+ '<!doctype html><html><head><title>x</title></head><body>'
+ + '<div data-bento-preview><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect/></svg></div>'
+ + '<script type="application/json" id="bento-doc">{"format":"bento/dash","docId":"d1","title":"Q3"}</script>'
+ + '</body></html>';
+ const e = readArtifact(artifact);
+ ok(e !== null, 'the artifact is recognised');
+ ok(e?.app === 'bento/dash', 'its app comes from the document format');
+ ok(typeof e?.view === 'string' && e.view.startsWith('<svg'), 'the still is taken from the saved preview');
+ ok((e?.doc as { title?: string })?.title === 'Q3', 'and the source document rides along');
+
+ // Format additivity: an app this build has never heard of must still embed.
+ const future = artifact.replace('bento/dash', 'bento/whatever');
+ const f = readArtifact(future);
+ ok(f?.app === 'bento/whatever', 'an UNKNOWN bento app is accepted, not rejected');
+ ok(!(f!.app in APPS), 'and it genuinely is not in the known list');
+ ok(embedHtml({ id: 'e', kind: 'embed', text: '', embed: f } as never).includes('bento/whatever'),
+ 'its name is shown, so the reader knows where to open it');
+
+ ok(readArtifact('<html><body>nothing here</body></html>') === null, 'a non-Bento file is refused');
+ ok(readArtifact('<script id="bento-doc">{not json</script>') === null, 'so is a corrupt block');
+ ok(readArtifact('<script id="bento-doc">{"format":"text/plain"}</script>') === null,
+ 'so is a JSON block that is not a Bento document');
+}
+
+console.log('\n— a file with no preview still embeds —');
+{
+ const e = readArtifact('<script id="bento-doc">{"format":"bento/slides","docId":"s1"}</script>');
+ ok(e !== null && safeView(e.view) !== null, 'the fallback still is itself safe');
+ ok(e!.view.includes('Bento Slides'), 'and says which app it came from');
+}
+
+console.log(`\n${checks - bad}/${checks} checks passed`);
+if (bad) process.exit(1);
diff --git a/scripts/test-type-find.ts b/scripts/test-type-find.ts
new file mode 100644
index 00000000..fa5ac823
--- /dev/null
+++ b/scripts/test-type-find.ts
@@ -0,0 +1,214 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type find and replace. node scripts/test-type-find.ts
+//
+// Search and replace are PURE FUNCTIONS over a document, and that is the whole
+// reason this rig can exist without a browser. The panel is chrome around
+// these four: matchesInText, findMatches, replaceAll, nextFrom.
+//
+// What this exists to prevent, in order of how much it would cost:
+//
+// 1. A REPLACE THAT MOVES TEXT AND NOT ITS MARKS. Marks and footnote anchors
+// are offsets into the block's text; a replacement of a different length
+// shifts every one of them. That arithmetic lives in model.spliceText and
+// is REUSED here — these checks are what proves it is actually reused,
+// because a private copy would pass a "the text changed" test and fail
+// these.
+// 2. Overlapping matches. "aa" in "aaaa" is two matches, not three: three
+// would mean replacing text a previous replacement had already removed.
+// 3. Case folding that changes the LENGTH of the haystack ('İ'), which makes
+// every offset after it address the wrong character.
+// 4. A search that does not see list items or table cells. They are ordinary
+// blocks, so this is free — and a regression here would be silent, which
+// is why it is asserted rather than assumed.
+
+import { matchesInText, findMatches, replaceAll, replaceMatch, nextFrom } from '../type/src/find.ts';
+import { emptyDoc, spliceText, type Block } from '../type/src/model.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const b = (id: string, text: string, extra: Partial<Block> = {}): Block =>
+ ({ id, kind: 'para', text, ...extra });
+
+const spans = (text: string, q: string, o = {}) =>
+ matchesInText(text, q, o).map(([f, t]) => text.slice(f, t)).join('|');
+
+H('finding');
+{
+ ok(spans('the cat sat on the mat', 'at') === 'at|at|at', 'every occurrence, in order');
+ ok(matchesInText('the cat sat', 'at')[0][0] === 5, 'offsets are into the block text');
+ ok(matchesInText('nothing here', 'zebra').length === 0, 'a miss is an empty list');
+ ok(matchesInText('anything', '').length === 0, 'an empty query matches nothing, not everything');
+}
+
+H('overlaps are never reported');
+{
+ // three would be a bug with teeth: replacing them in turn splices text the
+ // previous replacement already removed
+ ok(matchesInText('aaaa', 'aa').length === 2, '"aa" in "aaaa" is two matches');
+ ok(spans('aaaaa', 'aa') === 'aa|aa', 'and the odd character is left over');
+}
+
+H('match case');
+{
+ ok(spans('Cat cat CAT', 'cat') === 'Cat|cat|CAT', 'off by default: case is ignored');
+ ok(spans('Cat cat CAT', 'cat', { matchCase: true }) === 'cat', 'on: only the exact spelling');
+ ok(spans('Cat cat CAT', 'CAT', { matchCase: true }) === 'CAT', 'and it is not a one-way fold');
+}
+
+H('case folding never moves an offset');
+{
+ // 'İ'.toLowerCase() is TWO characters. A lowercased haystack would then be
+ // longer than the text it came from and every later offset would be wrong —
+ // which, followed by a replace, splices into the middle of a word.
+ const text = 'İstanbul is a city';
+ for (const [from, to] of matchesInText(text, 'city')) {
+ ok(text.slice(from, to) === 'city', `the offset still addresses the match (${from}..${to})`);
+ }
+ const long = 'aİa cat';
+ ok(spans(long, 'cat') === 'cat', 'a length-changing fold earlier in the line does not shift a later match');
+}
+
+H('whole word');
+{
+ ok(spans('cat catalog concat cat.', 'cat') === 'cat|cat|cat|cat', 'off: substrings count');
+ ok(matchesInText('cat catalog concat cat.', 'cat', { wholeWord: true }).length === 2,
+ 'on: only the standalone words');
+ const t2 = 'cat catalog concat cat.';
+ const m = matchesInText(t2, 'cat', { wholeWord: true });
+ ok(m[0][0] === 0 && m[1][0] === 19, 'the first word and the one before the full stop');
+ ok(matchesInText('re-cat', 'cat', { wholeWord: true }).length === 1, 'a hyphen is a boundary');
+ ok(matchesInText('cat9', 'cat', { wholeWord: true }).length === 0, 'a digit is not');
+ ok(matchesInText('naïve', 'naï', { wholeWord: true }).length === 0, 'and neither is an accented letter');
+}
+
+H('every block is searched — including list items and table cells');
+{
+ const body: Block[] = [
+ b('p1', 'the term appears here'),
+ b('li1', 'and in a list item: term', { kind: 'ul' }),
+ b('li2', 'nested too: term', { kind: 'ul', level: 2 }),
+ b('c1', 'term', { kind: 'cell', cell: { table: 'tb', cols: 2, head: true } }),
+ b('c2', 'and term again', { kind: 'cell', cell: { table: 'tb', cols: 2 } }),
+ b('h', 'TERM as a heading', { kind: 'h2' }),
+ ];
+ const found = findMatches(body, 'term');
+ ok(found.length === 6, `six matches across paragraph, list, table and heading (${found.length})`);
+ ok(found.map(m => m.id).join(',') === 'p1,li1,li2,c1,c2,h', 'reported in document order');
+ ok(found[0].block === 0 && found[5].block === 5, 'each match carries its block index, for stepping');
+ ok(findMatches(body, 'term', { matchCase: true }).length === 5, 'the heading drops out under match case');
+}
+
+H('a replace keeps marks pointing at the same words');
+{
+ // "Payment is due in 30 days." bold over "due in" (11..17), a note at 26
+ const src = b('p', 'Payment is due in 30 days.', {
+ marks: [{ t: 'b', from: 11, to: 17 }],
+ notes: [{ id: 'n1', at: 26 }],
+ });
+ const m = findMatches([src], '30')[0];
+ const out = replaceMatch(src, m, 'sixty'); // 2 chars → 5
+ ok(out.text === 'Payment is due in sixty days.', out.text);
+ ok(out.marks![0].from === 11 && out.marks![0].to === 17, 'a mark BEFORE the edit does not move');
+ ok(out.notes![0].at === 29, 'a footnote anchor after the edit moves by the delta (+3)');
+ ok(out.text.slice(out.marks![0].from, out.marks![0].to) === 'due in',
+ 'and the mark still covers the words it was put on');
+
+ // the same edit, with the mark AFTER the replacement
+ const src2 = b('p', 'Payment is due in 30 days.', { marks: [{ t: 'i', from: 21, to: 25 }] });
+ const out2 = replaceMatch(src2, findMatches([src2], '30')[0], 'sixty');
+ ok(out2.text.slice(out2.marks![0].from, out2.marks![0].to) === 'days',
+ 'a mark after the edit follows its own text');
+
+ // shortening, too — the delta is negative and everything must come back
+ const src3 = b('p', 'Payment is due in sixty days.', {
+ marks: [{ t: 'b', from: 24, to: 28 }], notes: [{ id: 'n1', at: 29 }],
+ });
+ const out3 = replaceMatch(src3, findMatches([src3], 'sixty')[0], '30');
+ ok(out3.text === 'Payment is due in 30 days.', out3.text);
+ ok(out3.text.slice(out3.marks![0].from, out3.marks![0].to) === 'days', 'a shorter replacement too');
+ ok(out3.notes![0].at === 26, 'and the note comes back with it');
+}
+
+H('replace does no offset arithmetic of its own');
+{
+ // the point of the reuse: replaceMatch must be spliceText, exactly
+ const src = b('p', 'one two three', { marks: [{ t: 'u', from: 4, to: 7 }], notes: [{ id: 'n', at: 8 }] });
+ const m = findMatches([src], 'two')[0];
+ const mine = replaceMatch(src, m, 'ii');
+ const theirs = spliceText(src, m.from, m.to - m.from, 'ii');
+ ok(JSON.stringify(mine) === JSON.stringify(theirs), 'byte-identical to model.spliceText');
+}
+
+H('replace all');
+{
+ const body: Block[] = [
+ b('p1', 'the term, the term'),
+ b('p2', 'no hits here'),
+ b('li', 'a term in a list', { kind: 'ul' }),
+ b('c', 'term', { kind: 'cell', cell: { table: 't', cols: 1 } }),
+ ];
+ const r = replaceAll(body, 'term', 'clause');
+ ok(r.count === 4, `four replacements (${r.count})`);
+ ok(r.body[0].text === 'the clause, the clause', 'both hits in one block, and the second offset is right');
+ ok(r.body[2].text === 'a clause in a list', 'the list item too');
+ ok(r.body[3].text === 'clause', 'and the table cell');
+ ok(r.body[1] === body[1], 'a block with no match is the SAME object — the snapshot stays cheap');
+ ok(body[0].text === 'the term, the term', 'and the input is untouched: the function is pure');
+}
+
+H('replace all applies back to front, so a length change cannot corrupt later hits');
+{
+ const src = b('p', 'x term y term z', { marks: [{ t: 'b', from: 14, to: 15 }], notes: [{ id: 'n', at: 15 }] });
+ const r = replaceAll([src], 'term', 'a'); // shrinks by 3, twice
+ ok(r.body[0].text === 'x a y a z', r.body[0].text);
+ ok(r.body[0].text.slice(r.body[0].marks![0].from, r.body[0].marks![0].to) === 'z',
+ 'the mark on the last character survives both replacements');
+ ok(r.body[0].notes![0].at === 9, 'and so does the note anchored at the end');
+
+ const grow = replaceAll([b('p', 'a b a b')], 'b', 'LONGER');
+ ok(grow.body[0].text === 'a LONGER a LONGER', grow.body[0].text);
+}
+
+H('a replacement that contains the query does not run away');
+{
+ const r = replaceAll([b('p', 'cat cat')], 'cat', 'cats');
+ ok(r.body[0].text === 'cats cats' && r.count === 2, 'each match is replaced exactly once');
+ // and stepping past it is how the panel avoids re-matching what it wrote
+ const after = findMatches(r.body, 'cat');
+ ok(nextFrom(after, 0, 0 + 'cats'.length) === 1, 'the cursor lands on the NEXT match, not the new one');
+ ok(nextFrom(after, 0, 999) === 0, 'past the end it wraps to the top');
+ ok(nextFrom([], 0, 0) === -1, 'with nothing found there is nowhere to go');
+}
+
+H('replace all is one undo step');
+{
+ // the store is the thing under test here: ONE commit, so ONE ⌘Z, no matter
+ // how many matches were swept
+ const doc = emptyDoc();
+ doc.body = [b('p1', 'term term term'), b('p2', 'term'), b('p3', 'nothing')];
+ const { Store } = await import('../type/src/store.ts');
+ const store = new Store(doc);
+ const before = store.undoDepth;
+ store.commit(d => { d.body = replaceAll(d.body, 'term', 'clause').body; });
+ ok(store.undoDepth === before + 1, `four replacements cost one undo step (${store.undoDepth - before})`);
+ ok(store.doc.body[0].text === 'clause clause clause', 'and they all landed');
+ store.undo();
+ ok(store.doc.body[0].text === 'term term term' && store.doc.body[1].text === 'term',
+ 'one ⌘Z brings the whole document back');
+}
+
+H('the panel registered itself');
+{
+ const { panels, tools, keys } = await import('../type/src/features.ts');
+ ok(panels().some(p => p.id === 'find'), 'a Find panel');
+ ok(panels().find(p => p.id === 'find')!.label === 'Find', 'whose label is read late, through t()');
+ ok(tools('review').some(t => t.id === 'find'), 'a toolbar button in the review group');
+ ok(keys().some(k => k.key === 'f' && k.mod === true), 'and ⌘F');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-font.ts b/scripts/test-type-font.ts
new file mode 100644
index 00000000..f9395dda
--- /dev/null
+++ b/scripts/test-type-font.ts
@@ -0,0 +1,193 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Per-selection typeface and size.
+//
+// node scripts/test-type-font.ts
+//
+// A font is a CHARACTER property — "make these three words Verdana" — so it is
+// a mark, and doc.type stays the document's default. Two things are easy to
+// get wrong and both lose the user's work silently: setting a size must not
+// discard the family under it, and a family written into a `style` attribute
+// is untrusted document data going into CSS.
+
+import { register } from 'node:module';
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+
+const inline = await import('../type/src/inline.ts');
+const { setFont, fontAt, fontAcross, safeFamily, safeSize, fontStyle, toHtml, normalize } = inline;
+
+let checks = 0, bad = 0;
+const ok = (c: boolean, m: string) => { checks++; if (c) console.log(` ok ${m}`); else { bad++; console.log(` FAIL ${m}`); } };
+const eq = (a: unknown, b: unknown, m: string) => {
+ const same = JSON.stringify(a) === JSON.stringify(b);
+ checks++;
+ if (same) console.log(` ok ${m}`);
+ else { bad++; console.log(` FAIL ${m}\n got ${JSON.stringify(a)}\n want ${JSON.stringify(b)}`); }
+};
+const LEN = 20;
+const fonts = (ms: unknown[]) => (ms as Array<{ t: string }>).filter(m => m.t === 'font');
+
+console.log('\n— setting a family —');
+{
+ const ms = setFont([], LEN, 0, 5, { family: 'Verdana' });
+ eq(fonts(ms).length, 1, 'one font mark');
+ eq([fonts(ms)[0].from, fonts(ms)[0].to], [0, 5], 'over exactly the range');
+ eq(fonts(ms)[0].family, 'Verdana', 'carrying the family');
+ ok(fonts(ms)[0].size === undefined, 'and no size it was not asked for');
+}
+
+console.log('\n— a font REPLACES, it does not nest —');
+{
+ let ms = setFont([], LEN, 0, 10, { family: 'Georgia' });
+ ms = setFont(ms, LEN, 0, 10, { family: 'Verdana' });
+ eq(fonts(ms).length, 1, 'still one mark over the range');
+ eq(fonts(ms)[0].family, 'Verdana', 'the new family wins outright');
+}
+
+console.log('\n— setting a SIZE keeps the family under it —');
+{
+ let ms = setFont([], LEN, 0, 10, { family: 'Verdana' });
+ ms = setFont(ms, LEN, 0, 10, { size: 14 });
+ const f = fonts(ms);
+ eq(f.length, 1, 'one mark');
+ eq([f[0].family, f[0].size], ['Verdana', 14], 'BOTH survive — this is the one that silently lost work');
+}
+
+console.log('\n— a size over PART of a fonted run —');
+{
+ let ms = setFont([], LEN, 0, 10, { family: 'Verdana' });
+ ms = setFont(ms, LEN, 4, 7, { size: 18 });
+ const f = fonts(ms).sort((a, b) => a.from - b.from);
+ eq(f.length, 3, 'the run splits in three');
+ eq(f.map(m => [m.from, m.to, m.family ?? null, m.size ?? null]),
+ [[0, 4, 'Verdana', null], [4, 7, 'Verdana', 18], [7, 10, 'Verdana', null]],
+ 'and every piece keeps Verdana, with the size only in the middle');
+}
+
+console.log('\n— clearing —');
+{
+ let ms = setFont([], LEN, 0, 10, { family: 'Verdana', size: 14 });
+ ms = setFont(ms, LEN, 0, 10, { family: null });
+ eq(fonts(ms)[0].family, undefined, 'null clears the family');
+ eq(fonts(ms)[0].size, 14, 'and leaves the size');
+ const gone = setFont(ms, LEN, 0, 10, { size: null });
+ eq(fonts(gone).length, 0, 'clearing the last attribute drops the mark entirely');
+}
+
+console.log('\n— what the picker shows —');
+{
+ let ms = setFont([], LEN, 0, 10, { family: 'Verdana' });
+ eq(fontAcross(ms, 0, 10).family, 'Verdana', 'one family across the range');
+ ms = setFont(ms, LEN, 5, 10, { family: 'Georgia' });
+ eq(fontAcross(ms, 0, 10).family, 'mixed', 'two families read as mixed, not as the first one');
+ eq(fontAcross(ms, 0, 5).family, 'Verdana', 'and a uniform sub-range still reads plainly');
+ eq(fontAcross([], 0, 10).family, undefined, 'no mark at all is undefined, not mixed');
+ eq(fontAt(ms, 7)?.family, 'Georgia', 'fontAt reads the run at an offset');
+}
+
+console.log('\n— different fonts must not merge —');
+{
+ const ms = normalize([{ t: 'font', from: 0, to: 5, family: 'Verdana' },
+ { t: 'font', from: 5, to: 10, family: 'Georgia' }] as never, LEN);
+ eq(fonts(ms).length, 2, 'two abutting runs stay two');
+ eq(fonts(ms).map(m => m.family), ['Verdana', 'Georgia'], 'each keeps its own family');
+ const same = normalize([{ t: 'font', from: 0, to: 5, family: 'Verdana' },
+ { t: 'font', from: 5, to: 10, family: 'Verdana' }] as never, LEN);
+ eq(fonts(same).length, 1, 'but two runs of the SAME family do merge');
+}
+
+console.log('\n— the CSS boundary —');
+{
+ ok(safeFamily('Georgia, serif') === 'Georgia, serif', 'an ordinary stack passes');
+ ok(safeFamily('"Iowan Old Style", Palatino, serif') === '"Iowan Old Style", Palatino, serif', 'quoted names pass');
+ const ATTACKS: Array<[string, string]> = [
+ ['Georgia; background: url(https://tracker/x.png)', 'a second declaration'],
+ ['Georgia; behavior: url(#x)', 'a behavior url'],
+ ['expression(alert(1))', 'an expression()'],
+ ['url(javascript:alert(1))', 'a javascript url'],
+ ['Georgia"><script>alert(1)</script>', 'an attribute break-out'],
+ ['a'.repeat(300), 'an absurdly long value'],
+ ];
+ for (const [attack, what] of ATTACKS) ok(safeFamily(attack) === null, `refused: ${what}`);
+
+ eq(safeSize(14), 14, 'a plain size passes');
+ eq(safeSize(0), null, 'zero is refused');
+ eq(safeSize(1e6), null, 'and so is a page-breaking one');
+ eq(safeSize(NaN), null, 'and NaN');
+
+ // the rendered attribute, which is what actually reaches the page
+ eq(fontStyle({ t: 'font', from: 0, to: 1, family: 'Georgia', size: 14 } as never),
+ 'font-family:Georgia;font-size:14px', 'a good mark renders both properties');
+ eq(fontStyle({ t: 'font', from: 0, to: 1, family: 'Georgia; background: url(x)' } as never),
+ '', 'a refused family renders NOTHING, not a broken declaration');
+
+ const html = toHtml('hello world', [{ t: 'font', from: 0, to: 5, family: 'Georgia"><script>alert(1)</script>' }] as never);
+ ok(!html.includes('<script'), 'and no script reaches the output');
+ ok(html.includes('hello'), 'while the text itself survives');
+}
+
+console.log('\n— it reaches paper —');
+{
+ // print.ts renders through render.ts blockHtml, which is the same toHtml
+ // this rig has been testing. A per-run typeface that only existed on screen
+ // would be a strange thing for a word processor to have.
+ const { blockHtml } = await import('../type/src/render.ts');
+ const html = blockHtml({ id: 'p', kind: 'para', text: 'hello world',
+ marks: [{ t: 'font', from: 0, to: 5, family: 'Verdana, sans-serif', size: 14 }] } as never);
+ ok(/font-family:Verdana, sans-serif/.test(html), 'the print path emits the family');
+ ok(/font-size:14px/.test(html), 'and the size');
+}
+
+console.log('\n— the DOM round trip, which is what every keystroke does —');
+{
+ // The editor reads a block back out of contentEditable on EVERY keystroke
+ // (render.ts readBlock -> fromDom). A mark whose payload does not survive
+ // that trip is silently destroyed by the next character typed. This was a
+ // live bug for tracked changes: <ins> was in no map and vanished, and <del>
+ // mapped to a plain strikethrough, so a tracked deletion came back as
+ // ordinary struck text with its author gone.
+ const { JSDOM } = await (async () => {
+ try { return await import('jsdom'); } catch { return { JSDOM: null as never }; }
+ })();
+ if (!JSDOM) {
+ console.log(' -- skipped: jsdom is not installed (the browser check below covers it)');
+ } else {
+ const dom = new JSDOM('<div></div>');
+ const g = globalThis as { document?: unknown };
+ const had = g.document;
+ g.document = dom.window.document;
+ const trip = (text: string, marks: unknown[]) => {
+ const host = dom.window.document.createElement('div');
+ host.innerHTML = toHtml(text, marks as never);
+ return inline.fromDom(host);
+ };
+
+ const font = trip('hello world', [{ t: 'font', from: 0, to: 5, family: 'Verdana, sans-serif', size: 14 }]);
+ eq(font.text, 'hello world', 'font: text survives');
+ eq(font.marks, [{ t: 'font', from: 0, to: 5, family: 'Verdana, sans-serif', size: 14 }],
+ 'font: family AND size survive the round trip');
+
+ const ins = trip('abc', [{ t: 'ins', from: 0, to: 3, by: 'Counsel', at: '2026-08-18T10:00:00Z' }]);
+ eq(ins.marks, [{ t: 'ins', from: 0, to: 3, by: 'Counsel', at: '2026-08-18T10:00:00Z' }],
+ 'ins: survives WITH its author and timestamp');
+
+ const del = trip('abc', [{ t: 'del', from: 0, to: 3, by: 'Counsel', at: '2026-08-18T10:00:00Z' }]);
+ eq(del.marks, [{ t: 'del', from: 0, to: 3, by: 'Counsel', at: '2026-08-18T10:00:00Z' }],
+ 'del: stays a DELETION, not a strikethrough');
+
+ const bold = trip('abc', [{ t: 'b', from: 0, to: 3 }]);
+ eq(bold.marks, [{ t: 'b', from: 0, to: 3 }], 'plain marks are unaffected');
+
+ // a <del> from OUTSIDE bento still means strikethrough, as it does
+ // everywhere else on the web
+ const host = dom.window.document.createElement('div');
+ host.innerHTML = '<del>abc</del>';
+ eq(inline.fromDom(host).marks, [{ t: 's', from: 0, to: 3 }], 'a pasted <del> is still a strikethrough');
+
+ if (had === undefined) delete g.document; else g.document = had;
+ }
+}
+
+console.log(`\n${checks - bad}/${checks} checks passed`);
+if (bad) process.exit(1);
diff --git a/scripts/test-type-image.ts b/scripts/test-type-image.ts
new file mode 100644
index 00000000..78da896b
--- /dev/null
+++ b/scripts/test-type-image.ts
@@ -0,0 +1,78 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type pictures. node scripts/test-type-image.ts
+//
+// An image is the first block that is not text, and that makes it the first one
+// pagination cannot see: paginate.ts measures LINE BOXES through a TreeWalker
+// over text nodes, so a picture contributed height nobody had counted. It now
+// carries `data-atomic` and is measured as one box — which is not an
+// approximation but the truth, since a picture cannot be split across a page.
+//
+// The parts that can be tested without a browser are here: what may be a
+// source, and what the parser does with a picture it cannot use. The layout
+// behaviour is verified in the browser and the numbers are in the commit.
+
+import { parseDoc, emptyDoc, SAFE_IMG, IMAGE_EMBED_BUDGET } from '../type/src/model.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+H('what may be a source');
+{
+ // A document is untrusted input and this string goes straight into an <img>.
+ const good = [
+ 'data:image/png;base64,iVBORw0KGgo=',
+ 'data:image/jpeg;base64,/9j/4AAQ',
+ 'data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=',
+ // no `;` at all: a data URI only has one when it carries a parameter such
+ // as ;base64. This form is valid, common, and WAS REFUSED — the pattern
+ // required the semicolon, so every unencoded SVG was silently dropped.
+ 'data:image/svg+xml,%3Csvg%3E%3C/svg%3E',
+ 'https://example.com/a.png',
+ 'http://example.com/a.png',
+ './beside.png', '../up.png', '/root.png',
+ ];
+ for (const s of good) ok(SAFE_IMG.test(s), `accepted: ${s.slice(0, 42)}`);
+
+ const bad = [
+ 'javascript:alert(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'data:image/png', // no separator, so not a payload
+ 'vbscript:msgbox',
+ 'file:///etc/passwd',
+ ' javascript:alert(1)', // leading space must not slip past
+ ];
+ for (const s of bad) ok(!SAFE_IMG.test(s), `refused: ${s.slice(0, 42)}`);
+}
+
+H('the parser repairs a picture it cannot use');
+{
+ const doc = emptyDoc();
+ const r = parseDoc(JSON.stringify({ ...doc, body: [
+ { id: 'good', kind: 'image', text: '', image: { src: 'https://example.com/a.png', alt: 'A chart', w: 0.5 } },
+ { id: 'nosrc', kind: 'image', text: '', image: { alt: 'The Q3 revenue chart' } },
+ { id: 'evil', kind: 'image', text: '', image: { src: 'javascript:alert(1)', alt: 'nope' } },
+ { id: 'wide', kind: 'image', text: '', image: { src: 'https://example.com/b.png', w: 9 } },
+ ] }));
+ ok(r.ok, 'it still parses');
+ if (r.ok) {
+ ok(r.doc.body[0].kind === 'image' && r.doc.body[0].image?.w === 0.5, 'a good picture survives with its width');
+ ok(r.doc.body[1].kind === 'para', 'a picture with no source becomes a paragraph');
+ ok(r.doc.body[1].text === 'The Q3 revenue chart',
+ 'and keeps its alt text as the words — a vanished figure is the worse outcome');
+ ok(r.doc.body[2].kind === 'para', 'a javascript: source is refused, not sanitised into the document');
+ ok(r.doc.body[3].image?.w === undefined, 'a nonsense width is dropped rather than clamped to a guess');
+ ok(r.repaired.length >= 3, `and every repair is reported (${r.repaired.length})`);
+ }
+}
+
+H('the embed budget is a real number, not a vibe');
+{
+ ok(IMAGE_EMBED_BUDGET > 0 && IMAGE_EMBED_BUDGET <= 16 * 1024 * 1024,
+ `a sane ceiling for a self-contained file (${(IMAGE_EMBED_BUDGET / 1024 / 1024).toFixed(1)} MB)`);
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-inline.ts b/scripts/test-type-inline.ts
index 1c2902f0..75187db4 100644
--- a/scripts/test-type-inline.ts
+++ b/scripts/test-type-inline.ts
@@ -22,6 +22,7 @@
// because the round trip has to be checkable in CI, and a property only
// checked in a browser is a property nobody checks.
+import { readFileSync } from 'node:fs';
import {
normalize, coversAll, activeAt, addMark, removeMark, toggleMark, shift,
toHtml, fromDom, type Mark,
@@ -219,5 +220,51 @@ H('fuzz: 2,000 random mark sets round-trip exactly');
if (bad) console.log(` ${worst}`);
}
+H('an href cannot escape its attribute, and cannot carry a scheme');
+{
+ // Both of these were live. A document is untrusted input, so neither needed a
+ // user of the link feature: a hand-written #bento-doc block, a pasted <a>
+ // (fromDom copies the attribute verbatim) or a sync op would do, and
+ // render.ts puts the result through innerHTML.
+ const inject = toHtml('click me', [{ t: 'link', from: 0, to: 8,
+ href: 'https://x" onmouseover="alert(1)' }] as never);
+ ok(/^<a href="[^"]*">click me<\/a>$/.test(inject),
+ `the attribute stays one attribute: ${inject}`);
+ // NO SUBSTRING SEARCH. `onmouseover=` survives inside the escaped attribute
+ // VALUE, where it is inert, so grepping for it fails on correct output — and
+ // a cleverer regex over the same string fails the same way, because a regex
+ // cannot tell an attribute from text that looks like one. The assertion
+ // above IS the integrity check: `[^"]*` cannot contain a quote, so if the
+ // whole tag matches `<a href="...">` then the value never closed early and
+ // no second attribute exists. Two agents wrote the substring version first,
+ // which is why this note is here rather than a third one.
+
+ for (const bad of ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html,<script>',
+ 'vbscript:msgbox', 'file:///etc/passwd']) {
+ const out = toHtml('x', [{ t: 'link', from: 0, to: 1, href: bad }] as never);
+ ok(out === '<a>x</a>', `${bad.slice(0, 24)} renders with no href, keeping the words: ${out}`);
+ }
+ for (const good of ['https://example.com/a?b=1&c=2', 'mailto:[email protected]', '#anchor', '/rel', './rel']) {
+ const out = toHtml('x', [{ t: 'link', from: 0, to: 1, href: good }] as never);
+ ok(/^<a href="/.test(out), `${good} survives: ${out}`);
+ }
+ // & inside a real href must be escaped, not dropped
+ const amp = toHtml('x', [{ t: 'link', from: 0, to: 1, href: 'https://e.com/?a=1&b=2' }] as never);
+ ok(amp.includes('&amp;b=2'), `an ampersand in a query is escaped: ${amp}`);
+}
+
+H('the source carries no literal control characters');
+{
+ // A literal NUL in the merge key made git and grep treat this whole file as
+ // binary, which hid it from ordinary tooling and cost a debugging cycle. The
+ // separator is still a NUL at runtime; it is written as an escape.
+ const src = readFileSync(new URL('../type/src/inline.ts', import.meta.url), 'utf8');
+ const ctrl = [...src].filter(c => c.charCodeAt(0) < 9 || (c.charCodeAt(0) > 13 && c.charCodeAt(0) < 32));
+ ok(ctrl.length === 0, `no literal control characters in the source (${ctrl.length})`);
+ ok(normalize([{ t: 'link', from: 0, to: 2, href: 'a' },
+ { t: 'link', from: 2, to: 4, href: 'b' }] as never, 4).length === 2,
+ 'and two different links still do not merge, so the separator still works');
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`);
if (failures) process.exit(1);
diff --git a/scripts/test-type-layout.ts b/scripts/test-type-layout.ts
new file mode 100644
index 00000000..6952de06
--- /dev/null
+++ b/scripts/test-type-layout.ts
@@ -0,0 +1,304 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type paragraph-layout and page-setup rig. node scripts/test-type-layout.ts
+//
+// The geometry and the property→CSS mapping in type/src/layout.ts are pure, and
+// they are the half that has to be right: a page is 794px wide or the printed
+// A4 is wrong, and nobody finds that out until it is on paper. So everything
+// below runs without a browser.
+//
+// What it holds down, in the order it burned:
+//
+// · A4 and Letter convert at 96px to the inch, because that is what a CSS px
+// IS — and print.ts already emits @page in px.
+// · turning the page swaps width and height and nothing else.
+// · margins that leave no text area are REJECTED. Let through, they reach
+// pagination as a negative page body, where the break loop places a page
+// every zero pixels until its 2000-iteration guard fires.
+// · a property a paragraph does not carry means THE DOCUMENT'S — so the
+// document can change its mind and every untouched paragraph follows.
+// · the CSS for each alignment, and the margin/padding pair that the
+// stylesheet's `p + p` hack forces space-before to override as a unit.
+// · with no keep hints anywhere, atomize/breakY reproduce the line-by-line
+// break paginate.ts does today, exactly. That is the condition for putting
+// them in the core loop at all.
+
+import {
+ PX_PER_IN, PX_PER_MM, PAPER, matchSize, orientationOf, withOrientation, withSize,
+ margins, withMargins, contentBox, validatePage, unitFor, formatLen, parseLen,
+ DOC_DEFAULTS, effective, docEffective, writeProps, blockStyle, docVars, pageVars,
+ atomize, breakY, type PageGeom, type LineBox,
+} from '../type/src/layout.ts';
+import { emptyDoc, LETTER, type Block, type TypeDoc } from '../type/src/model.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const block = (id: string, extra: Record<string, unknown> = {}): Block =>
+ ({ id, kind: 'para', text: `${id} text`, ...extra }) as Block;
+
+H('paper sizes convert at 96px to the inch');
+{
+ ok(PX_PER_IN === 96, 'the inch is 96px, by the definition of a CSS px');
+ ok(Math.abs(PX_PER_MM - 96 / 25.4) < 1e-12, 'and the millimetre follows from it');
+
+ ok(PAPER.letter.width === 816 && PAPER.letter.height === 1056,
+ `US Letter is 8.5×11in = ${PAPER.letter.width}×${PAPER.letter.height}px`);
+ ok(PAPER.legal.width === 816 && PAPER.legal.height === 1344,
+ `US Legal is 8.5×14in = ${PAPER.legal.width}×${PAPER.legal.height}px`);
+ ok(PAPER.a4.width === 794 && PAPER.a4.height === 1123,
+ `A4 is 210×297mm = ${PAPER.a4.width}×${PAPER.a4.height}px`);
+ // the rounding is the only lossy step, and it must stay under a tenth of a mm
+ const drift = Math.abs(PAPER.a4.width / PX_PER_MM - 210);
+ ok(drift < 0.1, `rounding A4 to whole px costs ${drift.toFixed(3)}mm`);
+
+ // the model's own default IS US Letter — if these disagree, "Letter" in the
+ // dialog would silently be a custom size
+ ok(LETTER.width === PAPER.letter.width && LETTER.height === PAPER.letter.height,
+ 'the model default is the same Letter this module offers');
+ ok(matchSize(LETTER) === 'letter', 'and it is recognised as Letter, not custom');
+ ok(matchSize({ ...LETTER, width: 500 }) === undefined, 'an odd page is custom');
+}
+
+H('orientation swaps width and height');
+{
+ const p = withSize(LETTER, 'a4');
+ ok(orientationOf(p) === 'portrait', 'A4 portrait is taller than wide');
+ const land = withOrientation(p, 'landscape');
+ ok(land.width === p.height && land.height === p.width,
+ `landscape A4 is ${land.width}×${land.height}`);
+ ok(orientationOf(land) === 'landscape', 'and reads back as landscape');
+ ok(matchSize(land) === 'a4', 'a turned page is still A4');
+ ok(land.marginTop === p.marginTop && land.marginX === p.marginX,
+ 'turning the page leaves the margins alone');
+ ok(withOrientation(land, 'landscape').width === land.width, 'turning it the way it already faces does nothing');
+ // a custom sheet turns too — landscape is not a lookup
+ const odd = withOrientation({ ...LETTER, width: 300, height: 500 }, 'landscape');
+ ok(odd.width === 500 && odd.height === 300, 'a custom sheet turns as well');
+ // choosing a size keeps the orientation you were in
+ ok(orientationOf(withSize(land, 'legal')) === 'landscape', 'picking a size keeps the current orientation');
+}
+
+H('margins that leave no text area are rejected, not measured');
+{
+ ok(validatePage(LETTER).ok, 'US Letter with 104px margins is fine');
+ const c = contentBox(LETTER);
+ ok(c.width === 816 - 208 && c.height === 1056 - 208, `text area ${c.width}×${c.height}`);
+
+ const noWidth = { ...LETTER, marginX: 410 }; // 820 > 816
+ const v1 = validatePage(noWidth);
+ ok(!v1.ok && v1.fault === 'no-width', 'side margins wider than the sheet are refused');
+ ok(contentBox(noWidth).width < 0, 'and the measure they would have produced is NEGATIVE');
+
+ const noHeight = validatePage({ ...LETTER, marginTop: 600, marginBottom: 600 });
+ ok(!noHeight.ok && noHeight.fault === 'no-height', 'top and bottom margins that meet are refused');
+ // the boundary: exactly one inch of text is allowed, a hair less is not
+ const exact = { ...LETTER, marginX: (816 - 96) / 2 };
+ ok(validatePage(exact).ok, 'exactly one inch of measure is allowed');
+ ok(!validatePage({ ...exact, marginX: (816 - 95) / 2 }).ok, 'less than an inch is not');
+
+ ok(!validatePage({ ...LETTER, width: 50, height: 50 }).ok, 'a stamp-sized sheet is refused');
+ ok(!validatePage({ ...LETTER, width: 99999 }).ok, 'and so is a sheet no printer takes');
+}
+
+H('four margins, stored as the fewest fields that say it');
+{
+ const sym = withMargins(LETTER, { top: 96, bottom: 96, left: 72, right: 72 });
+ ok(sym.marginX === 72, 'equal sides are stored as marginX alone');
+ ok(sym.marginLeft === undefined && sym.marginRight === undefined,
+ 'so a symmetric page never needs a field older builds have not shipped');
+ ok(margins(sym).left === 72 && margins(sym).right === 72, 'and read back as both sides');
+
+ const bound = withMargins(LETTER, { top: 96, bottom: 96, left: 144, right: 72 });
+ ok(bound.marginLeft === 144 && bound.marginRight === 72, 'a bound document stores both sides');
+ ok(margins(bound).left === 144 && margins(bound).right === 72, 'and reads them back');
+ ok(contentBox(bound).width === 816 - 216, 'the measure uses both, not twice one');
+ // an older build reading only marginX must not overlap the text off the page
+ ok(bound.marginX === 72, 'marginX stays as the narrower side, so an old build under-indents rather than clipping');
+ const plain = { ...LETTER } as PageGeom;
+ ok(margins(plain).left === LETTER.marginX, 'a page with no left/right falls back to marginX');
+}
+
+H('a property a paragraph does not carry is the document’s');
+{
+ const doc: TypeDoc = emptyDoc();
+ const plain = block('p1');
+ ok(effective(doc, plain).align === 'justify',
+ 'a paragraph with no align is justified — the built-in default, not a stored value');
+ ok(!('align' in (plain as Record<string, unknown>)), 'and nothing was written to it to say so');
+ ok(DOC_DEFAULTS.align === 'justify', 'justify stays the default: Knuth–Plass is the point');
+
+ // the document changes its mind and the untouched paragraph follows
+ (doc as { layout?: unknown }).layout = { align: 'left' };
+ ok(effective(doc, plain).align === 'left', 'change the document and every untouched paragraph follows');
+ ok(docEffective(doc).align === 'left', 'the document default reads back');
+ ok(docEffective(doc).lh === DOC_DEFAULTS.lh, 'and what the document does not say is still built-in');
+
+ // a paragraph that says something keeps saying it
+ const centred = block('p2', { align: 'center' });
+ ok(effective(doc, centred).align === 'center', 'a paragraph override beats the document');
+
+ // writing the current default DELETES rather than stores
+ const b = block('p3');
+ writeProps(doc, b, { align: 'center' });
+ ok((b as Record<string, unknown>).align === 'center', 'a difference is written');
+ writeProps(doc, b, { align: 'left' });
+ ok(!('align' in (b as Record<string, unknown>)),
+ 'setting the value the document already has deletes the field instead of storing it');
+ writeProps(doc, b, { sb: 12 });
+ ok((b as Record<string, unknown>).sb === 12, 'space before is written');
+ writeProps(doc, b, { sb: undefined });
+ ok(!('sb' in (b as Record<string, unknown>)), 'and undefined means back to the default');
+ writeProps(doc, b, { keepNext: true });
+ ok((b as Record<string, unknown>).keepNext === true, 'a keep flag is written as true');
+ writeProps(doc, b, { keepNext: undefined });
+ ok(!('keepNext' in (b as Record<string, unknown>)), 'and cleared by removal, never stored as false');
+ writeProps(doc, b, { lh: 1.5 });
+ ok(Object.keys(b as object).join() === 'id,kind,text,lh',
+ `a paragraph carries only what makes it different (${Object.keys(b as object).join(', ')})`);
+}
+
+H('the CSS a paragraph produces');
+{
+ ok(blockStyle(block('a')) === '', 'a paragraph with no properties produces NO css, so it inherits');
+ ok(blockStyle(block('a', { align: 'left' })) === 'text-align:left', 'left');
+ ok(blockStyle(block('a', { align: 'center' })) === 'text-align:center', 'centre');
+ ok(blockStyle(block('a', { align: 'right' })) === 'text-align:right', 'right');
+ ok(blockStyle(block('a', { align: 'justify' })) === 'text-align:justify',
+ 'justify is emitted too — it must beat a document default of left');
+
+ ok(blockStyle(block('a', { lh: 1.5 })) === 'line-height:1.5', 'line spacing is a unitless multiple');
+ ok(blockStyle(block('a', { ind: 24 })) === 'text-indent:24px', 'first-line indent');
+ ok(blockStyle(block('a', { sa: 18 })) === 'margin-bottom:18px', 'space after');
+ // the stylesheet spaces consecutive paragraphs with margin-top:-10px +
+ // padding-top:10px; overriding only the margin adds 10px to what was asked
+ ok(blockStyle(block('a', { sb: 20 })) === 'margin-top:20px;padding-top:0',
+ 'space before clears the stylesheet’s padding half of the p + p pair');
+ ok(blockStyle(block('a', { align: 'center', lh: 2, sb: 6, sa: 6, ind: 0 })) ===
+ 'text-align:center;line-height:2;margin-top:6px;padding-top:0;margin-bottom:6px;text-indent:0px',
+ 'and everything together, in one declaration list');
+ ok(blockStyle(block('a', { keepNext: true, keepTogether: true, breakBefore: true })) === '',
+ 'the keep hints produce no CSS at all — they are pagination’s, not the browser’s');
+}
+
+H('document defaults go on the paper, not into every paragraph');
+{
+ const doc = emptyDoc();
+ ok(Object.keys(docVars(doc)).length === 0,
+ 'a document that never touched layout sets nothing, so the stylesheet is untouched');
+ (doc as { layout?: unknown }).layout = { align: 'left', lh: 1.5, sa: 14 };
+ const v = docVars(doc);
+ ok(v['--lay-align'] === 'left' && v['--lay-lh'] === '1.5' && v['--lay-sa'] === '14px',
+ 'the defaults become custom properties');
+ ok(v['--lay-ind'] === undefined, 'and what the document does not say stays with the stylesheet');
+
+ const g = pageVars({ ...LETTER, marginLeft: 144 } as PageGeom);
+ ok(g['--page-w'] === '816px' && g['--mar-t'] === '104px', 'the page geometry drives the paper');
+ ok(g['--mar-l'] === '144px' && g['--mar-r'] === '104px', 'including a left margin the sheet alone does not know');
+}
+
+H('break atoms: with no hints, the line-by-line break of today');
+{
+ const lines = (id: string, from: number, n: number): LineBox[] =>
+ Array.from({ length: n }, (_, i) => ({ top: from + i * 20, bottom: from + i * 20 + 20, id }));
+ const body = [block('p1'), block('p2'), block('p3')];
+ const boxes = [...lines('p1', 0, 3), ...lines('p2', 60, 3), ...lines('p3', 120, 3)];
+
+ const flat = atomize(body, boxes);
+ ok(flat.length === 9, 'with no hints every LINE is its own atom, as pagination is free to break today');
+ // the loop paginate.ts runs today, reproduced
+ const naive = (start: number, avail: number) => {
+ for (const b of boxes) {
+ if (b.top < start - 0.5) continue;
+ if (b.bottom - start > avail) return b.top;
+ }
+ return Infinity;
+ };
+ let same = true;
+ for (const avail of [30, 45, 50, 100, 130, 200]) {
+ for (const start of [0, 20, 60, 100]) {
+ if (breakY(flat, start, avail) !== naive(start, avail)) { same = false; console.log(` start ${start} avail ${avail}: ${breakY(flat, start, avail)} vs ${naive(start, avail)}`); }
+ }
+ }
+ ok(same, 'breakY matches it for every start and page height tried');
+ ok(breakY(flat, 0, 1000) === Infinity, 'and reports Infinity when the rest of the document fits');
+}
+
+H('break atoms: the hints');
+{
+ const lines = (id: string, from: number, n: number): LineBox[] =>
+ Array.from({ length: n }, (_, i) => ({ top: from + i * 20, bottom: from + i * 20 + 20, id }));
+
+ // keep-together: a paragraph that would straddle the break moves whole
+ {
+ const body = [block('p1'), block('p2', { keepTogether: true })];
+ const boxes = [...lines('p1', 0, 3), ...lines('p2', 60, 3)];
+ const loose = atomize([block('p1'), block('p2')], boxes);
+ ok(breakY(loose, 0, 80) === 80, 'without the hint the break falls mid-paragraph, at y=80');
+ const kept = atomize(body, boxes);
+ ok(kept.length === 4, 'the kept paragraph is one atom and the loose one is three');
+ ok(breakY(kept, 0, 80) === 60, 'with it the whole paragraph moves to the next page, at y=60');
+ }
+
+ // keep-with-next: the heading rule
+ {
+ const body = [block('h', { keepNext: true }), block('p')];
+ const boxes = [...lines('h', 0, 1), ...lines('p', 20, 4)];
+ const atoms = atomize(body, boxes);
+ ok(atoms.length === 1, 'a keepNext block fuses with the one after it, lines and all');
+ ok(breakY(atoms, 0, 200) === Infinity, 'and is never parted while the page can hold the pair');
+ const body2 = [block('a'), block('h', { keepNext: true }), block('p')];
+ const boxes2 = [...lines('a', 0, 2), ...lines('h', 40, 1), ...lines('p', 60, 2)];
+ const at2 = atomize(body2, boxes2);
+ ok(breakY(at2, 0, 50) === 40, 'a heading whose paragraph will not fit goes over with it');
+ }
+
+ // an author's page break
+ {
+ const body = [block('p1'), block('p2', { breakBefore: true })];
+ const boxes = [...lines('p1', 0, 2), ...lines('p2', 40, 2)];
+ const atoms = atomize(body, boxes);
+ ok(breakY(atoms, 0, 1000) === 40, 'a page break is honoured even though everything fits');
+ ok(breakY(atoms, 40, 1000) === Infinity, 'and does not fire again once the page starts there');
+ }
+
+ // a break the author asked for beats a keep that would swallow it
+ {
+ const body = [block('h', { keepNext: true }), block('p', { breakBefore: true })];
+ const boxes = [...lines('h', 0, 1), ...lines('p', 20, 2)];
+ const atoms = atomize(body, boxes);
+ ok(atoms[0].lines.length === 1 && atoms[0].lines[0].id === 'h',
+ 'keepNext does not fuse across a break the author inserted');
+ ok(atoms[1].forced, 'the break rides on the first atom of the paragraph that asked for it');
+ ok(breakY(atoms, 0, 1000) === 20, 'so the break still happens');
+ }
+
+ // the escape hatch: an atom taller than the page
+ {
+ const body = [block('p', { keepTogether: true })];
+ const boxes = Array.from({ length: 10 }, (_, i) => ({ top: i * 20, bottom: i * 20 + 20, id: 'p' }));
+ const atoms = atomize(body, boxes);
+ const y = breakY(atoms, 0, 100);
+ ok(y === 100, `a keep-together paragraph taller than the page breaks by line anyway (y=${y})`);
+ ok(y > 0, 'because returning the page’s own start would emit zero-height pages forever');
+ }
+}
+
+H('units follow the reader, never the document');
+{
+ ok(unitFor('en-US') === 'in' && unitFor('en-CA') === 'in' && unitFor('en-PH') === 'in',
+ 'the three countries that never adopted ISO 216 get inches');
+ ok(unitFor('sv-SE') === 'mm' && unitFor('en-GB') === 'mm' && unitFor('ja-JP') === 'mm',
+ 'everyone else gets millimetres');
+ ok(formatLen(PAPER.a4.width, 'mm') === '210', 'A4 shows as 210mm');
+ ok(formatLen(PAPER.letter.width, 'in') === '8.5', 'Letter shows as 8.5in');
+ ok(parseLen('8.5', 'in') === 816, 'and 8.5in reads back as 816px');
+ ok(parseLen('210', 'mm') !== null && Math.round(parseLen('210', 'mm')!) === 794, '210mm reads back as 794px');
+ ok(parseLen('21,0', 'mm') !== null, 'a decimal comma is a decimal point');
+ ok(parseLen('wide', 'in') === null, 'and a word is not a length');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-link.ts b/scripts/test-type-link.ts
new file mode 100644
index 00000000..b3dc238b
--- /dev/null
+++ b/scripts/test-type-link.ts
@@ -0,0 +1,280 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type link rig.
+//
+// node scripts/test-type-link.ts (Node ≥ 23.6 strips types natively)
+//
+// WHAT THIS PROVES, in the order it matters.
+//
+// 1. SANITISING, because it is a security boundary and not a nicety. A Bento
+// document is untrusted input by house rule, and an href is the one field
+// in this model that a browser will EXECUTE. `javascript:` is the case
+// everyone writes a test for; the ones that actually get shipped are
+// `java\tscript:` (browsers strip the tab before parsing, so a naive
+// startsWith check reads it as a relative path) and the schemes a denylist
+// had not heard of yet, which is why this is an allowlist.
+//
+// 2. THAT TWO DIFFERENT LINKS DO NOT MERGE. `normalize()` fuses touching marks
+// of the same kind, so if href were not part of its grouping key, linking
+// two adjacent words to two different pages would silently produce ONE link
+// — and the author would not find out until a reader clicked. It IS part of
+// the key; this rig pins that, because a well-meaning simplification of
+// that key is exactly the change nobody would think to test.
+//
+// 3. THAT AUTOLINK DOES NOT FIRE. The firing cases are easy and the restraint
+// is the feature: this runs on every keystroke of ordinary prose, and a
+// rule loose enough to catch `example.com` also catches `index.html`,
+// `README.md` and `Mr.Smith`. Half the autolink section is negative.
+//
+// No DOM: link.ts keeps its logic above the browser guard for exactly this
+// reason, so all of the above is a CI gate rather than something checked by
+// hand in a browser once.
+
+import {
+ sanitizeUrl, safeHref, setLink, linkAt, hasLinkIn, autolinkAt,
+} from '../type/src/link.ts';
+import { normalize, toHtml, type Mark } from '../type/src/inline.ts';
+import { safeHref as renderGate } from '../type/src/inline.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+const J = (v: unknown) => JSON.stringify(v);
+
+// ───────────────────────────────────────────────────────── sanitising
+H('a hostile scheme never survives');
+{
+ const hostile = [
+ 'javascript:alert(1)',
+ 'JaVaScRiPt:alert(1)',
+ ' javascript:alert(1)',
+ 'java\tscript:alert(1)',
+ 'java\nscript:alert(1)',
+ 'java\rscript:alert(1)',
+ 'javascript :alert(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'DATA:text/html;base64,PHNjcmlwdD4=',
+ 'vbscript:msgbox(1)',
+ 'blob:https://evil.example/9f',
+ 'filesystem:https://evil.example/temporary/x',
+ 'jar:https://evil.example!/a',
+ ];
+ for (const h of hostile) ok(sanitizeUrl(h) === null, `refused: ${J(h)}`);
+ ok(safeHref('javascript:alert(1)') === null, 'and refused again at the moment of following');
+}
+
+H('an honest address is kept, and completed the way the author meant it');
+{
+ const cases: Array<[string, string]> = [
+ ['https://example.com/a', 'https://example.com/a'],
+ ['http://example.com', 'http://example.com'],
+ ['mailto:[email protected]', 'mailto:[email protected]'],
+ ['tel:+441234567890', 'tel:+441234567890'],
+ ['example.com', 'https://example.com'],
+ ['www.example.com/x?y=1#z', 'https://www.example.com/x?y=1#z'],
+ ['#clause-3', '#clause-3'],
+ // Protocol-relative. A Bento document is one FILE, usually opened from
+ // file://, where `//host` means a local path — never the web page the
+ // author was pointing at. Promoted, not passed through, and not refused.
+ ['//evil.example/x', 'https://evil.example/x'],
+ ['///evil.example', 'https://evil.example'],
+ ['/schedule-a', 'https://schedule-a'],
+ ];
+ for (const [raw, want] of cases) ok(sanitizeUrl(raw) === want, `${J(raw)} → ${J(want)} (got ${J(sanitizeUrl(raw))})`);
+ ok(sanitizeUrl('') === null && sanitizeUrl(' ') === null, 'nothing typed is nothing linked');
+}
+
+H('nothing this feature stores can break out of an href attribute');
+{
+ // inline.ts escapes & < > in an attribute value and NOT the double quote, so
+ // an href carrying one closes the attribute and everything after it becomes
+ // markup. That is a core bug and it is written up at the top of link.ts; this
+ // rig pins the half of it this feature owns — that the strings THIS code
+ // produces cannot exercise it, whoever fixes the renderer and whenever.
+ const nasty = 'https://x" onmouseover="alert(1)';
+ const href = sanitizeUrl(nasty)!;
+ ok(href !== null && !href.includes('"'), `a quote is percent-encoded: ${J(href)}`);
+ const html = toHtml('click', [{ t: 'link', from: 0, to: 5, href }]);
+ ok(/^<a href="[^"]*">click<\/a>$/.test(html),
+ `so the anchor is ONE attribute inside ONE pair of quotes, with nothing bolted on after it — ${html}`);
+ for (const ch of ['"', "'", '`', '<', '>']) {
+ ok(!sanitizeUrl(`https://x${ch}y`)!.includes(ch), `${J(ch)} never reaches the document`);
+ }
+}
+
+// ─────────────────────────────────────────────────────────── applying
+const TEXT = 'See the schedule and the annex for the details.';
+
+H('applying a link over a selection');
+{
+ const marks = setLink([], TEXT.length, 8, 16, 'https://example.com/schedule');
+ ok(J(marks) === J([{ t: 'link', from: 8, to: 16, href: 'https://example.com/schedule' }]),
+ `the selected range carries the mark and nothing else does — ${J(marks)}`);
+ ok(TEXT.slice(8, 16) === 'schedule', 'and it covers the words that were selected');
+ ok(toHtml(TEXT, marks).includes('<a href="https://example.com/schedule">schedule</a>'),
+ 'which renders as one anchor around them');
+}
+
+H('a link lands beside other formatting without disturbing it');
+{
+ const bold: Mark[] = [{ t: 'b', from: 0, to: 20 }];
+ const marks = setLink(bold, TEXT.length, 8, 16, 'https://example.com/s');
+ ok(marks.filter(m => m.t === 'b').length === 1, 'the bold run is still one run');
+ ok(marks.filter(m => m.t === 'b')[0].to === 20, 'and still the same length');
+}
+
+H('re-targeting a link REPLACES it — it is not a toggle');
+{
+ const one = setLink([], TEXT.length, 8, 16, 'https://one.example');
+ const two = setLink(one, TEXT.length, 8, 16, 'https://two.example');
+ ok(two.length === 1 && two[0].href === 'https://two.example',
+ `editing the address leaves exactly one link, the new one — ${J(two)}`);
+}
+
+H('THE ONE THAT WOULD BE SILENT: two adjacent DIFFERENT links do not merge');
+{
+ // 'schedule' 8–16, ' and ' 16–21, 'the annex' 21–30 — the middle words are
+ // linked too, so the two marks TOUCH. normalize() fuses touching marks of the
+ // same kind; it must not fuse these.
+ let marks = setLink([], TEXT.length, 8, 21, 'https://example.com/schedule');
+ marks = setLink(marks, TEXT.length, 21, 30, 'https://example.com/annex');
+ ok(marks.length === 2, `two touching links stay two marks (got ${marks.length}: ${J(marks)})`);
+ ok(marks[0].href === 'https://example.com/schedule' && marks[1].href === 'https://example.com/annex',
+ 'each keeps its own address');
+ ok(marks[0].to === marks[1].from, 'and they really are touching, not separated by a gap');
+ ok(normalize(marks, TEXT.length).length === 2,
+ 'normalize agrees — href is part of its grouping key');
+ const html = toHtml(TEXT, marks);
+ ok((html.match(/<a /g) ?? []).length === 2, `and the render is two anchors — ${html.slice(0, 110)}…`);
+
+ // The same two ranges with the SAME address SHOULD become one: that is the
+ // merge doing its job, and it is what makes the negative result above mean
+ // something rather than being merging switched off.
+ let same = setLink([], TEXT.length, 8, 21, 'https://example.com/x');
+ same = setLink(same, TEXT.length, 21, 30, 'https://example.com/x');
+ ok(same.length === 1 && same[0].from === 8 && same[0].to === 30,
+ `two touching links to the same page DO merge — ${J(same)}`);
+}
+
+H('removing a link');
+{
+ const marks = setLink([], TEXT.length, 8, 16, 'https://example.com/s');
+ ok(setLink(marks, TEXT.length, 8, 16, null).length === 0, 'clearing the whole link removes it');
+ const bold = setLink([{ t: 'b', from: 0, to: 20 }], TEXT.length, 8, 16, 'https://example.com/s');
+ const gone = setLink(bold, TEXT.length, 8, 16, null);
+ ok(gone.length === 1 && gone[0].t === 'b', 'and takes nothing else with it');
+ // A partial unlink splits, because removeMark does — the rule is inline.ts's,
+ // not this file's, and that is the point of not reimplementing it.
+ const split = setLink(setLink([], TEXT.length, 8, 30, 'https://example.com/s'),
+ TEXT.length, 12, 20, null);
+ ok(split.length === 2 && split[0].to === 12 && split[1].from === 20,
+ `unlinking the middle of a link splits it — ${J(split)}`);
+ ok(split.every(m => m.href === 'https://example.com/s'), 'both halves keep the address');
+}
+
+H('which link the caret is on');
+{
+ const marks = setLink(setLink([], TEXT.length, 8, 16, 'https://a.example'),
+ TEXT.length, 21, 30, 'https://b.example');
+ ok(linkAt(marks, 12)?.href === 'https://a.example', 'inside the first link');
+ ok(linkAt(marks, 25)?.href === 'https://b.example', 'inside the second');
+ ok(linkAt(marks, 18) === undefined, 'between them, on neither');
+ ok(linkAt(marks, 8)?.href === 'https://a.example', 'on the first character counts as inside');
+ ok(linkAt(undefined, 3) === undefined, 'a block with no marks at all is fine');
+ ok(hasLinkIn(marks, 14, 24), 'a range overlapping either link is reported');
+ ok(!hasLinkIn(marks, 16, 21), 'a range in the gap is not');
+}
+
+// ─────────────────────────────────────────────────────────── autolink
+const auto = (text: string, marks: Mark[] = []) => autolinkAt(text, text.length, marks);
+
+H('autolink fires on a URL completed by a space');
+{
+ const cases: Array<[string, string, string]> = [
+ ['see https://example.com/a ', 'https://example.com/a', 'an explicit https URL'],
+ ['see http://example.com ', 'http://example.com', 'and http'],
+ ['see www.example.com ', 'https://www.example.com', 'the www. idiom is completed to https'],
+ ['mail [email protected] ', 'mailto:[email protected]', 'an email becomes mailto:'],
+ ['see https://example.com/a. ', 'https://example.com/a', 'a sentence full stop is left out of it'],
+ ['see https://example.com/a, ', 'https://example.com/a', 'so is a comma'],
+ ['(see https://example.com/a) ', 'https://example.com/a', 'so is a closing bracket it did not open'],
+ ['see https://ex.example/Foo_(bar) ', 'https://ex.example/Foo_(bar)', 'but a bracket the URL DID open is kept'],
+ ];
+ for (const [text, want, why] of cases) {
+ const hit = auto(text);
+ ok(hit?.href === want, `${why} — ${J(text)} → ${J(hit?.href)}`);
+ }
+ const hit = auto('see https://example.com/a ')!;
+ ok('see https://example.com/a '.slice(hit.from, hit.to) === 'https://example.com/a',
+ 'the offsets cover exactly the URL, not the space that triggered it');
+}
+
+H('autolink stays silent — the half that runs on every keystroke of prose');
+{
+ const quiet: Array<[string, string]> = [
+ ['see https://example.com/a', 'nothing has completed the word yet — no trailing space'],
+ ['the fee is agreed ', 'ordinary prose'],
+ ['see example.com ', 'a BARE domain: index.html and README.md are the same shape'],
+ ['open index.html ', 'a filename is not an address'],
+ ['read README.md ', 'even though .md is a real TLD'],
+ ['ask Mr.Smith ', 'a name with a full stop in it'],
+ ['clause 3.5 ', 'a number'],
+ ['e.g. ', 'an abbreviation'],
+ ['version v1.2.3 ', 'a version'],
+ ['javascript:alert(1) ', 'a hostile scheme is not a scheme we autolink'],
+ ['data:text/html,x ', 'nor is data:'],
+ ['ftp://files.example/x ', 'nor a scheme outside the allowlist'],
+ ['www. ', 'a www. prefix with no domain after it'],
+ ['a@b ', 'an @ with no dotted domain'],
+ [' ', 'a lone space'],
+ ['', 'an empty block'],
+ ];
+ for (const [text, why] of quiet) ok(auto(text) === null, `${why} — ${J(text)}`);
+}
+
+H('autolink never fires inside a link that already exists');
+{
+ const text = 'see https://example.com/a ';
+ const linked = setLink([], text.length, 4, 25, 'https://chosen.example');
+ ok(auto(text, linked) === null,
+ 'a URL already linked is left alone — re-linking would replace the address the author chose');
+ // and a link ELSEWHERE in the block does not block a new one
+ const other = setLink([], text.length, 0, 3, 'https://elsewhere.example');
+ ok(auto(text, other)?.href === 'https://example.com/a', 'but a link on other words does not stop it');
+}
+
+H('autolink is cheap, because it runs on every input event');
+{
+ // The gate is the character before the caret. A long paragraph with no
+ // trailing space must not be scanned at all — measured rather than asserted,
+ // because "it is O(1)" is the kind of claim that quietly stops being true.
+ const long = 'lorem ipsum dolor sit amet '.repeat(4000) + 'x';
+ const t0 = performance.now();
+ for (let i = 0; i < 20000; i++) autolinkAt(long, long.length, []);
+ const per = (performance.now() - t0) / 20000;
+ ok(per < 0.01, `20,000 rejections of a ${long.length.toLocaleString()}-char block: ${per.toFixed(5)}ms each`);
+}
+
+H('the two gates agree — the render one and the navigation one');
+{
+ // There are deliberately TWO: inline.ts guards what enters the document's
+ // HTML, link.ts guards what a ⌘-click follows. They serve different moments,
+ // but they share an ALLOWLIST, and a duplicated security policy is one that
+ // drifts — someone adds a scheme to one and the other silently disagrees.
+ // Nothing forces them together, so this asserts they cannot part.
+ const cases = [
+ 'https://example.com/a', 'http://x.test', 'mailto:[email protected]', 'tel:+44123', '#frag',
+ '/abs', './rel', '../up', 'relative/path',
+ 'javascript:alert(1)', 'JAVASCRIPT:alert(1)', 'data:text/html,<script>',
+ 'vbscript:x', 'file:///etc/passwd', '//evil.example/x', 'ftp://f.example',
+ ' https://ok.example ', 'HTTPS://UP.EXAMPLE',
+ ];
+ const apart = cases.filter(c => (renderGate(c) !== null) !== (safeHref(c) !== null));
+ ok(apart.length === 0,
+ `both gates reach the same verdict on ${cases.length} urls${apart.length ? ` — differ on ${JSON.stringify(apart)}` : ''}`);
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-math.ts b/scripts/test-type-math.ts
new file mode 100644
index 00000000..eca4a615
--- /dev/null
+++ b/scripts/test-type-math.ts
@@ -0,0 +1,354 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type mathematics rig.
+//
+// node scripts/test-type-math.ts (Node ≥ 23.6 strips types natively)
+//
+// WHAT THIS PROVES. `type/src/math/` turns TeX-like source into markup with no
+// dependency and no DOM, and three properties have to hold for that to be safe
+// to run on every render of every block:
+//
+// 1. TOTALITY. A formula is CONTENT. It arrives half-typed, pasted from a
+// paper, or generated by a script that got a brace wrong — and none of
+// those may throw, because the renderer is called from the layout loop and
+// an exception there blanks the page. Every malformed input below must
+// come back with markup.
+// 2. DETERMINISM. The same source must produce the same bytes, every time and
+// in any order. The document is signed and redlined: markup that drifted
+// between renders would show up as a change nobody made.
+// 3. THE PAGINATION INVARIANT. paginate.ts finds line boxes by walking TEXT
+// NODES and skipping whitespace-only ones. A formula that rendered to
+// elements with no text in them would take space the page breaks cannot
+// see, and every page after it would break in the wrong place. So every
+// formula — including the empty one — must carry a text node.
+//
+// The layout is checked as METRICS rather than as pixels: the module reports
+// how far each box rises and falls, and the assertions are about those numbers
+// (a nested fraction is taller; a fence clears its content; two scripts clear
+// each other). That is testable without a browser, which is the point — a
+// property only checked by eye is a property nobody checks.
+
+import { lex, parseMath, MAX_NODES, type MathNode } from '../type/src/math/parse.ts';
+import { layoutMath, renderMath, num, ZW } from '../type/src/math/layout.ts';
+import { displayMathHtml, inlineMathHtml, mathErrors } from '../type/src/math.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const P = (s: string): MathNode => parseMath(s).root;
+const R = (s: string, display = false) => renderMath(s, { display });
+/** the visible characters of a rendering, with the markup taken out */
+const textOf = (html: string) => html.replace(/<[^>]*>/g, '').replace(/\u200B/g, '');
+const kinds = (n: MathNode): string => {
+ switch (n.k) {
+ case 'row': return `row(${n.body.map(kinds).join(' ')})`;
+ case 'atom': return n.ch;
+ case 'op': return `op:${n.name ?? n.ch}`;
+ case 'frac': return `frac(${kinds(n.num)},${kinds(n.den)})`;
+ case 'sqrt': return `sqrt(${kinds(n.body)}${n.index ? `,idx=${kinds(n.index)}` : ''})`;
+ case 'script': return `script(${kinds(n.base)}${n.sup ? `,^${kinds(n.sup)}` : ''}${n.sub ? `,_${kinds(n.sub)}` : ''})`;
+ case 'fence': return `fence(${n.left}${kinds(n.body)}${n.right})`;
+ case 'accent': return `acc(${kinds(n.body)})`;
+ case 'bar': return `${n.under ? 'under' : 'over'}(${kinds(n.body)})`;
+ case 'matrix': return `mat[${n.rows.map(r => r.map(kinds).join('|')).join(' ; ')}]`;
+ case 'text': return `text(${n.s})`;
+ case 'space': return `sp`;
+ case 'style': return `style(${n.style},${kinds(n.body)})`;
+ case 'font': return `font(${kinds(n.body)})`;
+ case 'err': return `ERR(${n.s})`;
+ }
+};
+
+// ─────────────────────────────────────────────────────────────── the lexer
+
+H('the lexer');
+{
+ ok(lex('\\alpha').length === 2 && lex('\\alpha')[0].t === 'cmd',
+ '\\alpha is one command token');
+ const t = lex('\\alpha2');
+ ok(t.length === 3 && t[0].t === 'cmd' && (t[0] as { v: string }).v === 'alpha'
+ && t[1].t === 'ch' && (t[1] as { v: string }).v === '2',
+ '\\alpha2 is the command \\alpha followed by a 2, not a command called alpha2');
+ ok(lex('\\,')[0].t === 'cmd' && (lex('\\,')[0] as { v: string }).v === ',',
+ 'a backslash plus a non-letter is a one-character command');
+ ok(lex('\\\\')[0].t === 'nl', '\\\\ is a row break');
+ // whitespace IS tokenised — `\text{if x}` needs it — and then skipped by the
+ // parser everywhere else, so `a b` is still `ab` in math mode
+ ok(lex('a b').filter(x => x.t === 'ws').length === 1, 'whitespace is tokenised');
+ ok(lex('a\n\tb').filter(x => x.t === 'ws').length === 2, 'newlines and tabs too');
+ ok(kinds(P('a b')) === 'row(a b)' && kinds(P('x ^ 2')) === 'script(x,^2)',
+ 'and the parser ignores it — space is not a character in math mode');
+}
+
+// ─────────────────────────────────────────────────────────── the parser
+
+H('structure and precedence');
+{
+ ok(kinds(P('x^2')) === 'script(x,^2)', 'x^2 is a script over x');
+ ok(kinds(P('x^2_i')) === kinds(P('x_i^2')),
+ 'x^2_i and x_i^2 are the same tree — script order does not matter');
+ ok(kinds(P('x^{a+b}')) === 'script(x,^row(a + b))',
+ 'a braced script takes the whole group');
+ ok(kinds(P('x^ab')) === 'row(script(x,^a) b)',
+ 'an unbraced script takes ONE token — x^ab is (x^a)b');
+ ok(kinds(P('\\frac{a}{b}')) === 'frac(a,b)', '\\frac takes two arguments');
+ ok(kinds(P('\\frac12')) === 'frac(1,2)',
+ '\\frac12 is one half — a single token counts as an argument, as in TeX');
+ ok(kinds(P('\\frac{\\frac{a}{b}}{c}')) === 'frac(frac(a,b),c)', 'fractions nest');
+ ok(kinds(P('x^{\\frac{a}{b}}')) === 'script(x,^frac(a,b))', 'a fraction fits inside a script');
+ ok(kinds(P('\\frac{x^2}{y_1}')) === 'frac(script(x,^2),script(y,_1))',
+ 'and scripts fit inside a fraction');
+ ok(kinds(P('\\sqrt[3]{x}')) === 'sqrt(x,idx=3)', '\\sqrt takes an optional index');
+ ok(kinds(P('\\sqrt x')) === 'sqrt(x)', 'and an unbraced argument');
+ ok(kinds(P("x''")) === 'script(x,^′′)', 'primes are superscripts');
+ ok(kinds(P('\\left(\\frac{a}{b}\\right)')) === 'fence((frac(a,b)))', '\\left…\\right fences');
+ ok(kinds(P('\\left. x \\right|')) === 'fence(x|)', '. is the null delimiter');
+ ok(kinds(P('\\sum_{i=1}^{n} i')) === 'row(script(op:∑,^n,_row(i = 1)) i)',
+ 'a big operator carries its bounds');
+ ok(kinds(P('\\alpha\\Omega')) === 'row(α Ω)', 'Greek resolves to characters');
+ ok(kinds(P('\\text{if } x')) === 'row(text(if ) x)', '\\text keeps its spaces');
+ ok(kinds(P('\\begin{pmatrix}a&b\\\\c&d\\end{pmatrix}')) === 'mat[a|b ; c|d]',
+ 'a matrix splits on & and \\\\');
+ ok(kinds(P('\\begin{cases}x&x>0\\\\0&\\text{else}\\end{cases}')) === 'mat[x|row(x > 0) ; 0|text(else)]',
+ 'so does cases');
+ ok(kinds(P('\\begin{matrix}a\\\\b\\\\\\end{matrix}')) === 'mat[a ; b]',
+ 'a trailing \\\\ does not add an empty row');
+}
+
+H('classes decide spacing');
+{
+ // `-x` is a negation and `a-x` a subtraction: the same character, different
+ // space, and the rendering must show it
+ const neg = R('-x').html, sub = R('a-x').html;
+ const spacers = (h: string) => (h.match(/t-msp/g) ?? []).length;
+ ok(spacers(neg) === 0, 'a leading minus is tight — it binds nothing');
+ ok(spacers(sub) > 0, 'a minus between two terms is spaced as a binary operator');
+ ok((R('a=b').html.match(/width:0\.278em/g) ?? []).length === 2,
+ 'a relation takes a thick space on both sides');
+ ok(spacers(R('x^{a+b}').html) === 0,
+ 'and script styles get no inter-atom space at all');
+}
+
+// ────────────────────────────────────────────────── malformed input
+
+H('malformed input degrades, and never throws');
+{
+ const NASTY = [
+ '', ' ', '{', '}', '{{{{{{', '}}}}}}', '\\', '\\\\', '^', '_', '^^^', '_{',
+ '\\frac', '\\frac{', '\\frac{a}', '\\frac{}{}', '\\sqrt', '\\sqrt[', '\\sqrt[3]',
+ '\\left', '\\left(', '\\right)', '\\left(\\right', '\\left{x\\right}',
+ '\\begin', '\\begin{}', '\\begin{foo}x\\end{foo}', '\\begin{pmatrix}',
+ '\\end{pmatrix}', '\\unknowncommand', '\\newcommand{\\x}{y}',
+ 'x^^2', 'x^2^3', 'x_1_2', '\\text', '\\text{', '&', '\\\\&\\\\',
+ '\\hat', '\\mathbb', '\\displaystyle', '\\limits', '\\big',
+ '\u0000\u0001', '💥', 'x'.repeat(500),
+ '\\frac{'.repeat(60) + 'x', '{'.repeat(200), '\\sqrt{'.repeat(100),
+ ];
+ let threw = '', empty = '', unsafe = '';
+ for (const src of NASTY) {
+ let html = '';
+ try { html = R(src).html; } catch (e) { threw ||= `${JSON.stringify(src)} → ${(e as Error).message}`; continue; }
+ if (!html) empty ||= JSON.stringify(src);
+ if (/<script|onerror=|javascript:/i.test(html)) unsafe ||= JSON.stringify(src);
+ try { R(src, true); } catch (e) { threw ||= `display ${JSON.stringify(src)} → ${(e as Error).message}`; }
+ }
+ ok(!threw, `no malformed formula throws${threw ? ` — ${threw}` : ''}`);
+ ok(!empty, `and none renders to nothing${empty ? ` — ${empty}` : ''}`);
+ ok(!unsafe, `and none produces active markup${unsafe ? ` — ${unsafe}` : ''}`);
+ ok(mathErrors('\\unknowncommand').length > 0, 'an unknown command is REPORTED, not swallowed');
+ ok(mathErrors('\\frac{a}{b}').length === 0, 'and a good formula reports nothing');
+}
+
+H('an error is local — the rest of the formula still sets');
+{
+ const r = R('a + \\nosuchthing + b');
+ const text = textOf(r.html);
+ ok(text.includes('a') && text.includes('b'),
+ 'the atoms either side of an unknown command survive it');
+ ok(r.html.includes('t-merr') && r.html.includes('nosuchthing'),
+ 'and the offending source is shown in place');
+ ok(kinds(P('\\begin{foo}\\frac{a}{b}\\end{foo}c')).endsWith('c)'),
+ 'an unsupported environment is skipped to its \\end, not to the end of the formula');
+}
+
+H('the caps hold');
+{
+ const deep = '\\frac{'.repeat(400) + 'x' + '}{y}'.repeat(400);
+ const t0 = Date.now();
+ const r = R(deep);
+ ok(Date.now() - t0 < 2000, `400-deep nesting renders in bounded time (${Date.now() - t0}ms)`);
+ ok(r.errors.some(e => /deep|large/.test(e)), 'and says why it stopped');
+ const huge = 'x+'.repeat(20000);
+ const t1 = Date.now();
+ const big = R(huge);
+ ok(Date.now() - t1 < 2000, `a 40,000-character formula is bounded too (${Date.now() - t1}ms)`);
+ ok(big.html.length < 3e6, 'and its output is bounded');
+ ok(MAX_NODES < 1e5, 'the node budget is a real cap');
+}
+
+H('nothing from the source escapes as markup');
+{
+ const r = R('\\text{<script>alert(1)</script> & "quoted"}');
+ ok(!r.html.includes('<script'), 'a script tag in the source is escaped');
+ ok(r.html.includes('&lt;script&gt;'), 'and rendered as visible text');
+ ok(!/&(?!amp;|lt;|gt;|quot;)/.test(r.html), 'every ampersand is escaped');
+ const atom = inlineMathHtml('a<b & c"d');
+ ok(!/data-tex="[^"]*"[^ >]/.test(atom), 'the source survives into data-tex without breaking the attribute');
+ ok(atom.includes('&lt;') && atom.includes('&amp;') && atom.includes('&quot;'),
+ 'data-tex escapes <, & and "');
+}
+
+// ─────────────────────────────────────────────────────────── determinism
+
+H('the same source always produces the same output');
+{
+ const CORPUS = [
+ 'x^2 + y^2 = z^2', '\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}',
+ '\\sum_{i=1}^{n} \\frac{1}{i^2} = \\frac{\\pi^2}{6}',
+ '\\int_0^\\infty e^{-x^2}\\,dx = \\frac{\\sqrt{\\pi}}{2}',
+ '\\left(\\begin{matrix}a&b\\\\c&d\\end{matrix}\\right)',
+ '\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1',
+ '\\hat{y} = \\mathbf{X}\\beta + \\varepsilon',
+ '\\begin{cases} 1 & x > 0 \\\\ 0 & \\text{otherwise} \\end{cases}',
+ '\\sqrt[3]{\\frac{a}{b}}', '\\mathbb{R}^n \\subseteq \\mathbb{C}^n',
+ ];
+ let drift = '';
+ for (const src of CORPUS) {
+ const a = R(src).html, b = R(src).html, c = R(src, true).html, d = R(src, true).html;
+ if (a !== b || c !== d) drift ||= src;
+ }
+ ok(!drift, `ten real formulas render identically on every call${drift ? ` — ${drift}` : ''}`);
+
+ // interleaved, because a renderer that carried state between calls (a shared
+ // buffer, a counter in a generated id) would pass the loop above and fail here
+ const inter = CORPUS.map(s => R(s).html);
+ const shuffled = [...CORPUS].reverse().map(s => R(s).html).reverse();
+ ok(JSON.stringify(inter) === JSON.stringify(shuffled),
+ 'and identically when rendered in a different order — there is no shared state');
+
+ ok(!/NaN|undefined|Infinity/.test(CORPUS.map(s => R(s, true).html).join('')),
+ 'no NaN, undefined or Infinity reaches the markup');
+ ok(num(0.30000000000000004) === '0.3' && num(-0) === '0',
+ 'numbers are rounded to a fixed form, and -0 is 0');
+ ok(R('x').html === R('x').html && !/id="/.test(R('\\sqrt{x}').html),
+ 'nothing carries a generated id — ids would differ per call and per document');
+}
+
+// ─────────────────────────────────────────────────────────── the metrics
+
+H('vertical layout');
+{
+ const box = (s: string, display = false) => layoutMath(P(s), { display });
+ const plain = box('x');
+ ok(plain.h > 0 && plain.d > 0, 'a plain letter has a height and a depth');
+
+ const f1 = box('\\frac{a}{b}');
+ ok(f1.h > plain.h && f1.d > plain.d, 'a fraction rises above and falls below the line');
+ const f2 = box('\\frac{\\frac{a}{b}}{c}');
+ ok(f2.h > f1.h, 'a fraction with a fraction in its numerator is taller');
+ const f3 = box('\\frac{a}{\\frac{b}{c}}');
+ ok(f3.d > f1.d, 'and one in the denominator falls further');
+ ok(Math.abs(f1.h - f2.h) > 0.1, 'the difference is a real amount, not a rounding');
+
+ const sup = box('x^2'), sub = box('x_2'), both = box('x_1^2');
+ ok(sup.h > plain.h, 'a superscript raises the box');
+ ok(sup.d === plain.d, 'and does not deepen it');
+ ok(sub.d > plain.d && sub.h === plain.h, 'a subscript deepens the box only');
+ ok(both.h >= sup.h && both.d >= sub.d, 'with both, the box covers both');
+ ok(box('x^{y^{z}}').h > box('x^{y}').h, 'a script on a script raises the box further');
+
+ const tall = box('\\left(\\frac{\\frac{a}{b}}{c}\\right)');
+ const inner = box('\\frac{\\frac{a}{b}}{c}');
+ ok(tall.h >= inner.h && tall.d >= inner.d, 'a fence is at least as tall as what it holds');
+ ok(box('\\left(x\\right)').h < tall.h, 'and only as tall as it needs to be');
+
+ ok(box('\\sqrt{x}').h > box('x').h, 'a radical adds its bar above the content');
+ ok(box('\\sqrt{\\frac{a}{b}}').h > box('\\sqrt{x}').h, 'and grows with it');
+
+ ok(box('\\sum_{i}^{n}', true).h > box('\\sum_{i}^{n}', false).h,
+ 'a summation with limits is taller in display style than in text style');
+ ok(box('\\overline{x}').h > plain.h && box('\\underline{x}').d > plain.d,
+ 'over- and underlines go the right way round');
+ ok(box('\\hat{x}').h > plain.h, 'an accent sits above its base');
+
+ const m = box('\\begin{matrix}a&b\\\\c&d\\\\e&f\\end{matrix}');
+ const m2 = box('\\begin{matrix}a&b\\end{matrix}');
+ ok(m.h > m2.h && m.d > m2.d, 'a taller matrix grows in both directions');
+ ok(Math.abs((m.h - 0.25) - (m.d + 0.25)) < 0.001,
+ 'and stays centred on the math axis (0.25em above the baseline)');
+ const paren = box('\\begin{pmatrix}a&b\\\\c&d\\\\e&f\\end{pmatrix}');
+ ok(paren.h > m.h && paren.d > m.d, 'and its parentheses stretch past it on both sides');
+}
+
+H('script sizes step down, and stop');
+{
+ const sizes = [...R('x^{y^{z^{w}}}').html.matchAll(/font-size:([0-9.]+)em/g)].map(m => m[1]);
+ // each size is RELATIVE to its parent, so the chain reads 0.7 → 0.5/0.7 → 1
+ ok(sizes.join(' ') === '0.7 0.7143 1',
+ `the scripts step 100% → 70% → 50% and then STOP at scriptscript (${sizes.join(' ')})`);
+ ok(!R('x^{y^{z^{w}}}').html.includes('font-size:0.5em'),
+ 'and nothing is ever set below half the base size');
+}
+
+// ────────────────────────────────────────────── the pagination invariant
+
+H('every formula carries a text node');
+{
+ const EMPTIES = ['', '{}', '\\frac{}{}', '\\sqrt{}', '\\left(\\right)', '{ }',
+ '\\begin{matrix}&\\\\&\\end{matrix}', '\\hat{}', '\\text{}'];
+ let missing = '';
+ for (const src of EMPTIES) {
+ const html = inlineMathHtml(src);
+ // what the TreeWalker in paginate.ts would accept: a text node whose value
+ // is not whitespace once trimmed
+ const texts = html.replace(/<[^>]*>/g, '');
+ if (!texts.trim().length) missing ||= JSON.stringify(src);
+ }
+ ok(!missing, `an empty formula still contains a measurable text node${missing ? ` — ${missing}` : ''}`);
+ ok('\u200B'.trim().length === 1,
+ 'U+200B is NOT whitespace to String.trim — which is why it is the filler');
+ ok(ZW === '\u200B', 'and it is the character the layout engine uses');
+ ok(inlineMathHtml('').includes(ZW), 'the inline wrapper carries one unconditionally');
+ ok(displayMathHtml('').includes(ZW), 'and so does the display wrapper');
+}
+
+H('the wrappers the core will embed');
+{
+ const a = inlineMathHtml('\\frac{a}{b}');
+ ok(a.startsWith('<span class="t-math"') && a.endsWith('</span>'), 'an inline formula is one span');
+ ok(a.includes('contenteditable="false"'),
+ 'and is contenteditable=false — the caret may not enter a box with no model position');
+ ok(a.includes('data-tex="\\frac{a}{b}"'),
+ 'the SOURCE rides in data-tex — that is what fromDom reads back, never the glyphs');
+ const d = displayMathHtml('x^2');
+ ok(d.includes('t-math-display'), 'a display equation is marked as one');
+ ok(!d.includes('contenteditable'),
+ 'and is not locked: a math BLOCK is addressed by its own id, not by an offset');
+ ok(inlineMathHtml('\\nope').includes('t-math-bad'),
+ 'a formula with an error is flagged on the wrapper, so the chrome can show it');
+ ok(!inlineMathHtml('x').includes('t-math-bad'), 'and a good one is not');
+
+ // the round trip the core edit (3) depends on
+ for (const src of ['x^2', '\\frac{a}{b}', 'a<b', '"q"', '\\text{&}', '']) {
+ const m = /data-tex="([^"]*)"/.exec(inlineMathHtml(src));
+ const back = (m?.[1] ?? '').replace(/&quot;/g, '"').replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>').replace(/&amp;/g, '&');
+ ok(back === src, `data-tex round-trips ${JSON.stringify(src)}`);
+ }
+}
+
+H('the source is never the output');
+{
+ // the property that keeps the model honest: the rendering of a formula shares
+ // no bytes with its own syntax
+ const html = R('\\frac{a}{b}').html;
+ ok(!html.includes('\\frac') && !html.includes('{a}'),
+ 'the rendering contains none of the TeX syntax — only what it means');
+ ok(textOf(html) === 'ab', 'just the numerator and the denominator, in order');
+ ok(textOf(R('\\alpha + \\beta').html) === 'α+β', 'and commands become their characters');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-move.ts b/scripts/test-type-move.ts
new file mode 100644
index 00000000..25c9cb02
--- /dev/null
+++ b/scripts/test-type-move.ts
@@ -0,0 +1,180 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Moving a block — and never tearing one in half.
+//
+// node scripts/test-type-move.ts
+//
+// The body is FLAT but the rendering is grouped, so the interesting cases are
+// all about runs: a table is consecutive `cell` blocks sharing a table id, a
+// list is consecutive ul/ol blocks. Move one member of a run and you split a
+// table down the middle or drop a paragraph between two bullets. Every check
+// here is a way that could happen.
+
+import { register } from 'node:module';
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+
+const { unitAt, units, moveUnit, canMove } = await import('../type/src/move.ts');
+
+let checks = 0, bad = 0;
+const ok = (c: boolean, m: string) => { checks++; if (c) console.log(` ok ${m}`); else { bad++; console.log(` FAIL ${m}`); } };
+const eq = (a: unknown, b: unknown, m: string) => {
+ const same = JSON.stringify(a) === JSON.stringify(b);
+ checks++;
+ if (same) console.log(` ok ${m}`);
+ else { bad++; console.log(` FAIL ${m}\n got ${JSON.stringify(a)}\n want ${JSON.stringify(b)}`); }
+};
+
+const p = (id: string) => ({ id, kind: 'para', text: id });
+const li = (id: string, level = 0) => ({ id, kind: 'ul', text: id, level });
+const cell = (id: string, table: string) => ({ id, kind: 'cell', text: id, cell: { table, cols: 2 } });
+const cap = (id: string, of: string) => ({ id, kind: 'caption', text: id, caption: { kind: 'figure', of } });
+const img = (id: string) => ({ id, kind: 'image', text: '', image: { src: 'x' } });
+const ids = (body: readonly { id: string }[]) => body.map(b => b.id);
+
+console.log('\n— plain paragraphs —');
+{
+ const body = [p('a'), p('b'), p('c')];
+ eq(ids(moveUnit(body, 'b', -1)!), ['b', 'a', 'c'], 'up swaps with the one above');
+ eq(ids(moveUnit(body, 'b', 1)!), ['a', 'c', 'b'], 'down swaps with the one below');
+ ok(moveUnit(body, 'a', -1) === null, 'the first cannot go up');
+ ok(moveUnit(body, 'c', 1) === null, 'the last cannot go down');
+ ok(moveUnit(body, 'nope', 1) === null, 'an unknown id moves nothing');
+ ok(!canMove(body, 'a', -1) && canMove(body, 'a', 1), 'canMove agrees');
+}
+
+console.log('\n— a table is one thing —');
+{
+ const body = [p('a'), cell('c1', 't'), cell('c2', 't'), cell('c3', 't'), cell('c4', 't'), p('z')];
+ const u = unitAt(body, 2); // asked about the SECOND cell
+ eq([u.start, u.end], [1, 5], 'any cell resolves to the whole table');
+ eq(ids(moveUnit(body, 'c1', 1)!), ['a', 'z', 'c1', 'c2', 'c3', 'c4'],
+ 'the table moves down as a block, past the paragraph');
+ eq(ids(moveUnit(body, 'c3', -1)!), ['c1', 'c2', 'c3', 'c4', 'a', 'z'],
+ 'and a move asked from a middle cell moves the whole table');
+ eq(ids(moveUnit(body, 'a', 1)!), ['c1', 'c2', 'c3', 'c4', 'a', 'z'],
+ 'a paragraph jumps the ENTIRE table, never into it');
+ // two adjacent tables must not merge into one unit
+ const two = [cell('x1', 't1'), cell('x2', 't1'), cell('y1', 't2'), cell('y2', 't2')];
+ eq(units(two).map(u2 => [u2.start, u2.end]), [[0, 2], [2, 4]], 'two tables are two units');
+ eq(ids(moveUnit(two, 'y1', -1)!), ['y1', 'y2', 'x1', 'x2'], 'and they swap whole');
+}
+
+console.log('\n— a list is one thing —');
+{
+ const body = [p('a'), li('l1'), li('l2', 1), li('l3'), p('z')];
+ eq([unitAt(body, 3).start, unitAt(body, 3).end], [1, 4], 'any item resolves to the whole list');
+ eq(ids(moveUnit(body, 'a', 1)!), ['l1', 'l2', 'l3', 'a', 'z'],
+ 'a paragraph jumps the whole list, never landing between bullets');
+ eq(ids(moveUnit(body, 'l2', 1)!), ['a', 'z', 'l1', 'l2', 'l3'],
+ 'and the list moves as one, asked from a nested item');
+}
+
+console.log('\n— a caption travels with its figure —');
+{
+ const body = [p('a'), img('f1'), cap('c1', 'f1'), p('z')];
+ eq([unitAt(body, 1).start, unitAt(body, 1).end], [1, 3], 'the figure unit absorbs its caption');
+ eq([unitAt(body, 2).start, unitAt(body, 2).end], [1, 3], 'and asking about the caption gives the same unit');
+ eq(ids(moveUnit(body, 'f1', 1)!), ['a', 'z', 'f1', 'c1'], 'they move together');
+ eq(ids(moveUnit(body, 'c1', -1)!), ['f1', 'c1', 'a', 'z'], 'from either end');
+ // a caption is never left as an orphan unit that could outrun its figure
+ ok(!units(body).some(u => u.end - u.start === 1 && body[u.start].kind === 'caption'),
+ 'no caption is ever a unit on its own');
+}
+
+console.log('\n— a captioned table —');
+{
+ const body = [cell('c1', 't'), cell('c2', 't'), cap('cp', 'c1'), p('z')];
+ eq([unitAt(body, 0).start, unitAt(body, 0).end], [0, 3], 'the table unit absorbs its caption too');
+ eq(ids(moveUnit(body, 'c1', 1)!), ['z', 'c1', 'c2', 'cp'], 'and all three move as one');
+}
+
+console.log('\n— units() terminates and covers everything —');
+{
+ const body = [p('a'), img('f'), cap('c', 'f'), li('l1'), li('l2'), cell('t1', 't'), p('z')];
+ const us = units(body);
+ eq(us.map(u => [u.start, u.end]), [[0, 1], [1, 3], [3, 5], [5, 6], [6, 7]], 'the body partitions cleanly');
+ // Every block belongs to exactly one unit — no gaps, no overlaps. A caption
+ // resolving BACKWARDS to its figure is what could have made units() loop.
+ const covered = us.flatMap(u => Array.from({ length: u.end - u.start }, (_, k) => u.start + k));
+ eq(covered, body.map((_, k) => k), 'every block is covered exactly once');
+}
+
+console.log('\n— a move is a permutation, never a loss —');
+{
+ const body = [p('a'), li('l1'), li('l2'), cell('t1', 't'), cell('t2', 't'), img('f'), cap('c', 'f'), p('z')];
+ for (const id of ['a', 'l1', 't1', 'f', 'z']) {
+ for (const dir of [-1, 1] as const) {
+ const out = moveUnit(body, id, dir);
+ if (!out) continue;
+ eq(ids(out).slice().sort(), ids(body).slice().sort(), `${id} ${dir < 0 ? 'up' : 'down'} keeps every block`);
+ eq(out.length, body.length, `${id} ${dir < 0 ? 'up' : 'down'} changes no count`);
+ }
+ }
+}
+
+console.log('\n— up then down is the identity —');
+{
+ const body = [p('a'), li('l1'), li('l2'), p('z')];
+ const down = moveUnit(body, 'a', 1)!;
+ eq(ids(moveUnit(down, 'a', -1)!), ids(body), 'moving down then up restores the order');
+}
+
+console.log('\n— dropping a unit anywhere (what a drag does) —');
+{
+ const { moveUnitTo, boundaries } = await import('../type/src/move.ts');
+ const body = [p('a'), li('l1'), li('l2'), cell('t1', 't'), cell('t2', 't'), p('z')];
+ eq(boundaries(body), [0, 1, 3, 5, 6], 'the legal drop points are the unit edges and the end');
+
+ eq(ids(moveUnitTo(body, 'a', 6)!), ['l1', 'l2', 't1', 't2', 'z', 'a'], 'a paragraph dropped at the end');
+ eq(ids(moveUnitTo(body, 'z', 0)!), ['z', 'a', 'l1', 'l2', 't1', 't2'], 'and one dropped at the start');
+ eq(ids(moveUnitTo(body, 'l1', 6)!), ['a', 't1', 't2', 'z', 'l1', 'l2'], 'a whole list travels');
+ eq(ids(moveUnitTo(body, 't1', 1)!), ['a', 't1', 't2', 'l1', 'l2', 'z'], 'and a whole table');
+
+ // A sloppy drop must never land INSIDE a table or a list. Ties snap to the
+ // EARLIER boundary, which is arbitrary but deterministic; the UI measures in
+ // pixels, where an exact tie is vanishingly unlikely.
+ eq(ids(moveUnitTo(body, 'a', 4)!), ['l1', 'l2', 'a', 't1', 't2', 'z'],
+ 'a drop aimed between two table cells snaps to the table edge');
+ eq(ids(moveUnitTo(body, 'z', 2)!), ['a', 'z', 'l1', 'l2', 't1', 't2'],
+ 'and one aimed between two bullets snaps out of the list');
+ ok(moveUnitTo(body, 'a', 2) === null,
+ 'a drop aimed into the list from the block right above it snaps back to where it already is');
+
+ ok(moveUnitTo(body, 'a', 0) === null, 'dropping a unit on its own leading edge is a no-op');
+ ok(moveUnitTo(body, 'a', 1) === null, 'and on its own trailing edge');
+ ok(moveUnitTo(body, 'nope', 0) === null, 'an unknown id moves nothing');
+
+ for (const target of [0, 1, 2, 3, 4, 5, 6]) {
+ const out = moveUnitTo(body, 'l1', target);
+ if (!out) continue;
+ eq(ids(out).slice().sort(), ids(body).slice().sort(), `drop at ${target} keeps every block`);
+ }
+}
+
+console.log('\n— the shortcut matcher, which every other shortcut shares —');
+{
+ const { matchKey, registerKey } = await import('../type/src/features.ts');
+ const ev = (o: Record<string, unknown>) =>
+ ({ key: 'ArrowUp', shiftKey: false, altKey: false, ctrlKey: false, metaKey: false, ...o }) as never;
+
+ registerKey({ key: 'arrowup', ctrl: true, shift: true, run() {} });
+ registerKey({ key: 'arrowdown', alt: true, shift: true, run() {} });
+
+ ok(!!matchKey(ev({ ctrlKey: true, shiftKey: true })), 'Ctrl+Shift+Up matches the ctrl binding');
+ // The whole reason `ctrl` exists: mod conflates ⌘ with Ctrl, and ⌘⇧↑ is
+ // "select to the start of the document" on a Mac. It must NOT move a block.
+ ok(!matchKey(ev({ metaKey: true, shiftKey: true })), 'Cmd+Shift+Up does NOT');
+ ok(!matchKey(ev({ ctrlKey: true })), 'Ctrl+Up alone does not');
+ ok(!matchKey(ev({ ctrlKey: true, shiftKey: true, altKey: true })), 'nor with Alt added');
+ ok(!!matchKey(ev({ key: 'ArrowDown', altKey: true, shiftKey: true })), 'Alt+Shift+Down matches the alt binding');
+ ok(!matchKey(ev({ key: 'ArrowDown', ctrlKey: true, shiftKey: true })), 'Ctrl+Shift+Down does not match it');
+
+ // an existing mod binding still behaves exactly as before
+ registerKey({ key: 'b', mod: true, run() {} });
+ ok(!!matchKey(ev({ key: 'b', metaKey: true })), 'mod still matches Cmd');
+ ok(!!matchKey(ev({ key: 'b', ctrlKey: true })), 'and still matches Ctrl');
+}
+
+console.log(`\n${checks - bad}/${checks} checks passed`);
+if (bad) process.exit(1);
diff --git a/scripts/test-type-redline.ts b/scripts/test-type-redline.ts
index 30ef227b..9fbc0e4c 100644
--- a/scripts/test-type-redline.ts
+++ b/scripts/test-type-redline.ts
@@ -156,5 +156,44 @@ H('a proposal is attributable');
'altering a change after signing changes the digest');
}
+H('a table is reviewed CELL BY CELL');
+{
+ // The whole reason a cell is a block. If a table were one block, changing one
+ // figure would report "the fees table changed" — which is the failure that
+ // makes line diffs useless on prose, and the limitation bento/slides
+ // documents for its own tables.
+ const c = (text: string, head?: boolean): Block =>
+ ({ id: 'c-' + text.replace(/\W/g, ''), kind: 'cell', text,
+ cell: { table: 'fees', cols: 2, ...(head ? { head: true } : {}) } } as Block);
+
+ const before = { docId: 'd', body: [
+ { id: 'p', kind: 'para', text: 'Fees:' } as Block,
+ c('Service', true), c('Rate', true),
+ c('Design'), c('£1,200'),
+ c('Build'), c('£1,050'),
+ ] };
+ const after = {
+ docId: 'd',
+ body: before.body.map(b => b.text === '£1,050' ? { ...b, text: '£1,300' } : b),
+ };
+
+ const set = redline(before, after, { author: 'counsel' });
+ ok(set.changes.length === 1, `one change, not a rewritten table (${set.changes.length})`);
+ const ch = set.changes[0] as { kind: string; blockId?: string };
+ ok(ch.kind === 'text', `and it is a text edit (${ch.kind})`);
+ ok(ch.blockId === 'c-1050', `anchored to the CELL that changed (${ch.blockId})`);
+ console.log(` · ${describe(set.changes[0])}`);
+
+ const all = new Set(set.changes.map(x => x.id));
+ ok(same(apply(before, set, all), after), 'accepting it reproduces their table');
+ ok(same(apply(before, set, new Set()), before), 'rejecting it leaves yours');
+
+ // and a structural change is still structural
+ const rowAdded = { docId: 'd', body: [...after.body, c('Support'), c('£400')] };
+ const set2 = redline(after, rowAdded);
+ ok(set2.changes.length === 2 && set2.changes.every(x => x.kind === 'block-ins'),
+ `adding a row is two cell inserts (${set2.changes.map(x => x.kind).join(',')})`);
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`);
if (failures) process.exit(1);
diff --git a/scripts/test-type-styles.ts b/scripts/test-type-styles.ts
new file mode 100644
index 00000000..16f04dda
--- /dev/null
+++ b/scripts/test-type-styles.ts
@@ -0,0 +1,380 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type named-styles rig. node scripts/test-type-styles.ts
+//
+// docstyles.ts closes the biggest gap versus Word: before it, a heading's
+// size/weight/colour was a build constant (styles.css), not a document
+// property, so "make every heading 18px Palatino" had no home. This pins the
+// pure half — resolution, CSS composition, precedence, round-tripping — with
+// no DOM, mirroring test-type-layout.ts's split for the same reason: it is
+// the half that has to be right, and it is the half a browser is not needed
+// to check.
+//
+// What it holds down, in the order it would burn:
+//
+// · FORMAT ADDITIVITY (docs/PLATFORM.md §3). A document with no `doc.styles`
+// and blocks with no `styleId` must render BYTE-IDENTICAL to before this
+// feature existed — docStyleCss must return '' for every ordinary block.
+// · applying a style (styleId), and the KIND DEFAULT a block with none
+// falls back to — which is what makes "restyle every heading" possible
+// for paragraphs that never opted in individually.
+// · editing a style repaints every block that uses it, explicit or implicit.
+// · a block's own direct formatting (align/sb/sa/lh/ind) still wins over
+// its style — verified by actually composing the two CSS strings the way
+// render.ts and print.ts do, and reading back which value survives.
+// · a style, and a block's reference to one, survive save/reload — and a
+// dangling reference (the style was deleted) degrades to the kind
+// default rather than losing the paragraph's formatting entirely.
+
+import { emptyDoc, parseDoc, type Block, type DocStyle, type TypeDoc } from '../type/src/model.ts';
+import { blockStyle } from '../type/src/layout.ts';
+import {
+ BUILT_IN_STYLES, DEFAULT_STYLE_ID, activeStyleId, ownStyleId, resolveStyle,
+ lookupStyle, listStyles, docStyleCss, styleSheetCss, effectiveLayout, hasDirectFormatting,
+ materialize, mergeStyle, captureStyleFromBlock, safeStyleColor,
+} from '../type/src/docstyles.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const block = (id: string, kind: Block['kind'], extra: Record<string, unknown> = {}): Block =>
+ ({ id, kind, text: `${id} text`, ...extra }) as Block;
+
+/** A tiny CSS-declaration-list reader: last declaration of a property wins,
+ * exactly as a browser resolves one `style` attribute — so a test can ask
+ * "what does text-align actually compute to" instead of string-matching. */
+const winner = (css: string, prop: string): string | undefined => {
+ let v: string | undefined;
+ for (const decl of css.split(';')) {
+ const [k, ...rest] = decl.split(':');
+ if (k?.trim() === prop) v = rest.join(':').trim();
+ }
+ return v;
+};
+
+// ═══════════════════════════════════════════════════════ format additivity
+
+H('a document with no styles renders exactly as it always did');
+{
+ const doc = emptyDoc();
+ ok(doc.styles === undefined, 'emptyDoc carries no styles field at all');
+
+ // Only `para`'s built-in is EMPTY (docs/DECISIONS-style rationale in
+ // docstyles.ts: body text's look already comes entirely from unconditional
+ // CSS). The other six kinds always had a real, hardcoded look — additivity
+ // for THEM means the built-in table reproduces styles.css's own numbers
+ // exactly, which is asserted by name below, not "no css at all".
+ const kinds: Block['kind'][] = ['para', 'h1', 'h2', 'h3', 'quote', 'ul', 'ol'];
+ for (const kind of kinds) {
+ const b = block(`b-${kind}`, kind);
+ ok(b.styleId === undefined, `a fresh ${kind} block carries no styleId`);
+ if (kind === 'para') ok(docStyleCss(doc, b) === '', 'a plain paragraph produces NO css');
+ else ok(docStyleCss(doc, b) !== '', `${kind} resolves to its built-in's real numbers`);
+ }
+ // kinds with no default style at all (image, cell, caption, toc, math, embed)
+ for (const kind of ['image', 'cell', 'caption', 'toc', 'math', 'embed'] as const) {
+ ok(DEFAULT_STYLE_ID[kind] === undefined, `${kind} has no default style`);
+ ok(docStyleCss(doc, block(`b-${kind}`, kind)) === '', `${kind} produces no css either`);
+ }
+}
+
+H('parseDoc round-trips a file with no "styles" key unchanged');
+{
+ const raw = JSON.stringify({
+ format: 'bento/type', version: 1, docId: 'd1', title: 'T',
+ page: { width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104 },
+ body: [{ id: 'p1', kind: 'h1', text: 'Title' }],
+ footnotes: {}, revisions: [], signatures: [],
+ });
+ const r = parseDoc(raw);
+ ok(r.ok, 'parses');
+ if (r.ok) {
+ ok(r.doc.styles === undefined, 'no styles field is invented on load');
+ // an h1 is NOT expected to produce '' — it always resolved to a real
+ // Heading-1 look, in styles.css before this feature and through the
+ // built-in table now. What additivity promises is the SAME numbers.
+ const css = docStyleCss(r.doc, r.doc.body[0]);
+ ok(winner(css, 'font-size') === '26px' && winner(css, 'font-weight') === '600',
+ 'the heading still resolves to exactly styles.css\'s own Heading-1 numbers, from the built-in table alone');
+ // a plain paragraph, by contrast, has an EMPTY built-in — additivity for
+ // it means no inline css at all, matching a document that never opened
+ // the Styles section before this feature existed
+ const para = { id: 'x', kind: 'para' as const, text: 'body text' };
+ ok(docStyleCss(r.doc, para) === '', 'a plain paragraph still produces no inline css');
+ }
+}
+
+// ═══════════════════════════════════════════════════════ built-ins, derived from styles.css
+
+H('built-in styles are derived from styles.css\'s own numbers');
+{
+ const doc = emptyDoc();
+ const h1 = block('h', 'h1');
+ const css = docStyleCss(doc, h1);
+ ok(winner(css, 'font-size') === '26px', `h1 is 26px (${winner(css, 'font-size')})`);
+ ok(winner(css, 'font-weight') === '600', 'h1 is weight 600');
+ ok(winner(css, 'line-height') === '1.24', 'h1 keeps its own line-height');
+ ok(winner(css, 'margin-bottom') === '14px', 'h1\'s CSS margin: 0 0 14px becomes sa=14');
+ ok(winner(css, 'margin-top') === undefined, 'h1 has no sb, so no margin-top is emitted at all');
+
+ const quote = block('q', 'quote');
+ const qcss = docStyleCss(doc, quote);
+ ok(winner(qcss, 'font-style') === 'italic', 'a quote is italic');
+ ok(winner(qcss, 'color') === '#3a3d44', 'a quote takes --paper-ink-2, an UNTHEMED fixed value');
+
+ ok(BUILT_IN_STYLES['default-body'].size === undefined
+ && BUILT_IN_STYLES['default-body'].weight === undefined
+ && BUILT_IN_STYLES['default-body'].color === undefined,
+ 'Body is intentionally empty — its look already comes from unconditional CSS');
+}
+
+// ═══════════════════════════════════════════════════════ applying a style
+
+H('applying a style to a block — explicit styleId beats the kind default');
+{
+ const doc = emptyDoc();
+ const p = block('p1', 'para');
+ ok(activeStyleId(doc, p) === 'default-body', 'a plain paragraph defaults to Body');
+ ok(ownStyleId(p) === undefined, 'and carries no explicit reference yet');
+
+ p.styleId = 'default-h2';
+ ok(ownStyleId(p) === 'default-h2', 'the explicit reference is now Heading 2');
+ ok(activeStyleId(doc, p) === 'default-h2', 'and it wins over the kind default');
+ const css = docStyleCss(doc, p);
+ ok(winner(css, 'font-size') === '15.5px', 'the PARAGRAPH now renders Heading 2\'s size, kind unchanged');
+
+ // choosing the kind's OWN default again clears the field, the same
+ // "absent means default" rule layout.ts's paragraph properties already
+ // follow — never store what is already implied
+ const cleared: Block = { ...p };
+ delete cleared.styleId;
+ ok(activeStyleId(doc, cleared) === 'default-body', 'clearing it returns to Body');
+}
+
+H('a dangling styleId falls back to the kind default, not to nothing');
+{
+ const doc = emptyDoc();
+ const h3 = block('h', 'h3', { styleId: 'no-such-style' });
+ ok(resolveStyle(doc, h3)?.id === 'default-h3', 'an unresolvable id falls back to h3\'s own default');
+ ok(docStyleCss(doc, h3) !== '', 'so the heading still looks like a heading, not like plain text');
+}
+
+// ═══════════════════════════════════════════════════════ editing a style repaints every user
+
+H('editing a style updates every block that uses it — explicit AND implicit');
+{
+ let doc = emptyDoc();
+ const explicit = block('e', 'para', { styleId: 'default-h1' }); // opted in
+ const implicit = block('i', 'h1'); // uses h1's default, unset
+ const other = block('o', 'h2'); // a different kind, untouched
+
+ ok(docStyleCss(doc, explicit) === docStyleCss(doc, implicit),
+ 'before any edit, the explicit user and the implicit user already agree (both read the built-in)');
+
+ // "Update style to match this paragraph" writes into doc.styles — simulate
+ // the panel's edit path directly with the exported pure helper
+ doc = { ...doc, styles: { 'default-h1': mergeStyle(doc, 'default-h1', 'h1', { size: 40, color: '#ff0000' }) } };
+
+ const cssExplicit = docStyleCss(doc, explicit);
+ const cssImplicit = docStyleCss(doc, implicit);
+ ok(winner(cssExplicit, 'font-size') === '40px', 'the explicit user picks up the edit');
+ ok(winner(cssImplicit, 'font-size') === '40px', 'so does the block that never set styleId at all');
+ ok(winner(cssExplicit, 'color') === '#ff0000' && winner(cssImplicit, 'color') === '#ff0000',
+ 'both agree on the new colour too');
+ ok(docStyleCss(doc, other) !== cssExplicit, 'a DIFFERENT kind (h2) is unaffected by editing h1');
+}
+
+H('materialize copies the built-in on first edit, and only then');
+{
+ const doc = emptyDoc();
+ ok(doc.styles?.['default-h2'] === undefined, 'nothing materialized yet');
+ const copy = materialize(doc, 'default-h2', 'h2');
+ ok(copy.size === 15.5 && copy.sb === 24, 'the copy carries the built-in\'s own numbers');
+ ok(doc.styles?.['default-h2'] === undefined, 'materialize does not mutate the document — the caller commits');
+
+ const shell = materialize(doc, 'my-custom-style', 'para');
+ ok(shell.id === 'my-custom-style' && shell.kind === 'para', 'an id with no built-in gets a bare shell, not a crash');
+}
+
+// ═══════════════════════════════════════════════════════ per-block overrides win
+
+H('direct per-block formatting wins over the style — composed the way render.ts does');
+{
+ const doc: TypeDoc = { ...emptyDoc(), styles: { 'default-h1': { ...BUILT_IN_STYLES['default-h1'], align: 'left', sb: 5 } } };
+ const b = block('h', 'h1'); // uses the (now edited) h1 default: align left, sb 5
+
+ const undisturbed = [docStyleCss(doc, b), blockStyle(b)].filter(Boolean).join(';');
+ ok(winner(undisturbed, 'text-align') === 'left', 'with no override, the style\'s own alignment applies');
+
+ b.align = 'right'; // a direct per-block override (layout.ts vocabulary)
+ b.sb = 40;
+ const overridden = [docStyleCss(doc, b), blockStyle(b)].filter(Boolean).join(';');
+ ok(winner(overridden, 'text-align') === 'right', 'the block\'s OWN alignment wins, not the style\'s "left"');
+ ok(winner(overridden, 'margin-top') === '40px', 'and its own space-before wins over the style\'s 5px');
+ ok(hasDirectFormatting(b), 'and the panel can tell this block has been overridden');
+ ok(!hasDirectFormatting(block('clean', 'h1')), 'while an untouched block does not read as modified');
+}
+
+H('effectiveLayout reports block over style over document, for "update style to match"');
+{
+ const doc: TypeDoc = {
+ ...emptyDoc(),
+ layout: { sa: 99 }, // document default
+ styles: { 'default-h2': { ...BUILT_IN_STYLES['default-h2'], sa: 8, lh: 1.5 } }, // style layer
+ };
+ const untouched = block('u', 'h2');
+ const eff0 = effectiveLayout(doc, untouched);
+ ok(eff0.sa === 8, 'the style\'s space-after beats the document default (8, not 99)');
+ ok(eff0.lh === 1.5, 'and its line spacing applies too');
+
+ const overridden = block('v', 'h2', { sa: 1 });
+ const eff1 = effectiveLayout(doc, overridden);
+ ok(eff1.sa === 1, 'the block\'s own space-after beats the style\'s 8');
+ ok(eff1.lh === 1.5, 'while the style still supplies what the block did not touch');
+}
+
+H('captureStyleFromBlock — the pure half of "Update style to match this paragraph"');
+{
+ const doc = emptyDoc();
+ const b: Block = { id: 'h', kind: 'h1', text: 'A much longer heading', align: 'center', sa: 3,
+ marks: [{ t: 'font', from: 0, to: 6, family: 'Georgia, serif', size: 30 }] };
+ const patch = captureStyleFromBlock(doc, b);
+ ok(patch !== null, 'h1 has an active style, so there is something to capture');
+ ok(patch!.align === 'center' && patch!.sa === 3, 'the block\'s own overrides are captured');
+ ok(patch!.family === undefined && patch!.size === undefined,
+ 'a font mark that does not cover the WHOLE block is "mixed", so family/size are left alone');
+
+ b.marks = [{ t: 'font', from: 0, to: b.text.length, family: 'Georgia, serif', size: 30 }];
+ const whole = captureStyleFromBlock(doc, b);
+ ok(whole!.family === 'Georgia, serif' && whole!.size === 30,
+ 'a font mark covering the ENTIRE block is captured into the style');
+
+ const noStyleKind = block('t', 'toc'); // no default style, and no explicit styleId
+ ok(captureStyleFromBlock(doc, noStyleKind) === null, 'a kind with nothing active captures nothing');
+}
+
+// ═══════════════════════════════════════════════════════ save / reload
+
+H('a style, and a block\'s reference to it, survive save/reload');
+{
+ const doc: TypeDoc = {
+ ...emptyDoc(),
+ body: [
+ block('p1', 'h2', { styleId: 'brand-heading' }),
+ block('p2', 'para'),
+ ],
+ styles: {
+ 'brand-heading': { id: 'brand-heading', kind: 'h2', name: 'Brand heading',
+ family: 'Georgia, serif', size: 22, weight: 700, italic: true,
+ color: '#204060', align: 'left', sb: 10, sa: 4, lh: 1.3, ind: 12 },
+ 'default-h1': { ...BUILT_IN_STYLES['default-h1'], size: 40 }, // a materialized built-in too
+ },
+ };
+ const raw = JSON.stringify(doc);
+ const r = parseDoc(raw);
+ ok(r.ok, 'the file with styles parses');
+ if (!r.ok) throw new Error('unreachable');
+
+ ok(r.doc.body[0].styleId === 'brand-heading', 'the block\'s style reference survives');
+ const s = r.doc.styles?.['brand-heading'];
+ ok(!!s, 'the custom style survives');
+ ok(s?.family === 'Georgia, serif' && s?.size === 22 && s?.weight === 700 && s?.italic === true
+ && s?.color === '#204060' && s?.align === 'left' && s?.sb === 10 && s?.sa === 4
+ && s?.lh === 1.3 && s?.ind === 12,
+ 'every field of the custom style round-trips exactly');
+ ok(r.doc.styles?.['default-h1']?.size === 40, 'a materialized built-in override survives too');
+ ok(docStyleCss(r.doc, r.doc.body[0]) === docStyleCss(doc, doc.body[0]),
+ 'and the reloaded document renders identically to the one that was saved');
+}
+
+H('parseDoc repairs a malformed styles map instead of trusting it');
+{
+ const raw = JSON.stringify({
+ format: 'bento/type', version: 1, docId: 'd1', title: 'T',
+ page: { width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104 },
+ body: [{ id: 'p1', kind: 'para', text: 'x' }],
+ footnotes: {}, revisions: [], signatures: [],
+ styles: {
+ good: { kind: 'h1', name: 'Good', size: 20, weight: 650, italic: 'yes',
+ color: 'red; background:url(https://evil/x.png)', align: 'diagonal', lh: 100 },
+ bad1: 'not an object',
+ bad2: null,
+ },
+ });
+ const r = parseDoc(raw);
+ ok(r.ok, 'still parses — a bad style entry is repaired, not fatal');
+ if (!r.ok) throw new Error('unreachable');
+ const styles = r.doc.styles ?? {};
+ ok(Object.keys(styles).length === 1, `only the one usable entry survives (${Object.keys(styles).join(',')})`);
+ const g = styles.good;
+ ok(g.kind === 'h1' && g.name === 'Good', 'the valid fields are kept');
+ ok(g.size === 20, 'a size inside range is kept');
+ // Math.round(6.5) rounds UP in JS (round-half-up), so 650 → 700
+ ok(g.weight === 700, `weight 650 rounds to the nearest hundred (${g.weight})`);
+ ok(g.italic === undefined, 'a non-boolean italic is dropped, not coerced');
+ ok(g.color === undefined, 'a colour that could close its declaration and open another is refused');
+ ok(g.align === undefined, 'an align that is not one of the four words is dropped');
+ ok(g.lh === undefined, 'a line-height of 100 is outside 0.5–4 and dropped');
+}
+
+H('safeStyleColor is an allow-list, defence in depth over the parser\'s own check');
+{
+ ok(safeStyleColor('#1a1a1a') === '#1a1a1a', 'a hex colour passes');
+ ok(safeStyleColor('rgba(10, 20, 30, .5)') === 'rgba(10, 20, 30, .5)', 'an rgba() passes');
+ ok(safeStyleColor('crimson') === 'crimson', 'a named colour passes');
+ ok(safeStyleColor('red; } body { background: url(https://evil/x.png') === null, 'an injection attempt is refused');
+ ok(safeStyleColor(undefined) === null, 'undefined is refused, not printed as "undefined"');
+}
+
+H('listStyles offers the built-ins in a stable order, plus any custom ones');
+{
+ const doc: TypeDoc = { ...emptyDoc(), styles: { 'brand': { id: 'brand', kind: 'para', name: 'Brand body' } } };
+ const ids = listStyles(doc).map(s => s.id);
+ ok(ids[0] === 'default-body' && ids.includes('default-h1') && ids.includes('default-quote'),
+ 'the seven built-ins are always offered');
+ ok(ids.includes('brand'), 'and a custom style the document defines is offered too');
+ ok(lookupStyle(doc, 'brand')?.name === 'Brand body', 'lookupStyle finds it');
+}
+
+// ═══════════════════════════════════════════════════════ the live-editor stylesheet
+//
+// render.ts does NOT write named-style CSS into a block's `style` attribute —
+// see docstyles.ts's `styleSheetCss` header for why: layout.ts repaints that
+// attribute independently (its own MutationObserver, `blockStyle(b)` alone)
+// on every render, and an earlier version of this feature that also wrote
+// there had its contribution silently erased microtasks later. Instead a
+// `[data-style-id]` stylesheet is injected once and updated in step; the
+// editor tags each element with the attribute. This is the part of the
+// design that closed a REAL bug, so it gets its own coverage.
+
+H('styleSheetCss — the mechanism the live editor actually uses');
+{
+ const doc = emptyDoc();
+ const css = styleSheetCss(doc);
+ ok(css.includes('[data-style-id="default-h1"]'), 'h1\'s built-in gets a rule, unedited or not');
+ ok(!css.includes('[data-style-id="default-body"]'),
+ 'Body is empty, so it gets NO rule at all — an empty selector would be dead weight');
+ ok(winner(css.match(/\[data-style-id="default-h2"\]\{([^}]*)\}/)?.[1] ?? '', 'font-size') === '15.5px',
+ 'each rule carries that style\'s own declarations');
+
+ const edited: TypeDoc = { ...doc, styles: { 'default-h3': { ...BUILT_IN_STYLES['default-h3'], color: '#112233' } } };
+ const css2 = styleSheetCss(edited);
+ ok(css2.includes('[data-style-id="default-h3"]{') && css2.includes('color:#112233'),
+ 'editing a built-in changes ITS rule, in place');
+
+ const custom: TypeDoc = { ...doc, styles: { brand: { id: 'brand', kind: 'para', name: 'Brand', size: 19 } } };
+ ok(styleSheetCss(custom).includes('[data-style-id="brand"]{font-size:19px}'), 'a custom style gets its own rule too');
+
+ // an id must not be able to close its own attribute selector and inject a
+ // second one — defence in depth, since parseDoc already restricts what
+ // reaches an id in practice
+ const hostile: TypeDoc = { ...doc, styles: { 'x"}body{display:none}[x="y': { id: 'x"}body{display:none}[x="y', kind: 'para', name: 'x', size: 10 } } };
+ const hcss = styleSheetCss(hostile);
+ ok(hcss.includes('\\"') && !hcss.includes('}body{display:none}[x="y"]{font-size'),
+ 'a quote inside a style id is escaped, not left to break out of the selector');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-theme.mjs b/scripts/test-type-theme.mjs
index 720cc2be..3c698d44 100644
--- a/scripts/test-type-theme.mjs
+++ b/scripts/test-type-theme.mjs
@@ -80,10 +80,23 @@ H('chrome never borrows a document token');
H('no literal colours outside the token blocks');
{
+ // EXEMPT, with the reason written down — the house pattern from
+ // scripts/test-slides-theme.mjs, which keeps a list like this rather than
+ // letting the gate erode:
+ //
+ // .t-mark-word span the slash in `bento/type` is the BRAND accent, and
+ // brand does not follow the reader's theme — the same
+ // literal appears in slides and spaces, beside the
+ // mark's SVG fills which are literal for the same
+ // reason. Tokenising it would let a future theme
+ // recolour the wordmark, which is the one thing in the
+ // chrome that must look identical in all three apps.
+ const EXEMPT = /\.t-mark-word\s+span/;
const lines = css.split('\n');
const strays = [];
lines.forEach((line, i) => {
if (/^\s*--/.test(line)) return; // a token definition
+ if (EXEMPT.test(line)) return;
if (/#[0-9a-fA-F]{3,8}\b/.test(line)) strays.push(`${i + 1}: ${line.trim().slice(0, 56)}`);
});
ok(strays.length === 0,
diff --git a/scripts/test-type-toc.ts b/scripts/test-type-toc.ts
new file mode 100644
index 00000000..a0df5434
--- /dev/null
+++ b/scripts/test-type-toc.ts
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type section numbering + table of contents. node scripts/test-type-toc.ts
+//
+// Everything here is a PURE function over (document, metrics) — that is the
+// whole design claim. A number or a page reference that reached the document
+// JSON would be wrong the moment the next heading was typed, so this rig checks
+// the derivation AND checks that the derivation writes nothing.
+//
+// The interesting cases are the ones that renumber: an insertion in the middle,
+// a heading that opts out, and an h3 with no h2 above it — which numbers 1.0.1,
+// because a number's depth must equal its heading's level and because a
+// silently promoted 1.1 hides a hole in the author's outline.
+
+import {
+ headings, sectionNumbers, buildToc, tocFor, pageOfY, headingPages,
+ sectionSettings, setNumbered, tocEntriesHtml, sectionNumberHtml, decorate,
+ TOC_KIND, hasToc,
+} from '../type/src/toc.ts';
+import { emptyDoc, type Block, type BlockKind, type TypeDoc } from '../type/src/model.ts';
+import type { Metrics, Page } from '../type/src/paginate.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const b = (kind: string, text: string, extra: Partial<Block> = {}): Block =>
+ ({ id: `${kind}-${text.toLowerCase().replace(/\W+/g, '-')}`, kind: kind as BlockKind, text, ...extra });
+
+// Numbering is OPT-IN — absent means off, because the documents this app opens
+// mostly carry their numbers in the heading text already ("1. Scope of Work"),
+// and numbering those again renders "1.1 1. Scope of Work". These fixtures
+// exercise the numbering machinery, so they turn it on; the default itself is
+// asserted separately below.
+const docOf = (body: Block[]): TypeDoc =>
+ ({ ...emptyDoc(), body, sections: { numbered: true } } as TypeDoc);
+
+/** '1.1 Scope' for every heading, so an expectation reads like the page. */
+const numbering = (doc: TypeDoc) =>
+ headings(doc).map(h => `${h.number ?? '—'} ${h.text}`).join(' | ');
+
+const page = (n: number, start: number, end: number): Page =>
+ ({ n, start, end, notes: [], reserved: 0 });
+const metricsOf = (...pages: Page[]): Metrics => ({ pages, ms: 0 });
+
+H('h1 / h2 / h3 number as 1, 1.1, 1.2.3');
+{
+ const doc = docOf([
+ b('h1', 'One'), b('para', 'text'),
+ b('h2', 'One A'), b('h3', 'One A i'), b('h3', 'One A ii'),
+ b('h2', 'One B'),
+ b('h1', 'Two'), b('h2', 'Two A'), b('h3', 'Two A i'),
+ ]);
+ ok(numbering(doc) ===
+ '1 One | 1.1 One A | 1.1.1 One A i | 1.1.2 One A ii | 1.2 One B | 2 Two | 2.1 Two A | 2.1.1 Two A i',
+ numbering(doc));
+ ok(sectionNumbers(doc).get('h3-two-a-i') === '2.1.1', 'the map is keyed by block id');
+ ok(sectionNumbers(doc).size === 8, 'every heading has a number and nothing else does');
+}
+
+H('a deeper level resets when a shallower one advances');
+{
+ const doc = docOf([b('h1', 'A'), b('h2', 'A1'), b('h3', 'A1a'), b('h2', 'A2'), b('h3', 'A2a')]);
+ ok(numbering(doc) === '1 A | 1.1 A1 | 1.1.1 A1a | 1.2 A2 | 1.2.1 A2a', numbering(doc));
+}
+
+H('a SKIPPED level numbers with a zero, and is not promoted');
+{
+ // an h3 with no h2 above it: the h2 counter has never advanced, so it reads
+ // 0. The depth of the number still equals the level of the heading, which is
+ // the invariant that makes numbers comparable — and the hole is visible.
+ const doc = docOf([b('h1', 'A'), b('h3', 'Orphan'), b('h2', 'A1'), b('h3', 'A1a')]);
+ ok(numbering(doc) === '1 A | 1.0.1 Orphan | 1.1 A1 | 1.1.1 A1a', numbering(doc));
+
+ // LEADING zeros are dropped, because they are not a hole: a document that
+ // never uses h1 (its title is the h1, or it has none) does not have a level
+ // one to be missing. This is the case a role:'title' heading creates, and it
+ // read '0.1 Scope' until the rig caught it.
+ const noTop = docOf([b('h2', 'A'), b('h3', 'A1'), b('h2', 'B')]);
+ ok(numbering(noTop) === '1 A | 1.1 A1 | 2 B', numbering(noTop));
+
+ // filling the gap in later is an ordinary renumber
+ const filled = docOf([b('h1', 'A'), b('h2', 'New'), b('h3', 'Orphan')]);
+ ok(sectionNumbers(filled).get('h3-orphan') === '1.1.1', '1.0.1 becomes 1.1.1 once the h2 exists');
+}
+
+H('inserting a heading renumbers everything after it');
+{
+ const before = docOf([b('h1', 'A'), b('h2', 'A1'), b('h2', 'A2'), b('h1', 'B'), b('h2', 'B1')]);
+ ok(numbering(before) === '1 A | 1.1 A1 | 1.2 A2 | 2 B | 2.1 B1', numbering(before));
+
+ const after = docOf([...before.body]);
+ after.body.splice(2, 0, b('h2', 'Inserted'));
+ ok(numbering(after) === '1 A | 1.1 A1 | 1.2 Inserted | 1.3 A2 | 2 B | 2.1 B1', numbering(after));
+ // the point of deriving: the SAME blocks carry different numbers now
+ ok(sectionNumbers(before).get('h2-a2') === '1.2' && sectionNumbers(after).get('h2-a2') === '1.3',
+ 'a block that did not change got a new number');
+}
+
+H('roles decide what is numbered and what is listed');
+{
+ const doc = docOf([
+ b('h1', 'The Deed', { role: 'title' }),
+ b('h2', 'Preamble', { role: 'unnumbered' }),
+ b('h2', 'Scope'),
+ b('h2', 'Schedule', { role: 'unlisted' }),
+ b('h2', 'Fees'),
+ ]);
+ // the title never opens level 1, so its sections are 1, 2, 3 — not 0.1, 0.2
+ ok(numbering(doc) === '— The Deed | — Preamble | 1 Scope | 2 Schedule | 3 Fees', numbering(doc));
+ ok(headings(doc).filter(h => h.listed).map(h => h.text).join(',') === 'Preamble,Scope,Fees',
+ 'title and unlisted headings stay out of the contents');
+ // an opted-out heading is outside the sequence, not a gap in it
+ ok(buildToc(doc).map(e => `${e.number ?? '—'}`).join(' ') === '— 1 3',
+ 'the numbers its neighbours carry are unaffected by the exclusion');
+ ok(headings(doc)[0].number === undefined, 'a document title is not section 1 of itself');
+}
+
+H('the document-level switch turns numbering off');
+{
+ const doc = docOf([b('h1', 'A'), b('h2', 'A1')]);
+ ok(sectionSettings(doc).numbered, 'absent means on — numbering is automatic by default');
+ setNumbered(doc, false);
+ ok(numbering(doc) === '— A | — A1', numbering(doc));
+ ok(buildToc(doc).length === 2, 'the contents still lists them, without numbers');
+ setNumbered(doc, true);
+ ok(numbering(doc) === '1 A | 1.1 A1', 'and back on again');
+ ok(JSON.stringify(doc.sections) === '{"numbered":true}', 'the switch is the ONLY thing stored');
+}
+
+H('a TOC built against metrics gives the right page per heading');
+{
+ const doc = docOf([b('h1', 'A'), b('h2', 'A1'), b('h2', 'A2'), b('h2', 'A3')]);
+ const metrics = metricsOf(page(1, 0, 800), page(2, 800, 1600), page(3, 1600, Infinity));
+ const tops = new Map([['h1-a', 0], ['h2-a1', 400], ['h2-a2', 800], ['h2-a3', 2000]]);
+
+ ok(pageOfY(metrics.pages, 0) === 1 && pageOfY(metrics.pages, 799) === 1, 'page one');
+ ok(pageOfY(metrics.pages, 800) === 2, 'a heading exactly on a break is on the NEW page');
+ ok(pageOfY(metrics.pages, 5000) === 3, 'the last page has no end and swallows the rest');
+ ok(pageOfY(metrics.pages, -50) === undefined, 'nothing above the first line is on a page');
+
+ const pages = headingPages(metrics, tops);
+ ok([...pages.values()].join(',') === '1,1,2,3', `pages ${[...pages.values()].join(',')}`);
+
+ const entries = tocFor(doc, metrics, tops);
+ ok(entries.map(e => `${e.number} ${e.text} ${e.page}`).join(' | ') ===
+ '1 A 1 | 1.1 A1 1 | 1.2 A2 2 | 1.3 A3 3',
+ entries.map(e => `${e.number} ${e.text} ${e.page}`).join(' | '));
+ ok(buildToc(doc).every(e => e.page === undefined),
+ 'built with no metrics, an entry simply has no page yet');
+ ok(entries.every(e => e.level === (e.number!.includes('.') ? 2 : 1)), 'level comes from the kind');
+}
+
+H('an empty document, and one with no headings');
+{
+ const empty = emptyDoc();
+ ok(headings(empty).length === 0 && buildToc(empty).length === 0, 'no headings, no entries');
+ ok(tocEntriesHtml(buildToc(empty)) === '', 'and no markup at all — an empty list is not a blank row');
+ ok(hasToc(empty) === false, 'a fresh document has no contents block');
+
+ const prose = docOf([b('para', 'one'), b('quote', 'two'), b('ul', 'three')]);
+ ok(buildToc(prose).length === 0, 'paragraphs, quotes and list items are not headings');
+ const metrics = metricsOf(page(1, 0, Infinity));
+ ok(tocFor(prose, metrics, new Map()).length === 0, 'and metrics change nothing about that');
+}
+
+H('DERIVED, NEVER STORED');
+{
+ const doc = docOf([
+ b('h1', 'A'), { id: 'toc-1', kind: TOC_KIND, text: 'Contents' }, b('h2', 'A1'),
+ ]);
+ const before = JSON.stringify(doc);
+ const metrics = metricsOf(page(1, 0, 800), page(2, 800, Infinity));
+ const entries = tocFor(doc, metrics, new Map([['h1-a', 0], ['h2-a1', 900]]));
+ const html = tocEntriesHtml(entries) + sectionNumberHtml('1.1') + JSON.stringify(headings(doc));
+ ok(html.length > 0, 'the whole derivation ran');
+ ok(JSON.stringify(doc) === before, 'and not one byte of the document changed');
+
+ // the redline diffs a block's plain text: the contents block's text is its
+ // HEADING, so repagination can never make a review noisy
+ ok(doc.body[1].text === 'Contents', 'the TOC block still stores only its heading');
+ const bodyJson = JSON.stringify(doc.body);
+ ok(!/"(number|page|sections)"/.test(bodyJson) && !bodyJson.includes('1.1'),
+ 'no number and no page reference is anywhere in the body JSON');
+
+ // the injected markup is an ATOM (data-derived), which the core's atom
+ // predicate skips — that is what stops it being read back into the model
+ ok(tocEntriesHtml(entries).startsWith('<span class="t-toc" data-derived'), 'entries are one atom');
+ ok(sectionNumberHtml('1.1').includes('data-derived'), 'so is a section number');
+ ok(!/data-derived[^>]*>\s/.test(sectionNumberHtml('1.1')),
+ 'with no stray whitespace beside it — a space there WOULD be a character');
+}
+
+H('the decorator, which is what the renderer calls');
+{
+ const doc = docOf([
+ b('h1', 'A'), { id: 'toc-1', kind: TOC_KIND, text: 'Contents' }, b('h2', 'A<b>1</b>'),
+ ]);
+ ok(decorate(doc, doc.body[0], 'A') === sectionNumberHtml('1') + 'A', 'a heading gains its number in front');
+ ok(decorate(doc, b('para', 'nothing'), 'nothing') === null, 'a paragraph is left entirely alone');
+
+ const toc = decorate(doc, doc.body[1], 'Contents')!;
+ ok(toc.startsWith('Contents'), 'the TOC keeps its own heading as real, editable text');
+ ok(toc.includes(`data-goto="${doc.body[2].id}"`), 'and carries an anchor per entry, for click-to-scroll');
+ ok(toc.includes('&lt;b&gt;'), 'entry text is escaped — a heading is plain text, not markup');
+ ok(!toc.includes('#'), 'no literal colour in the derived markup; colour comes from the stylesheet');
+ ok(/flex:0 0 2\.4em/.test(toc),
+ 'the page column has a FIXED width, so filling pages in later moves nothing');
+
+ setNumbered(doc, false);
+ ok(decorate(doc, doc.body[0], 'A') === null, 'with numbering off a heading is not touched at all');
+}
+
+H('automatic numbering is OFF until asked for');
+{
+ // The risk is asymmetric. On by default visibly corrupts an existing
+ // document — the starter contract renders "1.1 1. Scope of Work" — while off
+ // by default is a feature somebody has to find. Verified on that document,
+ // which is exactly the common case: headings that already carry numbers.
+ const plain = { ...emptyDoc(), body: [b('h1', '1. Scope of Work'), b('h2', '1.1 Fees')] } as TypeDoc;
+ ok(headings(plain).every(h => h.number === undefined),
+ 'a document that says nothing about numbering gets no numbers');
+ const on = { ...plain, sections: { numbered: true } } as TypeDoc;
+ ok(headings(on).some(h => h.number !== undefined), 'and asking for them turns them on');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/scripts/test-type-track.ts b/scripts/test-type-track.ts
new file mode 100644
index 00000000..c4f6b9e4
--- /dev/null
+++ b/scripts/test-type-track.ts
@@ -0,0 +1,250 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Tracked changes — the engine, before any UI is wired to it.
+//
+// node scripts/test-type-track.ts
+//
+// The property that matters and is easy to lose: a tracked document must be
+// able to go BOTH ways. Accepting everything must give the text as edited;
+// rejecting everything must give the text as it was. If either drifts, the
+// feature is worse than not having it — a lawyer rejects a change and gets
+// something nobody wrote.
+
+import { register } from 'node:module';
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+
+const {
+ trackEdit, resolve, resolveAll, textOf, changes, changeAt, stepChange, parseTrackView,
+} = await import('../type/src/track.ts');
+const { emptyDoc, wordCount } = await import('../type/src/model.ts');
+
+let checks = 0, bad = 0;
+const ok = (cond: boolean, msg: string) => {
+ checks++;
+ if (cond) console.log(` ok ${msg}`);
+ else { bad++; console.log(` FAIL ${msg}`); }
+};
+const eq = (a: unknown, b: unknown, msg: string) =>
+ ok(JSON.stringify(a) === JSON.stringify(b), `${msg}${JSON.stringify(a) === JSON.stringify(b) ? '' : ` (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`}`);
+
+const blk = (text: string, marks?: unknown[]) =>
+ ({ id: 'p1', kind: 'para', text, ...(marks ? { marks } : {}) }) as never;
+const WHO = 'Counsel', WHEN = '2026-08-18T10:00:00Z';
+const edit = (before: string, after: string) => trackEdit(blk(before), blk(after), WHO, WHEN);
+
+console.log('\n— an insertion —');
+{
+ const b = edit('Payment is due.', 'Payment is now due.');
+ eq(b.text, 'Payment is now due.', 'text carries the insertion');
+ const ins = (b.marks ?? []).filter((m: { t: string }) => m.t === 'ins');
+ eq(ins.length, 1, 'one ins mark');
+ eq(b.text.slice(ins[0].from, ins[0].to), 'now ', 'the mark covers exactly what was typed');
+ eq(ins[0].by, WHO, 'attributed');
+ eq(textOf(b), 'Payment is now due.', 'a reader sees the insertion');
+}
+
+console.log('\n— a deletion keeps its characters —');
+{
+ const b = edit('Payment is now due.', 'Payment is due.');
+ eq(b.text, 'Payment is now due.', 'the deleted characters are STILL THERE');
+ const del = (b.marks ?? []).filter((m: { t: string }) => m.t === 'del');
+ eq(del.length, 1, 'one del mark');
+ eq(b.text.slice(del[0].from, del[0].to), 'now ', 'the mark covers exactly what was removed');
+ eq(textOf(b), 'Payment is due.', 'a reader does NOT see deleted text');
+}
+
+console.log('\n— type over a selection: both, at once —');
+{
+ const b = edit('due within 30 days', 'due within 45 days');
+ ok((b.marks ?? []).some((m: { t: string }) => m.t === 'ins'), 'has an insertion');
+ ok((b.marks ?? []).some((m: { t: string }) => m.t === 'del'), 'has a deletion');
+ eq(textOf(b), 'due within 45 days', 'reads as the new text');
+}
+
+console.log('\n— accept and reject, one change at a time —');
+{
+ const ins = edit('Payment is due.', 'Payment is now due.');
+ const m = (ins.marks ?? []).find((x: { t: string }) => x.t === 'ins')!;
+ eq(resolve(ins, m, true).text, 'Payment is now due.', 'accepting an insertion keeps the words');
+ eq((resolve(ins, m, true).marks ?? []).length, 0, 'and drops the mark');
+ eq(resolve(ins, m, false).text, 'Payment is due.', 'rejecting an insertion removes them');
+
+ const del = edit('Payment is now due.', 'Payment is due.');
+ const d = (del.marks ?? []).find((x: { t: string }) => x.t === 'del')!;
+ eq(resolve(del, d, true).text, 'Payment is due.', 'accepting a deletion removes the words');
+ eq(resolve(del, d, false).text, 'Payment is now due.', 'rejecting a deletion puts them back');
+ eq((resolve(del, d, false).marks ?? []).length, 0, 'and drops the mark');
+}
+
+console.log('\n— the round trip, over a whole document —');
+{
+ const ORIGINAL = 'The Supplier shall provide the services within 30 days.';
+ const EDITED = 'The Supplier must provide the services within 45 days.';
+ const doc = emptyDoc();
+ doc.body = [trackEdit(blk(ORIGINAL), blk(EDITED), WHO, WHEN)];
+
+ eq(textOf(doc.body[0]), EDITED, 'a reader sees the edited text');
+ ok(changes(doc).length >= 2, `every change is listed (${changes(doc).length})`);
+
+ const accepted = JSON.parse(JSON.stringify(doc));
+ resolveAll(accepted, true);
+ eq(accepted.body[0].text, EDITED, 'accept all → the text as edited');
+ eq((accepted.body[0].marks ?? []).length, 0, 'accept all → no marks left');
+
+ const rejected = JSON.parse(JSON.stringify(doc));
+ resolveAll(rejected, false);
+ eq(rejected.body[0].text, ORIGINAL, 'reject all → the text as it was');
+ eq((rejected.body[0].marks ?? []).length, 0, 'reject all → no marks left');
+}
+
+console.log('\n— existing formatting survives —');
+{
+ const before = blk('Payment is due.', [{ t: 'b', from: 0, to: 7 }]);
+ const after = blk('Payment is really due.', [{ t: 'b', from: 0, to: 7 }]);
+ const b = trackEdit(before, after, WHO, WHEN);
+ ok((b.marks ?? []).some((m: { t: string; from: number; to: number }) =>
+ m.t === 'b' && m.from === 0 && m.to === 7), 'the bold run is still bold');
+}
+
+console.log('\n— two authors do not merge —');
+{
+ // `next` must CARRY the marks so far — in the app it is the block read back
+ // out of contentEditable, which has them. Building it with a bare blk() threw
+ // Ann's mark away before Bob ever edited, and the rig then reported the
+ // engine merging two authors when what it had actually done was lose one.
+ let b = trackEdit(blk('a'), blk('ab'), 'Ann', WHEN);
+ b = trackEdit(b, { ...b, text: b.text + 'c' } as never, 'Bob', WHEN);
+ const ins = (b.marks ?? []).filter((m: { t: string }) => m.t === 'ins');
+ eq(ins.length, 2, 'abutting insertions by different people stay separate');
+ eq(ins.map((m: { by: string }) => m.by).sort(), ['Ann', 'Bob'], 'each keeps its author');
+}
+
+console.log('\n— the word count is what a READER would count —');
+{
+ const doc = emptyDoc();
+ doc.body = [trackEdit(blk('one two three four five'), blk('one two'), WHO, WHEN)];
+ eq(doc.body[0].text, 'one two three four five', 'the deleted words are still in the model');
+ eq(wordCount(doc), 2, 'but the count is 2, not 5');
+ // Without this, DELETING text makes the word count go UP — the struck
+ // characters stay in b.text and a raw count has no way to know they are gone.
+ const grown = emptyDoc();
+ grown.body = [trackEdit(blk('one two'), blk('one two three'), WHO, WHEN)];
+ eq(wordCount(grown), 3, 'and an insertion counts');
+}
+
+console.log('\n— an untracked document is untouched —');
+{
+ const doc = emptyDoc();
+ const before = JSON.stringify(doc.body);
+ resolveAll(doc, true);
+ eq(JSON.stringify(doc.body), before, 'resolveAll on a clean document changes nothing');
+}
+
+console.log('\n— changeAt finds the change under a caret —');
+{
+ const doc = emptyDoc();
+ doc.body = [
+ { id: 'b1', kind: 'para', text: 'aaa bbb ccc', marks: [{ t: 'ins', from: 4, to: 7, by: 'A', at: WHEN }] },
+ { id: 'b2', kind: 'para', text: 'ddd eee fff', marks: [{ t: 'del', from: 4, to: 7, by: 'A', at: WHEN }] },
+ ] as never;
+ const list = changes(doc);
+ eq(list.length, 2, 'two tracked changes across two blocks');
+ eq(changeAt(list, 'b1', 5), 0, 'a caret inside a change finds it');
+ eq(changeAt(list, 'b1', 4), 0, 'the change\'s own start counts as inside it');
+ eq(changeAt(list, 'b1', 7), 0, 'and so does its own end');
+ eq(changeAt(list, 'b1', 0), -1, 'a caret elsewhere in the block finds nothing');
+ eq(changeAt(list, 'b2', 5), 1, 'and the second block finds the second change');
+}
+
+console.log('\n— stepChange walks the document in order, and wraps —');
+{
+ const doc = emptyDoc();
+ doc.body = [
+ { id: 'b1', kind: 'para', text: 'aaa bbb ccc', marks: [{ t: 'ins', from: 4, to: 7, by: 'A', at: WHEN }] },
+ { id: 'b2', kind: 'para', text: 'ddd eee fff', marks: [{ t: 'del', from: 4, to: 7, by: 'A', at: WHEN }] },
+ ] as never;
+ const list = changes(doc);
+
+ eq(stepChange(doc, list, null, 0, 1), 0, 'no caret: next starts at the first change');
+ eq(stepChange(doc, list, null, 0, -1), 1, 'no caret: previous starts at the last change');
+
+ eq(stepChange(doc, list, 'b1', 0, 1), 0, 'next, from before the first change, finds it');
+ eq(stepChange(doc, list, 'b1', 4, 1), 1,
+ 'next, from ON a change, SKIPS it and finds the next one — so pressing next twice always advances');
+ eq(stepChange(doc, list, 'b2', 7, 1), 0, 'next, past the last change, WRAPS to the first');
+
+ eq(stepChange(doc, list, 'b2', 7, -1), 1,
+ 'previous, from just past a change, lands ON that change — so pressing previous after next returns to it');
+ eq(stepChange(doc, list, 'b1', 0, -1), 1, 'previous, from before the first change, WRAPS to the last');
+
+ eq(stepChange(doc, [], 'b1', 0, 1), null, 'no changes at all: nothing to step to');
+}
+
+console.log('\n— accept/reject-at-the-caret uses the SAME engine a card does —');
+{
+ // review.ts resolves the change `changeAt`/`stepChange` point it at with
+ // track.ts's own `resolve` — there is no second path from "caret" to
+ // "mutated block", which is what makes the two ways in (a card, or the
+ // keyboard) produce byte-identical results.
+ const ORIGINAL = 'The Supplier shall deliver within 30 days.';
+ const EDITED = 'The Supplier must deliver within 45 days.';
+ const doc = emptyDoc();
+ doc.body = [trackEdit(blk(ORIGINAL), blk(EDITED), WHO, WHEN)];
+
+ const viaCard = JSON.parse(JSON.stringify(doc));
+ resolveAll(viaCard, true);
+
+ const list = changes(doc);
+ const caretDoc = JSON.parse(JSON.stringify(doc));
+ let i = changeAt(changes(caretDoc), 'p1', 0);
+ // walk every change from the start of the block, resolving whichever the
+ // "caret" (offset 0, always) currently finds or the next one coming up —
+ // exactly what review.ts's resolveCurrent does, minus the DOM
+ for (;;) {
+ const cur = changes(caretDoc);
+ if (!cur.length) break;
+ i = changeAt(cur, 'p1', 0);
+ if (i < 0) i = stepChange(caretDoc, cur, 'p1', 0, 1)!;
+ const ch = cur[i];
+ const bi = caretDoc.body.findIndex((b: { id: string }) => b.id === ch.block);
+ caretDoc.body[bi] = resolve(caretDoc.body[bi], ch.mark, true);
+ }
+ eq(caretDoc.body[0].text, viaCard.body[0].text, 'accepting via the caret matches accepting via "accept all"');
+ eq(caretDoc.body[0].text, EDITED, 'and both land on the edited text');
+}
+
+console.log('\n— display mode is closed and defaults safely —');
+{
+ eq(parseTrackView(null), 'all', 'nothing stored → all markup');
+ eq(parseTrackView(undefined), 'all', 'undefined → all markup');
+ eq(parseTrackView(''), 'all', 'empty string → all markup');
+ eq(parseTrackView('final'), 'final', 'a recognised value passes through');
+ eq(parseTrackView('original'), 'original', 'so does the other one');
+ eq(parseTrackView('garbage'), 'all', 'anything unrecognised → all markup, never a crash');
+}
+
+console.log('\n— display mode is purely presentational —');
+{
+ // The whole promise: NOTHING about "which view" can reach the model.
+ // parseTrackView's signature is the proof by construction — it takes a
+ // stored string, not a TypeDoc — but the requirement is behavioural, so
+ // this exercises it: build a tracked document, "view" it every which way
+ // (the exact sequence a reviewer clicking through the picker produces),
+ // and check the document — body, marks and all — never moved a byte.
+ const doc = emptyDoc();
+ doc.body = [trackEdit(blk('one two three'), blk('one two three four'), WHO, WHEN)];
+ const before = JSON.stringify(doc);
+ const beforeChanges = changes(doc).length;
+
+ for (const stored of ['final', 'original', 'all', 'original', 'garbage', null]) {
+ void parseTrackView(stored);
+ }
+
+ eq(JSON.stringify(doc), before, 'the document is byte-identical after switching through every view');
+ eq(changes(doc).length, beforeChanges,
+ 'switching to Original and back loses no change — the marks were never touched');
+}
+
+console.log(`\n${checks - bad}/${checks} checks passed`);
+if (bad) process.exit(1);
diff --git a/scripts/test-type-xref.ts b/scripts/test-type-xref.ts
new file mode 100644
index 00000000..46ac560f
--- /dev/null
+++ b/scripts/test-type-xref.ts
@@ -0,0 +1,231 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/type captions, numbering and cross-references. node scripts/test-type-xref.ts
+//
+// The claim under test is one sentence: a number is NEVER stored, so inserting
+// a table in the middle of a document renumbers everything after it and every
+// reference to it follows — and a reference whose target was deleted says so
+// out loud instead of rendering as nothing.
+//
+// All of it is pure functions over the body, which is why this rig is plain
+// node with no DOM: numbering is `captionEntries`, resolution is `refText`, and
+// the two consumers (the editor's DOM pass and print's string pass) both fill
+// the same atoms from the same index — `fillXrefsHtml` is checked here so that
+// paper cannot drift from the screen.
+
+import {
+ captionEntries, captionIndex, refText, refsIn, brokenRefs, shiftRefs, withRef,
+ newCaption, captionSite, captionForObject, refAtoms, captionPrefixHtml,
+ fillXrefsHtml, resolvedText, captionWord, docLang, joinLabel, CAPTION, BROKEN_TEXT,
+ type CaptionKind,
+} from '../type/src/xref.ts';
+import { emptyDoc, type Block, type TypeDoc } from '../type/src/model.ts';
+
+let checks = 0, failures = 0;
+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+
+const para = (id: string, text = ''): Block => ({ id, kind: 'para', text });
+const cell = (id: string, table: string, text = ''): Block =>
+ ({ id, kind: 'cell', text, cell: { table, cols: 2 } });
+const cap = (id: string, kind: CaptionKind, text: string, of?: string): Block =>
+ ({ id, kind: CAPTION, text, caption: { kind, ...(of ? { of } : {}) } });
+
+const labels = (body: Block[], lang = 'en') => captionEntries(body, lang).map(e => e.label).join(' | ');
+
+// ────────────────────────────────────────────────────────────────────────────
+H('numbering runs in document order, per kind');
+{
+ const body = [
+ para('p1', 'intro'),
+ cap('c1', 'table', 'Fees'),
+ para('p2', 'text'),
+ cap('c2', 'figure', 'The site'),
+ cap('c3', 'table', 'Milestones'),
+ cap('c4', 'figure', 'The plan'),
+ ];
+ ok(labels(body) === 'Table 1 | Figure 1 | Table 2 | Figure 2', labels(body));
+ const e = captionEntries(body);
+ ok(e[2].n === 2 && e[2].kind === 'table', 'the second table is Table 2');
+ ok(e.every(x => x.index === body.findIndex(b => b.id === x.id)), 'each entry knows where it sits');
+}
+
+H('two kinds are counted independently');
+{
+ // a document that is all figures and then all tables must not run one counter
+ const body = [cap('f1', 'figure', 'a'), cap('f2', 'figure', 'b'),
+ cap('t1', 'table', 'c'), cap('t2', 'table', 'd')];
+ ok(labels(body) === 'Figure 1 | Figure 2 | Table 1 | Table 2', labels(body));
+}
+
+H('a document with no captions');
+{
+ const body = [para('p1', 'nothing here'), para('p2', 'nor here')];
+ ok(captionEntries(body).length === 0, 'no entries');
+ ok(captionIndex(body).size === 0, 'an empty index');
+ ok(refsIn(body).length === 0 && brokenRefs(body).length === 0, 'and nothing to resolve');
+ ok(fillXrefsHtml('<p>plain text</p>', captionIndex(body)) === '<p>plain text</p>',
+ 'filling leaves ordinary markup untouched');
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+H('inserting a table in the MIDDLE renumbers everything after it');
+{
+ const before = [cap('c1', 'table', 'first'), cap('c2', 'table', 'second'), cap('c3', 'table', 'third')];
+ ok(labels(before) === 'Table 1 | Table 2 | Table 3', labels(before));
+
+ // the whole point: a number in the JSON would be wrong from here on
+ const after = [before[0], cap('cNEW', 'table', 'inserted'), before[1], before[2]];
+ ok(labels(after) === 'Table 1 | Table 2 | Table 3 | Table 4', labels(after));
+ const idx = captionIndex(after);
+ ok(idx.get('cNEW')!.n === 2, 'the newcomer is Table 2');
+ ok(idx.get('c2')!.n === 3 && idx.get('c3')!.n === 4, 'the two below it moved down');
+ ok(!('n' in (after[0] as unknown as Record<string, unknown>)), 'and no number is on the block');
+ ok(JSON.stringify(after).indexOf('"n":') < 0, 'nothing numeric entered the document JSON');
+}
+
+H('a reference resolves to the right number, and follows the target');
+{
+ const ref = { to: 'c2', at: 12 };
+ const body = [
+ cap('c1', 'table', 'Fees'),
+ cap('c2', 'table', 'Milestones'),
+ { ...para('p', 'as set out in , payment follows.'), refs: [ref] },
+ ];
+ ok(refText(captionIndex(body), ref).text === 'Table 2', 'resolves to Table 2');
+
+ const moved = [body[1], body[0], body[2]]; // the target is now first
+ ok(refText(captionIndex(moved), ref).text === 'Table 1', 'and to Table 1 once it moves up');
+ ok(refsIn(body).length === 1 && brokenRefs(body).length === 0, 'one reference, none broken');
+}
+
+H('a reference to a DELETED target degrades visibly, and is never dropped');
+{
+ const ref = { to: 'gone', at: 3 };
+ const body = [cap('c1', 'table', 'Fees'), { ...para('p', 'see above'), refs: [ref] }];
+ const r = refText(captionIndex(body), ref);
+ ok(r.ok === false, 'it does not resolve');
+ ok(r.text === BROKEN_TEXT && r.text.length > 0, `it renders as ${BROKEN_TEXT}, never as nothing`);
+ ok(brokenRefs(body).length === 1, 'and the panel can list it');
+
+ const html = fillXrefsHtml(refAtoms(body[1]).get(3)!, captionIndex(body));
+ ok(html.includes('t-xref-broken'), 'the rendered atom carries the broken class');
+ ok(html.includes(BROKEN_TEXT), 'and the visible text says so');
+
+ // restoring the table must heal it with no repair step — which is only true
+ // because the reference was kept in the model
+ const healed = [...body, cap('gone', 'table', 'Restored')];
+ ok(refText(captionIndex(healed), ref).text === 'Table 2', 'restoring the target heals the reference');
+}
+
+H('page and both styles, and their degradation');
+{
+ const body = [cap('c1', 'table', 'Fees')];
+ const idx = captionIndex(body);
+ const pageOf = (id: string) => (id === 'c1' ? 7 : undefined);
+ ok(refText(idx, { to: 'c1', at: 0, style: 'page' }, { pageOf }).text === 'page 7', 'page style');
+ ok(refText(idx, { to: 'c1', at: 0, style: 'both' }, { pageOf }).text === 'Table 1 (page 7)', 'both style');
+ ok(refText(idx, { to: 'c1', at: 0, style: 'page' }).text === 'Table 1',
+ 'with no pagination it degrades to the label, never to a guess');
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+H('the atoms occupy a position and no characters');
+{
+ const b = withRef(para('p', 'see and .'), 4, 'c1');
+ ok(b.text === 'see and .', 'the text is unchanged by adding a reference');
+ ok(b.refs!.length === 1 && b.refs![0].at === 4, 'the anchor is an offset');
+ const two = withRef(b, 9, 'c2');
+ ok(two.refs!.map(r => r.at).join(',') === '4,9', 'anchors stay sorted');
+ ok(refAtoms(two).size === 2, 'two atoms to inject');
+ ok(!/>[^<]*[A-Za-z]/.test(refAtoms(two).get(4)!.replace(BROKEN_TEXT, '')),
+ 'the atom carries no words of its own — they are filled from the index');
+}
+
+H('anchors follow an edit, by the same rule footnotes use');
+{
+ const refs = [{ to: 'a', at: 2 }, { to: 'b', at: 10 }, { to: 'c', at: 20 }];
+ const after = shiftRefs(refs, 5, 0, 3); // insert 3 chars at 5
+ ok(after.map(r => r.at).join(',') === '2,13,23', `insertion pushes later anchors (${after.map(r => r.at)})`);
+ const del = shiftRefs(refs, 8, 6, 0); // delete 8..14
+ ok(del.map(r => r.to).join(',') === 'a,c', 'an anchor inside deleted text goes with it');
+ ok(del.map(r => r.at).join(',') === '2,14', 'and the rest close up');
+ ok(shiftRefs(refs, 0, 0, 0).length === 3, 'a no-op edit changes nothing');
+}
+
+H('caption placement: after the whole table, not inside it');
+{
+ const body = [para('p0'), cell('a', 't1'), cell('b', 't1'), cell('c', 't1'), cell('d', 't1'), para('p1')];
+ const site = captionSite(body, 2)!; // caret in cell b
+ ok(site.at === 5, `the caption lands after the last cell (${site.at})`);
+ ok(site.kind === 'table' && site.of === 't1', 'and it captions that table');
+ const fig = captionSite(body, 0)!;
+ ok(fig.kind === 'figure' && fig.at === 1, 'outside a table it is a figure caption');
+ ok(captionSite([cap('c1', 'table', 'x')], 0) === null, 'a caption cannot be captioned');
+
+ const withCap = [...body.slice(0, 5), cap('c1', 'table', 'Fees', 't1'), ...body.slice(5)];
+ ok(captionForObject(withCap, 't1')?.id === 'c1', 'a table with a caption is recognised');
+ ok(captionForObject(withCap, 't9') === undefined, 'and one without is not');
+}
+
+H('a caption id is minted once and is what references point at');
+{
+ const a = newCaption('table', 't1');
+ const b = newCaption('table', 't1');
+ ok(a.id !== b.id && a.id.startsWith('cap-'), 'ids are fresh and prefixed');
+ ok(a.kind === CAPTION && a.caption!.kind === 'table' && a.caption!.of === 't1', 'shape');
+ ok(captionEntries([a]).at(0)!.id === a.id, 'the entry is keyed by the BLOCK id');
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+H('screen and paper fill the same atoms from the same index');
+{
+ const body = [
+ cap('c1', 'table', 'Fee schedule'),
+ { ...para('p', 'as in above'), refs: [{ to: 'c1', at: 6 }] },
+ ];
+ const idx = captionIndex(body);
+ const capHtml = fillXrefsHtml(captionPrefixHtml(body[0]) + 'Fee schedule', idx);
+ ok(capHtml.startsWith('<span class="t-cap-num" data-cap="c1">Table 1.</span>'),
+ `the caption label is derived into the atom — ${capHtml.slice(0, 60)}`);
+ const refHtml = fillXrefsHtml(`as in ${refAtoms(body[1]).get(6)!} above`, idx);
+ ok(refHtml.includes('>Table 1<'), 'and so is the reference');
+ ok(!refHtml.includes('t-xref-broken'), 'a good reference is not flagged');
+}
+
+H('the document as prose, with references resolved');
+{
+ const doc = { ...emptyDoc(), body: [
+ cap('c1', 'table', 'Fee schedule'),
+ { ...para('p', 'Payment follows .'), refs: [{ to: 'c1', at: 16 }] },
+ ] } as TypeDoc;
+ const text = resolvedText(doc);
+ ok(text.includes('Table 1. Fee schedule'), 'the caption reads with its label');
+ ok(text.includes('Payment follows Table 1.'), `and the sentence reads as the reader sees it — ${text.split('\n')[1]}`);
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+H('the label is the DOCUMENT’s language, not the reader’s');
+{
+ ok(captionWord('table', 'fr') === 'Tableau' && captionWord('figure', 'de') === 'Abbildung',
+ 'the words are looked up by language tag');
+ ok(captionWord('table', 'fr-CA') === 'Tableau', 'a region falls back to the base language');
+ ok(captionWord('figure', 'zh-TW') === '圖' && captionWord('figure', 'zh-CN') === '图',
+ 'and Chinese resolves by script, not by region alone');
+ ok(captionWord('table', 'fi') === 'Table', 'an unknown language reads English, never empty');
+ ok(joinLabel('表', 2, 'ja') === '表2' && joinLabel('Tableau', 2, 'fr') === 'Tableau 2',
+ 'CJK sets the number tight, Latin scripts space it');
+
+ const body = [cap('c1', 'table', 'Barème')];
+ ok(labels(body, 'fr') === 'Tableau 1', 'a French document says Tableau');
+ ok(labels(body, 'en') === 'Table 1', 'and the same bytes in an English one say Table');
+
+ ok(docLang({ lang: 'fr-FR' }) === 'fr-fr' && docLang({}) === 'en',
+ 'the language comes off the document, defaulting to English');
+ const doc = { ...emptyDoc(), lang: 'de', body } as TypeDoc;
+ ok(resolvedText(doc).startsWith('Tabelle 1.'), 'and the whole document follows it');
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`);
+if (failures) process.exit(1);
diff --git a/type/src/about.ts b/type/src/about.ts
new file mode 100644
index 00000000..21b5ea7f
--- /dev/null
+++ b/type/src/about.ts
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The About dialog — what this file is, what version, and the controls that
+// have nowhere else to live.
+//
+// WHY IT EXISTS AT ALL. bento/type had no route to any of this: no version
+// anywhere in the UI, no way to check for an update, no way to change theme
+// except a bar button with no explanation, and no answer to "what IS this
+// file". Both other apps put that behind the wordmark, so a person who learns
+// one app already knows where to look — and a wordmark that is only decoration
+// wastes the one place everyone looks first (spaces/src/editor.ts says the
+// same, and it is right).
+//
+// Modelled on spaces/src/about.ts, which is the smaller and more recent of the
+// two precedents. Sections in the same order, so the three dialogs read as one
+// product.
+
+import { checkForUpdates, applyUpdate, APP_VERSION, type ReleaseInfo } from '../../kernel/src/update.ts';
+import { canWriteInPlace, openedFileName } from '../../kernel/src/save.ts';
+import { setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';
+import type { Store } from './store.ts';
+import { wordCount, docForExport } from './model.ts';
+import { t } from './i18n.ts';
+import { knownAuthor, setAuthorName } from './comments.ts';
+import './comments.css';
+
+export interface AboutHooks {
+ store: Store;
+ /** pages, from the last pagination pass — the dialog does not re-measure */
+ pages: number;
+ onReplaceDoc(json: string): void;
+}
+
+const esc = (s: string) => s.replace(/[&<>"]/g, c =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]!));
+
+export function openAbout({ store, pages, onReplaceDoc }: AboutHooks): void {
+ const back = document.createElement('div');
+ back.className = 't-overlay';
+ const card = document.createElement('div');
+ card.className = 't-dlg t-about';
+ card.setAttribute('role', 'dialog');
+ card.setAttribute('aria-label', t('About this document'));
+ const close = () => back.remove();
+
+ const h = (text: string) => {
+ const n = document.createElement('h2');
+ n.className = 't-dlg-h';
+ n.textContent = text;
+ return n;
+ };
+ const p = (text: string, cls = 't-about-blurb') => {
+ const n = document.createElement('p');
+ n.className = cls;
+ n.textContent = text;
+ return n;
+ };
+ const row = (label: string, node: HTMLElement) => {
+ const r = document.createElement('div');
+ r.className = 't-row';
+ const s = document.createElement('span');
+ s.textContent = label;
+ r.append(s, node);
+ return r;
+ };
+ const button = (label: string, fn: () => void, primary = false) => {
+ const b = document.createElement('button');
+ b.className = 't-btn' + (primary ? ' t-primary' : '');
+ b.textContent = label;
+ b.addEventListener('click', fn);
+ return b;
+ };
+
+ // ---- what this is -------------------------------------------------------
+ const head = document.createElement('div');
+ head.className = 't-about-head';
+ head.innerHTML =
+ '<a class="t-about-logo" href="https://bento.page" target="_blank" rel="noopener" ' +
+ `title="${t('Visit bento.page (opens in a new tab)')}">` +
+ '<svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true">' +
+ '<rect width="32" height="32" rx="7" fill="#16273E"/>' +
+ '<rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/>' +
+ '<rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/>' +
+ '<rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/>' +
+ '</svg><div><b>bento<span style="color:#FF9E8A">/</span>type</b>' +
+ `<span>${esc(t('v{app} · format v{fmt}', { app: APP_VERSION, fmt: String(store.doc.version ?? 1) }))}</span></div></a>`;
+ card.append(head);
+
+ card.append(h(t('This file')));
+ const notes = Object.keys(store.doc.footnotes ?? {}).length;
+ card.append(p(t(
+ '{pages} page(s) · {words} words · {blocks} blocks · {notes} footnote(s). ' +
+ 'The document, the editor and the typesetter are all in this one file.',
+ { pages: pages || 1, words: wordCount(store.doc).toLocaleString(),
+ blocks: store.doc.body.length, notes })));
+
+ const fileName = openedFileName();
+ if (fileName) card.append(row(t('File'), p(fileName, 't-about-val')));
+ if (!canWriteInPlace()) {
+ card.append(p(t(
+ 'This browser cannot write back to the file, so every save makes a new copy. ' +
+ 'Chrome and Edge on a computer can save in place.'), 't-note'));
+ }
+
+ // ---- updates ------------------------------------------------------------
+ card.append(h(t('Updates')));
+ const upStatus = p('', 't-about-val');
+ const upRow = document.createElement('div');
+ upRow.className = 't-row';
+ let found: ReleaseInfo | null = null;
+ const checkBtn = button(t('Check for updates'), async () => {
+ upStatus.textContent = t('Checking…');
+ const r = await checkForUpdates();
+ if (r.status === 'update') {
+ found = r.release;
+ upStatus.textContent = t('Version {v} is available.', { v: r.release.version });
+ applyBtn.hidden = false;
+ } else if (r.status === 'current') {
+ upStatus.textContent = t('Up to date — v{v}.', { v: APP_VERSION });
+ } else {
+ // A failed check is not an error worth alarming anyone with: the file
+ // works offline by design, and that is the common reason it fails.
+ upStatus.textContent = t('Could not check right now.');
+ }
+ });
+ const applyBtn = button(t('Update this file'), async () => {
+ if (found) await applyUpdate(found, store.doc as never);
+ }, true);
+ applyBtn.hidden = true;
+ upRow.append(checkBtn, applyBtn);
+ card.append(upRow, upStatus);
+ card.append(p(t(
+ 'An update is a NEW file, downloaded beside this one — the original is untouched, ' +
+ 'so a bad update is undone by deleting it. Every release is signature-checked ' +
+ 'before it is applied.'), 't-note'));
+
+ // ---- appearance ---------------------------------------------------------
+ card.append(h(t('Appearance')));
+ const themeSel = document.createElement('select');
+ themeSel.className = 't-select';
+ for (const [val, label] of [['auto', t('Follow the system')], ['light', t('Light')], ['dark', t('Dark')]] as const) {
+ const o = document.createElement('option');
+ o.value = val; o.textContent = label;
+ o.selected = themeChoice() === val;
+ themeSel.append(o);
+ }
+ themeSel.addEventListener('change', () => setTheme(themeSel.value as ThemeChoice));
+ card.append(row(t('Theme'), themeSel));
+ card.append(p(t(
+ 'The theme is yours, not the document’s — it is remembered in this browser and ' +
+ 'never saved into the file. The PAGE stays white in both, because paper is white ' +
+ 'and somebody proofing a contract at midnight still has to see what will print.'),
+ 't-note'));
+
+ // ---- you ------------------------------------------------------------
+ //
+ // WHY THIS HAS TO EXIST: comments.ts's authorName() has always had a name to
+ // attribute comments and tracked changes to — it just never gave you a way
+ // to SEE or CORRECT it, only a one-shot prompt() the first time you left a
+ // comment. This is the one place in the app that shows the name and lets it
+ // change; authorName()'s prompt stays as the fallback for someone who never
+ // opened About before commenting or turning on tracking (both read/write the
+ // same 'bento-author' key, so whichever runs first is what the other sees).
+ card.append(h(t('You')));
+ const nameInput = document.createElement('input');
+ nameInput.type = 'text';
+ nameInput.className = 't-input t-about-name-input';
+ nameInput.placeholder = t('Your name');
+ nameInput.value = knownAuthor();
+ nameInput.autocomplete = 'off';
+ // applied on blur/Enter, not on every keystroke: a comment or tracked
+ // change made mid-edit must attribute to the name as it stood at that
+ // moment, not flicker with whatever is half-typed into this field right now
+ const commitName = () => setAuthorName(nameInput.value);
+ nameInput.addEventListener('change', commitName);
+ nameInput.addEventListener('keydown', e => { if (e.key === 'Enter') { commitName(); nameInput.blur(); } });
+ card.append(row(t('Name'), nameInput));
+ card.append(p(t(
+ 'A self-asserted claim, not an identity — this is the name shown beside ' +
+ 'your comments and tracked changes, and anyone can type any name here. ' +
+ 'It is remembered in this browser, applies immediately, and is never ' +
+ 'itself saved into the file (only the comments and changes it signs are).'),
+ 't-note'));
+
+ // ---- the document, for tools --------------------------------------------
+ card.append(h(t('Document')));
+ card.append(row(t('Document id'), p(String(store.doc.docId ?? ''), 't-about-val t-mono')));
+ const jsonRow = document.createElement('div');
+ jsonRow.className = 't-row';
+ jsonRow.append(
+ button(t('Copy document JSON'), async () => {
+ // docForExport, never store.doc — see model.ts. This text can be pasted
+ // anywhere, and the raw document carries the room's private keys.
+ try { await navigator.clipboard.writeText(JSON.stringify(docForExport(store.doc), null, 2)); }
+ catch { /* clipboard blocked — the agent surface below still works */ }
+ }),
+ button(t('Replace from JSON…'), () => {
+ const json = prompt(t('Paste a bento/type document JSON. This replaces the document and can be undone with ⌘Z.'));
+ if (json) onReplaceDoc(json);
+ }),
+ );
+ card.append(jsonRow);
+ card.append(p(t(
+ 'The document is the interchange unit: hand this JSON to an AI, get one back, ' +
+ 'and paste it in. `window.bento` exposes the same thing to scripts.'), 't-note'));
+
+ // ---- credits ------------------------------------------------------------
+ card.append(h(t('Credits')));
+ card.append(p(t(
+ 'bento/type is MIT-licensed. Line breaking uses the Knuth–Plass algorithm ' +
+ 'via tex-linebreak; hyphenation patterns are Liang’s. Everything runs in ' +
+ 'this file — nothing is fetched, and nothing is sent anywhere.'), 't-note'));
+
+ const foot = document.createElement('div');
+ foot.className = 't-dlg-foot';
+ foot.append(button(t('Close'), close, true));
+ card.append(foot);
+
+ back.append(card);
+ back.addEventListener('click', e => { if (e.target === back) close(); });
+ document.addEventListener('keydown', function esc2(e) {
+ if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc2); }
+ });
+ document.body.append(back);
+}
diff --git a/type/src/blockgrip.ts b/type/src/blockgrip.ts
new file mode 100644
index 00000000..2950adf5
--- /dev/null
+++ b/type/src/blockgrip.ts
@@ -0,0 +1,385 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE BLOCK GRIP — the handle in the margin that moves a block.
+//
+// Adapted from bento/spaces, which puts a hover gutter beside every block
+// (`.sp-gutter`: a + and a drag grip). Three things had to change on the way,
+// and each is a fact about this app rather than a preference:
+//
+// 1. IT IS AN OVERLAY, NOT PART OF THE BLOCK. spaces nests its gutter inside a
+// `.sp-b` wrapper. Here the block element IS the editable node, and the
+// editor reads text back out of it (render.ts readBlock, called on every
+// keystroke). A button inside it would be read as document text — the
+// grip's own glyph would end up in the paragraph. So the grips live in a
+// positioned layer, exactly as comment highlights already do.
+//
+// 2. ONE PER UNIT, NOT PER BLOCK. A list item and a table cell are blocks
+// here. A grip on every `td` says a cell can be dragged, which it cannot.
+// move.ts owns that grouping.
+//
+// 3. NO "+" BUTTON. spaces has one; this app has a single Insert menu driven
+// by the caret, and a second inserter in the margin would put one action in
+// two places — the thing scripts/test-type-chrome.ts exists to prevent.
+//
+// The layer is marked `data-bento-transient` so kernel save.ts strips it from
+// the clone. Without that it would be serialised into the file and re-appear,
+// doubled, on every save.
+
+import { t } from './i18n.ts';
+import { registerKey, registerPaginated, tools, type FeatureContext } from './features.ts';
+import { moveUnit, moveUnitTo, units, canMove, boundaries } from './move.ts';
+import type { Block } from './model.ts';
+
+const PLUS_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none"'
+ + ' stroke="currentColor" stroke-width="2" stroke-linecap="round">'
+ + '<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>';
+
+const GRIP_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor">'
+ + '<circle cx="9" cy="6" r="1.6"/><circle cx="15" cy="6" r="1.6"/>'
+ + '<circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/>'
+ + '<circle cx="9" cy="18" r="1.6"/><circle cx="15" cy="18" r="1.6"/></svg>';
+
+/** Move the unit containing `id`, and keep the caret with it. */
+export function move(ctx: FeatureContext, id: string, dir: -1 | 1): boolean {
+ const next = moveUnit(ctx.store.doc.body, id, dir);
+ if (!next) return false;
+ const caret = ctx.editor.caret();
+ ctx.store.commit(d => { d.body = next; });
+ ctx.editor.render();
+ // The caret follows the text, not the position — a move that dumped the
+ // caret wherever the old offset now points would put it in a different
+ // paragraph, which is how you keep typing into the wrong block.
+ if (caret) ctx.editor.setCaret(caret);
+ ctx.refresh();
+ return true;
+}
+
+/** Drop the unit before `target`, which the engine snaps to a unit boundary. */
+function moveTo(ctx: FeatureContext, id: string, target: number): boolean {
+ const next = moveUnitTo(ctx.store.doc.body, id, target);
+ if (!next) return false;
+ ctx.store.commit(d => { d.body = next; });
+ ctx.editor.render();
+ ctx.refresh();
+ return true;
+}
+
+/** The block the caret is in — what the keyboard shortcut acts on. */
+const caretBlock = (ctx: FeatureContext): Block | undefined => {
+ const c = ctx.editor.caret();
+ return c ? ctx.store.block(c.id) : undefined;
+};
+
+/**
+ * "Move paragraph up/down" — Word's shortcut, and Word's PLATFORM SPLIT.
+ *
+ * Windows and Linux: Alt+Shift+Arrow. macOS: Ctrl+Shift+Arrow.
+ *
+ * Not a nicety. On macOS Option+Shift+Arrow is the system gesture for
+ * extending a selection to the previous or next paragraph, and this handler
+ * calls preventDefault — so a single binding of Alt+Shift would silently eat a
+ * standard text-selection gesture on the platform this is being written on.
+ * Word made exactly this split for exactly this reason.
+ *
+ * The grip is mouse-only, so a keyboard path is not optional: a hover-only
+ * affordance with no shortcut is unreachable for anyone who does not use a
+ * mouse.
+ */
+export const isMac = (): boolean =>
+ /mac/i.test((navigator as { userAgentData?: { platform?: string } }).userAgentData?.platform
+ ?? navigator.platform ?? '');
+
+for (const [key, dir] of [['arrowup', -1], ['arrowdown', 1]] as const) {
+ registerKey({
+ key,
+ ...(isMac() ? { ctrl: true } : { alt: true }),
+ shift: true,
+ run(ctx) {
+ const b = caretBlock(ctx);
+ if (!b) return;
+ if (!move(ctx, b.id, dir)) ctx.toast(dir < 0 ? t('Already at the top.') : t('Already at the end.'));
+ },
+ });
+}
+
+// ───────────────────────────────────────────────────────────── the layer
+
+let openMenu: HTMLElement | null = null;
+const closeMenu = () => { openMenu?.remove(); openMenu = null; };
+document.addEventListener('click', closeMenu);
+
+/**
+ * The margin's + — insert a block after this one.
+ *
+ * It renders `tools('insert')`, which is the SAME registry the toolbar's
+ * Insert menu renders. Not a second menu with its own list: one home, two
+ * triggers, so the tenth insert appears in both without anybody remembering
+ * to add it twice.
+ *
+ * The insert tools all act at the CARET, so this puts the caret at the end of
+ * the block it belongs to first. That means every one of them works here
+ * unmodified — including any added later, which is the point of going through
+ * the registry rather than calling the four we happen to know about.
+ */
+function plusMenu(ctx: FeatureContext, blockId: string, at: HTMLElement): void {
+ closeMenu();
+ const menu = document.createElement('div');
+ menu.className = 't-menu t-grip-menu';
+ for (const spec of tools('insert')) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ const label = typeof spec.label === 'function' ? spec.label()
+ : (spec.label ?? (typeof spec.title === 'function' ? spec.title() : spec.title));
+ b.innerHTML = spec.icon + `<span>${label}</span>`;
+ b.addEventListener('mousedown', e => e.preventDefault());
+ b.addEventListener('click', e => {
+ e.stopPropagation();
+ closeMenu();
+ const blk = ctx.store.block(blockId);
+ if (blk) ctx.editor.setCaret({ id: blockId, at: blk.text.length });
+ spec.run(ctx);
+ });
+ menu.appendChild(b);
+ }
+ const r = at.getBoundingClientRect();
+ menu.style.top = `${r.bottom + window.scrollY + 4}px`;
+ menu.style.insetInlineStart = `${r.left + window.scrollX}px`;
+ document.body.appendChild(menu);
+ openMenu = menu;
+}
+
+function gripMenu(ctx: FeatureContext, id: string, at: HTMLElement): void {
+ closeMenu();
+ const menu = document.createElement('div');
+ menu.className = 't-menu t-grip-menu';
+ const items: Array<[string, () => void, boolean]> = [
+ [t('Move up'), () => move(ctx, id, -1), canMove(ctx.store.doc.body, id, -1)],
+ [t('Move down'), () => move(ctx, id, 1), canMove(ctx.store.doc.body, id, 1)],
+ ];
+ for (const [label, run, enabled] of items) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = label;
+ b.disabled = !enabled;
+ b.addEventListener('click', e => { e.stopPropagation(); closeMenu(); run(); });
+ menu.appendChild(b);
+ }
+ const r = at.getBoundingClientRect();
+ menu.style.top = `${r.bottom + window.scrollY + 4}px`;
+ menu.style.left = `${r.left + window.scrollX}px`;
+ document.body.appendChild(menu);
+ openMenu = menu;
+}
+
+/**
+ * ONE grip at a time — the block under the pointer.
+ *
+ * Revealing every grip on page hover put a column of handles down the margin
+ * of a document at rest, which is noise: nine of them beside a nine-paragraph
+ * contract, only ever one of which is wanted. bento/spaces reveals per BLOCK
+ * (.sp-b:hover > .sp-gutter) and that is the right behaviour; it is only
+ * expressed differently here because the grips live in an overlay rather than
+ * inside the block, so CSS cannot do it and this listener must.
+ */
+function trackPointer(paper: HTMLElement): void {
+ if ((paper as HTMLElement & { _gripTracked?: boolean })._gripTracked) return;
+ (paper as HTMLElement & { _gripTracked?: boolean })._gripTracked = true;
+
+ const wrap = paper.parentElement;
+ wrap?.addEventListener('pointermove', e => {
+ if (dragging) return; // a drag owns the pointer
+ const node = document.elementFromPoint(e.clientX, e.clientY) as HTMLElement | null;
+ const block = node?.closest('[data-id]') as HTMLElement | null;
+ // While the pointer is IN the margin the nearest grip stays lit, or moving
+ // towards a grip to press it would put it out.
+ const overGrip = node?.closest('.t-grip') as HTMLElement | null;
+ const want = overGrip?.dataset.for ?? blockUnitId(block?.dataset.id);
+ for (const g of wrap.querySelectorAll<HTMLElement>('.t-grip')) {
+ g.classList.toggle('on', !!want && g.dataset.for === want);
+ }
+ });
+ wrap?.addEventListener('pointerleave', () => {
+ if (dragging) return;
+ for (const g of wrap.querySelectorAll<HTMLElement>('.t-grip')) g.classList.remove('on');
+ });
+}
+
+/** The id the grip for this block carries — a unit's FIRST block. */
+let unitOf: (id: string | undefined) => string | undefined = () => undefined;
+const blockUnitId = (id: string | undefined) => unitOf(id);
+
+// ────────────────────────────────────────────────────────────────── drag
+
+let dragging: { id: string; from: number } | null = null;
+
+/** Where a drop at this y would go, and the y to draw the line at. */
+function dropAt(ctx: FeatureContext, paper: HTMLElement, clientY: number):
+ { target: number; y: number } | null {
+ const body = ctx.store.doc.body;
+ const top0 = paper.getBoundingClientRect().top;
+ const points: Array<{ target: number; y: number }> = [];
+ for (const b of boundaries(body)) {
+ if (b < body.length) {
+ const el = paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(body[b].id)}"]`);
+ if (el) points.push({ target: b, y: el.getBoundingClientRect().top });
+ } else {
+ const last = body[body.length - 1];
+ const el = paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(last.id)}"]`);
+ if (el) points.push({ target: b, y: el.getBoundingClientRect().bottom });
+ }
+ }
+ if (!points.length) return null;
+ const best = points.reduce((a, b) => Math.abs(b.y - clientY) < Math.abs(a.y - clientY) ? b : a);
+ return { target: best.target, y: best.y - top0 };
+}
+
+function startDrag(e: PointerEvent, ctx: FeatureContext, grip: HTMLElement,
+ id: string, paper: HTMLElement): void {
+ e.preventDefault();
+ const startY = e.clientY;
+ const layer = grip.parentElement;
+ let line: HTMLElement | null = null;
+ let moved = false;
+
+ const onMove = (ev: PointerEvent) => {
+ // A few pixels of slop before it is a drag, so a click that wobbles still
+ // opens the menu rather than starting a move nobody asked for.
+ if (!moved && Math.abs(ev.clientY - startY) < 4) return;
+ if (!moved) {
+ moved = true;
+ dragging = { id, from: 0 };
+ grip.classList.add('t-grip-dragging');
+ document.body.classList.add('t-dragging');
+ line = document.createElement('div');
+ line.className = 't-droptip';
+ layer?.appendChild(line);
+ }
+ const at = dropAt(ctx, paper, ev.clientY);
+ if (at && line) line.style.top = `${at.y}px`;
+ };
+
+ const onUp = (ev: PointerEvent) => {
+ try { grip.releasePointerCapture?.(ev.pointerId); } catch { /* never captured */ }
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ grip.classList.remove('t-grip-dragging');
+ document.body.classList.remove('t-dragging');
+ line?.remove();
+ const wasDrag = moved;
+ dragging = null;
+ if (!wasDrag) {
+ // A click, not a drag — but the `click` event that follows this
+ // pointerup bubbles to the document listener that closes menus, so
+ // opening synchronously here opened and shut it in one gesture. The
+ // timeout puts the open AFTER that click has been dispatched.
+ setTimeout(() => gripMenu(ctx, id, grip), 0);
+ return;
+ }
+ const at = dropAt(ctx, paper, ev.clientY);
+ if (at) moveTo(ctx, id, at.target);
+ };
+
+ // LISTENERS FIRST, capture second and best-effort. setPointerCapture throws
+ // NotFoundError when the pointer is not active — always for a synthetic
+ // event, and possible for a real one that was released or captured
+ // elsewhere. Calling it first meant one throw took the whole gesture with
+ // it: no drag AND no menu, because the pointerup handler was never attached
+ // either. The drag does not need capture — every listener is on `window` —
+ // so a failure here should cost nothing.
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ try { grip.setPointerCapture?.(e.pointerId); } catch { /* not an active pointer */ }
+}
+
+/**
+ * Paint a grip beside every unit.
+ *
+ * Runs from the PAGINATED hook: positions are only knowable once the paginator
+ * has laid the column out, and this is the same signal footnote sidenotes and
+ * page numbers already repaint on.
+ */
+function paintGrips(ctx: FeatureContext, _metrics: unknown, paper: HTMLElement): void {
+ // Into the DECORATIONS layer, which already holds the page rules, the page
+ // numbers and the footnote sidenotes — everything that is drawn beside the
+ // sheet rather than printed on it. A grip in the margin is one of those, and
+ // putting it anywhere else meant inventing a second layer with the same job.
+ // It is also what lets the grip use the paper's own ink: the palette gate
+ // classifies `.t-deco` as document, and a handle floating over a white page
+ // must not take chrome colours, which invert in dark mode while the paper
+ // stays white.
+ const deco = paper.parentElement?.querySelector<HTMLElement>('.t-deco');
+ if (!deco) return;
+ let layer = deco.querySelector<HTMLElement>('.t-grip-layer');
+ if (!layer) {
+ layer = document.createElement('div');
+ layer.className = 't-grip-layer';
+ // stripped from the save clone by kernel save.ts — see the note at the top
+ layer.setAttribute('data-bento-transient', '');
+ deco.appendChild(layer);
+ }
+ layer.replaceChildren();
+
+ const body = ctx.store.doc.body;
+ if (body.length < 2) return; // nothing to reorder
+
+ // Which unit any block belongs to — the pointer lands on a `td` or an `li`
+ // and the grip it should light is the one on that unit's first block.
+ const owner = new Map<string, string>();
+ for (const u of units(body)) {
+ for (let k = u.start; k < u.end; k++) owner.set(body[k].id, body[u.start].id);
+ }
+ unitOf = (id) => (id ? owner.get(id) : undefined);
+ trackPointer(paper);
+
+ const paperRect = paper.getBoundingClientRect();
+ // Inside the page's own left margin. The 250px gutter this layout allocates
+ // is on the RIGHT and already holds footnote sidenotes and comment cards, so
+ // mirroring it would mean widening the wrap and shifting the page sideways.
+ // marginX is empty by design and easily wide enough.
+ const x = Math.max(4, ctx.store.doc.page.marginX - 34);
+ const frag = document.createDocumentFragment();
+
+ for (const u of units(body)) {
+ const first = body[u.start];
+ const node = paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(first.id)}"]`);
+ if (!node) continue;
+ const r = node.getBoundingClientRect();
+ if (!r.height) continue;
+
+ const g = document.createElement('button');
+ g.type = 'button';
+ g.className = 't-grip';
+ g.innerHTML = GRIP_ICON;
+ g.title = t('Drag to move, click for options') + ' · '
+ + (isMac() ? t('⌃⇧↑ / ⌃⇧↓') : t('Alt+Shift+↑ / ↓'));
+ g.setAttribute('aria-label', t('Move this block'));
+ g.dataset.for = first.id;
+ g.dataset.unit = String(u.start);
+ g.style.top = `${r.top - paperRect.top + 1}px`;
+ g.style.insetInlineStart = `${x}px`;
+ // mousedown, not click: the caret must survive pressing it, exactly as the
+ // toolbar buttons do
+ g.addEventListener('mousedown', e => e.preventDefault());
+ g.addEventListener('pointerdown', e => startDrag(e, ctx, g, first.id, paper));
+
+ const plus = document.createElement('button');
+ plus.type = 'button';
+ plus.className = 't-grip t-plus';
+ plus.innerHTML = PLUS_ICON;
+ plus.title = t('Insert below');
+ plus.setAttribute('aria-label', t('Insert a block below this one'));
+ plus.dataset.for = first.id;
+ plus.style.top = `${r.top - paperRect.top + 1}px`;
+ plus.style.insetInlineStart = `${x - 24}px`;
+ plus.addEventListener('mousedown', e => e.preventDefault());
+ plus.addEventListener('click', e => { e.stopPropagation(); plusMenu(ctx, first.id, plus); });
+
+ frag.append(plus, g);
+ }
+ layer.appendChild(frag);
+}
+
+registerPaginated(paintGrips as never);
diff --git a/type/src/cite.ts b/type/src/cite.ts
new file mode 100644
index 00000000..e5473187
--- /dev/null
+++ b/type/src/cite.ts
@@ -0,0 +1,628 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Citations and a bibliography — the feature that decides whether a thesis or
+// a brief can be written in this app at all.
+//
+// ══════════════════════════════════════════════════ THE MODEL DECISION
+//
+// A citation is an ATOM: a position in a block's text that occupies no
+// characters. It is NOT a mark over a run of text.
+//
+// The choice looks close, because "(Knuth, 1984)" is visibly a piece of the
+// sentence and marks are how this model decorates pieces of sentences. It is
+// not close, and the three things this app is actually built on each rule the
+// mark out on their own:
+//
+// 1. THE REDLINE DIFFS PLAIN TEXT, WORD BY WORD. A mark needs characters
+// underneath it, so the mark version has to store the rendered citation —
+// "(Knuth, 1984)" or "[7]" — in `block.text`. Then inserting one citation
+// in paragraph two rewrites the visible text of every later citation, and
+// the redline reports eleven changed words in eleven paragraphs nobody
+// touched. Worse, switching the document from IEEE to APA becomes a
+// global text edit: every citation is a deletion and an insertion, and
+// the review that was supposed to show what counsel changed shows the
+// whole document. As an atom the citation contributes ZERO characters, so
+// re-numbering and re-styling produce an empty diff. That is the whole
+// argument on its own.
+//
+// 2. SIGNATURES CANONICALISE THE MODEL. A signature covers the canonical
+// content, and a stored rendering means the bytes under the signature
+// depend on the style setting and on the entry's author field. Fix a typo
+// in an author's initial and every signature over the document breaks,
+// for a change that is not in the prose. As an atom, the canonical form
+// holds `{ at, keys }` — the author's actual intent, "cite this work
+// here" — and it does not move when the rendering does.
+//
+// 3. THE CARET IS (blockId, offset). An atom sits BETWEEN two offsets and
+// can never be entered: arrowing over it is one step, backspace deletes
+// it whole, and there is no position "three characters into the
+// citation". A mark over stored text puts the caret inside a string the
+// author cannot meaningfully edit — type in the middle of "(Knuth," and
+// the model now holds text that no style would ever produce, with a mark
+// claiming it is a citation. The footnote marker already solved exactly
+// this, and `spliceText` in model.ts already carries the offset
+// arithmetic that keeps such an anchor pointing at the right word.
+//
+// So: `Block.cites?: CiteRef[]`, an offset list beside `Block.notes`, with the
+// SOURCES in a doc-level map — `doc.bibliography`, keyed by cite key, exactly
+// as `doc.footnotes` is keyed by note id and for exactly the same reason. A
+// source outlives the sentence citing it, is cited from three paragraphs at
+// once, and must survive the paragraph being rewritten.
+//
+// EVERYTHING VISIBLE IS DERIVED. The number, the "(Knuth, 1984)", the order of
+// the reference list, the disambiguating "1984b" — computed by
+// `cite/format.ts` at render time, never stored. A number in the document JSON
+// is a bug, not a cache.
+//
+// ══════════════════════════════════════════════════ NEEDS FROM THE CORE
+//
+// This module is complete and node-testable as it stands: the BibTeX reader,
+// the two styles and the resolution are pure functions, and the panel manages
+// entries today. What it cannot do without the core is put an atom in a
+// paragraph and have it SURVIVE A SAVE, because parseDoc rebuilds each block
+// from named fields and drops what it does not know. Five additions, all
+// additive, none of which changes the meaning of an existing file:
+//
+// ── 1. type/src/model.ts — the reference type, beside NoteRef (~line 60)
+//
+// /** A citation anchored INTO a block's text, by character offset. Like a
+// * footnote marker it is an ATOM: a position, no characters. `keys` is a
+// * list because "(Knuth, 1984; Lamport, 1994)" is ONE citation. */
+// export interface CiteRef { at: number; keys: string[]; locator?: string;
+// suppressAuthor?: boolean }
+//
+// ── 2. type/src/model.ts — the field on Block, beside `notes`
+//
+// /** citation references, by offset into `text` */
+// cites?: CiteRef[];
+//
+// WHY: without it the field exists at runtime and vanishes on reload.
+//
+// ── 3. type/src/model.ts — parseDoc, right after the `notes` block (~line 226)
+//
+// const cites = Array.isArray(b.cites)
+// ? (b.cites as CiteRef[])
+// .filter(c => isObj(c) && typeof c.at === 'number' && Array.isArray(c.keys))
+// .map(c => ({ ...c, at: Math.max(0, Math.min(c.at, text.length)),
+// keys: c.keys.filter(k => typeof k === 'string') }))
+// .filter(c => c.keys.length)
+// .sort((x, y) => x.at - y.at)
+// : undefined;
+//
+// and beside `if (notes?.length) out.notes = notes;`
+//
+// if (cites?.length) out.cites = cites;
+//
+// WHY: repairs must be deterministic (two readers must agree on every id),
+// and an out-of-range offset would put a citation past the end of a
+// paragraph. Note there is NO dangling-key sweep here, deliberately: unlike
+// a footnote reference with no note, a citation to a missing entry renders
+// VISIBLY as `[?key]` and is a defect the author must see and fix. Dropping
+// it would silently delete the evidence that a source went missing.
+//
+// ── 4. type/src/model.ts — spliceText, beside the `notes` block (~line 311)
+//
+// if ((block as Block & { cites?: CiteRef[] }).cites?.length) { …same rule… }
+//
+// i.e. the identical filter+shift the notes anchors get:
+//
+// if (block.cites?.length) {
+// const c = block.cites
+// .filter(x => !(x.at > at && x.at < end))
+// .map(x => x.at >= end ? { ...x, at: x.at + delta } : x);
+// if (c.length) out.cites = c; else delete out.cites;
+// }
+//
+// WHY: this is the one function that keeps offsets pointing at the same
+// words through an edit, and its own comment says notes and marks must move
+// TOGETHER or a marker lands in the middle of a word. A third offset list
+// that does not move with them is that bug again.
+//
+// ── 5. type/src/render.ts — the atom, mirroring `noteMarker`/`isNoteAtom`
+//
+// import { citeInject, isCiteAtom, readCiteAtoms } from './cite.ts';
+//
+// in `blockHtml`, merge the citation markers into the same inject map the
+// note markers use (a note and a citation CAN share an offset, so it must
+// concatenate rather than overwrite):
+//
+// const inject = mergeInject(noteInject(b), citeInject(b));
+//
+// in `readBlock`, pass a combined atom test and split the atoms back:
+//
+// const { text, marks, atoms } = fromDom(el, el => isNoteAtom(el) || isCiteAtom(el));
+// … const cites = readCiteAtoms(atoms);
+// if (cites.length) out.cites = cites; else delete out.cites;
+//
+// and in `renderBody`, after `numberNotes`:
+//
+// paintCitations(host, doc);
+//
+// WHY: `numberNotes` is already the house pattern for derived numbering —
+// walk the rendered output in document order and put the derived value in
+// the marker. `paintCitations` is the same function for citations, and it
+// lives here rather than in render.ts because it needs the styles.
+//
+// UNTIL THEN: the panel, the import, the styles and the reference list all
+// work; inserting a citation into a paragraph works for the session and is
+// lost on reload, because parseDoc drops the field. That is the whole gap.
+//
+// ══════════════════════════════════════════════════ FORMAT ADDITIVITY
+//
+// `doc.bibliography` and `doc.citeStyle` are plain extra keys. parseDoc
+// already spreads unknown fields through (`...(json as object)`), and save
+// re-serialises the whole object, so a file written here opens in an older
+// build, edits, and saves with its bibliography intact — the older build never
+// looks at the key and never drops it. An older FILE opened here has neither
+// key: `readBibliography(undefined)` is an empty map and `readStyle(undefined)`
+// is `numeric`. Nothing is required, nothing is migrated. (PLATFORM §3.)
+
+import { registerKey, registerMenuItem, registerPanel, registerTool, type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+import type { Block, TypeDoc } from './model.ts';
+import { parseBibtex } from './cite/bibtex.ts';
+import {
+ bibliography, citationText, missingText, referenceText, resolve,
+ type BibLine, type CitedBlock, type Resolution,
+} from './cite/format.ts';
+import {
+ cleanField, readBibliography, readCiteRef, readStyle, validKey,
+ type BibEntry, type Bibliography, type CiteRef, type CiteStyle,
+} from './cite/types.ts';
+
+export { parseBibtex, decodeTex } from './cite/bibtex.ts';
+export * from './cite/format.ts';
+export * from './cite/types.ts';
+
+/** A block carrying the field the core patch adds. Cast, not augmented, so
+ * applying that patch removes these casts instead of colliding with them. */
+type CiteBlock = Block & { cites?: CiteRef[] };
+
+// ───────────────────────────────────────────────────── reading the document
+
+export const docBib = (doc: TypeDoc): Bibliography => readBibliography(doc.bibliography);
+export const docStyle = (doc: TypeDoc): CiteStyle => readStyle(doc.citeStyle);
+
+/** Blocks as the resolver wants them: id plus (validated) citation refs. */
+const citedBody = (doc: TypeDoc): CitedBlock[] =>
+ doc.body.map(b => {
+ const raw = (b as CiteBlock).cites;
+ if (!Array.isArray(raw)) return { id: b.id };
+ const cites = raw.map(r => readCiteRef(r, b.text.length)).filter((r): r is CiteRef => !!r);
+ return cites.length ? { id: b.id, cites } : { id: b.id };
+ });
+
+/** The whole derived answer for one document. Cheap; recomputed, never cached. */
+export const resolveDoc = (doc: TypeDoc): Resolution =>
+ resolve(citedBody(doc), docBib(doc), docStyle(doc));
+
+/** Which keys are cited, and how often. Drives the panel's "uncited" hint. */
+export function citeCounts(doc: TypeDoc): Map<string, number> {
+ const n = new Map<string, number>();
+ for (const b of citedBody(doc)) for (const c of b.cites ?? []) {
+ for (const k of c.keys) n.set(k, (n.get(k) ?? 0) + 1);
+ }
+ return n;
+}
+
+// ───────────────────────────────────────────────────────────────── the atom
+
+export const CITE_CLASS = 't-cite';
+
+/** Does this element stand for a citation? The core's `fromDom` atom test. */
+export const isCiteAtom = (el: Element): boolean =>
+ el.tagName === 'SPAN' && el.classList.contains(CITE_CLASS);
+
+const escAttr = (s: string) => s.replace(/[&<>"']/g, c =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]!));
+
+/**
+ * The marker's HTML.
+ *
+ * It carries NO rendered text — `paintCitations` fills it in from the model
+ * after the block is in the DOM, which is what makes the rendering derived
+ * rather than baked into the markup the editor reads back. `contenteditable`
+ * is off so the browser treats it as one indivisible thing, exactly as the
+ * footnote marker does.
+ *
+ * Every attribute value is escaped, and keys are validated on the way in and
+ * on the way out — this string is built from a .bib somebody pasted.
+ */
+export function citeMarker(ref: CiteRef): string {
+ const keys = ref.keys.filter(validKey);
+ if (!keys.length) return '';
+ const loc = ref.locator ? ` data-loc="${escAttr(ref.locator)}"` : '';
+ const sup = ref.suppressAuthor ? ' data-sup="1"' : '';
+ return `<span class="${CITE_CLASS}" data-cite="${escAttr(keys.join(' '))}"${loc}${sup}` +
+ ` contenteditable="false">…</span>`;
+}
+
+/** Offset → marker, for the renderer's `inject` map. */
+export function citeInject(b: Block): Map<number, string> {
+ const out = new Map<number, string>();
+ for (const ref of (b as CiteBlock).cites ?? []) {
+ const html = citeMarker(ref);
+ if (html) out.set(ref.at, (out.get(ref.at) ?? '') + html);
+ }
+ return out;
+}
+
+/**
+ * Merge two inject maps.
+ *
+ * `toHtml` takes ONE marker string per offset, and a footnote and a citation
+ * can legitimately land on the same character — "…as held in Smith.[3](Knuth,
+ * 1984)". A plain `new Map([...a, ...b])` silently keeps only the second, so
+ * the footnote would disappear from the rendering and then from the model the
+ * next time the block was read back.
+ */
+export function mergeInject(...maps: Array<Map<number, string> | undefined>): Map<number, string> {
+ const out = new Map<number, string>();
+ for (const m of maps) for (const [at, html] of m ?? []) out.set(at, (out.get(at) ?? '') + html);
+ return out;
+}
+
+/** Read citation atoms back out of a rendered block (the `readBlock` half). */
+export function readCiteAtoms(atoms: ReadonlyArray<{ at: number; el: Element }>): CiteRef[] {
+ const out: CiteRef[] = [];
+ for (const a of atoms) {
+ if (!isCiteAtom(a.el)) continue;
+ const keys = (a.el.getAttribute('data-cite') ?? '').split(' ').filter(validKey);
+ if (!keys.length) continue;
+ const ref: CiteRef = { at: a.at, keys };
+ const loc = cleanField(a.el.getAttribute('data-loc') ?? '');
+ if (loc) ref.locator = loc;
+ if (a.el.getAttribute('data-sup') === '1') ref.suppressAuthor = true;
+ out.push(ref);
+ }
+ return out.sort((x, y) => x.at - y.at);
+}
+
+/**
+ * Put the derived citation text into every marker under `host`.
+ *
+ * The same job `numberNotes` does, and the same rule: walk the rendered output
+ * and write what the model says it should say. Nothing is read back from here,
+ * so a repaint can never change the document.
+ *
+ * `textContent`, never innerHTML — the text is built from an author field that
+ * came out of a pasted .bib, and this is the seam where it would otherwise
+ * become markup.
+ */
+export function paintCitations(host: ParentNode, doc: TypeDoc): Resolution {
+ const res = resolveDoc(doc);
+ const bib = docBib(doc);
+ for (const el of host.querySelectorAll<HTMLElement>(`span.${CITE_CLASS}`)) {
+ const keys = (el.dataset.cite ?? '').split(' ').filter(validKey);
+ if (!keys.length) { el.textContent = missingText('?'); continue; }
+ const ref: CiteRef = { at: 0, keys };
+ if (el.dataset.loc) ref.locator = el.dataset.loc;
+ if (el.dataset.sup === '1') ref.suppressAuthor = true;
+ el.textContent = citationText(ref, res, bib);
+ // A missing entry has to be VISIBLE, not just present in a panel nobody
+ // opened. The class tints it; the text already names the key.
+ el.classList.toggle('miss', keys.some(k => !bib[k]));
+ el.title = keys.map(k => bib[k] ? referenceText(bib[k], res.style, res.suffix[k] ?? '')
+ : `${k} — no entry in this document`).join('\n');
+ }
+ return res;
+}
+
+// ─────────────────────────────────────────────────────────────── mutations
+
+/** Merge parsed entries into the document. Returns what happened, for a toast. */
+export function importBibtex(ctx: FeatureContext, src: string): { added: number; replaced: number; skipped: string[] } {
+ const { entries, skipped } = parseBibtex(src);
+ let added = 0, replaced = 0;
+ if (entries.length) {
+ ctx.store.commit(doc => {
+ const bib = docBib(doc);
+ for (const { key, entry } of entries) {
+ if (bib[key]) replaced++; else added++;
+ bib[key] = entry;
+ }
+ doc.bibliography = bib;
+ });
+ }
+ return { added, replaced, skipped };
+}
+
+export function setCiteStyle(ctx: FeatureContext, style: CiteStyle): void {
+ ctx.store.commit(doc => { doc.citeStyle = style; });
+ ctx.refresh();
+}
+
+export function removeEntry(ctx: FeatureContext, key: string): void {
+ ctx.store.commit(doc => {
+ const bib = docBib(doc);
+ delete bib[key];
+ doc.bibliography = bib;
+ });
+ ctx.refresh();
+}
+
+/**
+ * Insert a citation at the caret.
+ *
+ * Scoped to the block, because that is all it touches — the doc-level
+ * bibliography is untouched here, which is exactly why a citation and its
+ * source have separate lifetimes.
+ */
+export function insertCitation(ctx: FeatureContext, keys: string[], locator?: string): boolean {
+ const c = ctx.editor.caret();
+ if (!c) { ctx.toast(t('Put the caret where the citation goes first')); return false; }
+ const clean = keys.filter(validKey);
+ if (!clean.length) return false;
+ ctx.store.commit(doc => {
+ const b = doc.body.find(x => x.id === c.id) as CiteBlock | undefined;
+ if (!b) return;
+ const ref: CiteRef = { at: Math.min(c.at, b.text.length), keys: clean };
+ const loc = cleanField(locator ?? '');
+ if (loc) ref.locator = loc;
+ b.cites = [...(b.cites ?? []), ref].sort((x, y) => x.at - y.at);
+ }, { scope: { block: c.id } });
+ ctx.refresh();
+ return true;
+}
+
+// ─────────────────────────────────────────────────────────────── the chrome
+
+const ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" ' +
+ 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
+ '<path d="M4 5h11"/><path d="M4 10h11"/><path d="M4 15h7"/>' +
+ '<path d="M17.5 14.5 19 19l-1.5-1-1.5 1z"/><path d="M17.5 14.5V9"/></svg>';
+
+const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls = '', text = ''): HTMLElementTagNameMap[K] => {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (text) n.textContent = text;
+ return n;
+};
+
+const btn = (label: string, onClick: () => void, cls = 't-cite-mini'): HTMLButtonElement => {
+ const b = el('button', cls, label);
+ b.type = 'button';
+ b.addEventListener('click', onClick);
+ return b;
+};
+
+/** A modal, built the way about.ts builds one so the two read as one app. */
+function dialog(title: string, body: HTMLElement, footer: HTMLElement[]): () => void {
+ const back = el('div', 't-overlay');
+ const card = el('div', 't-dlg');
+ card.setAttribute('role', 'dialog');
+ card.setAttribute('aria-label', title);
+ const h = el('h2', 't-dlg-h', title);
+ const foot = el('div', 't-dlg-foot');
+ foot.append(...footer);
+ card.append(h, body, foot);
+ back.append(card);
+ const close = () => { back.remove(); document.removeEventListener('keydown', onKey); };
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') close(); };
+ back.addEventListener('click', e => { if (e.target === back) close(); });
+ document.addEventListener('keydown', onKey);
+ document.body.append(back);
+ return close;
+}
+
+/** Paste-BibTeX. The import reports what it skipped — silence would be a lie. */
+function openImport(ctx: FeatureContext, done: () => void): void {
+ const body = el('div');
+ body.append(el('p', 't-about-blurb', t(
+ 'Paste BibTeX below. @article, @book, @inproceedings, @techreport and @misc ' +
+ 'are modelled; any other type is imported as @misc so it still cites.')));
+ const ta = el('textarea', 't-cite-paste');
+ ta.rows = 12;
+ ta.spellcheck = false;
+ ta.placeholder = '@book{knuth1984,\n author = {Knuth, Donald E.},\n title = {The {TeX}book},\n year = {1984}\n}';
+ body.append(ta);
+ const report = el('div', 't-note');
+ body.append(report);
+ const close = dialog(t('Import BibTeX'), body, [
+ btn(t('Cancel'), () => close(), 't-cite-btn'),
+ btn(t('Import'), () => {
+ const { added, replaced, skipped } = importBibtex(ctx, ta.value);
+ if (!added && !replaced) {
+ report.textContent = skipped.length
+ ? `${t('Nothing was imported.')} ${skipped.join(' \u00b7 ')}`
+ : t('Nothing that looks like a BibTeX entry.');
+ return;
+ }
+ ctx.toast(t('{added} added, {replaced} updated', { added, replaced }));
+ if (skipped.length) ctx.toast(skipped[0]);
+ done();
+ ctx.refresh();
+ close();
+ }, 't-cite-btn t-cite-go'),
+ ]);
+ setTimeout(() => ta.focus(), 0);
+}
+
+/** Pick a source and drop a citation at the caret, without typing a key. */
+function openPicker(ctx: FeatureContext): void {
+ const bib = docBib(ctx.store.doc);
+ const keys = Object.keys(bib).sort();
+ const body = el('div');
+ if (!keys.length) {
+ body.append(el('p', 't-about-blurb', t('This document has no sources yet. Import some BibTeX first.')));
+ const close0 = dialog(t('Insert citation'), body, [btn(t('Close'), () => close0(), 't-cite-btn')]);
+ return;
+ }
+ const search = el('input', 't-cite-search');
+ search.type = 'search';
+ search.placeholder = t('Search author, title or key');
+ const list = el('div', 't-cite-pick');
+ const chosen = new Set<string>();
+ const locator = el('input', 't-cite-search');
+ locator.placeholder = t('Page or section, optional — e.g. p. 34');
+
+ const draw = () => {
+ const q = search.value.trim().toLowerCase();
+ list.replaceChildren();
+ for (const key of keys) {
+ const e = bib[key];
+ const hay = `${key} ${e.author ?? ''} ${e.title ?? ''} ${e.year ?? ''}`.toLowerCase();
+ if (q && !hay.includes(q)) continue;
+ const row = el('label', 't-cite-row' + (chosen.has(key) ? ' on' : ''));
+ const box = el('input');
+ box.type = 'checkbox';
+ box.checked = chosen.has(key);
+ box.addEventListener('change', () => {
+ if (box.checked) chosen.add(key); else chosen.delete(key);
+ row.classList.toggle('on', box.checked);
+ });
+ const txt = el('span');
+ txt.append(el('b', '', `${e.author ?? e.title ?? key}${e.year ? ` (${e.year})` : ''}`));
+ txt.append(el('i', '', e.title ?? ''));
+ txt.append(el('code', '', key));
+ row.append(box, txt);
+ list.append(row);
+ }
+ if (!list.children.length) list.append(el('p', 't-note', t('Nothing matches.')));
+ };
+ search.addEventListener('input', draw);
+ draw();
+ body.append(search, list, locator);
+
+ const close = dialog(t('Insert citation'), body, [
+ btn(t('Cancel'), () => close(), 't-cite-btn'),
+ btn(t('Insert'), () => {
+ if (!chosen.size) return;
+ // Sorted, so the same set of sources always produces the same reference —
+ // "(Knuth, 1984; Lamport, 1994)" must not depend on click order.
+ if (insertCitation(ctx, [...chosen].sort(), locator.value)) close();
+ }, 't-cite-btn t-cite-go'),
+ ]);
+ setTimeout(() => search.focus(), 0);
+}
+
+/** The panel: sources, the reference list as it will print, and the trouble. */
+function mountPanel(host: HTMLElement, ctx: FeatureContext): void {
+ const draw = () => {
+ const doc = ctx.store.doc;
+ const bib = docBib(doc);
+ const res = resolveDoc(doc);
+ const counts = citeCounts(doc);
+ host.replaceChildren();
+
+ // ── controls
+ const bar = el('div', 't-cite-bar');
+ const sel = el('select', 't-cite-style');
+ for (const [value, label] of [['numeric', t('Numeric [1] — IEEE-ish')],
+ ['author-year', t('Author–year — APA-ish')]] as const) {
+ const o = el('option', '', label);
+ o.value = value;
+ sel.append(o);
+ }
+ sel.value = docStyle(doc);
+ sel.addEventListener('change', () => setCiteStyle(ctx, readStyle(sel.value)));
+ bar.append(sel);
+ bar.append(btn(t('Paste BibTeX…'), () => openImport(ctx, draw), 't-cite-btn'));
+ bar.append(btn(t('Cite…'), () => openPicker(ctx), 't-cite-btn'));
+ host.append(bar);
+
+ // ── citations pointing at nothing, first, because they are a defect
+ if (res.missing.length) {
+ const warn = el('div', 't-cite-miss');
+ warn.append(el('div', 't-cite-miss-h', t('Cited but not in this document')));
+ for (const k of res.missing) warn.append(el('code', '', k));
+ warn.append(el('p', 't-note', t('These render as [?key] in the document so they cannot be missed.')));
+ host.append(warn);
+ }
+
+ const keys = Object.keys(bib).sort();
+ if (!keys.length) {
+ host.append(el('p', 't-note', t('No sources yet. Paste a .bib file to get started.')));
+ return;
+ }
+
+ // ── the sources themselves
+ host.append(el('h3', 't-cite-h', t('Sources ({n})', { n: keys.length })));
+ for (const key of keys) {
+ const card = el('div', 't-card');
+ const who = el('div', 'who');
+ who.append(el('code', '', key));
+ const n = counts.get(key) ?? 0;
+ who.append(el('span', n ? 't-ok' : 't-warn',
+ n ? t('cited {n} times', { n }) : t('not cited')));
+ card.append(who);
+ card.append(el('div', 'what', referenceText(bib[key], res.style, res.suffix[key] ?? '')));
+ const btns = el('div', 'btns');
+ btns.append(btn(t('Cite here'), () => { insertCitation(ctx, [key]); }, ''));
+ btns.append(btn(t('Remove'), () => {
+ if (counts.get(key)
+ && !confirm(t('{key} is cited in this document. Remove it anyway?', { key }))) return;
+ removeEntry(ctx, key);
+ draw();
+ }, ''));
+ card.append(btns);
+ host.append(card);
+ }
+
+ // ── the list as it will print, in the style's own order
+ const lines: BibLine[] = bibliography(res, bib);
+ host.append(el('h3', 't-cite-h', t('References, as they will print')));
+ if (!lines.length) {
+ host.append(el('p', 't-note', t('Nothing is cited yet, so the list is empty.')));
+ return;
+ }
+ const list = el('div', 't-cite-list');
+ for (const line of lines) {
+ const row = el('div', 't-cite-ref');
+ if (line.label) row.append(el('span', 'n', line.label));
+ row.append(el('span', 'r', line.text));
+ list.append(row);
+ }
+ host.append(list);
+ };
+
+ // The panel repaints on every document change, and repaints the CITATIONS in
+ // the document with it. Once render.ts calls `paintCitations` itself (see
+ // NEEDS FROM THE CORE §5) this second call becomes redundant and harmless —
+ // it is idempotent, because it only ever writes derived text into markers.
+ ctx.store.on(() => {
+ draw();
+ paintCitations(document, ctx.store.doc);
+ });
+ draw();
+ paintCitations(document, ctx.store.doc);
+}
+
+registerPanel({
+ id: 'cite',
+ label: t('Sources'),
+ host: 'citeHost',
+ order: 40,
+ mount: mountPanel,
+ update: (_host, ctx) => { paintCitations(document, ctx.store.doc); },
+});
+
+registerTool({
+ id: 'cite',
+ icon: ICON,
+ title: t('Insert citation'),
+ group: 'insert',
+ label: () => t('Citation'),
+ order: 40,
+ run: openPicker,
+});
+
+registerMenuItem({
+ id: 'cite-import',
+ label: t('Import BibTeX…'),
+ order: 40,
+ run: ctx => openImport(ctx, () => {}),
+});
+
+// ⌘⇧C — beside ⌘⇧A for a footnote, and not ⌘C, which is copy.
+registerKey({ key: 'c', mod: true, shift: true, run: openPicker });
+
+/** Escape hatch for scripts and agents, matching `window.bento.comments()`. */
+export const citeApi = (doc: TypeDoc) => ({
+ style: docStyle(doc),
+ entries: docBib(doc) as Record<string, BibEntry>,
+ resolution: resolveDoc(doc),
+ references: bibliography(resolveDoc(doc), docBib(doc)),
+});
diff --git a/type/src/cite/bibtex.ts b/type/src/cite/bibtex.ts
new file mode 100644
index 00000000..b9e6dca6
--- /dev/null
+++ b/type/src/cite/bibtex.ts
@@ -0,0 +1,405 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// A BibTeX reader. Pasted text in, entries out, and it never throws.
+//
+// ─────────────────────────────────────────────────────── WHAT IS SUPPORTED
+//
+// ENTRY TYPES, modelled properly:
+// @article @book @inproceedings @techreport @misc
+// Aliases folded in: @conference → @inproceedings.
+// Any OTHER type (@incollection, @phdthesis, @manual, @unpublished, …) is
+// read as @misc with its fields intact and a line in `skipped` saying so —
+// the entry is still citable, it just formats generically. Losing a source
+// silently is worse than formatting it plainly.
+//
+// SYNTAX:
+// · `@type{key, field = value, …}` and the `@type(key, …)` paren form
+// · values as {braced}, "quoted", bare numbers, or @string macros
+// · @string definitions and `#` concatenation
+// · @comment and @preamble, skipped
+// · nested braces to any depth, `\{` and `\}` escaped
+// · a trailing comma before the closing delimiter
+// · % comments to end of line, outside braces and quotes
+// · the three-letter month macros (jan…dec)
+//
+// TeX IN VALUES:
+// · accents, both forms — \"o \'e \`a \^o \~n \=a \.z \u{a} \v{s} \H{o}
+// \c{c} \k{a} \d{h} \b{h} \r{a} — applied as Unicode combining marks and
+// composed with NFC, so `\'{\i}` really is í and not a dotted mess
+// · the standalone letters \ss \o \O \aa \AA \ae \AE \oe \OE \l \L \i \j
+// \dh \DH \th \TH
+// · escaped punctuation \& \% \_ \$ \# \{ \}
+// · font/emphasis commands (\textbf \textit \emph \texttt \textsc \mbox
+// \url \textsuperscript) unwrapped to their argument
+// · any other \command dropped, its braced argument kept
+// · `---` → em dash, `--` → en dash, ``…'' → curly quotes, `~` → a space
+// · $…$ math stripped to its contents
+// · BRACE-QUOTING: braces are removed and the text inside is kept EXACTLY.
+// We never case-fold a title, so `{DNA}` needs no protection — but it
+// gets it anyway, because the braces come off and the capitals do not.
+//
+// ─────────────────────────────────────────────────── WHAT IS NOT SUPPORTED
+//
+// · crossref / xdata inheritance — the child keeps only its own fields
+// · BibLaTeX date ranges (`date = {1984-06/1984-07}`); `year` is what is
+// read, and a `date` field's leading four digits are read as the year
+// · sorting keys, `sortname`, `shortauthor`, name-list options
+// · \newcommand and any macro not defined by @string
+// · maths beyond stripping the dollars — `$x^2$` reads as `x^2`
+// · verbatim fields; `url` is cleaned like everything else
+//
+// ────────────────────────────────────────────────────────────── UNTRUSTED
+//
+// Pasted BibTeX is a document, and in this repo every document is untrusted
+// input (docs/DECISIONS.md). Three consequences are built in here rather than
+// hoped for at the call site:
+//
+// 1. It cannot throw. A truncated file, a stray `@`, an unclosed brace, 40MB
+// of `{` — each stops the scan and adds a line to `skipped`. The caller
+// always gets a result it can show.
+// 2. It cannot inject markup. Values come out as TEXT: every `<`, `&` and
+// quote is an ordinary character here, and the atoms this module renders
+// escape on the way to the DOM. Nothing built from a value is ever
+// assigned to innerHTML.
+// 3. It is bounded. Input length, entry count, field count and nesting depth
+// all have ceilings, because the scanner runs on the UI thread on a paste.
+//
+// The whole file is pure: string in, data out, no DOM, so `node
+// scripts/test-type-cite.ts` exercises exactly the code the app runs.
+
+import { BIB_FIELDS, BIB_TYPES, cleanField, validKey, type BibEntry, type BibType } from './types.ts';
+
+/** Ceilings. Generous for real bibliographies, fatal for a denial-of-service. */
+export const SRC_MAX = 4 * 1024 * 1024;
+export const ENTRY_MAX = 5000;
+export const FIELDS_MAX = 64;
+export const DEPTH_MAX = 64;
+
+export interface BibParse {
+ /** in file order; a duplicate key keeps the FIRST definition */
+ entries: Array<{ key: string; entry: BibEntry }>;
+ /** everything not imported, phrased for a person to act on */
+ skipped: string[];
+}
+
+// ───────────────────────────────────────────────────────────── TeX decoding
+
+/** accent command → the Unicode combining mark it applies to the next letter */
+const ACCENT: Record<string, string> = {
+ "'": '\u0301', '`': '\u0300', '^': '\u0302', '\"': '\u0308', '~': '\u0303',
+ '=': '\u0304', '.': '\u0307', 'u': '\u0306', 'v': '\u030C', 'H': '\u030B',
+ 'c': '\u0327', 'k': '\u0328', 'd': '\u0323', 'b': '\u0331', 'r': '\u030A',
+};
+
+/** standalone letter commands */
+const LETTER: Record<string, string> = {
+ ss: 'ß', o: 'ø', O: 'Ø', aa: 'å', AA: 'Å',
+ ae: 'æ', AE: 'Æ', oe: 'œ', OE: 'Œ', l: 'ł',
+ L: 'Ł', i: 'i', j: 'j', dh: 'ð', DH: 'Ð', th: 'þ',
+ TH: 'Þ', copyright: '©', pounds: '£',
+};
+
+/** commands whose argument is the content and whose styling we drop */
+const UNWRAP = new Set([
+ 'textbf', 'textit', 'textsl', 'textsc', 'texttt', 'textrm', 'textmd',
+ 'textnormal', 'textsuperscript', 'textsubscript', 'emph', 'mbox', 'hbox',
+ 'url', 'href', 'text', 'mathrm', 'bf', 'it', 'sc', 'tt', 'rm', 'em',
+]);
+
+const ESCAPED = new Set(['&', '%', '$', '#', '_', '{', '}']);
+
+/** Read a `{...}` group starting at `i` (which must be the brace). */
+function group(s: string, i: number): { body: string; end: number } | null {
+ if (s[i] !== '{') return null;
+ let depth = 0;
+ for (let k = i; k < s.length; k++) {
+ const c = s[k];
+ if (c === '\\') { k++; continue; }
+ if (c === '{') { depth++; if (depth > DEPTH_MAX) return null; }
+ else if (c === '}') { depth--; if (!depth) return { body: s.slice(i + 1, k), end: k + 1 }; }
+ }
+ return null;
+}
+
+/**
+ * TeX → text.
+ *
+ * A single left-to-right scan. Recursion happens only into a command's braced
+ * argument, and DEPTH_MAX bounds it — a value of 100,000 nested braces is a
+ * plausible paste and must not be a stack overflow.
+ */
+export function decodeTex(src: string, depth = 0): string {
+ if (depth > DEPTH_MAX) return '';
+ let out = '';
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i];
+
+ if (c === '\\') {
+ const next = src[i + 1];
+ if (next === undefined) break; // a trailing backslash
+ // \& \% \{ … — the character itself
+ if (ESCAPED.has(next)) { out += next; i++; continue; }
+ if (next === '\\') { out += ' '; i++; continue; } // a line break in a value
+ // a word command: \ss, \textbf, \relax
+ const word = /^[A-Za-z]+/.exec(src.slice(i + 1, i + 40));
+ if (word) {
+ const name = word[0];
+ let k = i + 1 + name.length;
+ // `\ss{}` and `\ss ` both mean ß — an empty group or a space is a
+ // TERMINATOR for the command name, not an argument.
+ if (src[k] === '{' && src[k + 1] === '}') k += 2;
+ else while (src[k] === ' ') k++;
+ if (LETTER[name] !== undefined && !(name.length === 1 && ACCENT[name] && src[k] === '{')) {
+ out += LETTER[name]; i = k - 1; continue;
+ }
+ if (ACCENT[name]) { const r = accent(src, k, ACCENT[name], depth); out += r.text; i = r.end - 1; continue; }
+ const g = src[k] === '{' ? group(src, k) : null;
+ if (UNWRAP.has(name)) {
+ if (g) { out += decodeTex(g.body, depth + 1); i = g.end - 1; continue; }
+ i = k - 1; continue; // \bf with no argument: a switch
+ }
+ // an unknown command: drop the command, keep what it wrapped
+ if (g) { out += decodeTex(g.body, depth + 1); i = g.end - 1; continue; }
+ i = k - 1; continue;
+ }
+ // a symbol accent: \'e or \'{e}
+ if (ACCENT[next]) { const r = accent(src, i + 2, ACCENT[next], depth); out += r.text; i = r.end - 1; continue; }
+ out += next; i++; continue;
+ }
+
+ if (c === '{' || c === '}') continue; // brace-quoting: off it comes
+ if (c === '$') continue; // math delimiters only
+ if (c === '~') { out += ' '; continue; } // a tie is still a space
+ if (c === '-' && src[i + 1] === '-') {
+ if (src[i + 2] === '-') { out += '—'; i += 2; } else { out += '–'; i += 1; }
+ continue;
+ }
+ if (c === '`') { if (src[i + 1] === '`') { out += '“'; i++; } else out += '‘'; continue; }
+ if (c === "'") { if (src[i + 1] === "'") { out += '”'; i++; } else out += "'"; continue; }
+ out += c;
+ }
+ return out;
+}
+
+/**
+ * Apply a combining mark to whatever follows, and compose.
+ *
+ * Composing with NFC is what makes this a table of 15 marks instead of a table
+ * of 300 precomposed characters, and it is also what makes `\v{s}` work — š is
+ * not in anybody's hand-written accent table and it is in Unicode.
+ */
+function accent(src: string, at: number, mark: string, depth: number): { text: string; end: number } {
+ let base = '';
+ let end = at;
+ if (src[at] === '{') {
+ const g = group(src, at);
+ if (!g) return { text: '', end: src.length };
+ base = decodeTex(g.body, depth + 1);
+ end = g.end;
+ } else if (src[at] === '\\') {
+ const word = /^\\([A-Za-z]+)/.exec(src.slice(at, at + 20));
+ if (word && LETTER[word[1]] !== undefined) { base = LETTER[word[1]]; end = at + word[0].length; }
+ else { base = src[at + 1] ?? ''; end = at + 2; }
+ } else if (src[at] !== undefined) {
+ base = src[at]; end = at + 1;
+ }
+ // `\'{\i}` is í: the dotless i exists so the accent can replace the dot.
+ base = base.replace(/ı/g, 'i').replace(/ȷ/g, 'j');
+ if (!base) return { text: '', end };
+ return { text: (base[0] + mark + base.slice(1)).normalize('NFC'), end };
+}
+
+// ─────────────────────────────────────────────────────────── the entry scanner
+
+/** Split on `sep` at brace depth 0, outside "quotes". */
+function splitTop(s: string, sep: string): string[] {
+ const out: string[] = [];
+ let depth = 0, quote = false, start = 0;
+ for (let i = 0; i < s.length; i++) {
+ const c = s[i];
+ if (c === '\\') { i++; continue; }
+ if (quote) { if (c === '"') quote = false; continue; }
+ if (c === '"' && depth === 0) { quote = true; continue; }
+ if (c === '{') depth++;
+ else if (c === '}') depth = Math.max(0, depth - 1);
+ else if (c === sep && depth === 0) { out.push(s.slice(start, i)); start = i + 1; }
+ }
+ out.push(s.slice(start));
+ return out;
+}
+
+/** One `#`-concatenated value, resolved through the @string macros. */
+function value(raw: string, macros: Map<string, string>, note: (s: string) => void): string {
+ let out = '';
+ for (const part of splitTop(raw, '#')) {
+ const p = part.trim();
+ if (!p) continue;
+ if (p[0] === '{') { const g = group(p, 0); out += decodeTex(g ? g.body : p.slice(1)); continue; }
+ if (p[0] === '"') { out += decodeTex(p.slice(1, p.endsWith('"') && p.length > 1 ? -1 : undefined)); continue; }
+ if (/^[0-9]+$/.test(p)) { out += p; continue; }
+ const m = macros.get(p.toLowerCase());
+ if (m !== undefined) { out += m; continue; }
+ note(`unknown @string macro "${p.slice(0, 40)}" used as written`);
+ out += decodeTex(p);
+ }
+ return out;
+}
+
+/** Strip `%` comments, which run to end of line outside braces and quotes. */
+function stripComments(s: string): string {
+ let out = '', depth = 0, quote = false;
+ for (let i = 0; i < s.length; i++) {
+ const c = s[i];
+ if (c === '\\') { out += c + (s[i + 1] ?? ''); i++; continue; }
+ if (quote) { out += c; if (c === '"') quote = false; continue; }
+ if (c === '"' && depth === 0) { out += c; quote = true; continue; }
+ if (c === '{') depth++;
+ else if (c === '}') depth = Math.max(0, depth - 1);
+ else if (c === '%' && depth === 0) {
+ const nl = s.indexOf('\n', i);
+ if (nl < 0) break;
+ i = nl - 1; out += '\n';
+ continue;
+ }
+ out += c;
+ }
+ return out;
+}
+
+const MONTHS: Array<[string, string]> = [
+ ['jan', 'January'], ['feb', 'February'], ['mar', 'March'], ['apr', 'April'],
+ ['may', 'May'], ['jun', 'June'], ['jul', 'July'], ['aug', 'August'],
+ ['sep', 'September'], ['oct', 'October'], ['nov', 'November'], ['dec', 'December'],
+];
+
+const ALIAS: Record<string, BibType> = { conference: 'inproceedings' };
+
+/** The whole job: text in, entries plus a list of what was not imported. */
+export function parseBibtex(input: unknown): BibParse {
+ const skipped: string[] = [];
+ const entries: Array<{ key: string; entry: BibEntry }> = [];
+ if (typeof input !== 'string' || !input.trim()) {
+ return { entries, skipped: input === undefined || input === null || input === '' ? [] : ['nothing that looks like BibTeX'] };
+ }
+ let src = input;
+ if (src.length > SRC_MAX) {
+ src = src.slice(0, SRC_MAX);
+ skipped.push(`the paste was longer than ${Math.round(SRC_MAX / 1024)}KB — only the first part was read`);
+ }
+ src = stripComments(src);
+
+ const macros = new Map<string, string>(MONTHS);
+ const seen = new Set<string>();
+ // Reported ONCE at the end, not per entry: every real .bib carries abstract,
+ // isbn and keywords, and 200 identical lines would bury the one line that
+ // says a source was lost.
+ const unmodelled = new Set<string>();
+ let i = 0;
+
+ while (i < src.length) {
+ const at = src.indexOf('@', i);
+ if (at < 0) break;
+ i = at + 1;
+ const tm = /^[A-Za-z]+/.exec(src.slice(i, i + 40));
+ if (!tm) { skipped.push(`ignored a stray "@" at character ${at}`); continue; }
+ const type = tm[0].toLowerCase();
+ i += tm[0].length;
+ while (i < src.length && /\s/.test(src[i])) i++;
+ const open = src[i];
+ if (open !== '{' && open !== '(') { skipped.push(`@${type} at character ${at} has no body — skipped`); continue; }
+
+ // Read the body with brace counting. The paren form still nests with
+ // braces, so `)` only closes when nothing is open.
+ let depth = 0, quote = false, end = -1;
+ for (let k = i; k < src.length; k++) {
+ const c = src[k];
+ if (c === '\\') { k++; continue; }
+ if (quote) { if (c === '"') quote = false; continue; }
+ if (c === '"' && depth <= 1) { quote = true; continue; }
+ if (c === '{') { depth++; if (depth > DEPTH_MAX) { end = -2; break; } continue; }
+ if (c === '}') { depth--; if (open === '{' && depth === 0) { end = k; break; } continue; }
+ if (c === ')' && open === '(' && depth === 0) { end = k; break; }
+ }
+ if (end === -2) { skipped.push(`@${type} at character ${at} nests braces too deeply — skipped`); i = at + 1; continue; }
+ // RESUME, do not stop. A file whose third entry lost a brace still has
+ // forty good entries after it, and `break` here threw them all away — the
+ // rig caught exactly that. Rewinding to just past the `@` lets the scan
+ // find the next entry, at the cost of one report per wrecked entry.
+ if (end < 0) {
+ skipped.push(`@${type} at character ${at} is never closed — skipped, and reading continued after it`);
+ i = at + 1;
+ continue;
+ }
+ const body = src.slice(i + 1, end);
+ i = end + 1;
+
+ if (type === 'comment' || type === 'preamble') continue;
+
+ if (type === 'string') {
+ const eq = splitTop(body, '=');
+ if (eq.length < 2) { skipped.push(`@string at character ${at} is not "name = value" — ignored`); continue; }
+ const name = eq[0].trim().toLowerCase();
+ if (!name) { skipped.push(`@string at character ${at} has no name — ignored`); continue; }
+ macros.set(name, value(eq.slice(1).join('='), macros, m => skipped.push(`@string ${name}: ${m}`)));
+ continue;
+ }
+
+ if (entries.length >= ENTRY_MAX) {
+ skipped.push(`stopped after ${ENTRY_MAX} entries`);
+ break;
+ }
+
+ const parts = splitTop(body, ',');
+ const key = (parts.shift() ?? '').trim();
+ if (!key) { skipped.push(`@${type} at character ${at} has no citation key — skipped (nothing could cite it)`); continue; }
+ if (!validKey(key)) {
+ skipped.push(`@${type} key ${JSON.stringify(key.slice(0, 40))} uses characters a citation cannot carry — skipped`);
+ continue;
+ }
+ if (seen.has(key)) { skipped.push(`${key}: a second @${type} with this key — kept the first`); continue; }
+
+ let btype: BibType;
+ if (BIB_TYPES.includes(type as BibType)) btype = type as BibType;
+ else if (ALIAS[type]) btype = ALIAS[type];
+ else {
+ btype = 'misc';
+ skipped.push(`${key}: @${type} is not a type this app models — imported as @misc, so it still cites`);
+ }
+
+ const entry: BibEntry = { type: btype };
+ const allowed = new Set<string>(BIB_FIELDS as readonly string[]);
+ let malformed = 0;
+ for (const f of parts.slice(0, FIELDS_MAX)) {
+ if (!f.trim()) continue; // the trailing comma
+ const eq = splitTop(f, '=');
+ if (eq.length < 2) { malformed++; continue; }
+ const name = eq[0].trim().toLowerCase();
+ const text = cleanField(value(eq.slice(1).join('='), macros, m => skipped.push(`${key}: ${m}`)));
+ if (!text) continue;
+ if (allowed.has(name)) { (entry as unknown as Record<string, string>)[name] = text; continue; }
+ // BibLaTeX writes `date = {1984-06-01}`; the year is in there and the
+ // alternative is an entry that formats as "n.d." for no good reason.
+ if (name === 'date' && !entry.year) {
+ const y = /^\d{4}/.exec(text);
+ if (y) entry.year = y[0];
+ continue;
+ }
+ if (name === 'journaltitle' && !entry.journal) { entry.journal = text; continue; }
+ unmodelled.add(name.slice(0, 32));
+ }
+ if (parts.length > FIELDS_MAX) {
+ skipped.push(`${key}: only the first ${FIELDS_MAX} fields were read`);
+ }
+ if (malformed) {
+ skipped.push(`${key}: ${malformed} piece${malformed > 1 ? 's' : ''} of the entry ${malformed > 1 ? 'were' : 'was'} not "field = value" — ignored`);
+ }
+ seen.add(key);
+ entries.push({ key, entry });
+ }
+
+ if (unmodelled.size) {
+ skipped.push(`fields this app does not model, dropped everywhere: ${[...unmodelled].sort().join(', ')}`);
+ }
+ return { entries, skipped };
+}
diff --git a/type/src/cite/format.ts b/type/src/cite/format.ts
new file mode 100644
index 00000000..5427f5c6
--- /dev/null
+++ b/type/src/cite/format.ts
@@ -0,0 +1,466 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The two styles, and the numbering that feeds them.
+//
+// EVERYTHING HERE IS DERIVED. Nothing this file computes is ever written back
+// into the document: not a number, not a formatted reference, not the sort
+// order of the bibliography. `resolve()` reads the body and the entry map and
+// returns a fresh answer every time, which is the only arrangement in which
+// inserting a citation into paragraph two can renumber the eleven after it —
+// and the only one in which switching from IEEE to APA is a preference rather
+// than a rewrite of the file.
+//
+// It is also what keeps the redline honest: a stored "[7]" would diff as a
+// changed word every time a citation was inserted earlier in the document,
+// and a stored "(Knuth, 1984)" would diff as a whole rewritten phrase the
+// moment somebody fixed a typo in the author field.
+//
+// PURE. No DOM, no `t()`. Bibliographic output is CONTENT, not chrome: a
+// reference list is set in the language of the source, not in the language of
+// the reader's menus, and the same document read in Tokyo and in Lyon must
+// print the same references. So nothing in this file is translated.
+//
+// TWO STYLES, deliberately not a citation-style engine. `numeric` reads as
+// IEEE and `author-year` reads as APA 7th; they are hand-written, not driven
+// by a style file, because two styles done properly beat a half-built CSL
+// interpreter that gets every style slightly wrong.
+
+import type { BibEntry, Bibliography, CiteRef, CiteStyle } from './types.ts';
+
+// ─────────────────────────────────────────────────────────────────── names
+
+export interface Name {
+ last: string;
+ first: string;
+ /** "von", "van der", "de la" — kept with the surname when sorting */
+ von: string;
+ /** "Jr.", "III" */
+ jr: string;
+}
+
+export interface NameList { names: Name[]; etAl: boolean }
+
+const isParticle = (w: string) => !!w && w[0] === w[0].toLowerCase() && /[a-z]/.test(w[0]);
+
+/**
+ * Split BibTeX's `author` field into names.
+ *
+ * Both orderings, as BibTeX defines them:
+ * "Donald E. Knuth" → First von Last
+ * "Knuth, Donald E." → von Last, First
+ * "de la Vega, Jr., Maria" → von Last, Jr, First
+ *
+ * `and others` sets the et-al flag, which is how a .bib says "and the rest".
+ *
+ * A COMMA WITH NOTHING AFTER IT means a literal name: `author = {World Health
+ * Organization,}` gives one name whose surname is the whole string and which
+ * therefore never gets initialised or inverted. That is the supported way to
+ * write an institutional author — BibTeX's brace-protection cannot survive
+ * into the model, because the model stores decoded text and decoding is what
+ * takes the braces off.
+ */
+export function parseNames(field: string | undefined): NameList {
+ const out: NameList = { names: [], etAl: false };
+ if (!field) return out;
+ // 64 names is more than any real paper and bounds the work
+ for (const raw of field.split(/\s+and\s+/i).slice(0, 64)) {
+ const chunk = raw.trim();
+ if (!chunk) continue;
+ if (chunk.toLowerCase() === 'others') { out.etAl = true; continue; }
+ out.names.push(parseName(chunk));
+ }
+ return out;
+}
+
+function parseName(s: string): Name {
+ const parts = s.split(',').map(p => p.trim());
+ if (parts.length > 1) {
+ const first = parts.length > 2 ? parts.slice(2).join(', ') : parts[1];
+ const jr = parts.length > 2 ? parts[1] : '';
+ const { von, last } = splitVon(parts[0]);
+ return { last, first, von, jr };
+ }
+ // "First von Last", BibTeX's own rule: the von part runs from the FIRST
+ // lowercase-initial word to the LAST one before the surname. Anything before
+ // it is given names, anything after it is the surname.
+ //
+ // A first version instead grew the surname leftwards through particles,
+ // which put "van" in `last` and left `von` empty — so "Ludwig van Beethoven"
+ // sorted under V in one place and B in another.
+ const words = s.split(/\s+/).filter(Boolean);
+ if (words.length <= 1) return { last: s, first: '', von: '', jr: '' };
+ let p = 0;
+ while (p < words.length - 1 && !isParticle(words[p])) p++;
+ if (!isParticle(words[p])) {
+ return { last: words[words.length - 1], first: words.slice(0, -1).join(' '), von: '', jr: '' };
+ }
+ let q = p;
+ for (let k = p; k < words.length - 1; k++) if (isParticle(words[k])) q = k;
+ return {
+ last: words.slice(q + 1).join(' '),
+ first: words.slice(0, p).join(' '),
+ von: words.slice(p, q + 1).join(' '),
+ jr: '',
+ };
+}
+
+function splitVon(s: string): { von: string; last: string } {
+ const words = s.split(/\s+/).filter(Boolean);
+ let k = 0;
+ while (k < words.length - 1 && isParticle(words[k])) k++;
+ return { von: words.slice(0, k).join(' '), last: words.slice(k).join(' ') };
+}
+
+/** "Donald E." → "D. E."; "Jean-Paul" → "J.-P." */
+export function initials(first: string): string {
+ return first.split(/\s+/).filter(Boolean)
+ .map(w => w.split('-').map(p => p ? `${p[0].toUpperCase()}.` : '').filter(Boolean).join('-'))
+ .join(' ');
+}
+
+const join = (...bits: Array<string | undefined>) => bits.filter(Boolean).join(' ');
+
+/** "Knuth, D. E." — APA's reference-list form. */
+const apaName = (n: Name): string => {
+ const surname = join(n.von, n.last);
+ const rest = [initials(n.first), n.jr].filter(Boolean).join(', ');
+ return rest ? `${surname}, ${rest}` : surname;
+};
+
+/** "D. E. Knuth" — IEEE's. */
+const ieeeName = (n: Name): string => {
+ const surname = join(n.von, n.last, n.jr && n.jr.replace(/\.$/, '') + '.');
+ const ini = initials(n.first);
+ return ini ? `${ini} ${surname}` : surname;
+};
+
+/** The family name alone — what an author–year citation shows. */
+export const familyName = (n: Name): string => join(n.von, n.last);
+
+// ────────────────────────────────────────────────────────── sorting, stably
+
+/**
+ * A sort key that does not move when the reader's locale does.
+ *
+ * `localeCompare` would order the bibliography differently in Stockholm and in
+ * Madrid, which means the same file prints differently for two readers — and
+ * in a numeric style the NUMBERS would differ too, so a colleague's "see [4]"
+ * would point at the wrong work. Fold to ASCII-ish and compare code units.
+ */
+export const sortKey = (s: string): string =>
+ s.normalize('NFD').replace(/[\u0300-\u036F]/g, '').toLowerCase().replace(/[^a-z0-9 ]/g, '').trim();
+
+const entrySortKey = (e: BibEntry | undefined): string => {
+ if (!e) return '\uFFFF'; // an entry that vanished sorts last, not first
+ const names = parseNames(e.author ?? e.editor);
+ const who = names.names.length ? names.names.map(familyName).join(' ') : (e.title ?? '');
+ return sortKey(who);
+};
+
+// ────────────────────────────────────────────────────────────── resolution
+
+/** Where a citation sits, in document order. */
+export interface CiteSite { blockId: string; ref: CiteRef }
+
+/** A block, as far as this module needs to know. */
+export interface CitedBlock { id: string; cites?: CiteRef[] }
+
+/** Citations in document order, each block's own in offset order. */
+export function collectCites(body: readonly CitedBlock[]): CiteSite[] {
+ const out: CiteSite[] = [];
+ for (const b of body) {
+ if (!b.cites?.length) continue;
+ for (const ref of [...b.cites].sort((x, y) => x.at - y.at)) out.push({ blockId: b.id, ref });
+ }
+ return out;
+}
+
+export interface Resolution {
+ style: CiteStyle;
+ /** the keys the bibliography prints, in the order it prints them */
+ order: string[];
+ /** numeric style: key → its number. Empty for author–year. */
+ number: Record<string, number>;
+ /** author–year: key → 'a' | 'b' | … when one author has two works in a year */
+ suffix: Record<string, string>;
+ /** cited keys with no entry behind them, first-cited first */
+ missing: string[];
+}
+
+/**
+ * Work out the numbering and the bibliography order for one document.
+ *
+ * Numeric numbers by FIRST APPEARANCE, which is what IEEE does and what makes
+ * "[1]" the first reference a reader meets. Author–year sorts alphabetically,
+ * because that is how a reader finds "Knuth, 1984" in the list.
+ */
+export function resolve(body: readonly CitedBlock[], bib: Bibliography, style: CiteStyle): Resolution {
+ const res: Resolution = { style, order: [], number: {}, suffix: {}, missing: [] };
+ const firstSeen: string[] = [];
+ const seen = new Set<string>();
+ const missing = new Set<string>();
+ for (const site of collectCites(body)) {
+ for (const key of site.ref.keys) {
+ if (bib[key]) {
+ if (!seen.has(key)) { seen.add(key); firstSeen.push(key); }
+ } else if (!missing.has(key)) { missing.add(key); res.missing.push(key); }
+ }
+ }
+
+ if (style === 'numeric') {
+ res.order = firstSeen;
+ firstSeen.forEach((k, i) => { res.number[k] = i + 1; });
+ return res;
+ }
+
+ res.order = [...firstSeen].sort((a, b) => {
+ const ka = entrySortKey(bib[a]), kb = entrySortKey(bib[b]);
+ if (ka !== kb) return ka < kb ? -1 : 1;
+ const ya = bib[a]?.year ?? '', yb = bib[b]?.year ?? '';
+ if (ya !== yb) return ya < yb ? -1 : 1;
+ const ta = sortKey(bib[a]?.title ?? ''), tb = sortKey(bib[b]?.title ?? '');
+ if (ta !== tb) return ta < tb ? -1 : 1;
+ return a < b ? -1 : a > b ? 1 : 0; // the key, so ties are stable
+ });
+
+ // Disambiguation letters: two works by the same author in the same year are
+ // 1984a and 1984b, in the order the list prints them.
+ const groups = new Map<string, string[]>();
+ for (const k of res.order) {
+ const g = `${entrySortKey(bib[k])}${bib[k]?.year ?? ''}`;
+ (groups.get(g) ?? groups.set(g, []).get(g)!).push(k);
+ }
+ for (const g of groups.values()) {
+ if (g.length < 2) continue;
+ g.forEach((k, i) => { res.suffix[k] = letters(i); });
+ }
+ return res;
+}
+
+/** 0 → a, 25 → z, 26 → aa. */
+function letters(i: number): string {
+ let s = '';
+ let n = i;
+ do { s = String.fromCharCode(97 + (n % 26)) + s; n = Math.floor(n / 26) - 1; } while (n >= 0);
+ return s;
+}
+
+// ─────────────────────────────────────────────────────── the in-text citation
+
+/**
+ * How a MISSING entry shows up.
+ *
+ * Visibly, and in both styles. A citation whose entry was deleted, or whose
+ * key was mistyped, is a defect in the document and the author has to be able
+ * to see it — in the paginated view, in print, and in the PDF. Rendering
+ * nothing would hide it until a reviewer noticed a sentence that cites the
+ * air; rendering "[?]" without the key would hide WHICH one.
+ */
+export const missingText = (key: string): string => `[?${key}]`;
+
+/** The text of one citation, in the document's style. */
+export function citationText(ref: CiteRef, res: Resolution, bib: Bibliography): string {
+ const keys = ref.keys;
+ if (!keys.length) return '';
+ if (res.style === 'numeric') {
+ const bits = keys.map(k => {
+ if (!bib[k]) return missingText(k);
+ const inner = ref.locator ? `${res.number[k]}, ${ref.locator}` : String(res.number[k]);
+ return `[${inner}]`;
+ });
+ return bits.join(', ');
+ }
+ // author–year: the list prints in bibliography order, so the reader can walk
+ // straight from "(Knuth, 1984; Lamport, 1994)" down the alphabet
+ const rank = new Map(res.order.map((k, i) => [k, i]));
+ const ordered = [...keys].sort((a, b) => (rank.get(a) ?? 1e9) - (rank.get(b) ?? 1e9));
+ const bits = ordered.map(k => {
+ const e = bib[k];
+ if (!e) return missingText(k);
+ const year = (e.year || 'n.d.') + (res.suffix[k] ?? '');
+ const who = ref.suppressAuthor ? '' : inTextAuthors(e);
+ return [who, year, ref.locator].filter(Boolean).join(', ');
+ });
+ return `(${bits.join('; ')})`;
+}
+
+/**
+ * APA's et-al rule, 7th edition: one or two authors are both named, three or
+ * more collapse to the first plus "et al." from the FIRST citation onward.
+ * (The 6th edition spelled out three on first use; the 7th stopped, because
+ * nobody could remember which citation was the first one.)
+ */
+export function inTextAuthors(e: BibEntry): string {
+ const { names, etAl } = parseNames(e.author ?? e.editor);
+ if (!names.length) return e.title ?? '';
+ if (etAl || names.length > 2) return `${familyName(names[0])} et al.`;
+ if (names.length === 2) return `${familyName(names[0])} & ${familyName(names[1])}`;
+ return familyName(names[0]);
+}
+
+// ───────────────────────────────────────────────────────────── the list
+
+export interface BibLine {
+ key: string;
+ /** the numeric style's label, "[3]"; empty in author–year */
+ label: string;
+ /** the reference itself, as plain text */
+ text: string;
+}
+
+/** The bibliography, in the style's own order and format. */
+export function bibliography(res: Resolution, bib: Bibliography): BibLine[] {
+ return res.order.map(key => ({
+ key,
+ label: res.style === 'numeric' ? `[${res.number[key]}]` : '',
+ text: referenceText(bib[key], res.style, res.suffix[key] ?? ''),
+ }));
+}
+
+const dash = (s: string | undefined): string =>
+ (s ?? '').replace(/\s*(?:--|-|–|—)\s*/g, '–');
+
+const period = (s: string): string => {
+ const t = s.replace(/\s+/g, ' ').trim();
+ if (!t) return '';
+ return /[.!?]$/.test(t) ? t : `${t}.`;
+};
+
+const link = (e: BibEntry): string =>
+ e.doi ? `https://doi.org/${e.doi.replace(/^https?:\/\/doi\.org\//i, '')}` : (e.url ?? '');
+
+/** One reference, formatted. `suffix` is the author–year disambiguation letter. */
+export function referenceText(e: BibEntry | undefined, style: CiteStyle, suffix = ''): string {
+ if (!e) return '';
+ return style === 'numeric' ? ieeeReference(e) : apaReference(e, suffix);
+}
+
+// ── IEEE-ish
+
+function ieeeAuthors(e: BibEntry): string {
+ const { names, etAl } = parseNames(e.author ?? e.editor);
+ if (!names.length) return '';
+ // IEEE names up to six authors and then gives up; that ceiling is the style's
+ const shown = names.length > 6 || etAl ? names.slice(0, 1) : names;
+ const rendered = shown.map(ieeeName);
+ if (names.length > 6 || etAl) return `${rendered[0]} et al.`;
+ if (rendered.length === 1) return rendered[0];
+ if (rendered.length === 2) return `${rendered[0]} and ${rendered[1]}`;
+ return `${rendered.slice(0, -1).join(', ')}, and ${rendered[rendered.length - 1]}`;
+}
+
+/**
+ * Pieces joined by ", ", except after a quoted title — which already carries
+ * its own comma INSIDE the quotes, IEEE-style, and must not gain a second one.
+ * A first version joined everything with ", " and produced `"Title," , Comput.
+ * J.`; a second sniffed for a trailing `,"` and broke on a title ending in a
+ * question mark, where the quoted form is `"Why?"`.
+ */
+interface Piece { t: string; sep?: string }
+
+function assemble(pieces: Piece[]): string {
+ let out = '';
+ for (const p of pieces) {
+ if (!p.t) continue;
+ out = out ? out + (sepOf(pieces, p) ?? ', ') + p.t : p.t;
+ }
+ return out;
+}
+const sepOf = (pieces: Piece[], p: Piece): string | undefined => {
+ const i = pieces.indexOf(p);
+ for (let k = i - 1; k >= 0; k--) if (pieces[k].t) return pieces[k].sep;
+ return undefined;
+};
+
+function ieeeReference(e: BibEntry): string {
+ const pieces: Piece[] = [{ t: ieeeAuthors(e) }];
+ const title = e.title ?? '';
+ const place = [e.address, e.publisher].filter(Boolean).join(': ');
+
+ if (e.type === 'book') {
+ pieces.push({ t: title });
+ // "1st ed." already ends in a period, so the separator that follows it is a
+ // SPACE. With ', ' it read "…, 1st ed., Reading"; with '. ' it doubled up.
+ pieces.push({ t: e.edition ? `${e.edition} ed.` : '', sep: ' ' });
+ pieces.push({ t: e.series ?? '' });
+ pieces.push({ t: place });
+ } else {
+ // the comma lives inside the quotes; a title that ends in its own
+ // punctuation keeps it and gains none
+ pieces.push({ t: title ? `"${title}${/[.?!,]$/.test(title) ? '' : ','}"` : '', sep: ' ' });
+ if (e.type === 'inproceedings') {
+ pieces.push({ t: e.booktitle ? `in ${e.booktitle}` : '' });
+ pieces.push({ t: e.address ?? '' });
+ } else if (e.type === 'article') {
+ pieces.push({ t: e.journal ?? '' });
+ pieces.push({ t: e.volume ? `vol. ${e.volume}` : '' });
+ pieces.push({ t: e.number ? `no. ${e.number}` : '' });
+ } else if (e.type === 'techreport') {
+ pieces.push({ t: e.institution ?? e.school ?? '' });
+ pieces.push({ t: e.address ?? '' });
+ pieces.push({ t: e.number ? `Tech. Rep. ${e.number}` : 'Tech. Rep.' });
+ } else {
+ pieces.push({ t: e.howpublished ?? '' });
+ pieces.push({ t: e.publisher ?? '' });
+ }
+ pieces.push({ t: e.pages ? `pp. ${dash(e.pages)}` : '' });
+ }
+ pieces.push({ t: e.year ?? '' });
+
+ let out = period(assemble(pieces));
+ const href = link(e);
+ if (href) out += ` [Online]. Available: ${href}`;
+ if (e.note) out += ` ${period(e.note)}`;
+ return out.replace(/\s+/g, ' ').trim();
+}
+
+// ── APA-ish
+
+function apaAuthors(e: BibEntry): string {
+ const { names, etAl } = parseNames(e.author ?? e.editor);
+ if (!names.length) return '';
+ // APA 7 lists up to twenty; beyond that, nineteen, an ellipsis, and the last
+ const rendered = names.map(apaName);
+ if (etAl) return `${rendered[0]}, et al.`;
+ if (rendered.length === 1) return rendered[0];
+ if (rendered.length === 2) return `${rendered[0]}, & ${rendered[1]}`;
+ if (rendered.length <= 20) return `${rendered.slice(0, -1).join(', ')}, & ${rendered[rendered.length - 1]}`;
+ return `${rendered.slice(0, 19).join(', ')}, ... ${rendered[rendered.length - 1]}`;
+}
+
+function apaReference(e: BibEntry, suffix: string): string {
+ const out: string[] = [];
+ const who = apaAuthors(e);
+ if (who) out.push(period(who));
+ out.push(`(${(e.year || 'n.d.') + suffix}).`);
+ const title = e.title ?? '';
+
+ if (e.type === 'article') {
+ if (title) out.push(period(title));
+ const vol = e.volume ? (e.number ? `${e.volume}(${e.number})` : e.volume) : '';
+ const tail = [e.journal, vol, e.pages ? dash(e.pages) : ''].filter(Boolean).join(', ');
+ if (tail) out.push(period(tail));
+ } else if (e.type === 'book') {
+ out.push(period([title, e.edition ? `(${e.edition} ed.)` : ''].filter(Boolean).join(' ')));
+ if (e.publisher) out.push(period(e.publisher));
+ } else if (e.type === 'inproceedings') {
+ if (title) out.push(period(title));
+ const where = [e.booktitle ? `In ${e.booktitle}` : '', e.pages ? `(pp. ${dash(e.pages)})` : '']
+ .filter(Boolean).join(' ');
+ if (where) out.push(period(where));
+ if (e.publisher) out.push(period(e.publisher));
+ } else if (e.type === 'techreport') {
+ out.push(period([title, e.number ? `(Report No. ${e.number})` : ''].filter(Boolean).join(' ')));
+ const org = e.institution ?? e.school;
+ if (org) out.push(period(org));
+ } else {
+ if (title) out.push(period(title));
+ const org = e.publisher ?? e.howpublished ?? e.institution;
+ if (org) out.push(period(org));
+ }
+ const href = link(e);
+ if (href) out.push(href);
+ if (e.note) out.push(period(e.note));
+ return out.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim();
+}
diff --git a/type/src/cite/types.ts b/type/src/cite/types.ts
new file mode 100644
index 00000000..aebd03a5
--- /dev/null
+++ b/type/src/cite/types.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The citation/bibliography DATA, and the rules for reading it back from a
+// file nobody trusts.
+//
+// Two shapes, and they mirror two shapes the model already has:
+//
+// BibEntry lives in a doc-level map keyed by id — `doc.bibliography` is
+// `doc.footnotes` with more fields. A source outlives the sentence that
+// cites it, gets cited from three paragraphs at once, and must survive the
+// paragraph being rewritten; a note has exactly the same lifetime problem
+// and the model already answered it with a doc-level map.
+//
+// CiteRef lives on the block, anchored by character offset — it is NoteRef
+// with a payload. See cite.ts for why this is an ATOM and not a mark.
+//
+// Everything here is defensive: a `bibliography` field arrives from a JSON
+// blob that may have been written by another tool, hand-edited, or crafted.
+// `readBibliography` is total — it returns a map, never throws, and drops what
+// it cannot understand rather than passing a surprise downstream.
+
+/** The entry types we model. Anything else a .bib names is read as `misc`. */
+export type BibType = 'article' | 'book' | 'inproceedings' | 'techreport' | 'misc';
+
+export const BIB_TYPES: readonly BibType[] =
+ ['article', 'book', 'inproceedings', 'techreport', 'misc'];
+
+/**
+ * The fields an entry may carry. All STRINGS, deliberately.
+ *
+ * `author` stays in BibTeX's own "Last, First and Last, First" form rather
+ * than being split into structured names at import. That keeps the document
+ * field human-readable and hand-editable, keeps a round trip through a .bib
+ * lossless, and means the ONE place that has to know how a name decomposes is
+ * the formatter — which has to know anyway, because IEEE and APA decompose it
+ * differently.
+ */
+export interface BibEntry {
+ type: BibType;
+ author?: string;
+ editor?: string;
+ title?: string;
+ year?: string;
+ month?: string;
+ journal?: string;
+ booktitle?: string;
+ publisher?: string;
+ institution?: string;
+ school?: string;
+ volume?: string;
+ number?: string;
+ pages?: string;
+ address?: string;
+ edition?: string;
+ series?: string;
+ howpublished?: string;
+ note?: string;
+ url?: string;
+ doi?: string;
+}
+
+/** The fields we keep. An unknown field is dropped, not carried. */
+export const BIB_FIELDS: ReadonlyArray<Exclude<keyof BibEntry, 'type'>> = [
+ 'author', 'editor', 'title', 'year', 'month', 'journal', 'booktitle',
+ 'publisher', 'institution', 'school', 'volume', 'number', 'pages',
+ 'address', 'edition', 'series', 'howpublished', 'note', 'url', 'doi',
+];
+
+export type Bibliography = Record<string, BibEntry>;
+
+/**
+ * A citation anchored into a block's text.
+ *
+ * `keys` is a LIST because "(Knuth, 1984; Lamport, 1994)" is one citation with
+ * one position, not two citations that happen to be adjacent — and because
+ * every style joins a multi-key citation differently, so the grouping has to
+ * survive into the formatter.
+ */
+export interface CiteRef {
+ /** character offset into the block's text — the coordinate NoteRef uses */
+ at: number;
+ keys: string[];
+ /** "p. 34", "ch. 2" — authored text, shown inside the citation */
+ locator?: string;
+ /** author-year only: render "(1984)" because the sentence already said Knuth */
+ suppressAuthor?: boolean;
+}
+
+export type CiteStyle = 'numeric' | 'author-year';
+export const CITE_STYLES: readonly CiteStyle[] = ['numeric', 'author-year'];
+export const DEFAULT_STYLE: CiteStyle = 'numeric';
+
+// ────────────────────────────────────────────────────── reading untrusted data
+
+const isObj = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v);
+
+/**
+ * How long a single field may be. A citation is rendered into a line of prose;
+ * a 4MB "title" is not a title, it is a way to make the layout engine chew.
+ */
+export const FIELD_MAX = 4000;
+
+/**
+ * Characters with no business in a bibliographic field.
+ *
+ * Control characters and the bidi overrides are the interesting ones: they are
+ * INVISIBLE in the panel and load-bearing in the output, so a crafted .bib
+ * could make a rendered reference read as a different work than the one the
+ * panel shows.
+ */
+const JUNK = /[\u0000-\u001F\u007F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
+
+/** Whitespace is collapsed for the same reason a title is one line: the
+ * citation is prose, not a code block. */
+export const cleanField = (s: string): string =>
+ s.replace(JUNK, '').replace(/\s+/g, ' ').trim().slice(0, FIELD_MAX);
+
+/**
+ * A citation key, as it may appear in markup and in a data- attribute.
+ * BibTeX allows nearly anything; we allow what cannot be mistaken for syntax.
+ */
+export const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9:._+/'-]{0,127}$/;
+export const validKey = (k: string): boolean => KEY_RE.test(k);
+
+/** Coerce one untrusted value into an entry, or reject it. */
+export function readEntry(v: unknown): BibEntry | undefined {
+ if (!isObj(v)) return undefined;
+ const type = BIB_TYPES.includes(v.type as BibType) ? v.type as BibType : 'misc';
+ const out: BibEntry = { type };
+ for (const f of BIB_FIELDS) {
+ const raw = v[f];
+ if (typeof raw !== 'string' && typeof raw !== 'number') continue;
+ const s = cleanField(String(raw));
+ if (s) out[f] = s;
+ }
+ return out;
+}
+
+/**
+ * Read `doc.bibliography`, whatever is actually there.
+ *
+ * Absent is the normal case — every file written before this feature existed,
+ * and every file with no sources. It reads as an empty map, which is why older
+ * files stay readable (format additivity, PLATFORM §3).
+ */
+export function readBibliography(v: unknown): Bibliography {
+ const out: Bibliography = {};
+ if (!isObj(v)) return out;
+ for (const [k, raw] of Object.entries(v)) {
+ if (!validKey(k)) continue;
+ const e = readEntry(raw);
+ if (e) out[k] = e;
+ }
+ return out;
+}
+
+export function readStyle(v: unknown): CiteStyle {
+ return CITE_STYLES.includes(v as CiteStyle) ? v as CiteStyle : DEFAULT_STYLE;
+}
+
+/** Coerce one untrusted citation reference. Returns undefined if unusable. */
+export function readCiteRef(v: unknown, textLen: number): CiteRef | undefined {
+ if (!isObj(v) || typeof v.at !== 'number' || !Number.isFinite(v.at)) return undefined;
+ if (!Array.isArray(v.keys)) return undefined;
+ const keys = (v.keys as unknown[])
+ .filter((k): k is string => typeof k === 'string' && validKey(k))
+ .slice(0, 64);
+ if (!keys.length) return undefined;
+ const out: CiteRef = { at: Math.max(0, Math.min(Math.floor(v.at), textLen)), keys };
+ const loc = typeof v.locator === 'string' ? cleanField(v.locator).slice(0, 120) : '';
+ if (loc) out.locator = loc;
+ if (v.suppressAuthor === true) out.suppressAuthor = true;
+ return out;
+}
diff --git a/type/src/collab.css b/type/src/collab.css
new file mode 100644
index 00000000..1f722749
--- /dev/null
+++ b/type/src/collab.css
@@ -0,0 +1,96 @@
+/* SPDX-License-Identifier: MIT
+ Copyright (c) 2026 The Bento authors
+ Live-collaboration chrome for bento/type — Share button, popover, presence
+ strip, toast. Tokens are the shared suite set from styles.css (--ink,
+ --chrome, --chrome-2, --line, --muted, --accent, --good, --bad, --warnc,
+ --field); this file adds none of its own so a themed rebuild never forks. */
+
+.tc-presence { display: flex; align-items: center; gap: 4px; }
+
+.tc-avatar {
+ width: 24px; height: 24px; border-radius: 50%;
+ border: 2px solid var(--chrome);
+ color: #fff; font: 600 11px/1 system-ui, sans-serif;
+ display: flex; align-items: center; justify-content: center;
+ cursor: pointer; padding: 0;
+}
+.tc-avatar-more { background: var(--chrome-2); color: var(--ink-2); }
+
+.tc-wrap { position: relative; display: inline-flex; }
+
+/* `button.tc-share-btn` (not `.tc-share-btn`) — the button sits inside .t-bar,
+ whose own `.t-bar button` rule ties on specificity with a bare class
+ selector, and losing that tie would drop the border this button actually
+ needs (unlike its plain topbar siblings, it has live/connecting/off states
+ to show). The type-plus-class form outranks it outright. */
+button.tc-share-btn {
+ border: 1px solid var(--line); border-radius: 7px;
+ gap: 6px;
+}
+button.tc-share-btn::before {
+ content: ''; width: 7px; height: 7px; border-radius: 50%;
+ background: var(--muted); flex: none;
+}
+button.tc-share-btn.connecting::before { background: var(--warnc); }
+button.tc-share-btn.live::before { background: var(--good); }
+
+.tc-pop {
+ display: none;
+ position: absolute; top: calc(100% + 6px); inset-inline-end: 0;
+ width: 270px; max-height: 70vh; overflow-y: auto;
+ background: var(--field); border: 1px solid var(--line); border-radius: 10px;
+ box-shadow: 0 14px 40px rgb(0 0 0 / .22);
+ padding: 12px; z-index: 40;
+ font-size: 12.5px; color: var(--ink);
+}
+.tc-wrap.open .tc-pop { display: block; }
+
+.tc-name-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
+.tc-name-row label { color: var(--muted); font-size: 11.5px; }
+.tc-name-row input {
+ font: inherit; font-size: 12.5px; width: 120px;
+ border: 1px solid var(--line); border-radius: 6px; padding: 4px 7px;
+ background: var(--chrome); color: var(--ink);
+}
+
+.tc-label { font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); margin: 10px 0 5px; }
+.tc-label:first-child { margin-top: 0; }
+
+.tc-peer, .tc-me {
+ display: flex; align-items: center; gap: 7px; width: 100%;
+ border: none; background: transparent; border-radius: 6px;
+ padding: 5px 6px; text-align: start; cursor: default; color: inherit; font: inherit;
+}
+.tc-peer { cursor: pointer; }
+.tc-peer:hover { background: var(--chrome-2); }
+.tc-peer .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }
+.tc-peer .who, .tc-me .who { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tc-peer .where, .tc-me .where { color: var(--muted); font-size: 11px; flex: none; }
+.tc-me { opacity: .85; }
+
+.tc-peers { display: flex; flex-direction: column; margin-bottom: 4px; }
+
+.tc-status { font-weight: 600; margin: 8px 0; }
+.tc-status.ok { color: var(--good); }
+
+.tc-note { color: var(--muted); line-height: 1.5; margin: 6px 0; }
+
+.tc-sep { height: 1px; background: var(--line); margin: 10px 0; }
+
+.tc-btn {
+ display: block; width: 100%; text-align: start;
+ font: inherit; font-size: 12.5px; color: var(--ink);
+ background: transparent; border: 1px solid var(--line); border-radius: 7px;
+ padding: 7px 10px; margin-bottom: 6px; cursor: pointer;
+}
+.tc-btn:hover { background: var(--chrome-2); }
+.tc-btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
+.tc-btn-primary:hover { filter: brightness(1.04); }
+
+.tc-toast {
+ position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%);
+ background: var(--ink); color: var(--chrome); padding: 9px 15px; border-radius: 8px;
+ font-size: 12.5px; box-shadow: 0 10px 34px rgb(0 0 0 / .35);
+ opacity: 0; transition: opacity .18s; pointer-events: none; z-index: 99;
+}
+.tc-toast.on { opacity: 1; }
diff --git a/type/src/collab.ts b/type/src/collab.ts
new file mode 100644
index 00000000..7a361a2f
--- /dev/null
+++ b/type/src/collab.ts
@@ -0,0 +1,418 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Live collaboration for bento/type — the chrome nothing imported yet.
+//
+// type/src/sync/crdt.ts and type/src/sync/session.ts were complete facades
+// over the kernel engine, but until this file nothing in the app constructed
+// a SyncSession: no local edit ever became an op, no remote op was ever
+// applied, and there was no way for a person to find out the feature exists.
+// This is the missing wire: it builds the session, joins same-machine tabs
+// over BroadcastChannel unconditionally (that transport is always on — see
+// kernel/src/sync/session.ts), joins the online relay when the document is
+// share-eligible, and adds a Share control + a presence strip to the topbar.
+//
+// DORMANCY (docs/PLATFORM.md §5, learned the hard way on bento/slides
+// v0.9.0 → v0.9.1: v0.9.0 connected every visitor, including anonymous demo
+// traffic). A document that never carried collab credentials and whose author
+// never asked to share must not open a network connection just because it was
+// opened. `SyncSession` already encodes the rule — `shareEligible()` is true
+// only if the doc ARRIVED with `doc.collab` (a saved/shared file) or the user
+// called `enableSharing()` this session — and this module never routes around
+// it: `startSharing`/`enableSharing` are called ONLY from a click inside the
+// Share popover, never from initCollab itself.
+//
+// type's Editor (src/editor.ts) owns its contentEditable DOM directly and
+// never re-renders from a generic store event (see the caret-is-a-model-
+// position design in that file's header) — so unlike bento/slides, this
+// module has to explicitly ask the editor to redraw after a REMOTE change
+// (never after a local one, which the editor has already painted itself).
+// That is what the `onRemoteApplied` callback threaded through
+// sync/session.ts's SyncSession is for.
+
+import './collab.css';
+import { serializeAuto, writeUpdatedFileAs } from '../../kernel/src/save.ts';
+import { lsGet, lsSet } from '../../kernel/src/storage.ts';
+import { offlineEnabled } from '../../kernel/src/net.ts';
+import {
+ joinFromDoc, mintInvite, onlineTransport, rotateKeys,
+ sharingOn, startSharing, stopSharing,
+} from './sync/online.ts';
+import { SyncSession, hostStore, type Peer, type SyncNotice } from './sync/session.ts';
+import type { Store } from './store.ts';
+import type { Editor } from './editor.ts';
+import type { TypeDoc } from './model.ts';
+
+// ─────────────────────────────────────────────────────────────── small DOM
+
+function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string): HTMLElementTagNameMap[K] {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ return n;
+}
+
+let toastEl: HTMLElement | null = null;
+let toastT: number | undefined;
+function toast(msg: string) {
+ if (!toastEl) {
+ toastEl = el('div', 'tc-toast');
+ document.body.appendChild(toastEl);
+ }
+ toastEl.textContent = msg;
+ toastEl.classList.add('on');
+ clearTimeout(toastT);
+ toastT = setTimeout(() => toastEl!.classList.remove('on'), 2400) as unknown as number;
+}
+
+function noticeText(n: SyncNotice): string {
+ switch (n.code) {
+ case 'too-large':
+ return n.media
+ ? 'That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.'
+ : 'That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.';
+ case 'room-full':
+ return 'This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.';
+ case 'storage-failed':
+ return 'The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.';
+ case 'rate-limited':
+ return 'Too many changes at once — live sync is catching up.';
+ }
+}
+
+/** A copy sent for someone else to work on must not carry the owner's keys. */
+function stripCollabSecrets(doc: TypeDoc, opts: { keepRoom?: boolean } = {}) {
+ if (!doc.collab) return;
+ if (!opts.keepRoom) { delete doc.collab; return; }
+ delete doc.collab.ownerPriv;
+ delete doc.collab.invite;
+}
+
+/** Where a peer is, in terms someone reading the sidebar understands. */
+function blockLabel(doc: TypeDoc, blockId: string): string {
+ const i = doc.body.findIndex(b => b.id === blockId);
+ if (i < 0) return '';
+ return `¶ ${i + 1} of ${doc.body.length}`;
+}
+
+// ───────────────────────────────────────────────────────────────── the wire
+
+export function initCollab(store: Store, editor: Editor): void {
+ const paper = document.getElementById('paper');
+
+ const session = new SyncSession(
+ store,
+ () => ({ block: editor.caret()?.id ?? '' }),
+ () => { editor.render(); repaint(); },
+ );
+
+ // Connect to the relay if the current doc is live AND share-eligible.
+ // Same-machine tabs already sync unconditionally (BroadcastChannel, wired
+ // inside SyncSession's own constructor) — this only concerns the online
+ // relay, which is the half that could phone home for an anonymous visitor.
+ function tryJoin() {
+ if (sharingOn(hostStore(store)) && session.shareEligible() && !onlineTransport()) {
+ joinFromDoc(session, hostStore(store));
+ wireOnlineStatus();
+ }
+ }
+ tryJoin();
+ store.on(() => tryJoin());
+
+ // Sharing sends the CRDT state along with every saved copy (doc.collab.sync)
+ // so an offline-edited copy can rejoin as a true fork later (PLATFORM §5).
+ // Debounced rather than hooked to the Save button: this module owns no part
+ // of main.ts's save() beyond the one initialisation call it was given, and
+ // a stamp that is at most a beat stale is exactly as good as one taken at
+ // the instant of the click — the state itself is already flushed/diffed.
+ let stampT: number | undefined;
+ store.on(() => {
+ if (!sharingOn(hostStore(store))) return;
+ clearTimeout(stampT);
+ stampT = setTimeout(() => session.stampInto(store.doc), 500) as unknown as number;
+ });
+
+ // ── topbar: Share button + presence strip ────────────────────────────────
+
+ // Mounted into `.t-right`, the bar's right-hand cluster.
+ //
+ // This originally anchored to `.t-spacer`, which does not exist in this
+ // app's markup — and the `if (bar && spacer)` guard below turned that into a
+ // SILENT no-op: the engine wired up, credentials minted, and no Share button
+ // ever appeared. A lookup that returns null behind a truthiness guard is the
+ // recurring way chrome goes missing here without anything looking broken.
+ const bar = document.querySelector('.t-bar');
+ const spacer = document.querySelector('#theme') ?? document.querySelector('#save');
+ const presenceBox = el('div', 'tc-presence');
+ const wrap = el('div', 'tc-wrap');
+ const shareB = el('button', 'tc-share-btn');
+ shareB.textContent = 'Share';
+ shareB.title = 'Share — invite people to edit live, or send a view-only copy';
+ const popover = el('div', 'tc-pop');
+ wrap.append(shareB, popover);
+ const host = spacer?.parentElement ?? bar;
+ if (host && spacer) {
+ host.insertBefore(presenceBox, spacer);
+ host.insertBefore(wrap, spacer);
+ } else {
+ // Never fail silently again: if the anchor is gone, say so loudly enough
+ // that the next person sees it in the console instead of wondering where
+ // the Share button went.
+ console.warn('[collab] topbar anchor not found — Share button not mounted');
+ }
+
+ shareB.addEventListener('click', () => {
+ wrap.classList.toggle('open');
+ if (wrap.classList.contains('open')) renderPanel();
+ });
+ document.addEventListener('pointerdown', (ev) => {
+ if (!wrap.contains(ev.target as Node)) wrap.classList.remove('open');
+ });
+
+ function wireOnlineStatus() {
+ const tr = onlineTransport();
+ if (!tr) {
+ shareB.classList.remove('live', 'connecting');
+ shareB.title = 'Not sharing yet — click to start a live session';
+ return;
+ }
+ tr.onStatus = () => wireOnlineStatus();
+ shareB.classList.toggle('live', tr.status === 'open');
+ shareB.classList.toggle('connecting', tr.status !== 'open');
+ shareB.title = tr.status === 'open'
+ ? 'Live — this document is being shared'
+ : 'Connecting to the live session…';
+ if (wrap.classList.contains('open')) renderPanel();
+ }
+
+ function repaint() {
+ renderPresence();
+ if (wrap.classList.contains('open')) renderPanel();
+ }
+
+ function renderPresence() {
+ presenceBox.replaceChildren();
+ const peers = session.peers();
+ const MAX = 3;
+ for (const p of peers.slice(0, MAX)) {
+ const chip = el('button', 'tc-avatar');
+ chip.style.background = p.color;
+ chip.textContent = (p.name || '?').trim().charAt(0).toUpperCase() || '?';
+ chip.title = `${p.name} — ${blockLabel(store.doc, p.slide) || 'in the document'} (click to follow)`;
+ chip.addEventListener('click', () => {
+ const node = paper?.querySelector<HTMLElement>(`[data-id="${CSS.escape(p.slide)}"]`);
+ node?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ });
+ presenceBox.appendChild(chip);
+ }
+ const extra = peers.length - MAX;
+ if (extra > 0) {
+ const more = el('button', 'tc-avatar tc-avatar-more');
+ more.textContent = `+${extra}`;
+ more.title = `${extra} more — click to see everyone`;
+ more.addEventListener('click', () => { wrap.classList.add('open'); renderPanel(); });
+ presenceBox.appendChild(more);
+ }
+ }
+
+ let known = new Map(session.peers().map(p => [p.actor, p.name]));
+ session.onPeers(() => {
+ repaint();
+ const now = new Map(session.peers().map(p => [p.actor, p.name]));
+ if (now.size <= 8) {
+ for (const [actor, name] of now) if (!known.has(actor)) toast(`${name} joined`);
+ for (const [actor, name] of known) if (!now.has(actor)) toast(`${name} left`);
+ }
+ known = now;
+ });
+ session.onNotice((n) => toast(noticeText(n)));
+
+ // ── the popover itself ────────────────────────────────────────────────
+
+ function action(label: string, primary: boolean, onClick: () => void, title = ''): HTMLButtonElement {
+ const b = el('button', primary ? 'tc-btn tc-btn-primary' : 'tc-btn');
+ b.textContent = label;
+ if (title) b.title = title;
+ b.addEventListener('click', onClick);
+ popover.appendChild(b);
+ return b;
+ }
+ function note(text: string): HTMLElement {
+ const n = el('div', 'tc-note');
+ n.textContent = text;
+ popover.appendChild(n);
+ return n;
+ }
+
+ async function goLive() {
+ if (offlineEnabled()) return;
+ session.enableSharing();
+ await startSharing(session, hostStore(store));
+ wireOnlineStatus();
+ }
+
+ async function inviteToEdit() {
+ await goLive();
+ const c = store.doc.collab;
+ if (!(c?.room && c.key && c.v === 2 && c.ownerPriv)) {
+ toast('Only the document owner can mint editor invites');
+ return;
+ }
+ session.stampInto(store.doc);
+ const clone: TypeDoc = JSON.parse(JSON.stringify(store.doc));
+ stripCollabSecrets(clone, { keepRoom: true });
+ clone.collab!.invite = await mintInvite(c.ownerPriv, 'writer');
+ clone.collab!.on = true;
+ try {
+ const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'invite' });
+ if (ok) toast('Editor copy saved — recipients join live with edit access');
+ } catch {
+ toast('Saving failed');
+ }
+ }
+
+ async function saveViewOnlyCopy() {
+ await goLive();
+ const c = store.doc.collab;
+ if (!c?.room || !c.key) { toast('This document has no live session to follow'); return; }
+ const clone: TypeDoc = JSON.parse(JSON.stringify(store.doc));
+ clone.collab = { ...c, role: 'reader', on: true, sync: undefined };
+ stripCollabSecrets(clone, { keepRoom: true });
+ try {
+ const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'viewonly' });
+ if (ok) toast('View-only copy saved — it follows the live session');
+ } catch {
+ toast('Saving failed');
+ }
+ }
+
+ function renderPanel() {
+ popover.replaceChildren();
+
+ const nameRow = el('div', 'tc-name-row');
+ nameRow.title = 'Shown next to your cursor and in the People list — stored only in this browser.';
+ const nameLabel = el('label');
+ nameLabel.textContent = 'Your name';
+ const nameInput = el('input');
+ nameInput.type = 'text';
+ nameInput.placeholder = 'Guest';
+ nameInput.value = lsGet('bento-author') ?? '';
+ nameInput.addEventListener('change', () => {
+ lsSet('bento-author', nameInput.value.trim());
+ session.hello();
+ });
+ nameRow.append(nameLabel, nameInput);
+ popover.appendChild(nameRow);
+
+ const cme = store.doc.collab;
+ const roleLabel = (r?: string) => r === 'owner' ? 'Owner' : r === 'viewer' ? 'Viewer' : r === 'editor' ? 'Editor' : '';
+
+ if (cme) {
+ let myRole: 'owner' | 'editor' | 'viewer' | undefined;
+ if (cme.role === 'reader') myRole = 'viewer';
+ else if (cme.v === 2 && cme.ownerPriv) myRole = 'owner';
+ else if (cme.v === 2 && cme.invite) myRole = 'editor';
+ if (myRole) {
+ const label = el('div', 'tc-label');
+ label.textContent = 'People';
+ popover.appendChild(label);
+ const me = el('div', 'tc-peer tc-me');
+ const who = el('span', 'who');
+ who.textContent = `${lsGet('bento-author') || 'Guest'} (you)`;
+ const where = el('span', 'where');
+ where.textContent = roleLabel(myRole);
+ me.append(who, where);
+ popover.appendChild(me);
+ }
+ }
+
+ const peers = session.peers();
+ if (peers.length) {
+ const list = el('div', 'tc-peers');
+ for (const peer of peers as Peer[]) {
+ const row = el('button', 'tc-peer');
+ const dot = el('span', 'dot');
+ dot.style.background = peer.color;
+ const who = el('span', 'who');
+ who.textContent = peer.name;
+ const where = el('span', 'where');
+ where.textContent = [roleLabel(peer.role), blockLabel(store.doc, peer.slide)].filter(Boolean).join(' · ');
+ row.append(dot, who, where);
+ row.title = `${peer.name} — click to follow`;
+ row.addEventListener('click', () => {
+ const node = paper?.querySelector<HTMLElement>(`[data-id="${CSS.escape(peer.slide)}"]`);
+ node?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ });
+ list.appendChild(row);
+ }
+ popover.appendChild(list);
+ }
+
+ if (offlineEnabled()) {
+ note('Offline mode is on — nothing leaves this computer.');
+ note('Tabs on this machine still sync; turn offline mode off to collaborate online.');
+ return;
+ }
+
+ const tr = onlineTransport();
+ const on = sharingOn(hostStore(store)) && !!tr;
+ const status = note('');
+ status.classList.add('tc-status');
+ if (on) {
+ const n = session.peers().length + 1;
+ status.textContent = tr!.status === 'open' ? `● Live — ${n} connected` : '● Connecting…';
+ status.classList.toggle('ok', tr!.status === 'open');
+ } else {
+ status.textContent = '○ Not live — turns on when you share';
+ }
+
+ const canWrite = !!cme && cme.role !== 'reader';
+ if (canWrite) {
+ const label = el('div', 'tc-label');
+ label.textContent = 'Share a copy';
+ popover.appendChild(label);
+ action('Invite to edit…', true, () => void inviteToEdit(),
+ 'Saves a copy to send. Whoever opens it edits this document live with you; you stay the owner and can remove them from the People list.');
+ action('View-only copy…', false, () => void saveViewOnlyCopy(),
+ 'A live viewer: follows every edit as it happens but can never change the document.');
+ } else {
+ note('This is a view-only copy — it follows the live session but can’t change the document.');
+ }
+
+ if (canWrite) {
+ popover.appendChild(el('div', 'tc-sep'));
+ if (on) {
+ action('Stop sharing', false, () => {
+ stopSharing(session, hostStore(store));
+ wireOnlineStatus();
+ renderPanel();
+ }, 'Disconnect this document from the live session. Copies keep their last state and can rejoin if you go live again.');
+ } else {
+ action('Go live', false, () => void goLive().then(renderPanel),
+ 'Connect to the live session without saving a new copy — copies you sent earlier will meet you there.');
+ }
+ action('Reset access…', false, async () => {
+ if (!confirm('Reset access? Every copy you’ve sent stops syncing; only copies saved after this can join.')) return;
+ await rotateKeys(session, hostStore(store));
+ toast('Access reset — only copies saved from now on can join');
+ renderPanel();
+ }, 'Mints brand-new keys. Every previously sent copy stops syncing for good; share fresh copies afterwards.');
+ }
+ }
+
+ renderPresence();
+ wireOnlineStatus();
+
+ // scripting surface, per PLATFORM §7 (mirrors bento/slides window.bento.sync)
+ const w = window as unknown as { bento?: Record<string, unknown> };
+ if (w.bento) {
+ w.bento.sync = {
+ get actor() { return session.actor; },
+ peers: () => session.peers(),
+ flush: () => session.flush(),
+ transports: () => session.transportKinds,
+ share: () => { void goLive(); return store.doc.collab; },
+ unshare: () => stopSharing(session, hostStore(store)),
+ online: () => onlineTransport()?.status ?? 'off',
+ };
+ }
+}
diff --git a/type/src/comments.css b/type/src/comments.css
new file mode 100644
index 00000000..f113617e
--- /dev/null
+++ b/type/src/comments.css
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: MIT */
+/* Copyright (c) 2026 The Bento authors */
+
+/* Author identity + comment edit/delete — the feature-local styles for
+ comments.ts (thread edit/delete controls) and about.ts (the "You" name
+ field). Kept out of styles.css because that file is owned by other work
+ happening on this app in parallel; this file is imported directly from
+ comments.ts, and vite folds it into the single shipped <style> tag same as
+ every other app stylesheet. */
+
+/* ---- "You" name field, About dialog ------------------------------------ */
+
+.t-about-name-input {
+ width: 100%;
+ max-width: 220px;
+ font: inherit;
+ font-size: 12px;
+ padding: 4px 7px;
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ background: var(--field, var(--chrome));
+ color: var(--ink);
+}
+.t-about-name-input:focus { border-color: var(--blue, var(--accent)); outline: none; }
+
+/* ---- per-message edit/delete -------------------------------------------
+ Small ghost buttons beside a message's byline, shown only on a message
+ whose author matches the name currently in localStorage — see
+ comments.ts buildMessage() for why that is an honour-system check, not
+ access control. */
+
+.t-cmt-msgtools {
+ float: inline-end;
+ display: inline-flex;
+ gap: 4px;
+ margin-inline-start: 6px;
+}
+.t-cmt-msgbtn {
+ font: inherit;
+ font-size: 10px;
+ line-height: 1.4;
+ padding: 1px 5px;
+ border-radius: 4px;
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--muted);
+ cursor: pointer;
+}
+.t-cmt-msgbtn:hover { background: var(--chrome-2); color: var(--ink); border-color: var(--line); }
+
+/* In-place edit box — sized and styled to match the reply textarea
+ (.acts textarea in styles.css) so a message being edited doesn't look
+ like a different control from the one you'd reply with. */
+.t-cmt-edit {
+ display: block;
+ width: 100%;
+ box-sizing: border-box;
+ font: inherit;
+ font-size: 12px;
+ padding: 5px 7px;
+ margin-top: 3px;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ background: var(--field, var(--chrome));
+ color: var(--ink);
+ resize: vertical;
+}
diff --git a/type/src/comments.ts b/type/src/comments.ts
new file mode 100644
index 00000000..d4d15f22
--- /dev/null
+++ b/type/src/comments.ts
@@ -0,0 +1,1112 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Comments — margin notes on a RANGE of text, with replies and resolution.
+//
+// The thing every reviewed document needs, and the last review surface this app
+// was missing: redline.ts answers "what changed", comments answer "why, and
+// what do you think". A redline is a diff between two revisions; a comment is a
+// conversation about text that has not changed at all, which is most of the
+// text a reviewer has something to say about.
+//
+// ─────────────────────────────────────────────────────────── the four choices
+//
+// 1. A COMMENT IS A DOC-LEVEL RECORD, KEYED BY ID — `doc.comments`, exactly the
+// shape `doc.footnotes` already uses. Not nested into the block it points
+// at. The document is FLAT (model.ts explains why: the redline aligns on
+// block ids, the caret is (blockId, offset), pagination walks line boxes),
+// and a thread hanging off a block would put a second kind of nesting under
+// all three. It also has to outlive its block — see orphans below — which a
+// field on the block cannot do by construction.
+//
+// 2. THE ANCHOR IS A CHARACTER RANGE INTO PLAIN TEXT, and it moves with the
+// text using inline.ts `shift` — the SAME function marks use and the same
+// rule footnote anchors follow. Not a copy of it. A comment whose range
+// drifts onto the wrong words is worse than no comment, and the way that
+// happens is a second implementation of offset arithmetic that is 95%
+// identical to the first. There is one implementation; this module wraps a
+// range in a carrier mark and asks `shift` to move it. Everything an author
+// can anchor into a block's text — a mark, a footnote, a comment — therefore
+// moves identically, and there is one place to get it right.
+//
+// 3. A COMMENT WHOSE TEXT IS DELETED IS ORPHANED, NEVER DROPPED. See below.
+//
+// 4. NOTHING IS DRAWN INSIDE THE EDITABLE. Highlights are rectangles painted
+// into an OVERLAY layer, computed from `Range.getClientRects()` — the same
+// technique paginate.ts uses to place its sidenotes, and for the same
+// reason: decorations inserted into the flow enter the undo stack, confuse
+// the caret's offset walk, and get destroyed on the next re-render anyway.
+//
+// ─────────────────────────────────────────────── how comments stay out of print
+//
+// STRUCTURALLY, not by a flag. print.ts builds its flow in `bodyHtml`, which
+// emits `blockHtml(b)` per block; `blockHtml` reads exactly `b.text`, `b.marks`
+// and `b.notes`. It never reads `doc.comments`, and this module never writes a
+// mark, a note, or a character into a block — the highlight is an absolutely
+// positioned <div> in a sibling overlay of `.t-paper`, and the margin cards are
+// in that same overlay. There is no code path from a comment to the printed
+// string, so no print-time exclusion is needed and none can be forgotten. (The
+// tempting shortcut — a `t:'comment'` mark — is exactly what would have printed
+// a yellow highlight onto every executed copy of a contract.) Verified in the
+// rig: `buildPrintDocument` output of a commented document contains no comment
+// text and is byte-identical to the same document with `comments` removed.
+//
+// ───────────────────────────────────────────────────────── NEEDS FROM THE CORE
+//
+// This module is complete and testable WITHOUT the following. Each one is a
+// call site the core owns; until they land, a comment's anchor survives every
+// edit that goes through `commentsOnEdit` (which nothing calls yet) and is
+// repaired defensively on every read by `reconcileThreads` — so nothing is ever
+// wrong, only coarse: after an unhooked edit a range is clamped to the block
+// and orphaned if it no longer fits, rather than tracked character by character.
+//
+// (A) type/src/model.ts — declare the field, and repair it at parse time.
+//
+// After `NoteRef`, add:
+//
+// /** comment id → thread. Doc-level and keyed by id, like footnotes:
+// * a thread must be able to outlive the block it points at. */
+// export interface CommentMsg { id: string; author: string; at: string; text: string }
+// export interface CommentThread {
+// id: string; block: string; from: number; to: number;
+// quote: string; messages: CommentMsg[];
+// resolved?: boolean; orphan?: boolean;
+// }
+//
+// and on `TypeDoc`, beside `footnotes`:
+//
+// comments?: Record<string, CommentThread>;
+//
+// WHY: format additivity means an unknown `comments` key already rides
+// through `parseDoc` untouched (the `...json` spread), so old files open in
+// a new build and NEW FILES OPEN IN AN OLD BUILD with the comments intact
+// but invisible — which is the additivity requirement, already met. The
+// field is wanted for two other reasons: so `tsc` types it instead of this
+// module casting through the index signature, and so `parseDoc` can repair
+// a hand-edited or generator-produced file (drop a thread with no messages,
+// clamp `from`/`to` into the block, detach a thread whose block is missing
+// or whose range is degenerate) deterministically, the way it already
+// repairs dangling footnote refs. That repair is already written here, pure
+// and in two halves, so `parseDoc` can call it directly:
+//
+// const list = reconcileThreads(readThreadsRaw(json), body);
+// if (list.length) doc.comments = Object.fromEntries(list.map(t => [t.id, t]));
+//
+// Note the ORDER, which matters: `readThreadsRaw` is the total parse and
+// `reconcileThreads` is the repair, and the edit hooks in (B) deliberately
+// use only the first — repairing before moving an anchor clamps it against
+// a body that has already changed.
+//
+// (B) type/src/editor.ts — three one-line calls, so an anchor tracks an edit
+// exactly rather than being repaired approximately.
+//
+// import { commentsOnEdit, commentsOnSplit, commentsOnMerge } from './comments.ts';
+//
+// · in `#input`, inside the existing `this.store.commit(d => { … })`
+// callback, after `d.body[i] = next`:
+// commentsOnEdit(d, c.id, prev.text, next.text);
+// WHY inside the commit: it must land in the same undo snapshot as the
+// text, or ⌘Z restores the words and leaves the anchor where the edit
+// put it. The snapshot scope is `{ block }` today, which does not cover
+// `doc.comments` — so this call also needs the scope widened to 'doc'
+// for the commits that move a comment, OR (cheaper, and what I would do)
+// `commentsOnEdit` returning false when it changed nothing, which it
+// does: a block carrying no comments never widens anybody's undo.
+// · in `#splitBlock`, inside its commit, after the splice:
+// commentsOnSplit(d, src.id, c.at, src.text.length, tail.id);
+// · in `#mergeBack`, inside its commit, after the splice:
+// commentsOnMerge(d, prev.id, cur.id, at);
+//
+// (C) type/src/print.ts — NOTHING. Deliberately. See above.
+//
+// (D) type/src/icons.ts — optional. `COMMENT_ICON` below follows the house
+// recipe exactly (24×24 box, rendered 16px, stroke currentColor, width 2,
+// round caps and joins) and lives here only because this module owns its
+// own file. Moving it to `ICONS.comment` is a pure lift.
+//
+// (E) type/src/main.ts — optional. `PanelSpec.update` is declared in
+// features.ts and never called; this module therefore drives its own
+// repaints from `store.on` and a MutationObserver on the paper, which is
+// self-contained and needs no change. If main.ts ever starts calling
+// `spec.update`, this panel is already idempotent.
+
+import { shift, type Mark } from './inline.ts';
+import { isNoteAtom } from './render.ts';
+import { uid, type Block, type TypeDoc } from './model.ts';
+import { registerTool, registerPanel, registerKey, registerMenuItem, registerReady, type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+// NOT `import './comments.css'` here: model.ts imports this module's pure
+// functions (readThreadsRaw, reconcileThreads) for parsing, and model.ts is
+// imported by nearly every test rig under plain Node, which cannot load a
+// bare `.css` specifier the way Vite does. about.ts is always loaded by
+// main.ts (never lazily) and no rig imports it, so it is the safe place that
+// pulls comments.css into the bundle — see about.ts.
+
+// ───────────────────────────────────────────────────────────────── the shape
+
+/** One message in a thread. The first is the comment; the rest are replies. */
+export interface CommentMsg {
+ id: string;
+ /** self-asserted, from localStorage 'bento-author'. A claim, not an identity —
+ * signatures (canon.ts) are the only thing in this document that proves who. */
+ author: string;
+ /** ISO wall clock, display only */
+ at: string;
+ /** CONTENT, not UI: never passed through t() */
+ text: string;
+}
+
+export interface CommentThread {
+ id: string;
+ /** the block this points into */
+ block: string;
+ /** character offsets into that block's PLAIN text — same coordinates as a
+ * mark and a footnote anchor, moved by the same function */
+ from: number;
+ to: number;
+ /**
+ * The anchored text, captured when the comment was made.
+ *
+ * Not a cache: it is the thread's only self-description once the text it
+ * pointed at is gone. "Is this enforceable?" with no idea what "this" was is
+ * not a comment, it is a riddle.
+ */
+ quote: string;
+ messages: CommentMsg[];
+ resolved?: boolean;
+ /**
+ * The anchor no longer exists: its block was deleted, or its words were.
+ *
+ * ORPHANS ARE KEPT, and this is the whole policy. Three options were on the
+ * table and two of them are wrong:
+ *
+ * · DROP the thread — silently destroys review conversation, and it does it
+ * precisely when somebody deletes the clause that was being argued about,
+ * which is the moment the argument matters most.
+ * · KEEP THE OFFSETS LIVE — the comment then points at whatever text has
+ * since flowed into those offsets, so "this indemnity is uncapped" ends
+ * up attached to the notices clause. Worse than no comment, because it
+ * is confidently wrong.
+ * · ORPHAN — the thread stays in the file with its conversation and its
+ * `quote` intact, `block`/`from`/`to` frozen as a record of where it USED
+ * to be, and this flag set. It is not highlighted (there is nothing to
+ * highlight), it is not clickable-to-scroll, and the panel lists it in a
+ * "detached" group saying which words it was about. A human decides
+ * whether it is finished; the app never decides for them.
+ *
+ * ONCE SET BY AN EDIT, THIS PERSISTS. The first version of this file derived
+ * the flag on every read instead — "never trust the file" — and it was wrong
+ * in a way the rig caught: a thread whose words were deleted keeps its old
+ * `from`/`to` as the record of where it was, and those numbers are usually
+ * still inside the (now shorter) block, so re-deriving cheerfully un-orphaned
+ * it and pointed it at whatever had flowed into those offsets. That is the
+ * exact failure the orphan policy exists to prevent.
+ *
+ * Undo still resurrects a thread, and does it properly: the store snapshots
+ * the whole document, so undoing the deletion restores the comment map as it
+ * was before it — flag and offsets together — rather than reconstructing a
+ * guess. `reconcileThreads` therefore only ever ADDS this flag, never clears
+ * it. What it adds is transient (a read does not write back), which is what
+ * lets a thread whose BLOCK is missing come back by itself if the block
+ * returns — a redline rejection re-inserting a deleted paragraph does exactly
+ * that.
+ */
+ orphan?: boolean;
+}
+
+/** Where a thread's anchor is, as bare offsets. */
+export interface Anchor { from: number; to: number }
+
+const AUTHOR_KEY = 'bento-author'; // shared with bento/slides, on purpose
+
+// ─────────────────────────────────────────────────── reading and writing them
+//
+// `doc.comments` is reached through TypeDoc's `[extra: string]: unknown` index
+// signature until (A) above lands. Centralised in these two functions so that
+// when it does, this is the only edit.
+
+type Commented = { comments?: Record<string, CommentThread> };
+const asCommented = (doc: TypeDoc): Commented => doc as unknown as Commented;
+
+const isObj = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v);
+
+/**
+ * Every thread in the document, EXACTLY as stored — no repair.
+ *
+ * Total: a `comments` field of any shape at all yields a valid list, because
+ * this runs on files a generator or a hand edit produced. A thread with no
+ * messages is not a thread and is the one thing dropped — there is no
+ * conversation in it to preserve.
+ *
+ * The edit hooks below read through THIS, not `readThreads`. They are told the
+ * exact edit and know how to move an anchor through it; running the defensive
+ * repair first would clamp anchors against the already-mutated body and destroy
+ * the very offsets the hook was about to move. That ordering bug is real and
+ * the rig caught it: a comment in the tail of a split paragraph was clamped
+ * against the truncated head, orphaned, and then skipped by the split.
+ */
+export function readThreadsRaw(doc: TypeDoc): CommentThread[] {
+ const raw = asCommented(doc).comments;
+ if (!isObj(raw)) return [];
+ const out: CommentThread[] = [];
+ for (const [key, v] of Object.entries(raw)) {
+ if (!isObj(v)) continue;
+ const messages = Array.isArray(v.messages)
+ ? (v.messages as unknown[]).filter(isObj).map((m, i) => ({
+ id: typeof m.id === 'string' && m.id ? m.id : `${key}-m${i}`,
+ author: typeof m.author === 'string' ? m.author : '',
+ at: typeof m.at === 'string' ? m.at : '',
+ text: typeof m.text === 'string' ? m.text : '',
+ }))
+ : [];
+ if (!messages.length) continue;
+ // NOT sorted into order and not clamped here: a stored range of (9e9, -3)
+ // is garbage, and quietly repairing it into "the whole paragraph" would
+ // attach somebody's comment to text they never selected. Left as read, so
+ // reconcileThreads sees a degenerate range and orphans it — which says
+ // "this pointed somewhere that no longer makes sense", which is the truth.
+ const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? Math.floor(v) : 0;
+ const from = num(v.from), to = num(v.to);
+ out.push({
+ id: typeof v.id === 'string' && v.id ? v.id : key,
+ block: typeof v.block === 'string' ? v.block : '',
+ from, to,
+ quote: typeof v.quote === 'string' ? v.quote : '',
+ messages,
+ ...(v.resolved === true ? { resolved: true as const } : {}),
+ ...(v.orphan === true ? { orphan: true as const } : {}),
+ });
+ }
+ return out;
+}
+
+/** Every thread, repaired against the current body — what every reader wants. */
+export const readThreads = (doc: TypeDoc): CommentThread[] =>
+ reconcileThreads(readThreadsRaw(doc), doc.body);
+
+/** Put a thread list back, as the id-keyed map the format stores. */
+export function writeThreads(doc: TypeDoc, threads: CommentThread[]): void {
+ const d = asCommented(doc);
+ if (!threads.length) { delete d.comments; return; }
+ const map: Record<string, CommentThread> = {};
+ for (const th of threads) map[th.id] = th;
+ d.comments = map;
+}
+
+// ───────────────────────────────────────────────────────── anchor maintenance
+//
+// All pure. This is the part that must not be wrong.
+
+/**
+ * A range wrapped as a MARK, so inline.ts `shift` can move it.
+ *
+ * The carrier's type is arbitrary and never rendered or stored — `shift` only
+ * ever reads `from`/`to`, and `normalize` (which it ends with) only cares that
+ * a mark of zero width is dropped, which is exactly the signal this module
+ * wants for "the anchored text is gone".
+ *
+ * This indirection is the point of the whole file. Marks, footnote anchors and
+ * comment anchors are three names for one problem, and the moment any of them
+ * gets its own arithmetic they start disagreeing under an edit that straddles a
+ * boundary — the failure mode being a comment sitting one word to the left of
+ * the sentence it is about, which nobody notices until a contract is signed.
+ */
+const CARRIER: Mark['t'] = 'b';
+
+/**
+ * Move a range to follow an edit that replaced [at, at+removed) with `added`
+ * characters, against a text of final length `len`.
+ *
+ * Returns null when the range no longer covers anything — the anchored text was
+ * deleted outright. The caller decides what that means; here it means orphan.
+ *
+ * The behaviour at the two edges is inherited, deliberately, rather than chosen:
+ * an insertion exactly AT `from` joins the range and one exactly AT `to` does
+ * not, because that is what `shift` does to a mark, and a comment highlight
+ * that grew differently from the bold underneath it would look like a bug in
+ * one of them.
+ */
+export function shiftAnchor(a: Anchor, at: number, removed: number, added: number, len: number): Anchor | null {
+ const moved = shift([{ t: CARRIER, from: a.from, to: a.to }], at, removed, added, len);
+ if (!moved.length) return null;
+ return { from: moved[0].from, to: moved[0].to };
+}
+
+/**
+ * The minimal edit between two versions of one block's text, as
+ * (at, removed, added) — a common-prefix / common-suffix trim.
+ *
+ * The editor rebuilds a whole block from the DOM on every `input` (render.ts
+ * readBlock) rather than reporting a splice, so the splice has to be recovered
+ * here. Minimal matters: treating a keystroke as "replaced the entire
+ * paragraph" would orphan every comment in it on the first character typed.
+ *
+ * Returns null when the text did not change.
+ */
+export function textEdit(prev: string, next: string): { at: number; removed: number; added: string } | null {
+ if (prev === next) return null;
+ const max = Math.min(prev.length, next.length);
+ let p = 0;
+ while (p < max && prev[p] === next[p]) p++;
+ let s = 0;
+ while (s < max - p && prev[prev.length - 1 - s] === next[next.length - 1 - s]) s++;
+ return { at: p, removed: prev.length - p - s, added: next.slice(p, next.length - s) };
+}
+
+/** Move one thread through an edit in ITS block. Pure; returns a new thread. */
+export function shiftThread(th: CommentThread, at: number, removed: number, added: number, len: number): CommentThread {
+ const moved = shiftAnchor({ from: th.from, to: th.to }, at, removed, added, len);
+ // The frozen from/to are kept as the record of where it was — see `orphan`.
+ if (!moved) return { ...th, orphan: true };
+ const out: CommentThread = { ...th, from: moved.from, to: moved.to };
+ delete out.orphan;
+ return out;
+}
+
+/** Move every thread anchored in `blockId` through one edit. Pure. */
+export function shiftThreads(threads: CommentThread[], blockId: string,
+ at: number, removed: number, added: number, len: number): CommentThread[] {
+ return threads.map(th =>
+ th.block === blockId && !th.orphan ? shiftThread(th, at, removed, added, len) : th);
+}
+
+/**
+ * Follow a paragraph SPLIT: `srcId` was cut at `at`, the head keeping `srcId`
+ * and the tail becoming `tailId`.
+ *
+ * A thread that straddles the cut cannot be in two places, and the two obvious
+ * answers are both bad: dropping it destroys a live conversation over an edit
+ * that changed no words at all, and duplicating it makes one comment that two
+ * people must now resolve twice. It goes to the side holding MORE of the text
+ * it was about, clipped — which is the side a reader would point at.
+ */
+export function splitThreads(threads: CommentThread[], srcId: string, at: number,
+ srcLen: number, tailId: string): CommentThread[] {
+ const tailLen = srcLen - at;
+ return threads.map(th => {
+ if (th.block !== srcId || th.orphan) return th;
+ if (th.to <= at) return th; // wholly in the head
+ if (th.from >= at) { // wholly in the tail
+ return { ...th, block: tailId, from: th.from - at, to: Math.min(th.to - at, tailLen) };
+ }
+ const inHead = at - th.from, inTail = th.to - at;
+ if (inTail > inHead) return { ...th, block: tailId, from: 0, to: Math.min(inTail, tailLen) };
+ return { ...th, to: at };
+ });
+}
+
+/**
+ * Follow a paragraph MERGE: `curId` was appended to `prevId` at offset `at`.
+ * Nothing is lost — a merge only concatenates — so every anchor survives.
+ */
+export function mergeThreads(threads: CommentThread[], prevId: string, curId: string, at: number): CommentThread[] {
+ return threads.map(th =>
+ th.block === curId && !th.orphan
+ ? { ...th, block: prevId, from: th.from + at, to: th.to + at }
+ : th);
+}
+
+/**
+ * Repair every thread against the body, and set or CLEAR `orphan`.
+ *
+ * A NET, NOT A DERIVATION. It only ever ADDS the flag — see `orphan` for the
+ * bug that taught the difference. Its job is to make this module safe before
+ * the editor hooks in (B) exist, and safe against files nothing in this app
+ * wrote: the worst an untracked edit or a bad generator can do is clamp a range
+ * or detach a thread, never point one somewhere false.
+ *
+ * Runs on every read and writes nothing back, so what it adds is transient —
+ * which is what lets a thread whose block is missing come back by itself when
+ * the block returns.
+ */
+export function reconcileThreads(threads: CommentThread[], body: readonly Block[]): CommentThread[] {
+ const byId = new Map(body.map(b => [b.id, b]));
+ return threads.map(th => {
+ if (th.orphan) return th; // already detached; leave the record alone
+ const blk = byId.get(th.block);
+ if (!blk) return { ...th, orphan: true };
+ const from = Math.max(0, Math.min(th.from, blk.text.length));
+ const to = Math.max(0, Math.min(th.to, blk.text.length));
+ if (to <= from) return { ...th, orphan: true };
+ return { ...th, from, to };
+ });
+}
+
+// ───────────────────────────────────────────────────────────── thread logic
+
+const now = () => new Date().toISOString();
+
+/** Start a thread on [from,to) of a block. `quote` is captured here, once. */
+export function newThread(block: Block, from: number, to: number, author: string, text: string,
+ id = uid('cm'), at = now()): CommentThread {
+ return {
+ id, block: block.id, from, to,
+ quote: block.text.slice(from, to),
+ messages: [{ id: uid('cmm'), author, at, text }],
+ };
+}
+
+/** Append a reply. Pure. An empty body is not a reply and is refused. */
+export function addReply(th: CommentThread, author: string, text: string, at = now()): CommentThread {
+ if (!text.trim()) return th;
+ return { ...th, messages: [...th.messages, { id: uid('cmm'), author, at, text }] };
+}
+
+/**
+ * Edit a message's text in place. Pure; touches nothing else on the thread —
+ * `block`/`from`/`to`/`quote` are the ANCHOR and an edit to what somebody
+ * SAID about the text is not an edit to what they said it ABOUT, so the
+ * anchor a caller reads before and after this call is byte-identical.
+ *
+ * An empty result is not an edit (that is what delete is for) and is refused:
+ * this returns the thread unchanged rather than leaving a blank message
+ * behind for a hasty save-of-empty-textarea to commit.
+ */
+export function editMessage(th: CommentThread, msgId: string, text: string): CommentThread {
+ const trimmed = text.trim();
+ if (!trimmed || !th.messages.some(m => m.id === msgId)) return th;
+ return { ...th, messages: th.messages.map(m => m.id === msgId ? { ...m, text: trimmed } : m) };
+}
+
+/**
+ * Remove one message. Returns the thread with it gone, or `null` when it was
+ * the LAST message — a thread with no messages is not a thread (the same
+ * rule `readThreadsRaw` applies on parse), so the caller deletes the whole
+ * thread rather than keep an empty shell with a frozen anchor and no
+ * conversation to show for it.
+ */
+export function deleteMessage(th: CommentThread, msgId: string): CommentThread | null {
+ const messages = th.messages.filter(m => m.id !== msgId);
+ return messages.length ? { ...th, messages } : null;
+}
+
+/**
+ * Resolve or unresolve. Both directions, because "resolved" is a reviewer's
+ * judgement and reviewers change their minds — a one-way resolve is a delete
+ * with extra steps.
+ */
+export function setResolved(th: CommentThread, resolved: boolean): CommentThread {
+ const out = { ...th };
+ if (resolved) out.resolved = true; else delete out.resolved;
+ return out;
+}
+
+/** How many threads still want a human. Orphans count: they are not resolved. */
+export const unresolvedCount = (threads: readonly CommentThread[]): number =>
+ threads.filter(th => !th.resolved).length;
+
+/**
+ * The order the panel shows.
+ *
+ * UNRESOLVED FIRST, because the panel's job is a to-do list and a document with
+ * forty settled comments must not bury the three that are open. Then attached
+ * before detached — a comment you can still click through to outranks one whose
+ * text is gone. Then DOCUMENT ORDER, so reading the panel top to bottom is
+ * reading the document top to bottom. Orphans have no position left, so they
+ * fall back to when they were written. Fully deterministic: two readers of one
+ * file see the same list, which matters because people say "the third comment".
+ */
+export function orderThreads(threads: readonly CommentThread[], body: readonly Block[]): CommentThread[] {
+ const pos = new Map(body.map((b, i) => [b.id, i]));
+ const rank = (th: CommentThread) => [
+ th.resolved ? 1 : 0,
+ th.orphan ? 1 : 0,
+ th.orphan ? Number.MAX_SAFE_INTEGER : (pos.get(th.block) ?? Number.MAX_SAFE_INTEGER),
+ th.orphan ? 0 : th.from,
+ ];
+ return [...threads].sort((a, b) => {
+ const ra = rank(a), rb = rank(b);
+ for (let i = 0; i < ra.length; i++) if (ra[i] !== rb[i]) return ra[i] - rb[i];
+ const ta = a.messages[0]?.at ?? '', tb = b.messages[0]?.at ?? '';
+ return ta < tb ? -1 : ta > tb ? 1 : (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
+ });
+}
+
+// ────────────────────────────────────── the hooks the core calls (see (B))
+//
+// Thin, mutating wrappers over the pure functions above. Each returns whether
+// it changed anything, so a commit whose block carries no comments costs
+// nothing and does not have to widen its undo scope.
+
+export function commentsOnEdit(doc: TypeDoc, blockId: string, prevText: string, nextText: string): boolean {
+ const d = asCommented(doc);
+ if (!d.comments) return false;
+ const e = textEdit(prevText, nextText);
+ if (!e) return false;
+ const before = readThreadsRaw(doc);
+ if (!before.some(th => th.block === blockId)) return false;
+ writeThreads(doc, shiftThreads(before, blockId, e.at, e.removed, e.added.length, nextText.length));
+ return true;
+}
+
+export function commentsOnSplit(doc: TypeDoc, srcId: string, at: number, srcLen: number, tailId: string): boolean {
+ const d = asCommented(doc);
+ if (!d.comments) return false;
+ const before = readThreadsRaw(doc);
+ if (!before.some(th => th.block === srcId)) return false;
+ writeThreads(doc, splitThreads(before, srcId, at, srcLen, tailId));
+ return true;
+}
+
+export function commentsOnMerge(doc: TypeDoc, prevId: string, curId: string, at: number): boolean {
+ const d = asCommented(doc);
+ if (!d.comments) return false;
+ const before = readThreadsRaw(doc);
+ if (!before.some(th => th.block === curId)) return false;
+ writeThreads(doc, mergeThreads(before, prevId, curId, at));
+ return true;
+}
+
+// ═══════════════════════════════════════════════════════════════════════ UI
+//
+// Everything below touches the DOM. The logic above does not, which is what
+// lets the rig run under plain node.
+
+/**
+ * The bubble, to the house recipe in icons.ts: 24×24 box, rendered at 16px,
+ * stroke currentColor at width 2, round caps and joins. It lives here rather
+ * than in ICONS because this feature is one file — see (D).
+ */
+const COMMENT_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" ' +
+ 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
+ '<path d="M21 12a8 8 0 0 1-8 8H8l-5 3 1.4-4.2A8 8 0 0 1 13 4a8 8 0 0 1 8 8z"/>' +
+ '<line x1="8.5" y1="11" x2="15.5" y2="11"/><line x1="8.5" y1="14.5" x2="13" y2="14.5"/></svg>';
+
+/**
+ * Who you are IF you have already said — never asks.
+ *
+ * authorName() below prompts when it does not know, which is right when you
+ * have just chosen to leave a comment and wrong on a keystroke: tracked changes
+ * attribute every edit, and a modal in the middle of a sentence would be
+ * unusable. Tracking asks once, when it is switched on.
+ */
+export function knownAuthor(): string {
+ try { return localStorage.getItem(AUTHOR_KEY) || ''; } catch { return ''; }
+}
+
+/** Ask for a name if there isn't one, without the caller needing a comment. */
+export const ensureAuthor = (): string => authorName();
+
+/**
+ * Set the name directly — the primary path, from the About dialog's "You"
+ * section. `authorName()`'s prompt stays as the FALLBACK for someone who
+ * comments or turns on tracking before ever opening About; both write the
+ * same key, so whichever ran first is what the other reads.
+ *
+ * Trimmed and stored empty-as-cleared: an empty saved name is not a name, and
+ * `authorName()` must still see nothing there so it prompts (or falls back to
+ * 'Anonymous') the next time it is needed, rather than silently attributing
+ * as ''.
+ */
+export function setAuthorName(name: string): void {
+ const who = name.trim();
+ try { who ? localStorage.setItem(AUTHOR_KEY, who) : localStorage.removeItem(AUTHOR_KEY); }
+ catch { /* private mode — the name just won't persist across reloads */ }
+}
+
+/** Who you are, as bento/slides records it — one suite, one answer. */
+function authorName(): string {
+ let who = '';
+ try { who = localStorage.getItem(AUTHOR_KEY) ?? ''; } catch { /* private mode */ }
+ if (who) return who;
+ const asked = typeof prompt === 'function'
+ ? prompt(t('Your name, so your comments are attributed'), '') : '';
+ who = (asked ?? '').trim();
+ if (who) { try { localStorage.setItem(AUTHOR_KEY, who); } catch { /* ignore */ } }
+ // NOT t(): this becomes CONTENT in the file, and content does not change
+ // language when somebody else opens it.
+ return who || 'Anonymous';
+}
+
+const when = (iso: string) => {
+ const d = new Date(iso);
+ return isNaN(d.getTime()) ? '' : d.toLocaleString(undefined,
+ { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
+};
+
+/** The selected thread — VIEW state, never in the document. */
+let selected: string | null = null;
+/** The one message currently being edited in place — VIEW state too. */
+let editingMsg: string | null = null;
+let layer: HTMLElement | null = null;
+let repaint: (() => void) | null = null;
+let refreshPanel: (() => void) | null = null;
+
+/**
+ * The DOM point `at` characters into a rendered block — footnote atoms skipped,
+ * exactly as editor.ts counts them. A comment's offsets are model offsets, and
+ * the model does not know the marker is there.
+ */
+function pointAt(block: HTMLElement, at: number): { node: Node; offset: number } | null {
+ let count = 0;
+ let last: { node: Node; offset: number } | null = null;
+ const walk = (n: Node): { node: Node; offset: number } | null => {
+ if (n.nodeType === 3) {
+ const len = n.nodeValue!.length;
+ if (count + len >= at) return { node: n, offset: at - count };
+ count += len;
+ last = { node: n, offset: len };
+ return null;
+ }
+ if (n.nodeType === 1 && isNoteAtom(n as Element)) return null;
+ for (const c of Array.from(n.childNodes)) { const r = walk(c); if (r) return r; }
+ return null;
+ };
+ for (const c of Array.from(block.childNodes)) { const r = walk(c); if (r) return r; }
+ return last;
+}
+
+/** Characters before (container, offset) in this block — the inverse of above. */
+function offsetIn(block: HTMLElement, container: Node, offset: number): number {
+ let count = 0, done = false;
+ const walk = (n: Node): void => {
+ if (done) return;
+ if (n === container && n.nodeType !== 3) {
+ for (let i = 0; i < offset && i < n.childNodes.length; i++) walk(n.childNodes[i]);
+ done = true; return;
+ }
+ if (n.nodeType === 3) {
+ if (n === container) { count += Math.min(offset, n.nodeValue!.length); done = true; return; }
+ count += n.nodeValue!.length; return;
+ }
+ if (n.nodeType === 1 && isNoteAtom(n as Element)) return;
+ for (const c of Array.from(n.childNodes)) { walk(c); if (done) return; }
+ };
+ for (const c of Array.from(block.childNodes)) { walk(c); if (done) break; }
+ return count;
+}
+
+const blockEl = (paper: HTMLElement, id: string) =>
+ paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(id)}"]`);
+
+function rangeFor(paper: HTMLElement, th: CommentThread): Range | null {
+ const el = blockEl(paper, th.block);
+ if (!el) return null;
+ const a = pointAt(el, th.from), b = pointAt(el, th.to);
+ if (!a || !b) return null;
+ const r = document.createRange();
+ try { r.setStart(a.node, a.offset); r.setEnd(b.node, b.offset); } catch { return null; }
+ return r;
+}
+
+/**
+ * Paint highlights and margin cards into the overlay.
+ *
+ * Its own layer, a sibling of `.t-deco` — because `drawPages` calls
+ * `deco.replaceChildren()` on every repagination and would wipe anything this
+ * module put there. The layer is `pointer-events:none` with only the cards
+ * interactive, so a highlight can never swallow a click meant for the text.
+ */
+function paintLayer(ctx: FeatureContext): void {
+ const paper = ctx.editor.host;
+ const wrap = paper.parentElement;
+ if (!wrap) return;
+ if (!layer || layer.parentElement !== wrap) {
+ layer = document.createElement('div');
+ layer.className = 't-cmt-layer';
+ // never captured by a save: the file carries doc.comments, not their pixels
+ layer.setAttribute('data-bento-transient', '');
+ wrap.appendChild(layer);
+ }
+ layer.replaceChildren();
+
+ const threads = orderThreads(readThreads(ctx.store.doc), ctx.store.doc.body)
+ .filter(th => !th.orphan);
+ if (!threads.length) return;
+
+ const top0 = paper.getBoundingClientRect().top;
+ const left0 = paper.getBoundingClientRect().left;
+ const frag = document.createDocumentFragment();
+
+ // The gutter is shared with footnote sidenotes, which paginate.ts has already
+ // stacked. Start below whatever is there and keep stacking, so a note and a
+ // comment beside the same line never land on top of each other.
+ const occupied: Array<[number, number]> = [];
+ const deco = wrap.querySelector('.t-deco');
+ if (deco) for (const n of Array.from(deco.querySelectorAll<HTMLElement>('.sidenote'))) {
+ const y = parseFloat(n.style.top || '0');
+ occupied.push([y, y + n.getBoundingClientRect().height]);
+ }
+ let lastBottom = -1e9;
+
+ for (const th of threads) {
+ const r = rangeFor(paper, th);
+ if (!r) continue;
+ const rects = Array.from(r.getClientRects()).filter(x => x.width > 0 && x.height > 0);
+ if (!rects.length) continue;
+
+ for (const rect of rects) {
+ const hl = document.createElement('div');
+ hl.className = 't-cmt-hl' + (th.resolved ? ' done' : '') + (th.id === selected ? ' on' : '');
+ hl.style.top = `${rect.top - top0}px`;
+ hl.style.left = `${rect.left - left0}px`;
+ hl.style.width = `${rect.width}px`;
+ hl.style.height = `${rect.height}px`;
+ frag.appendChild(hl);
+ }
+
+ const card = buildCard(ctx, th);
+ frag.appendChild(card);
+ layer.appendChild(card); // measured after insertion
+ let y = rects[0].top - top0 - 2;
+ for (const [a, b] of occupied) if (y < b && y + 10 > a) y = b + 8;
+ y = Math.max(y, lastBottom + 8);
+ card.style.top = `${y}px`;
+ lastBottom = y + card.getBoundingClientRect().height;
+ }
+ layer.prepend(frag);
+}
+
+/**
+ * One message, in the shape both the margin card and the panel use.
+ *
+ * Edit/delete are gated by NAME, not identity — this document has no notion
+ * of who is typing beyond the self-asserted `bento-author` value, so "is this
+ * yours" is "does the byline match what's in localStorage right now", the
+ * same honour-system comparison editor.ts already trusts for attributing a
+ * tracked change. Anyone can rename themselves to someone else's name and
+ * edit their comments; that is true of `authorName()` everywhere else in this
+ * file too, and is not something a margin-card button could fix.
+ */
+function buildMessage(ctx: FeatureContext, th: CommentThread, m: CommentMsg, cls: string, suffix = ''): HTMLElement {
+ const wrap = document.createElement('div');
+ wrap.className = cls;
+ const editing = editingMsg === m.id;
+
+ const who = document.createElement('div');
+ who.className = 'who';
+ who.textContent = `${m.author} · ${when(m.at)}${suffix}`;
+
+ const me = knownAuthor();
+ if (me && m.author === me && !editing) {
+ const tools = document.createElement('span');
+ tools.className = 't-cmt-msgtools';
+ const editBtn = document.createElement('button');
+ editBtn.type = 'button';
+ editBtn.className = 't-cmt-msgbtn';
+ editBtn.textContent = t('Edit');
+ editBtn.title = t('Edit your comment');
+ editBtn.addEventListener('click', () => { editingMsg = m.id; repaint?.(); refreshPanel?.(); });
+ const delBtn = document.createElement('button');
+ delBtn.type = 'button';
+ delBtn.className = 't-cmt-msgbtn';
+ delBtn.textContent = t('Delete');
+ delBtn.title = th.messages.length > 1 ? t('Delete your comment') : t('Delete this thread');
+ delBtn.addEventListener('click', () => {
+ const question = th.messages.length > 1
+ ? t('Delete this comment?') : t('Delete this whole thread?');
+ if (!confirm(question)) return;
+ mutateThread(ctx, th.id, cur => deleteMessage(cur, m.id));
+ });
+ tools.append(editBtn, delBtn);
+ who.appendChild(tools);
+ }
+ wrap.appendChild(who);
+
+ if (editing) {
+ const ta = document.createElement('textarea');
+ ta.className = 't-cmt-edit';
+ ta.rows = 2;
+ ta.value = m.text;
+ const row = document.createElement('div');
+ row.className = 'btns';
+ const save = document.createElement('button');
+ save.type = 'button';
+ save.textContent = t('Save');
+ save.addEventListener('click', () => {
+ const text = ta.value.trim();
+ if (!text) return;
+ editingMsg = null;
+ mutateThread(ctx, th.id, cur => editMessage(cur, m.id, text));
+ });
+ const cancel = document.createElement('button');
+ cancel.type = 'button';
+ cancel.textContent = t('Cancel');
+ cancel.addEventListener('click', () => { editingMsg = null; repaint?.(); refreshPanel?.(); });
+ row.append(save, cancel);
+ wrap.append(ta, row);
+ return wrap;
+ }
+
+ const what = document.createElement('div');
+ what.className = 'what';
+ what.textContent = m.text;
+ wrap.appendChild(what);
+ return wrap;
+}
+
+/** One margin card. Expanded — replies, a reply box, resolve — when selected. */
+function buildCard(ctx: FeatureContext, th: CommentThread): HTMLElement {
+ const card = document.createElement('div');
+ card.className = 't-cmt-card' + (th.resolved ? ' done' : '') + (th.id === selected ? ' on' : '');
+ card.dataset.thread = th.id;
+ const open = th.id === selected;
+ const msgs = open ? th.messages : th.messages.slice(0, 1);
+ const more = th.messages.length - msgs.length;
+ for (const m of msgs) card.appendChild(buildMessage(ctx, th, m, 'msg'));
+ if (more > 0) {
+ const rest = document.createElement('div');
+ rest.className = 'who';
+ rest.textContent = t('{n} more', { n: String(more) });
+ card.appendChild(rest);
+ }
+ card.addEventListener('mousedown', e => {
+ // not `click`: mousedown beats the selection change, so opening a card
+ // cannot be mistaken for the author clicking into the paper
+ if ((e.target as HTMLElement).closest('button, textarea')) return;
+ e.preventDefault();
+ select(ctx, th.id === selected ? null : th.id);
+ });
+ if (open) card.appendChild(threadActions(ctx, th));
+ return card;
+}
+
+/** Reply box + resolve toggle, shared by the margin card and the panel. */
+function threadActions(ctx: FeatureContext, th: CommentThread): HTMLElement {
+ const box = document.createElement('div');
+ box.className = 'acts';
+ const input = document.createElement('textarea');
+ input.rows = 2;
+ input.placeholder = t('Reply…');
+ const row = document.createElement('div');
+ row.className = 'btns';
+ const send = document.createElement('button');
+ send.type = 'button';
+ send.textContent = t('Reply');
+ send.addEventListener('click', () => {
+ const text = input.value.trim();
+ if (!text) return;
+ mutateThread(ctx, th.id, cur => addReply(cur, authorName(), text));
+ input.value = '';
+ });
+ const res = document.createElement('button');
+ res.type = 'button';
+ res.textContent = th.resolved ? t('Reopen') : t('Resolve');
+ res.addEventListener('click', () => mutateThread(ctx, th.id, cur => setResolved(cur, !cur.resolved)));
+ row.append(send, res);
+ box.append(input, row);
+ return box;
+}
+
+/**
+ * Change one thread and commit it, or DELETE it when `fn` returns null —
+ * deleting the last message in it. Whole-doc scope: comments are doc-level.
+ *
+ * A deleted thread leaves nothing behind to clean up: `paintLayer` and the
+ * panel both rebuild their contents from `readThreads(ctx.store.doc)` on
+ * every commit (via the `store.on` subscription below), so a thread that is
+ * no longer in the map is simply not painted — there is no separate
+ * highlight or marker element to remember to remove.
+ */
+function mutateThread(ctx: FeatureContext, id: string, fn: (th: CommentThread) => CommentThread | null): void {
+ ctx.store.commit(d => {
+ // raw: a reply/edit/delete must not silently write back the read-time repair
+ const threads = readThreadsRaw(d);
+ const i = threads.findIndex(x => x.id === id);
+ if (i < 0) return;
+ const next = fn(threads[i]);
+ if (next === null) {
+ threads.splice(i, 1);
+ if (selected === id) selected = null;
+ } else {
+ threads[i] = next;
+ }
+ writeThreads(d, threads);
+ });
+}
+
+function select(ctx: FeatureContext, id: string | null): void {
+ selected = id;
+ repaint?.();
+ refreshPanel?.();
+ if (!id) return;
+ const th = readThreads(ctx.store.doc).find(x => x.id === id);
+ if (!th || th.orphan) return;
+ const el = blockEl(ctx.editor.host, th.block);
+ el?.scrollIntoView({ block: 'center', behavior: 'smooth' });
+}
+
+// ─────────────────────────────────────────────────────────────── the feature
+
+/** Comment on the current selection. */
+function addComment(ctx: FeatureContext): void {
+ const c = ctx.editor.caret();
+ if (!c || c.to === undefined || c.to === c.at) {
+ ctx.toast(t('Select some text first, then comment on it'));
+ return;
+ }
+ const from = Math.min(c.at, c.to), to = Math.max(c.at, c.to);
+ const blk = ctx.store.block(c.id);
+ if (!blk) return;
+ const who = authorName();
+ const text = typeof prompt === 'function'
+ ? (prompt(t('Comment on “{quote}”', { quote: blk.text.slice(from, to).slice(0, 60) })) ?? '').trim()
+ : '';
+ if (!text) return;
+ const th = newThread(blk, from, to, who, text);
+ ctx.store.commit(d => { writeThreads(d, [...readThreadsRaw(d), th]); });
+ selected = th.id;
+ ctx.refresh();
+}
+
+registerTool({
+ id: 'comment',
+ icon: COMMENT_ICON,
+ get title() { return t('Comment on the selected text (⌘⇧M)'); },
+ group: 'review',
+ order: 10,
+ run: addComment,
+});
+
+registerKey({ key: 'm', mod: true, shift: true, run: addComment });
+
+registerPanel({
+ id: 'comments',
+ get label() { return t('Comments'); },
+ // a SECTION of the Review tab: comments are one of the things people did to
+ // this document, alongside tracked changes and signatures
+ host: 'commentsHost',
+ order: 20,
+ mount(host, ctx) {
+ const render = () => {
+ const threads = orderThreads(readThreads(ctx.store.doc), ctx.store.doc.body);
+ const open = unresolvedCount(threads);
+
+ // The count lives HERE and not on the tab. Putting it on the tab was the
+ // first version and it wrapped "Comments 1" onto two lines — four tabs
+ // share a 250px sidebar — which made the whole tab row grow taller the
+ // moment a document had a comment, jogging the panel below it. A count
+ // that reflows the chrome it lives in is not worth the glance it saves.
+
+ host.replaceChildren();
+ if (!threads.length) {
+ const hint = document.createElement('div');
+ hint.className = 't-hint';
+ hint.textContent = t('Select some text and press ⌘⇧M to comment on it.');
+ host.appendChild(hint);
+ return;
+ }
+ const count = document.createElement('div');
+ count.className = 't-hint';
+ count.textContent = open
+ ? t('{open} open of {all}', { open: String(open), all: String(threads.length) })
+ : t('All {all} resolved', { all: String(threads.length) });
+ host.appendChild(count);
+
+ for (const th of threads) {
+ const card = document.createElement('div');
+ card.className = 't-card t-cmt-item' + (th.resolved ? ' done' : '')
+ + (th.id === selected ? ' on' : '');
+ const first = th.messages[0];
+ const repliesSuffix = th.messages.length > 1
+ ? ` · ${t('{n} replies', { n: String(th.messages.length - 1) })}` : '';
+ const firstEl = buildMessage(ctx, th, first, 'msg', repliesSuffix);
+ // splice the quote between the byline and the body — the reading order
+ // is "who said it, about what, saying what" — by inserting it right
+ // after the who-line buildMessage always puts first.
+ const quote = document.createElement('div');
+ quote.className = 'quote' + (th.orphan ? ' gone' : '');
+ quote.textContent = th.quote;
+ firstEl.insertBefore(quote, firstEl.firstElementChild!.nextSibling);
+ card.appendChild(firstEl);
+ if (th.orphan) {
+ const gone = document.createElement('div');
+ gone.className = 'who';
+ gone.textContent = t('the text this was about is gone');
+ card.appendChild(gone);
+ }
+ card.addEventListener('click', e => {
+ if ((e.target as HTMLElement).closest('.acts, button, textarea')) return;
+ select(ctx, th.id === selected ? null : th.id);
+ });
+ if (th.id === selected) {
+ for (const m of th.messages.slice(1)) card.appendChild(buildMessage(ctx, th, m, 'reply'));
+ card.appendChild(threadActions(ctx, th));
+ }
+ host.appendChild(card);
+ }
+ };
+
+ refreshPanel = render;
+ repaint = () => paintLayer(ctx);
+ render();
+
+ // Own repaints, because main.ts never calls PanelSpec.update — see (E).
+ // The store fires on every commit; the observer catches the editor's
+ // re-renders and pagination's reflows, which move the geometry without
+ // changing the document.
+ let beat: number | undefined;
+ const soon = () => {
+ clearTimeout(beat);
+ beat = setTimeout(() => { render(); paintLayer(ctx); }, 60) as unknown as number;
+ };
+ ctx.store.on(soon);
+ new MutationObserver(soon).observe(ctx.editor.host, { childList: true, subtree: true, characterData: true });
+ window.addEventListener('resize', soon);
+
+ // Clicking a commented range focuses its comment — the other half of
+ // "clicking a comment scrolls to the range". Capture-phase and read-only:
+ // it never touches the selection the author is making.
+ ctx.editor.host.addEventListener('click', () => {
+ const sel = getSelection();
+ if (!sel || !sel.rangeCount) return;
+ const r = sel.getRangeAt(0);
+ if (!sel.isCollapsed || !ctx.editor.host.contains(r.startContainer)) return;
+ let n: Node | null = r.startContainer;
+ while (n && n !== ctx.editor.host && !(n.nodeType === 1 && (n as HTMLElement).dataset?.id)) n = n.parentNode;
+ if (!n || n === ctx.editor.host) return;
+ const el = n as HTMLElement;
+ const at = offsetIn(el, r.startContainer, r.startOffset);
+ const hit = orderThreads(readThreads(ctx.store.doc), ctx.store.doc.body)
+ .find(th => !th.orphan && th.block === el.dataset.id && at >= th.from && at <= th.to);
+ if (hit) select(ctx, hit.id);
+ });
+
+ setTimeout(() => paintLayer(ctx), 120);
+ },
+ update(_host, ctx) { refreshPanel?.(); paintLayer(ctx); },
+});
+
+// ─────────────────────────────────────────────────────── showing and hiding
+//
+// A VIEWER preference, kept beside the theme rather than in the document: it is
+// about reading this file today, not about the file. Two people opening the
+// same document disagree about whether they want the margin full of review,
+// and neither answer belongs in bytes they both sign.
+//
+// It hides the APPARATUS — highlights and cards — and never the text, and it
+// changes nothing in `doc.comments`, so a hidden thread is still saved, still
+// exported, and still there when it is turned back on.
+
+const HIDE_KEY = 'bento-type-hide-comments';
+
+export const commentsHidden = (): boolean => {
+ try { return localStorage.getItem(HIDE_KEY) === '1'; } catch { return false; }
+};
+
+export function setCommentsHidden(on: boolean): void {
+ try { on ? localStorage.setItem(HIDE_KEY, '1') : localStorage.removeItem(HIDE_KEY); }
+ catch { /* storage blocked — the class below still applies for this session */ }
+ document.documentElement.classList.toggle('t-hide-comments', on);
+}
+
+/** Apply the remembered choice at boot. */
+export const applyCommentVisibility = (): void => {
+ document.documentElement.classList.toggle('t-hide-comments', commentsHidden());
+};
+
+registerMenuItem({
+ id: 'comments-visibility',
+ get label() { return commentsHidden() ? t('Show comments') : t('Hide comments'); },
+ order: 15,
+ run(ctx) {
+ setCommentsHidden(!commentsHidden());
+ ctx.refresh();
+ ctx.toast(commentsHidden() ? t('Comments hidden') : t('Comments shown'));
+ },
+});
+
+// the remembered choice, applied once the app exists
+registerReady(() => applyCommentVisibility());
diff --git a/type/src/docstyles.css b/type/src/docstyles.css
new file mode 100644
index 00000000..13ff2806
--- /dev/null
+++ b/type/src/docstyles.css
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: MIT
+ Copyright (c) 2026 The Bento authors
+
+ Panel styling for docstyles.ts's "Styles" section — kept OUT of styles.css
+ deliberately: several agents are editing this app at once, and a shared
+ stylesheet puts every one of their diffs in the same file. Everything
+ reusable already exists there (t-section, t-row, t-select, t-field, t-btn,
+ t-note, t-toggles) and is reused as-is; only what those do not cover lives
+ here, under its own `t-sty-` prefix so nothing here can collide with a
+ class another feature owns. */
+
+.t-sty-badge {
+ display: inline-block; margin-inline-start: 6px;
+ font-size: 10px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase;
+ color: var(--accent-ink); background: var(--accent); border-radius: 999px;
+ padding: 1px 6px; vertical-align: middle;
+}
+/* the row grammar, matching .t-props .t-row's metrics — duplicated rather
+ than reusing that selector because it is scoped to `.t-props .t-row` and
+ this section may one day be mounted somewhere that scope does not reach */
+.t-sty-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
+.t-sty-row > span:first-child { flex: 1 1 auto; font-size: 12.5px; color: var(--muted); }
+.t-sty-row > :last-child { flex: 0 0 auto; }
+.t-sty-color {
+ width: 34px; height: 26px; padding: 2px; box-sizing: border-box;
+ border: 1px solid var(--line); border-radius: 7px; background: var(--field);
+ cursor: pointer;
+}
+.t-sty-actions { display: flex; gap: 6px; margin: 8px 0 2px; flex-wrap: wrap; }
+.t-sty-actions .t-btn { flex: 1 1 auto; white-space: nowrap; }
diff --git a/type/src/docstyles.ts b/type/src/docstyles.ts
new file mode 100644
index 00000000..d8c29216
--- /dev/null
+++ b/type/src/docstyles.ts
@@ -0,0 +1,572 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Named paragraph styles — the format piece described in DocStyle (model.ts)
+// and the panel that edits it.
+//
+// THE GAP THIS CLOSES. Before this, the panel's "Style" dropdown
+// (props.ts STYLE_OPTIONS) only set a block's `kind` — which picks a TAG
+// (h1, p, blockquote…) and nothing about how that tag looks. Every heading's
+// size, weight and spacing was hardcoded in styles.css, so "make every
+// heading 18px Palatino" was not a setting; it was a code change. This module
+// makes the LOOK of a kind a document property instead of a build constant.
+//
+// THE PRECEDENCE STACK, block wins over style wins over document:
+//
+// block's own align/sb/sa/lh/ind (Block, model.ts — set via the Layout panel)
+// │ (present ⇒ wins outright — "Direct per-block formatting must
+// │ still win over the style")
+// ▼
+// the block's STYLE (explicit b.styleId, or the kind's default — resolveStyle)
+// ▼
+// the document's OWN defaults (doc.layout — layout.ts docEffective)
+// ▼
+// the built-in fallback (layout.ts DOC_DEFAULTS)
+//
+// `family`/`size`/`weight`/`italic`/`color` have no per-block equivalent —
+// character-level formatting is already a MARK over a text range (inline.ts
+// t:'font', plus b/i toggle marks), and an inline `<span style="…">` always
+// wins the cascade over an ancestor's inline style, so nothing new is needed
+// there: a bold word inside a re-styled heading stays bold with no extra code.
+//
+// ADDITIVITY (docs/PLATFORM.md §3). `doc.styles` is optional and a block's
+// `styleId` is optional; BUILT_IN_STYLES below is chosen to compute to the
+// EMPTY string for every kind it covers when nothing has been edited — see
+// the comment on each entry. So a document that never opens the Styles
+// section renders through the same styles.css rules it always has, and
+// scripts/test-type-styles.ts asserts exactly that against a fixture with no
+// `doc.styles` at all.
+
+import { fontAcross, safeFamily, safeSize } from './inline.ts';
+import type { Block, BlockKind, DocStyle, TypeDoc } from './model.ts';
+import { docEffective, propsOf, type ParaLayout } from './layout.ts';
+import { t } from './i18n.ts';
+import type { FeatureContext } from './features.ts';
+// NOT `import './docstyles.css'` here: render.ts imports this module for
+// docStyleCss, and render.ts is reachable from model.ts (via comments.ts) —
+// which the node test rigs (scripts/test-type-*.ts) load directly with no
+// bundler in front of them, and plain node has no loader for a bare `.css`
+// import. props.ts pulls the stylesheet in instead: it is UI-only, reached
+// only through features.ts, which no rig imports.
+
+// ═══════════════════════════════════════════════════════════ resolution (pure)
+
+/** Which kinds carry a default style, and that style's built-in id. */
+export const DEFAULT_STYLE_ID: Partial<Record<BlockKind, string>> = {
+ para: 'default-body', h1: 'default-h1', h2: 'default-h2', h3: 'default-h3',
+ quote: 'default-quote', ul: 'default-ul', ol: 'default-ol',
+};
+
+/**
+ * The built-in styles, numbers copied from styles.css's `.t-paper` rules —
+ * see the file header. `default-body` is intentionally EMPTY: body text's
+ * appearance already comes entirely from the unconditional `.t-paper p` rule
+ * plus, when the document sets its own defaults, the `--lay-*` custom
+ * properties layout.ts already writes — this module adds nothing on top of
+ * either until the style is actually edited.
+ */
+export const BUILT_IN_STYLES: Record<string, DocStyle> = {
+ 'default-body': { id: 'default-body', kind: 'para', name: 'Body' },
+ 'default-h1': { id: 'default-h1', kind: 'h1', name: 'Heading 1', size: 26, weight: 600, lh: 1.24, sa: 14 },
+ 'default-h2': { id: 'default-h2', kind: 'h2', name: 'Heading 2', size: 15.5, weight: 600, sb: 24, sa: 8 },
+ 'default-h3': { id: 'default-h3', kind: 'h3', name: 'Heading 3', size: 14, weight: 600, color: '#3a3d44', sb: 16, sa: 6 },
+ 'default-quote': { id: 'default-quote', kind: 'quote', name: 'Quote', italic: true, color: '#3a3d44', sb: 12, sa: 12 },
+ 'default-ul': { id: 'default-ul', kind: 'ul', name: 'Bulleted list', sa: 3 },
+ 'default-ol': { id: 'default-ol', kind: 'ol', name: 'Numbered list', sa: 3 },
+};
+
+/** Fixed display order for the built-ins; anything else sorts after, by name. */
+const BUILT_IN_ORDER = ['default-body', 'default-h1', 'default-h2', 'default-h3',
+ 'default-quote', 'default-ul', 'default-ol'];
+
+/** The style a block currently carries, EXPLICIT only — no kind fallback. */
+export function ownStyleId(b: Block): string | undefined {
+ return typeof b.styleId === 'string' && b.styleId ? b.styleId : undefined;
+}
+
+/**
+ * The id actually in force for this block: its own `styleId` WHEN IT
+ * RESOLVES, else its kind's default. Needs `doc` for that first check — a
+ * `styleId` naming a style that does not exist (deleted since, or a typo
+ * from hand-edited JSON) is not "in force"; falling through to the kind
+ * default is what keeps that paragraph looking like a heading instead of
+ * silently going plain the moment its style disappears. Undefined only for a
+ * kind with no default (image, cell, caption, toc, math, embed) that also
+ * carries no *resolvable* explicit `styleId`.
+ */
+export function activeStyleId(doc: TypeDoc, b: Block): string | undefined {
+ const own = ownStyleId(b);
+ if (own && lookupStyle(doc, own)) return own;
+ return DEFAULT_STYLE_ID[b.kind];
+}
+
+/**
+ * Look up a style by id: the document's own copy if it has materialized one
+ * (edited at least once), else the built-in of that id, else undefined for an
+ * id that resolves to neither — a dangling `styleId` from hand-edited JSON,
+ * or a style that has since been removed. That case is not an error: the
+ * caller falls back to rendering nothing extra, exactly as an unstyled block
+ * always has.
+ */
+export function lookupStyle(doc: TypeDoc, id: string): DocStyle | undefined {
+ return doc.styles?.[id] ?? BUILT_IN_STYLES[id];
+}
+
+/** The style actually painting this block, following `activeStyleId`. */
+export function resolveStyle(doc: TypeDoc, b: Block): DocStyle | undefined {
+ const id = activeStyleId(doc, b);
+ return id ? lookupStyle(doc, id) : undefined;
+}
+
+/**
+ * Every style offered in the panel's picker: the seven built-ins in a fixed
+ * order, then any custom ids the document defines that are not one of them —
+ * so a hand-authored or future-tooling-written extra style is still reachable
+ * even though nothing in this build creates one.
+ */
+export function listStyles(doc: TypeDoc): DocStyle[] {
+ const ids = new Set<string>(BUILT_IN_ORDER);
+ for (const id of Object.keys(doc.styles ?? {})) ids.add(id);
+ const extra = [...ids].filter(id => !BUILT_IN_ORDER.includes(id)).sort();
+ return [...BUILT_IN_ORDER, ...extra]
+ .map(id => lookupStyle(doc, id))
+ .filter((s): s is DocStyle => !!s);
+}
+
+/**
+ * A CSS `color` value safe to interpolate into a `style` attribute.
+ *
+ * Defence in depth: parseDoc (model.ts) already validated every `doc.styles`
+ * entry against the same allow-list, but this module also RENDERS, and a
+ * renderer that trusts its own parser's promise instead of checking again is
+ * how inline.ts's font marks stayed safe through a refactor that almost
+ * dropped the parse-time check — sanitize again at the point of injection.
+ */
+const SAFE_STYLE_COLOR = /^(#[0-9a-fA-F]{3,8}|rgba?\([\d.,%\s]+\)|hsla?\([\d.,%\s]+\)|[a-zA-Z]{1,30})$/;
+export const safeStyleColor = (raw: string | undefined): string | null => {
+ const c = (raw ?? '').trim();
+ return c && SAFE_STYLE_COLOR.test(c) ? c : null;
+};
+
+/**
+ * A style's own typography, as CSS declarations — the STYLE alone, no
+ * document defaults folded in (those already reach the paper through
+ * styles.css's unconditional rules and layout.ts's `--lay-*` variables) and
+ * no block-level overrides folded in either (those are layout.ts's
+ * `blockStyle`, a separate mechanism — see the module header's precedence
+ * diagram and `docStyleCss`/`styleSheetCss` below for the two ways this gets
+ * composed with it).
+ */
+function styleDeclarations(s: DocStyle): string {
+ const out: string[] = [];
+ const fam = s.family ? safeFamily(s.family) : null;
+ if (fam) out.push(`font-family:${fam}`);
+ const size = s.size !== undefined ? safeSize(s.size) : null;
+ if (size !== null) out.push(`font-size:${size}px`);
+ if (s.weight !== undefined && Number.isFinite(s.weight)) {
+ out.push(`font-weight:${Math.max(100, Math.min(900, Math.round(s.weight / 100) * 100))}`);
+ }
+ if (s.italic) out.push('font-style:italic');
+ const color = safeStyleColor(s.color);
+ if (color) out.push(`color:${color}`);
+ if (s.align) out.push(`text-align:${s.align}`);
+ if (s.lh !== undefined) out.push(`line-height:${s.lh}`);
+ // `padding-top:0` rides with `sb`, mirroring layout.ts's blockStyle: the
+ // stylesheet spaces consecutive paragraphs with a
+ // `margin-top:-10px; padding-top:10px` pair (the `p + p` first-line-indent
+ // trick), and setting only margin-top would leave that padding behind and
+ // add 10px on top of whatever the style asked for.
+ if (s.sb !== undefined) out.push(`margin-top:${s.sb}px`, 'padding-top:0');
+ if (s.sa !== undefined) out.push(`margin-bottom:${s.sa}px`);
+ if (s.ind !== undefined) out.push(`text-indent:${s.ind}px`);
+ return out.join(';');
+}
+
+/**
+ * The named style's own typography, as inline CSS — the BLOCK's resolved
+ * style alone. Composed with `blockStyle(b)` from layout.ts by the caller,
+ * AFTER it in the declaration order, so a property both set resolves to the
+ * BLOCK's own value: later declarations win in one `style` attribute.
+ *
+ * USED BY PRINT ONLY (print.ts bodyHtml builds one static HTML string, once —
+ * there is nothing there to clobber it afterward). The LIVE editor does NOT
+ * use this — see `styleSheetCss`/`ensureStyleSheet` for why, and render.ts
+ * for where the split happens. Kept exported and pure for
+ * scripts/test-type-styles.ts, which is the most direct way to pin the
+ * composition rule this whole module leans on.
+ */
+export function docStyleCss(doc: TypeDoc, b: Block): string {
+ const s = resolveStyle(doc, b);
+ return s ? styleDeclarations(s) : '';
+}
+
+/** A style's escaped id, safe inside a double-quoted CSS attribute selector. */
+const cssAttrId = (id: string): string => id.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+
+/**
+ * Every style the document could paint, as ONE stylesheet — `[data-style-id]`
+ * attribute rules, one per style that has anything to say.
+ *
+ * THIS is how the LIVE editor applies named styles, and the reason is a real
+ * bug an earlier version of this module had: layout.ts's `applyToDom` runs on
+ * its OWN MutationObserver (any childList change under the paper) and
+ * unconditionally rewrites every block's `style` ATTRIBUTE from
+ * `blockStyle(b)` alone — right, since that attribute is where a block's
+ * OWN direct overrides live and layout.ts owns painting them. But a version
+ * of this module that also wrote into that same attribute got its
+ * contribution silently erased microtasks after render, the moment ANYTHING
+ * re-triggered that observer (which a fresh render always does — it replaces
+ * the paper's children). A stylesheet keyed by a `data-` attribute lives
+ * outside the attribute layout.ts repaints and outside the subtree its
+ * observer watches (the tag is a HEAD sibling, not a paper descendant), so
+ * the two mechanisms can never collide — and CSS SPECIFICITY still gives the
+ * right precedence for free: an inline `style` (blockStyle's) always beats
+ * ANY selector from a `<style>` sheet, so a block's own formatting keeps
+ * winning over its style with no coordination needed at all.
+ *
+ * Selectors are prefixed `.t-paper ` — not decoration, load-bearing. A bare
+ * `[data-style-id="…"]` is specificity (0,1,0), and styles.css's own
+ * `.t-paper h1` is (0,1,1): a class AND a type beats a lone attribute, so the
+ * built-in CSS would have silently kept winning over an edited style forever.
+ * `.t-paper [data-style-id="…"]` is (0,2,0), which beats `.t-paper h1` (and
+ * every other single-class-plus-type rule in styles.css) while still losing,
+ * correctly, to an inline `style` attribute.
+ */
+export function styleSheetCss(doc: TypeDoc): string {
+ const parts: string[] = [];
+ for (const s of listStyles(doc)) {
+ const decls = styleDeclarations(s);
+ if (decls) parts.push(`.t-paper [data-style-id="${cssAttrId(s.id)}"]{${decls}}`);
+ }
+ return parts.join('\n');
+}
+
+const STYLE_TAG_ID = 't-style-rules';
+
+/**
+ * Keep the injected stylesheet in step with the document. Idempotent (only
+ * touches the DOM when the text actually changed) and safe to call on every
+ * render — render.ts's `renderBody` does.
+ *
+ * The tag is marked `data-bento-transient`: it is runtime-injected DOM, not
+ * authored content, so a save must never write it back into the file (the
+ * same rule the compressed shell's own injected `<style>` follows —
+ * PLATFORM.md §4).
+ */
+export function ensureStyleSheet(doc: TypeDoc): void {
+ if (typeof document === 'undefined') return;
+ let tag = document.getElementById(STYLE_TAG_ID) as HTMLStyleElement | null;
+ if (!tag) {
+ tag = document.createElement('style');
+ tag.id = STYLE_TAG_ID;
+ tag.setAttribute('data-bento-transient', '');
+ document.head.appendChild(tag);
+ }
+ const css = styleSheetCss(doc);
+ if (tag.textContent !== css) tag.textContent = css;
+}
+
+/**
+ * What this paragraph looks like RIGHT NOW, block over style over document —
+ * the layout.ts vocabulary alone (align/sb/sa/lh/ind), used by "Update style
+ * to match this paragraph" to capture the paragraph's current appearance
+ * before folding it into the style.
+ */
+export function effectiveLayout(doc: TypeDoc, b: Block): Required<ParaLayout> {
+ const out = { ...docEffective(doc) };
+ const style = resolveStyle(doc, b);
+ const p = propsOf(b);
+ for (const layer of [style, p]) {
+ if (!layer) continue;
+ for (const k of ['align', 'sb', 'sa', 'lh', 'ind'] as const) {
+ const v = (layer as Partial<ParaLayout>)[k];
+ if (v !== undefined) (out as Record<string, unknown>)[k] = v;
+ }
+ }
+ return out;
+}
+
+/**
+ * Has this paragraph got DIRECT formatting of its own — the properties the
+ * Layout panel (layout.ts) writes straight onto the block — regardless of
+ * which style is in force? That is what makes a paragraph diverge from its
+ * style, and is what the panel badges "Modified".
+ */
+export const hasDirectFormatting = (b: Block): boolean =>
+ (['align', 'sb', 'sa', 'lh', 'ind'] as const).some(k => propsOf(b)[k] !== undefined);
+
+// ═══════════════════════════════════════════════════════════════════ the UI
+
+const FACE_STACKS: Array<[string, string]> = [
+ ['"Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif', 'Palatino (serif)'],
+ ['Georgia, "Times New Roman", Times, serif', 'Georgia (serif)'],
+ ['"Times New Roman", Times, serif', 'Times New Roman'],
+ ['Charter, "Bitstream Charter", Cambria, Georgia, serif', 'Charter (serif)'],
+ ['-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif', 'System (sans)'],
+ ['Helvetica, Arial, sans-serif', 'Helvetica'],
+ ['Verdana, Geneva, sans-serif', 'Verdana'],
+ ['ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', 'Monospace'],
+];
+
+const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string): HTMLElementTagNameMap[K] => {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ return n;
+};
+const row = (host: HTMLElement, label: string, control: HTMLElement): void => {
+ const r = el('div', 't-sty-row');
+ const s = el('span'); s.textContent = label;
+ r.append(s, control);
+ host.appendChild(r);
+};
+const select = (options: Array<[string, string]>, value: string, onChange: (v: string) => void): HTMLSelectElement => {
+ const s = el('select', 't-select');
+ for (const [v, label] of options) {
+ const o = el('option'); o.value = v; o.textContent = label; o.selected = v === value;
+ s.appendChild(o);
+ }
+ s.addEventListener('change', () => onChange(s.value));
+ return s;
+};
+
+const styleLabel = (s: DocStyle): string => {
+ switch (s.id) {
+ case 'default-body': return t('Body');
+ case 'default-h1': return t('Heading 1');
+ case 'default-h2': return t('Heading 2');
+ case 'default-h3': return t('Heading 3');
+ case 'default-quote': return t('Quote');
+ case 'default-ul': return t('Bulleted list');
+ case 'default-ol': return t('Numbered list');
+ default: return s.name;
+ }
+};
+
+/**
+ * Materialize a style for editing: the document's own copy if it has one,
+ * else a fresh copy of the built-in (or a bare shell for an id that is
+ * neither — a custom id someone applied but never defined). Never mutates;
+ * the caller decides whether the result gets written back. Exported so
+ * scripts/test-type-styles.ts can drive the "first edit copies the built-in"
+ * behaviour without a Store or a DOM.
+ */
+export function materialize(doc: TypeDoc, id: string, kind: BlockKind): DocStyle {
+ const found = lookupStyle(doc, id);
+ return found ? { ...found } : { id, kind, name: id };
+}
+
+/** `materialize`, then a patch on top — the pure half of every style edit. */
+export function mergeStyle(doc: TypeDoc, id: string, kind: BlockKind, patch: Partial<DocStyle>): DocStyle {
+ return { ...materialize(doc, id, kind), ...patch };
+}
+
+/** Write a patch onto a style, creating (materializing) it if needed. ONE commit. */
+function patchStyle(ctx: FeatureContext, id: string, kind: BlockKind, patch: Partial<DocStyle>): void {
+ ctx.store.commit(d => { d.styles = { ...(d.styles ?? {}), [id]: mergeStyle(d, id, kind, patch) }; });
+ ctx.refresh();
+}
+
+/**
+ * The patch "Update style to match this paragraph" would write, captured
+ * PURELY from the model — no store, no DOM, so scripts/test-type-styles.ts
+ * can assert it directly.
+ *
+ * Takes the paragraph's CURRENT effective align/sb/sa/lh/ind (block over
+ * style over document — effectiveLayout) and, when every character agrees on
+ * one, its family/size. Undefined (no active style at all — a kind with no
+ * default, and no explicit styleId) returns null.
+ */
+export function captureStyleFromBlock(doc: TypeDoc, b: Block): Partial<DocStyle> | null {
+ const id = activeStyleId(doc, b);
+ if (!id) return null;
+ const eff = effectiveLayout(doc, b);
+ const font = fontAcross(b.marks ?? [], 0, b.text.length);
+ const patch: Partial<DocStyle> = { align: eff.align, sb: eff.sb, sa: eff.sa, lh: eff.lh, ind: eff.ind };
+ // fontAcross's 'mixed' IS a string (and not a number), so a plain
+ // typeof-check would wrongly capture the literal word "mixed" as a font
+ // family the moment a block held more than one font — exclude it explicitly.
+ if (typeof font.family === 'string' && font.family !== 'mixed') patch.family = font.family;
+ if (typeof font.size === 'number') patch.size = font.size;
+ return patch;
+}
+
+/**
+ * "Update style to match this paragraph" — the workflow that makes a styles
+ * system worth having: nobody opens a typography dialog first, they format
+ * one paragraph until it looks right and then say "make this the style".
+ * The patch itself is `captureStyleFromBlock`; this is only the commit —
+ * write it into the active style, then clear the block's own direct
+ * overrides, since they now equal the style exactly and the paragraph should
+ * stop reading as "modified".
+ */
+function updateStyleToMatch(ctx: FeatureContext, b: Block): void {
+ const id = activeStyleId(ctx.store.doc, b);
+ const patch = captureStyleFromBlock(ctx.store.doc, b);
+ if (!id || !patch) return;
+ ctx.store.commit(d => {
+ d.styles = { ...(d.styles ?? {}), [id]: mergeStyle(d, id, b.kind, patch) };
+ const blk = d.body.find(x => x.id === b.id);
+ if (blk) for (const k of ['align', 'sb', 'sa', 'lh', 'ind'] as const) delete blk[k];
+ });
+ ctx.refresh();
+ ctx.toast(t('Style updated from this paragraph'));
+}
+
+// t() at call time, never frozen into a module-level const — the codebase's
+// one repeated i18n rule (see CLAUDE.md): a const built at import time is
+// built before the viewer's locale resolves.
+const weightOptions = (): Array<[string, string]> => [
+ ['', t('Default')], ['400', t('Regular')], ['500', t('Medium')],
+ ['600', t('Semibold')], ['700', t('Bold')],
+];
+
+/**
+ * The "Styles" section of the properties panel — mounted by props.ts, which
+ * owns the panel's overall assembly and calls this for any block whose kind
+ * has a default style (`DEFAULT_STYLE_ID`). A kind with no default (a
+ * picture, a table cell, a caption…) gets no section: there is nothing here
+ * for it to apply.
+ */
+export function stylesSection(host: HTMLElement, ctx: FeatureContext, b: Block): void {
+ if (!DEFAULT_STYLE_ID[b.kind]) return;
+ const doc = ctx.store.doc;
+ const activeId = activeStyleId(doc, b)!;
+ const active = lookupStyle(doc, activeId);
+
+ const h = el('div', 't-section');
+ h.textContent = t('Style');
+ if (hasDirectFormatting(b)) {
+ const badge = el('span', 't-sty-badge');
+ badge.textContent = t('Modified');
+ badge.title = t('This paragraph has direct formatting of its own, on top of its style.');
+ h.appendChild(badge);
+ }
+ const body = el('div', 't-sec-body');
+ host.append(h, body);
+
+ // ---- which style this block uses
+ const defaultId = DEFAULT_STYLE_ID[b.kind]!;
+ const options: Array<[string, string]> = listStyles(doc).map(s => [s.id, styleLabel(s)]);
+ row(body, t('Applied style'), select(options, activeId, v => {
+ ctx.store.commit(d => {
+ const blk = d.body.find(x => x.id === b.id);
+ if (!blk) return;
+ // "absent means the default" — the same rule the paragraph properties
+ // already follow (layout.ts): choosing the kind's own default deletes
+ // `styleId` rather than writing it, so an untouched document keeps
+ // writing nothing extra.
+ if (v === defaultId) delete blk.styleId; else blk.styleId = v;
+ }, { scope: { block: b.id } });
+ ctx.refresh();
+ }));
+
+ if (hasDirectFormatting(b)) {
+ const clear = el('button', 't-btn') as HTMLButtonElement;
+ clear.type = 'button';
+ clear.textContent = t('Clear direct formatting');
+ clear.addEventListener('click', () => {
+ ctx.store.commit(d => {
+ const blk = d.body.find(x => x.id === b.id);
+ if (!blk) return;
+ for (const k of ['align', 'sb', 'sa', 'lh', 'ind'] as const) delete blk[k];
+ }, { scope: { block: b.id } });
+ ctx.refresh();
+ });
+ const wrap = el('div', 't-toggles');
+ wrap.appendChild(clear);
+ body.appendChild(wrap);
+ }
+
+ // ---- the active style's own typography — editing it repaints EVERY block
+ // that uses this style, explicitly or as its kind's default.
+ const editHead = el('div', 't-section');
+ editHead.textContent = t('Edit “{name}”', { name: styleLabel(active ?? { id: activeId, kind: b.kind, name: activeId }) });
+ const edit = el('div', 't-sec-body');
+ host.append(editHead, edit);
+
+ const faceOptions: Array<[string, string]> = [['', t('Document default')], ...FACE_STACKS];
+ row(edit, t('Typeface'), select(faceOptions, active?.family ?? '', v =>
+ patchStyle(ctx, activeId, b.kind, { family: v || undefined })));
+
+ const sizeIn = el('input', 't-field') as HTMLInputElement;
+ sizeIn.type = 'number';
+ sizeIn.value = active?.size === undefined ? '' : String(active.size);
+ sizeIn.placeholder = t('default');
+ sizeIn.addEventListener('change', () => {
+ const raw = sizeIn.value.trim();
+ const v = raw === '' ? undefined : Number(raw);
+ patchStyle(ctx, activeId, b.kind, { size: v !== undefined && Number.isFinite(v) ? v : undefined });
+ });
+ row(edit, t('Size (px)'), sizeIn);
+
+ row(edit, t('Weight'), select(weightOptions(), active?.weight === undefined ? '' : String(active.weight), v =>
+ patchStyle(ctx, activeId, b.kind, { weight: v === '' ? undefined : Number(v) })));
+
+ const italicBox = el('input') as HTMLInputElement;
+ italicBox.type = 'checkbox';
+ italicBox.checked = active?.italic === true;
+ italicBox.addEventListener('change', () =>
+ patchStyle(ctx, activeId, b.kind, { italic: italicBox.checked ? true : undefined }));
+ row(edit, t('Italic'), italicBox);
+
+ const colorRow = el('div', 't-sty-row');
+ const colorLabel = el('span'); colorLabel.textContent = t('Colour');
+ const colorIn = el('input', 't-sty-color') as HTMLInputElement;
+ colorIn.type = 'color';
+ colorIn.value = /^#[0-9a-fA-F]{6}$/.test(active?.color ?? '') ? active!.color! : '#1a1a1a';
+ colorIn.addEventListener('change', () => patchStyle(ctx, activeId, b.kind, { color: colorIn.value }));
+ const colorClear = el('button', 't-btn') as HTMLButtonElement;
+ colorClear.type = 'button';
+ colorClear.textContent = t('Default');
+ colorClear.addEventListener('click', () => patchStyle(ctx, activeId, b.kind, { color: undefined }));
+ colorRow.append(colorLabel, colorIn, colorClear);
+ edit.appendChild(colorRow);
+
+ const ALIGN_OPTS: Array<[string, string]> = [
+ ['', t('Document default')], ['left', t('Left')], ['center', t('Centre')],
+ ['right', t('Right')], ['justify', t('Justified')],
+ ];
+ row(edit, t('Alignment'), select(ALIGN_OPTS, active?.align ?? '', v =>
+ patchStyle(ctx, activeId, b.kind, { align: (v || undefined) as DocStyle['align'] })));
+
+ const px = (label: string, key: 'sb' | 'sa' | 'ind') => {
+ const i = el('input', 't-field') as HTMLInputElement;
+ i.type = 'number';
+ i.value = active?.[key] === undefined ? '' : String(active[key]);
+ i.placeholder = t('default');
+ i.addEventListener('change', () => {
+ const raw = i.value.trim();
+ const v = raw === '' ? undefined : Number(raw);
+ patchStyle(ctx, activeId, b.kind, { [key]: v !== undefined && Number.isFinite(v) ? v : undefined });
+ });
+ row(edit, label, i);
+ };
+ px(t('Space before (px)'), 'sb');
+ px(t('Space after (px)'), 'sa');
+ px(t('First-line indent (px)'), 'ind');
+
+ const lhIn = el('input', 't-field') as HTMLInputElement;
+ lhIn.type = 'number';
+ lhIn.step = '0.01';
+ lhIn.value = active?.lh === undefined ? '' : String(active.lh);
+ lhIn.placeholder = t('default');
+ lhIn.addEventListener('change', () => {
+ const raw = lhIn.value.trim();
+ const v = raw === '' ? undefined : Number(raw);
+ patchStyle(ctx, activeId, b.kind, { lh: v !== undefined && Number.isFinite(v) ? v : undefined });
+ });
+ row(edit, t('Line spacing'), lhIn);
+
+ const actions = el('div', 't-sty-actions');
+ const updateBtn = el('button', 't-btn') as HTMLButtonElement;
+ updateBtn.type = 'button';
+ updateBtn.textContent = t('Update style to match this paragraph');
+ updateBtn.title = t('Take this paragraph’s current formatting and make it the style — every paragraph using this style follows.');
+ updateBtn.addEventListener('click', () => updateStyleToMatch(ctx, b));
+ actions.appendChild(updateBtn);
+ edit.appendChild(actions);
+
+ const note = el('p', 't-note');
+ note.textContent = t('Editing a style changes every paragraph that uses it — including ones that never set a style explicitly and are just using their kind’s default.');
+ edit.appendChild(note);
+}
diff --git a/type/src/editor.ts b/type/src/editor.ts
index 925c8071..6e5a7398 100644
--- a/type/src/editor.ts
+++ b/type/src/editor.ts
@@ -19,9 +19,12 @@
// model, so it is suppressed and every ⌘Z goes through the store.
import { renderBody, renderBlock, readBlock, isNoteAtom, TAG } from './render.ts';
-import { toggleMark, activeAt, type MarkType } from './inline.ts';
-import { uid, type Block, type TypeDoc } from './model.ts';
+import { toggleMark, activeAt, setFont, fontAcross, type MarkType, type FontAttrs } from './inline.ts';
+import { isList, uid, MAX_LIST_LEVEL, type Block, type TypeDoc } from './model.ts';
import type { Store } from './store.ts';
+import { commentsOnEdit, commentsOnSplit, commentsOnMerge } from './comments.ts';
+import { knownAuthor } from './comments.ts';
+import { tracking, trackEdit, editSpan, caretAfter } from './track.ts';
export interface Caret { id: string; at: number; to?: number }
@@ -147,12 +150,44 @@ export class Editor {
if (!prev) return;
const next = readBlock(el, prev);
if (next.text === prev.text && JSON.stringify(next.marks) === JSON.stringify(prev.marks)) return;
+
+ // TRACKED CHANGES are applied HERE, at the one point where the editor knows
+ // both the before and the after of a block. Deleted characters are put
+ // BACK and marked, so the DOM the browser just produced is no longer what
+ // the model says — which is why this path re-renders and re-places the
+ // caret, and the untracked path (overwhelmingly the common one) does not.
+ const tracked = tracking(this.store.doc)
+ ? trackEdit(prev, next, knownAuthor() || 'Anonymous', new Date().toISOString())
+ : next;
+ // Re-render whenever tracking CHANGED anything — not only when it restored
+ // deleted characters. An insertion leaves the text identical, so the first
+ // version of this skipped the render and the new ins mark sat in the model
+ // with nothing on screen to show for it: you typed into a tracked document
+ // and saw ordinary text.
+ const rerender = tracking(this.store.doc)
+ && (tracked.text !== next.text
+ || JSON.stringify(tracked.marks) !== JSON.stringify(next.marks));
+ const caretAt = rerender ? caretAfter(editSpan(prev, next)) : undefined;
+
// one undo step per typing run, per block
this.#runId ??= `type:${c.id}:${Date.now()}`;
this.store.commit(d => {
const i = d.body.findIndex(b => b.id === c.id);
- if (i >= 0) d.body[i] = next;
+ if (i >= 0) d.body[i] = tracked;
+ // INSIDE the commit deliberately: an anchor that moved outside it would
+ // survive a ⌘Z that put the words back, leaving the comment pointing at
+ // text nobody wrote. Returns false when the block carries no comment, so
+ // an ordinary paragraph never widens anybody's undo scope.
+ commentsOnEdit(d, c.id, prev.text, next.text);
}, { scope: { block: c.id }, run: this.#runId });
+ if (rerender) {
+ // Just THIS block, not the whole body: tracking re-renders on nearly
+ // every keystroke, and renderBody rebuilds every paragraph in the
+ // document — on a long contract that is a visible stall per character.
+ const fresh = renderBlock(tracked);
+ el.replaceWith(fresh);
+ if (caretAt !== undefined) this.setCaret({ id: c.id, at: caretAt });
+ }
this.onChange?.();
};
@@ -169,6 +204,16 @@ export class Editor {
if (!c) return;
if (e.inputType === 'insertParagraph') {
e.preventDefault();
+ // Enter on an EMPTY list item ends the list instead of adding another
+ // empty one — outdenting a level at a time, then becoming a paragraph.
+ // Every word processor does this and its absence is felt immediately:
+ // without it there is no way out of a list except changing the kind by
+ // hand.
+ const blk = this.store.block(c.id);
+ if (blk && isList(blk.kind) && blk.text === '') {
+ this.#exitList(c);
+ return;
+ }
this.#splitBlock(c);
return;
}
@@ -187,16 +232,22 @@ export class Editor {
const tailText = src.text.slice(c.at);
const tail: Block = {
id: uid(),
- // a heading's continuation is a paragraph — nobody wants two headings
- kind: src.kind === 'para' || src.kind === 'quote' ? src.kind : 'para',
+ // a heading's continuation is a paragraph — nobody wants two headings;
+ // a list item's continuation is another item at the same level, which is
+ // what makes a list feel like a list rather than a kind you re-pick
+ kind: src.kind === 'para' || src.kind === 'quote' || isList(src.kind) ? src.kind : 'para',
text: tailText,
};
+ if (isList(src.kind) && src.level) tail.level = src.level;
const shifted = shiftPast(src, c.at);
if (shifted.marks?.length) tail.marks = shifted.marks;
if (shifted.notes?.length) tail.notes = shifted.notes;
this.store.breakRun();
this.#runId = null;
- this.store.commit(d => { d.body.splice(i, 1, head, tail); });
+ this.store.commit(d => {
+ d.body.splice(i, 1, head, tail);
+ commentsOnSplit(d, src.id, c.at, src.text.length, tail.id);
+ });
this.render();
this.setCaret({ id: tail.id, at: 0 });
this.onChange?.();
@@ -213,7 +264,10 @@ export class Editor {
if (notes.length) merged.notes = notes; else delete merged.notes;
this.store.breakRun();
this.#runId = null;
- this.store.commit(d => { d.body.splice(i - 1, 2, merged); });
+ this.store.commit(d => {
+ d.body.splice(i - 1, 2, merged);
+ commentsOnMerge(d, prev.id, cur.id, at);
+ });
this.render();
this.setCaret({ id: merged.id, at });
this.onChange?.();
@@ -242,14 +296,184 @@ export class Editor {
this.onChange?.();
}
+ /**
+ * Set the typeface and/or size across the selection.
+ *
+ * Mirrors toggle(), but it is not a toggle: a font has a VALUE, so choosing
+ * Verdana over a Georgia run replaces it rather than turning something on
+ * and off. Pass null for an attribute to clear it back to the document
+ * default; leave it undefined to change only the other one.
+ */
+ setFontOn(attrs: FontAttrs): void {
+ const c = this.caret();
+ if (!c || c.to === undefined || c.to === c.at) return; // nothing selected
+ const from = Math.min(c.at, c.to), to = Math.max(c.at, c.to);
+ if (!this.store.block(c.id)) return;
+ this.store.breakRun();
+ this.#runId = null;
+ this.store.commit(d => {
+ const i = d.body.findIndex(b => b.id === c.id);
+ if (i < 0) return;
+ const b = d.body[i];
+ const marks = setFont(b.marks ?? [], b.text.length, from, to, attrs);
+ if (marks.length) b.marks = marks; else delete b.marks;
+ }, { scope: { block: c.id } });
+ this.render();
+ this.setCaret({ id: c.id, at: from, to });
+ this.onChange?.();
+ }
+
+ /** The typeface across the selection — a value, 'mixed', or nothing. */
+ fontOfSelection(): { family: string | 'mixed' | undefined; size: number | 'mixed' | undefined } {
+ const c = this.caret();
+ const blk = c ? this.store.block(c.id) : undefined;
+ if (!c || !blk) return { family: undefined, size: undefined };
+ const from = Math.min(c.at, c.to ?? c.at), to = Math.max(c.at, c.to ?? c.at);
+ return fontAcross(blk.marks ?? [], from, to);
+ }
+
/** Change a block's kind — paragraph, heading, quote. */
+ /**
+ * Insert a table at the caret: `rows` x `cols` empty cells, header row first.
+ *
+ * Every cell is a block, so this is an ordinary splice into `body` — nothing
+ * about the caret, the redline or pagination has to learn what a table is.
+ */
+ insertTable(rows = 3, cols = 3): void {
+ const c = this.caret();
+ if (!c) return;
+ const i = this.store.doc.body.findIndex(b => b.id === c.id);
+ if (i < 0) return;
+ const table = uid();
+ const cells: Block[] = [];
+ for (let r = 0; r < rows; r++) {
+ for (let k = 0; k < cols; k++) {
+ cells.push({ id: uid(), kind: 'cell', text: '',
+ cell: { table, cols, ...(r === 0 ? { head: true } : {}) } });
+ }
+ }
+ this.store.breakRun();
+ this.#runId = null;
+ // An empty paragraph at the caret is consumed; anything with text keeps its
+ // place and the table lands after it.
+ const here = this.store.doc.body[i];
+ const at = here.text === '' && here.kind === 'para' ? i : i + 1;
+ const drop = here.text === '' && here.kind === 'para' ? 1 : 0;
+ this.store.commit(d => { d.body.splice(at, drop, ...cells); });
+ this.render();
+ this.setCaret({ id: cells[0].id, at: 0 });
+ this.onChange?.();
+ }
+
+ /**
+ * Tab inside a table moves to the next cell, and off the last cell adds a
+ * row — the behaviour every table editor has, and the one that makes a table
+ * fillable without reaching for the mouse.
+ */
+ #nextCell(back: boolean): boolean {
+ const c = this.caret();
+ if (!c) return false;
+ const body = this.store.doc.body;
+ const i = body.findIndex(b => b.id === c.id);
+ const here = body[i];
+ if (i < 0 || here?.kind !== 'cell' || !here.cell) return false;
+ const step = back ? -1 : 1;
+ const next = body[i + step];
+ if (next?.kind === 'cell' && next.cell?.table === here.cell.table) {
+ this.setCaret({ id: next.id, at: 0 });
+ return true;
+ }
+ if (back) return true; // at the first cell: stay put
+ // off the end: append one row
+ const { table, cols } = here.cell;
+ const fresh: Block[] = Array.from({ length: cols }, () =>
+ ({ id: uid(), kind: 'cell' as const, text: '', cell: { table, cols } }));
+ this.store.breakRun();
+ this.store.commit(d => { d.body.splice(i + 1, 0, ...fresh); });
+ this.render();
+ this.setCaret({ id: fresh[0].id, at: 0 });
+ this.onChange?.();
+ return true;
+ }
+
+ /** Insert a picture at the caret as its own block. */
+ insertImage(image: { src: string; alt?: string }): void {
+ const c = this.caret();
+ if (!c) return;
+ const i = this.store.doc.body.findIndex(b => b.id === c.id);
+ if (i < 0) return;
+ const here = this.store.doc.body[i];
+ const block: Block = { id: uid(), kind: 'image', text: '', image: { ...image } };
+ // a following paragraph, so there is somewhere to type after the picture —
+ // an image as the last block leaves the caret nowhere to go
+ const after: Block = { id: uid(), kind: 'para', text: '' };
+ const empty = here.kind === 'para' && here.text === '';
+ this.store.breakRun();
+ this.#runId = null;
+ this.store.commit(d => { d.body.splice(empty ? i : i + 1, empty ? 1 : 0, block, after); });
+ this.render();
+ this.setCaret({ id: after.id, at: 0 });
+ this.onChange?.();
+ }
+
+ /** Empty list item + Enter: outdent one level, or leave the list entirely. */
+ #exitList(c: Caret): void {
+ this.store.breakRun();
+ this.#runId = null;
+ this.store.commit(d => {
+ const b = d.body.find(x => x.id === c.id);
+ if (!b) return;
+ const lv = b.level ?? 0;
+ if (lv > 0) b.level = lv - 1 || undefined;
+ else { b.kind = 'para'; delete b.level; }
+ }, { scope: { block: c.id } });
+ this.render();
+ this.setCaret(c);
+ this.onChange?.();
+ }
+
+ /**
+ * Indent or outdent a list item.
+ *
+ * An item may only ever be one level deeper than the item above it. Allowing
+ * a jump would produce a list whose first child is nested two deep, which the
+ * renderer has to express as two <ul>s with nothing between them — legal HTML
+ * that reads as a bug.
+ */
+ indent(by: 1 | -1): boolean {
+ const c = this.caret();
+ if (!c) return false;
+ const i = this.store.doc.body.findIndex(b => b.id === c.id);
+ if (i < 0) return false;
+ const b = this.store.doc.body[i];
+ if (!isList(b.kind)) return false;
+ const cur = b.level ?? 0;
+ const prev = i > 0 ? this.store.doc.body[i - 1] : undefined;
+ const ceiling = prev && isList(prev.kind) ? (prev.level ?? 0) + 1 : 0;
+ const next = Math.max(0, Math.min(by > 0 ? ceiling : cur - 1, MAX_LIST_LEVEL));
+ if (next === cur) return false;
+ this.store.breakRun();
+ this.store.commit(d => {
+ const t = d.body.find(x => x.id === c.id);
+ if (t) { if (next) t.level = next; else delete t.level; }
+ }, { scope: { block: c.id } });
+ this.render();
+ this.setCaret(c);
+ this.onChange?.();
+ return true;
+ }
+
setKind(kind: Block['kind']): void {
const c = this.caret();
if (!c) return;
this.store.breakRun();
this.store.commit(d => {
const b = d.body.find(x => x.id === c.id);
- if (b) b.kind = kind;
+ if (!b) return;
+ b.kind = kind;
+ // a level left behind on a paragraph is dead data that reappears the
+ // moment somebody makes it a list again, at a depth they did not choose
+ if (!isList(kind)) delete b.level;
}, { scope: { block: c.id } });
this.render();
this.setCaret(c);
@@ -259,6 +483,15 @@ export class Editor {
// ───────────────────────────────────────────────────────────── keys
#keydown = (e: KeyboardEvent): void => {
+ // Tab indents a list item. It is NOT swallowed elsewhere: in a document
+ // that is not a list, Tab must still move focus out of the editor, which is
+ // the only way a keyboard user leaves it.
+ if (e.key === 'Tab' && !e.metaKey && !e.ctrlKey && !e.altKey) {
+ // A table cell claims Tab first: inside a grid it means "next cell", and
+ // indenting a cell would mean nothing.
+ if (this.#nextCell(e.shiftKey) || this.indent(e.shiftKey ? -1 : 1)) e.preventDefault();
+ return;
+ }
const mod = e.metaKey || e.ctrlKey;
if (!mod) return;
const k = e.key.toLowerCase();
@@ -277,13 +510,27 @@ export class Editor {
}
};
- #selectionChange = (): void => {
- if (!this.onSelection) return;
+ /**
+ * The marks in force at the caret.
+ *
+ * The same answer `onSelection` pushes, available to ASK for. A panel that
+ * rebuilds itself needs the state at the moment it rebuilds, and a single
+ * push callback can only have one subscriber — so a second consumer either
+ * hijacks it or mirrors it into a variable that is stale by definition.
+ */
+ activeMarks(): Set<MarkType> {
const c = this.caret();
- if (!c) return;
+ if (!c) return new Set();
const blk = this.store.block(c.id);
- if (!blk) return;
- this.onSelection(activeAt(blk.marks ?? [], c.to !== undefined ? Math.min(c.at, c.to) + 1 : c.at));
+ if (!blk) return new Set();
+ return activeAt(blk.marks ?? [], c.to !== undefined ? Math.min(c.at, c.to) + 1 : c.at);
+ }
+
+ #selectionChange = (): void => {
+ if (!this.onSelection) return;
+ const marks = this.activeMarks();
+ if (!this.caret()) return;
+ this.onSelection(marks);
};
destroy(): void {
diff --git a/type/src/embed.ts b/type/src/embed.ts
new file mode 100644
index 00000000..4ec683b7
--- /dev/null
+++ b/type/src/embed.ts
@@ -0,0 +1,258 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// EMBEDDED BENTO ARTIFACTS — a Dash chart, a Slides deck, a Spaces page,
+// sitting inside a document.
+//
+// The shape is settled in docs/DECISIONS.md (2026-08-19) and is deliberately
+// the same in every app and in both directions. It belongs in the kernel; that
+// is a serialized kernel change of its own, so this is the consumer side
+// written against the agreed shape, and lifting it later is a move rather than
+// a redesign.
+//
+// { kind:'embed', app:'bento/dash', doc:{…}|'asset:…', view:'<svg…>', w, h }
+//
+// THE ORDER OF THE THREE TIERS IS THE WHOLE DESIGN:
+//
+// view a static render, ALWAYS present. Paints with no extra code, in any
+// app, including ones that have never heard of `app`. Thumbnails and
+// prints. This is what keeps a self-contained file self-contained.
+// doc the source, ALWAYS present. Round-trips: open it in Dash, edit,
+// come back. This is what stops the embed being a screenshot.
+// live a sandboxed iframe. OPT-IN per embed, because a Bento file is a
+// runnable page and embedding one costs a whole shell.
+//
+// The alternative — compiling the other apps' renderers in — means shipping
+// every renderer in every file to cover the matrix, and version skew between
+// the embedded copy and the real app.
+
+import { uid, type Block } from './model.ts';
+import { t } from './i18n.ts';
+import { registerTool, type FeatureContext } from './features.ts';
+
+// 24×24, 16px, stroke currentColor at width 2 — icons.ts's recipe, which is
+// what must not drift between apps.
+const EMBED_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16"'
+ + ' fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">'
+ + '<rect x="3" y="4" width="18" height="14" rx="2"/><path d="M8 20h8"/>'
+ + '<path d="M8 13l2.5-3 2 2.2L15 8.5"/></svg>';
+
+/** Apps whose artifacts can be embedded. Unknown values are RENDERED, not rejected. */
+export const APPS: Record<string, string> = {
+ 'bento/dash': 'Bento Dash',
+ 'bento/slides': 'Bento Slides',
+ 'bento/spaces': 'Bento Spaces',
+ 'bento/type': 'Bento Type',
+};
+
+export interface EmbedData {
+ app: string;
+ view: string;
+ doc?: unknown;
+ w?: number;
+ h?: number;
+ live?: boolean;
+}
+
+export const embedOf = (b: Block): EmbedData | undefined => {
+ const e = (b as { embed?: EmbedData }).embed;
+ return e && typeof e.app === 'string' && typeof e.view === 'string' ? e : undefined;
+};
+
+/**
+ * Is this SVG safe to drop into the page?
+ *
+ * The static render arrives as markup from a document, and a document is
+ * untrusted input — the same rule that made link hrefs and mark authors get
+ * escaped. An embed is the most attractive place in the format to hide a
+ * script, because its whole purpose is to carry markup someone else produced.
+ *
+ * So: it must BE an svg, and it must contain no script, no foreign content, no
+ * event handler and no external reference. Refusing beats sanitising — a
+ * rejected embed still shows its placeholder and its source is still there, so
+ * nothing is lost but the picture.
+ */
+const BANNED = /<\s*(script|iframe|object|embed|foreignObject|link|meta|style)\b/i;
+const HANDLER = /\son[a-z]+\s*=/i;
+// ALLOW-LIST, not a block-list. The first version enumerated the schemes to
+// refuse — https:, //, a non-image data: — and so let `javascript:alert(1)`
+// straight through, because it was not on the list. Naming the bad things is a
+// losing game: there is always another scheme. This permits a same-document
+// fragment and an inline raster image, and refuses everything else, including
+// relative paths (an embed has no business fetching anything).
+const REMOTE = /\b(?:href|xlink:href|src)\s*=\s*["']?(?!#|data:image\/(?:png|jpe?g|gif|webp);base64,)/i;
+
+export function safeView(svg: string): string | null {
+ const s = svg.trim();
+ if (!/^<svg[\s>]/i.test(s)) return null;
+ if (BANNED.test(s) || HANDLER.test(s) || REMOTE.test(s)) return null;
+ return s;
+}
+
+const esc = (x: string) => x.replace(/[&<>"']/g, c =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]!));
+
+/**
+ * Render an embed.
+ *
+ * `data-atomic` because it is a box with height and no text pagination can
+ * measure — the same treatment images and display equations get, and without it
+ * the paginator would put a page break through the middle of a chart.
+ */
+export function renderEmbed(b: Block): HTMLElement {
+ const host = document.createElement('figure');
+ host.className = 't-embed';
+ host.dataset.id = b.id;
+ host.dataset.atomic = '1';
+
+ const e = embedOf(b);
+ if (!e) {
+ host.append(placeholder(t('This embed is missing its data.')));
+ return host;
+ }
+ if (e.w) host.style.setProperty('--embed-w', `${e.w}px`);
+
+ const view = safeView(e.view);
+ if (view === null) {
+ // An embed whose picture was refused still says what it is and still
+ // carries its source, so a person can open it in the app that made it.
+ host.append(placeholder(t('This embed could not be displayed safely.')));
+ } else {
+ const box = document.createElement('div');
+ box.className = 't-embed-view';
+ box.innerHTML = view;
+ host.appendChild(box);
+ }
+
+ // The PROVENANCE line, not a caption. A caption is a `caption` BLOCK with a
+ // CaptionRef pointing at this one — the same mechanism tables and figures
+ // already use, and the reason it is a block is that a caption needs its own
+ // stable id for cross-references and for the redline to align on. An earlier
+ // version of this read `b.caption` as a string; that field is a CaptionRef,
+ // so the embed would have invented a second, weaker way to caption things
+ // and silently mistyped the format doing it.
+ //
+ // An unknown app is NAMED rather than hidden: format additivity means a file
+ // from a newer app must still make sense here, and "From Bento Whatever"
+ // tells the reader where to go and open it.
+ const cap = document.createElement('figcaption');
+ cap.textContent = t('From {app}').replace('{app}', APPS[e.app] ?? e.app);
+ host.appendChild(cap);
+ return host;
+}
+
+function placeholder(text: string): HTMLElement {
+ const p = document.createElement('div');
+ p.className = 't-embed-missing';
+ p.textContent = text;
+ return p;
+}
+
+/** The embed as plain HTML — for print and for the static first-page preview. */
+export function embedHtml(b: Block): string {
+ const e = embedOf(b);
+ if (!e) return '';
+ const view = safeView(e.view);
+ const cap = `From ${APPS[e.app] ?? e.app}`;
+ return `<figure class="t-embed" data-id="${esc(b.id)}" data-atomic="1">`
+ + (view === null ? `<div class="t-embed-missing">${esc('This embed could not be displayed safely.')}</div>`
+ : `<div class="t-embed-view">${view}</div>`)
+ + `<figcaption>${esc(cap)}</figcaption></figure>`;
+}
+
+// ─────────────────────────────────────────────────────────────── inserting
+
+/**
+ * Insert an embed from a file the user picks.
+ *
+ * A Bento artifact is a whole HTML file, so what is read out of it is the
+ * `#bento-doc` block — the splice contract (PLATFORM §2) guarantees it is
+ * plaintext JSON at a known id, which is precisely what makes one app able to
+ * read another's file without linking its code.
+ */
+export async function insertEmbed(ctx: FeatureContext): Promise<void> {
+ const file = await pickFile();
+ if (!file) return;
+ const html = await file.text();
+ const parsed = readArtifact(html);
+ if (!parsed) {
+ ctx.toast(t('That file does not look like a Bento document.'));
+ return;
+ }
+ const caret = ctx.editor.caret();
+ const block: Block = {
+ id: uid(), kind: 'embed', text: '',
+ embed: parsed,
+ } as Block;
+ ctx.store.commit(d => {
+ const i = caret ? d.body.findIndex(b => b.id === caret.id) : -1;
+ d.body.splice(i >= 0 ? i + 1 : d.body.length, 0, block);
+ });
+ ctx.editor.render();
+ ctx.refresh();
+ ctx.toast(t('Embedded from {app}').replace('{app}', APPS[parsed.app] ?? parsed.app));
+}
+
+/**
+ * Pull the document, and a still of it, out of another app's file.
+ *
+ * The STILL is the interesting part: `preview.ts` in slides writes a static
+ * first-page render into every saved shell so file managers can thumbnail it
+ * with JS off. That render is exactly the picture an embed needs, already in
+ * the file, already static, already safe to show without running anything —
+ * so an embed of a saved Bento file costs no new rendering anywhere.
+ */
+const DOC_BLOCK = /<script[^>]*\bid=["']bento-doc["'][^>]*>([\s\S]*?)<\/script>/i;
+const PREVIEW = /data-bento-preview[^>]*>[\s\S]*?(<svg[\s\S]*?<\/svg>)/i;
+
+export function readArtifact(html: string): EmbedData | null {
+ // Extracted by PATTERN rather than by DOMParser, and this is a narrow licence
+ // rather than a general habit: the splice contract (PLATFORM §2) guarantees
+ // #bento-doc is plaintext JSON at a known id in every Bento file ever
+ // written, which is the only reason a pattern is sound here. It must not grow
+ // into an HTML parser. The gain is that the whole boundary runs — and is
+ // tested — without a DOM, and safeView still validates whatever comes out, so
+ // a mis-extraction can produce a wrong picture but never an unsafe one.
+ const block = DOC_BLOCK.exec(html);
+ if (!block) return null;
+ let parsed: { format?: string };
+ try { parsed = JSON.parse(block[1]); } catch { return null; }
+ const app = typeof parsed?.format === 'string' ? parsed.format : '';
+ if (!app.startsWith('bento/')) return null;
+
+ // slides/src/preview.ts writes a static first-page render into every saved
+ // shell so file managers can thumbnail it with JS off. That render is exactly
+ // the picture an embed wants: already static, already in the file, and safe
+ // to show without running anything.
+ const still = PREVIEW.exec(html);
+ const view = still && safeView(still[1]) ? still[1] : fallbackView(app);
+ return { app, view, doc: parsed };
+}
+
+/** When a file carries no preview, the embed still says what it is. */
+const fallbackView = (app: string): string =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 180" width="320" height="180">`
+ + `<rect width="320" height="180" rx="8" fill="#eef2f7"/>`
+ + `<text x="160" y="94" text-anchor="middle" font-family="system-ui" font-size="13"`
+ + ` fill="#5b6675">${(APPS[app] ?? app).replace(/[<&>]/g, '')}</text></svg>`;
+
+async function pickFile(): Promise<File | null> {
+ return new Promise(resolve => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = '.html,text/html';
+ input.addEventListener('change', () => resolve(input.files?.[0] ?? null), { once: true });
+ input.click();
+ });
+}
+
+registerTool({
+ id: 'embed',
+ icon: EMBED_ICON,
+ get title() { return t('Embed a Bento chart, deck or page'); },
+ group: 'insert',
+ label: () => t('Bento artifact'),
+ order: 50,
+ run: ctx => { void insertEmbed(ctx); },
+});
diff --git a/type/src/features.ts b/type/src/features.ts
new file mode 100644
index 00000000..95b1fba4
--- /dev/null
+++ b/type/src/features.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The feature registry — how a module adds itself to the chrome without
+// editing the chrome.
+//
+// WHY. Every feature wants the same four things: a button in the bar, an item
+// in the ⋯ menu, a panel beside the outline, and a keyboard shortcut. Wiring
+// each one directly into main.ts made that file the place where all features
+// meet, which is fine for two and miserable for ten — and impossible for
+// several people working at once, because every feature's diff touches the same
+// hundred lines.
+//
+// So a feature module registers what it wants and main.ts renders the registry.
+// A feature is then ONE file plus one import line, which is also what makes it
+// reviewable: everything belonging to find-and-replace is in find.ts.
+//
+// Registration happens at import time and the chrome is built after, so order
+// is module evaluation order — deterministic, and the `order` field breaks ties
+// where a group's arrangement matters.
+
+import type { Editor } from './editor.ts';
+import type { Store } from './store.ts';
+
+/** What a feature is handed when it runs. Kept small on purpose. */
+export interface FeatureContext {
+ store: Store;
+ editor: Editor;
+ /** re-paginate and repaint; call after changing the document */
+ refresh(): void;
+ /**
+ * Bring a registered panel to the front, opening the sidebar if it is shut.
+ *
+ * Without this a feature could register a panel and then have no way to show
+ * it — the find feature reached through the DOM for the tab button and
+ * cleared the sidebar's collapsed class by hand, which is a feature knowing
+ * the chrome's markup.
+ */
+ showPanel(id: string): void;
+ /** transient message to the reader */
+ toast(msg: string): void;
+}
+
+/**
+ * A label that may be resolved LATE.
+ *
+ * registerTool/registerPanel run at module scope, so a plain `t('Find')` in a
+ * spec is evaluated at import time — frozen before the viewer's locale
+ * resolves, which is the one i18n rule this codebase repeats everywhere. The
+ * API was quietly forcing every feature to break it: one agent worked around it
+ * with a getter, another noticed and said so. A thunk makes the correct thing
+ * the easy thing, and a plain string still works for anything genuinely
+ * constant.
+ */
+export type Label = string | (() => string);
+export const text = (l: Label): string => (typeof l === 'function' ? l() : l);
+
+export interface ToolSpec {
+ id: string;
+ /** inline SVG, from icons.ts — the house recipe, 24px box at 16px */
+ icon: string;
+ /** tooltip — pass `() => t('…')` so it resolves at render, not at import */
+ title: Label;
+ /** optional visible label beside the icon */
+ label?: Label;
+ /** which cluster of the bar it joins */
+ group: 'format' | 'insert' | 'review' | 'right';
+ order?: number;
+ run(ctx: FeatureContext): void;
+ /** highlight the button when this returns true (called on selection change) */
+ active?(ctx: FeatureContext): boolean;
+}
+
+export interface MenuSpec {
+ id: string;
+ label: Label;
+ icon?: string;
+ order?: number;
+ run(ctx: FeatureContext): void;
+}
+
+export interface PanelSpec {
+ id: string;
+ /** tab label */
+ label: Label;
+ /**
+ * Which side it lives on, and this is not decoration.
+ *
+ * The suite's rule, written down in dash/src/panels.ts and copied from
+ * slides: LEFT is navigation — the list of things in the document — and
+ * RIGHT is the properties of whatever is selected. Two Bento apps that lay
+ * themselves out differently read as two products.
+ *
+ * Getting it wrong is not merely untidy: paragraph layout first landed on
+ * the left, beside Outline and Review, which put "properties of this
+ * paragraph" in the column that answers "what is in this document".
+ */
+ side?: 'left' | 'right';
+ /**
+ * Mount into an EXISTING element instead of creating a tab of its own.
+ *
+ * Every left-hand feature registering its own tab is how the sidebar reached
+ * eight of them — Outline, Review, Signatures, Comments, Figures, Sources,
+ * Find, Math — which is more than fits, and more importantly is not eight
+ * kinds of thing. They are three: where things are, what people did to the
+ * document, and what it cites.
+ *
+ * So a panel can now say "I am a SECTION of the Review tab" rather than "I am
+ * a tab". The tabs are declared once, in main.ts, by someone looking at the
+ * whole sidebar; features fill them.
+ */
+ host?: string;
+ order?: number;
+ /** called once with the panel's host element */
+ mount(host: HTMLElement, ctx: FeatureContext): void;
+ /**
+ * Called whenever the document changes.
+ *
+ * This was declared and never called — a panel implementing it was silently
+ * dead, and the only reason nothing broke is that the first feature to want
+ * it subscribed to the store itself instead. An interface that lies is worse
+ * than one that is missing: the second is a compile error, the first is a
+ * feature that quietly does nothing.
+ */
+ update?(host: HTMLElement, ctx: FeatureContext): void;
+}
+
+export interface KeySpec {
+ /** lowercase key name, as KeyboardEvent.key reports it */
+ key: string;
+ mod?: boolean; // ⌘ / Ctrl
+ shift?: boolean;
+ alt?: boolean;
+ /**
+ * The LITERAL Control key, as distinct from `mod`.
+ *
+ * `mod` deliberately conflates ⌘ and Ctrl, which is right for ⌘S/⌘B and
+ * every other shortcut that means the same thing on both platforms. It is
+ * wrong when a binding differs BY platform: Word moves a paragraph with
+ * Alt+Shift+Arrow on Windows and Ctrl+Shift+Arrow on a Mac, because macOS
+ * already uses Option+Shift+Arrow to extend a selection by paragraph. A
+ * shortcut that has to be Control on one platform and Alt on the other
+ * cannot be expressed with `mod`.
+ */
+ ctrl?: boolean;
+ run(ctx: FeatureContext): void;
+}
+
+/**
+ * Lifecycle hooks.
+ *
+ * `ready` fires once the app is built and a FeatureContext exists; `paginated`
+ * fires after every pagination pass, which is the only moment a feature can
+ * know a page number. Both exist because a feature that needs either had to
+ * reach into main.ts for it otherwise.
+ */
+export type ReadyFn = (ctx: FeatureContext) => void;
+export type PaginatedFn = (ctx: FeatureContext, metrics: unknown, host: HTMLElement) => void;
+const READY: ReadyFn[] = [];
+const PAGINATED: PaginatedFn[] = [];
+export const registerReady = (f: ReadyFn): void => { READY.push(f); };
+
+/**
+ * The caret moved, or the selection changed.
+ *
+ * A CONTEXTUAL panel needs this and the document signal is not enough: moving
+ * the caret from a paragraph into a table cell changes what the properties
+ * panel should show without changing a byte of the document.
+ */
+export type SelectionFn = (ctx: FeatureContext) => void;
+const SELECTION: SelectionFn[] = [];
+export const registerSelection = (f: SelectionFn): void => { SELECTION.push(f); };
+export const selectionFns = (): SelectionFn[] => SELECTION;
+export const registerPaginated = (f: PaginatedFn): void => { PAGINATED.push(f); };
+export const readyFns = (): ReadyFn[] => READY;
+export const paginatedFns = (): PaginatedFn[] => PAGINATED;
+
+const TOOLS: ToolSpec[] = [];
+const MENU: MenuSpec[] = [];
+const PANELS: PanelSpec[] = [];
+const KEYS: KeySpec[] = [];
+
+export const registerTool = (t: ToolSpec): void => { TOOLS.push(t); };
+export const registerMenuItem = (m: MenuSpec): void => { MENU.push(m); };
+export const registerPanel = (p: PanelSpec): void => { PANELS.push(p); };
+export const registerKey = (k: KeySpec): void => { KEYS.push(k); };
+
+const byOrder = <T extends { order?: number }>(a: T[]): T[] =>
+ [...a].sort((x, y) => (x.order ?? 100) - (y.order ?? 100));
+
+export const tools = (group: ToolSpec['group']): ToolSpec[] =>
+ byOrder(TOOLS.filter(t => t.group === group));
+export const menuItems = (): MenuSpec[] => byOrder(MENU);
+export const panels = (side: 'left' | 'right' = 'left'): PanelSpec[] =>
+ byOrder(PANELS.filter(p => (p.side ?? 'left') === side));
+export const keys = (): KeySpec[] => KEYS;
+
+/** Does this event match a registered shortcut? Returns the first match. */
+export function matchKey(e: KeyboardEvent): KeySpec | undefined {
+ const mod = e.metaKey || e.ctrlKey;
+ return KEYS.find(k => {
+ if (k.key !== e.key.toLowerCase()) return false;
+ if (!!k.shift !== e.shiftKey || !!k.alt !== e.altKey) return false;
+ // `ctrl` asks for Control SPECIFICALLY — and not Command, or a Mac user
+ // pressing ⌘⇧↑ (select to the start of the document) would move a block.
+ if (k.ctrl) return e.ctrlKey && !e.metaKey;
+ return !!k.mod === mod;
+ });
+}
diff --git a/type/src/find.ts b/type/src/find.ts
new file mode 100644
index 00000000..414c7b29
--- /dev/null
+++ b/type/src/find.ts
@@ -0,0 +1,552 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Find and replace.
+//
+// NEEDS FROM THE CORE:
+// 1. `PanelSpec.update` is declared in features.ts ("called whenever the
+// document changes") and main.ts NEVER CALLS IT — the panel loop at
+// main.ts:342 only calls `spec.mount`. So a feature that implements
+// `update` is silently dead. This module works around it by subscribing to
+// `ctx.store.on(...)` itself, which is correct but means every panel will
+// grow its own subscription and its own de-duplication. Fix: in the panel
+// loop, `if (spec.update) store.on(() => spec.update!(panel, featureCtx))`
+// — or drop `update` from the interface so it cannot be believed.
+// 2. There is no way for a feature to SHOW its own panel. `showTab` is a
+// local function in main.ts, and ⌘F must raise the Find panel (and undo a
+// collapsed sidebar) to be worth anything. This module therefore clicks
+// the registered tab button and clears `.t-side-off` through the DOM,
+// which works but reaches into chrome the registry is supposed to hide.
+// Fix: add `showPanel(id: string): void` to FeatureContext.
+//
+// WHAT THIS FILE IS CAREFUL ABOUT.
+//
+// A. A REPLACE IS A SPLICE, and the splice already exists. `model.spliceText`
+// moves marks AND footnote anchors together, because they are offsets into
+// the same string and a version that moved only one of them is a bug this
+// project has already paid for. So replace does no offset arithmetic of its
+// own — it computes WHERE, and spliceText does the rest.
+//
+// B. HIGHLIGHTS ARE NOT IN THE DOCUMENT. A match is a decoration: ranges handed
+// to the CSS Custom Highlight API, which paints without touching the DOM at
+// all. That matters for three separate reasons — a mark would be saved to
+// disk and signed, a wrapper element inside contentEditable would move the
+// caret and be read back into the model by `readBlock`, and either one would
+// make searching an undoable edit. Where the API is missing, the current
+// match is shown by SELECTING it, which is a decoration the browser owns.
+//
+// C. SEARCH IS INDEX-EXACT. Case folding is done per character and only when
+// the fold is one character long (see `fold`), because `'İ'.toLowerCase()`
+// is TWO characters: a lowercased haystack can be longer than the text it
+// came from, and then every offset after it addresses the wrong place — a
+// replace would splice into the middle of a word. Being slightly less clever
+// about Turkish dotted capitals is the right trade against corrupting marks.
+//
+// Every block is searched, and that is free: list items and table cells ARE
+// blocks (model.ts), so `doc.body` already is every searchable character.
+
+import { registerKey, registerPanel, registerTool, type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+import { spliceText, type Block } from './model.ts';
+import { isNoteAtom } from './render.ts';
+
+// ───────────────────────────────────────────────────────────── the search
+
+export interface FindOpts {
+ matchCase?: boolean;
+ wholeWord?: boolean;
+}
+
+/** One hit: which block, and the half-open character range inside its text. */
+export interface Match {
+ /** index into doc.body — the document order matches are stepped through in */
+ block: number;
+ /** the block's id, so a match survives a re-render */
+ id: string;
+ from: number;
+ /** exclusive */
+ to: number;
+}
+
+/** What counts as being inside a word, for the whole-word option. */
+const WORD = /[\p{L}\p{N}_]/u;
+
+/**
+ * Length-preserving case fold. A character whose lowercase form is not exactly
+ * one character is left alone rather than expanded — see note C above. The
+ * cost is that 'İ' does not match 'i̇' case-insensitively; the alternative is
+ * offsets that drift by one for the rest of the paragraph.
+ */
+const fold = (s: string): string => {
+ let out = '';
+ for (const ch of s) {
+ const low = ch.toLowerCase();
+ out += [...low].length === [...ch].length ? low : ch;
+ }
+ return out;
+};
+
+/** Every occurrence of `query` in `text`, as [from, to) pairs, in order. */
+export function matchesInText(text: string, query: string, opts: FindOpts = {}): Array<[number, number]> {
+ if (!query) return [];
+ const hay = opts.matchCase ? text : fold(text);
+ const needle = opts.matchCase ? query : fold(query);
+ // The fold is per character, so this can only fail on a lone surrogate or a
+ // fold that is legitimately shorter; either way, matching the raw text is
+ // safer than matching a string whose indices no longer address `text`.
+ const subject = hay.length === text.length ? hay : text;
+ const want = hay.length === text.length ? needle : query;
+ const out: Array<[number, number]> = [];
+ let at = 0;
+ for (;;) {
+ const i = subject.indexOf(want, at);
+ if (i < 0) break;
+ const end = i + want.length;
+ // Matches never overlap: after a hit, resume at its end. Without that,
+ // searching "aa" in "aaaa" reports three hits, two of which share
+ // characters — and replacing them in turn would splice text that the
+ // previous replacement already removed.
+ at = end;
+ if (opts.wholeWord) {
+ const before = i > 0 ? text[i - 1] : '';
+ const after = end < text.length ? text[end] : '';
+ if ((before && WORD.test(before)) || (after && WORD.test(after))) continue;
+ }
+ out.push([i, end]);
+ }
+ return out;
+}
+
+/** Every match in the document, in document order. */
+export function findMatches(body: readonly Block[], query: string, opts: FindOpts = {}): Match[] {
+ const out: Match[] = [];
+ body.forEach((b, block) => {
+ for (const [from, to] of matchesInText(b.text, query, opts)) {
+ out.push({ block, id: b.id, from, to });
+ }
+ });
+ return out;
+}
+
+/**
+ * Replace one match, through `spliceText` so marks and footnote anchors follow.
+ * Returns a NEW block; the caller decides where to put it.
+ */
+export function replaceMatch(block: Block, m: Match, replacement: string): Block {
+ return spliceText(block, m.from, m.to - m.from, replacement);
+}
+
+/**
+ * Replace every match in the body. Pure: returns a new array, and the blocks
+ * that had no match are the SAME objects, so the store's snapshot of the
+ * document stays cheap.
+ *
+ * Within a block the matches are applied BACK TO FRONT, so that each splice
+ * happens at an offset the earlier splices have not moved. Doing it forwards
+ * and adding a running delta is the same computation with one more place to be
+ * wrong, and it silently breaks whenever the replacement changes length.
+ */
+export function replaceAll(body: readonly Block[], query: string, replacement: string,
+ opts: FindOpts = {}): { body: Block[]; count: number } {
+ let count = 0;
+ const out = body.map(b => {
+ const hits = matchesInText(b.text, query, opts);
+ if (!hits.length) return b;
+ count += hits.length;
+ let next = b;
+ for (let i = hits.length - 1; i >= 0; i--) {
+ next = spliceText(next, hits[i][0], hits[i][1] - hits[i][0], replacement);
+ }
+ return next;
+ });
+ return { body: out, count };
+}
+
+/**
+ * The first match at or after a position — where the cursor lands once a
+ * replacement has shifted everything after it.
+ *
+ * It steps PAST the text just inserted rather than back to index 0, because a
+ * replacement that contains the query ("cat" → "cats") would otherwise put the
+ * cursor on the match it just made and Replace would never advance.
+ */
+export function nextFrom(matches: readonly Match[], block: number, at: number): number {
+ const i = matches.findIndex(m => m.block > block || (m.block === block && m.from >= at));
+ return i < 0 ? (matches.length ? 0 : -1) : i;
+}
+
+// ─────────────────────────────────────────────────────────── decoration
+
+const HL_OTHER = 't-find';
+const HL_CURRENT = 't-find-cur';
+
+/** The highlight registry, when the browser has one. Never assume it does. */
+const registry = (): HighlightRegistry | null =>
+ typeof CSS !== 'undefined' && 'highlights' in CSS ? CSS.highlights : null;
+
+/**
+ * The DOM point `at` characters into a rendered block.
+ *
+ * Footnote markers are skipped: they are atoms that occupy a position and no
+ * characters (render.ts), which is the same rule the caret uses. Counting them
+ * would make every highlight after a note land one character late.
+ */
+function pointAt(root: HTMLElement, at: number): { node: Node; offset: number } | null {
+ let count = 0;
+ let last: { node: Node; offset: number } | null = null;
+ const walk = (n: Node): { node: Node; offset: number } | null => {
+ if (n.nodeType === 3) {
+ const len = n.nodeValue!.length;
+ if (count + len >= at) return { node: n, offset: at - count };
+ count += len;
+ last = { node: n, offset: len };
+ return null;
+ }
+ if (n.nodeType === 1 && isNoteAtom(n as Element)) return null;
+ for (const c of Array.from(n.childNodes)) { const r = walk(c); if (r) return r; }
+ return null;
+ };
+ for (const c of Array.from(root.childNodes)) { const r = walk(c); if (r) return r; }
+ return last;
+}
+
+function rangeFor(host: HTMLElement, m: Match): Range | null {
+ const el = host.querySelector<HTMLElement>(`[data-id="${CSS.escape(m.id)}"]`);
+ if (!el) return null;
+ const a = pointAt(el, m.from), b = pointAt(el, m.to);
+ if (!a || !b) return null;
+ const r = document.createRange();
+ r.setStart(a.node, a.offset);
+ r.setEnd(b.node, b.offset);
+ return r;
+}
+
+// ────────────────────────────────────────────────────────────── the panel
+
+/** Everything the panel needs to remember between keystrokes. */
+interface State {
+ query: string;
+ replacement: string;
+ opts: FindOpts;
+ matches: Match[];
+ cur: number;
+}
+
+class FindPanel {
+ readonly #ctx: FeatureContext;
+ readonly #state: State = { query: '', replacement: '', opts: {}, matches: [], cur: -1 };
+ #q!: HTMLInputElement;
+ #r!: HTMLInputElement;
+ #count!: HTMLElement;
+ #buttons: HTMLButtonElement[] = [];
+
+ constructor(host: HTMLElement, ctx: FeatureContext) {
+ this.#ctx = ctx;
+ this.#build(host);
+ // See NEEDS FROM THE CORE (1): the registry's own `update` hook is never
+ // called, so the panel watches the document itself. Re-running the search
+ // on every commit is what keeps the count honest while somebody types.
+ ctx.store.on(() => this.#rerun());
+ }
+
+ // ─────────────────────────────────────────────────────────── chrome
+
+ #build(host: HTMLElement): void {
+ const box = document.createElement('div');
+ box.className = 't-find';
+
+ this.#q = document.createElement('input');
+ this.#q.type = 'text';
+ this.#q.className = 't-find-q';
+ this.#q.placeholder = t('Find in document');
+ this.#q.setAttribute('aria-label', t('Find in document'));
+
+ this.#r = document.createElement('input');
+ this.#r.type = 'text';
+ this.#r.className = 't-find-r';
+ this.#r.placeholder = t('Replace with');
+ this.#r.setAttribute('aria-label', t('Replace with'));
+
+ const opts = document.createElement('div');
+ opts.className = 't-find-opts';
+ const option = (label: string, set: (on: boolean) => void) => {
+ const l = document.createElement('label');
+ const cb = document.createElement('input');
+ cb.type = 'checkbox';
+ cb.addEventListener('change', () => { set(cb.checked); this.#search(true); });
+ l.append(cb, document.createTextNode(label));
+ opts.appendChild(l);
+ };
+ option(t('Match case'), on => { this.#state.opts.matchCase = on; });
+ option(t('Whole word'), on => { this.#state.opts.wholeWord = on; });
+
+ const bar = document.createElement('div');
+ bar.className = 't-find-bar';
+ this.#count = document.createElement('span');
+ this.#count.className = 't-find-count';
+ const prev = this.#button(t('Previous match (⇧Enter)'), '↑', () => this.step(-1));
+ const next = this.#button(t('Next match (Enter)'), '↓', () => this.step(1));
+ bar.append(this.#count, prev, next);
+
+ const actions = document.createElement('div');
+ actions.className = 't-find-actions';
+ actions.append(
+ this.#button(t('Replace this match'), t('Replace'), () => this.#replaceCurrent()),
+ this.#button(t('Replace every match, as one undo step'), t('Replace all'), () => this.#replaceAll()),
+ );
+
+ this.#q.addEventListener('input', () => this.#search(true));
+ this.#q.addEventListener('keydown', e => {
+ if (e.key !== 'Enter') return;
+ e.preventDefault();
+ this.step(e.shiftKey ? -1 : 1);
+ });
+ this.#r.addEventListener('input', () => { this.#state.replacement = this.#r.value; });
+ this.#r.addEventListener('keydown', e => {
+ if (e.key === 'Enter') { e.preventDefault(); this.#replaceCurrent(); }
+ });
+ for (const el of [this.#q, this.#r]) {
+ el.addEventListener('keydown', e => { if (e.key === 'Escape') this.close(); });
+ }
+
+ box.append(this.#q, this.#r, opts, bar, actions);
+ host.appendChild(box);
+ this.#paint();
+ }
+
+ #button(title: string, label: string, run: () => void): HTMLButtonElement {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.title = title;
+ b.textContent = label;
+ // mousedown, not click: pressing a button must not cost the caret, which is
+ // the same reason the toolbar in main.ts binds mousedown.
+ b.addEventListener('mousedown', e => { e.preventDefault(); run(); });
+ this.#buttons.push(b);
+ return b;
+ }
+
+ // ───────────────────────────────────────────────────────── searching
+
+ /** Re-run the search. `reset` re-picks the current match from the top. */
+ #search(reset: boolean): void {
+ const s = this.#state;
+ s.query = this.#q.value;
+ const before = s.matches[s.cur];
+ s.matches = findMatches(this.#ctx.store.doc.body, s.query, s.opts);
+ if (reset || !before) {
+ s.cur = s.matches.length ? 0 : -1;
+ } else {
+ const i = nextFrom(s.matches, before.block, before.from);
+ s.cur = s.matches.length ? Math.max(0, i) : -1;
+ }
+ this.#paint();
+ this.#repaint();
+ }
+
+ /** The document changed under us — keep the count and the cursor sane. */
+ #rerun(): void {
+ if (!this.#state.query) return;
+ this.#search(false);
+ }
+
+ step(by: 1 | -1): void {
+ const s = this.#state;
+ if (!s.matches.length) return;
+ // wraps, in both directions: a find that stops at the end of the document
+ // makes people scroll back to the top by hand
+ s.cur = (s.cur + by + s.matches.length) % s.matches.length;
+ this.#paint();
+ this.#repaint();
+ this.#reveal();
+ }
+
+ #paint(): void {
+ const s = this.#state;
+ this.#count.textContent = !s.query ? ''
+ : !s.matches.length ? t('No matches')
+ : t('{n} of {total}', { n: s.cur + 1, total: s.matches.length });
+ for (const b of this.#buttons) b.disabled = !s.matches.length;
+ }
+
+ // ─────────────────────────────────────────────────────── highlighting
+
+ #frame: number | null = null;
+
+ /**
+ * Paint on the NEXT frame, never in this one.
+ *
+ * A document change re-renders the body, and the re-render happens AFTER the
+ * store has told its listeners — so decorating straight from the listener
+ * builds ranges over nodes that are about to be thrown away, and the
+ * highlights vanish while the count stays right. Measured exactly that way:
+ * ⌘Z after a Replace all left "1 of 3" on screen with nothing painted.
+ */
+ #repaint(): void {
+ if (this.#frame !== null) cancelAnimationFrame(this.#frame);
+ this.#frame = requestAnimationFrame(() => { this.#frame = null; this.#decorate(); });
+ }
+
+ #decorate(): void {
+ const s = this.#state;
+ const reg = registry();
+ if (!reg) return;
+ reg.delete(HL_OTHER);
+ reg.delete(HL_CURRENT);
+ if (!s.matches.length) return;
+ const host = this.#ctx.editor.host;
+ const others = s.matches
+ .filter((_, i) => i !== s.cur)
+ .map(m => rangeFor(host, m))
+ .filter((r): r is Range => r !== null);
+ const current = s.matches[s.cur] ? rangeFor(host, s.matches[s.cur]) : null;
+ if (others.length) reg.set(HL_OTHER, new Highlight(...others));
+ if (current) {
+ const hl = new Highlight(current);
+ // the current match must win where the two overlap, which they cannot
+ // today — but they will the moment a match is ever painted twice
+ hl.priority = 1;
+ reg.set(HL_CURRENT, hl);
+ }
+ }
+
+ /** Bring the current match on screen — and, with no highlight API, show it. */
+ #reveal(): void {
+ const s = this.#state;
+ const m = s.matches[s.cur];
+ if (!m) return;
+ const host = this.#ctx.editor.host;
+ const el = host.querySelector<HTMLElement>(`[data-id="${CSS.escape(m.id)}"]`);
+ el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ if (registry()) return;
+ // Fallback: the browser's own selection is a decoration too, and it is the
+ // one every browser has. It costs the focus of the find field, so it is
+ // never done when the highlight API is available.
+ const r = rangeFor(host, m);
+ if (!r) return;
+ const sel = getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(r);
+ }
+
+ // ───────────────────────────────────────────────────────── replacing
+
+ #replaceCurrent(): void {
+ const s = this.#state;
+ const m = s.matches[s.cur];
+ if (!m) return;
+ const { store } = this.#ctx;
+ store.breakRun();
+ store.commit(d => {
+ const i = d.body.findIndex(b => b.id === m.id);
+ if (i < 0) return;
+ d.body[i] = replaceMatch(d.body[i], m, s.replacement);
+ }, { scope: { block: m.id } });
+ this.#ctx.refresh();
+ // Re-find, then land on the first match PAST the text just written, so a
+ // replacement containing the query does not re-match itself for ever.
+ s.matches = findMatches(store.doc.body, s.query, s.opts);
+ s.cur = s.matches.length ? Math.max(0, nextFrom(s.matches, m.block, m.from + s.replacement.length)) : -1;
+ this.#paint();
+ this.#repaint();
+ this.#reveal();
+ }
+
+ #replaceAll(): void {
+ const s = this.#state;
+ if (!s.query || !s.matches.length) return;
+ const { store } = this.#ctx;
+ store.breakRun();
+ let count = 0;
+ // ONE commit, so the whole sweep is ONE ⌘Z. A per-match commit would make
+ // undoing a 400-match replace a physical exercise.
+ store.commit(d => {
+ const r = replaceAll(d.body, s.query, s.replacement, s.opts);
+ d.body = r.body;
+ count = r.count;
+ });
+ store.breakRun();
+ this.#ctx.refresh();
+ this.#search(true);
+ this.#ctx.toast(count === 1 ? t('Replaced 1 match') : t('Replaced {n} matches', { n: count }));
+ }
+
+ // ──────────────────────────────────────────────────────────── opening
+
+ /** ⌘F: raise the panel, seed it from the selection, take the focus. */
+ focus(): void {
+ const c = this.#ctx.editor.caret();
+ if (c && c.to !== undefined && c.to !== c.at) {
+ const blk = this.#ctx.store.block(c.id);
+ const word = blk?.text.slice(Math.min(c.at, c.to), Math.max(c.at, c.to)) ?? '';
+ if (word && !word.includes('\n')) this.#q.value = word;
+ }
+ this.#q.focus();
+ this.#q.select();
+ this.#search(true);
+ if (this.#state.cur >= 0) this.#reveal();
+ }
+
+ /** Escape: stop painting matches, and give the document back its focus. */
+ close(): void {
+ const reg = registry();
+ reg?.delete(HL_OTHER);
+ reg?.delete(HL_CURRENT);
+ this.#state.matches = [];
+ this.#state.cur = -1;
+ this.#paint();
+ this.#ctx.editor.host.focus();
+ }
+}
+
+// ────────────────────────────────────────────────────────── registration
+
+let panel: FindPanel | null = null;
+
+/**
+ * Show the Find panel. See NEEDS FROM THE CORE (2): with no `showPanel` on the
+ * context, the tab the registry itself created is clicked, and a sidebar the
+ * reader collapsed is re-opened first — ⌘F that reveals nothing is a bug
+ * report, not a shortcut.
+ */
+function showPanel(): void {
+ document.querySelector('.t-main')?.classList.remove('t-side-off');
+ document.querySelector<HTMLElement>('.t-tabs button[data-tab="find"]')?.click();
+}
+
+// The house icon recipe, from icons.ts: 24 box, 16 render, currentColor,
+// width 2, round caps and joins. Declared here rather than added to icons.ts so
+// that everything belonging to this feature stays in this file.
+const SEARCH_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" ' +
+ 'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
+ '<circle cx="11" cy="11" r="7"/><line x1="16.2" y1="16.2" x2="21" y2="21"/></svg>';
+
+registerPanel({
+ id: 'find',
+ // A GETTER, not a value: a label computed at registration time would freeze
+ // before the viewer's locale is resolved (i18n.ts). The registry reads it
+ // when it builds the tab, which is late enough.
+ get label() { return t('Find'); },
+ // the Results view of the Navigate tab — Word's navigation pane has held
+ // headings, pages and search results together for twenty years, and search
+ // results ARE navigation: a list of places to go
+ host: 'findHost',
+ order: 40,
+ mount(host, ctx) { panel = new FindPanel(host, ctx); },
+});
+
+registerTool({
+ id: 'find',
+ icon: SEARCH_ICON,
+ get title() { return t('Find and replace (⌘F)'); },
+ group: 'review',
+ order: 10,
+ run() { showPanel(); panel?.focus(); },
+});
+
+registerKey({
+ key: 'f',
+ mod: true,
+ run() { showPanel(); panel?.focus(); },
+});
diff --git a/type/src/i18n.ts b/type/src/i18n.ts
new file mode 100644
index 00000000..a0614f5a
--- /dev/null
+++ b/type/src/i18n.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Facade: the i18n ENGINE lives in the shared kernel; CATALOGS are per-app
+// string data and live in ./i18n/. This module registers them at import time
+// and re-exports the engine, so registration is guaranteed to precede the first
+// t() call by ES module evaluation order — the same arrangement slides and
+// spaces use.
+//
+// ENGLISH-STRING-AS-KEY (gettext style): the source sentence IS the key, so a
+// missing entry falls back to readable English rather than a blank. Never call
+// t() in a module-level const — it would freeze at import time, before the
+// viewer's locale is resolved. That rule is why the chrome sets its labels from
+// script rather than from the markup template.
+//
+// NO CATALOGS YET, DELIBERATELY, and this is the interesting part.
+//
+// The sweep (every user-visible string routed through t()) and the translation
+// (those strings rendered into eight languages) are two different jobs, and
+// doing them together here would mean doing the second one twice. bento/type is
+// missing lists, tables, images, links and find — each of which brings its own
+// UI strings — so the string set is about to move a lot. Translating an
+// 85-string app that is on its way to a few hundred wastes the translation and,
+// worse, leaves half-translated chrome in the shipped file, which reads as
+// broken in a way plain English does not.
+//
+// So: the sweep lands now, because it must precede any translation and because
+// an un-swept string is invisible to the extractor later. The catalogs land
+// when the tier-1 features are in and the strings have stopped moving. Until
+// then the picker offers nothing, rather than offering languages that would
+// return English — an empty menu is honest and a dead one is not.
+//
+// The engine handles this exact case: with no packed table, t() returns its
+// argument, which IS the English source text.
+
+import { registerI18n } from '../../kernel/src/i18n.ts';
+
+registerI18n({
+ choices: [{ code: 'en', label: 'English' }],
+});
+
+export { t, locale, setLocale, localeChoices } from '../../kernel/src/i18n.ts';
+export type { LocaleChoice } from '../../kernel/src/i18n.ts';
diff --git a/type/src/icons.ts b/type/src/icons.ts
new file mode 100644
index 00000000..2a1ff64c
--- /dev/null
+++ b/type/src/icons.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Minimal inline icon set (lucide-style, stroke = currentColor). No deps.
+//
+// Per-app, as slides/src/icons.ts and spaces/src/icons.ts are: each app needs a
+// different dozen and a shared superset would ship every app the others' icons.
+// The RECIPE is shared and must not drift — 24x24 box, 16px render, stroke
+// currentColor at width 2, round caps and joins — because these sit beside each
+// other in one suite and a heavier stroke reads as a different product.
+
+const svg = (body: string, viewBox = '0 0 24 24') =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
+
+export const ICONS = {
+ // chrome — the same glyphs slides uses for the same jobs, so a person who
+ // learns one app has already learned these
+ panelLeft: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/>'),
+ plus: svg('<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>'),
+ panelRight: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="15" y1="3" x2="15" y2="21"/>'),
+ undo: svg('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>'),
+ redo: svg('<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>'),
+ save: svg('<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>'),
+ more: svg('<circle cx="5" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="12" r="1.5" fill="currentColor" stroke="none"/>'),
+ sync: svg('<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>'),
+ print: svg('<polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8" rx="1"/>'),
+
+ // formatting — a word processor's own vocabulary
+ bold: svg('<path d="M6 4h8a4 4 0 0 1 0 8H6z"/><path d="M6 12h9a4 4 0 0 1 0 8H6z"/>'),
+ italic: svg('<line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/>'),
+ underline: svg('<path d="M6 4v6a6 6 0 0 0 12 0V4"/><line x1="4" y1="21" x2="20" y2="21"/>'),
+ strike: svg('<path d="M16 4H9a3 3 0 0 0-2 5"/><path d="M14 12a3 3 0 0 1-2 5H8"/><line x1="3" y1="12" x2="21" y2="12"/>'),
+ code: svg('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>'),
+ link: svg('<path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/>'),
+
+ bullets: svg('<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1.4" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r="1.4" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r="1.4" fill="currentColor" stroke="none"/>'),
+ numbers: svg('<line x1="10" y1="6" x2="20" y2="6"/><line x1="10" y1="12" x2="20" y2="12"/><line x1="10" y1="18" x2="20" y2="18"/><path d="M3 8V4l-1 .8"/><path d="M2 12h3l-3 4h3" stroke-width="1.6"/>'),
+ indent: svg('<line x1="10" y1="6" x2="20" y2="6"/><line x1="10" y1="12" x2="20" y2="12"/><line x1="10" y1="18" x2="20" y2="18"/><polyline points="3 8 6 12 3 16"/>'),
+ outdent: svg('<line x1="10" y1="6" x2="20" y2="6"/><line x1="10" y1="12" x2="20" y2="12"/><line x1="10" y1="18" x2="20" y2="18"/><polyline points="6 8 3 12 6 16"/>'),
+
+ image: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.5-3.5L6 21"/>'),
+ table: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="9" y1="10" x2="9" y2="20"/><line x1="15" y1="10" x2="15" y2="20"/>'),
+
+ // document furniture
+ note: svg('<path d="M4 4h16v12H8l-4 4z"/>'),
+ sign: svg('<path d="M3 17c3 0 3-10 6-10s3 10 6 10 3-6 6-6"/><line x1="3" y1="21" x2="21" y2="21"/>'),
+ history: svg('<path d="M3 3v6h6"/><path d="M3.5 9a9 9 0 1 0 2.6-4.4L3 9"/><path d="M12 8v5l3.5 2"/>'),
+ review: svg('<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/>'),
+} as const;
+
+export type IconName = keyof typeof ICONS;
diff --git a/type/src/image.ts b/type/src/image.ts
new file mode 100644
index 00000000..533f80ea
--- /dev/null
+++ b/type/src/image.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Pictures — choosing one, and getting it into the document.
+//
+// EMBEDDED BY DEFAULT. The file IS the document, so a picture that lives beside
+// it is a picture that goes missing the first time somebody emails the file.
+// The cost is size, and above IMAGE_EMBED_BUDGET the reader is asked rather
+// than surprised: a browser file picker hands over BYTES, never a path, so
+// "just reference it from disk" is not a thing this app can offer — the URL
+// field is the honest escape hatch.
+//
+// The picture itself is verified before it enters the document. A src that is
+// not plainly an image reference is refused (model.ts SAFE_IMG): a document is
+// untrusted input, and this string goes straight into an <img>.
+
+import { registerTool } from './features.ts';
+import { ICONS } from './icons.ts';
+import { IMAGE_EMBED_BUDGET, SAFE_IMG } from './model.ts';
+import { t } from './i18n.ts';
+
+/** Read a picked file as a data URI. Rejects anything that is not an image. */
+export function readImage(file: File): Promise<{ src: string; alt: string }> {
+ return new Promise((resolve, reject) => {
+ if (!/^image\//.test(file.type)) { reject(new Error('not an image')); return; }
+ const fr = new FileReader();
+ fr.onerror = () => reject(fr.error ?? new Error('unreadable'));
+ fr.onload = () => {
+ const src = String(fr.result ?? '');
+ if (!SAFE_IMG.test(src)) { reject(new Error('unsafe source')); return; }
+ // the file name is a better alt than nothing, and the author can edit it
+ resolve({ src, alt: file.name.replace(/\.[^.]+$/, '') });
+ };
+ fr.readAsDataURL(file);
+ });
+}
+
+/** Human size, for the over-budget question. */
+export const humanSize = (bytes: number): string =>
+ bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.round(bytes / 1024)} KB`;
+
+registerTool({
+ id: 'image',
+ icon: ICONS.image,
+ title: () => t('Insert a picture'),
+ label: () => t('Picture'),
+ group: 'insert',
+ order: 20,
+ run(ctx) {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = 'image/*';
+ input.style.display = 'none';
+ document.body.appendChild(input);
+ input.addEventListener('change', async () => {
+ const file = input.files?.[0];
+ input.remove();
+ if (!file) return;
+ if (file.size > IMAGE_EMBED_BUDGET) {
+ const go = confirm(t(
+ 'This picture is {size}, and embedding it makes the document that much bigger. Insert it anyway?',
+ { size: humanSize(file.size) }));
+ if (!go) return;
+ }
+ try {
+ const image = await readImage(file);
+ ctx.editor.insertImage(image);
+ ctx.refresh();
+ } catch {
+ ctx.toast(t('That file could not be read as a picture.'));
+ }
+ }, { once: true });
+ input.click();
+ },
+});
+
+// The table lives in the Insert menu beside the picture, rather than as its own
+// button in the bar: both are things you place deliberately and rarely, and the
+// menu is what stops the ninth insertable thing costing another 32px.
+registerTool({
+ id: 'table',
+ icon: ICONS.table,
+ title: () => t('Insert a table'),
+ label: () => t('Table'),
+ group: 'insert',
+ order: 10,
+ run(ctx) { ctx.editor.insertTable(); ctx.refresh(); },
+});
diff --git a/type/src/inline.ts b/type/src/inline.ts
index 0c994b4a..b21ecdce 100644
Binary files a/type/src/inline.ts and b/type/src/inline.ts differ
diff --git a/type/src/layout.ts b/type/src/layout.ts
new file mode 100644
index 00000000..e8402274
--- /dev/null
+++ b/type/src/layout.ts
@@ -0,0 +1,1080 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Paragraph layout and page setup — the controls a word processor is expected
+// to have, and the geometry they are expressed in.
+//
+// WHAT IS HERE. Alignment, space before/after, line spacing, first-line indent
+// and the two page-breaking hints (keep with next, keep together) as PARAGRAPH
+// properties; page size, orientation and the four margins as DOCUMENT geometry;
+// and an explicit page break the author inserts. The maths and the
+// property→CSS mapping are pure functions with no DOM in them, because they are
+// the part that has to be right: a wrong millimetre is a wrong printed page,
+// and that is only observable on paper.
+//
+// ────────────────────────────────────────────────────────── 96px = 1in, why
+//
+// The model stores CSS px and this module converts mm and inches into them at
+// 96px to the inch. That is not a convention picked here, it is the definition:
+// CSS defines the px as 1/96 of an inch (css-values-4 §6.2), the browser maps
+// it to physical length when it prints, and print.ts already emits
+// `@page { size: 816px 1056px }` for US Letter — 8.5in × 96 and 11in × 96. So
+// A4 is 210mm × 96/25.4 = 793.7px, rounded to 794. Storing mm instead and
+// converting at print time would put the same constant in the pipeline one step
+// later, with the geometry the editor measures no longer being the geometry the
+// paper has. The rounding is to whole px and it is the ONLY lossy step: 794px
+// is 210.05mm, a twentieth of a millimetre, well inside what any printer's
+// unprintable margin swallows.
+//
+// Locale decides which unit the DIALOG speaks (in for the US, Canada and the
+// Philippines, which never adopted ISO 216; mm everywhere else). The stored
+// value is px in both cases — the unit is a viewer preference, exactly as the
+// locale and the theme are, and it never enters the document.
+//
+// ──────────────────────────────────────────── absent means the document default
+//
+// A paragraph property is written ONLY when it differs from what the document
+// says. A paragraph with no `align` is justified because the document's default
+// is justify — not because someone wrote 'justify' into it. Setting a property
+// to the current default DELETES the field rather than storing it.
+//
+// This is the whole point of the design, not tidiness. It is what makes "make
+// this document ragged-right" one edit to `doc.layout.align` instead of an edit
+// to nine hundred paragraphs, and it is what lets a document imported from
+// elsewhere adopt this document's typography. The cost is that a paragraph
+// deliberately set to the same value as the default is indistinguishable from
+// one that was never touched — and that is the right trade, because a
+// paragraph the author never touched SHOULD follow the document.
+//
+// Consequence for CSS: a block's inline style carries only its own overrides;
+// document defaults are set once on the paper (custom properties, read by the
+// rule block appended to styles.css). Neither is a value baked into a thousand
+// elements.
+//
+// ────────────────────────────────────────────────── the two page-break hints
+//
+// `keepTogether` (do not split this paragraph across pages) and `keepNext` (do
+// not part this paragraph from the one after it — the heading rule) are hints
+// to PAGINATION, not CSS. paginate.ts breaks at a LINE boundary: it measures
+// every line box through a TreeWalker and takes the first line whose bottom
+// overflows. A keep hint means the break may only fall at a BLOCK boundary for
+// the blocks that carry one, so pagination has to know which block each line
+// belongs to — which it deliberately does not today ("pagination stays
+// indifferent — it measures line boxes and never looks at block structure").
+//
+// So the change is real and it is two lines in lineBoxes plus a call: tag each
+// line box with the nearest [data-id] ancestor, then group the tagged boxes
+// into ATOMS (`atomize` below) and pick the break with `breakY` instead of the
+// inline loop. Both are pure and tested here. The escape hatch matters as much
+// as the rule: an atom TALLER than the page cannot be honoured, and pagination
+// falls back to line breaking inside it — without that a keep-together
+// three-page paragraph produces an empty page and then another one, forever.
+//
+// ══════════════════════════════════════════════════════ NEEDS FROM THE CORE
+//
+// Four patches. The module works without them — it applies everything to the
+// editor's DOM itself and draws its own page-break rule — but without (1) the
+// properties do not survive a save, and without (3) an explicit page break and
+// the keep hints do not move a page boundary.
+//
+// (1) model.ts — THE FORMAT. Two additions and one BUG.
+//
+// · `Block` gains the optional paragraph properties:
+//
+// align?: 'left' | 'center' | 'right' | 'justify';
+// sb?: number; // space before, px
+// sa?: number; // space after, px
+// lh?: number; // line spacing, a multiple of the font size
+// ind?: number; // first-line indent, px
+// keepNext?: true; keepTogether?: true; breakBefore?: true;
+//
+// · `PageSpec` gains `marginLeft?: number; marginRight?: number` — absent
+// means `marginX`, so every existing file and every symmetric page keeps
+// writing the one field it writes today.
+//
+// · `TypeDoc` gains `layout?: { align?; sb?; sa?; lh?; ind? }` — the
+// document defaults. Absent means the built-in ones (DOC_DEFAULTS here).
+//
+// · THE BUG: parseDoc BUILDS a fresh block — `const out: Block = { id,
+// kind, text }` — and copies only marks/notes/role/level/cell onto it.
+// Every OTHER field of a block is silently dropped on load. Document-level
+// unknown fields ride along on the object spread and survive; block-level
+// ones do not, so format additivity holds for the document and not for
+// the block, which is where a word processor's additive fields will
+// mostly land. This is not specific to my feature: any block property any
+// future version adds is erased by every older build that opens the file,
+// which is precisely the failure additivity exists to prevent. Minimal
+// fix, in the same place the known fields are copied:
+//
+// const KNOWN = new Set(['id','kind','text','marks','notes','role','level','cell']);
+// for (const [k, v] of Object.entries(b)) if (!KNOWN.has(k)) (out as Record<string, unknown>)[k] = v;
+//
+// and then CLAMP the ones we now know, as `level` already is — align to
+// the four words, lh to 0.5…4, sb/sa/ind to finite and ≥ 0, the three
+// keep flags to `true` — dropping anything else. `Block` also needs
+// `[extra: string]: unknown` for that copy to type-check, matching what
+// `TypeDoc` already declares.
+//
+// (2) render.ts — one line in `renderBlock`, so the editor and PRINT get the
+// same styles from the same place:
+//
+// import { blockStyle } from './layout.ts';
+// ...
+// const st = blockStyle(b); if (st) el.setAttribute('style', st);
+//
+// and the twin in print.ts `bodyHtml`, on the element it already builds:
+// `<${TAG[b.kind]} data-id="…" style="${blockStyle(b)}">`. `blockStyle`
+// takes the BLOCK ALONE by design — defaults belong to the paper, not to
+// ten thousand copies of themselves.
+//
+// (3) paginate.ts — the hints. In `lineBoxes`, tag each box:
+//
+// const owner = (n: Node) => { let p = n.parentElement;
+// while (p && p !== host && !p.dataset.id) p = p.parentElement;
+// return p?.dataset.id; };
+// ... out.push({ top: …, bottom: …, id: owner(n) });
+//
+// and in `paginate`, replace the inner break loop
+//
+// let e = Infinity;
+// for (const b of boxes) { if (b.top < start - 0.5) continue;
+// if (b.bottom - start > avail) { e = b.top; break; } }
+//
+// with `const e = breakY(units, start, avail);` where
+// `const units = atomize(doc.body, boxes)` is computed once, beside
+// `const boxes = …`. `LineBox` gains `id?: string`. Nothing else in that
+// file changes; with no keeps and no breaks in the document `atomize`
+// returns one atom per line and `breakY` reproduces the loop above exactly
+// — verified in scripts/test-type-layout.ts.
+//
+// (4) print.ts — asymmetric margins and the document defaults, both in
+// `printCss`: use `margins(doc.page)` for the page box's left/right padding
+// and for the `.t-run`/`.t-fn` insets, and emit `docVars(doc)` as
+// declarations on `body` so the printed page carries the same defaults the
+// screen does. paginate.ts's note probe (`probe.style.width`) needs the
+// same treatment: `contentBox(page).width`.
+//
+// Until (1) lands, the properties this module writes are lost on the next load
+// — the module is complete and testable, the FILE is not durable.
+
+import type { Block, PageSpec, TypeDoc } from './model.ts';
+import { registerKey, registerPanel, type FeatureContext } from './features.ts';
+import { locale, t } from './i18n.ts';
+
+// ────────────────────────────────────────────────────────────────── geometry
+
+/** CSS defines the px as 1/96 inch. Everything below follows from that. */
+export const PX_PER_IN = 96;
+export const PX_PER_MM = PX_PER_IN / 25.4;
+/** points, for vertical space — typography's own unit, 72 to the inch */
+export const PX_PER_PT = PX_PER_IN / 72;
+
+export type Unit = 'mm' | 'in';
+
+/** px per unit. One table, so no conversion is written twice. */
+const PER: Record<Unit, number> = { mm: PX_PER_MM, in: PX_PER_IN };
+
+export const toUnit = (px: number, u: Unit): number => px / PER[u];
+export const fromUnit = (v: number, u: Unit): number => v * PER[u];
+
+/**
+ * Which unit this reader thinks in.
+ *
+ * The US, Canada and the Philippines never adopted ISO 216 and their paper is
+ * sold in inches; everywhere else is millimetres. A reader's preference, so it
+ * follows the VIEWER's locale and never the document — the same rule the
+ * language picker follows.
+ */
+export function unitFor(loc: string): Unit {
+ const l = loc.toLowerCase();
+ return /(^|-)(us|ca|ph)(-|$)/.test(l) ? 'in' : 'mm';
+}
+
+/** Round for display: inches want 2 decimals (0.25in is a real setting), mm 0. */
+export function formatLen(px: number, u: Unit): string {
+ const v = toUnit(px, u);
+ return u === 'in' ? String(Math.round(v * 100) / 100) : String(Math.round(v));
+}
+
+/** Read a typed length back. Returns null for anything that is not a number. */
+export function parseLen(text: string, u: Unit): number | null {
+ const v = Number(String(text).replace(',', '.').trim());
+ return Number.isFinite(v) ? fromUnit(v, u) : null;
+}
+
+export type SizeId = 'a4' | 'letter' | 'legal';
+export type Orientation = 'portrait' | 'landscape';
+
+/**
+ * The paper sizes, PORTRAIT, in px at 96dpi. Whole px: see the header — the
+ * rounding is a twentieth of a millimetre and it keeps the page an integer
+ * number of device-independent pixels, which is what the editor lays out in.
+ */
+export const PAPER: Record<SizeId, { width: number; height: number }> = {
+ a4: { width: Math.round(210 * PX_PER_MM), height: Math.round(297 * PX_PER_MM) }, // 794 × 1123
+ letter: { width: 8.5 * PX_PER_IN, height: 11 * PX_PER_IN }, // 816 × 1056
+ legal: { width: 8.5 * PX_PER_IN, height: 14 * PX_PER_IN }, // 816 × 1344
+};
+
+/** Which named size this page is, either way up. Undefined = a custom size. */
+export function matchSize(page: PageSpec): SizeId | undefined {
+ const w = page.width, h = page.height;
+ for (const id of Object.keys(PAPER) as SizeId[]) {
+ const p = PAPER[id];
+ if ((near(w, p.width) && near(h, p.height)) || (near(w, p.height) && near(h, p.width))) return id;
+ }
+ return undefined;
+}
+const near = (a: number, b: number) => Math.abs(a - b) <= 1;
+
+export const orientationOf = (page: PageSpec): Orientation =>
+ page.width > page.height ? 'landscape' : 'portrait';
+
+/**
+ * Turn the page. Landscape is not a separate size: it is the same sheet with
+ * width and height exchanged, which is why this swaps rather than looking
+ * anything up — a custom 300×500 page turns too.
+ */
+export function withOrientation(page: PageSpec, o: Orientation): PageSpec {
+ if (orientationOf(page) === o) return { ...page };
+ return { ...page, width: page.height, height: page.width };
+}
+
+/** Apply a named size, keeping the page's current orientation. */
+export function withSize(page: PageSpec, id: SizeId, o = orientationOf(page)): PageSpec {
+ const p = PAPER[id];
+ return withOrientation({ ...page, width: p.width, height: p.height }, o);
+}
+
+/** PageSpec plus the two optional margins core does not know about yet. */
+export interface PageGeom extends PageSpec {
+ marginLeft?: number;
+ marginRight?: number;
+}
+export interface Margins { top: number; right: number; bottom: number; left: number }
+
+/** The four margins. Left and right fall back to `marginX` when absent. */
+export function margins(page: PageSpec): Margins {
+ const g = page as PageGeom;
+ return {
+ top: page.marginTop,
+ bottom: page.marginBottom,
+ left: g.marginLeft ?? page.marginX,
+ right: g.marginRight ?? page.marginX,
+ };
+}
+
+/**
+ * Write four margins back.
+ *
+ * Symmetric margins are stored as `marginX` ALONE — the field every existing
+ * file and every older build already understands. `marginLeft`/`marginRight`
+ * appear only when the two sides genuinely differ (a bound document), so the
+ * common page never depends on a field the core has not shipped yet.
+ */
+export function withMargins(page: PageSpec, m: Margins): PageGeom {
+ const out: PageGeom = { ...(page as PageGeom), marginTop: m.top, marginBottom: m.bottom };
+ if (near(m.left, m.right)) {
+ out.marginX = Math.round(m.left);
+ delete out.marginLeft;
+ delete out.marginRight;
+ } else {
+ out.marginX = Math.round(Math.min(m.left, m.right)); // the fallback stays sane
+ out.marginLeft = Math.round(m.left);
+ out.marginRight = Math.round(m.right);
+ }
+ return out;
+}
+
+/** What is left for text once the margins have had their share. */
+export function contentBox(page: PageSpec): { width: number; height: number } {
+ const m = margins(page);
+ return { width: page.width - m.left - m.right, height: page.height - m.top - m.bottom };
+}
+
+/** A page must leave at least this much room for text, each way. One inch. */
+export const MIN_CONTENT = PX_PER_IN;
+/** and the sheet itself must be at least this big, each way */
+export const MIN_SHEET = 2 * PX_PER_IN;
+export const MAX_SHEET = 48 * PX_PER_IN;
+
+export type PageFault = 'sheet-small' | 'sheet-large' | 'no-width' | 'no-height';
+
+/**
+ * Is this page usable?
+ *
+ * Margins that leave no content area are REJECTED here rather than allowed to
+ * reach pagination, where `bodyHeight` would go negative and the break loop
+ * would place a page every zero pixels until its 2000-iteration guard fired.
+ * The fault is returned as a CODE, not a sentence: this function is called from
+ * a node rig with no locale, and the sentence belongs to the dialog.
+ */
+export function validatePage(page: PageSpec): { ok: true } | { ok: false; fault: PageFault } {
+ if (!(page.width >= MIN_SHEET) || !(page.height >= MIN_SHEET)) return { ok: false, fault: 'sheet-small' };
+ if (page.width > MAX_SHEET || page.height > MAX_SHEET) return { ok: false, fault: 'sheet-large' };
+ const c = contentBox(page);
+ if (c.width < MIN_CONTENT) return { ok: false, fault: 'no-width' };
+ if (c.height < MIN_CONTENT) return { ok: false, fault: 'no-height' };
+ return { ok: true };
+}
+
+/** The fault, said out loud. t() at call time, never frozen into a const. */
+export function faultText(f: PageFault): string {
+ switch (f) {
+ case 'sheet-small': return t('That sheet is smaller than 2 inches — pick a bigger page.');
+ case 'sheet-large': return t('That sheet is larger than any printer takes.');
+ case 'no-width': return t('Those side margins leave no room for text.');
+ default: return t('Those top and bottom margins leave no room for text.');
+ }
+}
+
+// ─────────────────────────────────────────────────── paragraph properties
+
+export type Align = 'left' | 'center' | 'right' | 'justify';
+export const ALIGNS: readonly Align[] = ['left', 'center', 'right', 'justify'];
+
+/** The properties a paragraph may carry, and a document may default. */
+export interface ParaLayout {
+ align?: Align;
+ /** space before, px */
+ sb?: number;
+ /** space after, px */
+ sa?: number;
+ /** line spacing, as a multiple of the font size */
+ lh?: number;
+ /** first-line indent, px */
+ ind?: number;
+}
+/** …plus the three that are page-breaking, not typography. */
+export interface ParaFlags {
+ keepNext?: true;
+ keepTogether?: true;
+ breakBefore?: true;
+}
+export type ParaProps = ParaLayout & ParaFlags;
+
+/**
+ * What the document means when a paragraph says nothing.
+ *
+ * These are the STYLESHEET's own values, restated as numbers so the resolver
+ * has something to compare against. Justify is the default and stays it: the
+ * Knuth–Plass line breaker is what makes justified text worth having, and a
+ * word processor that defaults to ragged-right throws that away.
+ */
+export const DOC_DEFAULTS: Required<ParaLayout> = {
+ align: 'justify',
+ sb: 0,
+ sa: 10,
+ lh: 1.62,
+ ind: Math.round(1.4 * 17 * 10) / 10, // the stylesheet's 1.4em at 17px
+};
+
+const LAYOUT_KEYS = ['align', 'sb', 'sa', 'lh', 'ind'] as const;
+const FLAG_KEYS = ['keepNext', 'keepTogether', 'breakBefore'] as const;
+
+/** A block, read as layout properties. Core has not typed these yet. */
+export const propsOf = (b: Block): ParaProps => b as unknown as ParaProps;
+/** The document's own defaults, over the built-in ones. */
+export const docLayout = (doc: TypeDoc): ParaLayout =>
+ ((doc as { layout?: ParaLayout }).layout ?? {});
+
+/** What actually applies to this paragraph: block over document over built-in. */
+export function effective(doc: TypeDoc, b: Block): Required<ParaLayout> {
+ const d = docLayout(doc), p = propsOf(b);
+ const out = { ...DOC_DEFAULTS };
+ for (const k of LAYOUT_KEYS) {
+ const v = (p[k] ?? d[k]) as never;
+ if (v !== undefined) out[k] = v;
+ }
+ return out;
+}
+
+/** What the document says, where the block says nothing. */
+export function docEffective(doc: TypeDoc): Required<ParaLayout> {
+ const d = docLayout(doc);
+ const out = { ...DOC_DEFAULTS };
+ for (const k of LAYOUT_KEYS) {
+ const v = d[k] as never;
+ if (v !== undefined) out[k] = v;
+ }
+ return out;
+}
+
+/**
+ * Write properties onto a block — the one place absent-means-default is
+ * enforced.
+ *
+ * A value equal to the document default is DELETED rather than stored, so a
+ * paragraph only carries what makes it different. `undefined` in the patch
+ * means "back to the default" and deletes too. Mutates, because it is called
+ * inside store.commit on the live document.
+ */
+export function writeProps(doc: TypeDoc, b: Block, patch: Partial<ParaProps>): void {
+ const target = b as unknown as Record<string, unknown>;
+ const def = docEffective(doc);
+ for (const k of LAYOUT_KEYS) {
+ if (!(k in patch)) continue;
+ const v = patch[k];
+ if (v === undefined || v === def[k]) delete target[k];
+ else target[k] = v;
+ }
+ for (const k of FLAG_KEYS) {
+ if (!(k in patch)) continue;
+ if (patch[k]) target[k] = true; else delete target[k];
+ }
+}
+
+/**
+ * The document defaults, as custom properties for the paper element.
+ *
+ * Only what differs from the stylesheet is emitted, and `data-lay` is what
+ * switches the appended rule block on — a document that never touched any of
+ * this renders through the untouched original rules.
+ */
+export function docVars(doc: TypeDoc): Record<string, string> {
+ const d = docLayout(doc);
+ const out: Record<string, string> = {};
+ if (d.align) out['--lay-align'] = d.align;
+ if (d.lh !== undefined) out['--lay-lh'] = String(d.lh);
+ if (d.sb !== undefined) out['--lay-sb'] = `${d.sb}px`;
+ if (d.sa !== undefined) out['--lay-sa'] = `${d.sa}px`;
+ if (d.ind !== undefined) out['--lay-ind'] = `${d.ind}px`;
+ return out;
+}
+
+/** The page geometry, as the custom properties styles.css already reads. */
+export function pageVars(page: PageSpec): Record<string, string> {
+ const m = margins(page);
+ return {
+ '--page-w': `${page.width}px`,
+ '--page-h': `${page.height}px`,
+ '--mar-x': `${page.marginX}px`,
+ '--mar-l': `${m.left}px`,
+ '--mar-r': `${m.right}px`,
+ '--mar-t': `${m.top}px`,
+ '--mar-b': `${m.bottom}px`,
+ };
+}
+
+/**
+ * One paragraph's own overrides, as inline CSS.
+ *
+ * The BLOCK ALONE — no document, on purpose. What a paragraph does not say is
+ * not its business, and baking the document default into every element is how
+ * "change the document's alignment" stops working.
+ *
+ * `padding-top: 0` rides with `sb` because the stylesheet spaces consecutive
+ * paragraphs with a `margin-top: -10px; padding-top: 10px` pair; overriding
+ * only the margin would leave the padding behind and add 10px to whatever the
+ * author asked for.
+ */
+export function blockStyle(b: Block): string {
+ const p = propsOf(b);
+ const out: string[] = [];
+ if (p.align) out.push(`text-align:${p.align}`);
+ if (p.lh !== undefined) out.push(`line-height:${p.lh}`);
+ if (p.sb !== undefined) out.push(`margin-top:${p.sb}px`, 'padding-top:0');
+ if (p.sa !== undefined) out.push(`margin-bottom:${p.sa}px`);
+ if (p.ind !== undefined) out.push(`text-indent:${p.ind}px`);
+ return out.join(';');
+}
+
+// ──────────────────────────────────────────────── the page-breaking hints
+
+/** A line box as pagination measures it, tagged with the block it belongs to. */
+export interface LineBox { top: number; bottom: number; id?: string }
+
+/**
+ * A unit a page break may fall between. Ordinary text gives one atom per LINE,
+ * which is exactly the freedom pagination has today; a keep hint fuses lines,
+ * or whole blocks, into one.
+ */
+export interface Atom {
+ top: number;
+ bottom: number;
+ /** the lines inside, so an oversized atom can still be broken */
+ lines: LineBox[];
+ /** the author put a page break before this atom */
+ forced: boolean;
+}
+
+/**
+ * Group measured line boxes into break atoms.
+ *
+ * Reads the BODY for hints and the BOXES for geometry, and nothing else — no
+ * DOM, so the interesting cases are testable in node. Boxes with no block id
+ * (a stray text node) are treated as ordinary lines, which is the behaviour
+ * pagination has today.
+ */
+export function atomize(body: readonly Block[], boxes: readonly LineBox[]): Atom[] {
+ const prop = new Map<string, ParaProps>();
+ const order = new Map<string, number>();
+ body.forEach((b, i) => { prop.set(b.id, propsOf(b)); order.set(b.id, i); });
+
+ // consecutive boxes of one block are a run; a box with no id is its own run
+ type Run = { id?: string; lines: LineBox[] };
+ const runs: Run[] = [];
+ for (const box of boxes) {
+ const last = runs[runs.length - 1];
+ if (last && box.id && last.id === box.id) last.lines.push(box);
+ else runs.push({ id: box.id, lines: [box] });
+ }
+
+ const atoms: Atom[] = [];
+ for (let i = 0; i < runs.length; i++) {
+ const group: Run[] = [runs[i]];
+ let forced = !!(runs[i].id && prop.get(runs[i].id!)?.breakBefore);
+ // keepNext fuses this run with the next — repeatedly, so a stack of
+ // headings holds together. A break the author asked for WINS over a keep:
+ // fusing across it would silently discard the break.
+ while (i + 1 < runs.length) {
+ const here = runs[i].id ? prop.get(runs[i].id!) : undefined;
+ const next = runs[i + 1].id ? prop.get(runs[i + 1].id!) : undefined;
+ if (!here?.keepNext || next?.breakBefore) break;
+ group.push(runs[++i]);
+ }
+ const atomic = group.length > 1 ||
+ !!(group[0].id && prop.get(group[0].id!)?.keepTogether);
+ const lines = group.flatMap(r => r.lines);
+ if (!lines.length) continue;
+ if (atomic) {
+ atoms.push({
+ top: Math.min(...lines.map(l => l.top)),
+ bottom: Math.max(...lines.map(l => l.bottom)),
+ lines, forced,
+ });
+ } else {
+ for (const l of lines) {
+ atoms.push({ top: l.top, bottom: l.bottom, lines: [l], forced });
+ forced = false; // only the first line carries it
+ }
+ }
+ }
+ return atoms;
+}
+
+/**
+ * Where the page ends: the paper-space y of the first atom that will not fit
+ * in `avail` starting from `start`, or Infinity if everything left fits.
+ *
+ * With no hints anywhere this is line-for-line the loop paginate.ts runs today,
+ * which is the point — the hints are an addition, not a new pagination.
+ *
+ * The escape hatch: an atom that is taller than the whole page can never be
+ * honoured, so when the overflowing atom is the one the page STARTS with, the
+ * break falls at a line inside it. Without that, a keep-together paragraph
+ * longer than a page would return `start` as the break and pagination would
+ * emit zero-height pages until its guard tripped.
+ */
+export function breakY(atoms: readonly Atom[], start: number, avail: number): number {
+ for (const a of atoms) {
+ if (a.top < start - 0.5) continue;
+ if (a.forced && a.top > start + 0.5) return a.top;
+ if (a.bottom - start > avail) {
+ if (a.top > start + 0.5) return a.top;
+ for (const l of a.lines) {
+ if (l.bottom - start > avail && l.top > start + 0.5) return l.top;
+ }
+ return Infinity; // not even one line fits; take it
+ }
+ }
+ return Infinity;
+}
+
+// ═══════════════════════════════════════════════════════════════════ the UI
+//
+// Everything below touches the DOM. It is separated from the maths above by
+// this line and by nothing else: the pure half is what the rig exercises, the
+// impure half is what a browser needs, and neither imports anything of the
+// other's.
+
+/**
+ * Icons, to the house recipe (icons.ts): a 24×24 box rendered at 16px, stroke
+ * `currentColor` at width 2, round caps and joins. Declared HERE rather than in
+ * icons.ts because a feature is meant to be one file plus one line in
+ * registry.ts — the recipe is what must not drift, not the file it lives in.
+ */
+const svg = (body: string) =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
+const ALIGN_ICON: Record<Align, string> = {
+ left: svg('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="9.5" x2="15" y2="9.5"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="18.5" x2="15" y2="18.5"/>'),
+ center: svg('<line x1="3" y1="5" x2="21" y2="5"/><line x1="6" y1="9.5" x2="18" y2="9.5"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="6" y1="18.5" x2="18" y2="18.5"/>'),
+ right: svg('<line x1="3" y1="5" x2="21" y2="5"/><line x1="9" y1="9.5" x2="21" y2="9.5"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="9" y1="18.5" x2="21" y2="18.5"/>'),
+ justify: svg('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="9.5" x2="21" y2="9.5"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="18.5" x2="21" y2="18.5"/>'),
+};
+
+/**
+ * The unit this reader measures in.
+ *
+ * navigator.language FIRST, `locale()` only as the fallback — and that order is
+ * the bug this exists because of: `locale()` returns the resolved CATALOG
+ * locale, and type ships one catalog, so every reader in the world resolves to
+ * plain 'en' and a US reader was offered millimetres. The catalog a person
+ * reads the chrome in and the paper their printer holds are different
+ * questions.
+ */
+const readerUnit = (): Unit =>
+ unitFor(globalThis.navigator?.language || locale());
+
+const alignLabel = (a: Align): string => a === 'left' ? t('Left')
+ : a === 'center' ? t('Centre') : a === 'right' ? t('Right') : t('Justified');
+
+// ───────────────────────────────────────────── model → the live document DOM
+//
+// The editor renders blocks from the model and knows nothing about layout, so
+// this pass puts the geometry and the per-paragraph styles onto what it drew.
+// When core patch (2) lands, renderBlock does the per-block half at render time
+// and this becomes the page-geometry half alone.
+
+let painting = false;
+
+export function applyToDom(doc: TypeDoc, host: HTMLElement): void {
+ if (painting) return;
+ painting = true;
+ try {
+ // geometry on :root — styles.css declares --page-w and friends there
+ const root = document.documentElement;
+ for (const [k, v] of Object.entries(pageVars(doc.page))) root.style.setProperty(k, v);
+
+ // document defaults on the paper, plus the switch that engages the rules
+ const vars = docVars(doc);
+ for (const k of ['--lay-align', '--lay-lh', '--lay-sb', '--lay-sa', '--lay-ind']) {
+ host.style.removeProperty(k);
+ }
+ for (const [k, v] of Object.entries(vars)) host.style.setProperty(k, v);
+ if (Object.keys(vars).length) host.dataset.lay = '1'; else delete host.dataset.lay;
+
+ // per-paragraph overrides
+ const byId = new Map(doc.body.map(b => [b.id, b]));
+ for (const el of Array.from(host.querySelectorAll<HTMLElement>('[data-id]'))) {
+ const b = byId.get(el.dataset.id!);
+ if (!b) continue;
+ const style = blockStyle(b);
+ if (style) el.setAttribute('style', style); else el.removeAttribute('style');
+ if (propsOf(b).breakBefore) el.dataset.break = '1'; else delete el.dataset.break;
+ }
+ } finally { painting = false; }
+}
+
+/**
+ * Keep the DOM in step.
+ *
+ * Two signals, because the editor re-renders for reasons the store never hears
+ * about (a caret move that splits a block re-renders before it commits): the
+ * store for model changes, a MutationObserver on the paper for renders. The
+ * observer watches childList ONLY — this pass writes style ATTRIBUTES, which
+ * are a different mutation type, so it cannot re-trigger itself.
+ */
+function watch(ctx: FeatureContext): void {
+ const host = ctx.editor.host;
+ const paint = () => applyToDom(ctx.store.doc, host);
+ paint();
+ ctx.store.on(paint);
+ new MutationObserver(paint).observe(host, { childList: true, subtree: true });
+}
+
+// ───────────────────────────────────────────────────────── selection → model
+
+/** The blocks the selection touches, in document order. */
+function selectedIds(ctx: FeatureContext): string[] {
+ const host = ctx.editor.host;
+ const sel = getSelection();
+ const r = sel && sel.rangeCount ? sel.getRangeAt(0) : null;
+ if (r && !r.collapsed && host.contains(r.commonAncestorContainer)) {
+ const hit = Array.from(host.querySelectorAll<HTMLElement>('[data-id]'))
+ .filter(el => r.intersectsNode(el))
+ .map(el => el.dataset.id!);
+ if (hit.length) return hit;
+ }
+ const c = ctx.editor.caret();
+ return c ? [c.id] : [];
+}
+
+/** The block the panel is showing — the first of the selection. */
+function focusBlock(ctx: FeatureContext): Block | undefined {
+ const [id] = selectedIds(ctx);
+ return id ? ctx.store.block(id) : undefined;
+}
+
+/**
+ * Apply paragraph properties to the selection — ONE undo step, whether it
+ * lands on one paragraph or ninety.
+ *
+ * The caret is taken before and restored after, because refresh() re-renders
+ * the whole body and a re-render is a new set of nodes with no selection in
+ * them: without this, changing alignment silently ends text entry.
+ */
+function applyPara(ctx: FeatureContext, patch: Partial<ParaProps>): void {
+ const ids = selectedIds(ctx);
+ if (!ids.length) { ctx.toast(t('Put the caret in a paragraph first')); return; }
+ const set = new Set(ids);
+ const caret = ctx.editor.caret();
+ ctx.store.breakRun();
+ ctx.store.commit(d => {
+ for (const b of d.body) if (set.has(b.id)) writeProps(d, b, patch);
+ });
+ ctx.refresh();
+ ctx.editor.setCaret(caret);
+}
+
+/** Toggle the author's page break on the paragraph the caret is in. */
+function togglePageBreak(ctx: FeatureContext): void {
+ const b = focusBlock(ctx);
+ if (!b) { ctx.toast(t('Put the caret in a paragraph first')); return; }
+ const on = !propsOf(b).breakBefore;
+ if (on && ctx.store.doc.body[0]?.id === b.id) {
+ // a break before the first paragraph would start the document on page 2
+ ctx.toast(t('The first paragraph already starts a page'));
+ return;
+ }
+ applyPara(ctx, { breakBefore: on ? true : undefined });
+ ctx.toast(on ? t('Page break inserted') : t('Page break removed'));
+}
+
+// ────────────────────────────────────────────────────────── page setup dialog
+
+const el = (tag: string, cls?: string): HTMLElement => {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ return n;
+};
+
+/**
+ * Page setup — size, orientation, the four margins, and the document's
+ * paragraph defaults.
+ *
+ * The defaults live here rather than in the paragraph panel because that is
+ * what they are: a property of the DOCUMENT, changed once, followed by every
+ * paragraph that never overrode it. Applying is a single commit, so the whole
+ * dialog is one press of ⌘Z — a page resize that took three undos to put back
+ * would be a trap, since it moves every page break in the file.
+ */
+export function openPageSetup(ctx: FeatureContext): void {
+ const unit = readerUnit();
+ const start = ctx.store.doc.page as PageGeom;
+ let page: PageGeom = { ...start };
+ let defaults: ParaLayout = { ...docLayout(ctx.store.doc) };
+
+ const back = el('div', 't-overlay');
+ const card = el('div', 't-dlg');
+ card.setAttribute('role', 'dialog');
+ card.setAttribute('aria-label', t('Page setup'));
+ const close = () => back.remove();
+
+ const h = (text: string) => { const n = el('h2', 't-dlg-h'); n.textContent = text; return n; };
+ const row = (labelText: string, ...nodes: HTMLElement[]) => {
+ const r = el('div', 't-row');
+ const s = el('span');
+ s.textContent = labelText;
+ r.append(s, ...nodes);
+ return r;
+ };
+ const num = (value: number, on: (v: number) => void) => {
+ const i = el('input', 't-input') as HTMLInputElement;
+ i.type = 'text';
+ i.inputMode = 'decimal';
+ i.value = formatLen(value, unit);
+ i.addEventListener('input', () => {
+ const px = parseLen(i.value, unit);
+ if (px !== null) { on(px); sync(); }
+ });
+ return i;
+ };
+ const select = (options: Array<[string, string]>, value: string, on: (v: string) => void) => {
+ const s = el('select', 't-select') as HTMLSelectElement;
+ for (const [v, label] of options) {
+ const o = document.createElement('option');
+ o.value = v; o.textContent = label;
+ s.append(o);
+ }
+ s.value = value;
+ s.addEventListener('change', () => { on(s.value); sync(); });
+ return s;
+ };
+
+ // ---- size and orientation
+ const sizeSel = select(
+ [['a4', 'A4'], ['letter', t('US Letter')], ['legal', t('US Legal')], ['custom', t('Custom')]],
+ matchSize(page) ?? 'custom',
+ v => {
+ if (v === 'custom') return;
+ page = { ...page, ...withSize(page, v as SizeId) };
+ wIn.value = formatLen(page.width, unit);
+ hIn.value = formatLen(page.height, unit);
+ });
+ const orientSel = select(
+ [['portrait', t('Portrait')], ['landscape', t('Landscape')]],
+ orientationOf(page),
+ v => {
+ page = { ...page, ...withOrientation(page, v as Orientation) };
+ wIn.value = formatLen(page.width, unit);
+ hIn.value = formatLen(page.height, unit);
+ });
+ const wIn = num(page.width, v => { page = { ...page, width: Math.round(v) }; });
+ const hIn = num(page.height, v => { page = { ...page, height: Math.round(v) }; });
+
+ // ---- margins
+ const m0 = margins(page);
+ const set = (k: keyof Margins) => (v: number) => {
+ page = withMargins(page, { ...margins(page), [k]: Math.round(v) });
+ };
+ const mt = num(m0.top, set('top'));
+ const mb = num(m0.bottom, set('bottom'));
+ const ml = num(m0.left, set('left'));
+ const mr = num(m0.right, set('right'));
+
+ // ---- document paragraph defaults
+ const eff = docEffective(ctx.store.doc);
+ const alignSel = select(ALIGNS.map(a => [a, alignLabel(a)] as [string, string]), eff.align,
+ v => { defaults = { ...defaults, align: v as Align }; });
+ const lhSel = select(
+ [['1', '1.0'], ['1.15', '1.15'], ['1.5', '1.5'], ['1.62', t('Book (1.62)')], ['2', '2.0']],
+ String(eff.lh), v => { defaults = { ...defaults, lh: Number(v) }; });
+
+ const readout = el('p', 't-note');
+ const err = el('p', 't-note t-bad');
+ const apply = el('button', 't-btn t-primary') as HTMLButtonElement;
+
+ function sync() {
+ sizeSel.value = matchSize(page) ?? 'custom';
+ orientSel.value = orientationOf(page);
+ const check = validatePage(page);
+ const c = contentBox(page);
+ readout.textContent = t('Text area: {w} × {h} {unit}', {
+ w: formatLen(c.width, unit), h: formatLen(c.height, unit),
+ unit: unit === 'in' ? t('in') : t('mm'),
+ });
+ err.textContent = check.ok ? '' : faultText(check.fault);
+ err.hidden = check.ok;
+ apply.disabled = !check.ok;
+ }
+
+ apply.textContent = t('Apply');
+ apply.addEventListener('click', () => {
+ if (!validatePage(page).ok) return;
+ const caret = ctx.editor.caret();
+ ctx.store.breakRun();
+ // ONE commit: geometry and defaults land together, so ⌘Z puts the document
+ // back exactly as it was — including every page break this moved.
+ ctx.store.commit(d => {
+ d.page = page as PageSpec;
+ const keep: ParaLayout = {};
+ for (const [k, v] of Object.entries(defaults)) {
+ if (v !== undefined && v !== DOC_DEFAULTS[k as keyof ParaLayout]) {
+ (keep as Record<string, unknown>)[k] = v;
+ }
+ }
+ if (Object.keys(keep).length) (d as { layout?: ParaLayout }).layout = keep;
+ else delete (d as { layout?: ParaLayout }).layout;
+ });
+ ctx.refresh();
+ ctx.editor.setCaret(caret);
+ close();
+ });
+
+ const cancel = el('button', 't-btn');
+ cancel.textContent = t('Cancel');
+ cancel.addEventListener('click', close);
+
+ card.append(
+ h(t('Page')),
+ row(t('Size'), sizeSel, orientSel),
+ row(unit === 'in' ? t('Width × height (in)') : t('Width × height (mm)'), wIn, hIn),
+ h(t('Margins')),
+ row(unit === 'in' ? t('Top / bottom (in)') : t('Top / bottom (mm)'), mt, mb),
+ row(unit === 'in' ? t('Left / right (in)') : t('Left / right (mm)'), ml, mr),
+ readout, err,
+ h(t('Paragraph defaults')),
+ row(t('Alignment'), alignSel),
+ row(t('Line spacing'), lhSel),
+ );
+ const note = el('p', 't-note');
+ note.textContent = t('Paragraphs follow these unless they say otherwise.');
+ card.append(note);
+ const foot = el('div', 't-dlg-foot');
+ foot.append(cancel, apply);
+ card.append(foot);
+ sync();
+
+ back.append(card);
+ back.addEventListener('mousedown', e => { if (e.target === back) close(); });
+ document.addEventListener('keydown', function esc(e) {
+ if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); }
+ });
+ document.body.append(back);
+ (sizeSel as HTMLSelectElement).focus();
+}
+
+// ─────────────────────────────────────────────────────────── the panel
+//
+// Paragraph properties live in a PANEL rather than a dialog: they are adjusted
+// while looking at the paragraph, and a modal over the page hides the one thing
+// the author is judging the change by.
+
+function mountPanel(host: HTMLElement, ctx: FeatureContext): void {
+ // NO title of its own: the first group below is already "Paragraph", and
+ // adding a section header above it printed the word twice in a row.
+ watch(ctx);
+ const unit = readerUnit();
+ const wrap = el('div', 't-lay');
+
+ const group = (title: string, ...nodes: HTMLElement[]) => {
+ const g = el('div', 't-lay-g');
+ const hd = el('div', 't-lay-h');
+ hd.textContent = title;
+ g.append(hd, ...nodes);
+ return g;
+ };
+
+ // alignment
+ const alignRow = el('div', 't-lay-row');
+ const alignBtns = ALIGNS.map(a => {
+ const b = el('button', 't-btn') as HTMLButtonElement;
+ b.type = 'button';
+ b.innerHTML = ALIGN_ICON[a];
+ b.title = alignLabel(a);
+ b.addEventListener('mousedown', e => { e.preventDefault(); applyPara(ctx, { align: a }); });
+ alignRow.append(b);
+ return [a, b] as const;
+ });
+
+ const field = (labelText: string, suffix: string, read: (b: Block) => string,
+ write: (v: number | undefined) => Partial<ParaProps>) => {
+ const r = el('div', 't-lay-row');
+ const l = el('label');
+ l.textContent = labelText;
+ const i = el('input', 't-input') as HTMLInputElement;
+ i.type = 'text';
+ i.inputMode = 'decimal';
+ i.addEventListener('change', () => {
+ const raw = i.value.trim();
+ const v = raw === '' ? undefined : Number(raw.replace(',', '.'));
+ applyPara(ctx, write(v !== undefined && Number.isFinite(v) ? v : undefined));
+ });
+ const s = el('span', 't-lay-unit');
+ s.textContent = suffix;
+ r.append(l, i, s);
+ return { row: r, input: i, read };
+ };
+
+ const before = field(t('Space before'), t('pt'),
+ b => trim(effective(ctx.store.doc, b).sb / PX_PER_PT),
+ v => ({ sb: v === undefined ? undefined : v * PX_PER_PT }));
+ const after = field(t('Space after'), t('pt'),
+ b => trim(effective(ctx.store.doc, b).sa / PX_PER_PT),
+ v => ({ sa: v === undefined ? undefined : v * PX_PER_PT }));
+ const indent = field(t('First line'), unit === 'in' ? t('in') : t('mm'),
+ b => formatLen(effective(ctx.store.doc, b).ind, unit),
+ v => ({ ind: v === undefined ? undefined : fromUnit(v, unit) }));
+
+ const lineSel = el('select', 't-select') as HTMLSelectElement;
+ for (const [v, label] of [['1', '1.0'], ['1.15', '1.15'], ['1.5', '1.5'],
+ ['1.62', t('Book (1.62)')], ['2', '2.0']] as Array<[string, string]>) {
+ const o = document.createElement('option');
+ o.value = v; o.textContent = label;
+ lineSel.append(o);
+ }
+ lineSel.addEventListener('change', () => applyPara(ctx, { lh: Number(lineSel.value) }));
+ const lineRow = el('div', 't-lay-row');
+ const lineLabel = el('label');
+ lineLabel.textContent = t('Line spacing');
+ lineRow.append(lineLabel, lineSel);
+
+ const check = (labelText: string, key: keyof ParaFlags, hint: string) => {
+ const l = el('label', 't-lay-check');
+ const i = el('input') as HTMLInputElement;
+ i.type = 'checkbox';
+ i.addEventListener('change', () =>
+ applyPara(ctx, { [key]: i.checked ? true : undefined } as Partial<ParaProps>));
+ const s = document.createElement('span');
+ s.textContent = labelText;
+ l.append(i, s);
+ l.title = hint;
+ return { label: l, input: i, key };
+ };
+ const keepNext = check(t('Keep with next'), 'keepNext',
+ t('This paragraph and the one after it stay on the same page.'));
+ const keepTogether = check(t('Keep together'), 'keepTogether',
+ t('This paragraph is never split across a page break.'));
+ const breakBefore = check(t('Page break before'), 'breakBefore',
+ t('Start this paragraph on a new page.'));
+
+ const reset = el('button', 't-btn') as HTMLButtonElement;
+ reset.type = 'button';
+ reset.textContent = t('Use document defaults');
+ reset.addEventListener('mousedown', e => {
+ e.preventDefault();
+ applyPara(ctx, { align: undefined, sb: undefined, sa: undefined, lh: undefined, ind: undefined });
+ });
+
+ // The page-size summary, and ONLY the summary. The "Page setup…" button that
+ // used to sit beside it, under a second "Document" heading, is gone: page
+ // size and orientation are rows in the props panel's Document section now,
+ // and repeating the entry point here printed "Document" twice in one panel.
+ const summary = el('p', 't-hint');
+
+ wrap.append(
+ group(t('Paragraph'), alignRow, lineRow, before.row, after.row, indent.row),
+ group(t('Page breaking'), keepNext.label, keepTogether.label, breakBefore.label, summary),
+ );
+ const resetRow = el('div', 't-lay-row');
+ resetRow.append(reset);
+ wrap.insertBefore(resetRow, wrap.children[1]);
+ host.append(wrap);
+
+ /** Show what applies to the paragraph under the caret. */
+ const refresh = () => {
+ const b = focusBlock(ctx);
+ const doc = ctx.store.doc;
+ const e = b ? effective(doc, b) : docEffective(doc);
+ for (const [a, btn] of alignBtns) btn.classList.toggle('on', e.align === a);
+ lineSel.value = String(e.lh);
+ if (document.activeElement !== before.input) before.input.value = b ? before.read(b) : '';
+ if (document.activeElement !== after.input) after.input.value = b ? after.read(b) : '';
+ if (document.activeElement !== indent.input) indent.input.value = b ? indent.read(b) : '';
+ const p = b ? propsOf(b) : {};
+ keepNext.input.checked = !!p.keepNext;
+ keepTogether.input.checked = !!p.keepTogether;
+ breakBefore.input.checked = !!p.breakBefore;
+ const size = matchSize(doc.page);
+ const c = contentBox(doc.page);
+ summary.textContent = t('{size}, {orient} · text area {w} × {h} {unit}', {
+ size: size ? size.toUpperCase() : t('Custom'),
+ orient: orientationOf(doc.page) === 'portrait' ? t('Portrait') : t('Landscape'),
+ w: formatLen(c.width, unit), h: formatLen(c.height, unit),
+ unit: unit === 'in' ? t('in') : t('mm'),
+ });
+ };
+ refresh();
+ ctx.store.on(refresh);
+ document.addEventListener('selectionchange', refresh);
+}
+
+const trim = (v: number): string => String(Math.round(v * 10) / 10);
+
+// ─────────────────────────────────────────────────────────── registration
+
+registerPanel({
+ id: 'layout',
+ // RIGHT: these are the properties of the selected paragraph, not a list of
+ // what is in the document. The suite's rule, from dash/src/panels.ts.
+ side: 'right',
+ label: t('Layout'),
+ order: 40,
+ mount: mountPanel,
+});
+
+// Page setup is reached from the Document section of the properties panel;
+// it is a property, not an action, and the ⋯ menu is for actions.
+
+// NO ⋯ entry: "page break here" IS the breakBefore property, which is already
+// a checkbox in the Page breaking group of this panel. Offering it twice, once
+// as an action and once as a property, made the two look like different things.
+// The keyboard shortcut stays — that is the fast path, not a second home.
+
+// ⌘⏎ for the break and ⌘⇧L/E/R/J for alignment — the shortcuts every word
+// processor has had for thirty years. A person should not have to learn ours.
+registerKey({ key: 'enter', mod: true, run: togglePageBreak });
+for (const [key, align] of [['l', 'left'], ['e', 'center'], ['r', 'right'], ['j', 'justify']] as const) {
+ registerKey({ key, mod: true, shift: true, run: ctx => applyPara(ctx, { align }) });
+}
diff --git a/type/src/link.ts b/type/src/link.ts
new file mode 100644
index 00000000..79e780fc
--- /dev/null
+++ b/type/src/link.ts
@@ -0,0 +1,485 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Links.
+//
+// NEEDS FROM THE CORE (two security holes and one ergonomic gap; I have not
+// touched the files they live in):
+//
+// 1. **inline.ts `openTag` does not escape `"` in an href.** `esc()` handles
+// `& < >` only, so a mark with
+// href: 'https://x" onmouseover="alert(1)'
+// renders as
+// <a href="https://x" onmouseover="alert(1)">click me</a>
+// — a real event handler, because render.ts puts that string through
+// `innerHTML`. Verified in this tree, not reasoned about. This is arbitrary
+// script execution from opening a document, and the repo's rule is that
+// every document is untrusted input, so it is reachable without any user of
+// this feature being involved: a hand-written `#bento-doc` block, a pasted
+// `<a>` (fromDom copies the attribute verbatim), or a collaborator's op.
+// FIX: escape `"` in `ESC` — one entry, `'"': '&quot;'`. The round trip
+// survives it, because fromDom reads through `getAttribute`, which decodes.
+//
+// 2. **inline.ts `openTag` emits whatever scheme the mark carries.**
+// `toHtml('x', [{t:'link',from:0,to:1,href:'javascript:alert(1)'}])` yields
+// `<a href="javascript:alert(1)">`. Sanitising at the UI (which this file
+// does, twice) cannot close that, because the model is also written by
+// files, paste and sync. The rendering seam is the only place that sees
+// every href, so the allowlist belongs there too — `safeHref()` below is
+// written to be moved into inline.ts unchanged if you want it.
+//
+// 3. Not a bug, an ergonomic gap: `features.ts` has no `registerInit`, so a
+// feature that needs a listener on the editor cannot get a FeatureContext
+// until one of its own entry points fires. This file works around it by
+// remembering the ctx handed to `active()` (see `remember` — sound, because
+// `active()` runs on every selection change and the caret must be in the
+// document before anyone can type into it), but a one-line
+// `registerInit(fn)` called from main.ts beside `mountTools` would be
+// honest instead of clever, and every later feature will want it.
+//
+// WHAT IS NOT A BUG, because it was worth checking: `normalize()` groups by
+// `` `${m.t} ${m.href ?? ''}` ``, so href IS part of the merge key and two
+// adjacent DIFFERENT links do not fuse into one. That is the invariant this
+// whole feature would otherwise silently violate every time someone linked two
+// words in a row.
+//
+// THREE DECISIONS.
+//
+// A POPOVER, NOT `window.prompt`. prompt() blocks the event loop, cannot show
+// the link you are standing on, cannot offer Remove or Open, and is unstyled —
+// but the disqualifying one is that it destroys the selection in WebKit, and
+// the selection is the range the link is about to be applied to. A popover also
+// gets the caret's own coordinates: the target range is captured as MODEL
+// positions before the input takes focus, so it survives losing the selection
+// entirely, which is the same reason the caret is a model position at all.
+//
+// AUTOLINK IS DELIBERATELY NARROW: an explicit `http(s)://` URL, the `www.`
+// idiom, or an email address. It does NOT fire on a bare `example.com`, and
+// that restraint is the point. This app is aimed at prose — contracts, reports
+// — where a bare-domain rule mangles `index.html`, `README.md` (`.md` is a real
+// TLD), `Schedule A.doc` and `Mr.Smith` on the way past, and the cost is paid
+// on every keystroke of ordinary writing while the escape hatch is one ⌘K.
+// Word autolinks bare domains and it is a famous annoyance, not a feature.
+//
+// COST, since this runs on every input event: the first test is
+// `text[caret-1] === ' '`. Ordinary typing fails it and returns in constant
+// time; only a space arms the backward scan, which is bounded to one token.
+
+import { registerTool, registerKey, type FeatureContext } from './features.ts';
+import { addMark, removeMark, type Mark } from './inline.ts';
+import { isNoteAtom } from './render.ts';
+import { ICONS } from './icons.ts';
+import { t } from './i18n.ts';
+
+// ───────────────────────────────────────────────────────── URL sanitising
+//
+// AN ALLOWLIST, NOT A DENYLIST. A denylist that knows about `javascript:` and
+// `data:` misses `vbscript:`, `blob:`, `filesystem:`, `jar:` and whatever ships
+// next; an allowlist is wrong only in the direction of refusing something
+// harmless, which is the direction a security boundary should fail in.
+
+const SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
+const ALLOWED = new Set(['http', 'https', 'mailto', 'tel']);
+const EMAILISH = /^[^\s@]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,24}$/;
+
+/**
+ * What an author typed, turned into an href that is safe to store and to
+ * render — or `null` if there is no honest reading of it.
+ *
+ * Controls, spaces and DEL are stripped from ANYWHERE in the string, not just
+ * trimmed off the ends. That is not tidiness: browsers strip tab, LF and CR
+ * from a URL before parsing it, so `java\tscript:alert(1)` is a live
+ * `javascript:` URL that a naive `startsWith` check reads as a relative path.
+ * Stripping first means the scheme test sees what the browser will see. Real
+ * URLs cannot contain a raw space in any case — that is what %20 is for.
+ */
+export function sanitizeUrl(raw: string): string | null {
+ const s = (raw ?? '').replace(/[\u0000-\u0020\u007f]/g, '');
+ if (!s) return null;
+ const m = SCHEME.exec(s);
+ if (m) return ALLOWED.has(m[1].toLowerCase()) ? quote(s) : null;
+ // In-document fragment: no scheme, no host, nowhere to go but here.
+ if (s.startsWith('#')) return quote(s);
+ if (EMAILISH.test(s)) return quote('mailto:' + s);
+ // No scheme, so the author meant a web address. Leading slashes are dropped
+ // rather than kept, which is what turns the protocol-relative `//evil.example`
+ // into `https://evil.example`: a Bento document is usually opened from
+ // `file://`, where `//host` means a LOCAL path and a root-relative `/x` means
+ // the filesystem root — neither is ever what somebody typing a link meant.
+ return quote('https://' + s.replace(/^\/+/, ''));
+}
+
+/**
+ * Percent-encode the characters that could end an HTML attribute.
+ *
+ * Belt and braces: this is the renderer's job (NEEDS FROM THE CORE #1) and it
+ * is not doing it, so nothing THIS feature writes into a document will carry a
+ * quote out to `innerHTML`. It is also simply correct — a bare `"` or backtick
+ * in a URL is invalid and every browser encodes it anyway.
+ */
+const quote = (s: string) =>
+ s.replace(/"/g, '%22').replace(/'/g, '%27').replace(/`/g, '%60')
+ .replace(/</g, '%3C').replace(/>/g, '%3E');
+
+/** The second gate: an href already in the model, checked before it is FOLLOWED. */
+export function safeHref(href: string | undefined): string | null {
+ return href ? sanitizeUrl(href) : null;
+}
+
+// ───────────────────────────────────────────────────────────── mark math
+//
+// All of it goes through inline.ts. There is no offset arithmetic in this file
+// and there must never be: `removeMark` already knows how to split a mark that
+// straddles the range, and `addMark` already normalizes, which is what keeps
+// the canonical form — and therefore the signature — stable.
+
+/**
+ * Put a link on [from,to), replace the one that is there, or clear it.
+ *
+ * REMOVE-THEN-ADD, never `toggleMark`. Re-targeting a link means the range is
+ * already fully covered by a link mark, and `toggleMark` reads full coverage as
+ * "the user wants this off" — so editing a link's URL would delete it instead.
+ */
+export function setLink(marks: Mark[], len: number, from: number, to: number,
+ href: string | null): Mark[] {
+ const cleared = removeMark(marks, len, from, to, 'link');
+ return href === null ? cleared : addMark(cleared, len, { t: 'link', from, to, href });
+}
+
+/**
+ * The link the caret is standing on, if any.
+ *
+ * Inclusive at BOTH ends, unlike `activeAt` — deliberately. `activeAt` answers
+ * "what would I be typing in", where the leading boundary is outside; this
+ * answers "which link am I looking at", where standing on the first character
+ * of a link obviously means that one.
+ */
+export function linkAt(marks: Mark[] | undefined, at: number): Mark | undefined {
+ return (marks ?? []).find(m => m.t === 'link' && at >= m.from && at <= m.to);
+}
+
+/** Does any link overlap [from,to)? The autolink guard. */
+export function hasLinkIn(marks: Mark[] | undefined, from: number, to: number): boolean {
+ return (marks ?? []).some(m => m.t === 'link' && m.from < to && m.to > from);
+}
+
+// ───────────────────────────────────────────────────────────── autolink
+
+export interface Autolink { from: number; to: number; href: string }
+
+/** The three shapes worth guessing at. Anchored, so a token matches whole. */
+const AUTO = [
+ /^https?:\/\/[^\s/?#]+\S*$/i, // an explicit web URL
+ /^www\.[^\s/?#]+\.[a-zA-Z]{2,24}(?:[/?#]\S*)?$/i, // the www. idiom
+ EMAILISH,
+];
+
+/** Closing punctuation a sentence puts after a URL rather than inside it. */
+const TRAIL = '.,;:!?\'"”’»)]}';
+const PAIR: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
+const count = (s: string, ch: string) => s.split(ch).length - 1;
+
+/** Longest token we will look back over — a bound, so a pathological line cannot stall typing. */
+const MAX_TOKEN = 2048;
+
+/**
+ * The word just completed by a space, if it is a URL that is not already linked.
+ *
+ * Returns model offsets, so the caller applies it through `setLink` like any
+ * other link and the undo step is an ordinary one.
+ */
+export function autolinkAt(text: string, caret: number, marks: Mark[] = []): Autolink | null {
+ // The O(1) gate. Every keystroke that is not a space stops here.
+ if (caret < 2 || caret > text.length) return null;
+ const sp = text[caret - 1];
+ if (sp !== ' ' && sp !== '\u00a0') return null;
+
+ let end = caret - 1;
+ let from = end;
+ const floor = Math.max(0, end - MAX_TOKEN);
+ while (from > floor && !/\s/.test(text[from - 1])) from--;
+ if (from === end) return null;
+
+ // Strip sentence punctuation, but keep a closing bracket that something in
+ // the URL opened — `…/Foo_(bar)` is the classic case, and a URL that loses
+ // its last character is worse than one that keeps a stray dot.
+ while (end > from && TRAIL.includes(text[end - 1])) {
+ const ch = text[end - 1];
+ const open = PAIR[ch];
+ if (open) {
+ const slice = text.slice(from, end);
+ if (count(slice, open) >= count(slice, ch)) break;
+ }
+ end--;
+ }
+ if (end <= from) return null;
+
+ const token = text.slice(from, end);
+ if (!AUTO.some(re => re.test(token))) return null;
+ // Never inside an existing link: re-linking a link is at best a no-op and at
+ // worst replaces a URL the author chose with the text they happened to type.
+ if (hasLinkIn(marks, from, end)) return null;
+
+ const href = sanitizeUrl(token);
+ return href ? { from, to: end, href } : null;
+}
+
+// ═══════════════════════════════════════════════════════════════ the UI
+//
+// Everything below needs a browser. Guarded so the module still imports under
+// `node`, which is what lets the rig test the logic above without a DOM — the
+// same rule inline.ts states for itself, and for the same reason: a module that
+// only runs in one of the two environments passes every test in the other.
+
+let CTX: FeatureContext | null = null;
+/** See NEEDS FROM THE CORE #3 — the ctx arrives with the first entry point. */
+const remember = (ctx: FeatureContext) => { CTX = ctx; return ctx; };
+
+interface Target { id: string; from: number; to: number }
+
+/** Commit a link change and put the caret back where the author left it. */
+function applyLink(ctx: FeatureContext, tgt: Target, href: string | null,
+ caret: { id: string; at: number; to?: number }): void {
+ const blk = ctx.store.block(tgt.id);
+ if (!blk) return;
+ ctx.store.breakRun(); // its own undo step, not folded into typing
+ ctx.store.commit(d => {
+ const b = d.body.find(x => x.id === tgt.id);
+ if (!b) return;
+ const marks = setLink(b.marks ?? [], b.text.length, tgt.from, tgt.to, href);
+ if (marks.length) b.marks = marks; else delete b.marks;
+ }, { scope: { block: tgt.id } });
+ ctx.refresh();
+ ctx.editor.setCaret(caret);
+}
+
+// ───────────────────────────────────────────────────────────── popover
+
+let pop: HTMLElement | null = null;
+let popAnchor: HTMLElement | null = null;
+
+function closePopover(): void {
+ pop?.remove();
+ pop = null;
+ popAnchor?.classList.remove('t-link-on');
+ popAnchor = null;
+}
+
+/**
+ * Where to put the popover: the selection's rectangle, or — when the caret is
+ * merely sitting inside a link — the link's own box, which is also what tells
+ * the author WHICH link they are about to edit when several sit in a line.
+ */
+/**
+ * The rendered <a> for a target range — by OFFSET, not by href.
+ *
+ * "The first anchor in the block" and "the anchor whose href matches" are both
+ * wrong the moment a paragraph carries two links, and two links to the same
+ * page is not an exotic document. Counting characters is the same walk the
+ * caret uses, footnote markers excluded for the same reason: they occupy a
+ * position and no characters, so counting them shifts every anchor after one.
+ */
+function anchorFor(host: HTMLElement, tgt: Target): HTMLElement | null {
+ const block = host.querySelector<HTMLElement>(`[data-id="${CSS.escape(tgt.id)}"]`);
+ if (!block) return null;
+ let at = 0;
+ let found: HTMLElement | null = null;
+ const walk = (n: Node): void => {
+ if (found) return;
+ if (n.nodeType === 3) { at += n.nodeValue?.length ?? 0; return; }
+ if (n.nodeType !== 1) return;
+ const el = n as HTMLElement;
+ if (isNoteAtom(el)) return;
+ const start = at;
+ for (const c of Array.from(el.childNodes)) { walk(c); if (found) return; }
+ if (el.tagName === 'A' && start < tgt.to && at > tgt.from) found = el;
+ };
+ for (const c of Array.from(block.childNodes)) { walk(c); if (found) break; }
+ return found;
+}
+
+function anchorRect(host: HTMLElement, tgt: Target): DOMRect {
+ const a = anchorFor(host, tgt);
+ // Marked whether or not it is what we position against: with a caret sitting
+ // in one of three links on a line, "which one am I editing" is the question
+ // the popover exists to answer, and the address in the field only answers it
+ // for someone who already knows.
+ if (a) { popAnchor = a; a.classList.add('t-link-on'); }
+ const sel = getSelection();
+ const r = sel && sel.rangeCount ? sel.getRangeAt(0).getBoundingClientRect() : null;
+ if (r && r.width) return r; // a real selection: point at it
+ if (a) return a.getBoundingClientRect(); // a bare caret: point at the link
+ return r ?? host.getBoundingClientRect();
+}
+
+function openPopover(ctx: FeatureContext, tgt: Target, current: string | null): void {
+ closePopover();
+ const rect = anchorRect(ctx.editor.host, tgt);
+
+ const box = document.createElement('div');
+ box.className = 't-link-pop';
+
+ const field = document.createElement('input');
+ field.type = 'text';
+ field.className = 't-link-url';
+ field.spellcheck = false;
+ field.placeholder = t('https://example.com');
+ field.value = current ?? '';
+ field.setAttribute('aria-label', t('Link address'));
+
+ const btn = (label: string, cls: string, fn: () => void) => {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = `t-btn ${cls}`;
+ b.textContent = label;
+ // mousedown, so the button acts before the input's blur can close us
+ b.addEventListener('mousedown', e => { e.preventDefault(); fn(); });
+ return b;
+ };
+
+ const commit = () => {
+ const href = sanitizeUrl(field.value);
+ if (!href) {
+ // An empty field on an existing link means "unlink" — the gesture people
+ // already have. Anything else is a URL we refused, and saying so beats
+ // silently doing nothing.
+ if (!field.value.trim() && current) { closePopover(); applyLink(ctx, tgt, null, { id: tgt.id, at: tgt.from, to: tgt.to }); return; }
+ ctx.toast(t('That is not an address this document can link to'));
+ return;
+ }
+ closePopover();
+ applyLink(ctx, tgt, href, { id: tgt.id, at: tgt.from, to: tgt.to });
+ };
+
+ box.append(field, btn(t('Apply'), 't-link-ok', commit));
+ if (current) {
+ box.append(
+ btn(t('Open'), 't-link-open', () => { closePopover(); openHref(current); }),
+ btn(t('Remove'), 't-link-rm', () => {
+ closePopover();
+ applyLink(ctx, tgt, null, { id: tgt.id, at: tgt.from, to: tgt.to });
+ }),
+ );
+ }
+
+ field.addEventListener('keydown', e => {
+ if (e.key === 'Enter') { e.preventDefault(); commit(); }
+ else if (e.key === 'Escape') {
+ e.preventDefault();
+ closePopover();
+ ctx.editor.setCaret({ id: tgt.id, at: tgt.from, to: tgt.to });
+ }
+ e.stopPropagation(); // ⌘K and friends belong to the document, not here
+ });
+
+ document.body.appendChild(box);
+ pop = box;
+ // Positioned after mounting, because the width is not known before it.
+ const w = box.offsetWidth, h = box.offsetHeight;
+ const left = Math.max(8, Math.min(rect.left, innerWidth - w - 8));
+ const below = rect.bottom + 8;
+ box.style.left = `${left}px`;
+ box.style.top = `${below + h < innerHeight ? below : Math.max(8, rect.top - h - 8)}px`;
+ field.focus();
+ field.select();
+}
+
+function openHref(href: string): void {
+ // Re-sanitised at the moment of following, never trusted from the model:
+ // this href may have arrived in a file somebody else wrote.
+ const safe = safeHref(href);
+ if (safe) open(safe, '_blank', 'noopener,noreferrer');
+}
+
+// ─────────────────────────────────────────────────────── the entry point
+
+function openLinkEditor(ctx: FeatureContext): void {
+ remember(ctx);
+ if (pop) { closePopover(); return; } // ⌘K again closes it
+ const c = ctx.editor.caret();
+ if (!c) { ctx.toast(t('Put the caret in the document first')); return; }
+ const blk = ctx.store.block(c.id);
+ if (!blk) return;
+
+ const selected = c.to !== undefined && c.to !== c.at;
+ if (selected) {
+ const from = Math.min(c.at, c.to!), to = Math.max(c.at, c.to!);
+ // If the whole selection sits in one link, this is an EDIT of that link,
+ // so the field opens with its address rather than empty.
+ const inner = linkAt(blk.marks, from + 1);
+ const whole = inner && inner.from <= from && inner.to >= to ? inner : undefined;
+ openPopover(ctx, { id: c.id, from, to }, whole?.href ?? null);
+ return;
+ }
+
+ const here = linkAt(blk.marks, c.at);
+ if (!here) { ctx.toast(t('Select the words you want to link')); return; }
+ openPopover(ctx, { id: c.id, from: here.from, to: here.to }, here.href ?? null);
+}
+
+// ────────────────────────────────────────────────────────── registration
+
+registerTool({
+ id: 'link',
+ icon: ICONS.link,
+ // A GETTER, not a value. `registerTool` runs at module scope, and a t() call
+ // there freezes before the viewer's locale is resolved — the rule i18n.ts
+ // states. Reading it lazily makes this label behave exactly like every label
+ // main.ts sets from script.
+ get title() { return t('Link (⌘K)'); },
+ group: 'format',
+ order: 60,
+ run: openLinkEditor,
+ active: ctx => {
+ remember(ctx);
+ const c = ctx.editor.caret();
+ if (!c) return false;
+ const blk = ctx.store.block(c.id);
+ return !!linkAt(blk?.marks, c.at);
+ },
+});
+
+registerKey({ key: 'k', mod: true, run: openLinkEditor });
+
+if (typeof document !== 'undefined') {
+ /**
+ * A CLICK IN THE DOCUMENT PLACES THE CARET; IT DOES NOT NAVIGATE.
+ *
+ * This is an editing surface, and a link that walks the browser away from an
+ * unsaved document the moment you try to put the caret in it is a data-loss
+ * bug, not a hyperlink. ⌘/Ctrl-click opens, which is the modifier that means
+ * "actually follow this" everywhere else, and the popover has an Open button
+ * for people who do not know that.
+ *
+ * Capture phase, on the document: contentEditable's own handling and any
+ * later listener both come after, and this needs no FeatureContext.
+ */
+ document.addEventListener('click', e => {
+ const el = e.target as Element | null;
+ const a = el?.closest?.('a[href]') as HTMLAnchorElement | null;
+ if (!a || !a.closest('.t-paper')) return;
+ e.preventDefault();
+ if (e.metaKey || e.ctrlKey) openHref(a.getAttribute('href') ?? '');
+ }, true);
+
+ // Autolink. Bubble phase and on the document, so the editor's own `input`
+ // listener has already written the typed character into the model.
+ document.addEventListener('input', () => {
+ const ctx = CTX;
+ if (!ctx || pop) return;
+ const c = ctx.editor.caret();
+ if (!c || (c.to !== undefined && c.to !== c.at)) return;
+ const blk = ctx.store.block(c.id);
+ if (!blk) return;
+ const hit = autolinkAt(blk.text, c.at, blk.marks ?? []);
+ if (!hit) return;
+ applyLink(ctx, { id: c.id, from: hit.from, to: hit.to }, hit.href, { id: c.id, at: c.at });
+ });
+
+ // Clicking away, or scrolling the page under it, dismisses the popover —
+ // a floating box that outlives the thing it points at reads as a glitch.
+ document.addEventListener('mousedown', e => {
+ if (pop && !pop.contains(e.target as Node)) closePopover();
+ }, true);
+ window.addEventListener('resize', closePopover);
+}
diff --git a/type/src/main.ts b/type/src/main.ts
index eb096e12..6f5e91da 100644
--- a/type/src/main.ts
+++ b/type/src/main.ts
@@ -10,6 +10,12 @@ import { configureApp } from '../../kernel/src/app.ts';
import {
capturePristine, readEmbeddedDoc, saveFile, currentFileName, canWriteInPlace,
} from '../../kernel/src/save.ts';
+import { ICONS } from './icons.ts';
+import { t } from './i18n.ts';
+import { tools, menuItems, panels, matchKey, readyFns, paginatedFns, selectionFns, text as labelText, type FeatureContext } from './features.ts';
+import './registry.ts'; // side-effect: every feature module registers itself
+import { i18nApi } from '../../kernel/src/i18n.ts';
+import { openAbout } from './about.ts';
import { startTheme, setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';
import { parseDoc, emptyDoc, uid, wordCount, type TypeDoc } from './model.ts';
import { Store } from './store.ts';
@@ -19,7 +25,6 @@ import { redline, apply as applyRedline, describe, type ChangeSet } from './redl
import { printDocument, buildPrintDocument } from './print.ts';
import { sign as signDoc, verifyChain, newKey } from './canon.ts';
import { uid as newId } from './model.ts';
-import type { MarkType } from './inline.ts';
// Tell the kernel who this app is — must precede any kernel module use
// (window title suffix, save-picker label, update manifest).
@@ -92,61 +97,494 @@ if (parsed.ok) {
const app = document.getElementById('app')!;
app.innerHTML = `
- <div class="t-bar">
- <div class="t-brand">bento/<b>type</b></div>
- <div class="t-sep"></div>
- <button id="save" class="primary" title="Save (⌘S)">Save</button>
- <div class="t-sep"></div>
- <select id="kind" title="Block style">
- <option value="para">Body</option>
- <option value="h1">Title</option>
- <option value="h2">Heading</option>
- <option value="h3">Subheading</option>
- <option value="quote">Quote</option>
- </select>
- <div class="t-sep"></div>
- <button id="mb" title="Bold (⌘B)"><b>B</b></button>
- <button id="mi" title="Italic (⌘I)"><i>I</i></button>
- <button id="mu" title="Underline (⌘U)"><u>U</u></button>
- <button id="mc" title="Code">&lt;/&gt;</button>
- <div class="t-sep"></div>
- <button id="undo" title="Undo (⌘Z)">↶</button>
- <button id="redo" title="Redo (⇧⌘Z)">↷</button>
- <div class="t-sep"></div>
- <button id="theme" title="Theme: follow the system, light, or dark"></button>
- <div class="t-sep"></div>
- <button id="snap" title="Record a revision to compare against later">Snapshot</button>
- <button id="review" title="Compare with the last snapshot">Review…</button>
- <div class="t-sep"></div>
- <button id="sign" title="Sign this revision">Sign</button>
- <div class="t-sep"></div>
- <button id="print" title="Print or save as PDF (⌘P)">Print…</button>
- <div class="t-spacer"></div>
- <div class="t-stat" id="stat"></div>
- </div>
+ <header class="t-bar">
+ <button id="mark" class="t-mark" type="button">
+ <svg class="t-mark-svg" viewBox="0 0 32 32" width="20" height="20" aria-hidden="true">
+ <rect width="32" height="32" rx="7" fill="#16273E"/>
+ <rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/>
+ <rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/>
+ <rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/>
+ </svg><b class="t-mark-word">bento<span>/</span>type</b>
+ </button>
+ <button id="sidebar" class="t-btn" type="button"></button>
+ <input id="doctitle" class="t-doctitle" spellcheck="false">
+ <span class="t-status" id="status"></span>
+
+ <div class="t-right">
+ <div class="t-group" id="gFormat"></div>
+ <div class="t-group" id="gInsert"></div>
+ <div class="t-group" id="gReview"></div>
+ <div class="t-group">
+ <button id="undo" class="t-btn" type="button"></button>
+ <button id="redo" class="t-btn" type="button"></button>
+ </div>
+ <button id="props" class="t-btn" type="button"></button>
+ <button id="theme" class="t-btn" type="button"></button>
+ <button id="save" class="t-btn t-primary" type="button"></button>
+ <div class="t-menuwrap">
+ <button id="more" class="t-btn" type="button"></button>
+ <div class="t-menu" id="moreMenu" hidden>
+ <button id="snap" type="button"></button>
+ <button id="review" type="button"></button>
+ <button id="sign" type="button"></button>
+ <div class="t-menu-sep"></div>
+ <button id="print" type="button"></button>
+ <button id="about" type="button"></button>
+ </div>
+ </div>
+ </div>
+ </header>
<div class="t-main">
<div class="t-side">
<div class="t-tabs">
- <button data-tab="outline" class="on">Outline</button>
- <button data-tab="review">Review</button>
- <button data-tab="sigs">Signatures</button>
+ <button data-tab="navigate" class="on"></button>
+ <button data-tab="review"></button>
+ <button data-tab="sources"></button>
</div>
- <div class="t-panel on" data-panel="outline"><div class="t-outline" id="outline"></div></div>
- <div class="t-panel" data-panel="review"><div id="reviewPanel"></div></div>
- <div class="t-panel" data-panel="sigs"><div id="sigsPanel"></div></div>
+ <div class="t-panel on" data-panel="navigate">
+ <div class="t-seg" id="navSeg">
+ <button data-view="headings" class="on"></button>
+ <button data-view="pages"></button>
+ <button data-view="figures"></button>
+ <button data-view="results"></button>
+ </div>
+ <div class="t-view on" data-view="headings"><div class="t-outline" id="outline"></div></div>
+ <div class="t-view" data-view="pages"><div class="t-outline" id="pages"></div></div>
+ <div class="t-view" data-view="figures"><div id="figuresHost"></div></div>
+ <div class="t-view" data-view="results"><div id="findHost"></div></div>
+ </div>
+ <div class="t-panel" data-panel="review">
+ <div class="t-sub" data-sub="comments"></div>
+ <div id="commentsHost"></div>
+ <div class="t-sub" data-sub="changes"></div>
+ <div id="reviewPanel"></div>
+ <div class="t-sub" data-sub="sigs"></div>
+ <div id="sigsPanel"></div>
+ </div>
+ <div class="t-panel" data-panel="sources"><div id="citeHost"></div></div>
</div>
<div class="t-scroll"><div class="t-wrap">
<div class="t-paper" id="paper"></div><div class="t-deco" id="deco"></div>
</div></div>
+ <aside class="t-props" id="propsPanel"></aside>
</div>`;
const paper = document.getElementById('paper')!;
const deco = document.getElementById('deco')!;
-const statEl = document.getElementById('stat')!;
+const statEl = document.getElementById('status')!;
const store = new Store(doc);
const editor = new Editor(paper, store);
+// ───────────────────────────────────────────────────── chrome: labels & icons
+//
+// Set from script rather than written into the markup so every user-visible
+// string passes through one place — which is what makes the i18n sweep a sweep
+// rather than an archaeology dig through a template literal.
+const byId = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
+
+const label = (id: string, html: string, tip: string, text = '') => {
+ const b = byId(id);
+ b.innerHTML = html + (text ? `<span class="t-lbl">${text}</span>` : '');
+ b.title = tip;
+};
+
+// LABEL RULE — every bar control gets a `title`, full stop (an icon with no
+// tooltip names nothing). A VISIBLE text label is rarer, and earned only one
+// of two ways: (1) the control's face reports STATE, not just an action — Save/
+// Saved and the theme cycle both change what they say depending on what
+// happens next, and an icon alone can't say that; or (2) the icon stands for a
+// whole HIDDEN CATEGORY rather than one verb — Insert's "+" could mean a
+// picture, a table, a citation… nothing short of a word says which. Every
+// other control (sidebar, props, link, comment, find, undo, redo, ⋯) is one
+// icon-legible verb with a universally-read glyph, so it stays icon-only and
+// leans on its tooltip. Breaking this into "some buttons happen to have text"
+// is how the bar drifted into its current mix with no rule at all.
+label('sidebar', ICONS.panelLeft, t('Outline — show or hide the document map'));
+label('props', ICONS.panelRight, t('Format — show or hide the properties panel'));
+// Strikethrough and code leave the BAR for the ⋯ menu: of the five character
+// formats they are the two nobody reaches for mid-sentence in the prose this
+// app is for, and bar width is the scarcest thing in the app.
+label('undo', ICONS.undo, t('Undo (⌘Z)'));
+label('redo', ICONS.redo, t('Redo (⇧⌘Z)'));
+label('save', ICONS.save, t('Save (⌘S)'), t('Save'));
+label('more', ICONS.more, t('More — revisions, signing, print'));
+label('snap', ICONS.history, '', t('Snapshot'));
+label('review', ICONS.review, '', t('Review changes…'));
+label('sign', ICONS.sign, '', t('Sign…'));
+label('print', ICONS.print, '', t('Print or PDF…'));
+label('about', ICONS.sync, '', t('About bento/type'));
+byId('mark').title = t('About bento/type — version, updates, language');
+const showAbout = () => openAbout({
+ store,
+ pages: metrics.pages.length,
+ onReplaceDoc: json => {
+ try {
+ const parsed = parseDoc(json);
+ if (!parsed.ok) {
+ // `empty` carries no detail — the tagged union says so, and reading
+ // `.detail` off it would have printed "undefined" to the one person
+ // who most needs to know what went wrong.
+ alert(parsed.err === 'empty'
+ ? t('That JSON was empty.')
+ : t('That is not a bento/type document: {detail}', { detail: parsed.detail }));
+ return;
+ }
+ store.replace(parsed.doc);
+ // store.replace swaps the model; only this rebuilds the paper from it.
+ // Without it the document changed and the screen did not — which is what
+ // "Replace from JSON…" did on the day it was added.
+ editor.render();
+ schedule();
+ } catch { alert(t('That JSON could not be read.')); }
+ },
+});
+byId('mark').addEventListener('click', showAbout);
+byId('about').addEventListener('click', showAbout);
+
+for (const [sub, text] of [['comments', t('Comments')], ['changes', t('Tracked changes')],
+ ['sigs', t('Signatures')]] as const) {
+ const n = document.querySelector<HTMLElement>(`.t-sub[data-sub="${sub}"]`);
+ if (n) n.textContent = text;
+}
+// An empty section under a heading explains nothing, and this one is empty
+// until someone has taken a snapshot — which is exactly the step a person does
+// not know about yet. So the empty state IS the instruction.
+//
+// The live tracked-changes list itself is review.ts's `trackedChanges` panel,
+// mounted into `reviewPanel` through the feature registry — nothing to build
+// here.
+for (const [tab, text] of [['navigate', t('Navigate')], ['review', t('Review')], ['sources', t('Sources')]] as const) {
+ const b = document.querySelector<HTMLElement>(`.t-tabs [data-tab="${tab}"]`);
+ if (b) b.textContent = text;
+}
+
+// The DOCUMENT TITLE, in the bar — the one thing every other app in the suite
+// puts there and this one only had buried in the page. It is what the window
+// title, the save-picker filename and `{{title}}` all read.
+const titleInput = byId<HTMLInputElement>('doctitle');
+titleInput.value = store.doc.title;
+titleInput.setAttribute('aria-label', t('Document title'));
+titleInput.addEventListener('input', () => {
+ store.commit(d => { d.title = titleInput.value || 'Untitled'; }, { run: '__title' });
+});
+store.on(() => {
+ if (document.activeElement !== titleInput && titleInput.value !== store.doc.title) {
+ titleInput.value = store.doc.title;
+ }
+});
+
+// The bar's measured fit (fitBar) is wired up much further down, right after
+// every group and the ⋯ menu are actually mounted onto it — see the note
+// there for why the ordering matters.
+
+// ─────────────────────────────────────────────── the feature registry, rendered
+//
+// Everything a feature module registered at import time becomes chrome here.
+// A feature is one file plus one line in registry.ts; nothing below knows what
+// any particular feature is.
+const featureCtx: FeatureContext = {
+ store, editor,
+ refresh: () => { editor.render(); schedule(); },
+ toast: (m: string) => toast(m),
+ showPanel: (id: string) => {
+ document.querySelector('.t-main')!.classList.remove('t-side-off');
+ showTab(id);
+ },
+};
+
+const toolButton = (spec: ReturnType<typeof tools>[number]) => {
+ const b = document.createElement('button');
+ b.className = 't-btn';
+ b.type = 'button';
+ b.id = `tool-${spec.id}`;
+ const titleText = labelText(spec.title);
+ // Icon-only buttons rely on `title` in the BAR, but a row folded into the ⋯
+ // menu (see fitBar/setBarFolded below) has no hover to reveal that — a menu
+ // row has to name itself. `.t-mlbl` costs nothing while the button lives in
+ // the bar: styles.css only shows it inside `.t-menu`. The parenthetical
+ // shortcut ("(⌘K)") is dropped — a shortcut hint is dead weight on a row you
+ // reach precisely because a shortcut wasn't an option.
+ b.innerHTML = spec.icon + (spec.label
+ ? `<span class="t-lbl">${labelText(spec.label)}</span>`
+ : `<span class="t-mlbl">${titleText.replace(/\s*\([^)]*\)\s*$/, '')}</span>`);
+ b.title = titleText;
+ // mousedown, not click: the caret must survive pressing a toolbar button
+ b.addEventListener('mousedown', e => { e.preventDefault(); spec.run(featureCtx); });
+ return b;
+};
+
+const mountTools = (hostId: string, group: 'format' | 'insert' | 'review' | 'right') => {
+ const host = byId(hostId);
+ for (const spec of tools(group)) host.appendChild(toolButton(spec));
+ if (!host.children.length) host.remove();
+};
+
+/**
+ * INSERT IS ONE BUTTON, not eight.
+ *
+ * Every feature that can put something in the document registered its own icon,
+ * and the bar reached thirty-nine buttons needing 1253px inside a 1120px
+ * window — accumulated a feature at a time, never designed. slides solved the
+ * same problem the same way (shapeDropdown, mediaDropdown): related inserts
+ * live behind one control, so adding the ninth thing costs no width at all.
+ *
+ * They are also the RARE actions. A picture or a citation is chosen
+ * deliberately, once; bold is pressed mid-sentence without looking. Frequency
+ * is what earns a place in the bar.
+ */
+const mountInsertMenu = () => {
+ const host = byId('gInsert');
+ const specs = tools('insert');
+ if (!specs.length) { host.remove(); return; }
+ const wrap = document.createElement('div');
+ wrap.className = 't-menuwrap';
+ const btn = document.createElement('button');
+ btn.className = 't-btn';
+ btn.type = 'button';
+ btn.id = 'insertMenuBtn';
+ btn.innerHTML = ICONS.plus + `<span class="t-lbl">${t('Insert')}</span>`;
+ btn.title = t('Insert a picture, table, formula, citation…');
+ const menu = document.createElement('div');
+ menu.className = 't-menu';
+ menu.hidden = true;
+ for (const spec of specs) {
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.innerHTML = spec.icon + `<span>${labelText(spec.label ?? spec.title)}</span>`;
+ item.addEventListener('mousedown', e => { e.preventDefault(); menu.hidden = true; spec.run(featureCtx); });
+ menu.appendChild(item);
+ }
+ btn.addEventListener('click', e => { e.stopPropagation(); menu.hidden = !menu.hidden; });
+ document.addEventListener('click', () => { menu.hidden = true; });
+ wrap.append(btn, menu);
+ host.appendChild(wrap);
+};
+
+mountTools('gFormat', 'format');
+mountInsertMenu();
+mountTools('gReview', 'review');
+
+// Menu rows keep a reference to their spec so their labels can be RE-READ when
+// the menu opens. A toggle's label is a function of state — "Hide comments"
+// becomes "Show comments" — and rendering it once at mount left it permanently
+// wrong after the first use, describing the action you had already taken.
+const menuRows: Array<[HTMLElement, ReturnType<typeof menuItems>[number]]> = [];
+for (const spec of menuItems()) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.innerHTML = (spec.icon ?? '') + `<span>${labelText(spec.label)}</span>`;
+ b.addEventListener('click', () => spec.run(featureCtx));
+ byId('moreMenu').insertBefore(b, byId('about'));
+ menuRows.push([b, spec]);
+}
+const refreshMenuLabels = () => {
+ for (const [b, spec] of menuRows) {
+ const span = b.querySelector('span');
+ if (span) span.textContent = labelText(spec.label);
+ }
+};
+
+/**
+ * Size the bar by MEASURING it, not by width breakpoints.
+ *
+ * The same reasoning as slides' fitTopbar, and the same tiers: start at the
+ * widest layout and step down while the bar overflows its own box. Breakpoints
+ * were wrong here for the reason they are wrong there — zoom, OS text scaling
+ * and longer translations all change how much room the same buttons need at
+ * one viewport width.
+ *
+ * The title is the only shrinkable item, so flexbox crushes it toward its floor
+ * before anything technically overflows: stepping down only on hard overflow
+ * would leave full labels beside an unusably narrow title. So squeeze counts
+ * as overflow too.
+ *
+ * THIS BLOCK MUST COME AFTER the groups and the ⋯ menu are mounted (above),
+ * not before. Measured: with fitBar wired up where the "obvious" spot was —
+ * right after the title input, before mountTools('gFormat', …) etc. ran — its
+ * FIRST call and its ResizeObservers all saw a bar missing every format/
+ * insert/review button. Nothing observed afterward ever re-triggered it (the
+ * bar's own box size doesn't change just because overflowing children were
+ * appended inside it), so a page loaded directly at a narrow width — no
+ * interactive resize in between — stayed permanently untiered with real
+ * buttons hanging off the end of the bar (measured: 118px past the edge at
+ * 620px wide, forever, since nothing ever asked again).
+ */
+const bar = document.querySelector<HTMLElement>('.t-bar')!;
+const TIERS = ['t-bar-compact', 't-bar-tight', 't-bar-fold'];
+const ALL_BAR_CLASSES = [...TIERS, 't-bar-micro'];
+
+// Groups whose buttons are plain, POPOVER-FREE actions — safe to reparent
+// wholesale into the ⋯ menu when the fold tier engages. gInsert stays put: it
+// is ITSELF a dropdown, and nesting one popover inside another gets silently
+// clipped the moment the outer one scrolls (hard-won #10, CLAUDE.md — an
+// `overflow-y` menu clips any floating child, so a folded control must render
+// as a plain menu ROW, never a second floater). Reparenting the SAME button
+// nodes (not clones) keeps every listener intact for free.
+const FOLD_GROUPS = ['gFormat', 'gReview'];
+const foldHome = new WeakMap<HTMLElement, HTMLElement>();
+const foldSep = document.createElement('div');
+foldSep.className = 't-menu-sep';
+foldSep.hidden = true;
+byId('moreMenu').insertBefore(foldSep, byId('snap'));
+let barFolded = false;
+function setBarFolded(next: boolean) {
+ if (next === barFolded) return;
+ barFolded = next;
+ const menu = byId('moreMenu');
+ if (next) {
+ for (const gid of FOLD_GROUPS) {
+ const host = document.getElementById(gid);
+ if (!host) continue;
+ for (const btn of [...host.children] as HTMLElement[]) {
+ foldHome.set(btn, host);
+ menu.insertBefore(btn, foldSep);
+ }
+ }
+ foldSep.hidden = false;
+ } else {
+ // Walk the menu in DOM order so buttons land back in the same relative
+ // order they left it, and only touch the ones THIS moved (foldHome is
+ // empty for the menu's own static rows).
+ for (const btn of [...menu.children] as HTMLElement[]) {
+ const home = foldHome.get(btn);
+ if (home) { home.appendChild(btn); foldHome.delete(btn); }
+ }
+ foldSep.hidden = true;
+ }
+}
+
+function fitBar() {
+ if (!bar.isConnected) return;
+ bar.classList.remove(...ALL_BAR_CLASSES);
+ setBarFolded(false);
+ const title = bar.querySelector<HTMLElement>('.t-doctitle');
+ const tooTight = () =>
+ bar.scrollWidth - bar.clientWidth > 1 || (title ? title.clientWidth < 96 : false);
+ for (const tier of TIERS) {
+ if (!tooTight()) return;
+ bar.classList.add(tier);
+ if (tier === 't-bar-fold') setBarFolded(true);
+ }
+ // Folding the groups away is the last thing that can free width. If the bar
+ // is STILL too tight — or the title still can't clear its floor — the title
+ // has nowhere left to shrink to, so it drops out cleanly instead of being
+ // crushed below one legible character (measured: 24px wide at ~560px before
+ // this tier existed, narrower than a single glyph).
+ if (tooTight()) bar.classList.add('t-bar-micro');
+}
+// BOTH signals, deliberately. ResizeObserver catches content-driven changes
+// (a longer title, a translated label) that no resize event reports; the
+// resize event catches viewport changes when RO callbacks are being throttled,
+// which happens whenever the page is not painting — a background tab, or a
+// hidden preview pane. Measured: with only the observer, the bar stayed
+// untiered and overflowed at 700px because the callback never ran.
+fitBar();
+new ResizeObserver(() => fitBar()).observe(bar);
+new ResizeObserver(() => fitBar()).observe(document.documentElement);
+window.addEventListener('resize', fitBar);
+
+// And a MutationObserver, which is the third signal slides has always had
+// (CLAUDE.md: "driven by a Resize- + MutationObserver on the bar") and this
+// app was missing.
+//
+// It matters because the bar's own BOX does not change when its CONTENTS do.
+// The document title is painted after this first fitBar() runs, and a longer
+// title makes the bar too tight without resizing it — so no ResizeObserver
+// fires and the bar stays one tier short. Measured: loaded directly at 480px
+// the bar overflowed by 23px with a button hanging past its edge, and a single
+// stray resize event was enough to fix it, which is the signature of a missing
+// re-measure rather than a broken measurement.
+//
+// It DISCONNECTS around its own call: fitBar adds classes and reparents
+// buttons into the ⋯ menu, which are themselves mutations, and an observer
+// that watched its own work would never stop.
+const barWatch = new MutationObserver(() => {
+ barWatch.disconnect();
+ fitBar();
+ barWatch.observe(bar, { childList: true, characterData: true, subtree: true });
+});
+barWatch.observe(bar, { childList: true, characterData: true, subtree: true });
+
+// LEFT — navigation and review: facts about the document as a whole.
+//
+// A panel that names a `host` becomes a SECTION of one of the three tabs
+// declared above; only a panel without one still gets a tab of its own. That
+// is what took the sidebar from eight tabs to three.
+for (const spec of panels('left')) {
+ let panel: HTMLElement;
+ const host = spec.host ? document.getElementById(spec.host) : null;
+ if (host) {
+ panel = host;
+ } else {
+ const tab = document.createElement('button');
+ tab.dataset.tab = spec.id;
+ tab.textContent = labelText(spec.label);
+ document.querySelector('.t-tabs')!.appendChild(tab);
+ panel = document.createElement('div');
+ panel.className = 't-panel';
+ panel.dataset.panel = spec.id;
+ document.querySelector('.t-side')!.appendChild(panel);
+ }
+ spec.mount(panel, featureCtx);
+ // `update` was declared on PanelSpec and never called, so a panel that
+ // implemented it was silently dead. Wired to the same signal everything else
+ // repaints on.
+ if (spec.update) store.on(() => spec.update!(panel, featureCtx));
+}
+
+// RIGHT — the properties of whatever is selected. Stacked rather than tabbed:
+// a property panel answers "what is this thing", and hiding half the answer
+// behind a tab is how a formatting panel becomes a place people stop looking.
+for (const spec of panels('right')) {
+ const panel = document.createElement('div');
+ panel.className = 't-panel';
+ panel.dataset.panel = spec.id;
+ // a DIV, not an <h3>: these are chrome, and a real heading here joins the
+ // document's own headings for anything that collects them
+ byId('propsPanel').appendChild(panel);
+ // NO header added here. A contextual panel owns its whole body and rebuilds
+ // it with replaceChildren, which wiped a header the loop had just added — so
+ // the label vanished the first time the panel refreshed. A panel that wants a
+ // title writes its own section, which is also what lets ONE panel show
+ // several (Text, Picture, Table) as the selection changes.
+ spec.mount(panel, featureCtx);
+ if (spec.update) store.on(() => spec.update!(panel, featureCtx));
+}
+if (!byId('propsPanel').children.length) {
+ const empty = document.createElement('p');
+ empty.className = 't-props-empty';
+ empty.textContent = t('Select something to see its properties.');
+ byId('propsPanel').appendChild(empty);
+}
+
+// feature shortcuts, ahead of the editor's own so a feature can claim one
+window.addEventListener('keydown', e => {
+ const hit = matchKey(e);
+ if (hit) { e.preventDefault(); hit.run(featureCtx); }
+}, true);
+
+// active-state highlighting, on the same signal the mark buttons use
+const paintToolStates = () => {
+ for (const group of ['format', 'insert', 'review'] as const) {
+ for (const spec of tools(group)) {
+ if (!spec.active) continue;
+ document.getElementById(`tool-${spec.id}`)?.classList.toggle('on', spec.active(featureCtx));
+ }
+ }
+};
+
+// the ⋯ menu — secondary actions, off the bar but one click away
+const moreMenu = byId('moreMenu');
+byId('more').addEventListener('click', e => {
+ e.stopPropagation();
+ if (moreMenu.hidden) refreshMenuLabels();
+ moreMenu.hidden = !moreMenu.hidden;
+});
+document.addEventListener('click', () => { moreMenu.hidden = true; });
+moreMenu.addEventListener('click', () => { moreMenu.hidden = true; });
+
+
let metrics: Metrics = { pages: [], ms: 0 };
/**
@@ -155,10 +593,23 @@ let metrics: Metrics = { pages: [], ms: 0 };
* one. It runs on an idle beat instead, which is what makes typing feel free.
*/
let idle: number | undefined;
+// The document's typeface, onto the paper. Set before pagination measures
+// anything: a different face changes every line box, so measuring first would
+// paginate the old type.
+const applyDocType = () => {
+ const ty = store.doc.type;
+ paper.style.setProperty('--doc-family', ty?.family ?? '');
+ paper.style.setProperty('--doc-size', ty?.size ? `${ty.size}px` : '');
+};
+
const repaginate = () => {
+ applyDocType();
metrics = paginate(store.doc, paper);
drawPages(store.doc, paper, deco, metrics);
+ // page numbers are knowable only here, so anything that shows one is told now
+ for (const f of paginatedFns()) f(featureCtx, metrics, paper);
buildOutline();
+ buildPages();
paint();
void paintSigs();
};
@@ -167,6 +618,11 @@ const schedule = () => {
idle = setTimeout(repaginate, 180) as unknown as number;
};
+// A picture that finishes decoding changes the flow's height, so the pages have
+// to be recomputed — see renderImage. Listening on the paper rather than per
+// image keeps this to one handler however many pictures a document has.
+paper.addEventListener('t-relayout', () => schedule());
+
const paint = () => {
const d = store.doc;
const notes = Object.keys(d.footnotes).length;
@@ -182,18 +638,38 @@ const refresh = () => { markDirty(); paint(); schedule(); };
editor.onChange = refresh;
store.on(refresh);
-const MARK_BTN: Array<[string, MarkType]> = [['mb', 'b'], ['mi', 'i'], ['mu', 'u'], ['mc', 'code']];
-for (const [id, t] of MARK_BTN) {
- document.getElementById(id)!.addEventListener('mousedown', (e) => {
- e.preventDefault(); // keep the selection alive
- editor.toggle(t);
- });
-}
+// Bold, italic and underline moved to the properties panel with the rest of the
+// character formatting; strikethrough and code live in the ⋯ menu. Only the
+// ones still in the chrome are wired here, and the lookup is GUARDED rather
+// than asserted: `getElementById(id)!` on a button that had moved was a
+// TypeError at boot that tsc could not see — the app rendered its paper and
+// then stopped before it published `window.bento`, so it looked like it worked.
+// Strikethrough and code USED to live here as two loose buttons, exiled into ⋯
+// when the toolbar ran out of room. They have a proper home now — the
+// selection toolbar, which appears over the words they act on — so they are
+// gone from the overflow menu rather than being offered in two places at once.
editor.onSelection = (active) => {
- for (const [id, t] of MARK_BTN) document.getElementById(id)!.classList.toggle('on', active.has(t));
+ void active;
+ paintToolStates();
+ for (const f of selectionFns()) f(featureCtx);
};
-document.getElementById('kind')!.addEventListener('change', (e) => {
- editor.setKind((e.target as HTMLSelectElement).value as never);
+// A list button TOGGLES: pressing Bulleted list on an item that is already
+// bulleted returns it to a paragraph. Without that the button is a one-way door
+// and the only way back is the style menu, which is not where anyone looks.
+
+byId('sidebar').addEventListener('click', () => {
+ document.querySelector('.t-main')!.classList.toggle('t-side-off');
+});
+byId('props').addEventListener('click', () => {
+ document.querySelector('.t-main')!.classList.toggle('t-props-off');
+});
+// `[` and `]` collapse the panels, as they do in slides and dash
+window.addEventListener('keydown', e => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const tag = (e.target as HTMLElement)?.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement)?.isContentEditable) return;
+ if (e.key === '[') document.querySelector('.t-main')!.classList.toggle('t-side-off');
+ if (e.key === ']') document.querySelector('.t-main')!.classList.toggle('t-props-off');
});
document.getElementById('undo')!.addEventListener('mousedown', (e) => {
e.preventDefault(); store.undo(); editor.render(); refresh();
@@ -217,13 +693,59 @@ function showTab(name: string) {
document.querySelectorAll<HTMLElement>('.t-tabs button')
.forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab!)));
+/**
+ * The Navigate tab's four views — Headings, Pages, Figures, Results.
+ *
+ * A SEGMENTED CONTROL rather than four more tabs, because these are four
+ * answers to one question ("where is it?") and tabs would say they are four
+ * different tools. Word's navigation pane has worked this way since 2010.
+ */
+function showView(name: string) {
+ document.querySelectorAll<HTMLElement>('#navSeg button')
+ .forEach(b => b.classList.toggle('on', b.dataset.view === name));
+ document.querySelectorAll<HTMLElement>('.t-view')
+ .forEach(p => p.classList.toggle('on', p.dataset.view === name));
+}
+for (const [view, text] of [['headings', t('Headings')], ['pages', t('Pages')],
+ ['figures', t('Figures')], ['results', t('Results')]] as const) {
+ const b = document.querySelector<HTMLElement>(`#navSeg [data-view="${view}"]`);
+ if (b) { b.textContent = text; b.addEventListener('click', () => showView(view)); }
+}
+
+/** Pages, each with the first heading that lands on it. */
+function buildPages() {
+ const box = document.getElementById('pages');
+ if (!box) return;
+ box.replaceChildren();
+ const paperTop = paper.getBoundingClientRect().top + store.doc.page.marginTop;
+ // Where each heading sits, measured once rather than per page.
+ const heads = store.doc.body
+ .filter(b => b.kind === 'h1' || b.kind === 'h2' || b.kind === 'h3')
+ .map(b => {
+ const node = paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(b.id)}"]`);
+ return { text: b.text, y: node ? node.getBoundingClientRect().top - paperTop : 0 };
+ });
+ for (const pg of metrics.pages) {
+ const first = heads.find(h => h.y >= pg.start - 1 && (!isFinite(pg.end) || h.y < pg.end));
+ const a = el('a', 'pagerow') as HTMLAnchorElement;
+ a.innerHTML = `<span class="pg">${pg.n}</span>${esc(first ? first.text : t('(no heading)'))}`;
+ a.addEventListener('click', () => {
+ // scroll to the page's own top, not to a heading it may not contain
+ paper.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ const wrap = paper.closest('.t-scroll');
+ if (wrap) wrap.scrollTop = Math.max(0, pg.start);
+ });
+ box.appendChild(a);
+ }
+}
+
/** The outline, with the page each heading lands on. */
function buildOutline() {
const box = document.getElementById('outline')!;
const heads = store.doc.body.filter(b => b.kind === 'h2' || b.kind === 'h3');
box.replaceChildren();
if (!heads.length) {
- const h = el('div', 't-hint'); h.textContent = 'Headings appear here.';
+ const h = el('div', 't-hint'); h.textContent = t('Headings appear here.');
box.appendChild(h); return;
}
const paperTop = paper.getBoundingClientRect().top + store.doc.page.marginTop;
@@ -456,14 +978,25 @@ const markDirty = () => { dirty = true; paintTitle(); };
function paintTitle() {
const name = currentFileName();
- const t = store.doc.title || 'Untitled';
- document.title = `${dirty ? '• ' : ''}${t} — bento/type`;
+ const docTitle = store.doc.title || t('Untitled');
+ document.title = `${dirty ? '• ' : ''}${docTitle} — bento/type`;
const btn = document.getElementById('save')!;
- btn.textContent = dirty ? 'Save' : 'Saved';
- btn.classList.toggle('primary', dirty);
+ // Update the LABEL only. Setting textContent here wiped the icon that
+ // label() had just installed, so the button silently lost its glyph the
+ // first time the dirty flag moved — which is every document, immediately.
+ const lbl = btn.querySelector('.t-lbl');
+ if (lbl) lbl.textContent = dirty ? t('Save') : t('Saved');
+ btn.classList.toggle('t-primary', dirty);
+ // These two were the ONLY strings the pseudo-locale audit caught, and the
+ // reason is worth keeping: this function had a local `const t` holding the
+ // document title, which shadowed the imported t(). The sweep could not have
+ // wrapped them without renaming it first.
btn.title = name
- ? `${dirty ? 'Save' : 'Saved to'} ${name}${canWriteInPlace() ? '' : ' (downloads a copy)'}`
- : 'Save (⌘S)';
+ ? (dirty
+ ? t('Save to {file}', { file: name })
+ : t('Saved to {file}', { file: name })) +
+ (canWriteInPlace() ? '' : t(' (downloads a copy)'))
+ : t('Save (⌘S)');
}
async function save(forcePicker = false) {
@@ -501,10 +1034,28 @@ addEventListener('keydown', (e) => {
});
// theme picker — cycles auto → light → dark, and says which it is
-const themeBtn = document.getElementById('theme')!;
-const THEME_LABEL: Record<ThemeChoice, string> = { auto: '◐ Auto', light: '☀ Light', dark: '☾ Dark' };
-const paintTheme = () => { themeBtn.textContent = THEME_LABEL[themeChoice()]; };
-themeBtn.addEventListener('click', () => {
+//
+// Same recipe as icons.ts (24x24 box, 16px render, stroke currentColor at
+// width 2, round caps/joins) kept local rather than added to that file:
+// only this button needs it, and icons.ts is a different owner's file.
+const themeSvg = (body: string) =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
+const THEME_ICON: Record<ThemeChoice, string> = {
+ auto: themeSvg('<circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 0 0 18Z" fill="currentColor" stroke="none"/>'),
+ light: themeSvg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.5 1.5M17.6 17.6l1.5 1.5M2 12h2M20 12h2M4.9 19.1l1.5-1.5M17.6 6.4l1.5-1.5"/>'),
+ dark: themeSvg('<path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/>'),
+};
+const THEME_TEXT: Record<ThemeChoice, string> = { auto: t('Auto'), light: t('Light'), dark: t('Dark') };
+// This is control (1) of the label rule above: the face has to say what the
+// NEXT click leaves the app in, not just "theme", so it keeps its text label
+// like Save/Saved does.
+const paintTheme = () => {
+ const choice = themeChoice();
+ label('theme', THEME_ICON[choice],
+ t('Theme: {mode} — click to cycle auto/light/dark', { mode: THEME_TEXT[choice] }),
+ THEME_TEXT[choice]);
+};
+byId('theme').addEventListener('click', () => {
const order: ThemeChoice[] = ['auto', 'light', 'dark'];
const next = order[(order.indexOf(themeChoice()) + 1) % order.length];
setTheme(next);
@@ -527,4 +1078,40 @@ dirty = false; paintTitle();
printHtml: () => { repaginate(); return buildPrintDocument(store.doc, metrics, { pageNumbers: true }); },
paginate: () => { repaginate(); return metrics; },
get pages() { return metrics.pages; },
+ // PLATFORM §7: the AI round-trip surface. `loadDoc` is the scripted twin of
+ // About's "Replace from JSON…", and `serialize` is what a tool reads back.
+ serialize: () => JSON.stringify(store.doc),
+ loadDoc: (json: string) => {
+ const parsed = parseDoc(json);
+ if (!parsed.ok) throw new Error(`bento/type: ${parsed.err === 'empty' ? 'empty document' : parsed.detail}`);
+ store.replace(parsed.doc);
+ editor.render();
+ schedule();
+ return true;
+ },
+ // The language engine, so `bento.i18n.setLocale('x-pseudo')` can audit for
+ // unswept strings — which is the only way to find one that is cheap enough
+ // to actually do.
+ i18n: i18nApi,
};
+
+// ─────────────────────────────────────────────────────────────────── ready
+//
+// LAST LINE ON PURPOSE. Called from beside the panels() loop, where it visually
+// belongs, featureCtx.refresh() reaches `schedule` inside its temporal dead
+// zone — "Cannot access 'schedule' before initialization" — and the editor
+// boots blank. The agent that needed this hook found that by applying the patch
+// and loading the app, not by reading, and said so in its note; this comment is
+// here so the next person does not move it back.
+// The properties panel starts CLOSED, and this is arithmetic rather than taste:
+// the page is 816px plus a 250px note gutter, so with both panels open the
+// document needs 1566px before it stops being scrolled sideways. A laptop does
+// not have that. It opens on ] or the toolbar button, and slides makes the same
+// trade on a phone by booting with both panels collapsed.
+if (window.innerWidth < 1566) document.querySelector('.t-main')!.classList.add('t-props-off');
+
+for (const f of readyFns()) f(featureCtx);
+// Live collaboration (bento-sync) — dormant unless the doc carries collab
+// creds or the user opts in via the Share button; see src/collab.ts.
+import { initCollab } from './collab.ts';
+initCollab(store, editor);
diff --git a/type/src/marks.ts b/type/src/marks.ts
new file mode 100644
index 00000000..eb05f16a
--- /dev/null
+++ b/type/src/marks.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE CHARACTER MARKS — one list, rendered in more than one place.
+//
+// Bold, italic, underline, strikethrough and code were written out twice: as
+// toggles in the properties panel, and as two loose buttons in the ⋯ menu
+// (strikethrough and code, exiled there when the toolbar ran out of room). The
+// selection toolbar would have been a third copy.
+//
+// So the set lives here and the surfaces render it. That is the same rule the
+// Insert menu follows — ONE list, several ways to reach it — and it is the
+// difference between adding a sixth mark in one place and remembering three.
+
+import { ICONS } from './icons.ts';
+import { t } from './i18n.ts';
+import type { MarkType } from './inline.ts';
+
+export interface MarkTool {
+ t: MarkType;
+ icon: string;
+ /** a FUNCTION, not a string: a label built at import time freezes before the
+ * viewer's locale is resolved — the rule in i18n.ts. */
+ title: () => string;
+}
+
+export const MARK_TOOLS: readonly MarkTool[] = [
+ { t: 'b', icon: ICONS.bold, title: () => t('Bold (⌘B)') },
+ { t: 'i', icon: ICONS.italic, title: () => t('Italic (⌘I)') },
+ { t: 'u', icon: ICONS.underline, title: () => t('Underline (⌘U)') },
+ { t: 's', icon: ICONS.strike, title: () => t('Strikethrough') },
+ { t: 'code', icon: ICONS.code, title: () => t('Code') },
+];
diff --git a/type/src/math.ts b/type/src/math.ts
new file mode 100644
index 00000000..29c3b784
--- /dev/null
+++ b/type/src/math.ts
@@ -0,0 +1,510 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// ─────────────────────────────────────────────────────────────────────────────
+// MATHEMATICS for bento/type — a hand-rolled TeX-subset typesetter.
+// ─────────────────────────────────────────────────────────────────────────────
+//
+// NO DEPENDENCY, ON PURPOSE. KaTeX is ~280KB of JS plus 60 font files; MathJax
+// is larger still. This app ships as ONE HTML file that a person emails to
+// somebody, and a maths engine may not be half of it. So the layout is done
+// here, in about a thousand lines, and the glyphs come from whatever serif the
+// reader already has. That last part is the real cost of the choice and it is
+// stated plainly below.
+//
+// ═══ WHAT IS SUPPORTED ══════════════════════════════════════════════════════
+//
+// structure ^ _ (both orders, nested, primes `x''`), { } grouping,
+// \frac \dfrac \tfrac \cfrac \binom, \sqrt and \sqrt[n]{},
+// \left…\right with . as the null delimiter, \big \Big \bigg
+// \Bigg (accepted, set at natural size), \overline \underline
+// operators \sum \prod \coprod \int \iint \iiint \oint \bigcup \bigcap
+// \bigoplus \bigotimes \bigvee \bigwedge \bigsqcup \biguplus —
+// with LIMITS above/below in display style for the \sum family
+// and beside the sign for the \int family, as TeX does
+// functions \sin \cos \tan \cot \sec \csc \arcsin \arccos \arctan \sinh
+// \cosh \tanh \coth \log \ln \lg \exp \det \dim \deg \arg \ker
+// \hom \Pr \gcd \lim \limsup \liminf \max \min \sup \inf
+// symbols the full Greek alphabet incl. \var- forms; ~120 operators,
+// relations, arrows and ordinary symbols (see math/symbols.ts)
+// fences ( ) [ ] \{ \} | \| ⟨ ⟩ ⌈ ⌉ ⌊ ⌋ / ↑ ↓, stretched to their content
+// accents \hat \widehat \check \tilde \widetilde \acute \grave \dot
+// \ddot \breve \bar \vec \mathring
+// fonts \mathrm \mathbf \mathit \mathsf \mathtt \boldsymbol
+// \operatorname, and \mathbb \mathcal \mathfrak as UNICODE
+// transliterations (there is no font to ship)
+// text \text \textrm \textnormal \mbox
+// spacing \, \: \; \! \quad \qquad \enspace and a literal `\ `
+// styles \displaystyle \textstyle \scriptstyle \scriptscriptstyle
+// environments matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix cases
+// aligned array (rows with \\, cells with &)
+//
+// ═══ WHAT IS NOT ════════════════════════════════════════════════════════════
+//
+// · MACROS. No \newcommand, \def, \renewcommand. A document that can define
+// its own commands needs an expansion engine with its own loop guards, and
+// the whole point of this module is that it cannot hang the page.
+// · NUMBERED EQUATIONS, \label, \ref, \tag, and the `align`/`equation`
+// environments that carry them. Numbering is a DOCUMENT concern — it has to
+// interact with pagination, the outline and cross-references — and it
+// belongs in the core beside footnote numbering, not inside a formula
+// renderer. `aligned` (the inner form, unnumbered) is supported.
+// · \overbrace \underbrace \substack \not \mathchoice \genfrac \raisebox,
+// colour and size commands, \begin{tabular}, and TeX programming.
+// · LINE BREAKING INSIDE A FORMULA. A long display equation does not wrap; it
+// runs on. TeX breaks at relations with an author's hints, which needs the
+// line width, which this renderer deliberately does not know.
+// · A MATHS FONT. \mathbb{R} is U+211D, not a rendered glyph from a shipped
+// font, so exotic symbols look like whatever the reader's system has and a
+// few may show as a missing-glyph box. This is the price of one file.
+//
+// Anything unsupported RENDERS AS AN ERROR IN PLACE — the offending source, in
+// the error colour, with a tooltip — never as an exception and never as a blank
+// document. See math/parse.ts for why that is the only acceptable behaviour.
+//
+// ═══ HOW MATH FITS THE MODEL, AND WHY ═══════════════════════════════════════
+//
+// THE SOURCE IS THE MODEL. Nothing rendered is ever stored: a block holds
+// `\frac{a}{b}`, and this module turns that into markup on every render. That
+// is not negotiable — rendered output in the document would be a second
+// representation to keep in step with the first, and the format has exactly one
+// of everything on purpose.
+//
+// INLINE MATH IS A MARK over the source characters (MarkType 'math'), NOT an
+// atom like the footnote marker. The prompt for this feature offered both, and
+// the mark wins on all four of the things the app is actually built around:
+//
+// 1. REDLINE. The redline diffs plain text word by word. With the source in
+// the text, changing `x^2` to `x^3` reports as a one-word change to the
+// formula — reviewable. As an atom with the source held off to the side
+// (the footnote arrangement), the diff would see NO CHANGE AT ALL: the
+// text either side is identical and the marker is in the same place. For
+// an app whose differentiator is redlining contracts, a class of edit that
+// is invisible to review is disqualifying.
+// 2. SIGNATURES. canon.ts canonicalises text + marks. A mark is already
+// canonicalised; a side table of formulas would be a new field to fold in,
+// and every new field is a new chance for two honest parties to produce
+// different bytes.
+// 3. THE CARET is (blockId, offset). With the source in the text, a formula
+// occupies exactly as many model positions as it has source characters,
+// so every offset after it is a real offset and `spliceText` moves marks
+// and footnote anchors past it with the code that already exists.
+// 4. FOOTNOTE ANCHORS and marks already use one rule for "an offset into this
+// text". Math uses the same one. No third concept.
+//
+// The cost is that a formula is not one keystroke wide: with the naive core
+// the caret would walk through the source characters invisibly. That is what
+// the editor patch below is for — the rendered formula is
+// `contenteditable=false`, and the caret treats it as one indivisible unit of
+// N characters. N is the source length, so the MODEL arithmetic is unchanged;
+// only the visible stepping is.
+//
+// DISPLAY MATH IS A BLOCK KIND ('math'), whose `text` is the source. A display
+// equation is a paragraph-level object: it is centred, it takes the whole
+// measure, it can be a page break's target, and the outline and the redline
+// should be able to name it. Every one of those is what a BlockKind is for, and
+// none of them is expressible by a mark. The block stays FLAT — no new
+// container, no tree — exactly as `ul` and `cell` do.
+//
+// THE PAGINATION TRAP, AND WHAT WAS DONE ABOUT IT. paginate.ts measures LINE
+// BOXES with a TreeWalker over TEXT NODES, and rejects nodes whose value is
+// whitespace. An element containing no text is therefore INVISIBLE to
+// pagination: it would occupy vertical space on screen that the page breaks
+// know nothing about, and every page after it would break in the wrong place.
+// A formula normally contains plenty of text — the glyphs ARE text nodes, which
+// is one more reason this renderer emits HTML rather than SVG — but not always:
+// `\sqrt{}` while it is being typed, `\frac{}{}` from a generator, an empty
+// matrix cell. So every empty slot is filled with U+200B (see layout.ts ZW),
+// which is a text node, is NOT whitespace to `String.trim` (checked: it
+// survives the walker's filter), and prints nothing. The atom wrapper carries
+// one too, so a formula can never be a zero-text element.
+// The remaining honest limitation: a tall inline formula reports its own
+// parts' rects to the walker, so a page CAN break inside one. Display math is a
+// block and does not have this problem; it is the right shape for anything tall
+// enough to care.
+//
+// ═══ NEEDS FROM THE CORE ════════════════════════════════════════════════════
+//
+// This module is complete and testable without any of the following —
+// `renderMath`, `inlineMathHtml` and `displayMathHtml` are pure functions of a
+// string. These six edits are what connects it to the document.
+//
+// (1) type/src/inline.ts — one word.
+// export type MarkType = 'b' | 'i' | 'u' | 's' | 'code' | 'link' | 'math';
+// WHY: the mark is how a run of text is known to be a formula. `math` has
+// no entry in TAG because it is never emitted as a plain tag; see (2).
+//
+// (2) type/src/inline.ts — `toHtml` gains a fourth parameter, ranges whose text
+// is replaced wholesale:
+//
+// export function toHtml(text: string, marks: Mark[] = [],
+// inject?: Map<number, string>,
+// atoms?: Array<{ from: number; to: number; html: string }>): string
+//
+// Implementation: add each atom's `from`/`to` to the cut set; while walking,
+// when the current point is an atom's `from`, emit its `html`, skip to `to`,
+// and emit no marks or injections inside it. ~8 lines. inline.ts learns
+// NOTHING about math — the caller supplies the html — which is the same
+// arrangement `inject` already has for footnote markers.
+// WHY: without it the source characters render as literal text.
+//
+// (3) type/src/inline.ts — `fromDom` learns that an atom may carry characters:
+//
+// export function fromDom(root: Node,
+// isAtom: (el: Element) => boolean = () => false,
+// atomText?: (el: Element) => { text: string; t: MarkType } | undefined): Parsed
+//
+// When `atomText` returns a value for an atom element, append its `text` to
+// the running text and push a mark of type `t` over it, instead of
+// recording a zero-width atom. ~6 lines.
+// WHY: this is the seam where the DOM re-enters the model. Without it the
+// first keystroke anywhere in a block would delete every formula in it,
+// because the read-back would find no characters where the source was.
+//
+// (4) type/src/render.ts — three small things:
+// · `TAG` gains `math: 'div'`
+// · `blockHtml(b)`:
+// if (b.kind === 'math') return displayMathHtml(b.text);
+// const atoms = (b.marks ?? []).filter(m => m.t === 'math')
+// .map(m => ({ from: m.from, to: m.to,
+// html: inlineMathHtml(b.text.slice(m.from, m.to)) }));
+// …pass `atoms` as toHtml's fourth argument
+// · `isMathAtom = (el: Element) => el.tagName === 'SPAN' &&
+// el.classList.contains('t-math')`, and `readBlock`
+// passes `isNoteAtom(el) || isMathAtom(el)` as `isAtom` plus an
+// `atomText` that returns `{ text: el.dataset.tex, t: 'math' }` for a
+// math atom. `import { displayMathHtml, inlineMathHtml } from './math.ts'`
+// WHY: one renderer draws the editor, the thumbnails and print, so this is
+// also all that print.ts needs — it goes through `blockHtml` and `TAG`.
+//
+// (5) type/src/model.ts — `'math'` joins `BlockKind` and the kind allow-list in
+// `parseDoc` (the array literal in the same place). Nothing else: a math
+// block has no new fields, its source is `text`, so `spliceText`,
+// `plainText`, `wordCount` and the canonical form all already handle it.
+// WHY: without it a saved display equation is REPAIRED BACK to a paragraph
+// on the next open, silently, which is a data-loss bug.
+//
+// (6) type/src/editor.ts — the caret steps over a formula rather than through
+// it. In `#offsetIn`, an element for which `isMathAtom` holds contributes
+// `el.dataset.tex.length` characters and is not descended into; in
+// `#pointAt`, the same element is skipped with its length added, so a
+// position inside it resolves to its near edge. ~8 lines across the two
+// walks, mirroring exactly what they already do for note atoms — the only
+// difference is that a note contributes 0 characters and a formula
+// contributes its source length.
+// WHY: without it the caret sits at invisible positions inside a rendered
+// formula and arrow keys appear to stall.
+//
+// Optional, not needed for correctness: a "Equation" entry in main.ts's block
+// style select, so display math is reachable from the same place as headings.
+
+import { registerKey, registerPanel, registerTool,
+ type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+import { spliceText, uid, type Block } from './model.ts';
+import { renderMath, ZW } from './math/layout.ts';
+import type { Mark } from './inline.ts';
+
+export { parseMath } from './math/parse.ts';
+export { renderMath, layoutMath } from './math/layout.ts';
+export type { MathNode } from './math/parse.ts';
+export type { Box } from './math/layout.ts';
+
+/**
+ * The mark type and block kind this module needs from the core (edits 1 and 5).
+ *
+ * Named constants rather than literals so that the day the core patch lands,
+ * every use of them typechecks against the real union instead of being spelled
+ * out in six places.
+ */
+export const MATH_MARK = 'math';
+export const MATH_KIND = 'math';
+
+/** Is this mark a formula? Written against the string so it compiles today. */
+export const isMathMark = (m: Mark): boolean => (m.t as string) === MATH_MARK;
+
+/**
+ * A math mark.
+ *
+ * The cast is the ONE place this module admits that core edit (1) has not
+ * landed yet: `MarkType` does not include 'math', so the object cannot be typed
+ * as a `Mark` without it. When the union gains the member this becomes an
+ * ordinary literal and the helper can go. It is deliberately a single function
+ * rather than a cast at each call site, so applying the patch is a one-line
+ * cleanup and not a hunt.
+ */
+const mathMark = (from: number, to: number): Mark =>
+ ({ t: MATH_MARK, from, to } as unknown as Mark);
+
+// ───────────────────────────────────────────────────────────── the renderers
+
+/**
+ * One inline formula, as the ATOM the core will embed (core edits 2 and 4).
+ *
+ * `data-tex` carries the SOURCE — it is what `fromDom` reads back, so the
+ * rendered glyphs are never what re-enters the model. `contenteditable=false`
+ * keeps the browser from letting the caret inside a box whose structure has no
+ * model position, and the leading U+200B guarantees the element contains a text
+ * node whatever the formula turns out to be (see the pagination note above).
+ */
+export function inlineMathHtml(src: string): string {
+ const r = renderMath(src, { display: false });
+ const bad = r.errors.length ? ' t-math-bad' : '';
+ return `<span class="t-math${bad}" data-tex="${attr(src)}" contenteditable="false">` +
+ `${ZW}${r.html}</span>`;
+}
+
+/**
+ * One display equation, as the INNER html of a `math` block (core edit 4).
+ *
+ * The block element itself is created by render.ts from `TAG`, exactly as a
+ * paragraph is, so the model stays flat and nothing downstream has to learn
+ * what an equation is.
+ */
+export function displayMathHtml(src: string): string {
+ const r = renderMath(src, { display: true });
+ const bad = r.errors.length ? ' t-math-bad' : '';
+ return `<span class="t-math t-math-display${bad}" data-tex="${attr(src)}">${ZW}${r.html}</span>`;
+}
+
+const attr = (s: string): string =>
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+
+/** Everything the parser objected to, for the panel's error line. */
+export const mathErrors = (src: string, display = false): string[] =>
+ renderMath(src, { display }).errors;
+
+// ───────────────────────────────────────────────────────────── editing
+
+/** The math mark under the caret, if the caret is in a formula. */
+function formulaAt(ctx: FeatureContext): { block: Block; mark: Mark } | null {
+ const c = ctx.editor.caret();
+ if (!c) return null;
+ const block = ctx.store.block(c.id);
+ if (!block?.marks) return null;
+ const at = c.to !== undefined ? Math.min(c.at, c.to) : c.at;
+ const mark = block.marks.find(m => isMathMark(m) && at >= m.from && at <= m.to);
+ return mark ? { block, mark } : null;
+}
+
+/** The default a fresh formula starts from — short, valid, and obviously math. */
+const SEED = 'x^2 + y^2 = z^2';
+
+/**
+ * Insert an inline formula, or turn the selection into one.
+ *
+ * Turning a SELECTION into a formula matters more than it looks: it is how a
+ * document that already contains `E = mc^2` as ordinary text becomes one where
+ * that is typeset, without retyping it. The characters do not move — only the
+ * mark is added — so the redline of that edit is empty, which is correct: the
+ * words did not change.
+ */
+export function insertInlineMath(ctx: FeatureContext): void {
+ const c = ctx.editor.caret();
+ if (!c) { ctx.toast(t('Put the caret where the formula should go')); return; }
+ const block = ctx.store.block(c.id);
+ if (!block) return;
+ const has = c.to !== undefined && c.to !== c.at;
+ const from = has ? Math.min(c.at, c.to!) : c.at;
+ const to = has ? Math.max(c.at, c.to!) : c.at;
+
+ ctx.store.commit(d => {
+ const i = d.body.findIndex(b => b.id === c.id);
+ if (i < 0) return;
+ let b = d.body[i];
+ let end = to;
+ if (!has) {
+ b = spliceText(b, from, 0, SEED);
+ end = from + SEED.length;
+ }
+ const marks = (b.marks ?? []).filter(m => !isMathMark(m) || m.to <= from || m.from >= end);
+ marks.push(mathMark(from, end));
+ b.marks = marks.sort((x, y) => x.from - y.from);
+ d.body[i] = b;
+ }, { scope: { block: c.id } });
+ ctx.refresh();
+ ctx.toast(t('Formula added — edit it in the Math panel'));
+}
+
+/**
+ * Insert a display equation as its own block.
+ *
+ * An empty paragraph at the caret is CONSUMED rather than left above the
+ * equation, which is the same rule `insertTable` uses — pressing Enter and then
+ * inserting should not leave a blank line behind.
+ */
+export function insertDisplayMath(ctx: FeatureContext): void {
+ const c = ctx.editor.caret();
+ const body = ctx.store.doc.body;
+ const i = c ? body.findIndex(b => b.id === c.id) : body.length - 1;
+ const here = body[Math.max(0, i)];
+ const block = { id: uid(), kind: MATH_KIND, text: SEED } as unknown as Block;
+ ctx.store.commit(d => {
+ const at = here && here.text === '' && here.kind === 'para' ? i : i + 1;
+ const drop = here && here.text === '' && here.kind === 'para' ? 1 : 0;
+ d.body.splice(Math.max(0, at), drop, block);
+ });
+ ctx.refresh();
+ ctx.toast(t('Equation added — edit it in the Math panel'));
+}
+
+/** Rewrite the source of the formula at the caret. */
+function setSource(ctx: FeatureContext, id: string, from: number, to: number, src: string): void {
+ ctx.store.commit(d => {
+ const i = d.body.findIndex(b => b.id === id);
+ if (i < 0) return;
+ const b = spliceText(d.body[i], from, to - from, src);
+ const marks = (b.marks ?? []).filter(m => !isMathMark(m) || m.to <= from || m.from >= from + src.length);
+ marks.push(mathMark(from, from + src.length));
+ b.marks = marks.sort((x, y) => x.from - y.from);
+ d.body[i] = b;
+ }, { scope: { block: id } });
+ ctx.refresh();
+}
+
+// ───────────────────────────────────────────────────────────── the chrome
+
+/** House recipe, character for character with icons.ts: 24px box, 16px render. */
+const RADICAL_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" ' +
+ 'fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" ' +
+ 'stroke-linejoin="round"><path d="M3 13h3l3.5 7L14 4h7"/></svg>';
+
+registerTool({
+ id: 'math',
+ icon: RADICAL_ICON,
+ get title() { return t('Formula (⌘M)'); },
+ group: 'insert',
+ label: () => t('Formula'),
+ order: 40,
+ run: ctx => insertInlineMath(ctx),
+});
+
+// A display equation is a SECOND kind of insert, not an action — it puts
+// something in the document, so it belongs beside Formula in the Insert menu
+// rather than in ⋯ where it was competing with Print and Sign.
+registerTool({
+ id: 'math-display',
+ icon: RADICAL_ICON,
+ get title() { return t('Insert a display equation on its own line'); },
+ group: 'insert',
+ label: () => t('Equation block'),
+ order: 41,
+ run: ctx => insertDisplayMath(ctx),
+});
+
+registerKey({ key: 'm', mod: true, run: ctx => insertInlineMath(ctx) });
+
+/**
+ * The Math panel: the source of the formula under the caret, and what it looks
+ * like as you type it.
+ *
+ * A live preview is not decoration here. TeX is a language, the reader of this
+ * app is not required to know it, and the difference between `x^10` and
+ * `x^{10}` is invisible in the source and obvious in the preview. The panel
+ * also renders the ERRORS, which is where an unsupported command gets
+ * explained rather than silently ignored.
+ */
+registerPanel({
+ id: 'math',
+ get label() { return t('Math'); },
+ // RIGHT, not left: this panel edits the SOURCE OF THE FORMULA UNDER THE
+ // CARET, which is a property of the selection, not a list of what is in the
+ // document. It sat on the left only because that was where panels went.
+ side: 'right',
+ order: 60,
+ mount(host, ctx) {
+ host.innerHTML = '';
+ const hint = document.createElement('p');
+ hint.className = 't-hint';
+ host.appendChild(hint);
+
+ const area = document.createElement('textarea');
+ area.className = 't-mathsrc';
+ area.rows = 3;
+ area.spellcheck = false;
+ host.appendChild(area);
+
+ const preview = document.createElement('div');
+ preview.className = 't-mathprev';
+ host.appendChild(preview);
+
+ const errs = document.createElement('p');
+ errs.className = 't-hint t-bad';
+ host.appendChild(errs);
+
+ const help = document.createElement('p');
+ help.className = 't-hint';
+ host.appendChild(help);
+
+ // `current` is the formula the panel is editing, resolved on every update.
+ // Held here rather than read back from the DOM so that a re-render between
+ // keystrokes cannot make the panel write into the wrong block.
+ let current: { id: string; from: number; to: number; display: boolean } | null = null;
+
+ const draw = () => {
+ const src = area.value;
+ const r = renderMath(src, { display: !!current?.display });
+ preview.innerHTML = `<span class="t-math${current?.display ? ' t-math-display' : ''}">${ZW}${r.html}</span>`;
+ errs.textContent = r.errors.length ? r.errors.slice(0, 3).join(' · ') : '';
+ };
+
+ area.addEventListener('input', draw);
+ area.addEventListener('change', () => {
+ if (!current) return;
+ const src = area.value;
+ if (current.display) {
+ ctx.store.commit(d => {
+ const b = d.body.find(x => x.id === current!.id);
+ if (b) b.text = src;
+ }, { scope: { block: current.id } });
+ current = { ...current, to: src.length };
+ ctx.refresh();
+ } else {
+ setSource(ctx, current.id, current.from, current.to, src);
+ current = { ...current, to: current.from + src.length };
+ }
+ });
+
+ (host as HTMLElement & { _sync?: () => void })._sync = () => {
+ hint.textContent = t('The formula at the caret. TeX-like source; the document stores the source, never the picture.');
+ help.textContent = t('Supported: \\frac \\sqrt ^ _ \\sum \\int \\left( \\right) Greek, matrices, cases.');
+ const c = ctx.editor.caret();
+ const blk = c ? ctx.store.block(c.id) : undefined;
+ if (blk && (blk.kind as string) === MATH_KIND) {
+ current = { id: blk.id, from: 0, to: blk.text.length, display: true };
+ if (document.activeElement !== area) area.value = blk.text;
+ area.disabled = false;
+ } else {
+ const f = formulaAt(ctx);
+ if (f) {
+ current = { id: f.block.id, from: f.mark.from, to: f.mark.to, display: false };
+ if (document.activeElement !== area) area.value = f.block.text.slice(f.mark.from, f.mark.to);
+ area.disabled = false;
+ } else {
+ current = null;
+ if (document.activeElement !== area) area.value = '';
+ area.disabled = false;
+ }
+ }
+ // HIDDEN when there is no formula at the caret. On the left this panel sat
+ // behind a tab, so an empty one cost nothing; stacked on the right it is
+ // always on screen, and a permanent "The formula at the caret" under a
+ // contract that contains no mathematics is just noise. A contextual panel
+ // that is never absent stops being contextual.
+ host.hidden = current === null;
+ draw();
+ };
+ (host as HTMLElement & { _sync?: () => void })._sync!();
+ document.addEventListener('selectionchange', () => {
+ // `.on` is a LEFT-hand tab class. Right-hand panels are stacked and never
+ // carry it (.t-props .t-panel is display:block), so this guard was always
+ // false after the panel moved and the source stopped following the caret
+ // — it only refreshed when the document itself changed.
+ if (host.isConnected) (host as HTMLElement & { _sync?: () => void })._sync!();
+ });
+ },
+ update(host) {
+ (host as HTMLElement & { _sync?: () => void })._sync?.();
+ },
+});
diff --git a/type/src/math/layout.ts b/type/src/math/layout.ts
new file mode 100644
index 00000000..f1309672
--- /dev/null
+++ b/type/src/math/layout.ts
@@ -0,0 +1,523 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Math nodes → HTML, with the vertical arithmetic done here rather than by the
+// browser.
+//
+// WHY THERE ARE METRICS AT ALL. Almost everything horizontal (widths, line
+// breaking, centring a numerator over a denominator) is something CSS already
+// does well, and this module leaves all of it to CSS. Four things CSS cannot
+// do, and they are exactly the four that make a formula look typeset:
+//
+// · a fraction bar must sit on the MATH AXIS of the surrounding line, not at
+// an arbitrary offset, and the axis is where the `=` sign's bar is
+// · a superscript must clear the base's height and a subscript its depth,
+// and the two must clear EACH OTHER
+// · a radical and a `\left(` must be as tall as what they contain
+// · a matrix must centre on the axis
+//
+// Each needs a HEIGHT, and asking the DOM for one would mean rendering, then
+// measuring, then re-rendering — which is not pure, not deterministic, costs a
+// forced reflow per formula, and would make the printed document depend on the
+// screen it was laid out on. So this module carries a MODEL of the metrics:
+// every box reports how far it rises above and falls below its own baseline,
+// in em, and the shifts are computed from those.
+//
+// The model is APPROXIMATE and knows it. A line of text is taken to rise 0.75em
+// and fall 0.22em regardless of what glyphs are in it, because a self-contained
+// document cannot ship a font and therefore cannot know the reader's metrics.
+// The consequence is that a shift can be a few hundredths of an em out — which
+// is invisible — and never that a box overlaps its neighbour, because every
+// clearance is computed from the same conservative numbers on both sides.
+//
+// UNITS. All metrics are in em OF THE FORMULA'S OUTERMOST font size, so boxes
+// of different script sizes can be compared and added directly. CSS lengths,
+// however, resolve against the ELEMENT's font size — so every number that goes
+// into an attribute is divided by the size of the style it is emitted in. That
+// division is the one thing in this file that must never be forgotten; `emIn`
+// exists so it happens in one place.
+
+import {
+ parseMath, type MathNode, type ParseOut, type StyleName, type Variant,
+} from './parse.ts';
+import { ALPHABETS, type Cls } from './symbols.ts';
+
+/** Font size of each style, as a fraction of the formula's base size. */
+const SIZE: Record<StyleName, number> = { D: 1, T: 1, S: 0.7, SS: 0.5 };
+/** How far a line of text rises above, and falls below, its baseline. */
+const ASCENT = 0.75, DESCENT = 0.22;
+/** The math axis: where a fraction bar and a `−` sign sit. */
+const AXIS = 0.25;
+/** Default rule thickness (fraction bar, radical bar, overline). */
+const RULE = 0.048;
+
+/** The style a script (superscript, subscript) is set in. */
+const SCRIPT_OF: Record<StyleName, StyleName> = { D: 'S', T: 'S', S: 'SS', SS: 'SS' };
+/** The style a fraction's numerator and denominator are set in. */
+const FRAC_OF: Record<StyleName, StyleName> = { D: 'T', T: 'S', S: 'SS', SS: 'SS' };
+
+export interface Box {
+ html: string;
+ /** rise above the baseline, in em of the formula's base size */
+ h: number;
+ /** fall below it */
+ d: number;
+ /** the atom class, which is what decides the space before the next box */
+ cls: Cls;
+}
+
+export interface LayoutOpts {
+ /** display math is set in D style: bigger operators, taller fractions */
+ display?: boolean;
+}
+
+interface St {
+ style: StyleName;
+ variant?: Variant;
+ alphabet?: string;
+}
+
+// ────────────────────────────────────────────────────────────── plumbing
+
+const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
+export const esc = (s: string): string => s.replace(/[&<>"]/g, c => ESC[c]);
+
+/**
+ * A number, rounded to a fixed number of places.
+ *
+ * DETERMINISM LIVES HERE. The same source must produce the same bytes on every
+ * machine — the signature covers the document, but a redline that re-rendered
+ * a formula and saw different markup would report a change nobody made. Fixed
+ * rounding also keeps floating-point noise (0.30000000000000004) out of the
+ * output, which is the readable version of the same requirement.
+ */
+export const num = (v: number): string => {
+ const r = Math.round(v * 1e4) / 1e4;
+ return Object.is(r, -0) ? '0' : String(r);
+};
+
+/** A length in em of an element that is set at `size`. */
+const emIn = (v: number, size: number): string => `${num(v / size)}em`;
+
+const VARIANT_CLASS: Record<Variant, string> = {
+ italic: 't-mi', up: '', bold: 't-mb', bolditalic: 't-mbi', sans: 't-msf', mono: 't-mtt',
+};
+
+const box = (html: string, h: number, d: number, cls: Cls): Box => ({ html, h, d, cls });
+
+// ────────────────────────────────────────────────────────────── spacing
+//
+// TeX's inter-atom spacing, reduced to the rule that matters: a Bin gets a
+// medium space around it, a Rel a thick one, a Punct a thin one after, and an
+// Op a thin one after. Script styles get none of it, which is why `x^{a+b}`
+// stays compact.
+
+const SPACE_BEFORE: Record<Cls, number> = {
+ ord: 0, op: 0.167, bin: 0.222, rel: 0.278, open: 0, close: 0, punct: 0, inner: 0.167,
+};
+const SPACE_AFTER: Record<Cls, number> = {
+ ord: 0, op: 0.167, bin: 0.222, rel: 0.278, open: 0, close: 0, punct: 0.167, inner: 0.167,
+};
+/**
+ * A Bin that has nothing to bind becomes an Ord.
+ *
+ * This is what makes `-x` a negation set tight against the x, while `a-x` is a
+ * subtraction with air around the sign. Without it every leading minus in the
+ * document is spaced as though something were missing before it.
+ */
+const demoteBin = (cls: Cls, prev: Cls | null): Cls =>
+ cls === 'bin' && (prev === null || prev === 'bin' || prev === 'rel' || prev === 'open'
+ || prev === 'punct' || prev === 'op')
+ ? 'ord' : cls;
+
+// ────────────────────────────────────────────────────────────── the walk
+
+export function layout(node: MathNode, st: St): Box {
+ const size = SIZE[st.style];
+ switch (node.k) {
+ case 'row': return layoutRow(node.body, st);
+ case 'atom': return layoutAtom(node.ch, node.cls, node.variant, st);
+ case 'op': return layoutOp(node, st);
+ case 'frac': return layoutFrac(node, st);
+ case 'sqrt': return layoutSqrt(node, st);
+ case 'script': return layoutScript(node, st);
+ case 'fence': return layoutFence(node, st);
+ case 'accent': return layoutAccent(node, st);
+ case 'bar': return layoutBar(node, st);
+ case 'matrix': return layoutMatrix(node, st);
+ case 'text':
+ return box(`<span class="t-mtext">${esc(node.s)}</span>`, ASCENT * size, DESCENT * size, 'ord');
+ case 'space':
+ return node.em >= 0
+ ? box(`<span class="t-msp" style="width:${emIn(node.em * size, size)}"></span>`, 0, 0, 'ord')
+ : box(`<span class="t-msp" style="margin-left:${emIn(node.em * size, size)}"></span>`, 0, 0, 'ord');
+ case 'style': {
+ const inner = layout(node.body, { ...st, style: node.style });
+ const ratio = SIZE[node.style] / size;
+ if (ratio === 1) return inner;
+ return box(`<span style="font-size:${num(ratio)}em">${inner.html}</span>`, inner.h, inner.d, inner.cls);
+ }
+ case 'font':
+ return layout(node.body, { ...st, variant: node.variant ?? st.variant, alphabet: node.alphabet });
+ case 'err':
+ // The whole point of the error node: it is VISIBLE, it is in place, and
+ // it carries the reason in a tooltip. Everything around it still sets.
+ return box(`<span class="t-merr" title="${esc(node.msg)}">${esc(node.s || '?')}</span>`,
+ ASCENT * size, DESCENT * size, 'ord');
+ }
+}
+
+function layoutRow(body: MathNode[], st: St): Box {
+ const size = SIZE[st.style];
+ if (!body.length) return box('', 0, 0, 'ord');
+ const parts: string[] = [];
+ let h = 0, d = 0;
+ let prev: Cls | null = null;
+ let first: Cls | null = null;
+ const tight = st.style === 'S' || st.style === 'SS';
+ for (const child of body) {
+ const b = layout(child, st);
+ if (!b.html && b.h === 0 && b.d === 0 && b.cls === 'ord' && child.k === 'row') continue;
+ const cls = demoteBin(b.cls, prev);
+ if (prev !== null && !tight) {
+ // the wider of what the left atom wants after it and the right atom
+ // wants before it — never the sum, or `a = b` would set twice as loose
+ // as `a + b` for no reason a reader could name
+ const gap = Math.max(SPACE_AFTER[prev], SPACE_BEFORE[cls]);
+ if (gap > 0) parts.push(`<span class="t-msp" style="width:${num(gap)}em"></span>`);
+ }
+ parts.push(b.html);
+ h = Math.max(h, b.h); d = Math.max(d, b.d);
+ prev = cls;
+ if (first === null) first = cls;
+ }
+ if (!parts.length) return box('', 0, 0, 'ord');
+ // an empty-looking row still needs SOME height, or a fence around it collapses
+ if (h === 0 && d === 0) { h = ASCENT * size; d = DESCENT * size; }
+ return box(parts.join(''), h, d, body.length === 1 && first ? first : 'ord');
+}
+
+function layoutAtom(ch: string, cls: Cls, variant: Variant | undefined, st: St): Box {
+ const size = SIZE[st.style];
+ let c = ch;
+ if (st.alphabet) {
+ const table = ALPHABETS[st.alphabet];
+ if (table && table[c]) c = table[c];
+ }
+ const v = st.variant ?? variant ?? 'up';
+ const klass = VARIANT_CLASS[v];
+ const html = klass ? `<span class="${klass}">${esc(c)}</span>` : esc(c);
+ return box(html, ASCENT * size, DESCENT * size, cls);
+}
+
+function layoutOp(node: Extract<MathNode, { k: 'op' }>, st: St): Box {
+ const size = SIZE[st.style];
+ if (!node.big) {
+ // a function name: upright, and one unit — `\sin` never sets as s·i·n
+ return box(`<span class="t-mop">${esc(node.name ?? node.ch)}</span>`,
+ ASCENT * size, DESCENT * size, 'op');
+ }
+ // Big operators grow in display style, and they CENTRE ON THE AXIS rather
+ // than sitting on the baseline: a summation sign hanging off the baseline is
+ // the single most obvious tell of a home-made math renderer.
+ const f = st.style === 'D' ? 1.42 : 1;
+ const mid = ((ASCENT - DESCENT) / 2) * size * f;
+ const v = AXIS * size - mid;
+ const style = `font-size:${num(f)}em;vertical-align:${emIn(v, size * f)}`;
+ return box(`<span class="t-mbig" style="${style}">${esc(node.ch)}</span>`,
+ ASCENT * size * f + v, DESCENT * size * f - v, 'op');
+}
+
+/**
+ * A fraction.
+ *
+ * The bar goes on the AXIS, so `\frac{1}{2}` and `x = \frac{1}{2}` have their
+ * bar at the same height as the `=`. Everything else follows from that: the
+ * numerator is stacked above it and the denominator below, and the whole box is
+ * then lowered so the bar lands where it belongs.
+ *
+ * The emitted box is an inline-block whose baseline is its LAST line box — the
+ * denominator's — which is why the shift is computed from the denominator's
+ * height and not from the box's total height.
+ */
+function layoutFrac(node: Extract<MathNode, { k: 'frac' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const inner: StyleName = node.style ?? FRAC_OF[st.style];
+ const cs = SIZE[inner];
+ const num_ = layout(node.num, { ...st, style: inner });
+ const den = layout(node.den, { ...st, style: inner });
+ const rule = node.bar ? RULE * size : 0;
+ const gap = (st.style === 'D' ? 0.14 : 0.10) * size;
+
+ const barAbove = den.h + gap + rule / 2; // bar centre over box baseline
+ const v = AXIS * size - barAbove; // lower the box onto the axis
+ const h = AXIS * size + rule / 2 + gap + num_.h + num_.d;
+ const d = den.d + barAbove - AXIS * size;
+
+ const numStyle = `font-size:${num(cs / size)}em;padding-bottom:${emIn(gap, cs)}` +
+ (node.bar ? `;border-bottom-width:${emIn(rule, cs)}` : '');
+ const denStyle = `font-size:${num(cs / size)}em;padding-top:${emIn(gap, cs)}`;
+ const html =
+ `<span class="t-mfrac${node.bar ? '' : ' t-nobar'}" style="vertical-align:${emIn(v, size)}">` +
+ `<span class="t-mnum" style="${numStyle}">${num_.html || ZW}</span>` +
+ `<span class="t-mden" style="${denStyle}">${den.html || ZW}</span></span>`;
+
+ const inner_ = box(html, h, d, 'inner');
+ if (!node.left && !node.right) return inner_;
+ return fenceAround(inner_, node.left ?? '', node.right ?? '', st);
+}
+
+/**
+ * A square root.
+ *
+ * The surd is an SVG stretched to the height of what it covers, with
+ * `vector-effect="non-scaling-stroke"` so the stroke stays even however far it
+ * is stretched — the reason not to use a `√` glyph with a scaleY, which
+ * thickens the horizontal stroke as it grows and looks wrong at any size worth
+ * stretching for.
+ */
+function layoutSqrt(node: Extract<MathNode, { k: 'sqrt' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const body = layout(node.body, st);
+ const rule = RULE * size;
+ const gap = 0.09 * size;
+ const total = body.h + gap + rule + body.d;
+
+ const surd =
+ `<svg class="t-msurd" viewBox="0 0 12 100" preserveAspectRatio="none" aria-hidden="true" ` +
+ `style="height:${emIn(total, size)};vertical-align:${emIn(-body.d, size)}">` +
+ `<path d="M0.7 60 L3.4 55 L6.2 95 L10.5 3 L12 3" vector-effect="non-scaling-stroke"/></svg>`;
+
+ let index = '';
+ if (node.index) {
+ const ix = layout(node.index, { ...st, style: 'SS' });
+ // the index sits in the crook of the surd: up by most of its height, and
+ // pulled right so it does not push the radical along the line
+ const lift = total * 0.55;
+ index = `<span class="t-mroot" style="vertical-align:${emIn(lift, SIZE.SS * size)};` +
+ `font-size:${num(SIZE.SS)}em">${ix.html}</span>`;
+ }
+ const covered =
+ `<span class="t-mrad" style="border-top-width:${emIn(rule, size)};` +
+ `padding-top:${emIn(gap, size)}">${body.html || ZW}</span>`;
+ return box(index + surd + covered, body.h + gap + rule, body.d, 'ord');
+}
+
+/** Superscripts and subscripts — beside the base, or above and below it. */
+function layoutScript(node: Extract<MathNode, { k: 'script' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const base = layout(node.base, st);
+ const sStyle = SCRIPT_OF[st.style];
+ const ss = SIZE[sStyle];
+ const sup = node.sup ? layout(node.sup, { ...st, style: sStyle }) : null;
+ const sub = node.sub ? layout(node.sub, { ...st, style: sStyle }) : null;
+ if (!sup && !sub) return base;
+
+ // ── limits: `\sum_{i=1}^{n}` in display style stacks its bounds
+ const wantsLimits = node.base.k === 'op' && node.base.limits && st.style === 'D';
+ if (wantsLimits) return stackLimits(base, sup, sub, st);
+
+ const supShift = sup
+ ? Math.max(base.h - 0.30 * ss * size, (st.style === 'D' ? 0.42 : 0.36) * size, sup.d + 0.08 * size)
+ : 0;
+ let subShift = sub
+ ? Math.max(base.d + 0.20 * ss * size, 0.22 * size, sub.h - 0.36 * size)
+ : 0;
+
+ if (sup && sub) {
+ // they must clear each other, or `x_i^j` sets as a single blur
+ const clearance = 0.16 * size;
+ const between = (supShift - sup.d) - (sub.h - subShift);
+ if (between < clearance) subShift += clearance - between;
+ const pad = (supShift + subShift) - sup.d - sub.h;
+ const html =
+ `<span class="t-mss" style="vertical-align:${emIn(-subShift, ss)};font-size:${num(ss / size)}em">` +
+ `<span class="t-msup">${sup.html || ZW}</span>` +
+ `<span class="t-msub" style="padding-top:${emIn(Math.max(0, pad), ss)}">${sub.html || ZW}</span>` +
+ `</span>`;
+ return box(base.html + html,
+ Math.max(base.h, supShift + sup.h), Math.max(base.d, subShift + sub.d), base.cls);
+ }
+ if (sup) {
+ const html = `<span class="t-msup t-mside" style="font-size:${num(ss / size)}em;` +
+ `vertical-align:${emIn(supShift, ss)}">${sup.html || ZW}</span>`;
+ return box(base.html + html, Math.max(base.h, supShift + sup.h), base.d, base.cls);
+ }
+ const html = `<span class="t-msub t-mside" style="font-size:${num(ss / size)}em;` +
+ `vertical-align:${emIn(-subShift, ss)}">${sub!.html || ZW}</span>`;
+ return box(base.html + html, base.h, Math.max(base.d, subShift + sub!.d), base.cls);
+}
+
+/** Bounds above and below a big operator. */
+function stackLimits(base: Box, sup: Box | null, sub: Box | null, st: St): Box {
+ const size = SIZE[st.style];
+ const ss = SIZE[SCRIPT_OF[st.style]];
+ const gap = 0.16 * size;
+ const rows: string[] = [];
+ if (sup) {
+ rows.push(`<span class="t-mover" style="font-size:${num(ss / size)}em;` +
+ `padding-bottom:${emIn(gap, ss)}">${sup.html || ZW}</span>`);
+ }
+ rows.push(`<span class="t-mlimb">${base.html}</span>`);
+ if (sub) {
+ rows.push(`<span class="t-munder" style="font-size:${num(ss / size)}em;` +
+ `padding-top:${emIn(gap, ss)}">${sub.html || ZW}</span>`);
+ }
+ // the inline-block's baseline is its last row's; shift so the OPERATOR's
+ // baseline is the one that lands on the line
+ const v = sub ? -(base.d + gap + sub.h) : 0;
+ const html = `<span class="t-mlim" style="vertical-align:${emIn(v, size)}">${rows.join('')}</span>`;
+ return box(html,
+ base.h + (sup ? gap + sup.h + sup.d : 0),
+ base.d + (sub ? gap + sub.h + sub.d : 0), 'op');
+}
+
+/** `\left( … \right)` — the delimiters grow with what they hold. */
+function layoutFence(node: Extract<MathNode, { k: 'fence' }>, st: St): Box {
+ return fenceAround(layout(node.body, st), node.left, node.right, st);
+}
+
+function fenceAround(body: Box, left: string, right: string, st: St): Box {
+ const size = SIZE[st.style];
+ // how far the content reaches from the axis, in each direction
+ const above = body.h - AXIS * size;
+ const below = body.d + AXIS * size;
+ const k = Math.max(1,
+ above / ((ASCENT - AXIS) * size) * 1.02,
+ below / ((DESCENT + AXIS) * size) * 1.02);
+ const scaled = Math.round(k * 1000) / 1000;
+ const delim = (ch: string): string => {
+ if (!ch) return '';
+ if (scaled <= 1.001) return `<span class="t-mdelim">${esc(ch)}</span>`;
+ return `<span class="t-mdelim" style="transform:scaleY(${num(scaled)})">${esc(ch)}</span>`;
+ };
+ const h = Math.max(body.h, AXIS * size + scaled * (ASCENT - AXIS) * size);
+ const d = Math.max(body.d, scaled * (DESCENT + AXIS) * size - AXIS * size);
+ return box(delim(left) + body.html + delim(right), h, d, 'inner');
+}
+
+/**
+ * An accent (`\hat x`, `\vec v`).
+ *
+ * The accent is ABSOLUTELY positioned over the base, so it adds no width and
+ * cannot shift the base along the line. It is excluded from the box's reported
+ * height by only a hair, which is deliberate: a hat on a tall base would
+ * otherwise open up the line above it in running prose, and TeX makes the same
+ * compromise.
+ */
+function layoutAccent(node: Extract<MathNode, { k: 'accent' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const body = layout(node.body, st);
+ const gap = 0.04 * size;
+ // where an accent glyph's ink sits above the bottom of its own line box
+ const INK = 0.77 * size;
+ const bottom = body.h + body.d + gap - INK;
+ const html = `<span class="t-macc">${body.html || ZW}` +
+ `<span class="t-maccm" style="bottom:${emIn(bottom, size)}">${esc(node.ch)}</span></span>`;
+ return box(html, body.h + gap + 0.16 * size, body.d, body.cls);
+}
+
+/** `\overline` / `\underline`. */
+function layoutBar(node: Extract<MathNode, { k: 'bar' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const body = layout(node.body, st);
+ const rule = RULE * size;
+ const gap = 0.09 * size;
+ if (node.under) {
+ const html = `<span class="t-mbar t-under" style="border-bottom-width:${emIn(rule, size)};` +
+ `padding-bottom:${emIn(gap, size)}">${body.html || ZW}</span>`;
+ return box(html, body.h, body.d + gap + rule, body.cls);
+ }
+ const html = `<span class="t-mbar t-over" style="border-top-width:${emIn(rule, size)};` +
+ `padding-top:${emIn(gap, size)}">${body.html || ZW}</span>`;
+ return box(html, body.h + gap + rule, body.d, body.cls);
+}
+
+/**
+ * A matrix, `cases`, or `aligned` — one inline-table, centred on the axis.
+ *
+ * An inline-table takes its baseline from its FIRST row, which is why the shift
+ * is computed rather than assumed: without it a three-row matrix sits with its
+ * top row on the line and the rest hanging below.
+ */
+function layoutMatrix(node: Extract<MathNode, { k: 'matrix' }>, st: St): Box {
+ const size = SIZE[st.style];
+ const cellStyle: StyleName = st.style === 'D' ? 'T' : st.style;
+ const pad = 0.16 * size;
+ const rowsHtml: string[] = [];
+ const heights: Array<{ h: number; d: number }> = [];
+ for (const row of node.rows) {
+ let h = ASCENT * SIZE[cellStyle], d = DESCENT * SIZE[cellStyle];
+ const cells: string[] = [];
+ for (const cellNode of row) {
+ const b = layout(cellNode, { ...st, style: cellStyle });
+ h = Math.max(h, b.h); d = Math.max(d, b.d);
+ cells.push(`<span class="t-mcell">${b.html || ZW}</span>`);
+ }
+ heights.push({ h, d });
+ rowsHtml.push(`<span class="t-mrow2">${cells.join('')}</span>`);
+ }
+ if (!heights.length) return box('', ASCENT * size, DESCENT * size, 'inner');
+
+ const total = heights.reduce((a, r) => a + r.h + r.d + 2 * pad, 0);
+ const firstBaseline = pad + heights[0].h;
+ const v = AXIS * size - (firstBaseline - total / 2);
+ const cls = node.align === 'l' ? ' t-mleft' : '';
+ const html = `<span class="t-mmatrix${cls}" style="vertical-align:${emIn(v, size)};` +
+ `--t-mpad:${emIn(pad, size)}">${rowsHtml.join('')}</span>`;
+ const inner = box(html, v + firstBaseline, total - firstBaseline - v, 'inner');
+ if (!node.left && !node.right) return inner;
+ return fenceAround(inner, node.left, node.right, st);
+}
+
+/**
+ * A zero-width space, and the least obvious load-bearing character in this
+ * module.
+ *
+ * PAGINATION MEASURES TEXT NODES. `paginate.ts` walks the flow with a
+ * TreeWalker over SHOW_TEXT and takes a rect per line — an element carrying no
+ * text at all is invisible to it, so a formula made only of rules and SVG (an
+ * empty `\sqrt{}` while it is being typed, `\frac{}{}` from a generator) would
+ * occupy space on screen that the page breaks do not know about, and every page
+ * after it would break in the wrong place. Every empty slot therefore gets a
+ * U+200B, which is a text node, is not whitespace to `String.trim` (so the
+ * walker accepts it), and prints nothing.
+ */
+const ZW = '​';
+
+// ────────────────────────────────────────────────────────────── entry points
+
+/** Lay out a parsed formula. Exported for the rig, which checks purity. */
+export function layoutMath(root: MathNode, opts: LayoutOpts = {}): Box {
+ return layout(root, { style: opts.display ? 'D' : 'T' });
+}
+
+export interface Rendered {
+ /** the markup, without any wrapper */
+ html: string;
+ h: number;
+ d: number;
+ /** everything the parser objected to, in source order */
+ errors: string[];
+}
+
+/** Source → markup. Pure, deterministic, and it never throws. */
+export function renderMath(src: string, opts: LayoutOpts = {}): Rendered {
+ let parsed: ParseOut;
+ try {
+ parsed = parseMath(src);
+ } catch (e) {
+ parsed = { root: { k: 'err', s: src.slice(0, 80), msg: String(e) }, errors: [String(e)] };
+ }
+ try {
+ const b = layoutMath(parsed.root, opts);
+ return { html: b.html || ZW, h: b.h, d: b.d, errors: parsed.errors };
+ } catch (e) {
+ // Same contract as the parser's: a formula is content, and no content may
+ // be able to stop the page from rendering.
+ return { html: `<span class="t-merr">${esc(src.slice(0, 120))}</span>`,
+ h: ASCENT, d: DESCENT, errors: [...parsed.errors, String(e)] };
+ }
+}
+
+export { ZW };
diff --git a/type/src/math/parse.ts b/type/src/math/parse.ts
new file mode 100644
index 00000000..cc5dcfbc
--- /dev/null
+++ b/type/src/math/parse.ts
@@ -0,0 +1,474 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// TeX-like source → a tree of math nodes.
+//
+// TOTAL, NEVER THROWING. This parser runs on every render of every block that
+// carries a formula, on text a person is in the middle of typing — so at any
+// instant the input is almost certainly malformed. A parser that threw would
+// take the whole document's render down between the `\` and the `{`, which is
+// not a hypothetical: it is what the first spike did, and it blanked the page.
+//
+// So every failure has a value: an unknown command, an unclosed brace, an
+// argument that is not there — each becomes an `err` node that renders as the
+// offending source in a warning colour, in place, with the rest of the formula
+// intact. The reader sees exactly which bit is wrong and the document survives.
+//
+// The three caps below are the other half of that promise. `\frac{\frac{...`
+// nested by a generator, or a 200KB paste into a formula, must cost bounded
+// time — a renderer is called from a layout loop and has no right to hang the
+// tab.
+
+import {
+ ACCENTS, ALPHABETS, BIG_OPS, CHAR_CLASS, DELIMS, ESCAPED, GREEK_LOWER,
+ GREEK_UPPER, INT_OPS, NAMED_OPS, SPACES, SYMBOLS, type Cls,
+} from './symbols.ts';
+
+/** Longer than any real formula; a paste of a whole document is not one. */
+export const MAX_SOURCE = 8000;
+/** Enough for a page-sized matrix; far short of anything that stalls a frame. */
+export const MAX_NODES = 6000;
+/** `\frac{\frac{\frac{…` — deeper than this is unreadable anyway. */
+export const MAX_DEPTH = 32;
+
+export type Variant = 'italic' | 'up' | 'bold' | 'bolditalic' | 'sans' | 'mono';
+export type StyleName = 'D' | 'T' | 'S' | 'SS';
+
+export type MathNode =
+ /** one symbol, already resolved to the character it prints */
+ | { k: 'atom'; ch: string; cls: Cls; variant?: Variant }
+ | { k: 'row'; body: MathNode[] }
+ /** a big operator (∑) or a named function (sin); `limits` = scripts go above/below */
+ | { k: 'op'; ch: string; cls: Cls; limits: boolean; big: boolean; name?: string }
+ | { k: 'frac'; num: MathNode; den: MathNode; bar: boolean; style?: 'D' | 'T'; left?: string; right?: string }
+ | { k: 'sqrt'; body: MathNode; index?: MathNode }
+ | { k: 'script'; base: MathNode; sup?: MathNode; sub?: MathNode }
+ | { k: 'fence'; left: string; right: string; body: MathNode }
+ | { k: 'accent'; ch: string; body: MathNode }
+ | { k: 'bar'; body: MathNode; under: boolean }
+ | { k: 'text'; s: string }
+ | { k: 'space'; em: number }
+ | { k: 'style'; style: StyleName; body: MathNode }
+ | { k: 'font'; variant?: Variant; alphabet?: string; body: MathNode }
+ | { k: 'matrix'; rows: MathNode[][]; left: string; right: string; align: 'c' | 'l' }
+ | { k: 'err'; s: string; msg: string };
+
+export interface ParseOut { root: MathNode; errors: string[] }
+
+// ───────────────────────────────────────────────────────────────── tokens
+
+type Tok =
+ | { t: 'cmd'; v: string } // \frac, \, , \\ (v excludes the backslash)
+ | { t: 'ch'; v: string }
+ | { t: 'open' } | { t: 'close' } // { }
+ | { t: 'sup' } | { t: 'sub' }
+ | { t: 'amp' } | { t: 'nl' } // & and \\
+ | { t: 'ws' } // only ever meaningful inside \text
+ | { t: 'eof' };
+
+/**
+ * Split the source into tokens.
+ *
+ * A control sequence is a backslash plus LETTERS, or a backslash plus exactly
+ * one other character (`\,` `\{` `\\`). Getting that rule wrong is how `\alpha2`
+ * becomes the undefined command `\alpha2`.
+ */
+export function lex(src: string): Tok[] {
+ const out: Tok[] = [];
+ const s = src.slice(0, MAX_SOURCE);
+ let i = 0;
+ while (i < s.length) {
+ const c = s[i];
+ if (c === '\\') {
+ const rest = s.slice(i + 1);
+ const m = /^[a-zA-Z]+/.exec(rest);
+ if (m) { out.push({ t: 'cmd', v: m[0] }); i += 1 + m[0].length; continue; }
+ const next = s[i + 1];
+ if (next === undefined) { out.push({ t: 'ch', v: '\\' }); i++; continue; }
+ if (next === '\\') { out.push({ t: 'nl' }); i += 2; continue; }
+ out.push({ t: 'cmd', v: next }); i += 2; continue;
+ }
+ if (c === '{') { out.push({ t: 'open' }); i++; continue; }
+ if (c === '}') { out.push({ t: 'close' }); i++; continue; }
+ if (c === '^') { out.push({ t: 'sup' }); i++; continue; }
+ if (c === '_') { out.push({ t: 'sub' }); i++; continue; }
+ if (c === '&') { out.push({ t: 'amp' }); i++; continue; }
+ // Whitespace is not a character in math mode — `a b` is `ab` — but it IS
+ // one inside `\text{if x}`, and the two cannot be told apart until the
+ // parser knows which it is in. So it is TOKENISED and then skipped by
+ // `peek`/`next`; only `rawGroup`, which reads the token stream directly,
+ // ever sees it. Dropping it in the lexer instead cost every `\text` its
+ // spaces, and words ran together in the middle of a sentence.
+ if (/\s/.test(c)) { out.push({ t: 'ws' }); i++; continue; }
+ out.push({ t: 'ch', v: c }); i++;
+ }
+ out.push({ t: 'eof' });
+ return out;
+}
+
+// ───────────────────────────────────────────────────────────────── parser
+
+const ROW = (body: MathNode[]): MathNode =>
+ body.length === 1 ? body[0] : { k: 'row', body };
+
+/** Environments this subset knows, and the fences each one wears. */
+const ENVS: Record<string, { left: string; right: string; align: 'c' | 'l' }> = {
+ matrix: { left: '', right: '', align: 'c' },
+ pmatrix: { left: '(', right: ')', align: 'c' },
+ bmatrix: { left: '[', right: ']', align: 'c' },
+ Bmatrix: { left: '{', right: '}', align: 'c' },
+ vmatrix: { left: '|', right: '|', align: 'c' },
+ Vmatrix: { left: '‖', right: '‖', align: 'c' },
+ cases: { left: '{', right: '', align: 'l' },
+ aligned: { left: '', right: '', align: 'l' },
+ array: { left: '', right: '', align: 'c' },
+};
+
+class Parser {
+ private toks: Tok[];
+ private i = 0;
+ private depth = 0;
+ private made = 0;
+ readonly errors: string[] = [];
+
+ constructor(src: string) { this.toks = lex(src); }
+
+ /** Step over whitespace, which is never an atom. */
+ private skipWs(): void { while (this.toks[this.i]?.t === 'ws') this.i++; }
+ private peek(): Tok { this.skipWs(); return this.toks[this.i]; }
+ private next(): Tok { this.skipWs(); return this.toks[this.i++]; }
+ private fail(s: string, msg: string): MathNode {
+ if (this.errors.length < 20) this.errors.push(`${msg}: ${s}`);
+ return { k: 'err', s, msg };
+ }
+
+ /** The budget check every node creation goes through. */
+ private budget(): boolean {
+ return ++this.made <= MAX_NODES;
+ }
+
+ parse(): MathNode {
+ const body = this.list(t => t.t === 'eof');
+ if (this.peek().t !== 'eof') {
+ // a stray `}` (or worse) left the list early — consume the rest so the
+ // reader sees it rather than losing it silently
+ while (this.peek().t !== 'eof') {
+ const t = this.next();
+ if (t.t === 'close') body.push(this.fail('}', 'unmatched brace'));
+ }
+ }
+ return ROW(body);
+ }
+
+ /** Atoms until `stop` (not consumed) or the end of the input. */
+ private list(stop: (t: Tok) => boolean): MathNode[] {
+ const out: MathNode[] = [];
+ if (++this.depth > MAX_DEPTH) {
+ this.depth--;
+ return [this.fail('…', 'nested too deeply')];
+ }
+ for (;;) {
+ const t = this.peek();
+ if (t.t === 'eof' || stop(t)) break;
+ if (!this.budget()) { out.push(this.fail('…', 'formula too large')); break; }
+ const node = this.atom();
+ if (node) out.push(this.scripts(node));
+ }
+ this.depth--;
+ return out;
+ }
+
+ /**
+ * Attach `^` and `_` to the atom just parsed.
+ *
+ * Both orders (`x^2_i` and `x_i^2`) mean the same thing and both occur in
+ * real sources, so this loops rather than expecting one shape. A second
+ * superscript on the same base is TeX's "double superscript" error; here the
+ * later one wins and the reader is told, because refusing to render is worse
+ * than rendering the likely intent.
+ */
+ private scripts(base: MathNode): MathNode {
+ let sup: MathNode | undefined;
+ let sub: MathNode | undefined;
+ let any = false;
+ for (;;) {
+ const t = this.peek();
+ // a prime is a superscript written differently
+ if (t.t === 'ch' && t.v === "'") {
+ this.next();
+ let ch = '′';
+ while (this.peek().t === 'ch' && (this.peek() as { v: string }).v === "'") { this.next(); ch += '′'; }
+ sup = sup ? ROW([sup, { k: 'atom', ch, cls: 'ord' }]) : { k: 'atom', ch, cls: 'ord' };
+ any = true;
+ continue;
+ }
+ if (t.t !== 'sup' && t.t !== 'sub') break;
+ this.next();
+ const arg = this.arg();
+ if (t.t === 'sup') {
+ if (sup) this.errors.push('two superscripts on one base');
+ sup = arg;
+ } else {
+ if (sub) this.errors.push('two subscripts on one base');
+ sub = arg;
+ }
+ any = true;
+ }
+ if (!any) return base;
+ return { k: 'script', base, sup, sub };
+ }
+
+ /**
+ * One argument: a braced group, or the single next atom.
+ *
+ * `\frac12` really is one half in TeX and generators emit it, so the
+ * single-token form is not an indulgence.
+ */
+ private arg(): MathNode {
+ const t = this.peek();
+ if (t.t === 'open') {
+ this.next();
+ const body = this.list(x => x.t === 'close');
+ if (this.peek().t === 'close') this.next();
+ else this.errors.push('missing }');
+ return ROW(body);
+ }
+ if (t.t === 'eof' || t.t === 'close') return this.fail('', 'missing argument');
+ const node = this.atom();
+ return node ?? this.fail('', 'missing argument');
+ }
+
+ /** An optional `[...]` argument, for `\sqrt[3]{x}`. */
+ private optArg(): MathNode | undefined {
+ const t = this.peek();
+ if (t.t !== 'ch' || t.v !== '[') return undefined;
+ this.next();
+ const body = this.list(x => x.t === 'ch' && x.v === ']');
+ if (this.peek().t === 'ch') this.next();
+ return ROW(body);
+ }
+
+ /** The text of a braced group, verbatim — for `\text{…}` and `\begin{…}`. */
+ private rawGroup(): string {
+ if (this.peek().t !== 'open') {
+ const t = this.next();
+ return t.t === 'ch' || t.t === 'cmd' ? t.v : '';
+ }
+ this.next();
+ let out = '';
+ let depth = 1;
+ for (;;) {
+ // raw: this is the one reader that must NOT skip whitespace
+ const t = this.toks[this.i++] ?? { t: 'eof' as const };
+ if (t.t === 'eof') { this.errors.push('missing }'); break; }
+ if (t.t === 'open') { depth++; out += '{'; continue; }
+ if (t.t === 'close') { if (--depth === 0) break; out += '}'; continue; }
+ out += t.t === 'cmd' ? `\\${t.v}` : t.t === 'ch' ? t.v
+ : t.t === 'ws' ? ' ' : t.t === 'sup' ? '^' : t.t === 'sub' ? '_'
+ : t.t === 'amp' ? '&' : t.t === 'nl' ? ' ' : '';
+ }
+ return out;
+ }
+
+ private atom(): MathNode | null {
+ const t = this.next();
+ switch (t.t) {
+ case 'open': {
+ const body = this.list(x => x.t === 'close');
+ if (this.peek().t === 'close') this.next(); else this.errors.push('missing }');
+ return ROW(body);
+ }
+ case 'close': return this.fail('}', 'unmatched brace');
+ case 'ws': return null; // skipped everywhere but \text
+ case 'nl': case 'amp': return null; // only meaningful in a matrix
+ case 'sup': case 'sub': {
+ // a script with nothing before it: TeX errors, we render an empty base
+ this.i--;
+ return this.scripts({ k: 'row', body: [] });
+ }
+ case 'ch': return this.charAtom(t.v);
+ case 'cmd': return this.command(t.v);
+ default: return null;
+ }
+ }
+
+ private charAtom(c: string): MathNode {
+ const known = CHAR_CLASS[c];
+ if (known) return { k: 'atom', ch: known.ch, cls: known.cls };
+ if (c >= '0' && c <= '9') return { k: 'atom', ch: c, cls: 'ord', variant: 'up' };
+ if (/[a-zA-Z]/.test(c)) return { k: 'atom', ch: c, cls: 'ord', variant: 'italic' };
+ return { k: 'atom', ch: c, cls: 'ord' };
+ }
+
+ private delim(): string {
+ const t = this.next();
+ if (t.t === 'ch') {
+ const d = DELIMS[t.v];
+ if (d !== undefined) return d;
+ this.errors.push(`not a delimiter: ${t.v}`);
+ return '';
+ }
+ if (t.t === 'cmd') {
+ const d = DELIMS[`\\${t.v}`];
+ if (d !== undefined) return d;
+ this.errors.push(`not a delimiter: \\${t.v}`);
+ return '';
+ }
+ if (t.t === 'open') return '{';
+ if (t.t === 'close') return '}';
+ this.errors.push('missing delimiter');
+ return '';
+ }
+
+ private command(name: string): MathNode {
+ // ── fractions
+ if (name === 'frac' || name === 'dfrac' || name === 'tfrac' || name === 'cfrac') {
+ const num = this.arg(), den = this.arg();
+ return { k: 'frac', num, den, bar: true,
+ ...(name === 'dfrac' || name === 'cfrac' ? { style: 'D' as const }
+ : name === 'tfrac' ? { style: 'T' as const } : {}) };
+ }
+ if (name === 'binom' || name === 'choose') {
+ const num = this.arg(), den = this.arg();
+ return { k: 'frac', num, den, bar: false, left: '(', right: ')' };
+ }
+ if (name === 'sqrt') {
+ const index = this.optArg();
+ const body = this.arg();
+ return index ? { k: 'sqrt', body, index } : { k: 'sqrt', body };
+ }
+ if (name === 'overline') return { k: 'bar', body: this.arg(), under: false };
+ if (name === 'underline') return { k: 'bar', body: this.arg(), under: true };
+
+ // ── fences
+ if (name === 'left') {
+ const left = this.delim();
+ const body = ROW(this.list(x => x.t === 'cmd' && (x.v === 'right' || x.v === 'end')));
+ const t = this.peek();
+ if (t.t === 'cmd' && t.v === 'right') { this.next(); return { k: 'fence', left, right: this.delim(), body }; }
+ // An unclosed `\left` is the commonest half-typed state there is, so it
+ // degrades to a one-sided fence rather than to an error node — the
+ // formula keeps rendering while the author types the other half.
+ this.errors.push('\\left with no \\right');
+ return { k: 'fence', left, right: '', body };
+ }
+ if (name === 'right') return this.fail('\\right', 'no \\left for this');
+ if (name === 'big' || name === 'Big' || name === 'bigg' || name === 'Bigg'
+ || name === 'bigl' || name === 'bigr' || name === 'Bigl' || name === 'Bigr') {
+ // sized delimiters are accepted and set at their natural size: the shape
+ // is right, only the emphasis is lost
+ return { k: 'atom', ch: this.delim(), cls: name.endsWith('r') ? 'close' : 'open' };
+ }
+
+ // ── environments
+ if (name === 'begin') return this.env();
+ if (name === 'end') { this.rawGroup(); return this.fail('\\end', 'no \\begin for this'); }
+
+ // ── text and fonts
+ if (name === 'text' || name === 'textrm' || name === 'mbox' || name === 'textnormal') {
+ return { k: 'text', s: this.rawGroup() };
+ }
+ if (ALPHABETS[name]) return { k: 'font', alphabet: name, body: this.arg() };
+ const FONTS: Record<string, Variant> = {
+ mathrm: 'up', operatorname: 'up', mathbf: 'bold', boldsymbol: 'bolditalic',
+ mathit: 'italic', mathsf: 'sans', mathtt: 'mono',
+ };
+ if (FONTS[name]) return { k: 'font', variant: FONTS[name], body: this.arg() };
+
+ // ── style
+ const STYLES: Record<string, StyleName> = {
+ displaystyle: 'D', textstyle: 'T', scriptstyle: 'S', scriptscriptstyle: 'SS',
+ };
+ if (STYLES[name]) {
+ // a style command applies to the rest of its group, which is why it takes
+ // no argument and swallows what follows
+ const body = ROW(this.list(x => x.t === 'close' || x.t === 'eof'));
+ return { k: 'style', style: STYLES[name], body };
+ }
+
+ // ── accents
+ if (ACCENTS[name]) return { k: 'accent', ch: ACCENTS[name], body: this.arg() };
+
+ // ── spacing
+ if (SPACES[name] !== undefined) return { k: 'space', em: SPACES[name] };
+
+ // ── operators
+ if (BIG_OPS[name]) return { k: 'op', ch: BIG_OPS[name], cls: 'op', limits: true, big: true };
+ if (INT_OPS[name]) return { k: 'op', ch: INT_OPS[name], cls: 'op', limits: false, big: true };
+ if (NAMED_OPS[name] !== undefined) {
+ return { k: 'op', ch: name, cls: 'op', limits: NAMED_OPS[name], big: false, name };
+ }
+ if (name === 'limits' || name === 'nolimits' || name === 'mathop') {
+ // accepted and ignored: the default this renderer picks is the one TeX
+ // would pick in the overwhelming majority of sources
+ return { k: 'row', body: [] };
+ }
+
+ // ── letters and plain symbols
+ if (GREEK_LOWER[name]) return { k: 'atom', ch: GREEK_LOWER[name], cls: 'ord', variant: 'italic' };
+ if (GREEK_UPPER[name]) return { k: 'atom', ch: GREEK_UPPER[name], cls: 'ord', variant: 'up' };
+ const sym = SYMBOLS[name] ?? ESCAPED[name];
+ if (sym) return { k: 'atom', ch: sym.ch, cls: sym.cls };
+
+ return this.fail(`\\${name}`, 'unknown command');
+ }
+
+ /** `\begin{env} … \\ … & … \end{env}` */
+ private env(): MathNode {
+ const name = this.rawGroup();
+ const spec = ENVS[name];
+ if (!spec) {
+ // Skip to the matching \end so the REST of the formula still renders.
+ // Bailing here instead would turn one unsupported environment into a
+ // document with everything after it missing.
+ for (;;) {
+ const t = this.next();
+ if (t.t === 'eof') break;
+ if (t.t === 'cmd' && t.v === 'end') { this.rawGroup(); break; }
+ }
+ return this.fail(`\\begin{${name}}`, 'unsupported environment');
+ }
+ if (name === 'array') this.rawGroupIfBrace();
+ const rows: MathNode[][] = [];
+ let row: MathNode[] = [];
+ let cell: MathNode[] = [];
+ const endCell = () => { row.push(ROW(cell)); cell = []; };
+ const endRow = () => { endCell(); rows.push(row); row = []; };
+ for (;;) {
+ const t = this.peek();
+ if (t.t === 'eof') { this.errors.push(`missing \\end{${name}}`); break; }
+ if (t.t === 'cmd' && t.v === 'end') { this.next(); this.rawGroup(); break; }
+ if (t.t === 'amp') { this.next(); endCell(); continue; }
+ if (t.t === 'nl') { this.next(); endRow(); continue; }
+ if (!this.budget()) { cell.push(this.fail('…', 'formula too large')); break; }
+ const node = this.atom();
+ if (node) cell.push(this.scripts(node));
+ }
+ // a trailing `\\` means "end of the last row", not "one more empty row"
+ if (cell.length || row.length) endRow();
+ return { k: 'matrix', rows, left: spec.left, right: spec.right, align: spec.align };
+ }
+
+ /** `\begin{array}{cc}` — the column spec is accepted and not honoured. */
+ private rawGroupIfBrace(): void {
+ if (this.peek().t === 'open') this.rawGroup();
+ }
+}
+
+/**
+ * Parse a formula. Never throws; the errors are also embedded in the tree so
+ * they render in place.
+ */
+export function parseMath(src: string): ParseOut {
+ const p = new Parser(typeof src === 'string' ? src : '');
+ let root: MathNode;
+ try {
+ root = p.parse();
+ } catch (e) {
+ // The belt to the parser's braces. Nothing here is expected to throw, and
+ // if a future edit makes something throw, a formula must still not be able
+ // to take a page down.
+ root = { k: 'err', s: src.slice(0, 80), msg: (e as Error).message || 'could not read this formula' };
+ }
+ return { root, errors: p.errors };
+}
diff --git a/type/src/math/symbols.ts b/type/src/math/symbols.ts
new file mode 100644
index 00000000..61f9ee23
--- /dev/null
+++ b/type/src/math/symbols.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The symbol tables: what a control sequence means, and what CLASS it is.
+//
+// The class is not decoration — it is the whole of TeX's horizontal spacing
+// model. `a+b` sets wider than `ab` because `+` is a Bin, and `a=b` wider still
+// because `=` is a Rel. Getting the class right is most of what makes a formula
+// look like mathematics rather than like a string of characters, and it costs a
+// table rather than an algorithm.
+//
+// One table, one entry per command, no aliases resolved at runtime: the parser
+// looks a command up once and never branches on its name. Anything not in here
+// is an unknown command, which is a rendering ERROR the reader can see and not
+// an exception that takes the document down.
+
+/** TeX's atom classes, minus Vcent and Rad which this subset does not expose. */
+export type Cls = 'ord' | 'op' | 'bin' | 'rel' | 'open' | 'close' | 'punct' | 'inner';
+
+export interface Sym { ch: string; cls: Cls }
+
+const S = (ch: string, cls: Cls = 'ord'): Sym => ({ ch, cls });
+
+/**
+ * Greek. Lowercase is ITALIC and uppercase is UPRIGHT, which is the TeX
+ * convention and the one every physics and maths paper follows; rendering
+ * `\Omega` in italic makes a document look subtly foreign to the people who
+ * read these most.
+ */
+export const GREEK_LOWER: Record<string, string> = {
+ alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', epsilon: 'ϵ', varepsilon: 'ε',
+ zeta: 'ζ', eta: 'η', theta: 'θ', vartheta: 'ϑ', iota: 'ι', kappa: 'κ',
+ lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', omicron: 'ο', pi: 'π', varpi: 'ϖ',
+ rho: 'ρ', varrho: 'ϱ', sigma: 'σ', varsigma: 'ς', tau: 'τ', upsilon: 'υ',
+ phi: 'ϕ', varphi: 'φ', chi: 'χ', psi: 'ψ', omega: 'ω',
+};
+export const GREEK_UPPER: Record<string, string> = {
+ Gamma: 'Γ', Delta: 'Δ', Theta: 'Θ', Lambda: 'Λ', Xi: 'Ξ', Pi: 'Π',
+ Sigma: 'Σ', Upsilon: 'Υ', Phi: 'Φ', Psi: 'Ψ', Omega: 'Ω',
+};
+
+/** Named operators that take LIMITS above and below in display style. */
+export const BIG_OPS: Record<string, string> = {
+ sum: '∑', prod: '∏', coprod: '∐',
+ bigcup: '⋃', bigcap: '⋂', bigvee: '⋁', bigwedge: '⋀',
+ bigoplus: '⨁', bigotimes: '⨂', bigodot: '⨀', bigsqcup: '⨆', biguplus: '⨄',
+};
+
+/**
+ * Integrals. Separate from BIG_OPS because their scripts stay at the SIDE even
+ * in display style — `\int_0^1` sets its bounds beside the sign, `\sum_0^1`
+ * sets them above and below. TeX makes the same split (\intop vs \sum) and a
+ * renderer that treats them alike gets every integral in the document wrong.
+ */
+export const INT_OPS: Record<string, string> = {
+ int: '∫', iint: '∬', iiint: '∭', oint: '∮', oiint: '∯',
+};
+
+/**
+ * Function names: upright, and set as a single unit. `\sin x` must not be four
+ * italic variables multiplied together, which is what it looks like without
+ * this list.
+ *
+ * The `true` ones take limits below in display style (`\lim_{x\to0}`).
+ */
+export const NAMED_OPS: Record<string, boolean> = {
+ sin: false, cos: false, tan: false, cot: false, sec: false, csc: false,
+ arcsin: false, arccos: false, arctan: false, sinh: false, cosh: false,
+ tanh: false, coth: false, log: false, ln: false, lg: false, exp: false,
+ det: false, dim: false, deg: false, arg: false, ker: false, hom: false,
+ Pr: false, gcd: true, lim: true, limsup: true, liminf: true,
+ max: true, min: true, sup: true, inf: true,
+};
+
+/** Everything else, by control-sequence name. */
+export const SYMBOLS: Record<string, Sym> = {
+ // ── binary operators
+ times: S('×', 'bin'), div: S('÷', 'bin'), pm: S('±', 'bin'), mp: S('∓', 'bin'),
+ cdot: S('⋅', 'bin'), ast: S('∗', 'bin'), star: S('⋆', 'bin'), circ: S('∘', 'bin'),
+ bullet: S('∙', 'bin'), oplus: S('⊕', 'bin'), ominus: S('⊖', 'bin'),
+ otimes: S('⊗', 'bin'), oslash: S('⊘', 'bin'), odot: S('⊙', 'bin'),
+ cup: S('∪', 'bin'), cap: S('∩', 'bin'), setminus: S('∖', 'bin'),
+ wedge: S('∧', 'bin'), vee: S('∨', 'bin'), land: S('∧', 'bin'), lor: S('∨', 'bin'),
+ sqcup: S('⊔', 'bin'), sqcap: S('⊓', 'bin'), uplus: S('⊎', 'bin'),
+ triangleleft: S('◃', 'bin'), triangleright: S('▹', 'bin'),
+
+ // ── relations
+ le: S('≤', 'rel'), leq: S('≤', 'rel'), ge: S('≥', 'rel'), geq: S('≥', 'rel'),
+ ne: S('≠', 'rel'), neq: S('≠', 'rel'), equiv: S('≡', 'rel'),
+ approx: S('≈', 'rel'), cong: S('≅', 'rel'), sim: S('∼', 'rel'), simeq: S('≃', 'rel'),
+ propto: S('∝', 'rel'), ll: S('≪', 'rel'), gg: S('≫', 'rel'),
+ subset: S('⊂', 'rel'), subseteq: S('⊆', 'rel'), supset: S('⊃', 'rel'),
+ supseteq: S('⊇', 'rel'), sqsubseteq: S('⊑', 'rel'), sqsupseteq: S('⊒', 'rel'),
+ in: S('∈', 'rel'), notin: S('∉', 'rel'), ni: S('∋', 'rel'),
+ mid: S('∣', 'rel'), nmid: S('∤', 'rel'), perp: S('⊥', 'rel'),
+ parallel: S('∥', 'rel'), asymp: S('≍', 'rel'), doteq: S('≐', 'rel'),
+ models: S('⊨', 'rel'), vdash: S('⊢', 'rel'), dashv: S('⊣', 'rel'),
+ prec: S('≺', 'rel'), succ: S('≻', 'rel'), preceq: S('⪯', 'rel'), succeq: S('⪰', 'rel'),
+
+ // ── arrows (relations, for spacing)
+ to: S('→', 'rel'), rightarrow: S('→', 'rel'), leftarrow: S('←', 'rel'),
+ gets: S('←', 'rel'), leftrightarrow: S('↔', 'rel'),
+ Rightarrow: S('⇒', 'rel'), Leftarrow: S('⇐', 'rel'), Leftrightarrow: S('⇔', 'rel'),
+ implies: S('⟹', 'rel'), impliedby: S('⟸', 'rel'), iff: S('⟺', 'rel'),
+ mapsto: S('↦', 'rel'), hookrightarrow: S('↪', 'rel'),
+ uparrow: S('↑', 'rel'), downarrow: S('↓', 'rel'),
+ nearrow: S('↗', 'rel'), searrow: S('↘', 'rel'),
+
+ // ── ordinary symbols
+ infty: S('∞'), partial: S('∂'), nabla: S('∇'), forall: S('∀'), exists: S('∃'),
+ nexists: S('∄'), neg: S('¬'), lnot: S('¬'), emptyset: S('∅'), varnothing: S('∅'),
+ aleph: S('ℵ'), hbar: S('ℏ'), ell: S('ℓ'), imath: S('ı'), jmath: S('ȷ'),
+ Re: S('ℜ'), Im: S('ℑ'), wp: S('℘'), prime: S('′'), degree: S('°'),
+ angle: S('∠'), triangle: S('△'), square: S('□'), surd: S('√'),
+ top: S('⊤'), bot: S('⊥'), flat: S('♭'), sharp: S('♯'), natural: S('♮'),
+ clubsuit: S('♣'), diamondsuit: S('♢'), heartsuit: S('♡'), spadesuit: S('♠'),
+ checkmark: S('✓'), dagger: S('†'), ddagger: S('‡'),
+ ldots: S('…'), dots: S('…'), cdots: S('⋯'), vdots: S('⋮'), ddots: S('⋱'),
+ therefore: S('∴'), because: S('∵'),
+
+ // ── punctuation and fences
+ colon: S(':', 'punct'),
+ langle: S('⟨', 'open'), rangle: S('⟩', 'close'),
+ lceil: S('⌈', 'open'), rceil: S('⌉', 'close'),
+ lfloor: S('⌊', 'open'), rfloor: S('⌋', 'close'),
+ lbrace: S('{', 'open'), rbrace: S('}', 'close'),
+ lbrack: S('[', 'open'), rbrack: S(']', 'close'),
+ vert: S('|', 'ord'), Vert: S('‖', 'ord'),
+};
+
+/**
+ * Escaped literals: `\{` is a brace, not the start of a group.
+ *
+ * `\\` is NOT here — it is a row break inside an environment and the parser
+ * intercepts it before this table is consulted.
+ */
+export const ESCAPED: Record<string, Sym> = {
+ '{': S('{', 'open'), '}': S('}', 'close'),
+ '%': S('%'), '$': S('$'), '&': S('&'), '#': S('#'), '_': S('_'),
+ '|': S('‖', 'ord'),
+};
+
+/** Single characters that are not letters or digits. */
+export const CHAR_CLASS: Record<string, Sym> = {
+ '+': S('+', 'bin'), '-': S('−', 'bin'), '*': S('∗', 'bin'), '/': S('/', 'ord'),
+ '=': S('=', 'rel'), '<': S('<', 'rel'), '>': S('>', 'rel'),
+ ',': S(',', 'punct'), ';': S(';', 'punct'), ':': S(':', 'rel'),
+ '(': S('(', 'open'), '[': S('[', 'open'),
+ ')': S(')', 'close'), ']': S(']', 'close'),
+ '|': S('|', 'ord'), '!': S('!', 'close'), '?': S('?', 'ord'),
+ '.': S('.', 'ord'), '"': S('”', 'ord'),
+};
+
+/**
+ * Delimiters `\left` and `\right` will stretch, with the fraction of the box
+ * that lies ABOVE the glyph's own centre. `.` is the null delimiter — TeX's way
+ * of saying "one side only", and dropping it would make `\left. x \right|`
+ * (a very common evaluation bar) unwritable.
+ */
+export const DELIMS: Record<string, string> = {
+ '(': '(', ')': ')', '[': '[', ']': ']', '|': '|', '/': '/',
+ '.': '', '\\{': '{', '\\}': '}', '\\|': '‖',
+ '\\langle': '⟨', '\\rangle': '⟩',
+ '\\lceil': '⌈', '\\rceil': '⌉', '\\lfloor': '⌊', '\\rfloor': '⌋',
+ '\\lbrace': '{', '\\rbrace': '}', '\\vert': '|', '\\Vert': '‖',
+ '\\uparrow': '↑', '\\downarrow': '↓',
+};
+
+/** Accents, and the glyph each one draws over its base. */
+export const ACCENTS: Record<string, string> = {
+ hat: 'ˆ', widehat: 'ˆ', check: 'ˇ', tilde: '˜', widetilde: '˜',
+ acute: '´', grave: '`', dot: '˙', ddot: '¨', breve: '˘', bar: 'ˉ',
+ vec: '⇀', mathring: '˚',
+};
+
+/** Explicit spaces, in em. */
+export const SPACES: Record<string, number> = {
+ ',': 3 / 18, ':': 4 / 18, ';': 5 / 18, '!': -3 / 18,
+ ' ': 6 / 18, quad: 1, qquad: 2, enspace: 0.5, thinspace: 3 / 18,
+};
+
+/** `\mathbb{R}` and friends. Mapped to real Unicode, because there is no font. */
+const BB: Record<string, string> = {
+ A: '𝔸', B: '𝔹', C: 'ℂ', D: '𝔻', E: '𝔼', F: '𝔽', G: '𝔾', H: 'ℍ', I: '𝕀',
+ J: '𝕁', K: '𝕂', L: '𝕃', M: '𝕄', N: 'ℕ', O: '𝕆', P: 'ℙ', Q: 'ℚ', R: 'ℝ',
+ S: '𝕊', T: '𝕋', U: '𝕌', V: '𝕍', W: '𝕎', X: '𝕏', Y: '𝕐', Z: 'ℤ',
+};
+const CAL: Record<string, string> = {
+ A: '𝒜', B: 'ℬ', C: '𝒞', D: '𝒟', E: 'ℰ', F: 'ℱ', G: '𝒢', H: 'ℋ', I: 'ℐ',
+ J: '𝒥', K: '𝒦', L: 'ℒ', M: 'ℳ', N: '𝒩', O: '𝒪', P: '𝒫', Q: '𝒬', R: 'ℛ',
+ S: '𝒮', T: '𝒯', U: '𝒰', V: '𝒱', W: '𝒲', X: '𝒳', Y: '𝒴', Z: '𝒵',
+};
+const FRAK: Record<string, string> = {
+ A: '𝔄', B: '𝔅', C: 'ℭ', D: '𝔇', E: '𝔈', F: '𝔉', G: '𝔊', H: 'ℌ', I: 'ℑ',
+ J: '𝔍', K: '𝔎', L: '𝔏', M: '𝔐', N: '𝔑', O: '𝔒', P: '𝔓', Q: '𝔔', R: 'ℜ',
+ S: '𝔖', T: '𝔗', U: '𝔘', V: '𝔙', W: '𝔚', X: '𝔛', Y: '𝔜', Z: 'ℨ',
+};
+
+/**
+ * The alphabet a `\mathbb`-style command maps a letter through.
+ *
+ * These are TRANSLITERATIONS, not fonts: a self-contained document cannot ship
+ * a maths font, so `\mathbb{R}` becomes U+211D and takes whatever the reader's
+ * system has. A letter with no double-struck codepoint is left alone rather
+ * than replaced with a box.
+ */
+export const ALPHABETS: Record<string, Record<string, string>> = {
+ mathbb: BB, mathcal: CAL, mathfrak: FRAK,
+};
diff --git a/type/src/model.ts b/type/src/model.ts
index c36b5b4e..7b10bce7 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -12,16 +12,125 @@
// the container.
import { normalize, shift as shiftMarks, type Mark } from './inline.ts';
+// value import is safe: xref.ts imports only TYPES from this module, precisely
+// so the core can call into it without a cycle
+import { shiftRefs } from './xref.ts';
+import { readThreadsRaw, reconcileThreads } from './comments.ts';
export const FORMAT = 'bento/type';
export const VERSION = 1;
/** The kinds of block a document is made of. */
-export type BlockKind = 'para' | 'h1' | 'h2' | 'h3' | 'quote';
+export type BlockKind = 'para' | 'h1' | 'h2' | 'h3' | 'quote' | 'ul' | 'ol' | 'cell' | 'image' | 'caption' | 'toc' | 'math' | 'embed';
+
+/**
+ * Where a table cell sits. Carried on EVERY cell of the table, not on a table
+ * block — because there is no table block.
+ *
+ * A CELL IS A BLOCK, for the same reason a list item is one, and here the
+ * reason is sharper: the redline aligns on block ids, so per-cell blocks give
+ * per-cell review. A table as a single block would report "the payment table
+ * changed" when one figure moved — which is precisely the failure that makes
+ * line diffs useless on prose, and the limitation bento/slides documents for
+ * its own tables. For an app whose differentiator is redlining contracts, that
+ * is the wrong trade.
+ *
+ * `cols` is repeated on every cell rather than stored once. It is redundant and
+ * that is the point: there is no header block to lose, so a grid can always be
+ * rebuilt from any run of cells, and a file that disagrees with itself is
+ * repaired to the majority rather than being unreadable.
+ */
+export interface CellRef {
+ /** which table this cell belongs to — consecutive cells sharing it group */
+ table: string;
+ /** the table's column count */
+ cols: number;
+ /** cells of the first row, rendered as <th> */
+ head?: boolean;
+}
+
+/**
+ * A picture in the document.
+ *
+ * `src` is a data: URI (embedded, so the file stays self-contained) or an
+ * external URL (referenced, so the file stays small). Embedding is the default
+ * because the whole promise is that one file IS the document — a reference that
+ * breaks when the document is emailed is a worse failure than a large file.
+ *
+ * `w` is a fraction of the text measure (0–1), not pixels: the page size is a
+ * document property that can change, and an image sized in pixels would stop
+ * fitting the moment somebody switched to A4.
+ */
+export interface ImageRef {
+ src: string;
+ alt?: string;
+ /** width as a fraction of the text column, default 1 */
+ w?: number;
+ align?: 'left' | 'center' | 'right';
+}
+
+/**
+ * A caption, and what it captions.
+ *
+ * A BLOCK, not a field on the table — because there IS no table block to hang
+ * one on (a table is a run of `cell` blocks sharing an id), and a caption needs
+ * its own stable id anyway: that id is what a reference points at, and what the
+ * redline aligns on so an edited caption reports as an edited caption.
+ */
+export interface CaptionRef { kind: 'table' | 'figure'; of?: string }
+
+/**
+ * A citation: an atom at an offset, like a footnote anchor.
+ *
+ * `keys` is a LIST because "(Knuth 1984; Lamport 1994)" is one citation at one
+ * position, not two adjacent ones.
+ */
+export interface CiteRef { at: number; keys: string[]; locator?: string; suppressAuthor?: boolean }
+
+/** A cross-reference: an atom at an offset, exactly like a footnote anchor. */
+export interface XrefRef { to: string; at: number; style?: 'label' | 'page' | 'both' }
+
+/** Above this an embedded image is refused, and a URL offered instead. */
+export const IMAGE_EMBED_BUDGET = 4 * 1024 * 1024;
+
+/**
+ * Sources an image may have.
+ *
+ * A document is UNTRUSTED INPUT (docs/DECISIONS.md), and `src` goes straight
+ * into an <img>. `javascript:` is the obvious attack and is not the only one —
+ * anything that is not plainly an image reference is refused rather than
+ * guessed at.
+ */
+export const SAFE_IMG = /^(data:image\/(png|jpe?g|gif|webp|avif|svg\+xml)[;,]|https?:\/\/|\.{0,2}\/)/i;
+
+/** The list kinds, which are the ones that carry `level` and group when rendered. */
+export const LIST_KINDS: ReadonlySet<BlockKind> = new Set<BlockKind>(['ul', 'ol']);
+export const isList = (k: BlockKind): boolean => LIST_KINDS.has(k);
+
+/** How deep a list item may be nested. Beyond this the indents stop reading as
+ * structure and start reading as a mistake. */
+export const MAX_LIST_LEVEL = 5;
+
+/** Columns beyond this stop being a table and start being a spreadsheet. */
+export const MAX_TABLE_COLS = 20;
/** A footnote reference anchored INTO a block's text, by character offset. */
export interface NoteRef { id: string; at: number }
+/**
+ * A review comment: a thread anchored to a RANGE of a block's text.
+ *
+ * Doc-level and keyed by id, like `footnotes`, because a thread must be able to
+ * outlive the block it points at — the conversation about a deleted clause is
+ * exactly the conversation you still need.
+ */
+export interface CommentMsg { id: string; author: string; at: string; text: string }
+export interface CommentThread {
+ id: string; block: string; from: number; to: number;
+ quote: string; messages: CommentMsg[];
+ resolved?: boolean; orphan?: boolean;
+}
+
export interface Block {
/** stable identity: the redline aligns on it, so it must never be re-minted
* for a block the author considers the same paragraph */
@@ -35,12 +144,64 @@ export interface Block {
notes?: NoteRef[];
/** authoring role, for restyling and for a table of contents */
role?: string;
+ /**
+ * Nesting depth for a list item, 0-based. Absent means 0, and it means
+ * nothing on a block that is not a list.
+ *
+ * A LIST ITEM IS A BLOCK, and the list itself is not in the model at all —
+ * runs of adjacent `ul`/`ol` blocks are grouped into real <ul>/<ol> elements
+ * at RENDER time. That keeps the document flat, which is not a stylistic
+ * preference: the redline aligns on block ids, the caret is (blockId,
+ * offset), and pagination measures line boxes through a tree walker. A
+ * nested list model would have put a tree under all three, and each of them
+ * is correct today because there is no tree.
+ */
+ level?: number;
+ /** table placement; only meaningful on a `cell` block */
+ cell?: CellRef;
+ /** the picture; only meaningful on an `image` block */
+ image?: ImageRef;
+ /** caption placement; only meaningful on a `caption` block */
+ caption?: CaptionRef;
+ /** cross-references, by offset into `text` — atoms, like `notes` */
+ refs?: XrefRef[];
+ /** citations, by offset into `text` — atoms, like `notes` */
+ cites?: CiteRef[];
+
+ /**
+ * A named style this block carries BY REFERENCE — see docstyles.ts.
+ *
+ * Absent means "whatever `kind` implies by default", which is itself a named
+ * style (docstyles.ts's built-ins, keyed by kind) rather than special-cased —
+ * so editing "Heading 1" restyles every h1 that never set this field, which
+ * is the whole point of a styles system. A block that sets `styleId` opts
+ * INTO a different named look than its kind's default; it does not opt out
+ * of styling altogether.
+ */
+ styleId?: string;
+
+ // ---- paragraph layout. ABSENT MEANS "the document's default", never a
+ // value: a paragraph with no `align` is justified because the DOCUMENT says
+ // so, and setting the current default deletes the field rather than writing
+ // it. That is what keeps a restyled document from carrying ten thousand
+ // copies of its own defaults.
+ align?: 'left' | 'center' | 'right' | 'justify';
+ /** space before, px */ sb?: number;
+ /** space after, px */ sa?: number;
+ /** line spacing, a multiple of the font size */ lh?: number;
+ /** first-line indent, px */ ind?: number;
+ keepNext?: true; keepTogether?: true; breakBefore?: true;
+
+ /** Unknown fields ride through untouched — format additivity, PLATFORM §3. */
+ [extra: string]: unknown;
}
/** Page geometry, in CSS px at 96dpi. US Letter by default. */
export interface PageSpec {
width: number; height: number;
marginX: number; marginTop: number; marginBottom: number;
+ /** absent means `marginX`, so a symmetric page keeps writing one field */
+ marginLeft?: number; marginRight?: number;
}
export const LETTER: PageSpec = {
width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104,
@@ -67,6 +228,38 @@ export interface Revision {
body: Block[];
}
+/**
+ * A named paragraph style — what Word calls "Heading 1": a bundle of
+ * typography a block can carry BY REFERENCE (`Block.styleId`) instead of by
+ * repeating every property on itself. See docstyles.ts for resolution
+ * (built-ins, kind defaults, the panel that edits these) and render.ts /
+ * print.ts for where the bundle becomes CSS.
+ *
+ * `align`/`sb`/`sa`/`lh`/`ind` are the SAME vocabulary `Block` already has —
+ * a style is those five properties stored once and shared, not a parallel
+ * dialect. `family`/`size`/`weight`/`italic`/`color` are new: nothing before
+ * this let a document say what a heading looks like at all.
+ */
+export interface DocStyle {
+ id: string;
+ name: string;
+ /** the block kind this style is FOR — informs the panel, never enforced:
+ * nothing stops a style meant for h2 being applied to a quote */
+ kind: BlockKind;
+ /** a CSS font stack, like `TypeDoc.type.family` — no font files, no downloads */
+ family?: string;
+ /** px */ size?: number;
+ /** 100–900, CSS `font-weight` */ weight?: number;
+ italic?: boolean;
+ /** a CSS colour — hex, rgb()/rgba(), hsl()/hsla(), or a named colour */
+ color?: string;
+ align?: Block['align'];
+ /** space before, px */ sb?: number;
+ /** space after, px */ sa?: number;
+ /** line spacing, a multiple of the font size */ lh?: number;
+ /** first-line indent, px */ ind?: number;
+}
+
export interface TypeDoc {
format: typeof FORMAT;
version: number;
@@ -80,18 +273,115 @@ export interface TypeDoc {
/** note id → note text. Kept out of the blocks so a note can outlive a
* re-flow of the paragraph that references it. */
footnotes: Record<string, string>;
+ /** review threads, by id — see CommentThread */
+ comments?: Record<string, CommentThread>;
+ /** document-wide paragraph defaults; absent means the built-in ones */
+ layout?: { align?: Block['align']; sb?: number; sa?: number; lh?: number; ind?: number };
+ /**
+ * Named styles, by id — see DocStyle.
+ *
+ * Absent means every kind renders through docstyles.ts's built-in table,
+ * which is derived from styles.css exactly, so a document that never opened
+ * the Styles panel prints byte-for-byte what it always did. An entry here
+ * OVERRIDES the built-in of the same id (materialized the first time a
+ * built-in is edited); a document may also define ids the built-ins do not.
+ */
+ styles?: Record<string, DocStyle>;
+ /**
+ * The document's typeface and base size.
+ *
+ * A DOCUMENT property, not a viewer preference: a contract is typeset, and
+ * the person who wrote it chose how it reads on paper. The theme follows the
+ * reader; the typeface does not.
+ *
+ * `family` is a CSS font stack, not a single name, and the choices are stacks
+ * that resolve on every platform without shipping a font file — a
+ * self-contained document cannot rely on a download, and an embedded face is
+ * the separate `fonts` field. `size` is px, the unit the page geometry is
+ * already in.
+ */
+ type?: { family?: string; size?: number };
revisions: Revision[];
signatures: Signature[];
+ /**
+ * Is the document recording edits as tracked changes?
+ *
+ * DOCUMENT-level, not a viewer preference — unlike the locale, reduced motion
+ * or hidden comments. Whether edits are recorded is a property of the
+ * agreement everyone is working on: if it were per-viewer, one collaborator
+ * would silently make untracked edits to a document another believes is
+ * fully tracked, which is the one failure a tracked document cannot have.
+ *
+ * Absent means off, so every file written before this existed is untracked
+ * and reads identically.
+ */
+ track?: boolean;
fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>;
assets?: Record<string, string>;
readonly?: boolean;
template?: boolean;
/** volatile, never signed */
modified?: string;
+ /**
+ * Live-collaboration credentials (bento-sync), minted AT CREATION so any
+ * copy of the file can join once sharing is turned on. `room` is the relay
+ * WebSocket URL (a random id committed to the owner pubkey — never derived
+ * from docId), `key` the base64url AES-GCM room read key. `on` gates
+ * auto-join: absent = true. `sync` is the saved CRDT state, stamped at
+ * save-time on shared documents, so an offline-edited copy rejoins as a
+ * true fork. See docs/collab-design.md and type/src/sync/session.ts.
+ *
+ * type mints v2 (fine-grained access) credentials ONLY — there is no
+ * pre-v2 history to carry forward, unlike bento/slides. The room commits to
+ * an OWNER pubkey; a shared copy carries an owner-signed INVITE instead of
+ * `ownerPriv`, and each device mints its own member identity (kept in
+ * localStorage, never in the file).
+ */
+ collab?: {
+ room: string;
+ key: string;
+ on?: boolean;
+ sync?: import('./sync/crdt.ts').SyncStateJSON;
+ v?: number;
+ owner?: string;
+ ownerPriv?: string;
+ /** 'reader' = this copy is a live viewer: receives updates, never sends. */
+ role?: 'writer' | 'reader';
+ invite?: {
+ pub: string;
+ priv: string;
+ role: 'writer' | 'commenter';
+ /** unix ms expiry; 0/absent = no expiry */
+ exp?: number;
+ /** owner's signature over `inv.${pub}.${role}.${exp||0}` */
+ sig: string;
+ };
+ };
/** unknown fields are PRESERVED — format additivity (PLATFORM §3) */
[extra: string]: unknown;
}
+/**
+ * The document as it should leave this app — WITHOUT its collaboration
+ * credentials.
+ *
+ * `doc.collab` carries `ownerPriv`, `writerPriv` and the room key: private
+ * keys and a read capability. Anything that leaves the app as text — the
+ * clipboard, an agent hand-off — must not carry them, or pasting "the
+ * document JSON" into a chat hands over write access to a live room, which is
+ * not revocable by deleting the message.
+ *
+ * It strips by REMOVING the field rather than by listing the fields to keep,
+ * deliberately: a private field added to CollabCreds later is then covered
+ * without anyone remembering to update this. scripts/test-export-secrets.ts
+ * asserts that shape across every app that has a clipboard export.
+ */
+export function docForExport(doc: TypeDoc): TypeDoc {
+ const { collab, ...rest } = doc as TypeDoc & { collab?: unknown };
+ void collab;
+ return rest as TypeDoc;
+}
+
export const uid = (p = 'b'): string => {
const r = globalThis.crypto?.randomUUID?.();
return r ? `${p}-${r.slice(0, 8)}` : `${p}-${Math.random().toString(36).slice(2, 10)}`;
@@ -152,7 +442,7 @@ export function parseDoc(raw: string): ParseResult {
const body: Block[] = [];
(json.body as unknown[]).forEach((b, i) => {
if (!isObj(b)) { repaired.push(`dropped a block at ${i} that was not an object`); return; }
- const kind: BlockKind = ['para', 'h1', 'h2', 'h3', 'quote'].includes(b.kind as string)
+ const kind: BlockKind = ['para', 'h1', 'h2', 'h3', 'quote', 'ul', 'ol', 'cell', 'image', 'caption', 'toc', 'math', 'embed'].includes(b.kind as string)
? b.kind as BlockKind : 'para';
if (kind !== b.kind) repaired.push(`block ${i}: unknown kind ${JSON.stringify(b.kind)} read as a paragraph`);
const text = typeof b.text === 'string' ? b.text : '';
@@ -173,10 +463,127 @@ export function parseDoc(raw: string): ParseResult {
.sort((x, y) => x.at - y.at)
: undefined;
- const out: Block = { id, kind, text };
- if (marks?.length) out.marks = marks;
- if (notes?.length) out.notes = notes;
+ // START FROM THE INCOMING BLOCK, then overwrite what we validate.
+ //
+ // This used to be `{ id, kind, text }`, which silently DROPPED every
+ // block-level field this build does not know about — while doc-level
+ // unknowns survived on the object spread above. That breaks format
+ // additivity (PLATFORM §3) exactly where a word processor's additive
+ // fields land: a document written by a newer build, opened and saved by an
+ // older one, came back with its paragraph alignment, its page-break hints
+ // and anything else newer quietly deleted. Nothing announced it.
+ //
+ // Known fields are still validated and repaired below; unknown ones ride
+ // through untouched, which is the whole promise.
+ const out: Block = { ...(b as Partial<Block>), id, kind, text } as Block;
+ if (marks?.length) out.marks = marks; else delete out.marks;
+ if (notes?.length) out.notes = notes; else delete out.notes;
+ if (typeof b.role !== 'string') delete out.role;
+ // Now that these are KNOWN fields they are clamped like `level`, rather
+ // than riding through as unknowns. A generator can emit any of them.
+ const num = (v: unknown, lo: number, hi: number) =>
+ typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi ? v : undefined;
+ if (!['left', 'center', 'right', 'justify'].includes(out.align as string)) delete out.align;
+ for (const k of ['sb', 'sa', 'ind'] as const) {
+ const v = num(out[k], 0, 2000);
+ if (v === undefined) delete out[k]; else out[k] = v;
+ }
+ const lh = num(out.lh, 0.5, 4);
+ if (lh === undefined) delete out.lh; else out.lh = lh;
+ for (const k of ['keepNext', 'keepTogether', 'breakBefore'] as const) {
+ if (out[k] !== true) delete out[k];
+ }
+ // A styleId that resolves to nothing (a style since deleted, or a typo from
+ // hand-edited JSON) is kept rather than dropped, deliberately unlike a
+ // dangling footnote: docstyles.ts falls back to the block's KIND default
+ // when the id does not resolve, so an unknown id is never a rendering
+ // failure — only a "this named style no longer exists" the panel can show.
+ if (typeof b.styleId === 'string' && b.styleId) out.styleId = b.styleId; else delete out.styleId;
+ delete out.level; delete out.cell; delete out.image; delete out.caption; delete out.refs; delete out.cites;
if (typeof b.role === 'string') out.role = b.role;
+ // `level` is clamped and only kept on list kinds. A level on a paragraph
+ // would be silently meaningless, and a level of 40 would render as a list
+ // indented off the page — both are files a generator can produce.
+ if (isList(kind) && typeof b.level === 'number' && Number.isFinite(b.level)) {
+ const lv = Math.max(0, Math.min(MAX_LIST_LEVEL, Math.floor(b.level)));
+ if (lv !== b.level) repaired.push(`block ${i}: list level ${b.level} clamped to ${lv}`);
+ if (lv > 0) out.level = lv;
+ }
+ // A cell without a usable `cell` ref is not a cell — it becomes a paragraph
+ // rather than a block the renderer has to guess about. Repaired loudly:
+ // silently dropping a table is worse than saying the table was lost.
+ if (kind === 'cell') {
+ const c = isObj(b.cell) ? b.cell as Partial<CellRef> : undefined;
+ const cols = typeof c?.cols === 'number' && c.cols >= 1 ? Math.min(Math.floor(c.cols), MAX_TABLE_COLS) : 0;
+ if (c && typeof c.table === 'string' && c.table && cols) {
+ out.cell = { table: c.table, cols };
+ if (c.head === true) out.cell.head = true;
+ if (cols !== c.cols) repaired.push(`block ${i}: table columns ${c.cols} clamped to ${cols}`);
+ } else {
+ out.kind = 'para';
+ repaired.push(`block ${i}: table cell with no usable placement read as a paragraph`);
+ }
+ }
+ // An image with no usable src is not an image. Repaired to a paragraph
+ // carrying its alt text, so the words survive even when the picture does
+ // not — a silently vanished figure is the worse outcome.
+ if (kind === 'image') {
+ const im = isObj(b.image) ? b.image as Partial<ImageRef> : undefined;
+ if (im && typeof im.src === 'string' && im.src && SAFE_IMG.test(im.src)) {
+ out.image = { src: im.src };
+ if (typeof im.alt === 'string') out.image.alt = im.alt;
+ if (typeof im.w === 'number' && im.w > 0 && im.w <= 1) out.image.w = im.w;
+ else if (im.w !== undefined) {
+ // Dropped rather than clamped: `w` is a FRACTION of the measure, so a
+ // value outside 0–1 is not a big number, it is a different unit —
+ // most likely pixels — and guessing which would be worse than
+ // falling back to full width. Reported, because a silent repair is
+ // one the author cannot learn from.
+ repaired.push(`block ${i}: image width ${JSON.stringify(im.w)} is not a fraction of the measure — using full width`);
+ }
+ if (im.align === 'left' || im.align === 'center' || im.align === 'right') out.image.align = im.align;
+ } else {
+ out.kind = 'para';
+ if (!out.text && typeof im?.alt === 'string') out.text = im.alt;
+ repaired.push(`block ${i}: image with no usable source read as a paragraph`);
+ }
+ }
+ if (kind === 'caption') {
+ const c = isObj(b.caption) ? b.caption as Partial<CaptionRef> : undefined;
+ out.caption = { kind: c?.kind === 'figure' ? 'figure' : 'table',
+ ...(typeof c?.of === 'string' && c.of ? { of: c.of } : {}) };
+ }
+ // A dangling REFERENCE is kept, deliberately unlike a dangling note. A
+ // marker with no note behind it renders as a number pointing at nothing, so
+ // notes are dropped. A reference is the opposite case: the author wrote
+ // "see <that table>" and the table was deleted. Dropping it silently
+ // deletes the sentence's meaning and leaves prose reading "see ." Keeping
+ // it renders a visible ?? that says something must be fixed — the LaTeX
+ // behaviour, and the only safe one.
+ const refs = Array.isArray(b.refs)
+ ? (b.refs as XrefRef[]).filter(r => isObj(r) && typeof r.to === 'string' && typeof r.at === 'number')
+ .map(r => ({ to: r.to, at: Math.max(0, Math.min(r.at, text.length)),
+ ...(r.style === 'page' || r.style === 'both' ? { style: r.style } : {}) }))
+ .sort((x, y) => x.at - y.at)
+ : undefined;
+ if (refs?.length) out.refs = refs;
+ // No dangling-key sweep, deliberately, and for the same reason a dangling
+ // cross-reference is kept: a citation whose entry is missing must render
+ // visibly as [?key] so somebody fixes the bibliography. Dropping it deletes
+ // the author's claim to a source.
+ const cites = Array.isArray(b.cites)
+ ? (b.cites as CiteRef[])
+ .filter(c => isObj(c) && typeof c.at === 'number' && Array.isArray(c.keys))
+ .map(c => ({
+ at: Math.max(0, Math.min(c.at, text.length)),
+ keys: c.keys.filter((k): k is string => typeof k === 'string' && !!k),
+ ...(typeof c.locator === 'string' && c.locator ? { locator: c.locator } : {}),
+ ...(c.suppressAuthor === true ? { suppressAuthor: true } : {}),
+ }))
+ .filter(c => c.keys.length)
+ .sort((x, y) => x.at - y.at)
+ : undefined;
+ if (cites?.length) out.cites = cites;
body.push(out);
});
if (!body.length) body.push({ id: uid(), kind: 'para', text: '' });
@@ -196,6 +603,44 @@ export function parseDoc(raw: string): ParseResult {
}
if (dangling) repaired.push(`dropped ${dangling} footnote reference(s) with no note behind them`);
+ // Named styles (DocStyle) — same repair philosophy as everything above:
+ // validate and clamp what is known, drop what is not, never let a bad style
+ // definition reach docstyles.ts, which trusts the shape it is handed.
+ //
+ // `color` is document data written straight into a `style` attribute
+ // (render.ts, print.ts) — the same class of hole `safeHref`/`safeFamily`
+ // guard in inline.ts. This is an ALLOW-LIST for the same reason theirs is:
+ // no `;`, no `(` beyond a bare `rgb(`/`hsl(` function, so neither a second
+ // declaration nor a `url()` can be formed.
+ const SAFE_STYLE_COLOR = /^(#[0-9a-fA-F]{3,8}|rgba?\([\d.,%\s]+\)|hsla?\([\d.,%\s]+\)|[a-zA-Z]{1,30})$/;
+ const numClamp = (v: unknown, lo: number, hi: number): number | undefined =>
+ typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi ? v : undefined;
+ const styles: Record<string, DocStyle> = {};
+ if (isObj(json.styles)) {
+ const usedIds = new Set<string>();
+ for (const [key, raw0] of Object.entries(json.styles)) {
+ if (!isObj(raw0)) continue;
+ const raw = raw0 as Record<string, unknown>;
+ let id = typeof raw.id === 'string' && raw.id ? raw.id : key;
+ if (usedIds.has(id)) id = `${id}~${key}`;
+ usedIds.add(id);
+ const kind: BlockKind = ['para', 'h1', 'h2', 'h3', 'quote', 'ul', 'ol', 'cell', 'image', 'caption', 'toc', 'math', 'embed']
+ .includes(raw.kind as string) ? raw.kind as BlockKind : 'para';
+ const s: DocStyle = { id, name: typeof raw.name === 'string' && raw.name ? raw.name : id, kind };
+ if (typeof raw.family === 'string' && raw.family.trim()) s.family = raw.family.trim();
+ const size = numClamp(raw.size, 6, 96); if (size !== undefined) s.size = size;
+ const weight = numClamp(raw.weight, 100, 900); if (weight !== undefined) s.weight = Math.round(weight / 100) * 100;
+ if (raw.italic === true) s.italic = true;
+ if (typeof raw.color === 'string' && SAFE_STYLE_COLOR.test(raw.color.trim())) s.color = raw.color.trim();
+ if (['left', 'center', 'right', 'justify'].includes(raw.align as string)) s.align = raw.align as Block['align'];
+ const sb = numClamp(raw.sb, 0, 2000); if (sb !== undefined) s.sb = sb;
+ const sa = numClamp(raw.sa, 0, 2000); if (sa !== undefined) s.sa = sa;
+ const ind = numClamp(raw.ind, 0, 2000); if (ind !== undefined) s.ind = ind;
+ const lh = numClamp(raw.lh, 0.5, 4); if (lh !== undefined) s.lh = lh;
+ styles[id] = s;
+ }
+ }
+
const doc: TypeDoc = {
...(json as object) as TypeDoc, // unknown fields ride along
format: FORMAT,
@@ -205,17 +650,59 @@ export function parseDoc(raw: string): ParseResult {
page: isObj(json.page) ? { ...LETTER, ...(json.page as object) } as PageSpec : { ...LETTER },
body, footnotes,
revisions: Array.isArray(json.revisions) ? json.revisions as Revision[] : [],
+ ...(json.track === true ? { track: true } : {}),
signatures: Array.isArray(json.signatures) ? json.signatures as Signature[] : [],
};
+ if (Object.keys(styles).length) doc.styles = styles; else delete doc.styles;
if (typeof json.docId !== 'string' || !json.docId) repaired.push('minted a missing docId');
+ // Comment threads: parse totally, THEN repair. The order matters and the
+ // feature's note says why — repairing before an anchor moves would clamp it
+ // against a body that has already changed.
+ const threads = reconcileThreads(readThreadsRaw(doc), body);
+ if (threads.length) doc.comments = Object.fromEntries(threads.map(t => [t.id, t]));
+ else delete doc.comments;
+
return { ok: true, doc, repaired };
}
/** The document's text, in order — what gets measured, searched and diffed. */
export const plainText = (doc: TypeDoc): string => doc.body.map(b => b.text).join('\n');
+/**
+ * Words as a READER would count them: insertions in, tracked deletions out.
+ *
+ * A tracked deletion leaves its characters in `b.text` — that is what makes it
+ * rejectable — so counting the raw string reports words the document no longer
+ * says. Deleting a sentence would make the count go UP, since the struck text
+ * stays and the count has no way to know it is struck.
+ *
+ * This is the general hazard of the representation, and every other place that
+ * reads a block as prose has the same decision to make.
+ */
export const wordCount = (doc: TypeDoc): number =>
- doc.body.reduce((n, b) => n + (b.text.trim() ? b.text.trim().split(/\s+/).length : 0), 0);
+ doc.body.reduce((n, b) => {
+ const t = readerText(b).trim();
+ return n + (t ? t.split(/\s+/).length : 0);
+ }, 0);
+
+/**
+ * `b.text` with tracked deletions removed — the prose a reader sees.
+ *
+ * It lives HERE, the module with no dependencies, rather than in track.ts,
+ * because track.ts imports this one and the reverse would be a cycle. track.ts
+ * re-exports it as textOf(). One implementation: a second copy would be two
+ * answers to "what does this document say", and they would diverge.
+ */
+export function readerText(b: Block): string {
+ const dels = (b.marks ?? []).filter(m => m.t === 'del').sort((x, y) => x.from - y.from);
+ if (!dels.length) return b.text;
+ let out = '', at = 0;
+ for (const d of dels) {
+ if (d.from > at) out += b.text.slice(at, d.from);
+ at = Math.max(at, d.to);
+ }
+ return out + b.text.slice(at);
+}
/**
* Replace [at, at+removed) of a block's text with `added`, keeping marks and
@@ -232,6 +719,17 @@ export function spliceText(block: Block, at: number, removed: number, added: str
const m = shiftMarks(block.marks, at, removed, added.length, text.length);
if (m.length) out.marks = m; else delete out.marks;
}
+ if (block.cites?.length) {
+ const end = at + removed, delta = added.length - removed;
+ const c = block.cites
+ .filter(x => !(x.at > at && x.at < end))
+ .map(x => (x.at >= end ? { ...x, at: x.at + delta } : x));
+ if (c.length) out.cites = c; else delete out.cites;
+ }
+ if (block.refs?.length) {
+ const r = shiftRefs(block.refs, at, removed, added.length);
+ if (r.length) out.refs = r; else delete out.refs;
+ }
if (block.notes?.length) {
const end = at + removed;
const delta = added.length - removed;
diff --git a/type/src/move.ts b/type/src/move.ts
new file mode 100644
index 00000000..9ea36791
--- /dev/null
+++ b/type/src/move.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// MOVING A BLOCK.
+//
+// Until this existed the only way to reorder a paragraph was cut and paste,
+// which loses comment anchors and any tracked change attached to it.
+//
+// THE UNIT IS NOT THE BLOCK. The body is flat, but render.ts groupBlocks
+// assembles runs of it into single visible things: a table is a run of `cell`
+// blocks sharing a table id, and a list is a run of `ul`/`ol` blocks. Moving
+// one member of such a run would tear the table in half or drop a paragraph
+// between two bullets. So a move operates on the UNIT — the maximal run that
+// renders as one thing — and swaps it with the unit next to it.
+//
+// A caption travels with what it captions. `caption.of` points at the block,
+// and a figure that walks away from its caption leaves a numbered line
+// stranded under someone else's paragraph.
+
+import { isList, type Block } from './model.ts';
+
+export interface Unit { start: number; end: number; id: string }
+
+/**
+ * The unit containing body[i], as a half-open range.
+ *
+ * Called with the index of ANY member of a run, not just its first — the
+ * caret can be in the third cell of a table, and the unit is still the table.
+ */
+export function unitAt(body: readonly Block[], i: number): Unit {
+ if (i < 0 || i >= body.length) return { start: i, end: i + 1, id: '' };
+ const b = body[i];
+ let start = i, end = i + 1;
+
+ if (b.kind === 'cell' && b.cell) {
+ const table = b.cell.table;
+ while (start > 0 && body[start - 1].kind === 'cell' && body[start - 1].cell?.table === table) start--;
+ while (end < body.length && body[end].kind === 'cell' && body[end].cell?.table === table) end++;
+ } else if (isList(b.kind)) {
+ // A maximal run of list blocks, INCLUDING a change of bullet to number.
+ // groupBlocks would render those as two lists, so this is deliberately
+ // coarser than rendering: moving half of what looks like one block of list
+ // is a worse outcome than moving one more paragraph than you meant to.
+ while (start > 0 && isList(body[start - 1].kind)) start--;
+ while (end < body.length && isList(body[end].kind)) end++;
+ } else if (b.kind === 'caption') {
+ // Grab the thing being captioned, so a caption is never a unit on its own
+ // that could be moved away from its figure.
+ const of = b.caption?.of;
+ if (of) {
+ const owner = body.findIndex(x => x.id === of);
+ if (owner >= 0 && owner < i) return unitAt(body, owner);
+ }
+ }
+
+ // absorb a caption that follows this unit and points into it
+ const ids = new Set(body.slice(start, end).map(x => x.id));
+ while (end < body.length && body[end].kind === 'caption'
+ && body[end].caption?.of && ids.has(body[end].caption!.of!)) end++;
+
+ return { start, end, id: body[start].id };
+}
+
+/** Every unit in the body, in order. */
+export function units(body: readonly Block[]): Unit[] {
+ const out: Unit[] = [];
+ let i = 0;
+ while (i < body.length) {
+ const u = unitAt(body, i);
+ out.push(u);
+ // unitAt can look BACKWARDS (a caption resolves to its figure), so a unit
+ // that starts before where we are would loop forever. Step past regardless.
+ i = Math.max(u.end, i + 1);
+ }
+ return out;
+}
+
+/**
+ * Move the unit containing `id` one place up or down.
+ *
+ * Returns a NEW body, or null when it cannot move — at the end of the
+ * document, or when the id is not there. Null rather than an unchanged copy so
+ * the caller can skip the commit entirely and not put an empty step on the
+ * undo stack.
+ */
+export function moveUnit(body: readonly Block[], id: string, dir: -1 | 1): Block[] | null {
+ const i = body.findIndex(b => b.id === id);
+ if (i < 0) return null;
+ const u = unitAt(body, i);
+ const list = units(body);
+ const at = list.findIndex(x => x.start === u.start);
+ const other = list[at + dir];
+ if (!other) return null;
+
+ const block = body.slice(u.start, u.end);
+ const rest = body.slice(other.start, other.end);
+ const out = body.slice();
+ if (dir === 1) out.splice(u.start, block.length + rest.length, ...rest, ...block);
+ else out.splice(other.start, rest.length + block.length, ...block, ...rest);
+ return out;
+}
+
+/** Every index a unit may be dropped BEFORE, plus the end of the body. */
+export const boundaries = (body: readonly Block[]): number[] =>
+ [...units(body).map(u => u.start), body.length];
+
+/**
+ * Move a unit so it sits before `target`.
+ *
+ * Drag needs this: a drop is an arbitrary destination, not a step. The target
+ * is SNAPPED to the nearest unit boundary rather than taken literally, so a
+ * drop can never land inside a table or between two bullets however sloppy the
+ * gesture was — the same guarantee moveUnit gives, enforced in the engine
+ * rather than trusted to the pointer.
+ *
+ * Returns null when the move would change nothing: dropping a unit on either
+ * of its own edges is the commonest gesture in a drag that the user thought
+ * better of, and it should not land on the undo stack.
+ */
+export function moveUnitTo(body: readonly Block[], id: string, target: number): Block[] | null {
+ const i = body.findIndex(b => b.id === id);
+ if (i < 0) return null;
+ const u = unitAt(body, i);
+
+ const edges = boundaries(body);
+ const snapped = edges.reduce((best, e) =>
+ Math.abs(e - target) < Math.abs(best - target) ? e : best, edges[0]);
+
+ // its own two edges are no-ops
+ if (snapped === u.start || snapped === u.end) return null;
+
+ const block = body.slice(u.start, u.end);
+ const rest = [...body.slice(0, u.start), ...body.slice(u.end)];
+ // after removing the unit, everything past it shifts left by its length
+ const at = snapped > u.start ? snapped - block.length : snapped;
+ rest.splice(at, 0, ...block);
+ return rest;
+}
+
+/** Can the unit containing `id` move that way? Drives the disabled state. */
+export const canMove = (body: readonly Block[], id: string, dir: -1 | 1): boolean =>
+ moveUnit(body, id, dir) !== null;
diff --git a/type/src/paginate.ts b/type/src/paginate.ts
index a0fcae77..3608d550 100644
--- a/type/src/paginate.ts
+++ b/type/src/paginate.ts
@@ -32,6 +32,7 @@
// alternatives, less wasted note area, and what a typesetter does.
import type { PageSpec, TypeDoc } from './model.ts';
+import { atomize, breakY } from './layout.ts';
export interface Page {
n: number;
@@ -52,7 +53,7 @@ export interface Metrics {
}
/** A line box, in paper space. */
-interface LineBox { top: number; bottom: number }
+interface LineBox { top: number; bottom: number; id?: string }
const bodyHeight = (p: PageSpec) => p.height - p.marginTop - p.marginBottom;
@@ -70,13 +71,35 @@ function lineBoxes(host: HTMLElement, page: PageSpec): LineBox[] {
acceptNode: n => n.nodeValue?.trim().length ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
});
const r = document.createRange();
+ // Which BLOCK a line belongs to, so page-breaking hints (keep-together,
+ // keep-with-next) can group lines into units that must not be split.
+ const owner = (n: Node): string | undefined => {
+ let p: HTMLElement | null = n.parentElement;
+ while (p && p !== host && !p.dataset.id) p = p.parentElement;
+ return p?.dataset.id;
+ };
let n: Node | null;
while ((n = walker.nextNode())) {
r.selectNodeContents(n);
+ const id = owner(n);
for (const rect of Array.from(r.getClientRects())) {
- if (rect.height) out.push({ top: rect.top - top0, bottom: rect.bottom - top0 });
+ if (rect.height) out.push({ top: rect.top - top0, bottom: rect.bottom - top0, id });
}
}
+ // ATOMIC BLOCKS — an image, and later a display formula — contain no text
+ // nodes, so the walker above never sees them. Left out, they contributed
+ // height to the flow that pagination did not know about, and every page after
+ // the first image overflowed by exactly the image's height.
+ //
+ // One box for the whole element is not an approximation, it is the truth: an
+ // image cannot be broken across a page, so "does it fit in what is left" is
+ // the only question, and a box that does not fit pushes the break to its top
+ // — which moves the whole image to the next page. That falls out of the
+ // existing algorithm with no special case.
+ for (const el of Array.from(host.querySelectorAll<HTMLElement>('[data-atomic]'))) {
+ const rect = el.getBoundingClientRect();
+ if (rect.height) out.push({ top: rect.top - top0, bottom: rect.bottom - top0, id: el.dataset.id });
+ }
return out.sort((a, b) => a.top - b.top);
}
@@ -128,6 +151,7 @@ export function paginate(doc: TypeDoc, host: HTMLElement): Metrics {
const page = doc.page;
const H = bodyHeight(page);
const boxes = lineBoxes(host, page);
+ const units = atomize(doc.body, boxes);
const pages: Page[] = [];
let start = 0;
@@ -145,11 +169,11 @@ export function paginate(doc: TypeDoc, host: HTMLElement): Metrics {
for (let iter = 0; iter < 16; iter++) {
const avail = H - reserved;
- let e = Infinity;
- for (const b of boxes) {
- if (b.top < start - 0.5) continue;
- if (b.bottom - start > avail) { e = b.top; break; }
- }
+ // With no keeps and no explicit breaks in the document, atomize returns
+ // one atom per line and breakY reproduces the line-by-line loop this
+ // replaced, exactly — asserted in scripts/test-type-layout.ts for every
+ // start and height tried, which is what made the swap safe.
+ const e = breakY(units, start, avail);
const ids = carried.concat(notesIn(host, page, start, e));
const need = measureNotes(doc, page, ids);
if (Math.abs(need - reserved) < 0.5) { end = e; notes = ids; reserved = need; break; }
@@ -174,6 +198,18 @@ export function paginate(doc: TypeDoc, host: HTMLElement): Metrics {
reserved = need; end = e; notes = ids;
}
+ // NO PROGRESS. One box is taller than the page can ever be — an image
+ // larger than the paper, which a file can perfectly well contain. The break
+ // would be placed at the box's own top, the next page would start where
+ // this one did, and the loop would spin until the guard, producing hundreds
+ // of empty pages. Give the oversized box its own page and move past it: it
+ // will overflow the margin, which is visible and fixable, rather than
+ // hanging the document, which is neither.
+ if (isFinite(end) && end <= start + 0.5) {
+ const next = boxes.find(b => b.top > start + 0.5);
+ end = next ? next.top : Infinity;
+ }
+
pages.push({ n: pages.length + 1, start, end, notes, reserved });
if (!isFinite(end)) break;
start = end;
diff --git a/type/src/print.ts b/type/src/print.ts
index 30f4be1c..22f6005d 100644
--- a/type/src/print.ts
+++ b/type/src/print.ts
@@ -23,8 +23,12 @@
// pagination is the same computation the editor already ran.
import type { Block, TypeDoc } from './model.ts';
-import { blockHtml, TAG } from './render.ts';
+import { blockHtml, groupBlocks, TAG } from './render.ts';
import type { Metrics } from './paginate.ts';
+import { captionIndex, docLang, fillXrefsHtml } from './xref.ts';
+import { blockStyle } from './layout.ts';
+import { docStyleCss } from './docstyles.ts';
+import { embedHtml } from './embed.ts';
export interface PrintOptions {
/** running head text; omitted = the document title */
@@ -50,13 +54,18 @@ const esc = (s: string) => s.replace(/[&<>"]/g, c =>
* unreachable from content.
*/
function printCss(doc: TypeDoc): string {
- const p = doc.page;
+ // the document's typeface, so paper matches screen — same fallback as
+ // styles.css, so a file that says nothing prints exactly as it always did
+ const p = { ...doc.page,
+ __fontSize: `${doc.type?.size ?? 17}px`,
+ __fontFamily: doc.type?.family ?? '"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif',
+ };
return `
@page { size: ${p.width}px ${p.height}px; margin: 0; }
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
html, body { margin: 0; padding: 0; background: #fff; }
body {
- font: 17px/1.62 "Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;
+ font: ${p.__fontSize}/1.62 ${p.__fontFamily};
color: #1a1a1a; hyphens: auto; -webkit-hyphens: auto;
}
.t-page {
@@ -79,6 +88,20 @@ h2 { font-size: 15.5px; font-weight: 600; margin: 24px 0 8px; hyphens: none; }
h3 { font-size: 14px; font-weight: 600; margin: 16px 0 6px; color: #3a3d44; hyphens: none; }
p { margin: 0 0 10px; text-align: justify; orphans: 2; widows: 2; text-wrap: pretty; }
p + p { text-indent: 1.4em; margin-top: -10px; padding-top: 10px; }
+.t-figure { margin: 12px 0; text-align: center; break-inside: avoid; page-break-inside: avoid; }
+.t-figure img { max-width: 100%; height: auto; }
+.t-figure[data-align="left"] { text-align: left; }
+.t-figure[data-align="right"] { text-align: right; }
+.t-table { width: 100%; border-collapse: collapse; table-layout: fixed; margin: 0 0 12px; font-size: .95em; }
+.t-table th, .t-table td { border-bottom: 1px solid #c3cad4; padding: 6px 10px 6px 0;
+ vertical-align: top; text-align: start; text-indent: 0; hyphens: none; }
+.t-table th { font-weight: 600; border-bottom-width: 1.5px; }
+.t-table tr:last-child td { border-bottom: 0; }
+ul, ol { margin: 0 0 10px; padding-inline-start: 1.6em; }
+li { margin: 0 0 3px; text-align: justify; text-indent: 0; orphans: 2; widows: 2; }
+li > ul, li > ol { margin: 3px 0 0; }
+ul { list-style: disc; } ul ul { list-style: circle; } ul ul ul { list-style: square; }
+ol { list-style: decimal; } ol ol { list-style: lower-alpha; } ol ol ol { list-style: lower-roman; }
blockquote { margin: 12px 0 12px 24px; padding-left: 14px; border-left: 2px solid #d8dce2;
color: #3a3d44; font-style: italic; }
strong { font-weight: 600; }
@@ -102,9 +125,68 @@ sup.t-note { font: 600 9px/1 -apple-system, system-ui, sans-serif; color: #7a520
`;
}
-/** The body, rendered once — every page shows a window onto this same flow. */
-function bodyHtml(body: Block[]): string {
- return body.map(b => `<${TAG[b.kind]} data-id="${esc(b.id)}">${blockHtml(b)}</${TAG[b.kind]}>`).join('\n');
+/**
+ * A table, as HTML — the string twin of render.ts renderTable, and it must stay
+ * one: a table that gains a header row on screen and loses it on paper is the
+ * drift this module exists to prevent. Both are driven by the same token from
+ * the same grouping function, so only the emission differs.
+ */
+function tableHtml(rows: Block[][], head: boolean): string {
+ const cols = rows[0]?.length ?? 1;
+ const cell = (b: Block | undefined, tag: 'th' | 'td') =>
+ b ? `<${tag} data-id="${esc(b.id)}">${blockHtml(b)}</${tag}>`
+ : `<${tag}></${tag}>`;
+ const row = (r: Block[], tag: 'th' | 'td') =>
+ `<tr>${Array.from({ length: cols }, (_, c) => cell(r[c], tag)).join('')}</tr>`;
+ const parts: string[] = ['<table class="t-table">'];
+ if (head && rows.length) parts.push(`<thead>${row(rows[0], 'th')}</thead>`);
+ parts.push('<tbody>');
+ for (const r of rows.slice(head ? 1 : 0)) parts.push(row(r, 'td'));
+ parts.push('</tbody></table>');
+ return parts.join('');
+}
+
+/**
+ * The body, rendered once — every page shows a window onto this same flow.
+ *
+ * Uses the SAME grouping as the editor (render.ts groupBlocks), so a list that
+ * nests on screen nests identically on paper. Rebuilding the list structure
+ * here with a second implementation is exactly how print drifts from the
+ * editor, which is the failure this whole module exists to avoid.
+ */
+function bodyHtml(doc: TypeDoc, lang: string): string {
+ const body = doc.body;
+ const out: string[] = [];
+ for (const tok of groupBlocks(body)) {
+ if (tok.t === 'open') out.push(`<${tok.kind}>`);
+ else if (tok.t === 'close') out.push(`</${tok.kind}>`);
+ else if (tok.t === 'table') out.push(tableHtml(tok.rows, tok.head));
+ // An embed prints as its STATIC RENDER — which is the tier that exists for
+ // exactly this, and why the render is mandatory rather than a cache.
+ else if (tok.block.kind === 'embed') out.push(embedHtml(tok.block));
+ else if (tok.block.kind === 'image') {
+ const b = tok.block, im = b.image;
+ const w = im?.w ? ` style="width:${Math.round(im.w * 100)}%"` : '';
+ const al = im?.align ? ` data-align="${esc(im.align)}"` : '';
+ out.push(`<figure class="t-figure" data-id="${esc(b.id)}"${al}>` +
+ (im ? `<img src="${esc(im.src)}" alt="${esc(im.alt ?? '')}"${w}>` : '') +
+ `</figure>`);
+ }
+ else {
+ const b = tok.block;
+ // Same composition as render.ts renderBlock, same order — the named
+ // style first, the block's own direct properties second, so print
+ // shows exactly what the screen does: a block's own align/sb/sa/lh/ind
+ // beats its style, both beat the document's plain CSS defaults.
+ const st = [docStyleCss(doc, b), blockStyle(b)].filter(Boolean).join(';');
+ out.push(`<${TAG[b.kind]} data-id="${esc(b.id)}"${st ? ` style="${esc(st)}"` : ''}>` +
+ `${blockHtml(b)}</${TAG[b.kind]}>`);
+ }
+ }
+ // The DOM pass (numberXrefs) and this string pass fill the SAME atoms from
+ // the SAME index, which is what stops the printed numbering drifting from the
+ // screen's — the drift this module exists to prevent.
+ return fillXrefsHtml(out.join('\n'), captionIndex(body, lang));
}
/**
@@ -120,7 +202,9 @@ function bodyHtml(body: Block[]): string {
export function buildPrintDocument(doc: TypeDoc, metrics: Metrics, opts: PrintOptions = {}): string {
const p = doc.page;
const head = opts.header ?? doc.title;
- const flow = bodyHtml(doc.body);
+ // the DOCUMENT's language, not the reader's: a caption label is printed and
+ // signed with the author's sentences, so it must not change per reader
+ const flow = bodyHtml(doc, docLang(doc));
const contentH = p.height - p.marginTop - p.marginBottom;
// footnote numbering is derived, in document order, exactly as on screen
diff --git a/type/src/props.ts b/type/src/props.ts
new file mode 100644
index 00000000..49c82f43
--- /dev/null
+++ b/type/src/props.ts
@@ -0,0 +1,502 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The properties panel — what the thing under the caret IS, and how to change it.
+//
+// THE SUITE'S DIVISION, and it is not a matter of taste: the top bar holds
+// ACTIONS, the right panel holds PROPERTIES. slides does exactly this — its bar
+// inserts and its panel describes, with Typography, Fill & stroke and Position
+// & size all panel sections that change with the selection
+// (slides/src/editor/panels.ts). type had drifted into putting properties in
+// the bar, one control at a time, until the bar was permanently folded.
+//
+// CONTEXTUAL means the panel answers a question about the current block. Put the
+// caret in a paragraph and it offers the paragraph's style and its character
+// formatting; put it in a table cell and a Table section appears; select a
+// picture and its width, alignment and alt text appear. Nothing is shown for a
+// thing that is not there — a panel of permanently disabled controls teaches
+// people to stop reading it.
+//
+// It rebuilds on the SELECTION signal as well as the document one, because
+// moving the caret from a paragraph into a cell changes what should be shown
+// without changing a byte of the document.
+
+import { registerPanel, registerSelection, type FeatureContext } from './features.ts';
+import { MARK_TOOLS } from './marks.ts';
+import { t } from './i18n.ts';
+import { MAX_TABLE_COLS, type Block, type BlockKind } from './model.ts';
+import { PAPER, openPageSetup, withSize, withOrientation, type SizeId } from './layout.ts';
+import { isHeading, EXCLUDE_ROLE, sectionSettings, setNumbered, toggleExclude } from './toc.ts';
+import { ensureAuthor } from './comments.ts';
+import { stylesSection } from './docstyles.ts';
+// docstyles.ts's own panel styling — imported here rather than there so the
+// node test rigs, which load model.ts → comments.ts → render.ts → docstyles.ts
+// with no bundler in front of them, never meet a bare `.css` import. props.ts
+// is UI-only and reached only through features.ts, which no rig imports.
+import './docstyles.css';
+
+// ─────────────────────────────────────────────────────────────── small parts
+
+const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string): HTMLElementTagNameMap[K] => {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ return n;
+};
+
+/** A titled group. Sections are the panel's grammar — one per kind of thing. */
+function section(host: HTMLElement, title: string): HTMLElement {
+ const h = el('div', 't-section');
+ h.textContent = title;
+ const body = el('div', 't-sec-body');
+ host.append(h, body);
+ return body;
+}
+
+/** A labelled row: the name on the left, the control right-aligned. */
+function row(host: HTMLElement, label: string, control: HTMLElement): HTMLElement {
+ const r = el('div', 't-row');
+ const s = el('span');
+ s.textContent = label;
+ r.append(s, control);
+ host.appendChild(r);
+ return r;
+}
+
+/** A cluster of toggle buttons, e.g. bold / italic / underline. */
+function toggles(
+ host: HTMLElement,
+ items: Array<{ icon: string; title: string; on: boolean; run: () => void }>,
+): void {
+ const g = el('div', 't-toggles');
+ for (const it of items) {
+ const b = el('button', 't-btn' + (it.on ? ' on' : ''));
+ b.type = 'button';
+ b.innerHTML = it.icon;
+ b.title = it.title;
+ // mousedown, not click: the caret must survive pressing a formatting button
+ b.addEventListener('mousedown', e => { e.preventDefault(); it.run(); });
+ g.appendChild(b);
+ }
+ host.appendChild(g);
+}
+
+function select(
+ options: Array<[string, string]>, value: string, onChange: (v: string) => void,
+): HTMLSelectElement {
+ const s = el('select', 't-select');
+ for (const [v, label] of options) {
+ const o = el('option');
+ o.value = v; o.textContent = label; o.selected = v === value;
+ s.appendChild(o);
+ }
+ s.addEventListener('change', () => onChange(s.value));
+ return s;
+}
+
+function numberField(value: number | undefined, placeholder: string,
+ onCommit: (v: number | undefined) => void): HTMLInputElement {
+ const i = el('input', 't-field');
+ i.type = 'number';
+ i.value = value === undefined ? '' : String(value);
+ i.placeholder = placeholder;
+ i.addEventListener('change', () => {
+ const raw = i.value.trim();
+ onCommit(raw === '' ? undefined : Number(raw));
+ });
+ return i;
+}
+
+// ────────────────────────────────────────────────────────────────── sections
+
+/** The block under the caret, or undefined. */
+function current(ctx: FeatureContext): Block | undefined {
+ const c = ctx.editor.caret();
+ return c ? ctx.store.block(c.id) : undefined;
+}
+
+/**
+ * Faces that resolve everywhere without shipping a font file. Exported so
+ * docstyles.ts's typeface picker offers the SAME list rather than a second
+ * hand-copied one that drifts from this the first time someone edits either.
+ */
+export const FACES: Array<[string, string]> = [
+ ['"Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif', 'Palatino (serif)'],
+ ['Georgia, "Times New Roman", Times, serif', 'Georgia (serif)'],
+ ['"Times New Roman", Times, serif', 'Times New Roman'],
+ ['Charter, "Bitstream Charter", Cambria, Georgia, serif', 'Charter (serif)'],
+ ['-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif', 'System (sans)'],
+ ['Helvetica, Arial, sans-serif', 'Helvetica'],
+ ['Verdana, Geneva, sans-serif', 'Verdana'],
+ ['ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', 'Monospace'],
+];
+
+const STYLE_OPTIONS: Array<[BlockKind, string]> = [
+ ['para', 'Body'], ['h1', 'Title'], ['h2', 'Heading'], ['h3', 'Subheading'],
+ ['quote', 'Quote'], ['ul', 'Bulleted list'], ['ol', 'Numbered list'],
+];
+
+function textSection(host: HTMLElement, ctx: FeatureContext, b: Block): void {
+ const body = section(host, t('Text'));
+ row(body, t('Style'), select(
+ STYLE_OPTIONS.map(([v, l]) => [v, t(l)] as [string, string]),
+ b.kind,
+ v => { ctx.editor.setKind(v as BlockKind); ctx.refresh(); },
+ ));
+
+ // ONE list, in marks.ts, rendered here and in the selection toolbar. It was
+ // written out twice before, and a third copy was about to be written.
+ const active = ctx.editor.activeMarks() as Set<string>;
+ toggles(body, MARK_TOOLS.map(m => ({
+ icon: m.icon, title: m.title(), on: active.has(m.t), run: () => ctx.editor.toggle(m.t),
+ })));
+
+ // ---- typeface and size, for the SELECTION.
+ //
+ // A font is a character property: "make these three words Verdana" is the
+ // request, and the Document section's typeface is the DEFAULT these fall
+ // back to — the same relationship the paragraph controls already have with
+ // "Use document defaults" beneath them.
+ //
+ // Both controls are disabled without a selection, because there is nothing
+ // for them to act on: applying a font at a bare caret would either do
+ // nothing or silently restyle the whole paragraph, and a control that looks
+ // available and does nothing is worse than one that says it cannot.
+ const sel = ctx.editor.fontOfSelection();
+ const hasRange = (() => { const c = ctx.editor.caret(); return !!c && c.to !== undefined && c.to !== c.at; })();
+
+ const MIXED = '\u0000mixed';
+ const DEFAULT = '';
+ const faceOptions: Array<[string, string]> = [
+ [DEFAULT, t('Document default')],
+ ...FACES.map(([v, l]) => [v, l] as [string, string]),
+ ];
+ if (sel.family === 'mixed') faceOptions.unshift([MIXED, t('— mixed —')]);
+ // A family the document uses but this build does not list — from another
+ // editor, or a later version — is shown rather than silently relabelled as
+ // the default, which would rewrite it on the next click.
+ if (typeof sel.family === 'string' && sel.family !== 'mixed'
+ && !FACES.some(([v]) => v === sel.family)) faceOptions.push([sel.family, sel.family]);
+
+ const faceSel = select(faceOptions,
+ sel.family === 'mixed' ? MIXED : (sel.family ?? DEFAULT),
+ v => {
+ if (v === MIXED) return;
+ ctx.editor.setFontOn({ family: v === DEFAULT ? null : v });
+ ctx.refresh();
+ });
+ (faceSel as HTMLSelectElement).disabled = !hasRange;
+ row(body, t('Typeface'), faceSel);
+
+ const sizeField = numberField(
+ typeof sel.size === 'number' ? sel.size : undefined,
+ sel.size === 'mixed' ? t('mixed') : t('default'),
+ v => { ctx.editor.setFontOn({ size: v === undefined ? null : v }); ctx.refresh(); });
+ (sizeField as HTMLInputElement).disabled = !hasRange;
+ row(body, t('Size (px)'), sizeField);
+
+ // A disabled control that does not say why it is disabled is indistinguishable
+ // from a broken one — and this pair sits at the TOP of the panel, so it is the
+ // first thing reached for after clicking into a paragraph. Reported as "the
+ // dropdowns are not working", which is exactly right from the outside.
+ if (!hasRange) {
+ const why = el('p', 't-note');
+ why.textContent = t('Select some text to change its typeface or size. The document default is below.');
+ body.appendChild(why);
+ }
+
+ // Whether THIS heading is numbered is a property of the heading, so it is a
+ // checkbox here rather than the ⋯ entry it used to be — an action named "Do
+ // not number this heading" gave no way to see the current state, only a way
+ // to flip it, and no way at all to tell which heading it would act on.
+ //
+ // Shown only when the document numbers its sections: with numbering off there
+ // is nothing to exclude a heading from, and a control that cannot do anything
+ // is worse than an absent one.
+ if (isHeading(b) && sectionSettings(ctx.store.doc).numbered) {
+ const box = el('input') as HTMLInputElement;
+ box.type = 'checkbox';
+ box.checked = (b.role ?? '') !== EXCLUDE_ROLE;
+ box.addEventListener('change', () => toggleExclude(ctx));
+ row(body, t('Number this heading'), box);
+ }
+}
+
+function imageSection(host: HTMLElement, ctx: FeatureContext, b: Block): void {
+ const body = section(host, t('Picture'));
+ const im = b.image;
+ if (!im) return;
+
+ // WIDTH IS A PERCENTAGE of the text measure, because that is what the model
+ // stores — a fraction, not pixels, so the picture still fits when the page
+ // size changes. Showing pixels here would invite a value that stops being
+ // right the moment somebody switches to A4.
+ const w = numberField(im.w === undefined ? undefined : Math.round(im.w * 100), '100', v => {
+ ctx.store.commit(d => {
+ const t2 = d.body.find(x => x.id === b.id);
+ if (!t2?.image) return;
+ if (v === undefined || !(v > 0) || v > 100) delete t2.image.w;
+ else t2.image.w = v / 100;
+ }, { scope: { block: b.id } });
+ ctx.refresh();
+ });
+ row(body, t('Width (%)'), w);
+
+ row(body, t('Align'), select(
+ [['left', t('Left')], ['center', t('Centre')], ['right', t('Right')]],
+ im.align ?? 'center',
+ v => {
+ ctx.store.commit(d => {
+ const t2 = d.body.find(x => x.id === b.id);
+ if (t2?.image) t2.image.align = v as 'left' | 'center' | 'right';
+ }, { scope: { block: b.id } });
+ ctx.refresh();
+ },
+ ));
+
+ const alt = el('input', 't-field t-field-wide');
+ alt.value = im.alt ?? '';
+ alt.placeholder = t('What the picture shows');
+ alt.addEventListener('change', () => {
+ ctx.store.commit(d => {
+ const t2 = d.body.find(x => x.id === b.id);
+ if (t2?.image) t2.image.alt = alt.value;
+ }, { scope: { block: b.id } });
+ });
+ row(body, t('Alt text'), alt);
+ const note = el('p', 't-note');
+ // Alt text is not decoration: it is what a screen reader says, what search
+ // finds, and what survives when the picture does not (parseDoc keeps it as
+ // the paragraph text when a source is unusable).
+ note.textContent = t('Read aloud by screen readers, and kept as the text if the picture is ever lost.');
+ body.appendChild(note);
+}
+
+/** Every cell of the table the caret is in, in document order. */
+function tableCells(ctx: FeatureContext, b: Block): Block[] {
+ const id = b.cell?.table;
+ if (!id) return [];
+ return ctx.store.doc.body.filter(x => x.kind === 'cell' && x.cell?.table === id);
+}
+
+function tableSection(host: HTMLElement, ctx: FeatureContext, b: Block): void {
+ const body = section(host, t('Table'));
+ const cells = tableCells(ctx, b);
+ const cols = b.cell?.cols ?? 1;
+ const rows = Math.ceil(cells.length / cols);
+
+ const info = el('p', 't-note');
+ info.textContent = t('{rows} rows × {cols} columns', { rows, cols });
+ body.appendChild(info);
+
+ const headOn = !!cells[0]?.cell?.head;
+ const head = el('input');
+ head.type = 'checkbox';
+ head.checked = headOn;
+ head.addEventListener('change', () => {
+ ctx.store.commit(d => {
+ const all = d.body.filter(x => x.kind === 'cell' && x.cell?.table === b.cell!.table);
+ all.slice(0, cols).forEach(c => {
+ if (!c.cell) return;
+ if (head.checked) c.cell.head = true; else delete c.cell.head;
+ });
+ });
+ ctx.refresh();
+ });
+ row(body, t('Header row'), head);
+
+ const addRow = el('button', 't-btn');
+ addRow.type = 'button';
+ addRow.textContent = t('Add row');
+ addRow.addEventListener('click', () => {
+ ctx.store.commit(d => {
+ const all = d.body.filter(x => x.kind === 'cell' && x.cell?.table === b.cell!.table);
+ const last = d.body.indexOf(all[all.length - 1]);
+ const fresh: Block[] = Array.from({ length: cols }, (_, i) => ({
+ id: `${b.cell!.table}-r${Date.now().toString(36)}-${i}`,
+ kind: 'cell' as const, text: '', cell: { table: b.cell!.table, cols },
+ }));
+ d.body.splice(last + 1, 0, ...fresh);
+ });
+ ctx.refresh();
+ });
+
+ const addCol = el('button', 't-btn');
+ addCol.type = 'button';
+ addCol.textContent = t('Add column');
+ addCol.disabled = cols >= MAX_TABLE_COLS;
+ addCol.addEventListener('click', () => {
+ // Adding a column means inserting one cell per ROW and re-stamping `cols`
+ // on every cell — the count is repeated on each one deliberately, so a run
+ // of cells can always rebuild its own grid.
+ ctx.store.commit(d => {
+ const all = d.body.filter(x => x.kind === 'cell' && x.cell?.table === b.cell!.table);
+ const next = cols + 1;
+ for (let r = rows - 1; r >= 0; r--) {
+ const lastOfRow = all[r * cols + cols - 1];
+ const at = d.body.indexOf(lastOfRow);
+ d.body.splice(at + 1, 0, {
+ id: `${b.cell!.table}-c${Date.now().toString(36)}-${r}`,
+ kind: 'cell', text: '',
+ cell: { table: b.cell!.table, cols: next, ...(r === 0 && all[0]?.cell?.head ? { head: true } : {}) },
+ });
+ }
+ for (const c of d.body) if (c.kind === 'cell' && c.cell?.table === b.cell!.table) c.cell.cols = next;
+ });
+ ctx.refresh();
+ });
+
+ const btns = el('div', 't-toggles');
+ btns.append(addRow, addCol);
+ body.appendChild(btns);
+}
+
+function captionSection(host: HTMLElement, ctx: FeatureContext, b: Block): void {
+ const body = section(host, t('Caption'));
+ row(body, t('Numbered as'), select(
+ [['table', t('Table')], ['figure', t('Figure')]],
+ b.caption?.kind ?? 'table',
+ v => {
+ ctx.store.commit(d => {
+ const t2 = d.body.find(x => x.id === b.id);
+ if (t2?.caption) t2.caption.kind = v as 'table' | 'figure';
+ }, { scope: { block: b.id } });
+ ctx.refresh();
+ },
+ ));
+ const note = el('p', 't-note');
+ note.textContent = t('Tables and figures are numbered separately, in document order.');
+ body.appendChild(note);
+}
+
+/**
+ * Faces that resolve everywhere without shipping a font file.
+ *
+ * A self-contained document cannot fetch a webfont — the whole promise is that
+ * the file works from a memory stick in 2036 — so these are STACKS chosen so
+ * that every platform lands on something close. Embedding a real face is the
+ * separate `doc.fonts` field, which is how a house typeface would travel.
+ */
+
+
+function documentSection(host: HTMLElement, ctx: FeatureContext): void {
+ const body = section(host, t('Document'));
+ const doc = ctx.store.doc;
+
+ // ---- typeface. A DOCUMENT property: a contract is typeset, and the person
+ // who wrote it chose how it reads. The theme follows the reader; type does not.
+ // "Default typeface", not "Typeface". The Text section above has a Typeface
+ // row too, and two identically-labelled controls — one of them inert unless
+ // text is selected — is how a working panel reads as a broken one.
+ row(body, t('Default typeface'), select(
+ FACES.map(([v, l]) => [v, l] as [string, string]),
+ doc.type?.family ?? FACES[0][0],
+ v => {
+ ctx.store.commit(d => { d.type = { ...d.type, family: v }; });
+ ctx.refresh();
+ },
+ ));
+ row(body, t('Default size (px)'), numberField(doc.type?.size ?? 17, '17', v => {
+ ctx.store.commit(d => {
+ if (v === undefined || !(v >= 6 && v <= 96)) delete d.type?.size;
+ else d.type = { ...d.type, size: v };
+ });
+ ctx.refresh();
+ }));
+
+ // ---- page
+ const sizeId = (Object.keys(PAPER) as SizeId[])
+ .find(id => PAPER[id].width === doc.page.width && PAPER[id].height === doc.page.height)
+ ?? (Object.keys(PAPER) as SizeId[])
+ .find(id => PAPER[id].height === doc.page.width && PAPER[id].width === doc.page.height);
+ row(body, t('Page size'), select(
+ (Object.keys(PAPER) as SizeId[]).map(id => [id, id] as [string, string]),
+ sizeId ?? '',
+ v => { ctx.store.commit(d => { d.page = withSize(d.page, v as SizeId); }); ctx.refresh(); },
+ ));
+ row(body, t('Orientation'), select(
+ [['portrait', t('Portrait')], ['landscape', t('Landscape')]],
+ doc.page.width > doc.page.height ? 'landscape' : 'portrait',
+ v => {
+ ctx.store.commit(d => { d.page = withOrientation(d.page, v as 'portrait' | 'landscape'); });
+ ctx.refresh();
+ },
+ ));
+
+ // Margins stay behind the dialog: four numbers with live validation is more
+ // than a panel row, and it is the one thing here nobody sets twice.
+ const more = el('button', 't-btn');
+ more.type = 'button';
+ more.textContent = t('Margins…');
+ more.addEventListener('click', () => openPageSetup(ctx));
+ const wrap = el('div', 't-toggles');
+ wrap.appendChild(more);
+ body.appendChild(wrap);
+
+ // ---- numbering
+ const num = el('input');
+ num.type = 'checkbox';
+ num.checked = sectionSettings(doc).numbered;
+ num.addEventListener('change', () => {
+ ctx.store.commit(d => setNumbered(d, num.checked));
+ ctx.refresh();
+ });
+ row(body, t('Number sections'), num);
+
+ // ---- tracked changes. A DOCUMENT property, so it sits here beside the other
+ // document properties rather than in ⋯: it has a state, everyone working on
+ // the file shares it, and an action could only offer to flip it.
+ const trk = el('input') as HTMLInputElement;
+ trk.type = 'checkbox';
+ trk.checked = doc.track === true;
+ trk.addEventListener('change', () => {
+ // Ask for a name at the moment tracking is switched ON — the one place a
+ // prompt is expected. Every keystroke afterwards is attributed silently.
+ if (trk.checked) ensureAuthor();
+ ctx.store.commit(d => { if (trk.checked) d.track = true; else delete d.track; });
+ ctx.refresh();
+ });
+ row(body, t('Track changes'), trk);
+ const note = el('p', 't-note');
+ note.textContent = t('Off by default: most documents already carry their numbers in the heading text.');
+ body.appendChild(note);
+}
+
+// ──────────────────────────────────────────────────────────────── the panel
+
+function build(host: HTMLElement, ctx: FeatureContext): void {
+ host.replaceChildren();
+ const b = current(ctx);
+ if (!b) {
+ // No caret: the document's own properties are still worth showing, and are
+ // the ones you reach for before you start typing.
+ documentSection(host, ctx);
+ return;
+ }
+ // Order is stability, not importance: Text is always there, so it is always
+ // first, and the contextual sections appear beneath it rather than pushing it
+ // around as the caret moves.
+ textSection(host, ctx, b);
+ // Named styles — a SEPARATE section from Text's "Style" dropdown above: that
+ // one picks the block's KIND (which tag it is); this one picks how that kind
+ // LOOKS, which used to be a build constant (styles.css) and is now a
+ // document property. docstyles.ts no-ops for kinds with no default style.
+ stylesSection(host, ctx, b);
+ if (b.kind === 'image') imageSection(host, ctx, b);
+ if (b.kind === 'cell') tableSection(host, ctx, b);
+ if (b.kind === 'caption') captionSection(host, ctx, b);
+ // The document's own properties last: they are the ones you set once, so
+ // they should not push what you are working on down the panel.
+ documentSection(host, ctx);
+}
+
+registerPanel({
+ id: 'props',
+ label: () => t('Properties'),
+ side: 'right',
+ order: 10,
+ mount(host, ctx) {
+ build(host, ctx);
+ registerSelection(() => build(host, ctx));
+ },
+ update(host, ctx) { build(host, ctx); },
+});
diff --git a/type/src/registry.ts b/type/src/registry.ts
new file mode 100644
index 00000000..ebb92f35
--- /dev/null
+++ b/type/src/registry.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE ONE PLACE a feature module is switched on.
+//
+// Importing a feature file runs its registration; main.ts then renders whatever
+// the registry holds. This file exists so that adding a feature is a one-line
+// diff in a file nobody else is editing, instead of a diff in main.ts — which
+// is what lets several features be built at once without three-way conflicts
+// in the chrome.
+//
+// Order here is registration order, which decides ties within a toolbar group.
+// Anything order-sensitive should say so with an explicit `order` instead of
+// relying on this list.
+
+import './props.ts'; // the properties panel — Text, Picture, Table, Caption
+import './image.ts'; // pictures — insert, embed, atomic pagination
+import './embed.ts'; // embedded Bento artifacts — a Dash chart, a Slides deck
+import './blockgrip.ts'; // the margin handle that reorders a block, and ⌥⇧↑/↓
+import './seltoolbar.ts'; // the formatting bar that appears over a selection
+import './find.ts'; // find and replace — panel, ⌘F, replace all
+// captions, automatic figure/table numbering and cross-references
+import './xref.ts';
+import './layout.ts'; // paragraph properties, page setup, page breaks
+import './cite.ts'; // citations, the bibliography and the BibTeX import
+import './math.ts'; // mathematics: inline formulas and display equations
+
+export {};
+import './link.ts';
+import './toc.ts'; // section numbering + table of contents
+// comments — margin notes on a range of text, with replies and resolution.
+// Anchors ride inline.ts `shift`, so they move exactly as marks and footnote
+// anchors do; nothing here can reach print (see the header of comments.ts).
+import './comments.ts';
+// tracked-changes review: next/previous, accept/reject at the caret, and the
+// All markup/No markup/Original display modes. track.ts is the engine; this
+// is what makes an eighty-change document usable.
+import './review.ts';
diff --git a/type/src/render.ts b/type/src/render.ts
index ff537721..309ac83d 100644
--- a/type/src/render.ts
+++ b/type/src/render.ts
@@ -9,43 +9,309 @@
// editor re-render a block at any moment without asking whether it is safe.
import { toHtml, fromDom, type Mark } from './inline.ts';
-import type { Block, TypeDoc } from './model.ts';
+import { isList, MAX_LIST_LEVEL, type Block, type TypeDoc } from './model.ts';
+import { captionPrefixHtml, isXrefAtom, refAtoms, readXrefs, numberXrefs } from './xref.ts';
+import { blockStyle } from './layout.ts';
+import { activeStyleId, ensureStyleSheet } from './docstyles.ts';
+import { citeInject, isCiteAtom, mergeInject, paintCitations, readCiteAtoms } from './cite.ts';
+import { displayMathHtml, inlineMathHtml, isMathMark } from './math.ts';
+import { renderEmbed } from './embed.ts';
export const TAG: Record<Block['kind'], string> = {
para: 'p', h1: 'h1', h2: 'h2', h3: 'h3', quote: 'blockquote',
+ // A list ITEM is the block, and so is a table CELL. The <ul>/<ol> and the
+ // <table> around them are not in the model — see groupBlocks, and Block.level
+ // / Block.cell for why the document stays flat.
+ ul: 'li', ol: 'li', cell: 'td',
+ // atomic: rendered by renderImage/renderEmbed, never by the generic path
+ image: 'figure', caption: 'figcaption', toc: 'nav', math: 'div', embed: 'figure',
};
+/**
+ * Group a flat block list into the tree the browser needs to draw it.
+ *
+ * Runs of adjacent list blocks become real <ul>/<ol> elements, nested by
+ * `level`. Everything else is emitted as itself. This is the ONLY place that
+ * knows lists have a container, which is what lets the model stay flat and
+ * pagination stay indifferent — it measures line boxes through a tree walker
+ * and never looks at block structure at all.
+ *
+ * Emitted as a token stream rather than DOM so the editor and print can share
+ * it: print builds a string, the editor builds elements.
+ */
+export type GroupToken =
+ | { t: 'open'; kind: 'ul' | 'ol' }
+ | { t: 'close'; kind: 'ul' | 'ol' }
+ | { t: 'table'; rows: Block[][]; head: boolean }
+ | { t: 'block'; block: Block };
+
+export function groupBlocks(body: readonly Block[]): GroupToken[] {
+ const out: GroupToken[] = [];
+ // the open list stack, one entry per depth
+ const stack: Array<'ul' | 'ol'> = [];
+ // The close token carries its KIND. A consumer that has to work out what it
+ // is closing gets it wrong the moment lists nest — print did exactly that,
+ // scanning its own output backwards for the last open tag and finding one it
+ // had already closed.
+ const closeTo = (depth: number) => {
+ while (stack.length > depth) out.push({ t: 'close', kind: stack.pop()! });
+ };
+ for (let i = 0; i < body.length; i++) {
+ const b = body[i];
+ // ---- tables: a run of cells sharing one table id, chunked into rows
+ if (b.kind === 'cell' && b.cell) {
+ closeTo(0);
+ const id = b.cell.table;
+ const cells: Block[] = [];
+ while (i < body.length && body[i].kind === 'cell' && body[i].cell?.table === id) {
+ cells.push(body[i]); i++;
+ }
+ i--; // the for-loop will step past the run
+ // `cols` is repeated on every cell, so a disagreement is resolved by
+ // MAJORITY rather than by trusting whichever cell happened to be first —
+ // one edited cell should not reshape the whole table.
+ const tally = new Map<number, number>();
+ for (const c of cells) tally.set(c.cell!.cols, (tally.get(c.cell!.cols) ?? 0) + 1);
+ const cols = Math.max(1, [...tally.entries()].sort((x, y) => y[1] - x[1] || x[0] - y[0])[0][0]);
+ const rows: Block[][] = [];
+ for (let k = 0; k < cells.length; k += cols) rows.push(cells.slice(k, k + cols));
+ out.push({ t: 'table', rows, head: !!cells[0]?.cell?.head });
+ continue;
+ }
+ if (!isList(b.kind)) { closeTo(0); out.push({ t: 'block', block: b }); continue; }
+ const kind = b.kind as 'ul' | 'ol';
+ // CLAMPED HERE TOO, not only in the parser. parseDoc clamps what arrives
+ // from a file, but this function also runs on the LIVE model, which the
+ // editor and any script can write to directly. Unclamped, `level: 1e9`
+ // opened a billion list elements: the rig died with a V8 out-of-memory,
+ // and in a browser that is a hung tab from one bad number.
+ const lv = Number.isFinite(b.level) ? Math.max(0, Math.min(MAX_LIST_LEVEL, Math.floor(b.level!))) : 0;
+ const want = lv + 1; // depth in open elements
+ // A change of KIND at the same depth ends one list and starts another:
+ // bullets and numbers are different lists even when equally indented.
+ if (stack.length === want && stack[want - 1] !== kind) closeTo(want - 1);
+ closeTo(want);
+ while (stack.length < want) { stack.push(kind); out.push({ t: 'open', kind }); }
+ out.push({ t: 'block', block: b });
+ }
+ closeTo(0);
+ return out;
+}
+
/** Footnote markers are ATOMS: they occupy a position but no characters. */
export const isNoteAtom = (el: Element) =>
- el.tagName === 'SUP' && el.classList.contains('t-note');
+ (el.tagName === 'SUP' && el.classList.contains('t-note')) ||
+ // DERIVED content — a section number, a contents list — is an atom for the
+ // same reason a footnote marker is: it occupies a position, owns no
+ // characters, and readBlock must never absorb it into the text. Broadened
+ // here rather than at every call site so nothing downstream has to learn a
+ // second predicate.
+ el.hasAttribute('data-derived');
+
+/**
+ * Decorators — a feature's chance to add derived content to a block.
+ *
+ * ONE hook, consulted by blockHtml, so the editor and print cannot drift: both
+ * build their HTML through this function. A decorator returns a prefix, a
+ * suffix, or atoms; it must never change the block's text, which is what keeps
+ * the redline quiet and the signature stable.
+ */
+export type BlockDecorator = (b: Block, base: string) => string | null;
+const DECORATORS: BlockDecorator[] = [];
+export const registerBlockDecorator = (d: BlockDecorator): void => { DECORATORS.push(d); };
+/** Each decorator sees the previous one's output, so several can compose. */
+const decorate = (b: Block, base: string): string => {
+ let out = base;
+ for (const d of DECORATORS) out = d(b, out) ?? out;
+ return out;
+};
const noteMarker = (id: string) =>
`<sup class="t-note" data-note="${id}" contenteditable="false">•</sup>`;
/** One block, as HTML. Marks become tags; note refs become atoms. */
export function blockHtml(b: Block): string {
- const inject = b.notes?.length
- ? new Map(b.notes.map(n => [n.at, noteMarker(n.id)]))
- : undefined;
- const html = toHtml(b.text, b.marks ?? [], inject);
+ // Notes and cross-references are both ATOMS at offsets into the same text, so
+ // they share one inject map — a reference is the footnote marker's idea
+ // applied to a different target.
+ // A note, a cross-reference and a citation can all sit at the SAME offset, so
+ // these are merged rather than assigned — a plain map write silently drops
+ // one, and the one it drops depends on iteration order.
+ // INLINE MATH is a mark whose source characters are replaced wholesale by the
+ // typeset result. It is a mark and not an atom deliberately: the source lives
+ // in the text, so `x^2` → `x^3` reports to the redline as a one-word change
+ // to that formula. As an atom the diff would see no change at all, which for
+ // a redlining app is disqualifying.
+ const mathRanges = (b.marks ?? []).filter(isMathMark)
+ .map(m => ({ from: m.from, to: m.to, html: inlineMathHtml(b.text.slice(m.from, m.to)) }));
+ const atoms = mergeInject(
+ new Map((b.notes ?? []).map(n => [n.at, noteMarker(n.id)])),
+ refAtoms(b),
+ citeInject(b),
+ );
+ const html = toHtml(b.text, b.marks ?? [], atoms.size ? atoms : undefined,
+ mathRanges.length ? mathRanges : undefined);
// an empty block still needs a line box, or it collapses and cannot be clicked
- return html || '<br>';
+ return captionPrefixHtml(b) + decorate(b, html || '<br>');
+}
+
+/**
+ * A picture.
+ *
+ * `data-atomic` is what tells pagination this block has a height but no text
+ * nodes — without it the TreeWalker in paginate.ts never sees the image and
+ * every page after it overflows by exactly its height. Any future block that
+ * renders as a box rather than as text (a display formula, a chart) must carry
+ * the same attribute.
+ *
+ * The alt text is also the caption fallback and the redline's handle on the
+ * block, which is why it lives in the model rather than only in the markup.
+ */
+export function renderImage(b: Block): HTMLElement {
+ const fig = document.createElement('figure');
+ fig.className = 't-figure';
+ fig.dataset.id = b.id;
+ fig.dataset.kind = b.kind;
+ fig.dataset.atomic = '1';
+ const im = b.image;
+ if (!im) return fig;
+ if (im.align) fig.dataset.align = im.align;
+ const img = document.createElement('img');
+ img.src = im.src;
+ img.alt = im.alt ?? '';
+ if (im.w) img.style.width = `${Math.round(im.w * 100)}%`;
+ // PAGINATION MUST RE-RUN WHEN THE PICTURE ARRIVES. An image decodes
+ // asynchronously, so the pass that runs immediately after render measures it
+ // as one line of alt text. Measured: a 500px picture paginated as 2 pages
+ // before it decoded and 3 after, with the first break moving 836 → 560. And
+ // because print reproduces the editor's pagination exactly, that is a
+ // document that prints with the wrong breaks — silently, and only when it
+ // contains a picture.
+ //
+ // The renderer stays pure with respect to the document: it announces that the
+ // layout changed and does not know who is listening.
+ const relayout = () => fig.dispatchEvent(new CustomEvent('t-relayout', { bubbles: true }));
+ img.addEventListener('load', relayout, { once: true });
+ // An image that fails to load must not leave an invisible gap that
+ // pagination has already reserved space for.
+ img.addEventListener('error', () => { fig.dataset.broken = '1'; relayout(); }, { once: true });
+ fig.appendChild(img);
+ return fig;
}
-export function renderBlock(b: Block): HTMLElement {
+/**
+ * The document `renderBlock` styles a single block against, when the caller
+ * does not pass one explicitly.
+ *
+ * `renderBody` sets it on every pass, which is the common path; the one
+ * caller that renders a lone block WITHOUT the document in hand
+ * (editor.ts's live re-render of the block just typed in) still resolves
+ * named styles correctly because renderBody always ran at least once first —
+ * module state rather than a signature change on a function this module does
+ * not own the only caller of, mirroring layout.ts's own `painting` flag.
+ */
+let lastDoc: TypeDoc | undefined;
+
+export function renderBlock(b: Block, doc: TypeDoc | undefined = lastDoc): HTMLElement {
+ if (b.kind === 'image') return renderImage(b);
+ if (b.kind === 'embed') return renderEmbed(b);
+ if (b.kind === 'math') {
+ // A display formula is atomic: it has height and, once typeset, may hold no
+ // text node pagination can measure — so it carries data-atomic like a
+ // picture, and gets the same one-box treatment.
+ const el = document.createElement('div');
+ el.className = 't-mathblock';
+ el.dataset.id = b.id;
+ el.dataset.kind = b.kind;
+ el.dataset.atomic = '1';
+ el.dataset.tex = b.text;
+ el.innerHTML = displayMathHtml(b.text);
+ return el;
+ }
const el = document.createElement(TAG[b.kind]);
el.dataset.id = b.id;
el.dataset.kind = b.kind;
+ // A named style's typography arrives through a STYLESHEET keyed by this
+ // attribute (docstyles.ts ensureStyleSheet/styleSheetCss), never through
+ // this element's `style` attribute — that one belongs to layout.ts's
+ // `blockStyle` alone below, and layout.ts repaints it independently (its
+ // own MutationObserver) whenever the paper's children change, which a
+ // render always causes. Two mechanisms writing the SAME attribute would
+ // have the second one silently erase the first the next time that
+ // observer fired; the split is what keeps them from ever colliding.
+ const sid = doc ? activeStyleId(doc, b) : undefined;
+ if (sid) el.dataset.styleId = sid;
+ // The paragraph's OWN properties only — the document's defaults live on the
+ // paper, not on ten thousand copies of themselves. This is an INLINE style,
+ // so it beats the stylesheet rule above for any property both set: a
+ // block's own align/sb/sa/lh/ind wins over its named style, for free, by
+ // CSS specificity — no coordination between the two mechanisms required.
+ const st = blockStyle(b);
+ if (st) el.setAttribute('style', st);
el.innerHTML = blockHtml(b);
return el;
}
/** The whole body. Callers own the host; this replaces its contents. */
+/**
+ * A table, from its rows of cell blocks.
+ *
+ * Each <td> keeps its block's `data-id`, so everything that addresses a block —
+ * the caret, the redline, a comment — reaches a cell without knowing tables
+ * exist. A short last row is PADDED with empty cells rather than left ragged:
+ * the model may disagree with itself, but the rendered grid never should.
+ */
+export function renderTable(rows: Block[][], head: boolean): HTMLElement {
+ const table = document.createElement('table');
+ table.className = 't-table';
+ const cols = rows[0]?.length ?? 1;
+ const thead = head ? document.createElement('thead') : null;
+ const tbody = document.createElement('tbody');
+ rows.forEach((row, r) => {
+ const isHead = head && r === 0;
+ const tr = document.createElement('tr');
+ for (let c = 0; c < cols; c++) {
+ const b = row[c];
+ const cell = document.createElement(isHead ? 'th' : 'td');
+ if (b) {
+ cell.dataset.id = b.id;
+ cell.dataset.kind = b.kind;
+ cell.innerHTML = blockHtml(b);
+ } else {
+ cell.innerHTML = '<br>'; // padding for a short final row
+ cell.dataset.pad = '1';
+ }
+ tr.appendChild(cell);
+ }
+ (isHead ? thead! : tbody).appendChild(tr);
+ });
+ if (thead) table.appendChild(thead);
+ table.appendChild(tbody);
+ return table;
+}
+
export function renderBody(doc: TypeDoc, host: HTMLElement): void {
+ lastDoc = doc;
+ ensureStyleSheet(doc);
const frag = document.createDocumentFragment();
- for (const b of doc.body) frag.appendChild(renderBlock(b));
+ let cursor: Node = frag;
+ for (const tok of groupBlocks(doc.body)) {
+ if (tok.t === 'open') {
+ const list = document.createElement(tok.kind);
+ cursor.appendChild(list);
+ cursor = list;
+ } else if (tok.t === 'close') {
+ cursor = cursor.parentNode ?? frag;
+ } else if (tok.t === 'table') {
+ cursor.appendChild(renderTable(tok.rows, tok.head));
+ } else {
+ cursor.appendChild(renderBlock(tok.block, doc));
+ }
+ }
host.replaceChildren(frag);
numberNotes(host, doc);
+ numberXrefs(host, doc);
+ paintCitations(host, doc);
}
/**
@@ -72,7 +338,7 @@ export function numberNotes(host: HTMLElement, _doc: TypeDoc): string[] {
* nothing that has no place to go.
*/
export function readBlock(el: HTMLElement, prev: Block): Block {
- const { text, marks, atoms } = fromDom(el, isNoteAtom);
+ const { text, marks, atoms } = fromDom(el, el2 => isNoteAtom(el2) || isXrefAtom(el2) || isCiteAtom(el2));
const out: Block = { ...prev, id: el.dataset.id || prev.id, text };
const kind = el.dataset.kind as Block['kind'] | undefined;
if (kind && kind in TAG) out.kind = kind;
@@ -81,5 +347,9 @@ export function readBlock(el: HTMLElement, prev: Block): Block {
.map(a => ({ id: (a.el as HTMLElement).dataset.note!, at: a.at }))
.filter(n => n.id);
if (notes.length) out.notes = notes; else delete out.notes;
+ const refs = readXrefs(atoms);
+ if (refs.length) out.refs = refs; else delete out.refs;
+ const cites = readCiteAtoms(atoms);
+ if (cites.length) out.cites = cites; else delete out.cites;
return out;
}
diff --git a/type/src/review.css b/type/src/review.css
new file mode 100644
index 00000000..880e031a
--- /dev/null
+++ b/type/src/review.css
@@ -0,0 +1,48 @@
+/* SPDX-License-Identifier: MIT */
+/* Copyright (c) 2026 The Bento authors */
+
+/* review.ts — the compact nav bar in the Review tab, and the display-mode
+ CSS that makes "No markup" / "Original" a pure repaint. Variables reused
+ from styles.css's root palette (--ink/--muted/--line/--chrome-2/--accent),
+ never redeclared: a second copy would drift from the theme the moment
+ either side changed. */
+
+.t-trk-nav {
+ display: flex; align-items: center; gap: 4px;
+ margin-bottom: 8px;
+}
+.t-trk-icon {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 24px; height: 24px; padding: 0;
+ border: 1px solid var(--line); border-radius: 6px;
+ background: transparent; color: var(--ink);
+ cursor: pointer;
+}
+.t-trk-icon:hover { background: var(--chrome-2); }
+.t-trk-icon:active { background: var(--line); }
+.t-trk-count {
+ flex: 1 1 auto; text-align: center;
+ font-size: 11.5px; color: var(--muted);
+}
+/* the change the caret is on (or heading toward) — same "on" vocabulary
+ .t-card already uses elsewhere in this app, so it reads as one language */
+.t-card.on { border-color: var(--accent); }
+
+/* ─────────────────────────────────────────────────────── display modes
+ `<ins>`/`<del>` carry `.t-trk` (inline.ts openTag) wherever they render —
+ canvas, print, anywhere. These two classes on <html> are mutually
+ exclusive (review.ts applyTrackView) and never both present; 'all markup'
+ is the absence of either, which is why it needs no rule here at all —
+ .t-paper ins.t-trk / del.t-trk in styles.css already ARE that view. */
+
+/* No markup: reads as if every change were already accepted. */
+:root.t-track-final .t-paper ins.t-trk {
+ text-decoration: none; color: inherit; opacity: 1;
+}
+:root.t-track-final .t-paper del.t-trk { display: none; }
+
+/* Original: reads as if every change were rejected. */
+:root.t-track-original .t-paper del.t-trk {
+ text-decoration: none; color: inherit; opacity: 1;
+}
+:root.t-track-original .t-paper ins.t-trk { display: none; }
diff --git a/type/src/review.ts b/type/src/review.ts
new file mode 100644
index 00000000..f81b8c6d
--- /dev/null
+++ b/type/src/review.ts
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE REVIEW EXPERIENCE — turning the marks track.ts records into something a
+// reviewer can actually get through.
+//
+// track.ts proved the engine: a tracked change is a mark, accepting or
+// rejecting one is a pure function, and a document with eighty of them still
+// round-trips both ways. None of that is usable on an eighty-change document
+// without three more things, and this file is exactly those three:
+//
+// 1. NAVIGATION. Next / previous change, from wherever the caret is —
+// `changeAt`/`stepChange` in track.ts do the arithmetic; this file wires
+// it to the caret, the keyboard and the scroll position.
+// 2. ACCEPT/REJECT AT THE CARET. Not only from a card in a list — a
+// reviewer reads top to bottom and decides as they go.
+// 3. DISPLAY MODE. All markup (today's default), No markup (as if every
+// change were accepted) and Original (as if every change were
+// rejected). A VIEWER preference, in localStorage — never the document,
+// for the exact reason comments.ts keeps `commentsHidden` out of it: how
+// a person chooses to read a document is not a term of the agreement.
+// It is CSS only: `<ins>`/`<del>` already carry a `.t-trk` class
+// (inline.ts openTag), so a class on <html> is enough to make either
+// kind read as plain text or vanish. Nothing here calls `resolve` —
+// that is the one function that is allowed to touch the model, and nav,
+// accept-at-caret and display mode all leave it to the reviewer.
+//
+// The compact review surface (requirement 4) replaces the flat list
+// `buildTracked` used to paint directly in main.ts — it is now a PanelSpec
+// mounted into the same `reviewPanel` host, so main.ts owns none of this.
+
+import './review.css';
+import { registerPanel, registerKey, registerSelection, registerReady, type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+import {
+ changes, resolve, resolveAll, changeAt, stepChange, parseTrackView,
+ type Change, type TrackView,
+} from './track.ts';
+
+// ═══════════════════════════════════════════════════════ display mode
+
+const VIEW_KEY = 'bento-type-track-view';
+
+/** The remembered choice. Never read the document for this — see the header. */
+export const trackView = (): TrackView => {
+ try { return parseTrackView(localStorage.getItem(VIEW_KEY)); } catch { return 'all'; }
+};
+
+export function setTrackView(mode: TrackView): void {
+ try {
+ if (mode === 'all') localStorage.removeItem(VIEW_KEY);
+ else localStorage.setItem(VIEW_KEY, mode);
+ } catch { /* private mode — the class below still applies for this session */ }
+ applyTrackView();
+}
+
+/**
+ * Paint the choice as two classes on <html>, mutually exclusive.
+ *
+ * 'final' hides `del` and strips `ins` styling — a document that reads as if
+ * every change were already accepted. 'original' is the mirror: hides `ins`,
+ * strips `del` styling — as if every change were rejected. 'all' (the
+ * default) needs no class: today's `.t-trk` styling in styles.css already IS
+ * "show every mark", which is why that file needed no edit for this feature.
+ */
+export function applyTrackView(): void {
+ const v = trackView();
+ document.documentElement.classList.toggle('t-track-final', v === 'final');
+ document.documentElement.classList.toggle('t-track-original', v === 'original');
+}
+
+registerReady(() => applyTrackView());
+
+// ═══════════════════════════════════════════════════════════ navigation
+
+/**
+ * The "current" change for display and for accept/reject-at-caret: the one
+ * the caret sits inside, or — if the caret is not on one — the next one
+ * coming up, so "3 of 17" means something even while just reading.
+ */
+function currentIndex(list: readonly Change[], doc: Parameters<typeof stepChange>[0],
+ caret: { id: string; at: number } | null): number | null {
+ if (!list.length || !caret) return null;
+ const at = changeAt(list, caret.id, caret.at);
+ if (at >= 0) return at;
+ return stepChange(doc, list, caret.id, caret.at, 1);
+}
+
+/** Select the change's range and scroll it into view — nav's other half. */
+function gotoChange(ctx: FeatureContext, ch: Change): void {
+ ctx.editor.setCaret({ id: ch.block, at: ch.mark.from, to: ch.mark.to });
+ ctx.editor.host.querySelector<HTMLElement>(`[data-id="${CSS.escape(ch.block)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ repaintSurface?.();
+}
+
+function step(ctx: FeatureContext, dir: 1 | -1): void {
+ const list = changes(ctx.store.doc);
+ if (!list.length) { ctx.toast(t('No tracked changes')); return; }
+ const caret = ctx.editor.caret();
+ const idx = stepChange(ctx.store.doc, list, caret?.id ?? null, caret?.at ?? 0, dir);
+ if (idx === null) return;
+ gotoChange(ctx, list[idx]);
+}
+
+/** Accept or reject whichever change the caret is on (or, failing that, next up). */
+function resolveCurrent(ctx: FeatureContext, accept: boolean): void {
+ const list = changes(ctx.store.doc);
+ if (!list.length) { ctx.toast(t('No tracked changes')); return; }
+ const caret = ctx.editor.caret();
+ const idx = currentIndex(list, ctx.store.doc, caret);
+ if (idx === null) { ctx.toast(t('Put the caret on a tracked change first')); return; }
+ const ch = list[idx];
+ ctx.store.commit(d => {
+ const i = d.body.findIndex(x => x.id === ch.block);
+ if (i >= 0) d.body[i] = resolve(d.body[i], ch.mark, accept);
+ });
+ ctx.refresh();
+ // Land on whatever is next, Word-style, so a reviewer can keep going
+ // without reaching for the mouse. `ch.mark.from` is still a valid position
+ // in the SAME block: resolving only ever changes text at or after it.
+ const after = changes(ctx.store.doc);
+ const nextIdx = stepChange(ctx.store.doc, after, ch.block, ch.mark.from, 1);
+ if (nextIdx !== null) gotoChange(ctx, after[nextIdx]);
+ else repaintSurface?.();
+}
+
+// mod+alt — the same modifier xref.ts already uses for a shortcut with no
+// menu-driven equivalent (⌥⌘R), and Cmd/Ctrl being held stops macOS composing
+// Option into an accented character, so this is safe on both platforms without
+// blockgrip's ctrl/alt PLATFORM SPLIT. That split exists there because Word
+// genuinely binds "move this paragraph" to different keys per platform; there
+// is no such prior art for stepping through tracked changes, so one binding
+// serves both rather than inventing a difference nobody asked for.
+registerKey({ key: 'n', mod: true, alt: true, run: ctx => step(ctx, 1) });
+registerKey({ key: 'p', mod: true, alt: true, run: ctx => step(ctx, -1) });
+registerKey({ key: 'a', mod: true, alt: true, run: ctx => resolveCurrent(ctx, true) });
+registerKey({ key: 'd', mod: true, alt: true, run: ctx => resolveCurrent(ctx, false) });
+
+// ═══════════════════════════════════════════════════ the compact surface
+
+const esc = (s: string) => s.replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]!));
+
+const NEXT_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="none" '
+ + 'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">'
+ + '<polyline points="9 6 15 12 9 18"/></svg>';
+const PREV_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="none" '
+ + 'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">'
+ + '<polyline points="15 6 9 12 15 18"/></svg>';
+const CHECK_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="none" '
+ + 'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">'
+ + '<polyline points="20 6 9 17 4 12"/></svg>';
+const CROSS_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="none" '
+ + 'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">'
+ + '<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
+
+function iconBtn(icon: string, title: string, run: () => void): HTMLButtonElement {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 't-trk-icon';
+ b.innerHTML = icon;
+ b.title = title;
+ b.setAttribute('aria-label', title);
+ b.addEventListener('click', run);
+ return b;
+}
+
+let repaintSurface: (() => void) | null = null;
+
+function paintSurface(host: HTMLElement, ctx: FeatureContext): void {
+ host.replaceChildren();
+ const doc = ctx.store.doc;
+ const list = changes(doc);
+
+ if (!list.length) {
+ const hint = document.createElement('p');
+ hint.className = 't-hint';
+ hint.textContent = doc.track
+ ? t('Tracking is on. Edits you make from now on are recorded here.')
+ : t('Turn on "Track changes" in the properties panel, or take a Snapshot from ⋯ and use Review changes.');
+ host.appendChild(hint);
+ return;
+ }
+
+ const caret = ctx.editor.caret();
+ const idx = currentIndex(list, doc, caret);
+
+ // ---- the compact surface: current position, step, resolve
+ const bar = document.createElement('div');
+ bar.className = 't-trk-nav';
+ bar.appendChild(iconBtn(PREV_ICON, t('Previous change (⌘⌥P)'), () => step(ctx, -1)));
+ const count = document.createElement('span');
+ count.className = 't-trk-count';
+ count.textContent = idx !== null
+ ? t('{n} of {m}', { n: String(idx + 1), m: String(list.length) })
+ : (list.length === 1 ? t('1 change') : t('{m} changes', { m: String(list.length) }));
+ bar.appendChild(count);
+ bar.appendChild(iconBtn(NEXT_ICON, t('Next change (⌘⌥N)'), () => step(ctx, 1)));
+ bar.appendChild(iconBtn(CHECK_ICON, t('Accept (⌘⌥A)'), () => resolveCurrent(ctx, true)));
+ bar.appendChild(iconBtn(CROSS_ICON, t('Reject (⌘⌥D)'), () => resolveCurrent(ctx, false)));
+ host.appendChild(bar);
+
+ const all = document.createElement('div');
+ all.className = 't-trk-row';
+ for (const [label, accept] of [[t('Accept all'), true], [t('Reject all'), false]] as const) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = label;
+ b.addEventListener('click', () => {
+ ctx.store.commit(d => resolveAll(d, accept));
+ ctx.refresh();
+ });
+ all.appendChild(b);
+ }
+ host.appendChild(all);
+
+ for (let i = 0; i < list.length; i++) {
+ const ch = list[i];
+ const card = document.createElement('div');
+ card.className = 't-card' + (i === idx ? ' on' : '');
+ const who = document.createElement('div');
+ who.className = 'who';
+ who.textContent = `${ch.mark.by ?? t('Someone')} · ${ch.mark.t === 'ins' ? t('inserted') : t('deleted')}`;
+ const what = document.createElement('div');
+ what.className = 'what';
+ // the CHANGED TEXT ONLY, in the same ins/del styling the page uses, so the
+ // card and the paragraph it points at read as the same thing
+ what.innerHTML = ch.mark.t === 'ins' ? `<ins>${esc(ch.text)}</ins>` : `<del>${esc(ch.text)}</del>`;
+ card.append(who, what);
+ const row = document.createElement('div');
+ row.className = 't-trk-row';
+ for (const [label, accept] of [[t('Accept'), true], [t('Reject'), false]] as const) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = label;
+ b.addEventListener('click', e => {
+ e.stopPropagation();
+ ctx.store.commit(d => {
+ const bi = d.body.findIndex(x => x.id === ch.block);
+ if (bi >= 0) d.body[bi] = resolve(d.body[bi], ch.mark, accept);
+ });
+ ctx.refresh();
+ });
+ row.appendChild(b);
+ }
+ card.appendChild(row);
+ card.addEventListener('click', e => {
+ if ((e.target as HTMLElement).tagName === 'BUTTON') return;
+ gotoChange(ctx, ch);
+ });
+ host.appendChild(card);
+ }
+}
+
+registerPanel({
+ id: 'trackedChanges',
+ get label() { return t('Tracked changes'); },
+ // a SECTION of the Review tab, beside comments and signatures — the same
+ // reasoning comments.ts gives for its own `host`
+ host: 'reviewPanel',
+ order: 20,
+ mount(host, ctx) {
+ repaintSurface = () => paintSurface(host, ctx);
+ repaintSurface();
+ },
+ update(host, ctx) { paintSurface(host, ctx); },
+});
+
+registerSelection(() => repaintSurface?.());
+
+// ═══════════════════════════════════════════════════ the display-mode control
+//
+// A VALUE, so it lives on the right — the panel's own rule (features.ts
+// PanelSpec.side, and props.ts's header explains why). It cannot join
+// props.ts's `documentSection` (this app's boundary keeps that file to one
+// owner), so it is its OWN small right-hand panel, stacked below Properties.
+// Reusing the panel's own class names (`t-section`, `t-sec-body`, `t-row`) so
+// it reads as one more section of the same panel rather than a different
+// control entirely — styles.css already defines them, generically, for
+// exactly this.
+
+function buildViewPanel(host: HTMLElement, ctx: FeatureContext): void {
+ host.replaceChildren();
+ const head = document.createElement('div');
+ head.className = 't-section';
+ head.textContent = t('Review');
+ const body = document.createElement('div');
+ body.className = 't-sec-body';
+ host.append(head, body);
+
+ const row = document.createElement('div');
+ row.className = 't-row';
+ const label = document.createElement('span');
+ label.textContent = t('Display');
+ const sel = document.createElement('select');
+ const OPTIONS: Array<[TrackView, string]> = [
+ ['all', t('All markup')],
+ ['final', t('No markup')],
+ ['original', t('Original')],
+ ];
+ for (const [value, text] of OPTIONS) {
+ const o = document.createElement('option');
+ o.value = value;
+ o.textContent = text;
+ if (value === trackView()) o.selected = true;
+ sel.appendChild(o);
+ }
+ sel.addEventListener('change', () => {
+ setTrackView(sel.value as TrackView);
+ // Hiding/un-hiding `<ins>`/`<del>` changes the flow's height, so the pages
+ // need re-measuring — the same reason a picture finishing decoding does.
+ ctx.refresh();
+ });
+ row.append(label, sel);
+ body.appendChild(row);
+
+ const note = document.createElement('p');
+ note.className = 't-note';
+ note.textContent = t('How you view a document, not a change to it — nothing here is saved into the file.');
+ body.appendChild(note);
+}
+
+registerPanel({
+ id: 'trackView',
+ get label() { return t('Review'); },
+ side: 'right',
+ // below Properties (order 10 in props.ts) — always visible, not contextual
+ // on the selection, which is right for a VIEWER preference about the whole
+ // document rather than a fact about whatever the caret is in
+ order: 90,
+ mount(host, ctx) { buildViewPanel(host, ctx); },
+});
diff --git a/type/src/seltoolbar.ts b/type/src/seltoolbar.ts
new file mode 100644
index 00000000..b30659c0
--- /dev/null
+++ b/type/src/seltoolbar.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE SELECTION TOOLBAR — formatting where the words are.
+//
+// Select text and a small bar appears over it: the character marks, a link, a
+// comment. What Notion, Medium and Google Docs all do, and what a word
+// processor wants most, because formatting is a thing you do TO a selection
+// and the selection is where your eyes already are.
+//
+// It renders MARK_TOOLS and the registered link/comment tools rather than
+// listing buttons of its own — the same set the properties panel shows. Adding
+// a sixth mark means editing one array.
+//
+// THE ONE RULE THAT MAKES IT WORK: never take the selection away. Every button
+// preventDefaults on mousedown, because a focus change collapses the range and
+// the bar would act on nothing — the same reason the toolbar buttons do it.
+
+import { t } from './i18n.ts';
+import { registerReady, tools, type FeatureContext } from './features.ts';
+import { MARK_TOOLS } from './marks.ts';
+import type { MarkType } from './inline.ts';
+
+/** Registered tools that act on a SELECTION. Find does not; it acts on the document. */
+const SELECTION_TOOLS = ['link', 'comment'];
+
+let bar: HTMLElement | null = null;
+let pointerDown = false;
+
+/**
+ * Run after the current event has settled.
+ *
+ * A TIMER, not requestAnimationFrame. What is needed here is "once the
+ * selection has finished changing", not "on the next painted frame" — and rAF
+ * does not fire at all while the document is hidden, so on a background tab
+ * the bar would queue a callback that never ran and then appear, stale, at
+ * whatever the selection used to be when the tab came back. The timer is both
+ * the more honest description of the wait and the one that cannot get stuck.
+ */
+const soon = (fn: () => void) => { setTimeout(fn, 0); };
+
+const paperEl = () => document.getElementById('paper');
+
+/** Is the selection a real range inside the document? */
+function selectionRange(): Range | null {
+ const sel = getSelection();
+ if (!sel || !sel.rangeCount || sel.isCollapsed) return null;
+ const r = sel.getRangeAt(0);
+ const paper = paperEl();
+ if (!paper || !paper.contains(r.commonAncestorContainer)) return null;
+ if (!String(sel).trim()) return null; // a whitespace-only drag
+ return r;
+}
+
+function hide(): void {
+ bar?.remove();
+ bar = null;
+}
+
+function build(ctx: FeatureContext): HTMLElement {
+ const el = document.createElement('div');
+ el.className = 't-selbar';
+ // never captured by a save — kernel save.ts strips marked nodes from the clone
+ el.setAttribute('data-bento-transient', '');
+ el.setAttribute('role', 'toolbar');
+ el.setAttribute('aria-label', t('Formatting'));
+
+ const active = ctx.editor.activeMarks() as Set<string>;
+ for (const m of MARK_TOOLS) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 't-selbtn';
+ b.innerHTML = m.icon;
+ b.title = m.title();
+ b.setAttribute('aria-label', m.title());
+ b.setAttribute('aria-pressed', String(active.has(m.t)));
+ b.classList.toggle('on', active.has(m.t));
+ // mousedown, NOT click: a focus change collapses the selection, and the
+ // bar would then format nothing.
+ b.addEventListener('mousedown', e => e.preventDefault());
+ b.addEventListener('click', e => {
+ e.stopPropagation();
+ // NO ctx.refresh() here. editor.toggle already re-renders the block and
+ // restores the selection it acted on, and then fires onChange, which is
+ // what schedules re-pagination. Calling refresh() on top re-rendered the
+ // body a second time and destroyed the restored range — the selection
+ // vanished, the bar went with it, and a second click could not reach the
+ // words the first one had just formatted. The properties panel's toggles
+ // never called it either; this was mine.
+ ctx.editor.toggle(m.t as MarkType);
+ // re-place it: the block was re-rendered, so the old rects are stale
+ soon(() => show(ctx));
+ });
+ el.appendChild(b);
+ }
+
+ const rest = [...tools('format'), ...tools('review')].filter(s => SELECTION_TOOLS.includes(s.id));
+ if (rest.length) {
+ const sep = document.createElement('span');
+ sep.className = 't-selsep';
+ el.appendChild(sep);
+ for (const spec of rest) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 't-selbtn';
+ b.innerHTML = spec.icon;
+ const title = typeof spec.title === 'function' ? spec.title() : spec.title;
+ b.title = title;
+ b.setAttribute('aria-label', title);
+ b.addEventListener('mousedown', e => e.preventDefault());
+ b.addEventListener('click', e => { e.stopPropagation(); hide(); spec.run(ctx); });
+ el.appendChild(b);
+ }
+ }
+ return el;
+}
+
+/** Put the bar above the selection, or below it when there is no room. */
+function place(el: HTMLElement, r: Range): void {
+ const rect = r.getBoundingClientRect();
+ if (!rect.width && !rect.height) { hide(); return; }
+ const w = el.offsetWidth, h = el.offsetHeight;
+ const GAP = 9;
+
+ let top = rect.top + window.scrollY - h - GAP;
+ // A selection at the very top of the viewport would put the bar off-screen,
+ // so it flips under the text rather than being clipped.
+ if (rect.top < h + GAP + 4) top = rect.bottom + window.scrollY + GAP;
+
+ let left = rect.left + window.scrollX + rect.width / 2 - w / 2;
+ const min = window.scrollX + 8;
+ const max = window.scrollX + document.documentElement.clientWidth - w - 8;
+ left = Math.max(min, Math.min(left, max));
+
+ el.style.top = `${Math.round(top)}px`;
+ el.style.insetInlineStart = `${Math.round(left)}px`;
+}
+
+function show(ctx: FeatureContext): void {
+ const r = selectionRange();
+ if (!r) { hide(); return; }
+ hide();
+ bar = build(ctx);
+ document.body.appendChild(bar);
+ place(bar, r);
+}
+
+registerReady(ctx => {
+ // While the mouse is down the selection is still being dragged out, and a
+ // bar that tracked it would flicker under the cursor and land in the way of
+ // the gesture that is creating it.
+ document.addEventListener('pointerdown', () => { pointerDown = true; hide(); }, true);
+ document.addEventListener('pointerup', () => {
+ pointerDown = false;
+ soon(() => show(ctx));
+ }, true);
+
+ document.addEventListener('selectionchange', () => {
+ if (pointerDown) return;
+ soon(() => show(ctx));
+ });
+
+ // Typing dismisses it: the selection it described is gone the moment a key
+ // replaces it.
+ paperEl()?.addEventListener('beforeinput', hide);
+ document.addEventListener('keydown', e => {
+ if (e.key === 'Escape') hide();
+ });
+
+ // Keep it with the words when the page moves under it.
+ const reflow = () => { if (bar) { const r = selectionRange(); if (r) place(bar, r); else hide(); } };
+ window.addEventListener('scroll', reflow, true);
+ window.addEventListener('resize', reflow);
+});
diff --git a/type/src/styles.css b/type/src/styles.css
index 94840128..6cdb25a9 100644
--- a/type/src/styles.css
+++ b/type/src/styles.css
@@ -26,12 +26,27 @@
--paper-ink-2: #3a3d44;
--paper-rule: #c3cad4;
--paper-link-underline: #a9bcd8;
+ /* Tracked changes are PAPER ink, so they sit in the unthemed block with the
+ rest of it. The page is white in dark mode — it is paper — and a tracked
+ insertion that lightened with the chrome would be the one thing on the
+ sheet that changed colour with a preference. It also means the screen and
+ the print are the same ink, which is what a signed-off redline needs. */
+ --paper-trk: #1a6b4a;
+ --paper-trk-bg: #eaf3ef;
+ --paper-trk-del: #a3312a;
/* geometry */
--radius: 10px;
--page-w: 816px; --page-h: 1056px;
--mar-x: 104px; --mar-t: 104px; --mar-b: 104px;
--gutter: 250px;
+
+ /* find highlights — they sit ON the page, so like --paper they do NOT theme:
+ a match must look the same to the person proofing at midnight as it will
+ when the page is printed. */
+ --find-hit: #ffe9a8;
+ --find-cur: #f7a600;
+ --find-ink: #1a1a1a;
}
/* LIGHT — the suite's shared palette, character for character with
@@ -86,7 +101,43 @@ html, body {
overscroll-behavior: none;
}
#app { display: grid; grid-template-rows: auto 1fr; height: 100vh; overflow: hidden; }
-.t-main { display: grid; grid-template-columns: 250px 1fr; overflow: hidden; }
+/* THREE columns, the suite's arrangement: navigation, the document, and the
+ properties of what is selected. slides and dash both do this and say so —
+ two Bento apps that lay themselves out differently read as two products. */
+.t-main { display: grid; grid-template-columns: 250px minmax(0, 1fr) 250px; overflow: hidden; }
+/* The paper is a FIXED width — it is paper — so the middle column can be too
+ narrow for it. Never clip: scroll. Measured at 1120px with both panels open,
+ the column was 620px against a 1066px page and the page was cut off. */
+.t-scroll { overflow-x: auto; }
+.t-main.t-side-off { grid-template-columns: 0 1fr 250px; }
+.t-main.t-props-off { grid-template-columns: 250px 1fr 0; }
+.t-main.t-side-off.t-props-off { grid-template-columns: 0 1fr 0; }
+.t-props {
+ background: var(--chrome); border-inline-start: 1px solid var(--line);
+ overflow: auto; min-width: 0;
+}
+.t-props .t-panel { display: block; }
+.t-props .t-panel[hidden] { display: none; }
+/* the house geometry: 11px uppercase section headers, copied deliberately */
+.t-section {
+ font-size: 11px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: .07em; color: var(--muted);
+ margin: 14px 0 6px; padding-top: 10px; border-top: 1px solid var(--line);
+}
+.t-props > .t-panel > :first-child { border-top: 0; padding-top: 0; margin-top: 0; }
+.t-props-empty { padding: 14px 12px; font-size: 12px; color: var(--muted); }
+/* the panel's own furniture — the suite's metrics: 12.5px rows, the control
+ right-aligned at a fixed width, as slides and dash both do */
+.t-sec-body { padding: 0 0 4px; }
+.t-props .t-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
+.t-props .t-row > span:first-child { flex: 1 1 auto; font-size: 12.5px; color: var(--muted); }
+.t-props .t-row > :last-child { flex: 0 0 auto; }
+.t-toggles { display: flex; gap: 2px; margin: 6px 0; flex-wrap: wrap; }
+.t-toggles .t-btn { min-width: 30px; min-height: 28px; padding: 4px 7px; }
+.t-field { width: 68px; font: inherit; font-size: 12.5px; color: var(--ink);
+ background: var(--field); border: 1px solid var(--line); border-radius: 7px; padding: 4px 6px; }
+.t-field-wide { width: 130px; }
+.t-props .t-note { margin: 4px 0 8px; }
.t-side { background: var(--chrome); border-inline-end: 1px solid var(--line); overflow: auto; }
.t-tabs { display: flex; position: sticky; top: 0; z-index: 5;
background: var(--chrome); border-bottom: 1px solid var(--line); }
@@ -96,6 +147,29 @@ html, body {
.t-tabs button.on { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); font-weight: 600; }
.t-panel { display: none; padding: 10px 12px; }
.t-panel.on { display: block; }
+
+/* The Navigate tab's segmented control. Quieter than the tabs above it on
+ purpose: these are four views of one question, and giving them the same
+ weight as Navigate/Review/Sources would read as seven tabs again. */
+.t-seg { display: flex; gap: 2px; margin-bottom: 9px; padding: 2px;
+ background: var(--chrome-2); border-radius: 7px; }
+.t-seg button { flex: 1; border: 0; border-radius: 5px; background: transparent;
+ color: var(--muted); padding: 4px 2px; font: inherit; font-size: 11px;
+ cursor: pointer; white-space: nowrap; }
+.t-seg button:hover { color: var(--ink-2); }
+.t-seg button.on { background: var(--chrome); color: var(--ink); font-weight: 600; }
+.t-view { display: none; }
+.t-view.on { display: block; }
+.t-outline a.pagerow .pg { float: none; margin-inline-end: 8px; }
+
+/* Review stacks three sections in one tab, so each says what it is. Without
+ the rule a comment card and a tracked change sat flush against each other
+ and read as one list of two unrelated things. */
+.t-side .t-sub { font-size: 10.5px; letter-spacing: .06em; text-transform: uppercase;
+ color: var(--muted); margin: 14px 0 7px; }
+.t-side .t-sub:first-child { margin-top: 0; }
+.t-side #reviewPanel:not(:empty), .t-side #sigsPanel:not(:empty) {
+ border-top: 1px solid var(--line); margin-top: 12px; padding-top: 10px; }
.t-hint { color: var(--muted); font-size: 11.5px; line-height: 1.55; }
.t-outline a { display: block; color: var(--ink-2); text-decoration: none; padding: 3px 6px;
border-radius: 4px; font-size: 12px; line-height: 1.35; cursor: pointer; }
@@ -119,50 +193,150 @@ html, body {
word-break: break-all; margin-top: 3px; }
.t-ok { color: var(--good); } .t-bad { color: var(--bad); } .t-warn { color: var(--warnc); }
-/* ————— toolbar ————— */
+/* ————— toolbar —————
+ ONE ROW, and the same furniture every other app in the suite puts there:
+ the mark (which is also the way into About), a panel toggle, the document
+ title, a status line, then the tools. It was two stacked rows of text
+ buttons, which is the single loudest way this app read as a different
+ product. Class names are type's; the STRUCTURE and the metrics are shared
+ with slides/src/styles.css and spaces/src/styles.css deliberately. */
.t-bar {
- display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
- padding: 8px 14px;
- background: var(--chrome);
- border-bottom: 1px solid var(--line);
+ display: flex; align-items: center; gap: 4px;
+ padding: 8px max(12px, env(safe-area-inset-right)) 8px max(12px, env(safe-area-inset-left));
+ background: var(--chrome); border-bottom: 1px solid var(--line);
+ flex: 0 0 auto;
+ /* A grid item's automatic minimum size is its MIN-CONTENT width, so without
+ this the bar simply refused to be narrower than its buttons (measured:
+ 1135px inside a 1000px window) and #app clipped the overflow. Its own
+ scrollWidth then equalled its clientWidth, so fitBar's overflow test could
+ never fire and the tiers never engaged — the bar looked fine to the code
+ and was cut off on screen. */
+ min-width: 0;
}
-.t-brand {
- font-weight: 600; color: var(--ink); margin-inline-end: 6px;
- letter-spacing: .01em; white-space: nowrap;
+
+/* the suite's mark — identical geometry and colours in all three apps */
+.t-mark {
+ display: inline-flex; align-items: center; gap: 7px;
+ font: inherit; font-weight: 700; font-size: 14px; letter-spacing: -0.01em;
+ white-space: nowrap; padding: 4px 7px 4px 4px; user-select: none;
+ background: transparent; border: 1px solid transparent; border-radius: 8px;
+ color: var(--ink); cursor: pointer;
}
-.t-brand small { color: var(--muted); font-weight: 400; margin-inline-start: 4px; }
+.t-mark:hover { background: var(--chrome-2); }
+.t-mark-svg { display: block; flex: 0 0 auto; }
+.t-mark-word span { color: #FF9E8A; }
-.t-bar button {
- display: inline-flex; align-items: center; gap: 6px;
- font: inherit; font-size: 13px;
- color: var(--ink-2);
- background: transparent;
- border: 1px solid transparent;
- border-radius: 8px;
- padding: 6px 9px;
- cursor: pointer;
- white-space: nowrap;
+.t-doctitle {
+ /* Sized, not greedy — the right group's margin-inline-start:auto is the
+ spacer, so a long title cannot push the tools off the bar. */
+ flex: 0 1 260px;
+ /* A hard floor, not `min-width: 0`. Without it flexbox has nothing to stop
+ shrinking at and will crush the title toward zero before it ever counts
+ as "overflow" (measured: 16px wide, narrower than a single glyph) — the
+ t-bar-tight/-fold flex-basis steps below are what SHOULD do the shrinking;
+ this is the backstop for whatever gap remains, and the last width fitBar's
+ tooTight() check treats as still-readable before it gives up and folds
+ the title away entirely (see .t-bar-micro). */
+ min-width: 72px;
+ font: inherit; font-size: 14px; color: var(--ink);
+ background: transparent; border: 1px solid transparent; border-radius: 8px;
+ padding: 5px 8px; text-overflow: ellipsis;
}
-.t-bar button:hover { background: var(--chrome-2); }
-.t-bar button:active { background: var(--line); }
-.t-bar button.on {
- background: var(--accent); border-color: var(--accent);
- color: var(--accent-ink); font-weight: 600;
+.t-doctitle:hover { background: var(--chrome-2); }
+.t-doctitle:focus { background: var(--field); border-color: var(--blue); outline: none; }
+
+.t-status {
+ font-size: 12px; color: var(--muted); white-space: nowrap;
+ overflow: hidden; text-overflow: ellipsis; min-width: 0;
}
-.t-bar button.primary { background: var(--ink); color: var(--chrome); padding: 6px 14px; }
-.t-bar button.primary:hover { background: var(--ink-2); }
-.t-bar select {
+
+.t-right { margin-inline-start: auto; display: flex; align-items: center; gap: 4px; }
+.t-group { display: flex; align-items: center; gap: 2px; }
+.t-group + .t-group { margin-inline-start: 6px; padding-inline-start: 6px;
+ border-inline-start: 1px solid var(--line); }
+
+.t-btn {
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;
+ font: inherit; font-size: 13px; color: var(--ink-2);
+ background: transparent; border: 1px solid transparent; border-radius: 8px;
+ padding: 6px 9px; min-width: 32px; min-height: 32px;
+ cursor: pointer; white-space: nowrap;
+}
+.t-btn:hover { background: var(--chrome-2); }
+.t-btn:active { background: var(--line); }
+.t-btn.on { background: var(--accent); border-color: var(--accent);
+ color: var(--accent-ink); font-weight: 600; }
+.t-primary { background: var(--ink); color: var(--chrome); padding: 6px 12px; }
+.t-primary:hover { background: var(--ink-2); }
+
+.t-select {
font: inherit; font-size: 13px; color: var(--ink-2);
background: var(--field); border: 1px solid var(--line);
border-radius: 8px; padding: 5px 8px; cursor: pointer;
}
-.t-sep { width: 1px; height: 20px; background: var(--line); margin: 0 5px; }
-.t-spacer { flex: 1; }
-.t-stat {
- color: var(--muted);
- font: 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
- white-space: nowrap;
+
+/* the ⋯ menu — secondary actions, off the bar but one click away */
+.t-menuwrap { position: relative; }
+.t-menu {
+ position: absolute; inset-inline-end: 0; top: calc(100% + 6px); z-index: 60;
+ min-width: 200px; padding: 5px;
+ background: var(--field); border: 1px solid var(--line); border-radius: 10px;
+ box-shadow: 0 12px 32px rgb(20 30 45 / .16), 0 2px 6px rgb(20 30 45 / .08);
}
+.t-menu button {
+ display: flex; align-items: center; gap: 9px; width: 100%;
+ font: inherit; font-size: 13px; color: var(--ink-2); text-align: start;
+ background: transparent; border: 0; border-radius: 7px;
+ padding: 7px 9px; cursor: pointer;
+}
+.t-menu button:hover { background: var(--chrome-2); }
+.t-menu-sep { height: 1px; background: var(--line); margin: 5px 4px; }
+/* A bar button (`.t-btn`) reparented into the ⋯ menu at the fold tier
+ (main.ts setBarFolded) is still a `.t-btn` — its OWN rules (inline-flex,
+ fixed min-width) would make it a stray icon chip in a list of full-width
+ rows. `.t-menu button`'s selector is more specific (0,1,1 vs 0,1,0) so it
+ wins the conflicting properties without an !important war; this just
+ covers the one property that selector doesn't touch. */
+.t-menu .t-btn { width: 100%; justify-content: flex-start; }
+/* Icon-only bar buttons lean on `title` for their name; a menu row has no
+ hover to reveal that, so it needs visible text. `.t-mlbl` (main.ts
+ toolButton) is the fallback label those buttons carry for exactly this
+ case — invisible while the button lives in the bar, shown only once it is
+ actually inside a menu, so it costs nothing until it is needed. */
+.t-mlbl { display: none; }
+.t-menu .t-mlbl { display: inline; }
+
+/* RESPONSIVE, the suite's way: hide TEXT, never scroll the bar — and size it
+ by MEASURING, not by width breakpoints (slides/src/editor/editor.ts
+ fitTopbar explains why at length: browser zoom, OS text scaling and wider
+ translations all change how much room the same buttons need at the same
+ viewport width, and each one clipped the end of the bar).
+ The tiers are applied by fitBar() in main.ts, widest first. */
+.t-bar-compact .t-lbl { display: none; }
+/* `#moreMenu` is DOM-nested inside `.t-bar` (`.t-menuwrap` sits in `.t-right`),
+ so the rule above also matched every `.t-lbl` INSIDE the ⋯ menu — meaning
+ Snapshot/Review/Sign/Print/About (main.ts, built with the same `label()`
+ helper as the bar's own buttons) silently lost their text the moment the
+ bar reached the compact tier, even though a menu row never participates in
+ the bar's width squeeze and its text was never optional. Same fix as
+ `.t-mlbl` above, for the label spans that already existed before it; same
+ specificity as the rule it corrects, so it only wins by coming after it. */
+.t-menu .t-lbl { display: inline; }
+.t-bar-compact .t-primary { padding: 6px 9px; }
+.t-bar-tight .t-mark-word { display: none; }
+.t-bar-tight .t-doctitle { flex-basis: 160px; }
+.t-bar-fold .t-status { display: none; }
+.t-bar-fold .t-doctitle { flex-basis: 110px; }
+.t-bar-fold .t-group + .t-group { margin-inline-start: 2px; padding-inline-start: 2px; }
+/* Everything the fold tier could move into ⋯ (main.ts FOLD_GROUPS) is gone
+ from the bar by the time this matters, so an emptied `.t-group` host is
+ left with no children — collapse it rather than let its `gap` reserve
+ space for buttons that are no longer there. */
+.t-bar-fold .t-group:empty { display: none; }
+/* The last resort: even folded, a bar can be too narrow for a title that has
+ nowhere left to shrink. Drop it cleanly instead of crushing it below one
+ legible character — the window title and the About dialog still show it. */
+.t-bar-micro .t-doctitle { display: none; }
/* ————— the page ————— */
.t-scroll {
@@ -182,7 +356,9 @@ html, body {
border-radius: 2px;
position: relative; z-index: 1;
color: var(--paper-ink);
- font: 17px/1.62 "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
+ /* The document's own typeface. The fallback is the historical default, so a
+ file that says nothing about type is byte-for-byte unchanged. */
+ font: var(--doc-size, 17px)/1.62 var(--doc-family, "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif);
hyphens: auto; -webkit-hyphens: auto;
}
.t-paper:focus { outline: none; }
@@ -191,6 +367,66 @@ html, body {
.t-paper h3 { font-size: 14px; font-weight: 600; margin: 16px 0 6px; color: var(--paper-ink-2); hyphens: none; }
.t-paper p { margin: 0 0 10px; text-align: justify; orphans: 2; widows: 2; text-wrap: pretty; }
.t-paper p + p { text-indent: 1.4em; margin-top: -10px; padding-top: 10px; }
+/* ————— figures ————— */
+.t-paper .t-figure {
+ margin: 14px 0; text-align: center;
+ /* an image is atomic: it must not be split across a page, and pagination is
+ told the same thing by data-atomic */
+ break-inside: avoid; page-break-inside: avoid;
+}
+.t-paper .t-figure img { max-width: 100%; height: auto; vertical-align: top; }
+.t-paper .t-figure[data-align="left"] { text-align: left; }
+.t-paper .t-figure[data-align="right"] { text-align: right; }
+/* a source that will not load leaves a visible frame rather than a silent gap
+ that pagination has already reserved height for */
+.t-paper .t-figure[data-broken] img { min-height: 80px; outline: 1px dashed var(--paper-rule); }
+
+/* ————— tables —————
+ Ruled, not boxed: a contract table wants horizontal rules and air, not a grid
+ of borders. `table-layout: fixed` so a long cell widens nothing — the measure
+ is the page's, and a table that changes it makes the page look broken. */
+.t-paper .t-table {
+ width: 100%; border-collapse: collapse; table-layout: fixed;
+ margin: 0 0 12px; font-size: .95em;
+}
+.t-paper .t-table th, .t-paper .t-table td {
+ border-bottom: 1px solid var(--paper-rule);
+ padding: 6px 10px 6px 0; vertical-align: top;
+ text-align: start; text-indent: 0; hyphens: none;
+}
+.t-paper .t-table th {
+ font-weight: 600; border-bottom-width: 1.5px;
+ color: var(--paper-ink);
+}
+.t-paper .t-table tr:last-child td { border-bottom: 0; }
+/* a padded cell in a short final row is structure, not content */
+.t-paper .t-table td[data-pad] { opacity: .35; }
+
+/* ————— lists —————
+ Justified like body text, because a list in a contract is prose that happens
+ to be enumerated. `text-indent` is reset: `p + p` gives paragraphs a first-line
+ indent and a list item is not a continued paragraph.
+
+ The markers are OUTSIDE the text column so the text edge stays flush with the
+ paragraphs above and below — a list that shifts the measure makes the page
+ look broken even though nothing is wrong. */
+.t-paper ul, .t-paper ol {
+ margin: 0 0 10px; padding-inline-start: 1.6em;
+}
+.t-paper li {
+ margin: 0 0 3px; text-align: justify; text-indent: 0;
+ orphans: 2; widows: 2;
+}
+/* a nested list tucks under its parent item and loses the outer gap */
+.t-paper li > ul, .t-paper li > ol { margin: 3px 0 0; }
+.t-paper ul { list-style: disc; }
+.t-paper ul ul { list-style: circle; }
+.t-paper ul ul ul { list-style: square; }
+.t-paper ol { list-style: decimal; }
+.t-paper ol ol { list-style: lower-alpha; }
+.t-paper ol ol ol { list-style: lower-roman; }
+.t-paper li::marker { color: var(--paper-ink-2); }
+
.t-paper blockquote {
margin: 12px 0 12px 24px; padding-inline-start: 14px;
border-inline-start: 2px solid var(--line);
@@ -233,3 +469,617 @@ html, body {
font: 600 9px/1 -apple-system, system-ui, sans-serif;
color: var(--accent-ink); vertical-align: super; margin-inline-end: 4px;
}
+
+/* ————— dialogs —————
+ NOTE the class names: `.t-card` was already the review card in the sidebar,
+ so the About dialog uses `.t-dlg`. Reusing it inherited the card's padding
+ and 11px buttons and made the dialog look like a comment. */
+.t-overlay {
+ position: fixed; inset: 0; z-index: 200;
+ display: flex; align-items: flex-start; justify-content: center;
+ padding: 6vh 16px; overflow: auto;
+ background: rgb(20 30 45 / .38);
+}
+.t-dlg {
+ width: min(560px, 100%);
+ background: var(--field); color: var(--ink);
+ border: 1px solid var(--line); border-radius: 14px;
+ box-shadow: 0 24px 64px rgb(20 30 45 / .28), 0 4px 12px rgb(20 30 45 / .12);
+ padding: 18px 20px 14px;
+}
+.t-dlg-h {
+ font-size: 12px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: .07em; color: var(--muted);
+ margin: 20px 0 8px; padding-top: 12px; border-top: 1px solid var(--line);
+}
+.t-dlg-h:first-of-type { border-top: 0; padding-top: 0; }
+.t-dlg .t-row {
+ display: flex; align-items: center; gap: 10px; margin: 8px 0;
+}
+.t-dlg .t-row > span:first-child { flex: 0 0 120px; color: var(--muted); font-size: 13px; }
+.t-about-blurb { font-size: 13.5px; line-height: 1.5; color: var(--ink-2); margin: 6px 0; }
+.t-about-val { font-size: 13px; color: var(--ink-2); margin: 4px 0; }
+.t-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
+.t-note { font-size: 12px; line-height: 1.5; color: var(--muted); margin: 6px 0 0; }
+.t-about-head { margin-bottom: 4px; }
+.t-about-logo {
+ display: inline-flex; align-items: center; gap: 10px;
+ text-decoration: none; color: inherit;
+}
+.t-about-logo b { display: block; font-size: 15px; white-space: nowrap; }
+/* Scoped to the version line. Unscoped, this also caught the brand slash
+ INSIDE the <b> — `bento<span>/</span>type` — turning it into a block and
+ breaking the wordmark across three lines. */
+.t-about-logo > div > span { display: block; font-size: 12px; color: var(--muted); }
+
+/* `hidden` must actually hide. A class that sets `display` beats the hidden
+ attribute's UA rule, so `.t-btn[hidden]` stayed inline-flex and the
+ "Update this file" button was visible before any check had run. */
+.t-btn[hidden], [hidden] { display: none !important; }
+.t-dlg-foot { display: flex; justify-content: flex-end; margin-top: 18px; }
+
+/* ————— find and replace —————
+ The matches are painted with the CSS Custom Highlight API, so nothing is
+ inserted into the page: no wrapper element inside contentEditable to move
+ the caret, and nothing that `readBlock` could read back into the model.
+ The current match is the ACCENT; the others are a pale wash of it, which is
+ the distinction a person scanning the page needs at a glance. */
+::highlight(t-find) { background-color: var(--find-hit); color: var(--find-ink); }
+::highlight(t-find-cur) { background-color: var(--find-cur); color: var(--find-ink); }
+
+.t-find { display: grid; gap: 7px; }
+.t-find input[type="text"] {
+ width: 100%; font: inherit; font-size: 12px; padding: 5px 7px;
+ border: 1px solid var(--line); border-radius: 6px;
+ background: var(--field); color: var(--ink);
+}
+.t-find input[type="text"]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
+.t-find-opts { display: flex; gap: 12px; font-size: 11.5px; color: var(--muted); }
+.t-find-opts label { display: flex; align-items: center; gap: 4px; cursor: pointer; }
+.t-find-bar { display: flex; align-items: center; gap: 5px; }
+.t-find-count { flex: 1; font-size: 11.5px; color: var(--muted); }
+.t-find-actions { display: flex; gap: 5px; }
+.t-find-actions button { flex: 1; }
+.t-find button {
+ font: inherit; font-size: 11.5px; padding: 3px 8px; cursor: pointer;
+ border: 1px solid var(--line); border-radius: 6px;
+ background: var(--chrome); color: var(--ink-2);
+}
+.t-find button:hover:not(:disabled) { background: var(--chrome-2); }
+.t-find button:disabled { opacity: .45; cursor: default; }
+/* ── captions, numbering and cross-references (xref.ts) ───────────────────
+ The caption LABEL and every reference are derived text written into empty
+ atoms after render, so nothing here may reserve space by content: a rule
+ that generated the words in CSS would put them out of reach of print,
+ selection and copy, and would have to know the document's language. */
+.t-paper figcaption {
+ margin: -4px 0 14px; font-size: 14.5px; line-height: 1.5;
+ color: var(--paper-ink-2); text-align: start; hyphens: none;
+ break-before: avoid; /* a caption never starts a page alone */
+}
+.t-paper .t-cap-num { font-weight: 600; color: var(--paper-ink); margin-inline-end: .35em; }
+.t-paper .t-xref { color: var(--blue); white-space: nowrap; }
+/* A broken reference must be impossible to read past — it is prose that has
+ lost its meaning, not a styling detail. */
+.t-paper .t-xref-broken,
+.t-xref-broken { color: var(--bad); font-weight: 600; }
+.t-paper .t-xref-broken { background: color-mix(in srgb, var(--bad) 12%, transparent); border-radius: 2px; }
+
+/* The picker reuses the house dialog chrome (.t-overlay + .t-dlg) — a second
+ scrim and card would drift from About's the first time either is touched. */
+.t-xref-pick { width: min(440px, 100%); }
+.t-xref-pick h3 { margin: 0 0 10px; font-size: 14px; font-weight: 600; }
+.t-xref-style { margin-bottom: 10px; }
+.t-xref-style select {
+ width: 100%; font: inherit; font-size: 12.5px; padding: 5px 6px;
+ background: var(--field); color: var(--ink);
+ border: 1px solid var(--line); border-radius: 6px;
+}
+.t-xref-list { display: flex; flex-direction: column; gap: 3px; }
+.t-xref-list button {
+ display: flex; gap: 8px; align-items: baseline; text-align: start;
+ font: inherit; font-size: 12.5px; padding: 6px 8px; cursor: pointer;
+ background: transparent; color: var(--ink);
+ border: 1px solid transparent; border-radius: 6px;
+}
+.t-xref-list button:hover, .t-xref-list button:focus-visible {
+ background: var(--chrome-2); border-color: var(--line); outline: none;
+}
+.t-xref-list button span { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.t-xref-foot { display: flex; justify-content: flex-end; margin-top: 12px; }
+
+.t-xref-item {
+ display: block; color: var(--ink-2); text-decoration: none;
+ padding: 3px 6px; border-radius: 5px; font-size: 12px; line-height: 1.45;
+}
+.t-xref-item:hover { background: var(--chrome-2); }
+.t-xref-broken-head { margin: 12px 0 4px; font-size: 11px; color: var(--bad); font-weight: 600; }
+/* ─────────────────────────────────────────────────────── the link popover
+ CHROME, not document: it floats over the page and must follow the reader's
+ theme, so no --paper token appears here (scripts/test-type-theme.mjs would
+ fail the build if one did, and it would be a white box in dark mode). */
+.t-link-pop {
+ position: fixed; z-index: 60;
+ display: flex; align-items: center; gap: 4px;
+ background: var(--field); color: var(--ink);
+ border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 6px; max-width: min(440px, calc(100vw - 16px));
+ box-shadow: 0 12px 32px rgb(20 30 45 / .22), 0 2px 8px rgb(20 30 45 / .12);
+}
+.t-link-url {
+ font: inherit; font-size: 13px;
+ color: var(--ink); background: var(--field);
+ border: 1px solid var(--line); border-radius: 8px;
+ padding: 6px 8px; width: 240px; min-width: 0;
+}
+.t-link-url:focus { border-color: var(--blue); outline: none; }
+.t-link-pop .t-btn { padding: 6px 8px; }
+.t-link-ok { color: var(--ink); font-weight: 600; }
+.t-link-rm { color: var(--bad); }
+
+/* Which link you are standing on, while the popover is open. Scoped to the
+ page, so this rule may use a document token — and must, or the marker would
+ invert with the chrome while the paper stays white. */
+.t-paper a.t-link-on {
+ background: rgb(91 141 239 / .16);
+ border-radius: 2px;
+ box-shadow: 0 0 0 2px rgb(91 141 239 / .35);
+}
+/* ————— section numbers and the table of contents —————
+ LAYOUT (the columns, the indent, the fixed page column) is emitted inline by
+ toc.ts, because print.ts carries its own stylesheet and a TOC that got its
+ columns from here would print as a run-on paragraph. What lives here is
+ COLOUR and affordance — the parts that follow the theme and that only the
+ editor has. Both are derived content: `[data-derived]` is the core's atom
+ marker, so nothing selected here can ever be typed into the document. */
+.t-paper .t-secnum { color: var(--paper-ink-2); }
+.t-paper .t-toc-e { color: var(--paper-ink); border-bottom: 0; cursor: pointer;
+ border-radius: 3px; padding: 1px 3px; margin-inline-end: -3px; }
+.t-paper .t-toc-e:hover { background: var(--chrome-2); }
+.t-paper .t-toc-n, .t-paper .t-toc-p { color: var(--paper-ink-2); }
+/* the entries are not prose: no justification, no first-line indent */
+.t-paper .t-toc { text-align: start; }
+/* ————— paragraph layout & page setup (layout.ts) —————
+
+ ENGAGED, NOT ALWAYS ON. `data-lay` is set on the paper only when the document
+ carries its own paragraph defaults, so a document that never opened Page
+ Setup renders through the rules above, untouched. Per-paragraph properties
+ are inline styles and beat both.
+
+ The page stays UNTHEMED here as everywhere else: the break rule is drawn in
+ a --paper token, because it is furniture ON the page and has to be visible
+ against white paper at midnight, not against the chrome. */
+.t-paper[data-lay] p,
+.t-paper[data-lay] li {
+ text-align: var(--lay-align, justify);
+ line-height: var(--lay-lh, 1.62);
+}
+.t-paper[data-lay] p {
+ /* the `p + p` pair below is what the defaults replace: overriding one half of
+ a margin/padding hack and leaving the other is how spacing goes wrong by
+ exactly 10px */
+ margin-top: var(--lay-sb, 0px);
+ margin-bottom: var(--lay-sa, 10px);
+ padding-top: 0;
+ text-indent: 0;
+}
+.t-paper[data-lay] p + p { text-indent: var(--lay-ind, 1.4em); }
+
+/* Asymmetric margins. The padding shorthand above sets both sides from
+ --mar-x; this overrides the inline axis when a bound document gives the two
+ sides different widths, and falls back to --mar-x when it does not. */
+.t-paper { padding-inline: var(--mar-l, var(--mar-x)) var(--mar-r, var(--mar-x)); }
+
+/* An author's page break, while pagination has not been taught to honour it:
+ the paragraph that starts a page is marked where it starts. */
+.t-paper [data-break] {
+ border-top: 1.5px dashed var(--paper-rule);
+ margin-top: 18px; padding-top: 12px;
+}
+
+/* the Layout panel */
+.t-lay-g { margin-bottom: 14px; }
+.t-lay-h {
+ font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .07em;
+ color: var(--muted); margin: 0 0 6px;
+}
+.t-lay-row { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
+.t-lay-row label { flex: 1 1 auto; color: var(--ink-2); font-size: 12px; }
+.t-lay-row .t-select { flex: 0 0 auto; }
+.t-lay-unit { color: var(--muted); font-size: 11px; width: 18px; }
+.t-lay-check {
+ display: flex; align-items: center; gap: 7px;
+ color: var(--ink-2); font-size: 12px; margin-bottom: 5px; cursor: pointer;
+}
+.t-input {
+ font: inherit; font-size: 12px; color: var(--ink);
+ background: var(--field); border: 1px solid var(--line);
+ border-radius: 7px; padding: 4px 6px; width: 68px; min-width: 0;
+}
+.t-input:focus { border-color: var(--blue); outline: none; }
+.t-dlg .t-input { width: 90px; }
+/* ————— comments —————
+ The layer is a SIBLING of .t-deco, not a child: drawPages() calls
+ deco.replaceChildren() on every repagination and would wipe anything a
+ feature put there. Highlights are absolutely positioned boxes computed from
+ Range.getClientRects(), so nothing is drawn inside the editable — which is
+ also why a comment can never reach print (print.ts renders blocks from the
+ model and this module never touches a block).
+
+ Colours are token-derived throughout; the translucent highlight is a
+ color-mix of the accent rather than a literal, so a theme change carries it. */
+.t-cmt-layer { position: absolute; inset: 0; pointer-events: none; z-index: 3; }
+/* HIDING COMMENTS is a VIEWER preference, like the theme — it is about reading
+ this document today, not about the document, so it never enters the file and
+ the threads are untouched. One class on the root turns off the marginal
+ apparatus and leaves the words exactly where they were. */
+.t-hide-comments .t-cmt-layer, .t-hide-comments .t-cmt-card { display: none; }
+.t-cmt-hl {
+ position: absolute; border-radius: 2px;
+ background: color-mix(in srgb, var(--accent) 24%, transparent);
+ box-shadow: inset 0 -1px 0 color-mix(in srgb, var(--accent) 70%, transparent);
+}
+.t-cmt-hl.on { background: color-mix(in srgb, var(--accent) 42%, transparent); }
+.t-cmt-hl.done { background: color-mix(in srgb, var(--muted) 16%, transparent); box-shadow: none; }
+
+/* the margin, the same gutter the footnote sidenotes use */
+.t-cmt-card {
+ position: absolute; left: var(--page-w);
+ width: calc(var(--gutter) - 26px); margin-inline-start: 22px;
+ pointer-events: auto; cursor: pointer;
+ background: var(--field); color: var(--ink);
+ border: 1px solid var(--line); border-inline-start: 2px solid var(--accent);
+ border-radius: 7px; padding: 6px 8px;
+ font: 11.5px/1.45 -apple-system, system-ui, sans-serif;
+}
+.t-cmt-card.on { border-color: var(--accent); box-shadow: 0 2px 10px rgb(20 30 45 / .14); }
+.t-cmt-card.done { opacity: .5; border-inline-start-color: var(--muted); }
+.t-cmt-card .who { color: var(--muted); font-size: 10.5px; }
+.t-cmt-card .what { color: var(--ink); word-break: break-word; }
+.t-cmt-card .msg + .msg { margin-top: 5px; padding-top: 5px; border-top: 1px solid var(--line); }
+
+/* the reply box, shared by the margin card and the panel item */
+.acts { margin-top: 6px; }
+.acts textarea {
+ width: 100%; resize: vertical; font: inherit; font-size: 11.5px;
+ color: var(--ink); background: var(--field);
+ border: 1px solid var(--line); border-radius: 6px; padding: 4px 6px;
+}
+.acts .btns { display: flex; gap: 5px; margin-top: 5px; }
+.acts .btns button {
+ flex: 1; font: inherit; font-size: 11px; padding: 3px 6px; cursor: pointer;
+ border: 1px solid var(--line); border-radius: 6px;
+ background: var(--chrome); color: var(--ink-2);
+}
+.acts .btns button:hover { background: var(--chrome-2); }
+
+/* the panel list */
+.t-cmt-item { cursor: pointer; }
+.t-cmt-item.on { border-color: var(--accent); }
+.t-cmt-item .quote {
+ font-size: 11px; color: var(--muted); margin: 3px 0 4px;
+ padding-inline-start: 6px; border-inline-start: 2px solid var(--accent);
+ word-break: break-word;
+}
+/* a detached thread: its words are gone, so the quote is struck through and the
+ accent rail drops to muted — it is history, not a place you can click to */
+.t-cmt-item .quote.gone { text-decoration: line-through; border-inline-start-color: var(--muted); }
+.t-cmt-item .reply {
+ margin-top: 5px; padding-top: 5px; border-top: 1px solid var(--line);
+ padding-inline-start: 8px;
+}
+/* ————— citations & the bibliography (cite.ts) —————
+
+ The in-document citation is an ATOM: it occupies a position and no
+ characters, so it is styled as one indivisible thing the caret steps over,
+ exactly as `sup.t-note` is. It takes the PAPER ink, not the chrome ink,
+ because it is part of the printed sentence — a citation that dimmed with
+ the app's dark theme would print differently from how it reads.
+
+ A citation whose entry is missing is tinted with --bad and keeps its text
+ ("[?knuth1984]"), because the failure has to survive being printed. */
+.t-paper .t-cite {
+ color: var(--paper-ink);
+ white-space: nowrap;
+ cursor: default;
+ border-radius: 2px;
+}
+.t-paper .t-cite:hover { background: color-mix(in srgb, var(--accent) 22%, transparent); }
+.t-paper .t-cite.miss {
+ color: var(--bad);
+ background: color-mix(in srgb, var(--bad) 12%, transparent);
+}
+
+/* ————— the Sources panel ————— */
+.t-cite-bar { display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 9px; }
+.t-cite-style {
+ flex: 1 1 100%; font: inherit; font-size: 12px; padding: 4px 6px;
+ color: var(--ink); background: var(--field);
+ border: 1px solid var(--line); border-radius: 6px;
+}
+.t-cite-btn, .t-cite-mini {
+ font: inherit; font-size: 11.5px; padding: 4px 8px; cursor: pointer;
+ color: var(--ink-2); background: var(--chrome);
+ border: 1px solid var(--line); border-radius: 6px;
+}
+.t-cite-btn:hover, .t-cite-mini:hover { background: var(--chrome-2); }
+.t-cite-go { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); }
+.t-cite-h {
+ font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em;
+ color: var(--muted); margin: 14px 0 6px;
+}
+.t-cite-miss {
+ border: 1px solid var(--bad); border-radius: 8px; padding: 7px 9px; margin-bottom: 8px;
+ background: color-mix(in srgb, var(--bad) 8%, transparent);
+}
+.t-cite-miss-h { font-size: 11.5px; font-weight: 600; color: var(--bad); margin-bottom: 4px; }
+.t-cite-miss code { display: inline-block; margin: 0 5px 3px 0; }
+.t-cite-list { display: flex; flex-direction: column; gap: 7px; }
+.t-cite-ref { display: flex; gap: 7px; font-size: 11.5px; line-height: 1.45; color: var(--ink-2); }
+.t-cite-ref .n { flex: 0 0 auto; color: var(--muted); font-variant-numeric: tabular-nums; }
+.t-cite-ref .r { word-break: break-word; }
+
+/* ————— the import and picker dialogs ————— */
+.t-cite-paste, .t-cite-search {
+ width: 100%; font: inherit; font-size: 12.5px; padding: 6px 8px; margin-top: 8px;
+ color: var(--ink); background: var(--field);
+ border: 1px solid var(--line); border-radius: 8px;
+}
+.t-cite-paste { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; }
+.t-cite-pick { max-height: 46vh; overflow: auto; margin-top: 8px; }
+.t-cite-row {
+ display: flex; gap: 8px; align-items: flex-start; padding: 6px 7px;
+ border-radius: 7px; cursor: pointer;
+}
+.t-cite-row:hover { background: var(--chrome-2); }
+.t-cite-row.on { background: color-mix(in srgb, var(--accent) 16%, transparent); }
+.t-cite-row b { display: block; font-size: 12.5px; font-weight: 600; color: var(--ink); }
+.t-cite-row i { display: block; font-size: 12px; font-style: normal; color: var(--ink-2); }
+.t-cite-row code { font-size: 11px; color: var(--muted); }
+/* ————— mathematics —————
+ The metrics are computed in math/layout.ts and arrive as inline styles; this
+ block only supplies what is CONSTANT — display roles, the rule colours, and
+ the fonts. Nothing here may carry a number that the layout engine also knows,
+ or the two would drift and every formula would be subtly wrong.
+
+ COLOUR IS `currentColor`, everywhere. A formula is text: it must be the same
+ ink as the sentence it sits in, on the always-white page and equally in the
+ Math panel's live preview, which sits on CHROME and therefore inverts with
+ the theme. One token would have been wrong in one of those two places.
+
+ `line-height: 1` is load-bearing. The layout engine models a line box as
+ rising 0.75em and falling 0.22em from its baseline, which is only true when
+ nothing adds leading — with the paper's 1.62 line-height every stacked box
+ would be spaced by an amount the engine never accounted for. */
+.t-math {
+ display: inline-block;
+ line-height: 1;
+ white-space: nowrap;
+ hyphens: none; -webkit-hyphens: none;
+ text-indent: 0;
+ font-family: "STIX Two Math", "Cambria Math", "Latin Modern Math",
+ "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
+ font-style: normal; font-weight: normal;
+}
+/* A formula never justifies, never hyphenates and never breaks: the spacing
+ inside it is typeset, not text. */
+.t-paper .t-math { text-align: start; }
+
+/* the variants — the only place a letter's shape is decided */
+.t-math .t-mi { font-style: italic; }
+.t-math .t-mb { font-weight: 700; }
+.t-math .t-mbi { font-weight: 700; font-style: italic; }
+.t-math .t-msf { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
+.t-math .t-mtt { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+.t-math .t-mop { font-style: normal; }
+.t-math .t-mbig { display: inline-block; }
+/* prose inside a formula wears the PAGE's face, not the maths face */
+.t-math .t-mtext {
+ font-family: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
+ white-space: pre-wrap;
+}
+.t-math .t-msp { display: inline-block; }
+
+/* fractions: the bar is the numerator's bottom border, so it is exactly as
+ wide as the wider of the two rows and needs no width of its own */
+.t-math .t-mfrac { display: inline-block; text-align: center; }
+.t-math .t-mnum, .t-math .t-mden { display: block; }
+.t-math .t-mnum { border-bottom: 0 solid currentColor; }
+
+/* scripts */
+.t-math .t-mss { display: inline-block; text-align: start; }
+.t-math .t-mss > .t-msup, .t-math .t-mss > .t-msub { display: block; }
+.t-math .t-mside { display: inline-block; }
+
+/* limits above and below a big operator */
+.t-math .t-mlim { display: inline-block; text-align: center; }
+.t-math .t-mlim > span { display: block; }
+
+/* radicals. `non-scaling-stroke` (set in the markup) keeps the surd's stroke
+ even however far it is stretched; the width here is what stops a tall
+ radical from also becoming a wide one. */
+.t-math .t-msurd {
+ display: inline-block; width: .58em; overflow: visible;
+ fill: none; stroke: currentColor; stroke-width: .055em;
+ stroke-linecap: round; stroke-linejoin: miter;
+}
+.t-math .t-mrad { display: inline-block; border-top: 0 solid currentColor; }
+.t-math .t-mroot { display: inline-block; margin-inline-end: -.32em; }
+
+/* over- and underlines */
+.t-math .t-mbar { display: inline-block; }
+.t-math .t-mbar.t-over { border-top: 0 solid currentColor; }
+.t-math .t-mbar.t-under { border-bottom: 0 solid currentColor; }
+
+/* accents are ABSOLUTE: they add no width, so `\hat{x}` is exactly as wide as
+ `x` and a hatted symbol in a fraction still centres correctly */
+.t-math .t-macc { position: relative; display: inline-block; }
+.t-math .t-maccm {
+ position: absolute; inset-inline: 0; text-align: center;
+ line-height: 1; pointer-events: none;
+}
+
+/* matrices, cases and aligned — one inline-table, centred on the math axis */
+.t-math .t-mmatrix { display: inline-table; border-collapse: collapse; }
+.t-math .t-mrow2 { display: table-row; }
+.t-math .t-mcell {
+ display: table-cell; padding: var(--t-mpad, .16em) .3em; text-align: center;
+}
+.t-math .t-mmatrix.t-mleft .t-mcell { text-align: start; padding-inline-end: .7em; }
+.t-math .t-mmatrix.t-mleft .t-mcell:last-child { padding-inline-end: .3em; }
+
+/* delimiters stretch about the axis, which is 0.5em below the top of a
+ line-height:1 box — the one place a metric is duplicated between the engine
+ and the stylesheet, because a transform-origin cannot be computed per box
+ without a second inline style on every fence */
+.t-math .t-mdelim { display: inline-block; transform-origin: 50% .5em; }
+
+/* a display equation is its own paragraph-level object */
+.t-math.t-math-display { display: block; text-align: center; }
+.t-paper [data-kind="math"] {
+ margin: 16px 0; text-align: center; text-indent: 0;
+ hyphens: none; -webkit-hyphens: none; font-size: 1.06em;
+}
+
+/* what a formula does when it is wrong: says so, in place, and keeps setting */
+.t-math .t-merr {
+ color: var(--bad); font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: .86em; font-style: normal;
+}
+.t-math-bad { text-decoration: underline dotted var(--bad); text-underline-offset: 4px; }
+
+/* ————— the Math panel ————— */
+.t-mathsrc {
+ width: 100%; box-sizing: border-box; resize: vertical;
+ font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace;
+ color: var(--ink); background: var(--field);
+ border: 1px solid var(--line); border-radius: 6px; padding: 6px 7px;
+}
+.t-mathsrc:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
+.t-mathprev {
+ display: flex; align-items: center; justify-content: center;
+ min-height: 52px; margin: 8px 0; padding: 10px 8px; overflow-x: auto;
+ font-size: 17px; color: var(--ink);
+ background: var(--chrome-2); border: 1px solid var(--line); border-radius: 6px;
+}
+
+
+/* Tracked changes. Word's convention — coloured underline for an insertion,
+ strike for a deletion — because a document full of them is read by people who
+ have read a thousand of them elsewhere, and inventing a new visual language
+ for the most conventional feature in the category helps nobody. */
+.t-paper ins.t-trk { text-decoration: underline; text-decoration-thickness: 1px;
+ text-underline-offset: 2px; color: var(--paper-trk); background: var(--paper-trk-bg); }
+.t-paper del.t-trk { text-decoration: line-through; color: var(--paper-trk-del); opacity: .75; }
+/* Nothing to override for print: the ink is unthemed, so what is on screen is
+ what comes out of the printer — which is the point, since a tracked document
+ is usually printed precisely to be read and signed off on paper. */
+.t-trk-row { display: flex; gap: 5px; margin-top: 6px; }
+.t-trk-row button { flex: 1; padding: 3px 6px; font: inherit; font-size: 11px;
+ border: 1px solid var(--line); background: var(--chrome); color: var(--ink-2);
+ border-radius: 5px; cursor: pointer; }
+.t-trk-row button:hover { background: var(--chrome-2); color: var(--ink); }
+
+
+/* An embedded Bento artifact. Centred and bounded by the text column: an
+ embed is a figure, and a chart wider than the words it explains reads as a
+ different document interrupting this one. */
+.t-paper .t-embed { margin: 16px 0; text-align: center; }
+.t-paper .t-embed-view { display: inline-block; max-width: min(100%, var(--embed-w, 100%)); }
+.t-paper .t-embed-view svg { max-width: 100%; height: auto; }
+.t-paper .t-embed figcaption { margin-top: 6px; font-size: 12px; color: var(--paper-ink-2); font-style: italic; }
+.t-paper .t-embed-missing { padding: 22px 14px; border: 1px dashed var(--paper-rule);
+ border-radius: 8px; color: var(--paper-ink-2); font-size: 12.5px; }
+
+
+/* The block grip: a handle in the page's own left margin that reorders a
+ block. Hover-only, so a page at rest is just the document — the same rule
+ bento/spaces uses for its gutter, and the reason an affordance can exist at
+ all without becoming furniture. */
+.t-deco .t-grip-layer { position: absolute; inset: 0; pointer-events: none; }
+.t-deco .t-grip {
+ position: absolute; display: inline-flex; align-items: center; justify-content: center;
+ width: 26px; height: 24px; padding: 0; border: 0; border-radius: 5px;
+ /* PAPER ink, not chrome ink: this floats over a white sheet, and the sheet
+ stays white in dark mode while every chrome token inverts. */
+ color: var(--paper-rule); background: transparent; cursor: grab;
+ opacity: 0; transition: opacity .12s;
+ pointer-events: auto;
+}
+/* ONE at a time, not a column of them. Driven by script rather than :hover,
+ because the grips live in an overlay and CSS cannot ask which block the
+ pointer is over. */
+.t-deco .t-grip.on { opacity: .7; }
+/* The + shares the grip's reveal: they are one gutter, two buttons, as in
+ bento/spaces. It sits further out so the grip stays nearest the text — the
+ handle you reach for while reading, with insertion one step beyond. */
+.t-deco .t-plus { cursor: pointer; }
+.t-deco .t-grip.t-grip-dragging { opacity: 1; cursor: grabbing; }
+/* While a drag is live the whole page shows the grabbing cursor, or it
+ reverts the moment the pointer leaves the 26px handle. */
+body.t-dragging, body.t-dragging * { cursor: grabbing !important; user-select: none; }
+/* Where the block will land. */
+.t-deco .t-droptip {
+ position: absolute; inset-inline: 0; height: 2px; margin-top: -1px;
+ background: var(--accent); border-radius: 2px; pointer-events: none;
+}
+.t-deco .t-droptip::before {
+ content: ''; position: absolute; inset-inline-start: -3px; top: -3px;
+ width: 8px; height: 8px; border-radius: 50%; background: var(--accent);
+}
+.t-deco .t-grip:hover, .t-deco .t-grip:focus-visible {
+ opacity: 1; color: var(--paper-ink-2);
+ background: color-mix(in srgb, var(--paper-ink) 8%, transparent);
+}
+.t-deco .t-grip:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+/* The grip menu borrows .t-menu's ITEM styling, but none of its placement.
+ .t-menu is built to hang from the right edge of a topbar button's wrapper,
+ so it sets inset-inline-end:0 — and this one is appended to <body> and
+ positioned by script from the left. With a left AND a right edge pinned, the
+ box stretched from the grip to the window edge: a full-width white band
+ across the document and the properties panel. */
+.t-grip-menu {
+ position: absolute; z-index: 60; display: block;
+ inset-inline-end: auto; /* the whole bug: unpin the right edge */
+ top: auto; /* script places it, in page coordinates */
+ min-width: 150px; width: max-content;
+}
+/* A disabled item must LOOK disabled. "Move up" on the first block is
+ correctly inert, and rendered identically to "Move down" — so the menu
+ silently did nothing and looked like it had failed. */
+.t-menu button:disabled { opacity: .4; cursor: default; }
+.t-menu button:disabled:hover { background: transparent; }
+
+/* It is chrome sitting ON the sheet, so it must never reach paper. */
+@media print { .t-deco .t-grip-layer { display: none; } }
+
+
+/* The selection toolbar.
+ It FOLLOWS THE THEME, like every other floating surface in this app — the ⋯
+ menu, the grip menu, the comment cards. It was dark in both themes at first,
+ on the argument that a white bar over white paper would need a border to
+ exist; but the comment cards sit beside the paper in exactly these tokens,
+ with exactly that border, and read as chrome perfectly well. So the argument
+ was already disproved inside this stylesheet, and all the dark version
+ bought was the only dark UI in an otherwise light app. It borrows .t-menu's
+ surface and .t-btn.on's active state so it is the same object as the rest. */
+.t-selbar {
+ position: absolute; z-index: 70;
+ display: flex; align-items: center; gap: 1px;
+ padding: 4px; border-radius: 10px;
+ background: var(--field); border: 1px solid var(--line);
+ box-shadow: 0 12px 32px rgb(20 30 45 / .16), 0 2px 6px rgb(20 30 45 / .08);
+}
+.t-selbtn {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 28px; height: 28px; padding: 0;
+ border: 0; border-radius: 7px; background: transparent;
+ color: var(--ink-2); cursor: pointer;
+}
+.t-selbtn:hover { background: var(--chrome-2); color: var(--ink); }
+.t-selbtn.on { background: var(--accent); color: var(--accent-ink); font-weight: 600; }
+.t-selbtn:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+.t-selsep { width: 1px; height: 18px; margin: 0 3px; background: var(--line); }
+
+/* Neither of these is part of the document. */
+@media print { .t-selbar, .t-deco .t-grip-layer { display: none; } }
diff --git a/type/src/sync/online.ts b/type/src/sync/online.ts
new file mode 100644
index 00000000..f52b3e77
--- /dev/null
+++ b/type/src/sync/online.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The online relay transport for bento/type — A FACADE. The implementation
+// is kernel/src/sync/online.ts.
+//
+// It needed nothing app-specific to move: the E2EE transport, the credential
+// minting, the invite/member signature chain and the reconnect logic all work
+// in terms of `doc.collab` and `docId`, which every Bento document has
+// (PLATFORM §2) — see type/src/model.ts TypeDoc.collab.
+
+export * from '../../../kernel/src/sync/online.ts';
diff --git a/type/src/sync/session.ts b/type/src/sync/session.ts
index a2285b57..4370c409 100644
--- a/type/src/sync/session.ts
+++ b/type/src/sync/session.ts
@@ -40,8 +40,18 @@ import type { Store } from '../store.ts';
* type's editor re-renders from one signal rather than five. Only 'doc' has a
* meaning here; the rest are accepted and dropped, which is the honest mapping
* — an app is not obliged to have a 'slides' event.
+ *
+ * `onRemoteApplied` is separate from `store.on('doc', …)` on purpose: type's
+ * Editor owns its contentEditable DOM directly (model.ts's caret-is-a-model-
+ * position design) and never re-renders from a generic store listener — doing
+ * so on every keystroke would fight the browser's own caret. `emit('doc')` is
+ * called ONLY by the kernel session's `afterRemoteChange`, for a change that
+ * did NOT originate from a local commit, so this is the one safe place to
+ * tell the editor "the model moved under you, redraw". Exported so collab.ts
+ * — the only other caller — can build the same wrapper for `startSharing` and
+ * friends without duplicating it, though those never call `.emit()`.
*/
-function hostStore(store: Store): HostStore {
+export function hostStore(store: Store, onRemoteApplied?: () => void): HostStore {
return {
get doc() { return store.doc; },
on(event: string, fn: () => void) {
@@ -49,7 +59,11 @@ function hostStore(store: Store): HostStore {
},
// A remote edit repaints but must NEVER push an undo entry — see
// Store.touch. 'doc' is the only event type has.
- emit(event: string) { if (event === 'doc') store.touch(); },
+ emit(event: string) {
+ if (event !== 'doc') return;
+ store.touch();
+ onRemoteApplied?.();
+ },
commit(fn: () => void) { store.commit(() => fn()); },
// type has no dirty flag: the document is saved from the editor's own
// state, and a remote edit does not change whether THIS person has
@@ -59,9 +73,9 @@ function hostStore(store: Store): HostStore {
}
/** What a word-processing document knows that the session cannot work out. */
-function typeHost(store: Store, caret: () => { block: string }): SyncHost {
+function typeHost(store: Store, caret: () => { block: string }, onRemoteApplied?: () => void): SyncHost {
return {
- store: hostStore(store),
+ store: hostStore(store, onRemoteApplied),
engine: SyncState,
heal(): boolean {
@@ -111,9 +125,17 @@ function typeHost(store: Store, caret: () => { block: string }): SyncHost {
* `caret` is a callback rather than a value because presence is pushed
* whenever the session likes; the editor owns where the caret is and should
* not have to mirror it into the session on every keystroke.
+ *
+ * `onRemoteApplied`, likewise, is a callback rather than an event because
+ * type's editor has no event to subscribe to for "the model changed
+ * remotely" — see `hostStore` above. collab.ts passes `() => editor.render()`.
*/
export class SyncSession extends KernelSession {
- constructor(store: Store, caret: () => { block: string } = () => ({ block: '' })) {
- super(typeHost(store, caret));
+ constructor(
+ store: Store,
+ caret: () => { block: string } = () => ({ block: '' }),
+ onRemoteApplied?: () => void,
+ ) {
+ super(typeHost(store, caret, onRemoteApplied));
}
}
diff --git a/type/src/toc.ts b/type/src/toc.ts
new file mode 100644
index 00000000..87b98a79
--- /dev/null
+++ b/type/src/toc.ts
@@ -0,0 +1,601 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Section numbering and the table of contents.
+//
+// Both are DERIVED. Nothing this file computes — not a section number, not a
+// page reference, not a TOC entry — is ever written into the document. That is
+// the same rule the footnote markers already follow (render.ts numberNotes),
+// and for the same reason: inserting one heading renumbers every heading after
+// it, so a stored number is wrong the instant the author types. A stored PAGE
+// number is worse: it is wrong when somebody else opens the file at a different
+// zoom, or edits a paragraph twenty pages earlier.
+//
+// WHAT IS IN THE MODEL
+//
+// · a `toc` block, whose stored `text` is only its HEADING ("Contents").
+// The entries are derived at render time and injected as an ATOM.
+// · `doc.sections = { numbered: boolean }` — a document-level switch. An
+// additive top-level field, preserved by parseDoc like any unknown key;
+// absent means ON, so "automatic" is what an author gets by default.
+// · `Block.role` on a heading, which the author already has, to opt out.
+//
+// KEEPING THE REDLINE QUIET — the constraint that shaped the whole design.
+//
+// The redline aligns on block ids and diffs plain text. A TOC block whose
+// stored text was the LIST OF ENTRIES would change on every repagination, so
+// every review of every document would open with "the table of contents
+// changed" — the exact noise that makes line diffs useless on prose, and the
+// reason a cell is a block. So:
+//
+// · the TOC block's `text` is its heading and nothing else. Repaginating a
+// 200-page contract cannot change one byte of the document JSON, which
+// also means it cannot invalidate a SIGNATURE (canon.ts digests the model).
+// · section numbers are injected as `[data-derived]` spans, which the core's
+// atom predicate skips exactly as it skips a footnote marker: they occupy a
+// position but no characters, so readBlock cannot type them into the model
+// and the caret cannot land inside one.
+// · the page-number column has a FIXED width and tabular figures. "9" → "10"
+// therefore moves nothing, so filling page numbers in AFTER pagination
+// cannot change the pagination it was derived from. That is what lets the
+// TOC update after pagination rather than before, with no fixpoint loop.
+//
+// A SKIPPED LEVEL — an h3 with no h2 above it — numbers as `1.0.1`.
+//
+// The alternative is to promote it and call it `1.1`, which is wrong twice: two
+// different outlines then produce the same number, and the author is never told
+// their document has a hole in it. The zero keeps the invariant that a number's
+// depth equals its heading's level, which is what makes numbers comparable, and
+// it makes the missing level visible. Word does the same. Filling the gap later
+// turns 1.0.1 into 1.1.1 — a renumber, like any other.
+//
+// LEADING zeros are the one exception, and the rig is why. A document whose h1
+// is its TITLE (role 'title' — the app's own picker calls h1 "Title") never
+// opens level 1 at all, so every section came out `0.1`, `0.2`. A level the
+// document has NOT USED above this point is not a hole in the sequence, it is
+// a level the document does not have — so leading zeros are dropped and the
+// sections read 1, 2, 3. An INTERIOR zero is a genuine hole and stays.
+//
+// NEEDS FROM THE CORE
+// ═══════════════════
+// Four small additions. Until they land this module registers its chrome and
+// stays inert (the wiring below is soft — see `wire()`), so nothing breaks.
+//
+// 1. type/src/model.ts — the block kind.
+// · line ~20: add `'toc'` to the BlockKind union:
+// export type BlockKind = 'para' | 'h1' | ... | 'cell' | 'toc';
+// · in parseDoc, the kind whitelist (~line 207): add 'toc' to the array
+// ['para','h1','h2','h3','quote','ul','ol','cell','toc']
+// WHY: the TOC prints, so it has to be a block. Its content is derived, so
+// it needs no other model surface at all.
+//
+// 2. type/src/render.ts — three edits, all in existing functions.
+// a. TAG gains one entry: toc: 'nav',
+// b. the atom predicate learns about derived content, so injected numbers
+// and entries can never be read back into the model (isNoteAtom is what
+// editor.ts and readBlock both use, so broadening it in place needs no
+// other call-site change):
+//
+// export const isDerived = (el: Element) => el.hasAttribute('data-derived');
+// export const isNoteAtom = (el: Element) =>
+// (el.tagName === 'SUP' && el.classList.contains('t-note')) || isDerived(el);
+//
+// c. a decorator hook in blockHtml, so ONE function serves the editor, the
+// thumbnail-free print path and pagination — they all go through it:
+//
+// export type BlockDecorator = (b: Block, base: string) => string | null;
+// let decorator: BlockDecorator | null = null;
+// export const registerBlockDecorator = (d: BlockDecorator): void => { decorator = d; };
+//
+// and in blockHtml, after `const html = toHtml(...)`:
+//
+// const base = html || '<br>';
+// return decorator?.(b, base) ?? base;
+//
+// WHY (c): print.ts builds a string and the editor builds DOM. Anything
+// derived that is emitted in only one of them is drift, which is the failure
+// print.ts exists to prevent — one hook below both is the only shape that
+// cannot drift.
+//
+// 3. type/src/features.ts — two registries, in the style of the others:
+//
+// export type ReadyFn = (ctx: FeatureContext) => void;
+// export type PaginatedFn = (ctx: FeatureContext, metrics: Metrics, host: HTMLElement) => void;
+// const READY: ReadyFn[] = []; const PAGINATED: PaginatedFn[] = [];
+// export const registerReady = (f: ReadyFn): void => { READY.push(f); };
+// export const registerPaginated = (f: PaginatedFn): void => { PAGINATED.push(f); };
+// export const readyFns = (): ReadyFn[] => READY;
+// export const paginatedFns = (): PaginatedFn[] => PAGINATED;
+//
+// (`import type { Metrics } from './paginate.ts'` — type-only, no cycle.)
+//
+// 4. type/src/main.ts — two lines that call them.
+// · at the BOTTOM of the file, immediately above the existing bare
+// `repaginate();` (the "boot is finished" line):
+// for (const fn of readyFns()) fn(featureCtx);
+// · at the END of `repaginate()`, after `paint()`:
+// for (const fn of paginatedFns()) fn(featureCtx, metrics, paper);
+//
+// WHY: a feature needs two moments the registry does not yet offer — "the
+// chrome exists, here is your context" and "the pages have just been
+// measured". Page numbers are only knowable in the second one. Both are
+// general; find-and-replace will want the first, a running-header feature
+// the second.
+//
+// WHERE, AND THIS BIT IS LOAD-BEARING — the ready call must go at the
+// BOTTOM, not beside the `for (const spec of panels())` loop where it
+// visually belongs. `featureCtx.refresh()` closes over `schedule`, a `const`
+// declared 70 lines further down, so calling it from the panels loop throws
+// "Cannot access 'schedule' before initialization" and the app boots to a
+// blank page. Verified by applying this patch locally and loading the app:
+// it happened, and it kills the whole editor, not just the feature.
+
+import type { Metrics, Page } from './paginate.ts';
+import type { Block, TypeDoc } from './model.ts';
+import type { FeatureContext } from './features.ts';
+import * as features from './features.ts';
+import * as render from './render.ts';
+import { t } from './i18n.ts';
+
+// ───────────────────────────────────────────────────────────── pure: headings
+
+export type HeadKind = 'h1' | 'h2' | 'h3';
+
+/** Heading LEVEL comes from the block kind. The document stays flat. */
+export const HEAD_LEVEL: Readonly<Record<string, number>> = { h1: 1, h2: 2, h3: 3 };
+export const DEPTH = 3;
+
+export const isHeading = (b: Block): boolean => HEAD_LEVEL[b.kind] !== undefined;
+
+/**
+ * The TOC block's kind, as a value.
+ *
+ * Written once, through the model's own type, so that the day `'toc'` joins
+ * BlockKind (patch 1) this becomes an ordinary member and every use of it type
+ * checks unchanged — and until then the compiler is not asked to believe a
+ * literal that is not in the union yet.
+ */
+export const TOC_KIND = 'toc' as unknown as Block['kind'];
+
+/**
+ * What a `role` means here.
+ *
+ * The field already exists for "authoring role, for restyling and for a table
+ * of contents" (model.ts), and the app's own vocabulary already treats h1 as
+ * the document title — the block-kind picker calls it "Title" and the outline
+ * panel lists only h2/h3. So a title-roled heading is FURNITURE: a document's
+ * name is not section 1 of itself.
+ *
+ * The four combinations of (numbered, listed) are all reachable, because all
+ * four are things people actually want: a schedule heading that is listed but
+ * not numbered, an appendix marker that is numbered but not listed.
+ */
+export const ROLES = {
+ /** document furniture: no number, not in the TOC */
+ title: { numbered: false, listed: false },
+ subtitle: { numbered: false, listed: false },
+ /** LaTeX's \section* — in the contents, without a number */
+ unnumbered: { numbered: false, listed: true },
+ /** numbered like its siblings, but kept out of the contents */
+ unlisted: { numbered: true, listed: false },
+} as const satisfies Record<string, { numbered: boolean; listed: boolean }>;
+
+export type RoleName = keyof typeof ROLES;
+export const EXCLUDE_ROLE: RoleName = 'unnumbered';
+
+const roleOf = (b: Block): { numbered: boolean; listed: boolean } =>
+ ROLES[(b.role ?? '').trim().toLowerCase() as RoleName] ?? { numbered: true, listed: true };
+
+/** The document-level switch. Absent means ON — numbering is the default. */
+export interface SectionSettings { numbered: boolean }
+
+export function sectionSettings(doc: TypeDoc): SectionSettings {
+ const raw = (doc as { sections?: unknown }).sections;
+ const obj = raw && typeof raw === 'object' ? raw as Record<string, unknown> : undefined;
+ // ABSENT MEANS OFF. Automatic numbering is opt-in, because the documents this
+ // app opens mostly already carry their numbers in the heading text — every
+ // contract reads "1. Scope of Work" — and numbering those again renders
+ // "1.1 1. Scope of Work". The risk is asymmetric: on-by-default visibly
+ // corrupts an existing document, off-by-default is a feature somebody has to
+ // find. Verified on the starter contract, which is exactly this case.
+ return { numbered: obj?.numbered === true };
+}
+
+/** Mutate the switch. The only thing in this file that writes to the model. */
+export function setNumbered(doc: TypeDoc, on: boolean): void {
+ const raw = (doc as { sections?: unknown }).sections;
+ const obj = raw && typeof raw === 'object' ? { ...raw as object } : {};
+ (doc as { sections?: unknown }).sections = { ...obj, numbered: on };
+}
+
+export interface Heading {
+ id: string;
+ kind: HeadKind;
+ /** 1, 2 or 3 — from the kind, never stored separately */
+ level: number;
+ text: string;
+ /** '1.2.3'; absent when numbering is off or this heading opts out */
+ number?: string;
+ /** does it belong in the table of contents? */
+ listed: boolean;
+}
+
+/**
+ * Every heading, numbered in document order.
+ *
+ * PURE: it reads the document and writes nothing, which is what makes it
+ * testable in node and what makes "derived, never stored" true by construction
+ * rather than by discipline.
+ *
+ * A heading that opts out of numbering does NOT advance the counters — it is
+ * outside the sequence, not a gap in it, so its neighbours stay 3 and 4.
+ */
+export function headings(doc: TypeDoc): Heading[] {
+ const numbering = sectionSettings(doc).numbered;
+ const counters = new Array<number>(DEPTH).fill(0);
+ const out: Heading[] = [];
+ for (const b of doc.body) {
+ const level = HEAD_LEVEL[b.kind];
+ if (level === undefined) continue;
+ const role = roleOf(b);
+ const h: Heading = { id: b.id, kind: b.kind as HeadKind, level, text: b.text, listed: role.listed };
+ if (numbering && role.numbered) {
+ counters[level - 1]++;
+ for (let i = level; i < DEPTH; i++) counters[i] = 0;
+ // A skipped level shows as 0 — see the header. Leading zeros are dropped:
+ // they mean the document never opened that level (a title-only h1), which
+ // is not a hole in the sequence but a level the document does not use.
+ h.number = counters.slice(0, level).join('.').replace(/^(?:0\.)+/, '');
+ }
+ out.push(h);
+ }
+ return out;
+}
+
+/** blockId → '1.2.3', for the blocks that have one. */
+export function sectionNumbers(doc: TypeDoc): Map<string, string> {
+ const m = new Map<string, string>();
+ for (const h of headings(doc)) if (h.number) m.set(h.id, h.number);
+ return m;
+}
+
+// ──────────────────────────────────────────────────────── pure: the TOC itself
+
+export interface TocEntry {
+ id: string;
+ level: number;
+ text: string;
+ number?: string;
+ /** 1-based page, from the pagination Metrics; absent until pages are known */
+ page?: number;
+}
+
+/**
+ * The entries, optionally carrying page numbers.
+ *
+ * `pages` is separate from the document on purpose: the entries can be built
+ * before anything has been measured (the first paint) and the same function
+ * builds them again once the Metrics exist. Nothing about the entry depends on
+ * having been rendered.
+ */
+export function buildToc(doc: TypeDoc, pages?: ReadonlyMap<string, number>): TocEntry[] {
+ const out: TocEntry[] = [];
+ for (const h of headings(doc)) {
+ if (!h.listed) continue;
+ const e: TocEntry = { id: h.id, level: h.level, text: h.text };
+ if (h.number) e.number = h.number;
+ const p = pages?.get(h.id);
+ if (p !== undefined) e.page = p;
+ out.push(e);
+ }
+ return out;
+}
+
+export const hasToc = (doc: TypeDoc): boolean => doc.body.some(b => b.kind === TOC_KIND);
+
+// ─────────────────────────────────────────────────────── pure: pages from y
+
+/**
+ * Which page a paper-space y lands on.
+ *
+ * The half-pixel slack matches paginate.ts's own comparisons: a break is chosen
+ * at a line-box top, and asking for the page of that exact y must give the page
+ * the line is ON, not the one it ended.
+ */
+export function pageOfY(pages: readonly Page[], y: number): number | undefined {
+ for (const p of pages) {
+ if (y >= p.start - 0.5 && (!isFinite(p.end) || y < p.end - 0.5)) return p.n;
+ }
+ return undefined;
+}
+
+/** blockId → page, from measured tops. Pure, so the rig can supply the tops. */
+export function headingPages(
+ metrics: Metrics, tops: ReadonlyMap<string, number>,
+): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const [id, y] of tops) {
+ const n = pageOfY(metrics.pages, y);
+ if (n !== undefined) out.set(id, n);
+ }
+ return out;
+}
+
+/** The whole derivation, in one call: document + measurements → entries. */
+export const tocFor = (
+ doc: TypeDoc, metrics: Metrics, tops: ReadonlyMap<string, number>,
+): TocEntry[] => buildToc(doc, headingPages(metrics, tops));
+
+// ───────────────────────────────────────────────────────── derived markup
+//
+// LAYOUT is inline, COLOUR comes from styles.css.
+//
+// Not a style preference: print.ts carries its own stylesheet and this module
+// may not touch it, so a TOC that got its columns from styles.css would print
+// as a run-on paragraph. Inline layout prints correctly with no print-side
+// change; colour is themed and stays in the stylesheet where the theme rig can
+// see it. No literal colour appears in this file.
+
+const esc = (s: string): string =>
+ s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]!));
+
+/** width of the page column — fixed, so filling it in later moves nothing */
+const PAGE_COL = '2.4em';
+const NUM_COL = '3.4em';
+const TABULAR = 'font-variant-numeric:tabular-nums';
+
+/** The section number, as an atom the model can never absorb. */
+export const sectionNumberHtml = (number: string): string =>
+ `<span class="t-secnum" data-derived contenteditable="false"` +
+ ` style="margin-inline-end:.5em;${TABULAR}">${esc(number)}</span>`;
+
+/**
+ * The entry list.
+ *
+ * One atom wrapping the whole list, so the TOC block's own stored text (its
+ * heading) stays editable and everything derived stays outside the model. No
+ * whitespace is emitted between the atom and the heading text — a stray space
+ * there WOULD be a character, and readBlock would write it into the document.
+ */
+export function tocEntriesHtml(entries: readonly TocEntry[]): string {
+ if (!entries.length) return '';
+ const numbered = entries.some(e => e.number);
+ const rows = entries.map(e => {
+ const indent = (e.level - 1) * 1.5;
+ const num = numbered
+ ? `<span class="t-toc-n" style="flex:0 0 ${NUM_COL};${TABULAR}">${esc(e.number ?? '')}</span>` : '';
+ return `<a class="t-toc-e" data-goto="${esc(e.id)}"` +
+ ` style="display:flex;align-items:baseline;gap:.4em;text-decoration:none;color:inherit` +
+ `;margin-inline-start:${indent}em;text-indent:0">` +
+ num +
+ `<span class="t-toc-t" style="flex:1 1 auto">${esc(e.text)}</span>` +
+ `<span class="t-toc-p" style="flex:0 0 ${PAGE_COL};text-align:end;${TABULAR}">` +
+ `${e.page ?? ''}</span></a>`;
+ }).join('');
+ return `<span class="t-toc" data-derived contenteditable="false" style="display:block;margin-top:.4em">${rows}</span>`;
+}
+
+/**
+ * The decorator the core hook calls, for EVERY block.
+ *
+ * `base` is the block's ordinary html, already built — so a heading keeps its
+ * marks and its footnote markers and merely gains a number in front.
+ */
+export interface Derived {
+ /** blockId → section number; recomputed for you when omitted */
+ numbers?: ReadonlyMap<string, string>;
+ /** blockId → page; entries simply carry no page when omitted */
+ pages?: ReadonlyMap<string, number>;
+}
+
+export function decorate(doc: TypeDoc, b: Block, base: string, d: Derived = {}): string | null {
+ if (b.kind === TOC_KIND) return base + tocEntriesHtml(buildToc(doc, d.pages));
+ const level = HEAD_LEVEL[b.kind];
+ if (level === undefined) return null;
+ // The caches are PARAMETERS, not module state. Recomputing the numbering for
+ // every block would make a render O(blocks²) — 200 pages of contract is a
+ // real number — but a decorator that read a module-level cache would answer
+ // differently depending on what ran before it, which is untestable and, in
+ // node, simply wrong.
+ const n = (d.numbers ?? sectionNumbers(doc)).get(b.id);
+ return n ? sectionNumberHtml(n) + base : null;
+}
+
+// ──────────────────────────────────────────────────────────── live wiring
+//
+// Everything below is the browser side: caches, the DOM measurement, and the
+// chrome. The functions above never reach it, which is why they run in node.
+
+let ctxRef: FeatureContext | null = null;
+let numbers: Map<string, string> | null = null;
+let pageCache: Map<string, number> = new Map();
+let wired = false;
+
+/** The numbering, recomputed at most once per document change. */
+function numberCache(doc: TypeDoc): Map<string, string> {
+ if (!numbers) numbers = sectionNumbers(doc);
+ return numbers;
+}
+
+/** Paper-space top of every heading, measured the way paginate.ts measures. */
+export function measureTops(doc: TypeDoc, host: HTMLElement): Map<string, number> {
+ const top0 = host.getBoundingClientRect().top + doc.page.marginTop;
+ const tops = new Map<string, number>();
+ for (const b of doc.body) {
+ if (!isHeading(b)) continue;
+ const el = host.querySelector<HTMLElement>(`[data-id="${CSS.escape(b.id)}"]`);
+ if (el) tops.set(b.id, el.getBoundingClientRect().top - top0);
+ }
+ return tops;
+}
+
+/**
+ * After pagination: fill in the page numbers.
+ *
+ * In place, never by re-rendering, and never by committing. The page column has
+ * a fixed width, so writing "12" where "" was moves nothing and the pagination
+ * this was derived from stays valid — no second pass, no fixpoint. Only when
+ * the ENTRY COUNT disagrees with the DOM (a heading was added while the caret
+ * sat elsewhere and nothing re-rendered) is the list rebuilt wholesale.
+ */
+export function paintPages(ctx: FeatureContext, metrics: Metrics, host: HTMLElement): void {
+ const doc = ctx.store.doc;
+ pageCache = headingPages(metrics, measureTops(doc, host));
+ const entries = buildToc(doc, pageCache);
+ for (const box of Array.from(host.querySelectorAll<HTMLElement>('[data-kind="toc"]'))) {
+ const rows = Array.from(box.querySelectorAll<HTMLElement>('a[data-goto]'));
+ if (rows.length !== entries.length) {
+ const list = box.querySelector<HTMLElement>('.t-toc');
+ const html = tocEntriesHtml(entries);
+ if (list) list.outerHTML = html;
+ else box.insertAdjacentHTML('beforeend', html);
+ continue;
+ }
+ rows.forEach((row, i) => {
+ const e = entries[i];
+ const pg = row.querySelector<HTMLElement>('.t-toc-p');
+ const txt = row.querySelector<HTMLElement>('.t-toc-t');
+ const num = row.querySelector<HTMLElement>('.t-toc-n');
+ const page = e.page === undefined ? '' : String(e.page);
+ if (pg && pg.textContent !== page) pg.textContent = page;
+ if (txt && txt.textContent !== e.text) txt.textContent = e.text;
+ if (num && num.textContent !== (e.number ?? '')) num.textContent = e.number ?? '';
+ if (row.dataset.goto !== e.id) row.dataset.goto = e.id;
+ });
+ }
+}
+
+/** Insert a contents block above the caret's block, or at the top. */
+export function insertToc(ctx: FeatureContext): void {
+ if (!wired) { ctx.toast(t('The table of contents needs the core render hook.')); return; }
+ const doc = ctx.store.doc;
+ const caret = ctx.editor.caret();
+ // above the caret's block; with no caret, under a leading title — a contents
+ // page belongs beneath the document's name, which is where authors put it
+ let at = 0;
+ if (caret) at = Math.max(0, doc.body.findIndex(b => b.id === caret.id));
+ else while (at < doc.body.length && doc.body[at].kind === 'h1') at++;
+ const id = `toc-${Math.random().toString(36).slice(2, 10)}`;
+ const heading = t('Contents');
+ ctx.store.commit(d => {
+ d.body.splice(at, 0, { id, kind: TOC_KIND, text: heading });
+ });
+ ctx.editor.render();
+ ctx.refresh();
+ ctx.toast(t('Contents inserted. Page numbers fill in as the document paginates.'));
+}
+
+/** Toggle the document-level switch. */
+export function toggleNumbering(ctx: FeatureContext): void {
+ const on = !sectionSettings(ctx.store.doc).numbered;
+ ctx.store.commit(d => setNumbered(d, on));
+ numbers = null;
+ ctx.editor.render();
+ ctx.refresh();
+ ctx.toast(on ? t('Sections are numbered.') : t('Section numbering is off.'));
+}
+
+/** Exclude the caret's heading from numbering, or put it back. */
+export function toggleExclude(ctx: FeatureContext): void {
+ const caret = ctx.editor.caret();
+ const block = caret ? ctx.store.block(caret.id) : undefined;
+ if (!block || !isHeading(block)) { ctx.toast(t('Put the caret in a heading first.')); return; }
+ const off = (block.role ?? '') !== EXCLUDE_ROLE;
+ ctx.store.commit(d => {
+ const b = d.body.find(x => x.id === block.id);
+ if (!b) return;
+ if (off) b.role = EXCLUDE_ROLE; else delete b.role;
+ }, { scope: { block: block.id } });
+ numbers = null;
+ ctx.editor.render();
+ ctx.refresh();
+ ctx.toast(off ? t('This heading is no longer numbered.') : t('This heading is numbered again.'));
+}
+
+// The icon follows type/src/icons.ts exactly: 24×24 box, rendered at 16px,
+// stroke currentColor at width 2, round caps and joins. It lives here rather
+// than in icons.ts because a feature is one file — the recipe is what must not
+// drift, not the location.
+const TOC_ICON =
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16"' +
+ ' fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
+ '<line x1="4" y1="6" x2="14" y2="6"/><line x1="4" y1="12" x2="12" y2="12"/>' +
+ '<line x1="4" y1="18" x2="15" y2="18"/><line x1="19" y1="6" x2="20" y2="6"/>' +
+ '<line x1="19" y1="12" x2="20" y2="12"/><line x1="19" y1="18" x2="20" y2="18"/></svg>';
+
+// ── registration. Labels are GETTERS so t() runs when the chrome is built,
+// never at module evaluation — a translated string frozen at import is the
+// i18n bug this codebase names explicitly.
+features.registerTool({
+ id: 'toc',
+ icon: TOC_ICON,
+ get title() { return t('Insert a table of contents'); },
+ group: 'insert',
+ label: () => t('Contents'),
+ order: 60,
+ run: insertToc,
+});
+
+// 'Number sections' is a document PROPERTY and lives in the properties panel.
+
+// NO ⋯ entry for excluding a heading: it is a property of the heading under
+// the caret, and it lives as a checkbox in the properties panel's Text section,
+// where it can SHOW its state instead of only offering to flip it.
+
+/**
+ * Soft wiring.
+ *
+ * The three core hooks this feature needs (see NEEDS FROM THE CORE) do not
+ * exist yet. Looking them up by name rather than importing them keeps `tsc`
+ * clean and the app running BEFORE the patch lands, and needs no edit here
+ * AFTER it lands — the feature simply starts working. The casts are the only
+ * thing the patch makes unnecessary.
+ */
+/**
+ * One indirection, and it earns its keep: naming the export through a VARIABLE
+ * keeps the bundler from resolving it statically, so a hook that does not exist
+ * yet is `undefined` at run time instead of a build warning on every build.
+ */
+const soft = (mod: object, name: string): unknown => (mod as Record<string, unknown>)[name];
+
+function wire(): void {
+ const reg = soft(render, 'registerBlockDecorator');
+ if (typeof reg === 'function') {
+ (reg as (d: (b: Block, base: string) => string | null) => void)((b, base) => {
+ if (!ctxRef) return null;
+ const doc = ctxRef.store.doc;
+ return decorate(doc, b, base, { numbers: numberCache(doc), pages: pageCache });
+ });
+ wired = true;
+ }
+ const ready = soft(features, 'registerReady');
+ if (typeof ready === 'function') {
+ (ready as (f: (c: FeatureContext) => void) => void)(onReady);
+ }
+ const paginated = soft(features, 'registerPaginated');
+ if (typeof paginated === 'function') {
+ (paginated as (f: (c: FeatureContext, m: Metrics, h: HTMLElement) => void) => void)(
+ (ctx, metrics, host) => { if (ctxRef) paintPages(ctx, metrics, host); });
+ }
+}
+
+function onReady(ctx: FeatureContext): void {
+ ctxRef = ctx;
+ // the numbering is a derivation of the document, so it is invalidated by the
+ // document and by nothing else
+ ctx.store.on(() => { numbers = null; });
+ // Clicking an entry goes to the heading. Delegated, because the entries are
+ // rebuilt from scratch whenever anything changes and a listener per row would
+ // be attached to elements that no longer exist.
+ ctx.editor.host.addEventListener('click', e => {
+ const row = (e.target as HTMLElement | null)?.closest?.('a[data-goto]') as HTMLElement | null;
+ if (!row) return;
+ e.preventDefault();
+ ctx.editor.host.querySelector(`[data-id="${CSS.escape(row.dataset.goto!)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ });
+ // the first paint happened before the context existed, so it has no numbers
+ if (wired) ctx.refresh();
+}
+
+wire();
diff --git a/type/src/track.ts b/type/src/track.ts
new file mode 100644
index 00000000..6ea3fb43
--- /dev/null
+++ b/type/src/track.ts
@@ -0,0 +1,270 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// TRACKED CHANGES.
+//
+// Two jobs are easy to confuse, and this app does both:
+//
+// redline.ts — compare two SNAPSHOTS and report what moved. Derived, needs
+// nothing in the format, works across a file someone mailed
+// back. This is the review most contracts actually get.
+// track.ts — record each edit AS IT IS MADE, attributed. This is what
+// people mean by "turn on track changes", and it is the one a
+// lawyer expects to see before signing.
+//
+// They meet in the middle: both produce ins/del marks, so ONE review UI serves
+// both and redline can generate a tracked document.
+//
+// THE REPRESENTATION. A tracked deletion does not remove characters — it marks
+// them. That is the whole trick, and everything below follows from it:
+//
+// - rejecting a deletion is possible, because the text never left
+// - the marks ride on the same offsets as every other mark, so spliceText
+// moves them for free and the CRDT merges them like any other mark
+// - a block's `text` is no longer what the document SAYS. Anything reading
+// prose out of a block must skip del ranges, which is what textOf is for.
+//
+// That last point is the sharp edge. Word count, find, print-to-plain, export:
+// each has to decide whether it wants the text with deletions or without.
+
+import type { Block, TypeDoc } from './model.ts';
+import { spliceText } from './model.ts';
+import { normalize, type Mark } from './inline.ts';
+
+/** Is the document recording edits? Absent means no — old files are untracked. */
+export const tracking = (doc: TypeDoc): boolean => doc.track === true;
+
+/**
+ * The prose a reader sees: insertions included, deletions skipped.
+ *
+ * Defined in model.ts (which this module imports, so it cannot be the other way
+ * round) and re-exported here, where callers look for it. wordCount uses the
+ * same function, so the count and the text can never disagree.
+ */
+export { readerText as textOf } from './model.ts';
+
+/** Every tracked mark in the document, with the block it belongs to. */
+export interface Change { block: string; mark: Mark; text: string }
+export function changes(doc: TypeDoc): Change[] {
+ const out: Change[] = [];
+ for (const b of doc.body) {
+ for (const m of b.marks ?? []) {
+ if (m.t === 'ins' || m.t === 'del') out.push({ block: b.id, mark: m, text: b.text.slice(m.from, m.to) });
+ }
+ }
+ return out;
+}
+
+/**
+ * Re-express an edit as tracked changes.
+ *
+ * `prev` is the block before the edit and `next` after — which is what the
+ * editor has, because it reads the block back out of contentEditable rather
+ * than applying operations. The two are diffed by common prefix and suffix:
+ * one removal and one insertion, which is what a keystroke, a paste and a
+ * type-over-selection each are.
+ *
+ * The removal is UNDONE — the characters come back — and marked `del`; the
+ * insertion is marked `ins`. So the model keeps every character anyone typed
+ * or deleted, and the reader is shown the difference.
+ */
+export interface Span { head: number; removed: string; added: string }
+
+/**
+ * What changed between two versions of a block: one removal and one insertion.
+ *
+ * Exported because the EDITOR needs the same numbers to place the caret. A
+ * tracked deletion restores characters the browser had already taken out, so
+ * the caret position contentEditable left behind is wrong by exactly the length
+ * of the restored text — and computing that from a second, slightly different
+ * diff is how the caret ends up one character off on some edits and not others.
+ */
+export function editSpan(prev: Block, next: Block): Span {
+ const a = prev.text, b = next.text;
+ let head = 0;
+ while (head < a.length && head < b.length && a[head] === b[head]) head++;
+ let tail = 0;
+ while (tail < a.length - head && tail < b.length - head
+ && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;
+ return { head, removed: a.slice(head, a.length - tail), added: b.slice(head, b.length - tail) };
+}
+
+/** Where the caret belongs after `trackEdit` — past anything just typed. */
+export const caretAfter = (s: Span): number => s.head + s.added.length;
+
+export function trackEdit(prev: Block, next: Block, by: string, at: string): Block {
+ if (prev.text === next.text) return next;
+ const { head, removed, added } = editSpan(prev, next);
+
+ // Typing INSIDE an existing deletion would otherwise put new words in the
+ // middle of struck-through text, where they read as also deleted. The edit
+ // is pushed to the end of the del range instead.
+ let out = next;
+ if (added) {
+ const insAt = head;
+ out = markRange(out, insAt, insAt + added.length, 'ins', by, at);
+ }
+ if (removed) {
+ // put the characters back, immediately after the insertion, and mark them
+ const restoreAt = head + added.length;
+ out = spliceText(out, restoreAt, 0, removed);
+ out = markRange(out, restoreAt, restoreAt + removed.length, 'del', by, at);
+ // A deletion of text that was itself an untracked INSERTION by the same
+ // author is just a correction: drop both rather than showing someone
+ // deleting their own unsaved typing.
+ out = collapseSelfDeletes(out);
+ }
+ return out;
+}
+
+/** Add a mark over a range, merging with an adjacent same-kind mark by the same author. */
+function markRange(b: Block, from: number, to: number, t: 'ins' | 'del', by: string, at: string): Block {
+ if (to <= from) return b;
+ const marks = [...(b.marks ?? [])];
+ const touching = marks.findIndex(m => m.t === t && m.by === by && (m.to === from || m.from === to));
+ if (touching >= 0) {
+ const m = marks[touching];
+ marks[touching] = { ...m, from: Math.min(m.from, from), to: Math.max(m.to, to), at };
+ } else {
+ marks.push({ t, from, to, by, at });
+ }
+ const out: Block = { ...b, marks: normalize(marks, b.text.length) };
+ if (!out.marks?.length) delete out.marks;
+ return out;
+}
+
+/** An `ins` range fully covered by a `del` by the same author cancels out. */
+function collapseSelfDeletes(b: Block): Block {
+ const marks = b.marks ?? [];
+ const ins = marks.filter(m => m.t === 'ins');
+ const del = marks.filter(m => m.t === 'del');
+ for (const d of del) {
+ const hit = ins.find(i => i.by === d.by && i.from >= d.from && i.to <= d.to);
+ if (!hit) continue;
+ // remove the text the pair covers, and both marks with it
+ const cut = spliceText(b, d.from, d.to - d.from, '');
+ cut.marks = (cut.marks ?? []).filter(m => !(m.t === 'del' && m.from === d.from && m.to === d.from));
+ if (!cut.marks.length) delete cut.marks;
+ return cut;
+ }
+ return b;
+}
+
+const same = (a: Mark, b: Mark) => a.t === b.t && a.from === b.from && a.to === b.to;
+
+/**
+ * Accept or reject one tracked change.
+ *
+ * accept ins → keep the text, drop the mark reject ins → drop the text
+ * accept del → drop the text reject del → keep it, drop the mark
+ */
+export function resolve(b: Block, mark: Mark, accept: boolean): Block {
+ const keepText = mark.t === 'ins' ? accept : !accept;
+ if (keepText) {
+ const marks = (b.marks ?? []).filter(m => !same(m, mark));
+ const out: Block = { ...b };
+ if (marks.length) out.marks = marks; else delete out.marks;
+ return out;
+ }
+ // Dropping the text takes the mark with it: spliceText discards marks whose
+ // range is entirely inside the removed span.
+ const out = spliceText(b, mark.from, mark.to - mark.from, '');
+ const marks = (out.marks ?? []).filter(m => !(m.t === mark.t && m.from === mark.from && m.to === mark.from));
+ if (marks.length) out.marks = marks; else delete out.marks;
+ return out;
+}
+
+/** Accept or reject every tracked change in the document, in place. */
+export function resolveAll(doc: TypeDoc, accept: boolean): void {
+ for (let i = 0; i < doc.body.length; i++) {
+ let b = doc.body[i];
+ for (;;) {
+ // Re-read the marks each pass: resolving one shifts the offsets of the
+ // rest, so a cached list would apply the second change at stale
+ // coordinates. Slower, and correct.
+ const m = (b.marks ?? []).find(x => x.t === 'ins' || x.t === 'del');
+ if (!m) break;
+ b = resolve(b, m, accept);
+ }
+ doc.body[i] = b;
+ }
+}
+
+// ─────────────────────────────────────────────────────────────── navigation
+//
+// review.ts needs to answer two questions to put "Next", "Previous" and
+// "N of M" on screen: which change (if any) contains the caret, and which
+// change is next from wherever the caret happens to be. Both are pure — they
+// take a caret POSITION, never touch the DOM, and are exactly the numbers a
+// UI needs to move a real caret and scroll a real element into view. Kept
+// here, not in review.ts, for the same reason the rest of this file is here:
+// so scripts/test-type-track.ts can run them under plain node.
+
+/** The index of the change in `list` whose range contains (blockId, at); -1 if none. */
+export function changeAt(list: readonly Change[], blockId: string, at: number): number {
+ return list.findIndex(c => c.block === blockId && at >= c.mark.from && at <= c.mark.to);
+}
+
+/**
+ * Step to the next (`dir` 1) or previous (`dir` -1) tracked change from a
+ * caret at (blockId, at), in DOCUMENT ORDER, wrapping past either end.
+ *
+ * `changes()` walks doc.body in order and, within a block, its marks —
+ * already sorted by `from` because `normalize` ends every mutation that way —
+ * so `list` arrives in document order already, and "nearest" is simply the
+ * first (dir 1) or last (dir -1) candidate in array order. No second sort.
+ *
+ * The two directions are NOT mirror images, on purpose. Both must skip the
+ * change the caret is currently inside — reachable by direct selection or by
+ * a previous step — so "Next" twice in a row always advances. `blockId` and
+ * `at` are read straight off `editor.caret()` after a step, which reports the
+ * START of the just-selected range: so a change's own `from` never counts as
+ * "after" it (excluded with a strict `>`), while a change's `to` DOES count
+ * as "before" it when the caret sits at or past that same `to` (non-strict
+ * `<=`) — because `at` there is some OTHER change's `from`, or plain text,
+ * never this change's own start. Get the strictness backwards and either
+ * "Next" repeats the change you are already on, or "Previous" does.
+ *
+ * `blockId` may be null (no caret): dir 1 starts at the first change in the
+ * document, dir -1 at the last — so pressing "next" with nothing selected
+ * lands on the first change instead of nowhere.
+ */
+export function stepChange(doc: TypeDoc, list: readonly Change[], blockId: string | null,
+ at: number, dir: 1 | -1): number | null {
+ if (!list.length) return null;
+ if (blockId === null) return dir === 1 ? 0 : list.length - 1;
+ const order = new Map(doc.body.map((b, i) => [b.id, i]));
+ const here = order.get(blockId) ?? Number.MAX_SAFE_INTEGER;
+ const candidates: number[] = [];
+ for (let i = 0; i < list.length; i++) {
+ const c = list[i];
+ const ci = order.get(c.block) ?? Number.MAX_SAFE_INTEGER;
+ const hit = dir === 1
+ ? (ci > here || (ci === here && c.mark.from > at))
+ : (ci < here || (ci === here && c.mark.to <= at));
+ if (hit) candidates.push(i);
+ }
+ if (candidates.length) return dir === 1 ? candidates[0] : candidates[candidates.length - 1];
+ return dir === 1 ? 0 : list.length - 1; // wrap
+}
+
+// ───────────────────────────────────────────────────────────── display mode
+//
+// How a reviewer chooses to SEE a tracked document — every mark shown, shown
+// as if every change were accepted, or shown as if every change were
+// rejected. A VIEWER preference, never the document's: two people opening the
+// same contract may want different views of it right now, and neither
+// answer belongs in bytes they both sign. Exactly the reasoning
+// commentsHidden() in comments.ts already follows, for the same reason.
+//
+// Kept as a closed, parseable string here — pure, no localStorage, no DOM —
+// so the one thing that must be provably true (choosing a view cannot alter
+// the document) is checkable by the node rig. review.ts owns the localStorage
+// key and the CSS class that actually hides anything; this is just its
+// vocabulary, validated.
+
+export type TrackView = 'all' | 'final' | 'original';
+
+/** A stored value, made safe. Anything unrecognised (or absent) is 'all'. */
+export const parseTrackView = (v: string | null | undefined): TrackView =>
+ v === 'final' || v === 'original' ? v : 'all';
diff --git a/type/src/xref.ts b/type/src/xref.ts
new file mode 100644
index 00000000..bbb4ca01
--- /dev/null
+++ b/type/src/xref.ts
@@ -0,0 +1,755 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Captions, automatic figure/table numbering, and cross-references.
+//
+// This is the feature a long document cannot be maintained without, and the one
+// LaTeX users will not give up: you write "see Table 2", someone inserts a table
+// three pages earlier, and the sentence still says the right thing.
+//
+// ═══════════════════════════════════════════════════════ NEEDS FROM THE CORE
+//
+// Everything below is written and tested against the model as it will be. The
+// numbering, the resolution and the atom/string plumbing are complete and run
+// in node today (scripts/test-type-xref.ts); what they cannot do without these
+// edits is REACH the editor, because a feature module may not add a block kind
+// or an inline atom by itself. Each is minimal and each says why.
+//
+// 1. type/src/model.ts — the caption block kind
+// - BlockKind: add 'caption'
+// export type BlockKind = … | 'cell' | 'caption';
+// - add, beside CellRef:
+// export interface CaptionRef { kind: 'table' | 'figure'; of?: string }
+// - Block: add
+// /** caption placement; only meaningful on a `caption` block */
+// caption?: CaptionRef;
+// /** cross-references, by offset into `text` — atoms, like `notes` */
+// refs?: XrefRef[]; // { to: string; at: number; style?: 'label'|'page'|'both' }
+// WHY a block and not a field on the table: there IS no table block to hang
+// a caption on (a table is a run of `cell` blocks sharing an id), and a
+// caption must have its own stable id anyway — that id is what a reference
+// points at, and what the redline aligns on so an edited caption reports as
+// an edited caption. It is also what makes a figure caption drop in later
+// with no redesign: same block, `kind:'figure'`, `of` naming the image.
+//
+// 2. type/src/model.ts — parseDoc, in the per-block loop, after the `cell` case:
+// if (kind === 'caption') {
+// const c = isObj(b.caption) ? b.caption as Partial<CaptionRef> : undefined;
+// out.caption = { kind: c?.kind === 'figure' ? 'figure' : 'table',
+// ...(typeof c?.of === 'string' && c.of ? { of: c.of } : {}) };
+// }
+// const refs = Array.isArray(b.refs)
+// ? (b.refs as XrefRef[]).filter(r => isObj(r) && typeof r.to === 'string' && typeof r.at === 'number')
+// .map(r => ({ to: r.to, at: Math.max(0, Math.min(r.at, text.length)),
+// ...(r.style === 'page' || r.style === 'both' ? { style: r.style } : {}) }))
+// .sort((x, y) => x.at - y.at)
+// : undefined;
+// if (refs?.length) out.refs = refs;
+// NOTE — and this is a deliberate difference from footnotes: DO NOT drop a
+// reference whose target is missing. parseDoc drops dangling `notes` because
+// a marker with no note behind it renders as a number pointing at nothing.
+// A dangling REFERENCE is the opposite case: the author wrote "see ⟨that
+// table⟩" and the table was deleted. Dropping it silently deletes the
+// sentence's meaning and leaves prose reading "see ." Keeping it renders a
+// visible ?? that says out loud that something must be fixed — the LaTeX
+// behaviour, and the only safe one. See `BROKEN_TEXT` below.
+//
+// 3. type/src/model.ts — spliceText, so a reference follows the edit exactly as
+// a footnote anchor does. Beneath `if (block.notes?.length) { … }` add:
+// if (block.refs?.length) {
+// const r = shiftRefs(block.refs, at, removed, added.length);
+// if (r.length) out.refs = r; else delete out.refs;
+// }
+// with `import { shiftRefs } from './xref.ts';` at the top. That import is
+// safe: this module imports NOTHING from model.ts at value level (only
+// types), precisely so the core can call into it without a cycle — which is
+// also why `mint()` below exists instead of importing model's `uid`.
+//
+// 4. type/src/render.ts — the atom and the caption label
+// import { captionPrefixHtml, isXrefAtom, refAtoms, readXrefs } from './xref.ts';
+// - TAG: add `caption: 'figcaption'`
+// - blockHtml: merge `refAtoms(b)` into the `inject` map (they are offsets
+// into the same text as the note anchors), and return
+// `captionPrefixHtml(b) + (html || '<br>')`
+// - readBlock: pass `el => isNoteAtom(el) || isXrefAtom(el)` as the atom
+// predicate, and after the notes line add
+// const refs = readXrefs(atoms); if (refs.length) out.refs = refs; else delete out.refs;
+// - renderBody: after `numberNotes(host, doc)` call `numberXrefs(host, doc)`
+// (A general "atom registry" in render.ts would be tidier and would suit the
+// next feature that needs one — comments, index entries. It is a bigger
+// change than this feature is owed, so this mirrors how notes are wired.)
+//
+// 5. type/src/print.ts — one line, so paper agrees with screen. After the body
+// HTML is assembled (the `out.join('')` that feeds `.t-body`):
+// import { fillXrefsHtml, captionIndex } from './xref.ts';
+// html = fillXrefsHtml(html, captionIndex(doc.body, docLang(doc)));
+// The DOM pass and the string pass fill the SAME atoms from the SAME index,
+// which is what stops the printed numbering drifting from the screen's.
+//
+// 6. type/src/registry.ts — `import './xref.ts';` (mine to add, and added).
+//
+// Until 1–5 land, the interface augmentation at the bottom of this file keeps
+// `tsc` honest and the pure functions keep working; delete it when they do. The
+// two entry points refuse to run until then (see `corePatched`), so a build
+// carrying this file ahead of the patch cannot damage a document.
+//
+// VERIFIED, not asserted: patches 1–4 were applied to a throwaway copy of
+// type/src outside the repo, where `tsc --noEmit` is clean and a caption block
+// renders `<span class="t-cap-num" data-cap="c1">Table 1.</span>Fee schedule`,
+// a reference renders `Table 1`, spliceText moves a reference anchor from 6 to
+// 9 on a three-character insertion, and parseDoc round-trips both fields.
+//
+// ═════════════════════════════════════════ WHY A REFERENCE IS AN ATOM, NOT TEXT
+//
+// A reference sits inside a paragraph's text. It could be (a) literal text the
+// feature rewrites, (b) a MARK over a run whose text is the number, or (c) an
+// ATOM at an offset that occupies no characters — what a footnote marker
+// already is. It is (c), and the three properties this app is built on each
+// rule out the other two:
+//
+// · THE REDLINE DIFFS PLAIN TEXT, WORD BY WORD. With (a) or (b) the
+// characters "Table 2" live in `text`, so inserting an unrelated table on
+// page 1 rewrites every later reference — and the review pane reports a
+// dozen edits nobody made, in a document whose whole point is that a
+// reviewer can trust what it says changed. As an atom the text never moves:
+// renumbering is invisible to the diff, which is correct, because nobody
+// edited anything.
+// · SIGNATURES CANONICALISE THE MODEL. A stored number is content, so it is
+// signed. Renumbering would then break every signature on the document
+// without a human touching a word — and, worse, a signature would attest to
+// a number the reader is not being shown once it re-derives. The atom
+// stores an id and a style, both of which are stable under renumbering.
+// · THE CARET IS (blockId, offset). An atom has a position and no width, and
+// spliceText's arithmetic for exactly that already exists and is tested —
+// `shiftRefs` here is the same rule as the notes rule, on purpose, so there
+// is one concept in the codebase and not two.
+//
+// The cost is that the visible words are not in the model, so anything reading
+// the document as prose (search, export to plain text) must resolve references
+// itself. `refText()` is that function and it is pure.
+//
+// ═══════════════════════════════════════════════ WHOSE LANGUAGE SAYS "TABLE"?
+//
+// The word "Table" in "Table 2" is USER-VISIBLE and translatable, and it is NOT
+// t(). t() follows the READER: locale comes from navigator.language, and
+// language never enters the document format. That is right for chrome, and
+// wrong here, because this string is not chrome — it renders INTO the document,
+// between the author's sentences, and gets printed and signed alongside them.
+//
+// Follow the reader's locale and a French contract reads "Le calendrier des
+// paiements figure au Table 2" for an English reader and "…au Tableau 2" for a
+// French one: the label disagrees with the prose around it, and the SAME BYTES
+// show two different documents to two people. For an app whose differentiator
+// is that a signed document says one thing, that is disqualifying — nobody can
+// sign "whatever this renders as in your browser".
+//
+// So the caption label follows the DOCUMENT's language, `doc.lang` (BCP 47,
+// default 'en'; format-additive, so old files simply say English). That is not
+// a viewer preference sneaking into the format — it is the same fact `<html
+// lang>` carries, content metadata about what language the words are in, no
+// different from `title` being in the document. The chrome around the feature —
+// the buttons, the panel, the picker — stays on t() and follows the reader,
+// which is the correct split: the reader's UI in the reader's language, the
+// author's document in the author's.
+//
+// Hence CAPTION_WORDS below rather than t() calls: a t() catalog is keyed by the
+// viewer's locale and cannot answer "what is 'Table' in the document's
+// language". The two are different questions and only one of them is i18n.
+
+import type { Block, TypeDoc } from './model.ts';
+import { blockHtml, TAG } from './render.ts';
+import { registerKey, registerPanel, registerTool,
+ type FeatureContext } from './features.ts';
+import { t } from './i18n.ts';
+
+// ───────────────────────────────────────────────────────────────────── model
+
+export type CaptionKind = 'table' | 'figure';
+export type RefStyle = 'label' | 'page' | 'both';
+
+/** What a caption block captions. `of` names the object; numbering never uses it. */
+export interface CaptionRef { kind: CaptionKind; of?: string }
+
+/** A cross-reference anchored INTO a block's text, by character offset. */
+export interface XrefRef { to: string; at: number; style?: RefStyle }
+
+/** The block kind a caption is. Cast until model.ts learns the kind (patch 1). */
+export const CAPTION: Block['kind'] = 'caption' as unknown as Block['kind'];
+
+/** What a broken reference renders as. Visible, and deliberately ugly. */
+export const BROKEN_TEXT = '??';
+
+/**
+ * A fresh id. Mirrors model.ts `uid`, and is a copy rather than an import so
+ * that model.ts can import `shiftRefs` from here without a value-level cycle.
+ */
+const mint = (p = 'b'): string => {
+ const r = globalThis.crypto?.randomUUID?.();
+ return r ? `${p}-${r.slice(0, 8)}` : `${p}-${Math.random().toString(36).slice(2, 10)}`;
+};
+
+// ───────────────────────────────────────────────────── the document's language
+
+/**
+ * The words that render into the document, per language.
+ *
+ * Not t(): see the header. These follow `doc.lang`, not the reader. The eight
+ * languages are the suite's UI languages, which is a reasonable starting set
+ * and not a limit — an unknown language falls back to English rather than to
+ * nothing, because "Table 2" is wrong in Finnish but readable, and "" is not.
+ */
+export const CAPTION_WORDS: Record<string, { table: string; figure: string; page: string }> = {
+ en: { table: 'Table', figure: 'Figure', page: 'page' },
+ fr: { table: 'Tableau', figure: 'Figure', page: 'page' },
+ de: { table: 'Tabelle', figure: 'Abbildung', page: 'Seite' },
+ es: { table: 'Tabla', figure: 'Figura', page: 'página' },
+ it: { table: 'Tabella', figure: 'Figura', page: 'pagina' },
+ ja: { table: '表', figure: '図', page: 'ページ' },
+ 'zh-hans': { table: '表', figure: '图', page: '页' },
+ 'zh-hant': { table: '表', figure: '圖', page: '頁' },
+};
+
+/** The document's language tag, normalised. `lang` is format-additive. */
+export function docLang(doc: Partial<TypeDoc> | Record<string, unknown>): string {
+ const raw = (doc as Record<string, unknown>).lang;
+ return typeof raw === 'string' && raw.trim() ? raw.trim().toLowerCase() : 'en';
+}
+
+/** Resolve a BCP 47 tag onto the word table: exact, then script, then base. */
+function words(lang: string): { table: string; figure: string; page: string } {
+ const l = lang.toLowerCase();
+ if (CAPTION_WORDS[l]) return CAPTION_WORDS[l];
+ // zh-CN / zh-TW / zh-Hant-HK → the two written forms
+ if (l.startsWith('zh')) {
+ const trad = /hant|tw|hk|mo/.test(l);
+ return CAPTION_WORDS[trad ? 'zh-hant' : 'zh-hans'];
+ }
+ const base = l.split('-')[0];
+ return CAPTION_WORDS[base] ?? CAPTION_WORDS.en;
+}
+
+export const captionWord = (kind: CaptionKind, lang = 'en'): string => words(lang)[kind];
+export const pageWord = (lang = 'en'): string => words(lang).page;
+
+/** "Table 2" — the label, in the document's language. A space separates it in
+ * Latin scripts; CJK sets the number tight against the word, as those
+ * typographies do. */
+export function joinLabel(word: string, n: number, lang = 'en'): string {
+ return /^(ja|zh|ko)/.test(lang.toLowerCase()) ? `${word}${n}` : `${word} ${n}`;
+}
+
+// ───────────────────────────────────────────────────────────────── numbering
+
+export interface CaptionEntry {
+ /** the caption BLOCK's id — this is what a reference points at */
+ id: string;
+ kind: CaptionKind;
+ /** DERIVED, never stored */
+ n: number;
+ /** "Table" in the document's language */
+ word: string;
+ /** "Table 2" */
+ label: string;
+ /** the caption's own words */
+ text: string;
+ /** the object captioned, when known (a table id, later an image block id) */
+ of?: string;
+ /** position in `body`, for ordering and for the panel's jump */
+ index: number;
+}
+
+const captionOf = (b: Block): CaptionRef | undefined =>
+ b.kind === CAPTION ? (b.caption ?? { kind: 'table' }) : undefined;
+
+/**
+ * Every caption, numbered in DOCUMENT ORDER with a counter per kind.
+ *
+ * Numbering is derived on every read and stored nowhere. Insert a table in the
+ * middle and everything after it renumbers, which is the whole point; a number
+ * written into the JSON would be wrong the instant that happened — the rule
+ * render.ts's numberNotes already follows for footnotes, for the same reason.
+ */
+export function captionEntries(body: readonly Block[], lang = 'en'): CaptionEntry[] {
+ const counters: Record<CaptionKind, number> = { table: 0, figure: 0 };
+ const out: CaptionEntry[] = [];
+ body.forEach((b, index) => {
+ const cap = captionOf(b);
+ if (!cap) return;
+ const kind: CaptionKind = cap.kind === 'figure' ? 'figure' : 'table';
+ const n = ++counters[kind];
+ const word = captionWord(kind, lang);
+ out.push({ id: b.id, kind, n, word, label: joinLabel(word, n, lang),
+ text: b.text, ...(cap.of ? { of: cap.of } : {}), index });
+ });
+ return out;
+}
+
+/** The same, keyed by caption id — what reference resolution looks things up in. */
+export function captionIndex(body: readonly Block[], lang = 'en'): Map<string, CaptionEntry> {
+ return new Map(captionEntries(body, lang).map(e => [e.id, e]));
+}
+
+// ─────────────────────────────────────────────────────────────── resolution
+
+export type Resolved =
+ | { ok: true; text: string; entry: CaptionEntry }
+ | { ok: false; text: string };
+
+/**
+ * What a reference renders as.
+ *
+ * A MISSING TARGET IS NOT AN ERROR TO SWALLOW. It renders as `??` — visible,
+ * styled as a problem, and never empty. A reference that renders as nothing is
+ * the worst outcome available: the sentence silently becomes "as shown in ."
+ * and nobody proof-reading a 90-page contract will catch it. LaTeX prints ??
+ * for the same reason, and this keeps the reference in the model so that
+ * restoring the deleted table (undo, or accepting a rejected redline) makes
+ * every reference to it correct again with no repair step.
+ *
+ * `pageOf` is optional: page numbers exist only where pagination has been
+ * computed (the editor, print), so a style that asks for one degrades to the
+ * label rather than to a lie.
+ */
+export function refText(index: Map<string, CaptionEntry>, ref: XrefRef,
+ opts: { lang?: string; pageOf?: (blockId: string) => number | undefined } = {}): Resolved {
+ const entry = index.get(ref.to);
+ if (!entry) return { ok: false, text: BROKEN_TEXT };
+ const style = ref.style ?? 'label';
+ const page = style === 'label' ? undefined : opts.pageOf?.(entry.id);
+ const pw = pageWord(opts.lang ?? 'en');
+ if (style === 'page' && page !== undefined) return { ok: true, text: `${pw} ${page}`, entry };
+ if (style === 'both' && page !== undefined) return { ok: true, text: `${entry.label} (${pw} ${page})`, entry };
+ return { ok: true, text: entry.label, entry };
+}
+
+/** Every reference in the document, in order. */
+export function refsIn(body: readonly Block[]): Array<{ block: Block; ref: XrefRef }> {
+ const out: Array<{ block: Block; ref: XrefRef }> = [];
+ for (const b of body) for (const ref of b.refs ?? []) out.push({ block: b, ref });
+ return out;
+}
+
+/** The ones pointing at nothing — what the panel shows and what a pre-send
+ * check should refuse to ignore. */
+export function brokenRefs(body: readonly Block[]): Array<{ block: Block; ref: XrefRef }> {
+ const index = captionIndex(body);
+ return refsIn(body).filter(({ ref }) => !index.has(ref.to));
+}
+
+// ────────────────────────────────────────────────────────── offset arithmetic
+
+/**
+ * Move reference anchors to follow an edit that replaced [at, at+removed) with
+ * `added` characters. THE SAME RULE footnote anchors use — deliberately: an
+ * anchor inside the replaced span is dropped because the words it sat in are
+ * gone, and everything after it shifts.
+ *
+ * model.ts spliceText calls this (patch 3). It is here, and pure, so it can be
+ * tested without a DOM and without the core edit having landed.
+ */
+export function shiftRefs(refs: readonly XrefRef[], at: number, removed: number, added: number): XrefRef[] {
+ const end = at + removed;
+ const delta = added - removed;
+ return refs
+ .filter(r => !(r.at > at && r.at < end))
+ .map(r => (r.at >= end ? { ...r, at: r.at + delta } : { ...r }))
+ .sort((x, y) => x.at - y.at);
+}
+
+/** Add a reference to a block at an offset. Pure — the caller commits it. */
+export function withRef(block: Block, at: number, to: string, style?: RefStyle): Block {
+ const ref: XrefRef = { to, at: Math.max(0, Math.min(at, block.text.length)),
+ ...(style && style !== 'label' ? { style } : {}) };
+ return { ...block, refs: [...(block.refs ?? []), ref].sort((x, y) => x.at - y.at) };
+}
+
+/** A new caption block for an object. Its id is minted ONCE and never again:
+ * it is what every reference to this table points at, so re-minting it would
+ * break every sentence that mentions the table. */
+export function newCaption(kind: CaptionKind, of?: string, text = ''): Block {
+ return { id: mint('cap'), kind: CAPTION, text,
+ caption: { kind, ...(of ? { of } : {}) } };
+}
+
+/**
+ * Where a caption for the block at `i` belongs, and what it captions.
+ *
+ * Inside a table the caption goes AFTER the whole run of cells sharing the
+ * table id — a caption in the middle of a table would split it into two tables,
+ * since grouping is by adjacency.
+ */
+export function captionSite(body: readonly Block[], i: number):
+ { at: number; kind: CaptionKind; of?: string } | null {
+ const here = body[i];
+ if (!here) return null;
+ if (here.kind === CAPTION) return null; // already a caption
+ if (here.kind === 'cell' && here.cell) {
+ const table = here.cell.table;
+ let end = i;
+ while (end + 1 < body.length && body[end + 1].kind === 'cell'
+ && body[end + 1].cell?.table === table) end++;
+ return { at: end + 1, kind: 'table', of: table };
+ }
+ return { at: i + 1, kind: 'figure' };
+}
+
+/** Does this table already have a caption? Keeps the button from making two. */
+export function captionForObject(body: readonly Block[], of: string): Block | undefined {
+ return body.find(b => b.kind === CAPTION && b.caption?.of === of);
+}
+
+// ──────────────────────────────────────────────────── atoms: model → markup
+//
+// Two placeholder atoms are emitted with the block's HTML and FILLED afterwards
+// from the index — the numbering cannot be known block-locally, and doing it in
+// a second pass is exactly what numberNotes does. There are two consumers: the
+// editor fills DOM nodes, print fills a string. Both read the same index, so
+// paper and screen cannot disagree.
+
+const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
+const esc = (s: string) => s.replace(/[&<>"]/g, c => ESC[c]);
+
+/** The atoms a block contributes, keyed by offset — merged into blockHtml's
+ * inject map beside the footnote markers. */
+export function refAtoms(b: Block): Map<number, string> {
+ const m = new Map<number, string>();
+ for (const r of b.refs ?? []) {
+ const prev = m.get(r.at) ?? '';
+ m.set(r.at, prev + `<span class="t-xref" data-xref="${esc(r.to)}"` +
+ `${r.style && r.style !== 'label' ? ` data-style="${esc(r.style)}"` : ''}` +
+ ` contenteditable="false">${BROKEN_TEXT}</span>`);
+ }
+ return m;
+}
+
+/** The label that precedes a caption's own words. Empty for every other kind. */
+export function captionPrefixHtml(b: Block): string {
+ if (b.kind !== CAPTION) return '';
+ return `<span class="t-cap-num" data-cap="${esc(b.id)}" contenteditable="false"></span>`;
+}
+
+/** Is this element one of ours? Both atoms are invisible to the model: the
+ * reference is an id, and the caption label is DERIVED, so neither may come
+ * back through readBlock as text. */
+export const isXrefAtom = (el: Element): boolean =>
+ el.tagName === 'SPAN' && (el.classList.contains('t-xref') || el.classList.contains('t-cap-num'));
+
+/** Read reference atoms back out of a parsed block. Caption labels carry no
+ * `data-xref` and so vanish here, which is correct — they are derived. */
+export function readXrefs(atoms: Array<{ at: number; el: Element }>): XrefRef[] {
+ const out: XrefRef[] = [];
+ for (const a of atoms) {
+ const el = a.el as HTMLElement;
+ const to = el.dataset?.xref;
+ if (!to) continue;
+ const style = el.dataset.style;
+ out.push({ to, at: a.at, ...(style === 'page' || style === 'both' ? { style } : {}) });
+ }
+ return out.sort((x, y) => x.at - y.at);
+}
+
+// ─────────────────────────────────────────────────────────────── filling in
+
+/** Fill both atom kinds in a STRING of block HTML — the print path. Pure, so
+ * the rig can assert that paper renders the same words as the screen. */
+export function fillXrefsHtml(html: string, index: Map<string, CaptionEntry>,
+ opts: { lang?: string; pageOf?: (id: string) => number | undefined } = {}): string {
+ return html.replace(/<span class="t-(xref|cap-num)"([^>]*)>.*?<\/span>/g, (_m, which: string, attrs: string) => {
+ const id = /data-(?:xref|cap)="([^"]*)"/.exec(attrs)?.[1] ?? '';
+ if (which === 'cap-num') {
+ const e = index.get(id);
+ return `<span class="t-cap-num" data-cap="${esc(id)}">${e ? esc(e.label) + '.' : ''}</span>`;
+ }
+ const style = /data-style="([^"]*)"/.exec(attrs)?.[1] as RefStyle | undefined;
+ const r = refText(index, { to: id, at: 0, ...(style ? { style } : {}) }, opts);
+ return `<span class="t-xref${r.ok ? '' : ' t-xref-broken'}" data-xref="${esc(id)}">${esc(r.text)}</span>`;
+ });
+}
+
+/**
+ * Fill both atom kinds in a rendered host — the editor path, called from
+ * renderBody after numberNotes.
+ *
+ * Writes only text and one class, never structure, so it cannot disturb the
+ * caret: nothing an author can put a caret in changes size or identity.
+ */
+export function numberXrefs(host: HTMLElement, doc: TypeDoc,
+ pageOf?: (id: string) => number | undefined): void {
+ const lang = docLang(doc);
+ const index = captionIndex(doc.body, lang);
+ for (const el of host.querySelectorAll<HTMLElement>('span.t-cap-num')) {
+ const e = index.get(el.dataset.cap ?? '');
+ el.textContent = e ? `${e.label}.` : '';
+ }
+ for (const el of host.querySelectorAll<HTMLElement>('span.t-xref')) {
+ const style = el.dataset.style as RefStyle | undefined;
+ const r = refText(index, { to: el.dataset.xref ?? '', at: 0, ...(style ? { style } : {}) },
+ { lang, ...(pageOf ? { pageOf } : {}) });
+ el.textContent = r.text;
+ el.classList.toggle('t-xref-broken', !r.ok);
+ el.title = r.ok ? r.text : t('This reference points at something that is no longer in the document');
+ }
+}
+
+/** The document as prose, with references resolved — for search, plain-text
+ * export, and anything that must read what the reader reads. */
+export function resolvedText(doc: TypeDoc): string {
+ const lang = docLang(doc);
+ const index = captionIndex(doc.body, lang);
+ return doc.body.map(b => {
+ const cap = captionOf(b);
+ const head = cap ? `${index.get(b.id)?.label ?? ''}. ` : '';
+ if (!b.refs?.length) return head + b.text;
+ let out = '', cut = 0;
+ for (const r of [...b.refs].sort((x, y) => x.at - y.at)) {
+ out += b.text.slice(cut, r.at) + refText(index, r, { lang }).text;
+ cut = r.at;
+ }
+ return head + out + b.text.slice(cut);
+ }).join('\n');
+}
+
+// ══════════════════════════════════════════════════════════════════════ chrome
+//
+// From here down is the editor surface: two toolbar buttons, a picker, a panel
+// and a shortcut, all registered through features.ts so main.ts is untouched.
+// Every string here is CHROME and goes through t() — it is the reader's UI, in
+// the reader's language, which is the other half of the argument in the header.
+
+const svg = (body: string) =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" ` +
+ `stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
+const ICON_CAPTION = svg('<rect x="3" y="4" width="18" height="11" rx="2"/><line x1="6" y1="19" x2="18" y2="19"/>');
+const ICON_XREF = svg('<path d="M4 7h9"/><path d="M4 12h6"/><path d="M4 17h9"/><path d="M15 12l5 5-5 5" transform="translate(0,-7)"/>');
+
+/**
+ * Is this build's core patched (patches 1 and 4)?
+ *
+ * Until it is, a caption block would ask the renderer for TAG['caption'] and
+ * get `undefined`, and a reference would be committed into a document that
+ * renders it as nothing — the exact failure this feature exists to prevent,
+ * caused by the feature itself. So the two entry points refuse rather than
+ * damage a document, and say why. PROBED, not assumed: the check renders a
+ * throwaway block and looks for the atom, so it goes green the moment the
+ * patch lands and needs no second edit here.
+ *
+ * (The import of render.ts is a cycle once patch 4 lands. It is safe: neither
+ * module touches the other at evaluation time, only inside functions.)
+ */
+let probed: boolean | null = null;
+export function corePatched(): boolean {
+ if (probed === null) {
+ const probe: Block = { id: 'probe', kind: 'para', text: 'x', refs: [{ to: 'nothing', at: 0 }] };
+ probed = CAPTION in TAG && blockHtml(probe).includes('t-xref');
+ }
+ return probed;
+}
+const refuse = (ctx: FeatureContext): boolean => {
+ if (corePatched()) return false;
+ ctx.toast(t('This build cannot render captions yet — apply the core patch listed at the top of xref.ts'));
+ return true;
+};
+
+/** The block the caret is in, as an index into body. */
+function caretIndex(ctx: FeatureContext): number {
+ const c = ctx.editor.caret();
+ if (!c) return -1;
+ return ctx.store.doc.body.findIndex(b => b.id === c.id);
+}
+
+/** Add a caption to the table (or the block) the caret is in. */
+export function addCaption(ctx: FeatureContext): void {
+ if (refuse(ctx)) return;
+ const i = caretIndex(ctx);
+ if (i < 0) { ctx.toast(t('Put the caret in the table or paragraph to caption')); return; }
+ const site = captionSite(ctx.store.doc.body, i);
+ if (!site) { ctx.toast(t('That is already a caption')); return; }
+ if (site.of) {
+ const existing = captionForObject(ctx.store.doc.body, site.of);
+ if (existing) { ctx.editor.setCaret({ id: existing.id, at: existing.text.length }); ctx.toast(t('This already has a caption')); return; }
+ }
+ const block = newCaption(site.kind, site.of);
+ ctx.store.breakRun();
+ ctx.store.commit(d => { d.body.splice(site.at, 0, block); });
+ ctx.refresh();
+ ctx.editor.setCaret({ id: block.id, at: 0 });
+}
+
+/** Insert a cross-reference at the caret. */
+export function insertRef(ctx: FeatureContext, to: string, style: RefStyle = 'label'): void {
+ const c = ctx.editor.caret();
+ if (!c) { ctx.toast(t('Put the caret where the reference goes')); return; }
+ const at = c.at;
+ ctx.store.breakRun();
+ ctx.store.commit(d => {
+ const i = d.body.findIndex(b => b.id === c.id);
+ if (i < 0) return;
+ d.body[i] = withRef(d.body[i], at, to, style);
+ }, { scope: { block: c.id } });
+ ctx.refresh();
+ ctx.editor.setCaret({ id: c.id, at });
+}
+
+/**
+ * The picker — a reference is chosen from a list, never typed as an id.
+ *
+ * An id is a thing the author has no reason to know and every reason to get
+ * wrong; the list shows what they actually wrote, "Table 2 — Fee schedule".
+ */
+export function openPicker(ctx: FeatureContext): void {
+ if (refuse(ctx)) return;
+ const c = ctx.editor.caret();
+ if (!c) { ctx.toast(t('Put the caret where the reference goes')); return; }
+ const entries = captionEntries(ctx.store.doc.body, docLang(ctx.store.doc));
+ if (!entries.length) { ctx.toast(t('Nothing to refer to yet — caption a table first')); return; }
+
+ const back = document.createElement('div');
+ back.className = 't-overlay';
+ const box = document.createElement('div');
+ box.className = 't-dlg t-xref-pick';
+ box.innerHTML = `<h3>${t('Insert a cross-reference')}</h3>`;
+
+ const styleRow = document.createElement('div');
+ styleRow.className = 't-xref-style';
+ const sel = document.createElement('select');
+ for (const [value, label] of [['label', t('Label — “Table 2”')],
+ ['page', t('Page — “page 7”')],
+ ['both', t('Both — “Table 2 (page 7)”')]] as const) {
+ const o = document.createElement('option');
+ o.value = value; o.textContent = label;
+ sel.appendChild(o);
+ }
+ styleRow.append(sel);
+ box.appendChild(styleRow);
+
+ const list = document.createElement('div');
+ list.className = 't-xref-list';
+ for (const e of entries) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.innerHTML = `<b>${esc(e.label)}</b><span>${esc(e.text || t('(untitled)'))}</span>`;
+ b.addEventListener('click', () => {
+ close();
+ insertRef(ctx, e.id, sel.value as RefStyle);
+ });
+ list.appendChild(b);
+ }
+ box.appendChild(list);
+
+ const foot = document.createElement('div');
+ foot.className = 't-xref-foot';
+ const cancel = document.createElement('button');
+ cancel.type = 'button';
+ cancel.className = 't-btn';
+ cancel.textContent = t('Cancel');
+ cancel.addEventListener('click', () => close());
+ foot.appendChild(cancel);
+ box.appendChild(foot);
+
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); close(); } };
+ function close() {
+ window.removeEventListener('keydown', onKey, true);
+ back.remove();
+ // the caret was preserved by mousedown-preventDefault on the toolbar; put
+ // it back explicitly for the keyboard path, where focus moved into the box
+ if (c) ctx.editor.setCaret(c);
+ }
+ back.addEventListener('mousedown', e => { if (e.target === back) close(); });
+ window.addEventListener('keydown', onKey, true);
+ back.appendChild(box);
+ document.body.appendChild(back);
+ (list.querySelector('button') as HTMLElement | null)?.focus();
+}
+
+// ──────────────────────────────────────────────────────────────── the panel
+
+function paintPanel(host: HTMLElement, ctx: FeatureContext): void {
+ const doc = ctx.store.doc;
+ const entries = captionEntries(doc.body, docLang(doc));
+ const broken = brokenRefs(doc.body);
+ host.replaceChildren();
+
+ if (!entries.length) {
+ const p = document.createElement('p');
+ p.className = 't-hint';
+ p.textContent = t('No captions yet. Put the caret in a table and press the caption button; numbering and every reference to it follow automatically.');
+ host.appendChild(p);
+ }
+ for (const e of entries) {
+ const a = document.createElement('a');
+ a.href = '#';
+ a.className = 't-xref-item';
+ a.innerHTML = `<b>${esc(e.label)}</b> ${esc(e.text || t('(untitled)'))}`;
+ a.addEventListener('click', ev => {
+ ev.preventDefault();
+ ctx.editor.setCaret({ id: e.id, at: 0 });
+ document.querySelector(`[data-id="${CSS.escape(e.id)}"]`)?.scrollIntoView({ block: 'center' });
+ });
+ host.appendChild(a);
+ }
+ if (broken.length) {
+ const h = document.createElement('p');
+ h.className = 't-xref-broken-head';
+ h.textContent = t('{n} broken reference(s)').replace('{n}', String(broken.length));
+ host.appendChild(h);
+ for (const { block } of broken) {
+ const a = document.createElement('a');
+ a.href = '#';
+ a.className = 't-xref-item t-xref-broken';
+ a.textContent = block.text.slice(0, 60) || t('(empty paragraph)');
+ a.addEventListener('click', ev => {
+ ev.preventDefault();
+ ctx.editor.setCaret({ id: block.id, at: 0 });
+ document.querySelector(`[data-id="${CSS.escape(block.id)}"]`)?.scrollIntoView({ block: 'center' });
+ });
+ host.appendChild(a);
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────── registration
+
+registerTool({
+ id: 'caption', icon: ICON_CAPTION, group: 'insert', order: 30, label: () => t('Caption'),
+ get title() { return t('Caption this table or figure'); },
+ run: addCaption,
+});
+
+registerTool({
+ id: 'xref', icon: ICON_XREF, group: 'insert', order: 31, label: () => t('Cross-reference'),
+ get title() { return t('Insert a cross-reference to a caption'); },
+ run: openPicker,
+});
+
+// NO ⋯ entry: this is the same action as the Insert tool above, and a thing
+// with two homes teaches that neither is where it lives. Inserting is what the
+// Insert menu is for; ⋯ is for document-level actions.
+
+// ⌥⌘R: R for reference. ⌘R is the browser's reload and ⇧⌘R its hard reload, so
+// neither is available; Alt keeps it out of both.
+registerKey({ key: 'r', mod: true, alt: true, run: openPicker });
+
+registerPanel({
+ id: 'figures', order: 30,
+ get label() { return t('Figures'); },
+ // a VIEW of the Navigate tab: a figure list answers "where is it"
+ host: 'figuresHost',
+ mount(host, ctx) {
+ paintPanel(host, ctx);
+ // PanelSpec.update is declared in features.ts and main.ts never calls it,
+ // so a panel keeps itself current by subscribing. Said here rather than
+ // left as a surprise for the next feature.
+ ctx.store.on(() => paintPanel(host, ctx));
+ },
+ update: paintPanel,
+});
+
+// ────────────────────────────────────────────────────────────────────────────
+// Until core patch 1 lands, teach TypeScript about the two fields it adds.
+// DELETE THIS BLOCK when model.ts carries them.
+declare module './model.ts' {
+ interface Block {
+ caption?: CaptionRef;
+ refs?: XrefRef[];
+ }
+}