Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: Save perf improvements (phase 2) (#793)

Rahul Ravikumar5e5ee7b94835
diff --git a/.github/workflows/ci-slides.yml b/.github/workflows/ci-slides.yml
index 74bea133..f49956cd 100644
--- a/.github/workflows/ci-slides.yml
+++ b/.github/workflows/ci-slides.yml
@@ -127,6 +127,11 @@ jobs:
# password; the same with only the blob import allowed; the ⌘S re-save
# and the self-update re-splice open again.
run: node scripts/test-slides-encrypted-open-browser.mjs
+ - name: The saved preview keeps pictures that fit in Chromium
+ # An image used twice is held once (hoisted), a 62 KB image that fits
+ # keeps tier 1, and a page whose assets exceed the budget takes the fast
+ # path straight to tinted boxes.
+ run: node scripts/test-slides-preview-tiers-browser.mjs
- name: The loader reads what the app published in Chromium
# Toy shells from the real postbuild: an app that is running, locked at
# a gate, or refused (and threw) runs ONCE and gets no loader card; only
diff --git a/scripts/test-slides-preview-tiers-browser.mjs b/scripts/test-slides-preview-tiers-browser.mjs
new file mode 100644
index 00000000..f0f28405
--- /dev/null
+++ b/scripts/test-slides-preview-tiers-browser.mjs
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The saved preview keeps a first page's pictures whenever they fit the budget.
+//
+// npm run build:single --prefix slides && node scripts/test-slides-preview-tiers-browser.mjs
+//
+// WHAT THIS PROVES, in the packaged document. A saved deck carries a still of
+// its first page for file managers, in three tiers under PREVIEW_BUDGET: the
+// page with its images, the page with tinted boxes where the images were, and
+// a title card. Two things decide which tier a deck gets, and both are pinned:
+// 1. hoisting — a declaration repeated on the page moves into one rule, so an
+// image used twice costs ONE copy of its data. A length cap on what may be
+// hoisted kept the repeats inline, and a 33 KB image used twice fell to
+// tinted boxes where it fits once;
+// 2. the fast path — when the page's distinct assets already exceed the
+// budget, tier 1 is skipped without building it (a 9 MB first page saves
+// in a third of the time). The assets are a LOWER bound on tier 1's size,
+// so the comparison is against the budget itself: compared against less,
+// a 62 KB image that fits was sent to tinted boxes.
+// Each case is a saved file's own preview, read back: which tier, and how many
+// copies of the image data it holds.
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0
+let failures = 0
+function ok(cond, msg) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+const shell = readFileSync(new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url), 'utf8')
+const dir = mkdtempSync(join(tmpdir(), 'bento-preview-tiers-'))
+
+// incompressible-looking base64, so sizes are what they say
+const b64 = (bytes, seed) => { let s = ''; const a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; let x = seed; for (let i = 0; i < bytes; i++) { x = (x * 1103515245 + 12345) & 0x7fffffff; s += a[x % 64] } return s }
+const img = (kb, seed = 7) => 'data:image/png;base64,' + b64(kb * 1024, seed)
+const at = (i) => ({ x: 80 + i * 380, y: 120, w: 340, h: 220, rotation: 0, opacity: 1 })
+const images = (srcs) => srcs.map((src, i) => ({ id: 'i' + i, type: 'image', ...at(i), src }))
+const deck = (elements) => ({
+ format: 'bento/slides', version: 1, docId: 'preview-tiers', title: 'tiers', size: { width: 1280, height: 720 },
+ theme: { background: '#ffffff', color: '#1E2A3A', accent: '#f7a600', fontFamily: 'system-ui' },
+ slides: [{ id: 's1', background: '#ffffff', transition: 'none', notes: '', elements }],
+})
+const same = (kb, n) => { const s = img(kb); return Array.from({ length: n }, () => s) }
+const CASES = [
+ // [name, elements, expected tier, expected copies of image data in tier 1]
+ ['one 33 KB image, used twice', images(same(33, 2)), 1, 1],
+ ['one 20 KB image, used three times', images(same(20, 3)), 1, 1],
+ ['two different 20 KB images', images([img(20, 1), img(20, 2)]), 1, 2],
+ ['one 62 KB image, alone (fits)', images([img(62)]), 1, 1],
+ ['one 70 KB image, alone (does not fit)', images([img(70)]), 2, 0],
+ ['three 3 MB images (the fast path)', images([img(3072, 1), img(3072, 2), img(3072, 3)]), 2, 0],
+]
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } })
+ await ctx.route(/^https?:/, (r) => r.abort())
+ for (const [name, elements, tier, copies] of CASES) {
+ const p = await ctx.newPage()
+ const open = '<script type="application/bento+json" id="bento-doc">', close = '</' + 'script>'
+ const a = shell.indexOf(open) + open.length
+ const file = join(dir, `${name.replace(/\W+/g, '-')}.bento.html`)
+ writeFileSync(file, shell.slice(0, a) + JSON.stringify(deck(elements)).replace(/</g, '\\u003c') + shell.slice(shell.indexOf(close, a)))
+ await p.goto('file://' + file)
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.ed-topbar'), null, { timeout: 30000 })
+ const r = await p.evaluate(() => {
+ const html = window.bento.serialize()
+ const d = new DOMParser().parseFromString(html, 'text/html')
+ const pv = d.querySelector('[data-bento-preview]:not(script)')
+ if (!pv) return { tier: 0, copies: 0, bytes: 0 }
+ const out = pv.outerHTML
+ const copies = (out.match(/data:image\/png/g) || []).length
+ const tinted = /linear-gradient\(135deg/.test(out)
+ return { tier: copies ? 1 : tinted ? 2 : 3, copies, bytes: new TextEncoder().encode(out).length }
+ })
+ const label = (t) => ['no preview', 'tier 1 (images)', 'tier 2 (tinted boxes)', 'tier 3 (title card)'][t]
+ ok(r.tier === tier && (tier !== 1 || r.copies === copies),
+ `${name}: ${label(tier)}${tier === 1 ? `, image data held ${copies}×` : ''} — got ${label(r.tier)}${r.tier === 1 ? `, ${r.copies}×` : ''} (${r.bytes} bytes)`)
+ await p.close()
+ }
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/src/preview.ts b/slides/src/preview.ts
index 70082e3c..3633f2d0 100644
--- a/slides/src/preview.ts
+++ b/slides/src/preview.ts
@@ -33,7 +33,7 @@
// the content scaled non-uniformly. It is not usable for the one renderer this
// feature exists to serve.
-import { renderSlide } from './render'
+import { renderSlide, resolveAsset } from './render'
import { PREVIEW_BUDGET, type BentoDoc, type Slide, inLinearFlow } from './model'
/** Elements that must never reach a static preview (active or external). */
@@ -215,11 +215,24 @@ function titleCard(doc: BentoDoc): HTMLElement {
/** Split a style attribute into declarations. Not `split(';')`: a data: URI
* carries its own semicolons (`;charset=utf-8,`) inside url(). */
function splitDecls(css: string): string[] {
+ if (!css.includes('(') && !css.includes('"') && !css.includes("'")) {
+ return css.split(';').map((d) => d.trim()).filter(Boolean)
+ }
const out: string[] = []
let depth = 0, quote = '', start = 0
for (let i = 0; i < css.length; i++) {
const c = css[i]
- if (quote) { if (c === quote && css[i - 1] !== '\\') quote = '' ; continue }
+ if (quote) {
+ const nextQuote = css.indexOf(quote, i)
+ if (nextQuote === -1) break
+ if (css[nextQuote - 1] === '\\') {
+ i = nextQuote
+ continue
+ }
+ quote = ''
+ i = nextQuote
+ continue
+ }
if (c === '"' || c === "'") quote = c
else if (c === '(') depth++
else if (c === ')') depth--
@@ -292,10 +305,16 @@ function imagesToBackgrounds(root: HTMLElement) {
*/
function hoistRepeats(root: HTMLElement) {
const parsed = Array.from(root.querySelectorAll<HTMLElement>('[style]'))
- .map((el) => ({ el, decls: splitDecls(el.getAttribute('style') ?? '') }))
+ .map((el) => {
+ const decls = splitDecls(el.getAttribute('style') ?? '')
+ const props = decls.map(propOf)
+ return { el, decls, props }
+ })
- const movable = ({ decls }: { decls: string[] }, i: number) => {
- const props = decls.map(propOf)
+ // No length limit here: a long declaration is exactly what hoisting is for.
+ // An image used twice on the page is the same multi-kilobyte url() twice, and
+ // hoisting it is what makes the page pay for it once.
+ const movable = ({ decls, props }: { decls: string[]; props: string[] }, i: number) => {
const p = props[i]
// A `<` in a declaration must stay inline. The stylesheet is raw text, so a
// hoisted `</style>` would close it early and the rest would parse as live
@@ -367,7 +386,47 @@ function slim(built: HTMLElement) {
hoistRepeats(built)
}
-const byteLength = (el: HTMLElement) => new TextEncoder().encode(el.outerHTML).length
+const encoder = new TextEncoder()
+const byteLength = (el: HTMLElement) => encoder.encode(el.outerHTML).length
+
+/**
+ * Fast-fail heuristic for Tier 1: If the distinct image, media, or svg assets
+ * on the slide exceed the byte budget, don't bother with Tier 1 previews at all.
+ */
+function slideAssetsExceedBudget(slide: Slide, doc: BentoDoc, budget: number): boolean {
+ let size = 0
+ const bg = slide.background || doc.theme?.background
+ if (bg && (bg.includes('data:') || bg.includes('url('))) {
+ size += bg.length
+ if (size > budget) return true
+ }
+ const seen = new Set<string>()
+ for (const el of slide.elements ?? []) {
+ if (el.type === 'image' && el.src) {
+ const src = resolveAsset(doc, el.src)
+ if (src && !seen.has(src)) {
+ seen.add(src)
+ size += src.length
+ if (size > budget) return true
+ }
+ } else if (el.type === 'svg') {
+ const markup = el.asset ? (doc.assets?.[el.asset] ?? '') : (el.markup ?? '')
+ if (markup && !seen.has(markup)) {
+ seen.add(markup)
+ size += markup.length
+ if (size > budget) return true
+ }
+ } else if (el.type === 'media') {
+ const poster = el.poster ? resolveAsset(doc, el.poster) : ''
+ if (poster && !seen.has(poster)) {
+ seen.add(poster)
+ size += poster.length
+ if (size > budget) return true
+ }
+ }
+ }
+ return false
+}
/**
* Build the static preview of the deck's first page, or null when there is
@@ -388,7 +447,17 @@ export function buildSlidePreview(doc: BentoDoc): HTMLElement | null {
const slide = doc.slides.find(inLinearFlow) ?? doc.slides[0]
if (!slide) return null
- for (const keepImages of [true, false]) {
+ // If the first page carries raster payloads or complex SVGs that already
+ // exceed the byte budget, Tier 1 (keepImages: true) will always fail.
+ // Fast-fail directly to Tier 2 to avoid rendering multi-megabyte DOMs,
+ // running splitDecls/hoistRepeats on giant base64 payloads, and outerHTML encoding.
+ // Compared against the budget itself: every distinct asset counted appears
+ // at least once in a tier-1 page, so their sum is a lower bound on its size,
+ // and only a sum OVER the budget proves tier 1 cannot fit.
+ const canFitImages = !slideAssetsExceedBudget(slide, doc, PREVIEW_BUDGET)
+ const tiers = canFitImages ? [true, false] : [false]
+
+ for (const keepImages of tiers) {
const page = renderSlide(slide, doc, { svgAsImage: true, hidePlaceholders: true })
staticize(page, doc, keepImages)
if (!keepImages) page.style.background = flatBackground(slide.background) ?? doc.theme.background