Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: a deck names the shell's two fonts instead of embedding them (#468)

nyblnetdcb1ff5fe2b9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3233853a..975a802f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1310,6 +1310,13 @@ jobs:
# image gone from a file with nothing on screen to say so.
run: node scripts/test-slides-assets.ts
+ - name: Slides built-in fonts rig
+ # The shell carries two faces; a deck names them (builtin:…) instead
+ # of embedding 86 KB the file already has. At save a deck embedding
+ # byte-identical bytes is rewritten to name them; a different font
+ # keeps its bytes; the live document is untouched; measured saving.
+ run: node scripts/test-slides-fonts.ts
+
- name: Slides pagination rig
# Three ways a slide declines a page number (state, hidden, unnumbered)
# and only one of them stays in the walk; every surface — page fields,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 673bb46d..79453214 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,14 @@ pre-1.0.
otherwise the captured view shows. Embedded documents are stripped of
envelope secrets at the shape gate, and a save keeps an embed's view and
source (the asset prune learned the new reference form).
+- **Files are about 86 KB smaller.** Every saved deck used to carry the two
+ built-in typefaces (Fraunces and Instrument Sans) as embedded font data —
+ the same bytes the app itself already ships, so they existed twice in every
+ file, and were most of a typical text deck's data. A deck now names those
+ faces instead, and any deck that embedded them is slimmed on its next save.
+ Other fonts you add are embedded exactly as before. A copy of the app older
+ than this one shows those two families in the system fallback until it
+ updates itself.
## [1.0.19] — 2026-09-04
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 2f071a5f..6a08d4d2 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -6818,3 +6818,36 @@ updated guard (adding to the themed set can only relax, never regress).
Pointers: `kernel/src/ui/toggle.{ts,css}`, `scripts/test-ui-toggle.ts` (61
checks; role, click-toggle, aria, set-not-firing-onChange, destroy each
mutation-caught).
+
+## 2026-09-14 — A deck names the shell's fonts instead of embedding them
+
+**Measured first.** Three real decks, document block only: a photo deck was
+96% assets; two text decks were 80% assets — and in those two, the "assets"
+were the same two woff2 files, Fraunces 900 and Instrument Sans, 86 KB. Both
+faces are compiled into every shell (`fontdata.ts`). Every saved deck carried
+them again. The structure an AI actually edits was 17–21 KB.
+
+**Decision.** A `doc.fonts[]` entry may name a face the shell carries —
+`asset: 'builtin:fraunces-900'`, `'builtin:instrument-sans'` — with no bytes
+in `assets`. `resolveFontSrc` asks the deck's table first, then
+`BUILTIN_FONTS`; `injectFonts` goes through it. The starter deck names both.
+At save, `adoptBuiltinFonts` (slides' save facade, beside the asset prune)
+rewrites any deck whose embedded bytes are IDENTICAL to a built-in face —
+by bytes, not by family name, so a deck carrying its own cut of Fraunces
+keeps it — and the bytes leave the file. The live document is never touched.
+Measured in Chrome: both faces load from the shell; a legacy deck saved
+85,269 bytes smaller.
+
+**What it costs, said plainly.** An older shell opening a new deck looks
+the `builtin:` key up in `assets`, finds nothing, and skips the rule: those
+two families render in the system fallback until the shell updates itself.
+That is a degrade, not a break, and it is the additivity promise's edge —
+"opens plain", not "opens wrong". Accepted because the saving is 80% of a
+typical text deck's data and the update channel closes the window.
+
+**What was rejected.** Compressing the document block (the splice contract
+says plaintext, and a chat AI reads it); subsetting fonts to used glyphs
+(fragile under editing); moving assets to a payload block outside
+`#bento-doc` (an old shell re-serialises from the doc alone and would drop
+them). The next lever is photos — there is no downscale or recompression at
+insert today — and that is format-neutral.
diff --git a/scripts/test-slides-fonts.ts b/scripts/test-slides-fonts.ts
new file mode 100644
index 00000000..e9082f80
--- /dev/null
+++ b/scripts/test-slides-fonts.ts
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Built-in fonts rig for bento/slides.
+//
+// node scripts/test-slides-fonts.ts
+//
+// WHAT THIS PROVES. The shell carries two faces (fontdata.ts); a deck may
+// NAME them (`builtin:…`) instead of embedding their bytes. Measured before
+// this change on three real decks: the two woff2 files were 86 KB of every
+// saved deck — 80% of a typical text deck's document block — and the same
+// bytes were already in the shell. So:
+//
+// - the starter deck names the faces and embeds no font bytes
+// - resolveFontSrc answers a built-in key from the shell, an asset key
+// from the deck, and nothing for a key that is neither
+// - at save, a deck that embeds bytes IDENTICAL to a built-in face is
+// rewritten to name it and the bytes leave the file; a deck carrying a
+// DIFFERENT font keeps it; the live document is never touched; the
+// result is idempotent
+// - the saving is real: a deck that embedded both faces serialises ~86 KB
+// smaller through the facade, with the same fonts resolving
+//
+// The one thing this cannot measure is an OLDER shell opening a new deck:
+// its injectFonts looks the key up in assets, finds nothing, and skips the
+// rule — the family renders in its fallback stack. A degrade, stated in
+// fonts.ts, and short-lived because the shell updates itself.
+
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, join } from 'node:path'
+import { BUILTIN_FONTS, adoptBuiltinFonts, resolveFontSrc } from '../slides/src/fonts.ts'
+import { FRAUNCES_900, INSTRUMENT_VAR } from '../slides/src/fontdata.ts'
+import { starterDoc } from '../slides/src/starterdeck.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}`)
+}
+const deck = (o: Partial<BentoDoc>): BentoDoc =>
+ ({ format: 'bento/slides', version: 1, docId: 'd', title: 't', slides: [], ...o } as unknown as BentoDoc)
+const OTHER = 'data:font/woff2;base64,AAAAotherfontbytes=='
+
+console.log('the shell\'s faces\n')
+ok(BUILTIN_FONTS['builtin:fraunces-900'] === FRAUNCES_900 && BUILTIN_FONTS['builtin:instrument-sans'] === INSTRUMENT_VAR,
+ 'BUILTIN_FONTS names the two faces fontdata.ts carries')
+ok(Object.keys(BUILTIN_FONTS).every((k) => k.startsWith('builtin:')), 'every built-in key carries the builtin: prefix (no asset table holds one)')
+
+console.log('\nthe starter deck\n')
+const starter = starterDoc()
+ok((starter.fonts ?? []).length === 2 && starter.fonts!.every((f) => f.asset.startsWith('builtin:')), 'the starter deck names both faces')
+ok(!Object.values(starter.assets ?? {}).some((v) => v.startsWith('data:font/')), 'and embeds no font bytes at all')
+ok(starter.fonts!.every((f) => resolveFontSrc(starter, f.asset) !== undefined), 'both resolve from the shell')
+
+console.log('\nresolveFontSrc\n')
+const own = deck({ fonts: [{ family: 'Other', asset: 'font-other' }], assets: { 'font-other': OTHER } })
+ok(resolveFontSrc(own, 'font-other') === OTHER, 'a deck\'s own font resolves from its assets')
+ok(resolveFontSrc(own, 'builtin:fraunces-900') === FRAUNCES_900, 'a built-in key resolves from the shell even in a deck that has assets')
+ok(resolveFontSrc(own, 'font-missing') === undefined && resolveFontSrc(own, 'builtin:nope') === undefined, 'an unknown key resolves to nothing')
+ok(resolveFontSrc(deck({ assets: { 'builtin:fraunces-900': OTHER } }), 'builtin:fraunces-900') === OTHER, 'a deck\'s own asset under a builtin: key would still win (the table is asked first)')
+
+console.log('\nadoptBuiltinFonts at save\n')
+const legacy = deck({
+ fonts: [
+ { family: 'Fraunces', asset: 'font-fraunces-900', weight: '900' },
+ { family: 'Instrument Sans', asset: 'font-instrument', weight: '400 700' },
+ { family: 'Other', asset: 'font-other' },
+ ],
+ assets: { 'font-fraunces-900': FRAUNCES_900, 'font-instrument': INSTRUMENT_VAR, 'font-other': OTHER, pic: 'data:image/png;base64,AAAA' },
+})
+const before = JSON.stringify(legacy)
+const adopted = adoptBuiltinFonts(legacy)
+ok(JSON.stringify(legacy) === before, 'the live document is untouched')
+ok(adopted !== legacy, 'a deck with byte-identical faces gets a copy back')
+ok(adopted.fonts![0].asset === 'builtin:fraunces-900' && adopted.fonts![0].weight === '900', 'Fraunces is rewritten to the built-in key, weight kept')
+ok(adopted.fonts![1].asset === 'builtin:instrument-sans', 'Instrument Sans likewise')
+ok(adopted.fonts![2].asset === 'font-other' && adopted.assets!['font-other'] === OTHER, 'a different font keeps its bytes')
+ok(!('font-fraunces-900' in adopted.assets!) && !('font-instrument' in adopted.assets!), 'the built-in bytes leave the file')
+ok(adopted.assets!.pic === 'data:image/png;base64,AAAA', 'other assets are untouched')
+ok(adopted.fonts!.every((f) => resolveFontSrc(adopted, f.asset) !== undefined), 'every font still resolves after adoption')
+ok(adoptBuiltinFonts(adopted) === adopted, 'idempotent: a second pass returns the same object')
+ok(adoptBuiltinFonts(own) === own, 'a deck with only its own fonts is returned as-is')
+ok(adoptBuiltinFonts(deck({})) !== undefined, 'a deck with no fonts is fine')
+const renamed = deck({ fonts: [{ family: 'Fraunces', asset: 'my-cut' }], assets: { 'my-cut': FRAUNCES_900 } })
+ok(adoptBuiltinFonts(renamed).fonts![0].asset === 'builtin:fraunces-900', 'adoption is by BYTES, whatever the key was')
+const different = deck({ fonts: [{ family: 'Fraunces', asset: 'my-cut' }], assets: { 'my-cut': OTHER } })
+ok(adoptBuiltinFonts(different) === different, '…and not by family name: a deck\'s own Fraunces cut is kept')
+
+console.log('\nthe saving, measured\n')
+const embedded = deck({
+ fonts: [{ family: 'Fraunces', asset: 'f', weight: '900' }, { family: 'Instrument Sans', asset: 'i' }],
+ assets: { f: FRAUNCES_900, i: INSTRUMENT_VAR },
+})
+const sizeBefore = JSON.stringify(embedded).length
+const sizeAfter = JSON.stringify(adoptBuiltinFonts(embedded)).length
+ok(sizeBefore - sizeAfter > 80_000, `a deck embedding both faces shrinks by ${sizeBefore - sizeAfter} bytes (${((1 - sizeAfter / sizeBefore) * 100).toFixed(1)}%)`)
+
+console.log('\nthe facade\n')
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const save = readFileSync(join(root, 'slides/src/save.ts'), 'utf8')
+ok(/kernelSerializeAuto\(pruneUnusedAssets\(adoptBuiltinFonts\(doc\)\)\)/.test(save) && /kernelSerializeFile\(pruneUnusedAssets\(adoptBuiltinFonts\(doc\)\)\)/.test(save),
+ 'save.ts: both serializers adopt built-ins before pruning — every write from this app goes through it')
+ok(/resolveFontSrc\(doc, f\.asset\)/.test(readFileSync(join(root, 'slides/src/fonts.ts'), 'utf8')), 'injectFonts resolves through resolveFontSrc')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-validate.ts b/scripts/test-validate.ts
index 5d63fe01..d537f212 100644
--- a/scripts/test-validate.ts
+++ b/scripts/test-validate.ts
@@ -44,6 +44,18 @@ 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 === 'font-not-embedded'),
'the starter deck carries every typeface it names')
+// The starter deck NAMES the shell's two faces (fonts[].asset = 'builtin:…')
+// with no bytes in assets: a satisfied reference, not a missing asset. Only an
+// unknown built-in name is broken; an asset key with no bytes still is.
+ok(!starter.findings.some((f) => f.code === 'missing-asset'),
+ 'the starter deck\'s built-in font references are not missing assets')
+{
+ const missing = (fonts: NonNullable<BentoDoc['fonts']>) =>
+ validateDoc({ ...starterDoc(), fonts, assets: {} }, { measure: false }).findings.filter((f) => f.code === 'missing-asset')
+ ok(missing([{ family: 'X', asset: 'builtin:nope' }]).length === 1, 'an unknown built-in font name is a missing-asset error')
+ ok(missing([{ family: 'X', asset: 'font-x' }]).length === 1, 'an asset key with no bytes is still the error it was')
+ ok(missing([{ family: 'Fraunces', asset: 'builtin:fraunces-900' }]).length === 0, 'a known built-in name satisfies the reference')
+}
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')
diff --git a/slides/src/fonts.ts b/slides/src/fonts.ts
index f93d515a..982f8450 100644
--- a/slides/src/fonts.ts
+++ b/slides/src/fonts.ts
@@ -3,7 +3,60 @@
// Font utilities: the curated system-stack choices offered in the editor,
// and @font-face injection for fonts embedded in the document's asset table.
-import type { BentoDoc } from './model'
+import type { BentoDoc } from './model.ts'
+import { FRAUNCES_900, INSTRUMENT_VAR } from './fontdata.ts'
+
+/**
+ * Faces the SHELL carries (fontdata.ts, compiled into every build). A font
+ * entry may name one by this key instead of an asset — `builtin:` is not a
+ * key any asset table holds — and the bytes are not written into the file.
+ *
+ * Why: every saved deck used to embed the same two woff2 files the shell
+ * already ships, 86 KB that existed twice in every file and was 80% of a
+ * typical text deck's document block (measured 2026-09-14 on three decks).
+ * A font that is NOT one of these still embeds, as before.
+ *
+ * Older shells: `injectFonts` there looks the key up in `assets`, finds
+ * nothing, and skips the rule — the deck opens with the system stack for
+ * that family. A degrade, and a short one: the shell updates itself.
+ */
+export const BUILTIN_FONTS: Readonly<Record<string, string>> = {
+ 'builtin:fraunces-900': FRAUNCES_900,
+ 'builtin:instrument-sans': INSTRUMENT_VAR,
+}
+
+/** Font bytes for a font entry: the deck's own asset, or a built-in face. */
+export function resolveFontSrc(doc: BentoDoc, asset: string): string | undefined {
+ return doc.assets?.[asset] ?? BUILTIN_FONTS[asset]
+}
+
+/**
+ * At save: a deck that embeds bytes IDENTICAL to a built-in face is rewritten
+ * to name the face instead, and the bytes leave the file. Byte equality, not
+ * family name — a deck carrying its own Fraunces cut keeps it. Returns the
+ * same object when there is nothing to do, a shallow copy otherwise (the live
+ * document is never touched — same contract as pruneUnusedAssets).
+ */
+export function adoptBuiltinFonts(doc: BentoDoc): BentoDoc {
+ const fonts = doc.fonts
+ const assets = doc.assets
+ if (!fonts?.length || !assets) return doc
+ const byBytes = new Map(Object.entries(BUILTIN_FONTS).map(([k, v]) => [v, k]))
+ const rewrite = new Map<string, string>() // asset key → builtin key
+ for (const f of fonts) {
+ const bytes = assets[f.asset]
+ const builtin = bytes !== undefined ? byBytes.get(bytes) : undefined
+ if (builtin) rewrite.set(f.asset, builtin)
+ }
+ if (rewrite.size === 0) return doc
+ const nextAssets = { ...assets }
+ for (const k of rewrite.keys()) delete nextAssets[k]
+ return {
+ ...doc,
+ fonts: fonts.map((f) => (rewrite.has(f.asset) ? { ...f, asset: rewrite.get(f.asset)! } : f)),
+ assets: nextAssets,
+ }
+}
/** Safe cross-platform stacks offered in the font picker. */
export const FONT_CHOICES: Array<{ label: string; stack: string }> = [
@@ -30,7 +83,7 @@ export function firstFamily(stack: string): string {
export function injectFonts(doc: BentoDoc) {
const css = (doc.fonts ?? [])
.map((f) => {
- const src = doc.assets?.[f.asset]
+ const src = resolveFontSrc(doc, f.asset)
if (!src) return ''
return `@font-face{font-family:${JSON.stringify(f.family)};src:url(${JSON.stringify(src)});` +
`font-weight:${f.weight ?? 'normal'};font-style:${f.style ?? 'normal'};font-display:swap}`
diff --git a/slides/src/model.ts b/slides/src/model.ts
index 88090663..367044a1 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -572,6 +572,9 @@ export interface BentoDoc {
/**
* embedded fonts: each entry becomes an @font-face at boot, with the font
* data living in assets (data: URI). Elements then use `family` normally.
+ * `asset` may instead name a face the shell carries (`builtin:…`, see
+ * fonts.ts BUILTIN_FONTS) — no bytes in the file; a shell that does not
+ * know the key renders the family with its fallback stack.
*/
fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>
/**
diff --git a/slides/src/save.ts b/slides/src/save.ts
index 458d56b8..c7f218eb 100644
--- a/slides/src/save.ts
+++ b/slides/src/save.ts
@@ -16,14 +16,15 @@ export * from '../../kernel/src/save.ts'
import { serializeAuto as kernelSerializeAuto, serializeFile as kernelSerializeFile } from '../../kernel/src/save.ts'
import type { BentoDoc } from './model'
import { pruneUnusedAssets } from './assets'
+import { adoptBuiltinFonts } from './fonts'
/** Encryption-aware serializer, with unreferenced assets pruned from the copy it writes. */
export function serializeAuto(doc: BentoDoc): Promise<string> {
- return kernelSerializeAuto(pruneUnusedAssets(doc))
+ return kernelSerializeAuto(pruneUnusedAssets(adoptBuiltinFonts(doc)))
}
/** Plain serializer (tooling, window.bento.serialize), pruned the same way so
* a script sees the file a save would produce rather than a larger one. */
export function serializeFile(doc: BentoDoc): string {
- return kernelSerializeFile(pruneUnusedAssets(doc))
+ return kernelSerializeFile(pruneUnusedAssets(adoptBuiltinFonts(doc)))
}
diff --git a/slides/src/starterdeck.ts b/slides/src/starterdeck.ts
index ef2c0b34..f7e5d37f 100644
--- a/slides/src/starterdeck.ts
+++ b/slides/src/starterdeck.ts
@@ -20,10 +20,9 @@ import {
newDoc, uid, defaultText, defaultShape, defaultChart, defaultTable, defaultCode,
type BentoDoc, type Slide, type SlideElement, type TextElement, type ShapeElement,
type SvgElement, type TableElement,
-} from './model'
-import { FRAUNCES_900, INSTRUMENT_VAR } from './fontdata'
+} from './model.ts'
-/** Display face — embedded in the file (see fontdata.ts). */
+/** Display face — the shell's own (fonts.ts BUILTIN_FONTS), named by the deck, not embedded. */
const DISPLAY = "'Fraunces', Georgia, serif"
/** Text face — embedded variable sans. */
const BODY = "'Instrument Sans', -apple-system, 'Segoe UI', Helvetica, sans-serif"
@@ -337,13 +336,13 @@ export function starterDoc(): BentoDoc {
a: '#3f9142', // diff: added
d: '#c25a43', // diff: removed
}
+ // The two faces are the shell's own (fonts.ts BUILTIN_FONTS): named, not
+ // embedded — 86 KB that every saved deck used to carry twice.
doc.fonts = [
- { family: 'Fraunces', asset: 'font-fraunces-900', weight: '900' },
- { family: 'Instrument Sans', asset: 'font-instrument', weight: '400 700' },
+ { family: 'Fraunces', asset: 'builtin:fraunces-900', weight: '900' },
+ { family: 'Instrument Sans', asset: 'builtin:instrument-sans', weight: '400 700' },
]
doc.assets = {
- 'font-fraunces-900': FRAUNCES_900,
- 'font-instrument': INSTRUMENT_VAR,
'dots-ink': DOTS_INK,
'dots-paper': DOTS_PAPER,
'aurora-amber': AURORA_PEACH,
diff --git a/slides/src/validate.ts b/slides/src/validate.ts
index a53df087..54a780e6 100644
--- a/slides/src/validate.ts
+++ b/slides/src/validate.ts
@@ -26,6 +26,7 @@ import type { BentoDoc, Slide, SlideElement, TextElement } from './model.ts'
import { MODEL_KEYS } from './modelkeys.generated.ts'
import { isRemoteUrl } from '../../kernel/src/net.ts'
import { measureElements } from './measure.ts'
+import { BUILTIN_FONTS } from './fonts.ts'
import { eachRef, paletteOf, parseThemeRef, resolveRef, _readPath } from './palette.ts'
export type Severity = 'error' | 'warning' | 'info'
@@ -153,10 +154,19 @@ export function validateDoc(doc: BentoDoc, opts: ValidateOpts = {}): ValidateRes
}
}
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.` })
+ if (!f.asset || assets[f.asset]) continue
+ // A `builtin:` key names a face the shell carries (fonts.ts BUILTIN_FONTS)
+ // — a satisfied reference with no bytes in the file. Only an unknown
+ // built-in name is broken.
+ if (f.asset.startsWith('builtin:')) {
+ if (!(f.asset in BUILTIN_FONTS)) {
+ add({ code: 'missing-asset', severity: 'error', path: `fonts.${f.family}`,
+ message: `Font "${f.family}" names built-in face "${f.asset}", which this app does not carry (known: ${Object.keys(BUILTIN_FONTS).join(', ')}) — the face will not load and text falls back silently.` })
+ }
+ continue
}
+ 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.` })
}
// A live-shared deck carries the keys to its own room — that is how opening a
// copy joins a session with no account and nothing to configure. The file IS