Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: complete the font lifecycle fix from #516 (#539)

nyblnetde75b92da1b7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1867d768..3c08850b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1869,3 +1869,26 @@ jobs:
# which paints "Edited" and would credit a colleague's typing to you.
# The last section is two real sessions over a real BroadcastChannel.
run: node --no-warnings scripts/test-sync-spaces-session.ts
+
+ slides-font-browser:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Install browser test runtime
+ # Pinned outside app packages: browser automation is not shipped in documents.
+ run: |
+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]
+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium
+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"
+ - name: Build the tested standalone documents
+ run: |
+ npm ci --prefix slides
+ npm run build:single --prefix slides
+ - name: Exercise the packaged documents in Chromium
+ # Real UI and serialization, offline; delayed mock writes expose save races.
+ run: |
+ node scripts/test-slides-font-lifecycle-browser.mjs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f731fccd..a6a43854 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,14 @@ pre-1.0.
know. The underline only appears while editing, never in the show, in print
or in the saved file. Pasting or editing a formula no longer drops the
backslash from `\_`. Reported in #540.
+- **Embedded fonts show up after "Replace from JSON".** Rahul Ravikumar (#516)
+ found that a deck loaded through Replace from JSON could keep showing
+ fallback fonts instead of the ones embedded in it (every time, for a font
+ used by code snippets) and fixed it by refreshing the fonts whenever the
+ document changes. Building on that, a font you remove from the deck now
+ disappears, undo and redo bring fonts back and forth, replacing a font's
+ file takes effect, and ordinary edits no longer re-apply every embedded
+ font.
## [1.2.3] — 2026-09-19
diff --git a/scripts/test-slides-font-lifecycle-browser.mjs b/scripts/test-slides-font-lifecycle-browser.mjs
new file mode 100644
index 00000000..2efd91b6
--- /dev/null
+++ b/scripts/test-slides-font-lifecycle-browser.mjs
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+import assert from 'node:assert/strict'
+import * as fs from 'node:fs'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ const p = await browser.newPage(); const errors = [];
+ p.on('pageerror', e => errors.push(e.message));
+ p.on('dialog', d => d.accept());
+ await p.route(/^https?:/, r => r.abort());
+ await p.goto(new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url).href);
+ await p.waitForFunction(() => window.bento?.doc);
+ // #516: JSON replacement must refresh fonts, including removals and undo.
+ const original = await p.evaluate(() => structuredClone(window.bento.doc));
+ const custom = structuredClone(original);
+ const fontBytes = fs.readFileSync(new URL('./gallery-fonts/SpaceMono-400-latin.woff2', import.meta.url)).toString('base64');
+ custom.fonts = [{ family: 'Review516', asset: 'review-font' }];
+ custom.assets = { ...custom.assets, 'review-font': 'data:font/woff2;base64,' + fontBytes };
+ async function replace(doc) {
+ await p.getByRole('button',{name:'Save as… — copy, new deck, password',exact:true}).click();
+ await p.getByText('Replace from JSON…',{exact:true}).click();
+ await p.locator('.ed-about-json').fill(JSON.stringify(doc));
+ await p.locator('.ed-about-overlay').getByRole('button',{name:'Apply',exact:true}).click();
+ }
+ await replace(custom);
+ assert(await p.evaluate(async () => {
+ await document.fonts.load('32px Review516');
+ return [...document.fonts].some(f => f.family.includes('Review516') && f.status === 'loaded');
+ }));
+ await p.evaluate(() => {
+ window.fontChanges = 0;
+ window.fontObserver = new MutationObserver(r => window.fontChanges += r.length);
+ window.fontObserver.observe(document.getElementById('bento-fonts'), { childList: true, characterData: true, subtree: true });
+ });
+ for (let i=0;i<3;i++) {
+ await p.locator('.ed-title').fill('Unrelated edit ' + i);
+ await p.locator('.ed-title').press('Tab');
+ }
+ assert.equal(await p.evaluate(() => window.fontChanges), 0);
+ const removed = structuredClone(custom); removed.fonts = []; delete removed.assets['review-font'];
+ await replace(removed);
+ const absent = () => p.evaluate(() => !document.getElementById('bento-fonts').textContent.includes('Review516') &&
+ ![...document.fonts].some(f => f.family.includes('Review516')));
+ assert(await absent());
+ await replace(custom);
+ await p.evaluate(() => window.bento.undo());
+ assert(await absent());
+ await p.evaluate(() => window.bento.redo());
+ assert(await p.evaluate(() => document.getElementById('bento-fonts').textContent.includes('Review516')));
+ // Changing bytes under an existing key also invalidates the font registration.
+ const changed = structuredClone(custom);
+ changed.assets['review-font'] = 'data:font/woff2;base64,' + fs.readFileSync(new URL('./gallery-fonts/SpaceMono-700-latin.woff2', import.meta.url)).toString('base64');
+ await replace(changed);
+ assert(await p.evaluate(src => document.getElementById('bento-fonts').textContent.includes(src), changed.assets['review-font']));
+ await replace(original);
+ await p.evaluate(() => window.fontObserver.disconnect());
+ console.log('Font JSON import loads; removal, undo/redo and asset replacement refresh; unrelated edits cause zero stylesheet writes');
+ assert.deepEqual(errors, []);
+} finally { await browser.close() }
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 9e44787a..5c8aa1be 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -136,6 +136,7 @@ export class Editor {
store.on('doc', () => this.syncConnectors())
store.on('doc', () => this.syncThemeRefs())
store.on('doc', () => this.syncFonts())
+ this.syncFonts()
document.addEventListener('bento:apply-layout', ((ev: CustomEvent) => {
this.openLayoutPicker(ev.detail.anchor as HTMLElement, { kind: 'apply' })
}) as EventListener)
@@ -2395,7 +2396,6 @@ export class Editor {
if (clip?.kind === 'elements') {
let added: SlideElement[] = []
this.store.commit(() => { added = insertElements(clip, this.store.doc, this.store.slide) })
- if (clip.fonts?.length) injectFonts(this.store.doc)
this.store.select(added.map((e) => e.id))
this.toast(added.length === 1 ? t('Pasted 1 item') : t('Pasted {n} items', { n: added.length }))
return true
@@ -2404,7 +2404,6 @@ export class Editor {
const at = this.store.currentIndex + 1
let made: Slide[] = []
this.store.commit(() => { made = insertSlides(clip, this.store.doc, at) }, 'slides')
- if (clip.fonts?.length) injectFonts(this.store.doc)
this.rebuildSidebar()
this.store.goTo(at)
this.toast(made.length === 1 ? t('Pasted 1 slide') : t('Pasted {n} slides', { n: made.length }))
@@ -2473,7 +2472,7 @@ export class Editor {
* Re-inject custom font bundles when applicable.
*/
private syncFonts() {
- if (this.store.doc.fonts?.length) injectFonts(this.store.doc)
+ injectFonts(this.store.doc)
}
// --- live table→chart binding -------------------------------------------------
diff --git a/slides/src/fonts.ts b/slides/src/fonts.ts
index 982f8450..f8bd03b0 100644
--- a/slides/src/fonts.ts
+++ b/slides/src/fonts.ts
@@ -76,24 +76,32 @@ export function firstFamily(stack: string): string {
return (stack.split(',')[0] ?? '').trim().replace(/^['"]|['"]$/g, '').toLowerCase()
}
-/**
- * (Re)register @font-face rules for every embedded font in the document.
- * Idempotent — call at boot and again whenever a font is added.
- */
+// A descriptor snapshot avoids rebuilding large data-URL CSS on unrelated edits.
+// Compare values, not doc/array identity: imports replace objects; editing mutates them.
+const injected = new WeakMap<HTMLStyleElement, string[]>()
+
+/** Refresh on every document event, including removal/undo. Only font changes
+ * touch the stylesheet, so unrelated edits never restart font loading. */
export function injectFonts(doc: BentoDoc) {
- const css = (doc.fonts ?? [])
- .map((f) => {
- 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}`
- })
- .join('\n')
+ const faces = (doc.fonts ?? []).map(f => ({
+ family: f.family, src: resolveFontSrc(doc, f.asset) ?? '',
+ weight: f.weight ?? 'normal', style: f.style ?? 'normal',
+ }))
+ const signature = faces.flatMap(f => [f.family, f.src, f.weight, f.style])
let style = document.getElementById('bento-fonts') as HTMLStyleElement | null
+ const previous = style && injected.get(style)
+ if (previous && previous.length === signature.length && previous.every((v, i) => v === signature[i])) return
+ const css = faces.filter(f => f.src).map(f =>
+ `@font-face{font-family:${JSON.stringify(f.family)};src:url(${JSON.stringify(f.src)});` +
+ `font-weight:${f.weight};font-style:${f.style};font-display:swap}`,
+ ).join('\n')
if (!style) {
+ if (!css) return
style = document.createElement('style')
style.id = 'bento-fonts'
+ style.setAttribute('data-bento-transient', '')
document.head.appendChild(style)
}
- style.textContent = css
+ if (style.textContent !== css) style.textContent = css
+ injected.set(style, signature)
}