Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

20.2 KB
Raw Blame
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
// The compact document (#422 / #411): defaults omitted, expanded on load.
//
//   node scripts/test-slides-compact.ts
//
// WHAT THIS PROVES. compactDoc and expandDoc are inverses on real decks: the
// starter deck and every gallery deck round-trip to a deep-equal document
// (canonical JSON byte-identical — key ORDER is the one thing a round-trip
// may change, and nothing reads key order). A minimal compact deck expands
// to what the editor's own insert helpers produce, field for field — the
// defaults come from those helpers, not a second table. Nested arrays
// flatten; missing ids are minted deterministically; theme-derived defaults
// follow the theme; compactDoc never strips a value that differs from its
// default; the flag is explicit; and the gated loader runs sanitizeSlide on
// the expanded document. Also the measured numbers: the starter deck's
// compact form is under 90% of the full one (11–14% saved on designed decks
// that override most defaults), and an agent deck written the compact way
// expands to more than 2.5× its bytes — the case the feature is for.

import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { compactDoc, expandDoc, expandDocWithStats, provisionalHeight, isCompact, compactJson, COMPACT_FLAG } from '../slides/src/compact.ts'
import { markdownToHtml } from '../slides/src/editor/markdown.ts'
import { starterDoc } from '../slides/src/starterdeck.ts'
import { defaultText, defaultShape, defaultTable, defaultCode, readableInk, FONT_STACK, newDoc, isLightBg, type BentoDoc, type TextElement, type ShapeElement, type TableElement } 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}`)
}
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const read = (f: string) => readFileSync(join(root, f), 'utf8')
type Obj = Record<string, unknown>
const canon = (v: unknown): string => JSON.stringify(v, (_k, x) => (x && typeof x === 'object' && !Array.isArray(x)) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Obj)[k]])) : x)

console.log('round-trip on real decks\n')
const decks: Array<[string, BentoDoc]> = [['starter deck', starterDoc()]]
// Two gallery decks as checked-in fixtures (their doc JSON with photo/font
// payloads replaced by `data:,` — the rig measures structure, not bytes).
// Regenerated by hand from build-example-decks.mjs output (doc JSON, payloads
// blanked); a rig carries what it measures, never a path from one machine's
// environment.
const fixturesDir = join(root, 'scripts/fixtures/compact-decks')
for (const f of readdirSync(fixturesDir).filter((f) => f.endsWith('.json')).sort()) {
  decks.push([f, JSON.parse(readFileSync(join(fixturesDir, f), 'utf8'))])
}
// "Never loses or changes a value": every field of d is in the round-trip with
// the same value. A deck the EDITOR wrote is byte-identical (every default is
// present, so nothing is added back that was not there). A deck a SCRIPT wrote
// may omit optional fields (a media element with no `autoplay`); expansion
// fills those with the editor's insert defaults, so the round-trip can be a
// superset — the additions are listed and must all be editor defaults, which
// is the compact form's one promise: absent means "what the editor inserts".
const subsetDiff = (from: unknown, to: unknown, path = ''): { changed: string[]; added: string[] } => {
  const out = { changed: [] as string[], added: [] as string[] }
  if (Array.isArray(from)) {
    if (!Array.isArray(to) || to.length !== from.length) { out.changed.push(path); return out }
    from.forEach((v, i) => { const d = subsetDiff(v, to[i], `${path}[${i}]`); out.changed.push(...d.changed); out.added.push(...d.added) })
    return out
  }
  if (from && typeof from === 'object') {
    if (!to || typeof to !== 'object') { out.changed.push(path); return out }
    for (const k of Object.keys(from as Obj)) { const d = subsetDiff((from as Obj)[k], (to as Obj)[k], `${path}.${k}`); out.changed.push(...d.changed); out.added.push(...d.added) }
    for (const k of Object.keys(to as Obj)) if (!(k in (from as Obj))) out.added.push(`${path}.${k}`)
    return out
  }
  if (from !== to) out.changed.push(path)
  return out
}
for (const [name, doc] of decks) {
  const c = compactDoc(doc)
  const back = expandDoc(c)
  const d = subsetDiff(doc, back)
  ok(d.changed.length === 0, `${name}: no value is lost or changed by the round-trip${d.changed.length ? ` (${d.changed.slice(0, 3).join(', ')})` : ''}`)
  const addedKeys = [...new Set(d.added.map((p) => p.replace(/^.*\./, '')))]
  if (name === 'starter deck') ok(canon(back) === canon(doc), 'the starter deck (editor-shaped: every default present) round-trips canonical-JSON byte-identical')
  else ok(addedKeys.every((k) => ['radius', 'fit', 'autoplay', 'loop', 'muted', 'controls', 'preset', 'rotation', 'opacity', 'fontFamily', 'fontWeight', 'lineHeight', 'align', 'valign', 'stroke', 'strokeWidth', 'header', 'notes', 'transition', 'background', 'style', 'color', 'fontSize'].includes(k)), `${name}: the only additions are editor insert defaults the script left out (${addedKeys.join(', ') || 'none'})`)
  ok(!(COMPACT_FLAG in (back as unknown as Obj)), `${name}: the flag does not survive expansion`)
  ok(JSON.stringify(c).length < JSON.stringify(doc).length, `${name}: the compact form is smaller`)
}
ok(decks.length === 3, `the starter deck and the two gallery fixtures were measured (${decks.length})`)

console.log('\nexpansion matches the editor\'s inserts\n')
const compact = {
  compact: true, title: 'Agent deck',
  slides: [
    { id: 'a', elements: [
      { id: 't1', type: 'text', x: 96, y: 80, w: 1000, h: 80, html: 'Hello', fontSize: 48 },
      { id: 's1', type: 'shape', shape: 'ellipse', x: 100, y: 200, w: 200, h: 200 },
      { id: 'tb', type: 'table', x: 100, y: 400, w: 800, h: 200, columns: [{ w: 1 }], rows: [{ cells: [{ html: 'x' }] }] },
    ] },
    { id: 'b', background: '#101820', elements: [
      { id: 't2', type: 'text', x: 96, y: 80, w: 1000, h: 80, html: 'Dark' },
      { id: 'c2', type: 'code', x: 96, y: 200, w: 800, h: 300, content: 'x' },
      { id: 'tb2', type: 'table', x: 100, y: 400, w: 800, h: 200, columns: [{ w: 1 }], rows: [{ cells: [{ html: 'x' }] }] },
    ] },
  ],
}
const ex = expandDoc(JSON.parse(JSON.stringify(compact)))
const el = (si: number, id: string) => ex.slides[si].elements.find((e) => e.id === id) as unknown as Obj
const t1 = el(0, 't1') as unknown as TextElement
const want = defaultText({ id: 't1', x: 96, y: 80, w: 1000, h: 80, html: 'Hello', fontSize: 48, color: readableInk(ex.slides[0].background) })
ok(canon(t1) === canon(want), 'a light-slide text box equals defaultText(...) with readableInk of the slide background — the editor\'s own insert')
ok(t1.fontFamily === FONT_STACK && t1.fontWeight === 400 && t1.align === 'center' && t1.valign === 'middle' && t1.lineHeight === 1.25 && t1.rotation === 0 && t1.opacity === 1, 'rotation, opacity, font stack, weight, align, valign, line height filled')
const s1 = el(0, 's1') as unknown as ShapeElement
ok(canon(s1) === canon(defaultShape('ellipse', { id: 's1', x: 100, y: 200, w: 200, h: 200 })), 'an ellipse equals defaultShape(\'ellipse\', …) — radius 0, not the rect\'s 12')
const t2 = el(1, 't2') as unknown as TextElement
ok(t2.color === readableInk('#101820') && t2.color === '#F5F7FA', 'text on a dark slide gets light ink, as the editor gives it')
const c2 = el(1, 'c2')
ok(canon(c2) === canon(defaultCode({ id: 'c2', x: 96, y: 200, w: 800, h: 300, content: 'x', color: readableInk('#101820') })), 'a code block equals defaultCode(...) with the slide\'s ink')
const tb = el(0, 'tb') as unknown as TableElement
ok(canon(tb.style) === canon(defaultTable({}, ex.theme).style), 'a table on a light slide carries tableStyleFor(theme)')
const tb2 = el(1, 'tb2') as unknown as TableElement
ok(tb2.style.color === '#F5F7FA' && tb2.style.zebra === 'rgba(255,255,255,0.06)' && tb2.style.borderColor === 'rgba(255,255,255,0.16)', 'a table on a dark slide gets editor.newTable()\'s dark adaptation')
ok(ex.slides[0].background === newDoc().theme.background && ex.slides[0].transition === 'fade' && ex.slides[0].notes === '', 'slide background follows the theme; transition fade; notes empty')
ok(ex.format === 'bento/slides' && ex.version === 1 && ex.size.width === 1280 && canon(ex.theme) === canon(newDoc().theme), 'format, version, size and theme filled from newDoc()')
ok(ex.title === 'Agent deck', 'an authored field is kept as written')

console.log('\nnested arrays, ids, the flag\n')
const nested = expandDoc({ compact: true, slides: [{ id: 'x', elements: [
  { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'a' },
  [ { type: 'shape', shape: 'rect', x: 0, y: 0, w: 1, h: 1 }, { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'b' } ],
  { id: 'mine', type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'c' },
] }] })
ok(nested.slides[0].elements.length === 4, 'a nested array of elements is flattened into the slide (the POC\'s BentoElement | BentoElement[])')
ok(nested.slides[0].elements.map((e) => e.id).join(' ') === 'x-text-0 x-shape-1 x-text-2 mine', 'missing ids mint as ${slideId}-${type}-${index}; an authored id is kept')
const again = expandDoc({ compact: true, slides: [{ id: 'x', elements: [ { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'a' }, [ { type: 'shape', shape: 'rect', x: 0, y: 0, w: 1, h: 1 }, { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'b' } ], { id: 'mine', type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'c' } ] }] })
ok(canon(again) === canon(nested), 'the same input expands to the same ids — deterministic, so a re-run keeps morph pairing')
ok(new Set(nested.slides[0].elements.map((e) => e.id)).size === 4, 'minted ids are unique on the slide')
const noSlideId = expandDoc({ compact: true, slides: [{ elements: [{ type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'a' }] }, {}] })
ok(noSlideId.slides[0].id === 's1' && noSlideId.slides[1].id === 's2' && noSlideId.slides[0].elements[0].id === 's1-text-0', 'a slide without an id gets s1, s2 …; its elements mint from that')
const backCompact = compactDoc(nested)
ok(!('id' in ((backCompact.slides as Obj[])[0].elements as Obj[])[0]) && ((backCompact.slides as Obj[])[0].elements as Obj[])[3].id === 'mine', 'compactDoc drops an id that equals the mint scheme and keeps an authored one')
const full = starterDoc()
ok(canon(expandDoc(full)) === canon(full) && !isCompact(full), 'a document WITHOUT the flag is returned as is — a full file missing an optional field keeps its meaning (no fontFamily = theme font, not the stack)')
ok(isCompact({ compact: true }) && !isCompact({ compact: 'yes' }) && !isCompact(null), 'the flag is exactly `compact: true`')

console.log('\nnothing non-default is stripped\n')
const mutated = starterDoc()
const firstText = mutated.slides[0].elements.find((e) => e.type === 'text') as TextElement
firstText.rotation = 5; firstText.opacity = 0.5; firstText.lineHeight = 1.7
const mc = compactDoc(mutated)
const mEl = ((mc.slides as Obj[])[0].elements as Obj[]).find((e) => e.id === firstText.id)!
ok(mEl.rotation === 5 && mEl.opacity === 0.5 && mEl.lineHeight === 1.7, 'rotation 5, opacity 0.5, lineHeight 1.7 survive compaction')
const geom = ((mc.slides as Obj[])[0].elements as Obj[]).every((e) => 'x' in e && 'y' in e && 'w' in e && 'h' in e && 'type' in e)
ok(geom, 'x, y, w, h and type are always kept — geometry is never a default')
ok(((mc.slides as Obj[])[0].elements as Obj[]).every((e) => e.type !== 'text' || 'html' in e), 'html is always kept on text')

console.log('\nthe gated loader and the surfaces\n')
const loader = read('slides/src/compactload.ts')
ok(/import \{ sanitizeSlide, withDropReport, withPathSegment[^}]*\} from '\.\/untrusted'/.test(loader) && /=> sanitizeSlide\(s\)/.test(loader) && /const base = parseDoc\(JSON\.stringify\(ex\)\)[\s\S]{0,300}sanitizeDoc\(base as unknown as Record<string, unknown>, o\.live\)/.test(loader), 'compactload.ts expands, runs sanitizeSlide on every slide (collecting drops), then parseDoc and the document gate — one gate, one point of validation')
ok(/if \(!isCompact\(raw\)\) \{\s*const base = parseDoc\(json\)[\s\S]{0,120}sanitizeDoc\(base as unknown as Record<string, unknown>, o\.live\)/.test(loader),
  'a full document passes the structural gate too (sanitizeDoc), not parseDoc alone')
const main = read('slides/src/main.ts')
ok(/const parsed = parseDocInputReport\(json, \{ live: store\.doc \}\)/.test(main) && /return parsed\.report/.test(main) && /compact: \(\) => compactJson\(store\.doc\)/.test(main), 'window.bento.loadDoc accepts compact input and returns the load report; window.bento.compact() emits compact JSON')
ok(/return serializeFile\(store\.doc\)/.test(main), 'window.bento.serialize() is unchanged — the file is full')
const editor = read('slides/src/editor/editor.ts')
ok(/const parsed = parseDocInputReport\(ta\.value, \{ live: this\.store\.doc \}\)/.test(editor) && /Loaded: \{dropped\} fields dropped, \{warnings\} warnings — see console/.test(editor), 'Replace from JSON… accepts compact input and summarises the report in a toast')
ok(/t\('Copy compact JSON \(for agents\)'\)/.test(editor) && /this\.copyDocJson\(true\)/.test(editor) && /compact \? compactJson\(clone\)/.test(editor), 'the Save menu has Copy compact JSON, wired to compactJson')
ok(!/compact/i.test(read('slides/src/save.ts')) && !/compactDoc|compactJson/.test(read('slides/src/model.ts')), 'save.ts and model.ts know nothing of compaction — the on-disk file cannot be compact')
ok(!/compact/.test(read('slides/src/modelkeys.generated.ts')), 'no model key named compact — the flag is input, never stored')
ok(/compact/.test(read('AGENTS.md')), 'AGENTS.md tells agents about the compact form')

console.log('\nround two: md, auto height, the report\n')
{
  const mk = (el: Obj) => ({ compact: true, slides: [{ id: 's1', elements: [el] }] })
  const one = (d: unknown) => (expandDoc(d).slides[0].elements[0] as unknown as Obj)
  // md → the editor's paste conversion, byte for byte
  const md = '**Bold** and *it*\n- one\n  - two'
  ok(one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md })).html === markdownToHtml(md), 'md converts through markdownToHtml — the same html a paste produces')
  ok(!('md' in one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md }))), 'md never reaches the document')
  const both = one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md, html: '<b>kept</b>' }))
  ok(both.html === '<b>kept</b>' && !('md' in both), 'html wins when both are present; md is dropped')
  ok(one(mk({ type: 'shape', shape: 'rect', x: 0, y: 0, w: 10, h: 10, md })).md === md, 'md on a non-text element is left to the gate (which drops it as unknown)')
  // h omitted / "auto" → a provisional one-line height, listed for the browser
  const r1 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, html: 'hi', fontSize: 30, lineHeight: 1.5 }))
  const e1 = r1.doc.slides[0].elements[0] as unknown as Obj
  ok(e1.h === provisionalHeight(30, 1.5) && e1.h === 45, `omitted h → provisional one line (${e1.h} = 30 × 1.5)`)
  ok(r1.stats.autoHeight.length === 1 && r1.stats.autoHeight[0].id === e1.id && r1.stats.autoHeight[0].slide === 's1', 'the element is listed for fitting, by slide and id')
  const r2 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, h: 'auto', html: 'hi' }))
  const e2 = r2.doc.slides[0].elements[0] as unknown as Obj
  ok(typeof e2.h === 'number' && r2.stats.autoHeight.length === 1, 'h: "auto" is the same request as omitting h')
  const r3 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, h: 120, html: 'hi' }))
  ok((r3.doc.slides[0].elements[0] as unknown as Obj).h === 120 && r3.stats.autoHeight.length === 0, 'a given h is kept and not listed')
  const r4 = expandDocWithStats(mk({ type: 'table', x: 0, y: 0, w: 400, columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a' }] }] }))
  ok(r4.stats.autoHeight.length === 0, 'tables are never auto-fitted (their height follows their rows)')
  // the stats
  const r5 = expandDocWithStats({ compact: true, slides: [{ elements: [[{ type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'a' }, { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'b' }]] }] })
  ok(r5.stats.minted === 2 && r5.stats.expanded > 20 && r5.stats.fromMarkdown === 0, `stats: 2 ids minted, ${r5.stats.expanded} fields expanded, 0 from markdown`)
  ok(expandDocWithStats({ format: 'x', slides: [] }).stats.expanded === 0, 'a full document reports nothing expanded')
  // the report shape on the browser side, by source
  ok(/export interface LoadReport/.test(loader) && /dropped: Dropped\[\]/.test(loader) && /expanded: number/.test(loader) && /findings: ValidateResult/.test(loader) && /refit: ExpandStats\['autoHeight'\]/.test(loader), 'LoadReport carries dropped, expanded, fitted, findings and refit')
  ok(/fitAutoHeights\(doc, stats\)/.test(loader) && /measureElement\(tx, doc\)/.test(loader), 'compactload fits every provisional height with measureElement — the panel button\'s measurement')
  ok(/document\.fonts\.ready\.then/.test(main) && /fitAutoHeights\(store\.doc, \{ autoHeight: parsed\.report\.refit \}\)/.test(main), 'loadDoc re-fits after document.fonts.ready when fonts were still loading')
  const gate = read('slides/src/untrusted.ts')
  ok(/export function withDropReport/.test(gate) && /if \(!collector\) return$/m.test(gate), 'the gate collects drops only under withDropReport — one null check otherwise')
  ok(/note\(key, 'unknown key'\)/.test(gate) && /note\(key, `unknown key for a \$\{type\} element`\)/.test(gate) && /note\(key, 'invalid value'\)/.test(gate), 'unknown keys and invalid values are reported with a reason')
}

console.log('\nwhat the editor dereferences on first render\n')
{
  // parseDoc checks only format and a non-empty slides array; render.ts reads
  // doc.size.width/height for every thumbnail and doc.theme.fontFamily for
  // every text box, the About dialog reads doc.title. A compact deck that
  // leaves them out (or writes null) must still arrive whole (found by the
  // bento-check build: a doc without size threw in rebuildSidebar).
  const dEq = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
  const bare = expandDoc({ compact: true, slides: [{ elements: [{ type: 'text', x: 0, y: 0, w: 100, h: 20, html: 'x' }] }] }) as unknown as Obj
  ok(dEq(bare.size, { width: 1280, height: 720 }), 'a compact deck without size gets the model default 1280×720')
  ok(bare.format === 'bento/slides' && typeof bare.version === 'number' && typeof bare.title === 'string' && typeof (bare.theme as Obj).fontFamily === 'string', 'format, version, title and theme.fontFamily are present from newDoc()')
  const nulls = expandDoc({ compact: true, size: null, theme: null, title: 7, format: 'nope', version: 'x', slides: [] }) as unknown as Obj
  ok(dEq(nulls.size, { width: 1280, height: 720 }) && typeof (nulls.theme as Obj).fontFamily === 'string' && typeof nulls.title === 'string' && nulls.format === 'bento/slides' && nulls.version === 1, 'null or wrong-shaped size/theme/title/format/version are replaced by the defaults, not passed through')
  const halfSize = expandDoc({ compact: true, size: { width: 1600 }, slides: [] }) as unknown as Obj
  ok(dEq(halfSize.size, { width: 1280, height: 720 }), 'a size missing its height is replaced whole')
  ok(dEq((expandDoc({ compact: true, size: { width: 1600, height: 900 }, slides: [] }) as unknown as Obj).size, { width: 1600, height: 900 }), 'a well-formed size is kept')
  const nullFont = expandDoc({ compact: true, theme: { fontFamily: null, accent: '#123456' }, slides: [] }) as unknown as Obj
  ok(typeof (nullFont.theme as Obj).fontFamily === 'string' && (nullFont.theme as Obj).accent === '#123456', 'a null theme slot falls back; a set one is kept')
}

console.log('\nthe numbers\n')
const sj = JSON.stringify(starterDoc()), sc = compactJson(starterDoc())
ok(sc.length / sj.length < 0.9, `the starter deck compacts to ${(sc.length / sj.length * 100).toFixed(1)}% of full (a designed deck overrides most defaults; measured 86.1%)`)
const agentCompact = JSON.stringify(compact), agentFull = JSON.stringify(ex)
ok(agentFull.length / agentCompact.length > 2.5, `an agent deck written compact is ${(agentFull.length / agentCompact.length).toFixed(1)}× smaller than its expansion`)

console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)