Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
window.bento.validate(): report what the runtime silently swallows (#195)
nyblnetf867ba5508f5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 74416c7a..8c8384af 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -122,6 +122,21 @@ jobs:# file carrying a script tag.run: node scripts/test-preview.ts+ - name: Model key tables match the format+ # slides/src/modelkeys.generated.ts is derived from model.ts and drives+ # validate()'s unknown-key check. A stale copy would report real+ # properties as unknown, and an agent acting on that deletes working+ # configuration — so the generated file is committed and pinned here.+ run: node scripts/build-modelkeys.mjs --check++ - name: Document validation rig+ # validate() is only useful if it is trusted: the rig proves the starter+ # deck and a realistic chart stay silent, and that a deliberately broken+ # deck trips every check.+ run: |+ slides/node_modules/.bin/esbuild scripts/test-validate.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-validate.mjs"+ node "$RUNNER_TEMP/test-validate.mjs"+- name: Built-in layout geometry rig# The built-ins are drawn against 1600x900 while the model default is# 1280x720, so they used to hang 200px off the right edge of a defaultdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34c5753c..f291172d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,18 @@ pre-1.0.## [Unreleased]+- **`window.bento.validate()` — see what the runtime silently swallows.**+ Almost everything that goes wrong in a generated deck fails quietly: a typo'd+ property is ignored, a `dash-march` loop on a solid stroke animates nothing,+ an entrance on a morph arrival never runs, and text overflows its box while+ the JSON looks perfect. `validate()` reports all of it in one structured+ pass, including text overflow measured against the real renderer. It only+ reads — it never changes the document. Its first run found dead configuration+ in our own starter deck: three charts carrying a chart option the renderer+ has never read, and two `fx.enter` declarations on a morph arrival, where the+ morph supplies its own entrance and ignores them. Both now removed.+ Requested by thinkbig1979 in #194.+- **Fix: count-up numbers work on morph slides.** `fx.countUp` was started onlyby the entrance runner, and morph and entrances are mutually exclusive — so astatistic on a slide reached by `transition:"morph"` silently rendered adiff --git a/docs/agents.md b/docs/agents.mdindex f37e26ff..7c2e1e6d 100644--- a/docs/agents.md+++ b/docs/agents.md@@ -168,6 +168,31 @@ each kind of content to the feature built for it:obvious on screen. This is the only check that catches what the otherscannot; a deck nobody rendered is not finished.+### `window.bento.validate()`++Open the deck and run it in the browser console. It reports, in one pass, the+things the runtime otherwise swallows in silence:++```js+const { ok, counts, findings } = window.bento.validate()+findings.filter(f => f.severity !== 'info')+```++Each finding is `{code, severity, message, slide?, element?, path?}`. It checks+unknown property names (a typo is ignored, so the styling just never applies),+text that overflows its box (measured against the real renderer), elements off+the canvas, entrances that can never run, `dash-march` without a dashed stroke,+broken `link` and `asset:` references, duplicate ids and morph-key collisions,+and chart options charts-lite does not implement.++It only reads — it never changes the document, and a finding is advice, not a+refusal. `severity: "info"` is deliberately quiet (a photo bleeding off the+canvas is a design move, not a defect); `error` means something is broken, like+a link to a slide that does not exist.++This does not replace looking at the deck. It catches what is checkable; the+rest — whether a slide is any good — still needs eyes.+## Minimal valid documentStart from this skeleton when creating a deck from scratch. `size` anddiff --git a/scripts/build-modelkeys.mjs b/scripts/build-modelkeys.mjsnew file mode 100644index 00000000..f01262e5--- /dev/null+++ b/scripts/build-modelkeys.mjs@@ -0,0 +1,154 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Generates slides/src/modelkeys.generated.ts — the set of property names the+// bento/slides format defines, read straight off the interfaces in model.ts.+//+// node scripts/build-modelkeys.mjs write the file+// node scripts/build-modelkeys.mjs --check fail if it is out of date (CI)+//+// WHY GENERATE IT. `validate()` reports keys the format does not define,+// because a typo'd property is ignored silently and the styling just does not+// apply. That check is only worth having if its key list is RIGHT: a stale+// list reports real keys as unknown, and an agent acting on that would delete+// working properties. A hand-maintained copy of model.ts would drift the first+// time somebody adds a field — so it is derived, and CI fails if the committed+// output does not match the source.+//+// Read via the TypeScript AST rather than regex: the interfaces nest (fx, and+// fx.loop is a union of two shapes) and extend, and a regex gets both wrong.++import { readFileSync, writeFileSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'+import { createRequire } from 'node:module'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const require = createRequire(join(root, 'slides/package.json'))+const ts = require('typescript')++const MODEL = join(root, 'slides/src/model.ts')+const OUT = join(root, 'slides/src/modelkeys.generated.ts')++const src = ts.createSourceFile(MODEL, readFileSync(MODEL, 'utf8'), ts.ScriptTarget.Latest, true)++/** Every interface in model.ts, by name. */+const interfaces = new Map()+src.forEachChild((n) => {+ if (ts.isInterfaceDeclaration(n)) interfaces.set(n.name.text, n)+})++/** Property names declared directly on a type-literal-ish member list. */+const propsOf = (members) =>+ members.filter((m) => ts.isPropertySignature(m) && m.name).map((m) => m.name.getText(src))++/** Property names of an interface, including everything it extends. */+function keysOf(name, seen = new Set()) {+ if (seen.has(name)) return []+ seen.add(name)+ const decl = interfaces.get(name)+ if (!decl) return []+ const out = [...propsOf(decl.members)]+ for (const h of decl.heritageClauses ?? []) {+ for (const t of h.types) out.push(...keysOf(t.expression.getText(src), seen))+ }+ return out+}++/**+ * Keys of a nested property's object type. Unions contribute every member's+ * keys — `fx.loop` is `dash-march | motion-path`, and a document may hold+ * either, so the valid set is their union.+ */+function nestedKeys(ownerName, path) {+ let node = interfaces.get(ownerName)+ for (const step of path) {+ const member = (node?.members ?? []).find(+ (m) => ts.isPropertySignature(m) && m.name?.getText(src) === step,+ )+ if (!member?.type) return []+ node = member.type+ }+ const collect = (t) => {+ if (ts.isTypeLiteralNode(t)) return propsOf(t.members)+ if (ts.isUnionTypeNode(t)) return t.types.flatMap(collect)+ if (ts.isParenthesizedTypeNode(t)) return collect(t.type)+ if (ts.isTypeReferenceNode(t)) return keysOf(t.typeName.getText(src))+ return []+ }+ return collect(node)+}++const uniq = (a) => [...new Set(a)].sort()++const ELEMENTS = {+ text: 'TextElement',+ shape: 'ShapeElement',+ image: 'ImageElement',+ svg: 'SvgElement',+ chart: 'ChartElement',+ table: 'TableElement',+ media: 'MediaElement',+}++const tables = {+ doc: uniq(keysOf('BentoDoc')),+ slide: uniq(keysOf('Slide')),+ comment: uniq(keysOf('Comment')),+ element: Object.fromEntries(+ Object.entries(ELEMENTS).map(([k, iface]) => [k, uniq(keysOf(iface))]),+ ),+ fx: uniq(nestedKeys('ElementBase', ['fx'])),+ fxKen: uniq(nestedKeys('ElementBase', ['fx', 'ken'])),+ fxLoop: uniq(nestedKeys('ElementBase', ['fx', 'loop'])),+ shadow: uniq(keysOf('ShadowSpec')),+ connectorEnd: uniq(keysOf('ConnectorEnd')),+ tableStyle: uniq(keysOf('TableStyle')),+ tableRow: uniq(keysOf('TableRow')),+ tableCell: uniq(keysOf('TableCell')),+ gradient: uniq(keysOf('GradientFill')),+}++const lit = (v, indent = ' ') =>+ Array.isArray(v)+ ? `[${v.map((s) => JSON.stringify(s)).join(', ')}]`+ : `{\n${Object.entries(v)+ .map(([k, x]) => `${indent} ${JSON.stringify(k)}: ${lit(x, indent + ' ')},`)+ .join('\n')}\n${indent}}`++const body = `// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GENERATED by scripts/build-modelkeys.mjs from slides/src/model.ts — do not+// edit. Run \`node scripts/build-modelkeys.mjs\` after changing the format's+// interfaces; CI fails if this file is out of date.+//+// The property names the bento/slides format defines. \`validate()\` reports+// anything outside these sets, because an unknown key is ignored silently and+// a typo just means the styling does not apply.++export const MODEL_KEYS = ${lit(tables)} as const++export type ElementKind = keyof typeof MODEL_KEYS.element+`++const current = (() => {+ try { return readFileSync(OUT, 'utf8') } catch { return null }+})()++if (process.argv.includes('--check')) {+ if (current !== body) {+ console.error(+ 'modelkeys.generated.ts is out of date with model.ts.\n' ++ 'Run: node scripts/build-modelkeys.mjs',+ )+ process.exit(1)+ }+ const n = Object.values(tables.element).reduce((a, v) => a + v.length, 0)+ console.log(`model keys up to date (${Object.keys(tables.element).length} element types, ${n} keys)`)+} else {+ writeFileSync(OUT, body)+ console.log(`wrote ${OUT}`)+ for (const [k, v] of Object.entries(tables.element)) console.log(` ${k.padEnd(6)} ${v.length} keys`)+}diff --git a/scripts/test-validate.ts b/scripts/test-validate.tsnew file mode 100644index 00000000..ea62722f--- /dev/null+++ b/scripts/test-validate.ts@@ -0,0 +1,156 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Document validation rig.+//+// esbuild scripts/test-validate.ts --bundle --platform=node --format=esm ...+// node <bundle>+//+// (bundled because it pulls in starterdeck.ts, whose imports are extensionless)+//+// WHAT THIS PROVES. `validate()` exists so an agent can see what the runtime+// silently swallows. Its whole value rests on being TRUSTED, and the way it+// loses that is FALSE POSITIVES: an agent told that a real property is unknown+// will delete working configuration, which is worse than never having warned.+//+// So the rig pushes from both sides:+//+// 1. Real content stays quiet. The starter deck — our own showcase, which+// exercises nearly every feature in the format — must report NO errors,+// and a realistic chart option must produce no chart findings at all.+// 2. Broken content is caught. A deck built to trip every check must trip+// exactly the expected codes, so a check silently ceasing to fire shows up+// here rather than in somebody's deck.++import { starterDoc } from '../slides/src/starterdeck.ts'+import { validateDoc } from '../slides/src/validate.ts'+import type { BentoDoc } from '../slides/src/model.ts'++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}`)+}++// ---------------------------------------------------------------- real content+const starter = validateDoc(starterDoc(), { measure: false })+ok(starter.ok && starter.counts.error === 0,+ `the starter deck reports no errors (${starter.counts.error} error, ${starter.counts.warning} warning, ${starter.counts.info} info)`)+ok(!starter.findings.some((f) => f.code === 'unknown-key'),+ 'the starter deck has no unknown keys — the generated key tables match the format it is written in')+ok(!starter.findings.some((f) => f.code === 'chart-key-ignored'),+ 'the starter deck has no dead chart options')+ok(!starter.findings.some((f) => f.code === 'overridden-enter-fx'),+ 'the starter deck has no entrance animations the morph would override')+ok(starter.measured === false, 'measured is false without a DOM rather than silently skipping')++// ------------------------------------------------------------- a clean deck+const clean: BentoDoc = {+ format: 'bento/slides', version: '1.0.0', docId: 'test', title: 'clean',+ size: { width: 1280, height: 720 }, theme: { accent: '#F7A600', fontFamily: 'system-ui' },+ assets: {}, fonts: null,+ slides: [{+ id: 's1', name: 'one', background: '#FFF', transition: 'fade', notes: '', elements: [+ { id: 'a', type: 'text', x: 96, y: 100, w: 600, h: 120, rotation: 0, opacity: 1,+ html: 'hello', fontSize: 40, fontFamily: 'system-ui', fontWeight: 700,+ color: '#111', align: 'left', valign: 'middle', lineHeight: 1.2 },+ ],+ }],+} as any+const cleanResult = validateDoc(clean, { measure: false })+ok(cleanResult.findings.length === 0,+ `a clean deck produces no findings at all (got ${cleanResult.findings.length}: ${cleanResult.findings.map((f) => f.code).join(', ')})`)++// --------------------------------------------------------------- broken deck+const broken: BentoDoc = {+ ...clean,+ slides: [+ {+ id: 's1', name: 'one', background: '#FFF', transition: 'fade', notes: '', elements: [+ // unknown key, out of canvas, broken link, duplicate id+ { id: 'dup', type: 'text', x: 1000, y: 100, w: 600, h: 120, rotation: 0, opacity: 1,+ html: 'over the edge', fontSize: 40, fontFamily: 'system-ui', fontWeight: 700,+ color: '#111', align: 'left', valign: 'middle', lineHeight: 1.2,+ fontStyle: 'italic', link: 'nope' } as any,+ { id: 'dup', type: 'text', x: 96, y: 300, w: 400, h: 80, rotation: 0, opacity: 1,+ html: 'same id', fontSize: 20, fontFamily: 'system-ui', fontWeight: 400,+ color: '#111', align: 'left', valign: 'middle', lineHeight: 1.2 } as any,+ // dash-march on a solid stroke, and a morph-key collision with 'dup'+ { id: 'dash', morphId: 'dup', type: 'shape', shape: 'line', x: 96, y: 500, w: 400, h: 4,+ rotation: 0, opacity: 1, fill: '#000', stroke: '#000', strokeWidth: 2,+ fx: { loop: { type: 'dash-march' } } } as any,+ // missing asset+ { id: 'img', type: 'image', x: 96, y: 560, w: 100, h: 100, rotation: 0, opacity: 1,+ src: 'asset:nope', fit: 'cover' } as any,+ ],+ },+ {+ id: 's2', name: 'two', background: '#FFF', transition: 'morph', notes: '', elements: [+ // entrance on a morph arrival; also an unknown fx key+ { id: 'e', type: 'text', x: 96, y: 100, w: 400, h: 80, rotation: 0, opacity: 1,+ html: 'x', fontSize: 20, fontFamily: 'system-ui', fontWeight: 400,+ color: '#111', align: 'left', valign: 'middle', lineHeight: 1.2,+ fx: { enter: 'fade-up', wobble: true } } as any,+ // a chart with options charts-lite does not implement+ { id: 'c', type: 'chart', x: 600, y: 100, w: 400, h: 300, rotation: 0, opacity: 1,+ preset: 'bar',+ option: {+ xAxis: { type: 'category', data: ['a'] }, yAxis: { type: 'value' },+ series: [{ type: 'bar', data: [1], label: { show: true } }],+ toolbox: { show: true },+ } } as any,+ ],+ },+ ],+} as any++const r = validateDoc(broken, { measure: false })+const codes = new Set(r.findings.map((f) => f.code))+for (const expected of [+ 'unknown-key', 'out-of-canvas', 'broken-link', 'duplicate-id',+ 'morph-key-collision', 'dash-march-no-dash', 'missing-asset',+ 'overridden-enter-fx', 'chart-key-ignored',+]) {+ ok(codes.has(expected), `the broken deck trips ${expected}`)+}+ok(!r.ok, 'a deck with broken references is not ok')+ok(r.findings.some((f) => f.code === 'chart-key-ignored' && f.path === 'option.series[0].label'),+ 'a label on a bar series is reported (it is read for pie only)')+ok(r.findings.some((f) => f.code === 'unknown-key' && f.path === 'fx.wobble'),+ 'an unknown key nested under fx is reported with its path')++// ------------------------------------------------- chart false-positive guard+// The shape the starter deck's own charts use. Every key here IS implemented,+// so any finding is the validator lying about working configuration.+const realisticChart = {+ color: ['#F7A600', '#5B8DEF'],+ grid: { left: 48, right: 16, top: 24, bottom: 56 },+ legend: { show: true, top: 0, textStyle: { fontSize: 13 } },+ tooltip: { trigger: 'axis' },+ xAxis: { type: 'category', data: ['Mon', 'Tue'], axisLine: { lineStyle: { color: '#D8D2C4' } }, axisLabel: { color: '#6B7280' } },+ yAxis: [+ { type: 'value', axisLabel: { color: '#6B7280' }, splitLine: { lineStyle: { color: '#EAE4D6' } } },+ { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },+ ],+ series: [+ { type: 'bar', name: 'Signups', data: [1, 2], itemStyle: { borderRadius: [6, 6, 0, 0] } },+ { type: 'line', name: 'Rate', yAxisIndex: 1, data: [3, 4], smooth: true, symbolSize: 8, lineStyle: { width: 3 } },+ ],+}+const chartDoc: BentoDoc = {+ ...clean,+ slides: [{+ id: 's1', name: 'one', background: '#FFF', transition: 'fade', notes: '', elements: [+ { id: 'ch', type: 'chart', x: 96, y: 96, w: 800, h: 400, rotation: 0, opacity: 1,+ preset: 'bar', option: realisticChart } as any,+ ],+ }],+} as any+const chartFindings = validateDoc(chartDoc, { measure: false }).findings+ok(chartFindings.length === 0,+ `a realistic dual-axis chart produces no findings (got ${chartFindings.map((f) => f.path).join(', ') || 'none'})`)++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/slides/src/main.ts b/slides/src/main.tsindex ce64e115..a72dc7f8 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -15,6 +15,7 @@ import { buildSlidePreview } from './preview'import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './update'import { i18nApi, t, applyDirection } from './i18n'import { parseDoc, type BentoDoc } from './model'+import { validateDoc, type ValidateOpts } from './validate'import { starterDoc } from './starterdeck'import { injectFonts } from './fonts'import { Store } from './store'@@ -216,6 +217,16 @@ if (location.hash === '#present') {store.replaceDoc(next)return true},+ /**+ * Report what the runtime would otherwise swallow: unknown keys, text that+ * overflows its box, elements off the canvas, effects that can never run,+ * broken links and asset refs, chart options charts-lite ignores. Read-only+ * — it never changes the document. Pass a doc to check one you have not+ * loaded; defaults to the open one.+ */+ validate(target?: BentoDoc, opts?: ValidateOpts) {+ return validateDoc(target ?? store.doc, opts)+ },/*** Self-update surface (all user/tooling-initiated, never automatic):* check() fetches + signature-verifies the release manifest; build()diff --git a/slides/src/modelkeys.generated.ts b/slides/src/modelkeys.generated.tsnew file mode 100644index 00000000..7d32c200--- /dev/null+++ b/slides/src/modelkeys.generated.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GENERATED by scripts/build-modelkeys.mjs from slides/src/model.ts — do not+// edit. Run `node scripts/build-modelkeys.mjs` after changing the format's+// interfaces; CI fails if this file is out of date.+//+// The property names the bento/slides format defines. `validate()` reports+// anything outside these sets, because an unknown key is ignored silently and+// a typo just means the styling does not apply.++export const MODEL_KEYS = {+ "doc": ["assets", "blobs", "collab", "docId", "fonts", "format", "layouts", "meta", "modified", "present", "readonly", "size", "slides", "template", "theme", "title", "version"],+ "slide": ["background", "comments", "elements", "hover", "id", "name", "notes", "stateOf", "transition"],+ "comment": ["at", "author", "elementId", "id", "replies", "resolved", "text", "x", "y"],+ "element": {+ "text": ["align", "backdropFilter", "blend", "blur", "color", "colorGradient", "fontFamily", "fontSize", "fontWeight", "fx", "group", "groupId", "h", "html", "id", "letterSpacing", "lineHeight", "link", "morphId", "opacity", "placeholder", "role", "rotation", "shadow", "showOnHover", "textStroke", "type", "valign", "w", "x", "y"],+ "shape": ["backdropFilter", "blend", "blur", "d", "fill", "fillGradient", "from", "fx", "group", "groupId", "h", "id", "lineEnd", "lineStart", "link", "morphId", "opacity", "pathBox", "radius", "role", "rotation", "shadow", "shape", "showOnHover", "stroke", "strokeDash", "strokeStyle", "strokeWidth", "to", "type", "w", "x", "y"],+ "image": ["backdropFilter", "blend", "blur", "fit", "fx", "group", "groupId", "h", "id", "link", "morphId", "opacity", "radius", "role", "rotation", "shadow", "showOnHover", "src", "type", "w", "x", "y"],+ "svg": ["asset", "backdropFilter", "blend", "blur", "css", "fx", "group", "groupId", "h", "id", "link", "markup", "morphId", "opacity", "role", "rotation", "shadow", "showOnHover", "type", "w", "x", "y"],+ "chart": ["backdropFilter", "blend", "blur", "fx", "group", "groupId", "h", "id", "link", "morphId", "opacity", "option", "preset", "role", "rotation", "shadow", "showOnHover", "source", "type", "w", "x", "y"],+ "table": ["backdropFilter", "blend", "blur", "columns", "fx", "group", "groupId", "h", "header", "id", "link", "morphId", "opacity", "role", "rotation", "rows", "shadow", "showOnHover", "style", "type", "w", "x", "y"],+ "media": ["autoplay", "backdropFilter", "blend", "blur", "controls", "fit", "fx", "group", "groupId", "h", "id", "kind", "link", "loop", "morphId", "muted", "opacity", "poster", "radius", "role", "rotation", "shadow", "showOnHover", "src", "type", "w", "x", "y"],+ },+ "fx": ["ambient", "countUp", "enter", "enterDur", "ken", "loop", "order"],+ "fxKen": ["dir", "duration", "scale"],+ "fxLoop": ["delay", "distance", "duration", "ease", "path", "speeds", "type"],+ "shadow": ["blur", "color", "x", "y"],+ "connectorEnd": ["el", "side"],+ "tableStyle": ["borderColor", "borderWidth", "cellPadX", "cellPadY", "color", "fontFamily", "fontSize", "headerBg", "headerColor", "radius", "zebra"],+ "tableRow": ["cells"],+ "tableCell": ["align", "bg", "bold", "color", "html"],+ "gradient": ["angle", "stops"],+ } as const++export type ElementKind = keyof typeof MODEL_KEYS.elementdiff --git a/slides/src/starterdeck.ts b/slides/src/starterdeck.tsindex 9bf8cbc7..f9d16b0d 100644--- a/slides/src/starterdeck.ts+++ b/slides/src/starterdeck.ts@@ -184,7 +184,7 @@ const barOption = () => ({grid: { left: 48, right: 16, top: 24, bottom: 56 },xAxis: {type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],- axisLine: { lineStyle: { color: '#D8D2C4' } }, axisTick: { show: false },+ axisLine: { lineStyle: { color: '#D8D2C4' } },axisLabel: { color: '#6B7280' },},yAxis: { type: 'value', axisLabel: { color: '#6B7280' }, splitLine: { lineStyle: { color: '#EAE4D6' } } },@@ -219,7 +219,6 @@ const trendOption = () => ({type: 'category',data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],axisLine: { lineStyle: { color: 'rgba(185,196,212,0.25)' } },- axisTick: { show: false },axisLabel: { color: 'rgba(185,196,212,0.8)' },},yAxis: {@@ -252,7 +251,7 @@ const scatterOption = () => ({grid: { left: 52, right: 24, top: 24, bottom: 56 },xAxis: {type: 'value', name: 'Reach',- axisLine: { lineStyle: { color: '#D8D2C4' } }, axisTick: { show: false },+ axisLine: { lineStyle: { color: '#D8D2C4' } },axisLabel: { color: '#6B7280' }, splitLine: { lineStyle: { color: '#EAE4D6' } },},yAxis: {@@ -755,7 +754,6 @@ export function starterDoc(): BentoDoc {borderColor: 'rgba(30,42,58,0.10)', borderWidth: 1,cellPadX: 18, cellPadY: 12, fontSize: 18, color: '#26303E', radius: 12,},- fx: { enter: 'fade-up', order: 1 },} as TableElement,shape('rect', {id: T_D, x: 920, y: 196, w: 264, h: 458, radius: 18, fill: PANEL,@@ -791,7 +789,7 @@ export function starterDoc(): BentoDoc {],tooltip: { trigger: 'axis' },},- { id: 'sd-tbl-chart', x: 922, y: 266, w: 262, h: 224, preset: 'bar', source: { tableId: 'sd-table' }, fx: { enter: 'fade-up', order: 2 } },+ { id: 'sd-tbl-chart', x: 922, y: 266, w: 262, h: 224, preset: 'bar', source: { tableId: 'sd-table' } },),text({x: 944, y: 504, w: 216, h: 56,diff --git a/slides/src/validate.ts b/slides/src/validate.tsnew file mode 100644index 00000000..b89a632d--- /dev/null+++ b/slides/src/validate.ts@@ -0,0 +1,343 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Document validation — `window.bento.validate()`.+//+// WHY THIS EXISTS. Almost everything that goes wrong in a generated deck fails+// SILENTLY. A typo'd property is ignored, so the styling just does not apply. A+// dash-march loop on a solid stroke animates nothing. An entrance on a morph+// arrival never runs. Text overflows its box and the JSON looks perfect. An+// agent authoring a deck has no way to see any of it without rendering the+// result and looking at every slide — which is exactly what nobody does.+//+// So this reports, in one structured pass, the things the runtime would+// otherwise swallow. It only READS: it never mutates the document, and a+// finding is advice, not a refusal. `parseDoc` remains the thing that decides+// whether a document is loadable at all.+//+// Text overflow needs real layout, so it renders each slide off-screen with the+// SAME renderer the editor and present mode use (`renderSlide`) and measures+// what comes out. Anything else would measure a different deck than the one the+// audience sees. Without a DOM (node tooling) the measured checks are skipped+// and `measured` reports false, rather than guessing.++import type { BentoDoc, Slide, SlideElement } from './model.ts'+import { MODEL_KEYS } from './modelkeys.generated.ts'+import { renderSlide } from './render.ts'++export type Severity = 'error' | 'warning' | 'info'++export interface Finding {+ /** stable machine-readable code, e.g. 'text-overflow' */+ code: string+ severity: Severity+ /** one line, written to be actionable on its own */+ message: string+ /** slide id, when the finding belongs to a slide */+ slide?: string+ /** element id, when it belongs to an element */+ element?: string+ /** property path within the element/document, e.g. 'option.series[0].label' */+ path?: string+}++export interface ValidateResult {+ ok: boolean+ /** false when there was no DOM, so overflow was not checked */+ measured: boolean+ counts: Record<Severity, number>+ findings: Finding[]+}++export interface ValidateOpts {+ /** measure text overflow (needs a DOM). Default true when one exists. */+ measure?: boolean+ /** side margin in px on a 1280-wide canvas; scaled to the deck. 0 disables. */+ margin?: number+}++/**+ * Chart option keys charts-lite implements (kernel/src/charts.ts). Anything+ * else in an `option` is ignored at render time with no warning — the engine+ * reads the ECharts option SHAPE, it is not ECharts.+ *+ * Kept deliberately close to the renderer: `label` is listed for pie only,+ * because `renderPie` is the sole reader of it and a `label` on a bar or line+ * series genuinely does nothing.+ */+const CHART_KEYS = {+ top: ['color', 'series', 'xAxis', 'yAxis', 'legend', 'grid', 'tooltip', 'textStyle', 'dataZoom'],+ series: ['type', 'name', 'data', 'yAxisIndex', 'itemStyle'],+ seriesByType: {+ bar: ['barWidth'],+ line: ['smooth', 'symbol', 'symbolSize', 'lineStyle', 'areaStyle'],+ scatter: ['symbol', 'symbolSize'],+ pie: ['radius', 'label'],+ } as Record<string, string[]>,+ axis: ['type', 'data', 'min', 'max', 'axisLabel', 'axisLine', 'splitLine', 'name'],+ legend: ['show', 'top', 'bottom', 'textStyle', 'itemWidth', 'itemHeight', 'itemGap', 'data'],+}++const morphKey = (el: SlideElement) => el.morphId || el.id++/**+ * Small chrome — page numerals, running heads, corner labels. These live in+ * the margin ON PURPOSE, so flagging them for it is pure noise; the margin+ * guideline is about the body content that has to look aligned.+ */+const isFurniture = (el: SlideElement, doc: BentoDoc) =>+ el.w * el.h < doc.size.width * doc.size.height * 0.03++/** Slides reached by a morph transition, forward or backward out of one. */+function morphArrivals(doc: BentoDoc): Map<string, Slide | undefined> {+ const out = new Map<string, Slide | undefined>()+ doc.slides.forEach((s, i) => {+ if (s.transition === 'morph' && i > 0) out.set(s.id, doc.slides[i - 1])+ })+ return out+}++export function validateDoc(doc: BentoDoc, opts: ValidateOpts = {}): ValidateResult {+ const findings: Finding[] = []+ const add = (f: Finding) => findings.push(f)++ const hasDom = typeof document !== 'undefined'+ const measure = (opts.measure ?? true) && hasDom+ const marginBase = opts.margin ?? 96+ const margin = marginBase * (doc.size.width / 1280)+ const slideIds = new Set(doc.slides.map((s) => s.id))+ const assets = doc.assets ?? {}+ const arrivals = morphArrivals(doc)++ // ---- document level ------------------------------------------------------+ for (const k of Object.keys(doc)) {+ if (!(MODEL_KEYS.doc as readonly string[]).includes(k)) {+ add({ code: 'unknown-key', severity: 'warning', path: k,+ message: `Document key "${k}" is not part of the bento/slides format — it is ignored at render time.` })+ }+ }+ for (const f of doc.fonts ?? []) {+ if (f.asset && !assets[f.asset]) {+ add({ code: 'missing-asset', severity: 'error', path: `fonts.${f.family}`,+ message: `Font "${f.family}" points at asset "${f.asset}", which is not in doc.assets — the face will not load and text falls back silently.` })+ }+ }++ for (const slide of doc.slides) {+ const sid = slide.id+ const prev = arrivals.get(sid)+ const isMorphArrival = arrivals.has(sid)+ const partners = new Set((prev?.elements ?? []).map(morphKey))+ const seenIds = new Set<string>()+ const seenMorph = new Map<string, string>()+ const elsOnSlide = new Set(slide.elements.map((e) => e.id))++ for (const k of Object.keys(slide)) {+ if (!(MODEL_KEYS.slide as readonly string[]).includes(k)) {+ add({ code: 'unknown-key', severity: 'warning', slide: sid, path: k,+ message: `Slide key "${k}" is not part of the format — it is ignored.` })+ }+ }+ if (slide.stateOf && !slideIds.has(slide.stateOf)) {+ add({ code: 'broken-state-parent', severity: 'error', slide: sid, path: 'stateOf',+ message: `stateOf points at "${slide.stateOf}", which is not a slide in this deck — the state is unreachable.` })+ }++ for (const el of slide.elements) {+ const at = { slide: sid, element: el.id }++ // identity ---------------------------------------------------------+ if (seenIds.has(el.id)) {+ add({ ...at, code: 'duplicate-id', severity: 'error',+ message: `Two elements on this slide share the id "${el.id}" — selection, morph and comment anchors all key off it.` })+ }+ seenIds.add(el.id)+ const mk = morphKey(el)+ const clash = seenMorph.get(mk)+ if (clash && clash !== el.id) {+ add({ ...at, code: 'morph-key-collision', severity: 'error', path: 'morphId',+ message: `Morph key "${mk}" is used by both "${clash}" and "${el.id}" on this slide — morph pairs by that key, so one of them will not tween.` })+ }+ seenMorph.set(mk, el.id)++ // unknown keys -------------------------------------------------------+ const known = (MODEL_KEYS.element as Record<string, readonly string[]>)[el.type]+ if (known) {+ for (const k of Object.keys(el)) {+ if (!known.includes(k)) {+ add({ ...at, code: 'unknown-key', severity: 'warning', path: k,+ message: `"${k}" is not a property of a ${el.type} element — it is ignored, so whatever it was meant to do will not happen.` })+ }+ }+ }+ if (el.fx) {+ for (const k of Object.keys(el.fx)) {+ if (!(MODEL_KEYS.fx as readonly string[]).includes(k)) {+ add({ ...at, code: 'unknown-key', severity: 'warning', path: `fx.${k}`,+ message: `"fx.${k}" is not a known effect property — it is ignored.` })+ }+ }+ }++ // geometry -----------------------------------------------------------+ // Bleeding a shape or photo off the canvas is a deliberate idiom, and a+ // full-bleed backdrop is SUPPOSED to ignore the margin — so geometry is+ // only a warning for the element types that carry words, where going+ // past an edge means the reader loses some. For everything else it is+ // recorded at 'info' and stays out of the way.+ const carriesText = el.type === 'text' || el.type === 'table'+ const right = el.x + el.w+ const bottom = el.y + el.h+ const fullBleed = el.w >= doc.size.width * 0.9 || el.h >= doc.size.height * 0.9+ if (right > doc.size.width || bottom > doc.size.height || el.x < 0 || el.y < 0) {+ add({ ...at, code: 'out-of-canvas', severity: carriesText ? 'warning' : 'info',+ message: carriesText+ ? `Extends outside the ${doc.size.width}x${doc.size.height} canvas (x ${el.x}-${right}, y ${el.y}-${bottom}) — the text past the edge is cropped when presenting.`+ : `Extends outside the ${doc.size.width}x${doc.size.height} canvas (x ${el.x}-${right}, y ${el.y}-${bottom}) — fine as a deliberate bleed, cropped either way.` })+ // A few px inside the margin is an optical adjustment, not crowding —+ // large type is routinely nudged left to hang its side bearing. Only+ // flag content that misses the margin by an amount a reader would see.+ } else if (carriesText && !fullBleed && margin > 0 && !isFurniture(el, doc)+ && (el.x < margin * 0.9 || right > doc.size.width - margin * 0.9)) {+ add({ ...at, code: 'past-margin', severity: 'info',+ message: `Reaches past the ${Math.round(margin)}px side margin (x ${el.x}-${right}) — the deck's other content stops short of it.` })+ }++ // effects that will not run -------------------------------------------+ if (el.fx?.enter && isMorphArrival) {+ add({ ...at, code: 'overridden-enter-fx', severity: 'warning', path: 'fx.enter',+ message: `On a morph arrival the morph supplies its own entrance — new elements fade and rise 14px — so fx.enter's direction, duration and order are all ignored here.` })+ }+ if (el.fx?.enter && el.fx?.loop?.type === 'motion-path') {+ add({ ...at, code: 'entrance-on-motion-path', severity: 'warning', path: 'fx.enter',+ message: `An entrance tween and a motion-path loop fight over the same transform — the element can freeze off its path. Use one or the other.` })+ }+ if (el.fx?.countUp && isMorphArrival && partners.has(mk)) {+ add({ ...at, code: 'inert-countup', severity: 'info', path: 'fx.countUp',+ message: `This element morphs in from the previous slide already showing its number, so the count-up is skipped by design. Give it a morph key that is new to this slide if you want it to count.` })+ }+ if (el.fx?.loop?.type === 'dash-march') {+ const dashed = el.type === 'shape' && (el.strokeStyle === 'dashed' || el.strokeStyle === 'dotted')+ const stroked = el.type === 'shape' && !!el.stroke && el.stroke !== 'transparent' && (el.strokeWidth ?? 0) > 0+ if (!dashed || !stroked) {+ add({ ...at, code: 'dash-march-no-dash', severity: 'warning', path: 'fx.loop',+ message: `A dash-march loop animates strokeDashoffset, so it needs a visible stroke AND strokeStyle "dashed" or "dotted". As set, the tween runs and nothing moves.` })+ }+ }++ // references -----------------------------------------------------------+ if (el.link && !slideIds.has(el.link)) {+ add({ ...at, code: 'broken-link', severity: 'error', path: 'link',+ message: `Links to slide "${el.link}", which does not exist — clicking it does nothing.` })+ }+ for (const [side, end] of [['from', (el as any).from], ['to', (el as any).to]] as const) {+ if (end?.el && !elsOnSlide.has(end.el)) {+ add({ ...at, code: 'dangling-connector', severity: 'warning', path: side,+ message: `Connector ${side} references element "${end.el}", which is not on this slide — that end is dropped and stops following.` })+ }+ }+ for (const key of ['src', 'asset', 'poster'] as const) {+ const ref = (el as any)[key]+ if (typeof ref === 'string' && ref.startsWith('asset:') && !assets[ref.slice(6)]) {+ add({ ...at, code: 'missing-asset', severity: 'error', path: key,+ message: `${key} references asset "${ref.slice(6)}", which is not in doc.assets — nothing renders.` })+ }+ }++ // charts ---------------------------------------------------------------+ if (el.type === 'chart' && el.option) validateChart(el.option as any, at, add)+ }+ }++ // ---- measured checks -----------------------------------------------------+ if (measure) measureOverflow(doc, add)++ const counts = { error: 0, warning: 0, info: 0 }+ for (const f of findings) counts[f.severity]+++ return { ok: counts.error === 0, measured: measure, counts, findings }+}++/** Report option keys charts-lite does not implement. */+function validateChart(+ option: Record<string, any>,+ at: { slide: string; element: string },+ add: (f: Finding) => void,+) {+ const note = (path: string, what: string) =>+ add({ ...at, code: 'chart-key-ignored', severity: 'warning', path,+ message: `charts-lite does not implement ${what} — it is ignored, with no warning at render time.` })++ for (const k of Object.keys(option)) {+ if (!CHART_KEYS.top.includes(k)) note(`option.${k}`, `the top-level chart option "${k}"`)+ }+ const series = Array.isArray(option.series) ? option.series : option.series ? [option.series] : []+ series.forEach((s: any, i: number) => {+ if (!s || typeof s !== 'object') return+ const allowed = [...CHART_KEYS.series, ...(CHART_KEYS.seriesByType[s.type] ?? [])]+ for (const k of Object.keys(s)) {+ if (allowed.includes(k)) continue+ // the one people reach for most, and the one that reads as a bug+ if (k === 'label') {+ note(`option.series[${i}].label`,+ 'value labels on a bar, line or scatter series (label is read for pie only)')+ } else {+ note(`option.series[${i}].${k}`, `"${k}" on a ${s.type ?? 'series'} series`)+ }+ }+ })+ for (const axis of ['xAxis', 'yAxis'] as const) {+ const list = Array.isArray(option[axis]) ? option[axis] : option[axis] ? [option[axis]] : []+ list.forEach((a: any, i: number) => {+ if (!a || typeof a !== 'object') return+ for (const k of Object.keys(a)) {+ if (!CHART_KEYS.axis.includes(k)) note(`option.${axis}[${i}].${k}`, `"${k}" on an axis`)+ }+ })+ }+ if (option.legend && typeof option.legend === 'object') {+ for (const k of Object.keys(option.legend)) {+ if (!CHART_KEYS.legend.includes(k)) note(`option.legend.${k}`, `"${k}" on the legend`)+ }+ }+}++/**+ * Render every slide off-screen and measure what the text actually does.+ *+ * Uses the shared renderer so the measurement is of the same DOM the audience+ * gets — a reimplementation here would drift from render.ts and start lying.+ * The host is visibility:hidden rather than display:none, because a+ * display:none subtree has no layout at all and every height would read 0.+ */+function measureOverflow(doc: BentoDoc, add: (f: Finding) => void) {+ const host = document.createElement('div')+ host.setAttribute('data-bento-transient', '') // never captured into a save+ host.style.cssText =+ 'position:fixed;left:-10000px;top:0;visibility:hidden;pointer-events:none;contain:strict;'+ document.body.appendChild(host)+ try {+ for (const slide of doc.slides) {+ const surface = renderSlide(slide, doc)+ host.appendChild(surface)+ for (const el of slide.elements) {+ if (el.type !== 'text') continue+ const node = surface.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)+ const inner = node?.querySelector<HTMLElement>('.bento-text-inner')+ if (!inner) continue+ const need = inner.scrollHeight+ // a placeholder with no content measures as one empty line — not overflow+ if (!el.html?.trim()) continue+ if (need > el.h + 1) {+ add({+ slide: slide.id, element: el.id, code: 'text-overflow', severity: 'warning',+ path: 'h',+ message: `Text needs ${Math.ceil(need)}px but the box is ${el.h}px tall — it overflows by ${Math.ceil(need - el.h)}px and will collide with whatever is below it.`,+ })+ }+ }+ surface.remove()+ }+ } finally {+ host.remove()+ }+}