Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento.page/convert: one page for PowerPoint in and out, and four export improvements (#675)

nyblnet9e173928ebf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39ddb346..10235598 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,18 +11,29 @@ pre-1.0.
## [Unreleased]
-- **Save a deck as PowerPoint, from a terminal.**
- `node convert/cli.mjs deck.bento.html --to pptx` writes `deck.pptx`, with
- speaker notes, links, tables, charts, pictures and hidden slides. It reports
- what it approximated or left out, and on which slides: animations show
+- **One page for PowerPoint, in and out: bento.page/convert.** Drop a
+ `.pptx` to open it as a bento/slides deck, or drop a bento/slides deck (or
+ its document JSON) to save it as PowerPoint. The page detects what you
+ dropped and offers what it can become; there's a sample deck to try. As
+ before, nothing is uploaded: the conversion runs in your browser, and the
+ page only downloads the signed bento/slides release when it makes a deck.
+ bento.page/import now opens this page, so its links keep working.
+
+- **Saving as PowerPoint keeps more of your deck.** Speaker notes, links,
+ tables, charts, pictures and hidden slides come across, and now code
+ blocks too (as editable text in Consolas, indentation kept) and embedded
+ documents (as a picture of what they show). WebP pictures are converted to
+ PNG on bento.page/convert. Interactive states can come along as hidden
+ slides that their links lead to. After each conversion you get a list of
+ what was approximated or left out, and on which slides: animations show
their final frame, Morph becomes a plain cut, formulas stay as their LaTeX
- source, and code and embedded documents are not exported yet. It also says
- which of the deck's own fonts to install, and `--report r.json` saves the
- full report. It reads a saved deck or its document JSON. Every export is
- checked before it is written, and a package PowerPoint would want to repair
- is refused. Export is a library and a command-line tool rather than a
- button in the app, so every shared file stays small and the app stays
- focused.
+ source, and code loses its syntax colours. Page numbers stay right after
+ hidden slides. Every export is checked before it is written, so you never
+ get a file PowerPoint wants to repair. From a terminal:
+ `node convert/cli.mjs deck.bento.html --to pptx` (with `--states` and
+ `--report r.json`). Export is a page, a library and a command-line tool
+ rather than a button in the app, so every shared file stays small and the
+ app stays focused.
- **Long speaker notes scroll in presenter view.** Notes that are taller than
the space beside the current and next slides now get their own vertical
diff --git a/convert/CONTRIBUTING.md b/convert/CONTRIBUTING.md
index da4f1319..ed260b70 100644
--- a/convert/CONTRIBUTING.md
+++ b/convert/CONTRIBUTING.md
@@ -23,10 +23,11 @@ convert/
index.ts walks the deck, allocates ids, assembles the package
contract.ts the element-writer contract (read this first)
text.ts shapes.ts media.ts tables.ts charts.ts one writer per element type
- code.ts embed.ts writers not written yet (stubs)
+ code.ts embed.ts writers on the contract (code → text, embed → its picture)
parts.ts the package skeleton: presentation, masters, layouts, theme, notes
src/xmlout.ts builds XML as plain data, escapes everything
- page/ bento.page/import
+ src/pairs.ts the conversion table bento.page/convert offers
+ page/ bento.page/convert (one page, every pair in pairs.ts)
scripts/test-convert/ the rigs (tests); files starting with _ are helpers
```
@@ -66,7 +67,13 @@ starter deck uses nearly every element type.
writes the package with `parts.ts`: presentation, master, layout, theme,
notes, and the property parts PowerPoint expects.
5. Everything the writers could not carry exactly is in the **fidelity
- report** that comes back with the bytes.
+ report** that comes back with the bytes, with the slides it happened on.
+
+Two options change what is exported. `includeStates` adds interactive
+states as hidden slides that links lead to (the CLI's `--states`).
+`rasterise` lets a host with a browser turn pictures PowerPoint cannot take
+(WebP, AVIF, BMP) into PNG; bento.page/convert passes one, and the CLI
+reports such pictures dropped.
## The writer contract
@@ -127,25 +134,31 @@ the runner picks it up and CI runs it.
purpose once (delete the line that does the thing) and watch the rig go red.
A check that never failed hasn't been shown to work.
-## Walkthrough: writing the `code` writer
-
-1. Open `pptx-write/code.ts`. `CodeElIn` lists the fields you get. The stub
- reports the element dropped and returns `null`.
-2. Look at `textSp` in `text.ts`. It builds a text box (`p:sp` with
- `p:txBody`) from a frame, paragraphs and run properties. `emu()` in
- `shapes.ts` converts px to PowerPoint units.
-3. Build a text box at the element's frame: one paragraph per line of
- `content`, in the element's font (fall back to `Consolas`), size, colour
- and alignment. Keep leading spaces: indentation is the point of code.
-4. Syntax colours are optional in a first version. If you leave them out,
- report it: `ctx.report.add('approximated', 'code-colours-flattened',
- ctx.where, 'code shows in one colour; syntax highlighting is not exported')`.
-5. In `scripts/test-convert/pptx-coverage.ts`, move `code` from `NOT_YET`
- to `SAMPLE`/`MAPPED`. The rig now requires one shape and a clean package.
-6. Add `scripts/test-convert/pptx-code.ts` with your own checks: lines become
- paragraphs, leading spaces survive, `<` and `&` in code are escaped, an
- empty `content` doesn't crash.
-7. Run `node scripts/test-convert.ts` and the typecheck. Then **open the
+## Walkthrough: a better `bar` line end
+
+A line can end in an arrow, a dot or a `bar` (a short flat tick across the
+line). PowerPoint's arrowheads have no bar, so today the writer draws a
+diamond and says so (`line-tip-approximated`). This walks through replacing
+that with something closer.
+
+1. Open `pptx-write/shapes.ts` and find `tipType`. It maps a Bento tip to a
+ PowerPoint arrowhead for `a:headEnd`/`a:tailEnd`. `'bar'` falls through to
+ `'diamond'` and a report entry.
+2. Decide what "closer" means and try it in real PowerPoint first. One idea:
+ end the line with no arrowhead and draw the bar as a short extra line at
+ the end point, perpendicular to the line. `shapeNode` builds a `p:sp`;
+ `emu()` converts px; the line's endpoints follow from its frame and
+ rotation (see the header of `shapes.ts`).
+3. If you add a shape, the writer contract still holds: one top-level node
+ per element. Wrap the line and its bar in a group (`p:grpSp`), or keep
+ the diamond and improve its size. Whatever you choose, change the report
+ entry to say what PowerPoint now shows, or remove it if nothing is lost.
+4. Add `scripts/test-convert/pptx-line-tips.ts` with your own checks, built
+ on `./_export-harness.ts`: a bar at either end, at both, on a rotated
+ line, and a clean package every time.
+5. **Prove your checks can fail**: break your code on purpose once and watch
+ the rig go red.
+6. Run `node scripts/test-convert.ts` and the typecheck. Then **open the
result in PowerPoint**, the one check no rig can do. Say in your PR which
app and version you opened it in (PowerPoint for Mac or Windows, Keynote,
LibreOffice, Google Slides).
@@ -157,13 +170,11 @@ Each task is self-contained and has a rig to extend. Tasks marked
| task | where | notes |
|---|---|---|
-| **Export `code` elements** · good first issue | `pptx-write/code.ts` | the walkthrough above |
-| **Export `embed` elements** · good first issue | `pptx-write/embed.ts` | every embed has an SVG `view`; `svgPic` in `media.ts` already places SVG. Report `approximated` (`embed-static`): the picture travels, the live document doesn't |
-| **Line tip `bar`** · good first issue | `pptx-write/shapes.ts` | a `bar` line end exports as a diamond today (`line-tip-approximated`); find the closest real PowerPoint end, or draw it |
+| **Line tip `bar`** · good first issue | `pptx-write/shapes.ts` | the walkthrough above; a `bar` line end exports as a diamond today (`line-tip-approximated`) |
| **Playable audio and video** | `pptx-write/media.ts` | today only a video's poster exports (`media-dropped`). PowerPoint embeds media as a `p:pic` with a media relationship and timing |
| **Morph transitions** | `pptx-write/index.ts`, `parts.ts` | PowerPoint's Morph is an extension (`p159:morph` inside `mc:AlternateContent`); slides currently cut (`morph-not-exported`). Bento morphs pair elements by id, so the pairing is already in the deck |
-| **Picture fallback for SVG** | `pptx-write/media.ts` | PowerPoint 2016 shows SVG as a blank frame without a PNG fallback (`svg-no-raster-fallback`). Rasterising needs a renderer: open an issue to discuss before writing code |
-| **Export compact documents** | `src/export.ts` | `bentoToPptx` refuses `compact: true` files; slides' compact loader shows how they expand |
+| **Picture fallback for SVG** | `pptx-write/media.ts` | PowerPoint 2016 shows SVG as a blank frame without a PNG fallback (`svg-no-raster-fallback`). The `rasterise` option already gives the writer a renderer where a host has one, but a PNG beside every SVG makes files much larger: open an issue to discuss before writing code |
+| **Export compact documents** | `src/export.ts` | `bentoToPptx` refuses `compact: true` files. `page/load-json.ts` already expands them for the page (slides' expander and gate, no DOM); the CLI could do the same |
| **One `bento` command** | `bin/` (new) | a small dispatcher so `bento convert …` and `bento check …` are one tool |
## Before you open a pull request
diff --git a/convert/cli.mjs b/convert/cli.mjs
index 02adfebb..265a44ad 100755
--- a/convert/cli.mjs
+++ b/convert/cli.mjs
@@ -23,7 +23,8 @@
// refuses the network entirely and requires `--shell`.
//
// EXPORT (--to pptx) reads a saved deck's #bento-doc block and writes a .pptx.
-// It needs no network. It refuses an encrypted deck, a raw compact document and
+// It needs no network. --states adds interactive states as hidden slides that
+// links lead to (default: left out, links go to the parent). It refuses an encrypted deck, a raw compact document and
// non-slides files, each with what to do instead. Export is a library and this
// command, never a button in the app: the writer stays out of every shell.
//
@@ -54,7 +55,7 @@ process.on('warning', (w) => {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const USAGE = `usage:
bento convert <deck.pptx> [-o out.bento.html] [--shell path | --offline] [--report r.json]
- bento convert <deck.bento.html|doc.json> --to pptx [-o out.pptx] [--report r.json]`
+ bento convert <deck.bento.html|doc.json> --to pptx [-o out.pptx] [--states] [--report r.json]`
function die(msg, code = 1) {
process.stderr.write(`bento convert: ${msg}\n`)
@@ -64,13 +65,14 @@ function die(msg, code = 1) {
// --- arguments ---------------------------------------------------------------
const argv = process.argv.slice(2)
if (argv[0] === 'convert') argv.shift()
-const opts = { out: null, to: null, shell: null, offline: false, input: null, report: null }
+const opts = { out: null, to: null, shell: null, offline: false, input: null, report: null, states: false }
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
const val = () => (i + 1 < argv.length ? argv[++i] : die(`${a} needs a value\n${USAGE}`, 2))
if (a === '-o' || a === '--out') opts.out = val()
else if (a === '--to') opts.to = val()
else if (a === '--report') opts.report = val()
+ else if (a === '--states') opts.states = true
else if (a === '--shell') opts.shell = val()
else if (a === '--offline') opts.offline = true
else if (a === '-h' || a === '--help') { process.stdout.write(USAGE + '\n'); process.exit(0) }
@@ -115,7 +117,7 @@ function printReport(r) {
try {
if (exporting) {
- const res = await api.bentoToPptx(fs.readFileSync(opts.input, 'utf8'))
+ const res = await api.bentoToPptx(fs.readFileSync(opts.input, 'utf8'), { includeStates: opts.states })
const out = opts.out ?? opts.input.replace(/(\.bento)?\.(html?|json)$/i, '') + '.pptx'
fs.writeFileSync(out, res.bytes)
printReport(res.report)
diff --git a/convert/page/convert-page.ts b/convert/page/convert-page.ts
new file mode 100644
index 00000000..d535bf22
--- /dev/null
+++ b/convert/page/convert-page.ts
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento.page/convert — drop a file, choose what to make of it.
+//
+// A view over convert/src/pairs.ts: the page detects what was dropped, lists
+// every conversion the table offers for it (with the reason when one applies
+// but cannot run), and runs the chosen one. A new format is a new row in
+// that table, not a new page.
+//
+// Everything happens in this tab. Files are read with the File API, converted
+// by convert/src (the same code the `bento convert` CLI runs), and handed back
+// as Blobs. Nothing is uploaded, and the page's CSP (scripts/build-convert-page.mjs)
+// makes that a rule the BROWSER enforces: `connect-src 'self'`. The only
+// requests the page makes are the signed release manifest and the shell it
+// pins, and only for a conversion that builds a bento/slides deck.
+//
+// bento.page/import redirects here with ?from=pptx, so that its links (the
+// slides menu entry, the release announcement) keep working.
+
+import { detect, describe, optionsFor, nothingFor, LimitError, type Detected, type Conversion, type Env } from '../src/pairs.ts'
+import { fetchVerifiedShell, LIMITS } from '../src/api.ts'
+import { foldReport, type FidelityReport } from '../src/report.ts'
+import { loadDocJson } from './load-json.ts'
+import { rasteriseToPng } from './rasterise.ts'
+import { SAMPLE_DECK, SAMPLE_DECK_NAME } from './sample-deck.ts'
+
+const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T
+const input = $<HTMLInputElement>('file')
+const drop = $('drop')
+const status = $('status')
+const result = $('result')
+const choose = $('choose')
+const options = $('options')
+const convertBtn = $<HTMLButtonElement>('convert')
+
+const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!)
+// engine messages start lowercase because they are written to follow a colon
+const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
+const mb = (n: number) => `${Math.round(n / 1024 / 1024)} MB`
+
+$('limit').textContent = mb(LIMITS.inputBytes)
+
+// Arriving from bento.page/import: say what that page said.
+if (new URLSearchParams(location.search).get('from') === 'pptx') {
+ $('title').textContent = 'Open a PowerPoint deck in bento/slides'
+ $('lede').textContent = 'Turn a .pptx into a bento/slides deck: one HTML file that edits and presents itself in any browser, with nothing to install.'
+ $('drop-title').textContent = 'Drop a .pptx here, or choose one'
+}
+
+function say(text: string, kind: 'busy' | 'error' | 'idle' = 'busy') {
+ status.textContent = text
+ status.dataset.kind = kind
+ status.hidden = false
+}
+
+// A verified shell is fetched once per page load and reused. A refused shell
+// is forgotten, never retried into a fallback.
+let shell: Promise<{ version: string; html: string }> | null = null
+const env: Env = {
+ shell() {
+ say('Fetching the latest bento/slides and checking its signature…')
+ // Both requests go to THIS origin: the manifest by relative path, and the
+ // shell by re-rooting the signed URL's path here (deliver.ts `resolve`).
+ // That is what lets the CSP be `connect-src 'self'` with no exceptions.
+ shell ??= fetchVerifiedShell('/releases/slides/manifest.json', fetch,
+ (u) => new URL(new URL(u).pathname, location.href).href)
+ return shell
+ },
+ loadDocJson,
+ rasterise: rasteriseToPng,
+}
+
+let current: Detected | null = null
+let urls: string[] = []
+let busy = false
+
+function reset() {
+ for (const u of urls) URL.revokeObjectURL(u)
+ urls = []
+ result.hidden = true
+ result.innerHTML = ''
+ status.hidden = true
+}
+
+async function take(name: string, bytes: Uint8Array) {
+ if (busy) return
+ reset()
+ current = null
+ choose.hidden = true
+ if (bytes.length > LIMITS.inputBytes)
+ return say(`That file is ${mb(bytes.length)}. This page takes files up to ${mb(LIMITS.inputBytes)}.`, 'error')
+ const d = detect(name, bytes)
+ const info = describe(d)
+ $('source').hidden = false
+ $('source-title').textContent = info.title
+ $('source-meta').textContent = info.meta
+ const opts = optionsFor(d)
+ if (!opts.length) return say(nothingFor(d), 'error')
+ current = d
+ options.innerHTML = opts.map((o, i) => `
+ <label class="option${o.ok ? '' : ' off'}">
+ <input type="radio" name="to" value="${esc(o.conversion.id)}"${o.ok ? '' : ' disabled'}${o.ok && i === opts.findIndex((x) => x.ok) ? ' checked' : ''}>
+ <span><b>${esc(o.conversion.label)}</b>${esc(o.ok ? o.conversion.hint : o.why)}${o.ok ? (o.conversion.flags ?? []).filter((f) => f.applies(d)).map((f) => `
+ <span class="flag"><input type="checkbox" data-flag="${esc(o.conversion.id)}:${esc(f.id)}"> ${esc(f.label)}</span>`).join('') : ''}</span>
+ </label>`).join('')
+ choose.hidden = false
+ convertBtn.disabled = !opts.some((o) => o.ok)
+}
+
+async function run() {
+ if (!current || busy) return
+ const id = (options.querySelector('input[name=to]:checked') as HTMLInputElement | null)?.value
+ const c = optionsFor(current).find((o) => o.ok && o.conversion.id === id)?.conversion
+ if (!c) return
+ busy = true
+ convertBtn.disabled = true
+ reset()
+ try {
+ say(`Converting ${current.name}…`)
+ const flags: Record<string, boolean> = {}
+ for (const box of options.querySelectorAll<HTMLInputElement>(`input[data-flag^="${c.id}:"]`)) flags[box.dataset.flag!.split(':')[1]] = box.checked
+ const r = await c.run(current, env, flags)
+ status.hidden = true
+ show(c, r.fileName, r.mime, r.bytes, r.report, r.stats, r.meta)
+ } catch (err) {
+ if (c.network) shell = null
+ const msg = err instanceof LimitError
+ ? `This file was refused: ${err.message}.`
+ : /signature|pin|manifest|release server/i.test(String((err as Error)?.message))
+ ? `Could not verify the bento/slides release, so nothing was produced. ${cap((err as Error).message)}.`
+ : `This file could not be converted: ${(err as Error)?.message ?? String(err)}.`
+ say(msg, 'error')
+ } finally {
+ busy = false
+ convertBtn.disabled = false
+ }
+}
+
+// The report, in words a person can act on. Engine `detail` strings are
+// written for developers; codes listed here are said plainly instead, and
+// any code not listed falls back to the engine's own words, never silence.
+const PLAIN: Record<string, string> = {
+ 'table-not-yet': 'Tables are not converted yet. A placeholder box marks where each one was.',
+ 'chart-not-yet': 'Charts are not converted yet. A placeholder box marks where each one was.',
+ 'text-needs-refit': 'Some text boxes may need resizing, because this device’s fonts differ slightly from the original’s.',
+ 'font-substituted': 'Some fonts were not included in the file, so a similar font is used instead.',
+ 'paragraph-spacing-dropped': 'Extra space between paragraphs is not kept.',
+ 'run-formatting-flattened': 'Mixed formatting inside a text box (different colours or sizes) is simplified.',
+ 'bullet-flattened': 'Bullet styles are simplified.',
+ 'auto-number-frozen': 'Numbered lists keep their numbers, but no longer renumber automatically.',
+ 'field-frozen': 'Slide numbers and dates are kept as plain text.',
+ 'image-crop-dropped': 'Cropped pictures show in full.',
+ 'image-external-dropped': 'Pictures linked from the web are left out. This page never downloads them.',
+ 'effect-dropped': 'Some visual effects (glows, reflections, 3-D) are left out.',
+ 'flip-dropped': 'Flipped shapes and pictures appear unflipped.',
+ 'picture-fill-dropped': 'Shapes filled with a picture are left empty.',
+ 'background-image-dropped': 'Slide background pictures are left out.',
+ 'nested-group-flattened': 'Groups inside groups are flattened into one group.',
+ 'state-slides-omitted': 'Interactive states (slides reached by clicking) are left out. Links to them go to the slide they belong to.',
+ 'morph-not-exported': 'Morph transitions become plain cuts.',
+ 'presentation-effects-static': 'Animations and reveal steps show their final frame.',
+ 'hover-static': 'Hover effects are static: everything on the slide shows.',
+ 'element-unsupported': 'Some elements have no PowerPoint equivalent yet and are left out.',
+ 'maths-as-source': 'Formulas appear as their LaTeX source, because PowerPoint does not typeset them.',
+ 'fonts-not-embedded': 'The deck’s own fonts are not included. Install them where the PowerPoint file is opened, or PowerPoint uses another font.',
+ 'svg-no-raster-fallback': 'Vector artwork shows in PowerPoint 2019 and later, and in PowerPoint for the web; PowerPoint 2016 shows an empty frame.',
+ 'media-dropped': 'Audio and video do not play in the PowerPoint file. A video’s poster picture stands in.',
+ 'text-field-pad-lost': 'Page numbers update in PowerPoint, but lose their leading zeros.',
+ 'multiple-shadows-simplified': 'Where a shape has several shadows, only the first is kept.',
+ 'table-radius-dropped': 'Rounded table corners become square.',
+ 'line-tip-approximated': 'Some line ends are drawn with the closest PowerPoint arrowhead.',
+ 'value-removed': 'Values the bento/slides format does not allow were removed.',
+ 'text-field-frozen': 'Some page numbers and other fields are fixed text in PowerPoint, so they won’t update if you add or move slides.',
+ 'code-colours-flattened': 'Code is editable text in one colour; its syntax highlighting is not carried.',
+ 'embed-static': 'Embedded documents show as a picture of what they show; their live content stays in bento.',
+ 'embed-no-view': 'An embedded web page with nothing to show is left out.',
+ 'path-approximated': 'A drawn shape could not be read in full, so it stops where the problem began.',
+ 'image-fit-approximated': 'Some pictures are stretched to their frame, where bento crops them to fit.',
+ 'missing-image': 'Some pictures could not be included (an unsupported format, or a missing file).',
+ 'states-as-hidden-slides': 'Interactive states are hidden slides, right after the slide they belong to. Links still lead to them, and the show skips them.',
+ 'image-converted-png': 'WebP and similar pictures were converted to PNG for PowerPoint. They look the same; the file is a little larger.',
+ 'text-height-provisional': 'Some text boxes had no height, so they start one line tall. Select one in bento/slides and use Fit height to text.',
+}
+
+function show(c: Conversion, name: string, mime: string, bytes: Uint8Array, report: FidelityReport,
+ stats: Array<{ label: string; value: number }>, meta?: string) {
+ const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: mime }))
+ const rep = URL.createObjectURL(new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' }))
+ urls.push(url, rep)
+ const rows = foldReport(report).map((e) => `
+ <li class="${esc(e.verdict)}"><span class="tag">${e.verdict === 'dropped' ? 'Not carried' : 'Approximated'}</span>${esc(PLAIN[e.code] ?? cap(e.detail))}${e.where ? ` <span class="where">· ${esc(e.where)}</span>` : ''}${e.count > 1 ? ` <span class="n">×${e.count}</span>` : ''}</li>`).join('')
+ const toPptx = c.id.endsWith('-to-pptx')
+ result.innerHTML = `
+ <h2>${esc(name)}</h2>
+ ${meta ? `<p class="meta">${esc(meta)}</p>` : ''}
+ <div class="stats">${stats.map((s) => `<div><strong>${s.value}</strong><span>${esc(s.label)}</span></div>`).join('')}</div>
+ <div class="actions">
+ <a class="btn" id="download" href="${url}" download="${esc(name)}">Download ${esc(name)}</a>
+ <a id="report-json" href="${rep}" download="${esc(name.replace(/\.[^.]+$/, ''))}.report.json">Save the list as JSON</a>
+ </div>
+ ${rows
+ ? `<p class="meta">These did not come across exactly, so check them before you share it:</p><ul class="report">${rows}</ul>`
+ : '<p class="meta">Everything the converter looked at came across.</p>'}
+ ${toPptx ? `<p class="nudge"><strong>Sharing with someone?</strong> You can send the .bento.html itself.
+ It opens in any browser, with nothing to install, and keeps its animations, morphs and interactive states, which PowerPoint does not.</p>`
+ : '<p class="meta">Open it in any browser to edit and present. Save once in bento/slides and it gets its file thumbnail.</p>'}`
+ result.hidden = false
+}
+
+input.addEventListener('change', async () => {
+ const f = input.files?.[0]
+ input.value = ''
+ if (f) await take(f.name, new Uint8Array(await f.arrayBuffer()))
+})
+for (const ev of ['dragenter', 'dragover']) drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over') })
+for (const ev of ['dragleave', 'drop']) drop.addEventListener(ev, () => drop.classList.remove('over'))
+drop.addEventListener('drop', async (e) => {
+ e.preventDefault()
+ const files = (e as DragEvent).dataTransfer?.files
+ if (!files?.length) return
+ if (files.length > 1) return say('Drop one file at a time.', 'error')
+ await take(files[0].name, new Uint8Array(await files[0].arrayBuffer()))
+})
+// A file dropped anywhere else must not navigate the tab away from the page.
+window.addEventListener('dragover', (e) => e.preventDefault())
+window.addEventListener('drop', (e) => e.preventDefault())
+$('sample').addEventListener('click', () => void take(SAMPLE_DECK_NAME, new TextEncoder().encode(SAMPLE_DECK)))
+convertBtn.addEventListener('click', () => void run())
diff --git a/convert/page/image-size.ts b/convert/page/image-size.ts
new file mode 100644
index 00000000..9318cb89
--- /dev/null
+++ b/convert/page/image-size.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// An image's width and height, read from its header bytes, BEFORE anything
+// decodes it. rasterise.ts refuses a picture whose header declares more than
+// its pixel cap, so a hostile file can't make the browser's decoder allocate
+// a huge bitmap. A header this cannot read is refused too: nothing unknown
+// reaches the decoder.
+//
+// DOM-free and dependency-free; scripts/test-convert/rasterise.ts drives it.
+
+export interface Size { width: number; height: number; format: string }
+
+const u16le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8)
+const u16be = (b: Uint8Array, o: number) => (b[o] << 8) | b[o + 1]
+const u24le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16)
+const u32le = (b: Uint8Array, o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0
+const u32be = (b: Uint8Array, o: number) => ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0
+const i32le = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)
+const ascii = (b: Uint8Array, o: number, n: number) => String.fromCharCode(...b.subarray(o, o + n))
+
+/** The header bytes of a base64 data: URI (enough for every format here). */
+export function headerBytes(dataUri: string, max = 64 * 1024): Uint8Array | null {
+ const m = /^data:[^;,]+;base64,/i.exec(dataUri)
+ if (!m) return null
+ const b64 = dataUri.slice(m[0].length, m[0].length + Math.ceil((max * 4) / 3 / 4) * 4)
+ try {
+ const bin = atob(b64)
+ const out = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
+ return out
+ } catch { return null }
+}
+
+/** Width and height from a header, or null when the format or header is not
+ * one this reads (and so must not be decoded). */
+export function imageSize(b: Uint8Array): Size | null {
+ // PNG: signature, then IHDR's width and height (big-endian)
+ if (b.length >= 24 && b[0] === 0x89 && ascii(b, 1, 3) === 'PNG' && ascii(b, 12, 4) === 'IHDR')
+ return { width: u32be(b, 16), height: u32be(b, 20), format: 'png' }
+ // WebP: RIFF....WEBP, then a VP8 / VP8L / VP8X chunk
+ if (b.length >= 30 && ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 4) === 'WEBP') {
+ const chunk = ascii(b, 12, 4)
+ if (chunk === 'VP8 ' && b[23] === 0x9d && b[24] === 0x01 && b[25] === 0x2a)
+ return { width: u16le(b, 26) & 0x3fff, height: u16le(b, 28) & 0x3fff, format: 'webp' }
+ if (chunk === 'VP8L' && b[20] === 0x2f) {
+ const b1 = b[22], b2 = b[23], b3 = b[24]
+ return { width: 1 + (b[21] | ((b1 & 0x3f) << 8)), height: 1 + ((b1 >> 6) | (b2 << 2) | ((b3 & 0x0f) << 10)), format: 'webp' }
+ }
+ if (chunk === 'VP8X') return { width: 1 + u24le(b, 24), height: 1 + u24le(b, 27), format: 'webp' }
+ return null
+ }
+ // BMP: 'BM', then BITMAPINFOHEADER width/height (height may be negative)
+ if (b.length >= 26 && b[0] === 0x42 && b[1] === 0x4d)
+ return { width: Math.abs(i32le(b, 18)), height: Math.abs(i32le(b, 22)), format: 'bmp' }
+ // TIFF: byte order, 42, then the first IFD's ImageWidth (256) / ImageLength (257)
+ if (b.length >= 8 && ((b[0] === 0x49 && b[1] === 0x49 && b[2] === 42) || (b[0] === 0x4d && b[1] === 0x4d && b[3] === 42))) {
+ const le = b[0] === 0x49
+ const r16 = (o: number) => (le ? u16le(b, o) : u16be(b, o))
+ const r32 = (o: number) => (le ? u32le(b, o) : u32be(b, o))
+ const ifd = r32(4)
+ if (ifd + 2 > b.length) return null
+ let w = 0, h = 0
+ const n = r16(ifd)
+ for (let k = 0; k < n; k++) {
+ const e = ifd + 2 + k * 12
+ if (e + 12 > b.length) return null
+ const tag = r16(e), type = r16(e + 2)
+ const val = type === 3 ? r16(e + 8) : type === 4 ? r32(e + 8) : 0
+ if (tag === 256) w = val
+ if (tag === 257) h = val
+ }
+ return w && h ? { width: w, height: h, format: 'tiff' } : null
+ }
+ // AVIF / HEIF: an 'ispe' (image spatial extents) property holds the size
+ if (b.length >= 12 && ascii(b, 4, 4) === 'ftyp') {
+ for (let i = 8; i + 16 <= b.length; i++) {
+ if (b[i] === 0x69 && ascii(b, i, 4) === 'ispe') return { width: u32be(b, i + 8), height: u32be(b, i + 12), format: 'avif' }
+ }
+ return null
+ }
+ return null
+}
diff --git a/convert/page/import-page.ts b/convert/page/import-page.ts
deleted file mode 100644
index f73e590e..00000000
--- a/convert/page/import-page.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Copyright (c) 2026 The Bento authors
-//
-// bento.page/import — drop a .pptx, get a .bento.html back.
-//
-// Everything happens in this tab. The file is read with the File API, converted
-// by convert/src/api.ts (the same composition the CLI runs), and handed back as
-// a Blob. Nothing is uploaded, and the page's CSP (scripts/build-import-page.mjs)
-// makes that a property the BROWSER enforces rather than one this code promises:
-// `connect-src 'self'` — the only requests this page can make are to bento.page,
-// and the only two it does make are the signed release manifest and the shell
-// that manifest pins.
-//
-// The shell is verified before anything is written into it (signature over the
-// pin, pin over the bytes — deliver.ts). A shell that fails is refused and the
-// visitor is told so; there is no download from an unverified shell.
-
-import { fetchVerifiedShell, pptxToBento, LimitError, LIMITS } from '../src/api.ts'
-import type { FidelityReport } from '../src/report.ts'
-
-const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T
-const drop = $<HTMLElement>('#drop')
-const input = $<HTMLInputElement>('#file')
-const status = $<HTMLElement>('#status')
-const result = $<HTMLElement>('#result')
-
-const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!)
-// engine messages start lowercase because they are written to follow a colon
-const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
-const mb = (n: number) => `${Math.round(n / 1024 / 1024)} MB`
-
-$<HTMLElement>('#limit').textContent = mb(LIMITS.inputBytes)
-
-function say(text: string, kind: 'busy' | 'error' | 'idle' = 'busy') {
- status.textContent = text
- status.dataset.kind = kind
- status.hidden = false
-}
-
-// A verified shell is fetched once per page load and reused: converting three
-// decks does not ask the release server three times.
-let shell: Promise<{ version: string; html: string }> | null = null
-
-async function convert(file: File) {
- result.hidden = true
- result.innerHTML = ''
- if (!/\.pptx$/i.test(file.name)) return say('That is not a .pptx file. Choose a PowerPoint presentation.', 'error')
- if (file.size > LIMITS.inputBytes)
- return say(`That file is ${mb(file.size)}. This page takes presentations up to ${mb(LIMITS.inputBytes)}.`, 'error')
- try {
- say('Fetching the latest bento/slides and checking its signature…')
- // Both requests go to THIS origin: the manifest by relative path, and the
- // shell by re-rooting the signed URL's path here (deliver.ts `resolve`).
- // That is what lets the CSP be `connect-src 'self'` with no exceptions.
- shell ??= fetchVerifiedShell('/releases/slides/manifest.json', fetch,
- (u) => new URL(new URL(u).pathname, location.href).href)
- const s = await shell
- say(`Converting ${file.name}…`)
- const res = await pptxToBento(new Uint8Array(await file.arrayBuffer()), s.html)
- const name = file.name.replace(/\.pptx$/i, '') + '.bento.html'
- const url = URL.createObjectURL(new Blob([res.html], { type: 'text/html' }))
- status.hidden = true
- showResult(name, url, res.slides, s.version, res.report, res.gated.length)
- } catch (err) {
- // A refused shell must stay refused for this page load: never retry into a
- // fallback, and never keep a rejected promise that later looks settled.
- shell = null
- const msg = err instanceof LimitError
- ? `This file was refused: ${err.message}.`
- : /signature|pin|manifest|release server/i.test(String((err as Error)?.message))
- ? `Could not verify the bento/slides release, so nothing was produced. ${cap((err as Error).message)}.`
- : `This file could not be converted: ${(err as Error)?.message ?? String(err)}.`
- say(msg, 'error')
- }
-}
-
-// The report, in words a visitor can act on. The engine's `detail` strings are
-// written for developers ("spcBef/spcAft have no bento equivalent"); the brief
-// for this page is to say what did not come across PLAINLY. Codes not listed
-// here fall back to the engine's own detail rather than to silence.
-const PLAIN: Record<string, string> = {
- 'table-not-yet': 'Tables are not converted yet. A placeholder box marks where each one was.',
- 'chart-not-yet': 'Charts are not converted yet. A placeholder box marks where each one was.',
- 'text-needs-refit': 'Some text boxes may need resizing, because this device’s fonts differ slightly from the original’s.',
- 'font-substituted': 'Some fonts were not included in the file, so a similar font is used instead.',
- 'paragraph-spacing-dropped': 'Extra space between paragraphs is not kept.',
- 'run-formatting-flattened': 'Mixed formatting inside a text box (different colours or sizes) is simplified.',
- 'bullet-flattened': 'Bullet styles are simplified.',
- 'auto-number-frozen': 'Numbered lists keep their numbers, but no longer renumber automatically.',
- 'field-frozen': 'Slide numbers and dates are kept as plain text.',
- 'image-crop-dropped': 'Cropped pictures show in full.',
- 'image-external-dropped': 'Pictures linked from the web are left out. This page never downloads them.',
- 'effect-dropped': 'Some visual effects (glows, reflections, 3-D) are left out.',
- 'flip-dropped': 'Flipped shapes and pictures appear unflipped.',
- 'picture-fill-dropped': 'Shapes filled with a picture are left empty.',
- 'background-image-dropped': 'Slide background pictures are left out.',
- 'nested-group-flattened': 'Groups inside groups are flattened into one group.',
-}
-
-function showResult(name: string, url: string, slides: number, version: string, r: FidelityReport, gated: number) {
- // One line per KIND of loss. The engine folds findings per (code, where) —
- // right for a developer locating a problem, noise for a visitor, who would
- // read "extra space between paragraphs is not kept" once per text box.
- const byCode = new Map<string, { verdict: string; code: string; detail: string; count: number }>()
- for (const e of r.entries) {
- if (e.verdict === 'carried') continue
- const seen = byCode.get(e.code)
- if (seen) seen.count += e.count
- else byCode.set(e.code, { verdict: e.verdict, code: e.code, detail: e.detail, count: e.count })
- }
- // not-carried first: those are the ones worth checking before anything else
- const lossy = [...byCode.values()].sort((a, b) => (a.verdict === b.verdict ? 0 : a.verdict === 'dropped' ? -1 : 1))
- const rows = lossy.map((e) => `
- <li class="${e.verdict}"><span class="tag">${e.verdict === 'dropped' ? 'Not carried' : 'Approximated'}</span>
- ${esc(PLAIN[e.code] ?? e.detail)}${e.count > 1 ? ` <span class="n">×${e.count}</span>` : ''}</li>`).join('')
- result.innerHTML = `
- <h2>${esc(name)}</h2>
- <p class="meta">${slides} slide${slides === 1 ? '' : 's'} · built on bento/slides ${esc(version)}, signature verified</p>
- ${lossy.length
- ? `<p>Most of your deck came across. These did not come across exactly, so check them after you open it:</p><ul class="report">${rows}</ul>`
- : '<p>Everything the converter looked at came across.</p>'}
- ${gated ? `<p class="meta">${gated} value${gated === 1 ? '' : 's'} the bento/slides format does not allow were removed.</p>` : ''}
- <a class="btn" href="${url}" download="${esc(name)}">Download ${esc(name)}</a>
- <p class="meta">Open it in any browser to edit and present. Save once in bento/slides and it gets its file thumbnail.</p>`
- result.hidden = false
-}
-
-input.addEventListener('change', () => { if (input.files?.[0]) void convert(input.files[0]) })
-drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over') })
-drop.addEventListener('dragleave', () => drop.classList.remove('over'))
-drop.addEventListener('drop', (e) => {
- e.preventDefault()
- drop.classList.remove('over')
- const f = e.dataTransfer?.files?.[0]
- if (f) void convert(f)
-})
diff --git a/convert/page/load-json.ts b/convert/page/load-json.ts
new file mode 100644
index 00000000..a38c7bad
--- /dev/null
+++ b/convert/page/load-json.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Document JSON → a full, gated bento/slides document, for the convert page.
+//
+// slides' own entry for this (compactload.ts parseDocInputReport) also MEASURES
+// text: a compact document may leave a text box's height out, and slides fits
+// it with its renderer and the deck's fonts. That cannot work here. The
+// renderer writes inline styles, which this page's hashed CSP blocks, and the
+// deck's fonts are not loaded on this page. It would also add ~300 KB to the
+// page. So this is the same expansion and the same gate, step for step, with
+// the measuring left out, and the boxes that needed it are REPORTED: they keep
+// a provisional one-line height until "Fit height to text" in the editor.
+
+import { expandDocWithStats, isCompact } from '../../slides/src/compact.ts'
+import { sanitizeDoc } from '../../slides/src/restoregate.ts'
+import { sanitizeSlide, withDropReport, withPathSegment, type Dropped } from '../../slides/src/untrusted.ts'
+import { parseDoc, type BentoDoc, type Slide } from '../../slides/src/model.ts'
+
+export interface Loaded {
+ doc: BentoDoc
+ dropped: Array<{ path: string; reason: string }>
+ /** text boxes left at a provisional height: their slide's id */
+ provisional: string[]
+}
+
+export function loadDocJson(json: string): Loaded | null {
+ let raw: unknown
+ try { raw = JSON.parse(json) } catch { return null }
+ if (!isCompact(raw)) {
+ const base = parseDoc(json)
+ if (!base) return null
+ const gated = sanitizeDoc(base as unknown as Record<string, unknown>)
+ return gated ? { doc: gated.doc, dropped: gated.dropped, provisional: [] } : null
+ }
+ const { doc: expanded, stats } = expandDocWithStats(raw)
+ const ex = expanded as unknown as Record<string, unknown>
+ const { result: slides, dropped } = withDropReport(() =>
+ ((ex.slides ?? []) as unknown[])
+ .map((s, i) => withPathSegment('slides', () => withPathSegment(String(i), () => sanitizeSlide(s))))
+ .filter((s): s is Slide => s !== null))
+ ex.slides = slides
+ const base = parseDoc(JSON.stringify(ex))
+ if (!base) return null
+ const gated = sanitizeDoc(base as unknown as Record<string, unknown>)
+ if (!gated) return null
+ const all: Dropped[] = [...dropped, ...gated.dropped, ...stats.notes.map((n) => ({ path: n.path, reason: n.reason } as Dropped))]
+ const provisional = stats.autoHeight.map((a) => a.slide)
+ return { doc: gated.doc, dropped: all, provisional }
+}
diff --git a/convert/page/rasterise.ts b/convert/page/rasterise.ts
new file mode 100644
index 00000000..74edf592
--- /dev/null
+++ b/convert/page/rasterise.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// A picture PowerPoint cannot take (WebP, AVIF, BMP, TIFF) → a PNG data: URI,
+// with the browser's own decoder and a canvas. The writer has no DOM, so the
+// page passes this in (ExportOpts.rasterise). Same pixels, PNG-encoded.
+//
+// Guards, in order:
+// 1. data: URIs only (the CSP's img-src allows data:, and nothing is fetched);
+// 2. the size is read from the header BEFORE anything decodes it
+// (image-size.ts), and a header declaring more than 40 megapixels, or one
+// that cannot be read, is refused: the browser's decoder never sees it;
+// 3. after decoding, the real size is checked again, before the canvas.
+// A refusal returns null, and the writer reports the picture dropped.
+
+import { headerBytes, imageSize } from './image-size.ts'
+
+export const MAX_PIXELS = 40_000_000
+
+/** Whether a picture may be decoded at all: its header must be readable and
+ * declare at most MAX_PIXELS. Exported for the rig. */
+export function mayDecode(dataUri: string): boolean {
+ if (!/^data:image\//i.test(dataUri)) return false
+ const head = headerBytes(dataUri)
+ const size = head && imageSize(head)
+ return !!size && size.width > 0 && size.height > 0 && size.width * size.height <= MAX_PIXELS
+}
+
+export async function rasteriseToPng(dataUri: string): Promise<string | null> {
+ if (!mayDecode(dataUri)) return null
+ const img = new Image()
+ img.decoding = 'async'
+ img.src = dataUri
+ try { await img.decode() } catch { return null }
+ const w = img.naturalWidth
+ const h = img.naturalHeight
+ if (!w || !h || w * h > MAX_PIXELS) return null
+ const canvas = document.createElement('canvas')
+ canvas.width = w
+ canvas.height = h
+ const g = canvas.getContext('2d')
+ if (!g) return null
+ g.drawImage(img, 0, 0)
+ const png = canvas.toDataURL('image/png')
+ return png.startsWith('data:image/png') ? png : null
+}
diff --git a/convert/page/sample-deck.ts b/convert/page/sample-deck.ts
new file mode 100644
index 00000000..0328f0b6
--- /dev/null
+++ b/convert/page/sample-deck.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The sample deck behind "Try it with a sample deck": three small slides that
+// exercise text, shapes, a table, a chart, an SVG, links, page fields and
+// speaker notes. Bento-authored content, first drawn for an earlier
+// standalone converter demo; kept as data, so it converts through exactly the
+// path a dropped file takes.
+
+export const SAMPLE_DECK_NAME = 'sample-deck.json'
+export const SAMPLE_DECK = "{\"format\": \"bento/slides\", \"version\": 1, \"docId\": \"bento-convert-demo-sample\", \"title\": \"A little more portable\", \"modified\": \"2026-09-21T00:00:00Z\", \"size\": {\"width\": 1280, \"height\": 720}, \"theme\": {\"background\": \"#F7F8F2\", \"color\": \"#244835\", \"accent\": \"#40835B\", \"fontFamily\": \"Arial\"}, \"assets\": {}, \"slides\": [{\"id\": \"intro\", \"background\": \"#F7F8F2\", \"transition\": \"morph\", \"elements\": [{\"id\": \"t-mv2r14tn-0gb4c\", \"type\": \"text\", \"x\": 70, \"y\": 60, \"w\": 1140, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"Your ideas can travel.\", \"fontSize\": 48, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 650, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"t-mv2r14tn-1r9md\", \"type\": \"text\", \"x\": 72, \"y\": 167, \"w\": 820, \"h\": 100, \"rotation\": 0, \"opacity\": 1, \"html\": \"One bento/slides deck.<br>One editable PowerPoint copy.\", \"fontSize\": 27, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 400, \"color\": \"#627561\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"green-card\", \"type\": \"shape\", \"shape\": \"rect\", \"x\": 72, \"y\": 330, \"w\": 340, \"h\": 220, \"rotation\": 0, \"opacity\": 1, \"fill\": \"#DDE9D1\", \"stroke\": \"transparent\", \"strokeWidth\": 0, \"radius\": 18}, {\"id\": \"cream-card\", \"type\": \"shape\", \"shape\": \"rect\", \"x\": 442, \"y\": 330, \"w\": 340, \"h\": 220, \"rotation\": 0, \"opacity\": 1, \"fill\": \"#F0E4CE\", \"stroke\": \"transparent\", \"strokeWidth\": 0, \"radius\": 18}, {\"id\": \"pink-card\", \"type\": \"shape\", \"shape\": \"rect\", \"x\": 812, \"y\": 330, \"w\": 340, \"h\": 220, \"rotation\": 0, \"opacity\": 1, \"fill\": \"#F0DACE\", \"stroke\": \"transparent\", \"strokeWidth\": 0, \"radius\": 18}, {\"id\": \"t-mv2r14tn-5xuvj\", \"type\": \"text\", \"x\": 98, \"y\": 400, \"w\": 292, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"Text you can edit\", \"fontSize\": 29, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 600, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"t-mv2r14tn-6qkuf\", \"type\": \"text\", \"x\": 468, \"y\": 400, \"w\": 292, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"Shapes you can move\", \"fontSize\": 29, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 600, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"t-mv2r14tn-76zxh\", \"type\": \"text\", \"x\": 838, \"y\": 400, \"w\": 292, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"Notes that travel\", \"fontSize\": 29, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 600, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"t-mv2r14tn-8kxv5\", \"type\": \"text\", \"x\": 72, \"y\": 631, \"w\": 1060, \"h\": 35, \"rotation\": 0, \"opacity\": 1, \"html\": \"bento/convert {{page}} / {{pages}}\", \"fontSize\": 17, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 400, \"color\": \"#627561\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25, \"link\": \"data\"}], \"notes\": \"Everything on this slide is editable in PowerPoint. The original bento deck keeps its motion.\"}, {\"id\": \"data\", \"background\": \"#F7F8F2\", \"transition\": \"none\", \"elements\": [{\"id\": \"t-mv2r14tn-aq0ox\", \"type\": \"text\", \"x\": 70, \"y\": 60, \"w\": 1140, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"The numbers stay useful.\", \"fontSize\": 48, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 650, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"tbl-mv2r14to-bqdn1\", \"type\": \"table\", \"x\": 72, \"y\": 215, \"w\": 475, \"h\": 320, \"rotation\": 0, \"opacity\": 1, \"header\": true, \"columns\": [{\"w\": 1}, {\"w\": 1}], \"rows\": [{\"cells\": [{\"html\": \"Quarter\"}, {\"html\": \"Projects\"}]}, {\"cells\": [{\"html\": \"Q1\"}, {\"html\": \"12\"}]}, {\"cells\": [{\"html\": \"Q2\"}, {\"html\": \"20\"}]}, {\"cells\": [{\"html\": \"Q3\"}, {\"html\": \"28\"}]}], \"style\": {\"headerBg\": \"#1E2A3A\", \"headerColor\": \"#FFFFFF\", \"zebra\": \"rgba(30,42,58,0.05)\", \"borderColor\": \"rgba(30,42,58,0.14)\", \"borderWidth\": 1, \"cellPadX\": 16, \"cellPadY\": 11, \"fontSize\": 18, \"color\": \"#1E2A3A\", \"radius\": 10}}, {\"id\": \"c-mv2r14to-cqphz\", \"type\": \"chart\", \"x\": 625, \"y\": 215, \"w\": 520, \"h\": 320, \"rotation\": 0, \"opacity\": 1, \"preset\": \"bar\", \"option\": {\"xAxis\": {\"type\": \"category\", \"data\": [\"Q1\", \"Q2\", \"Q3\"]}, \"yAxis\": {\"type\": \"value\"}, \"color\": [\"#40835B\"], \"series\": [{\"type\": \"bar\", \"name\": \"Projects\", \"data\": [12, 20, 28]}]}}, {\"id\": \"t-mv2r14to-dx986\", \"type\": \"text\", \"x\": 72, \"y\": 612, \"w\": 1100, \"h\": 50, \"rotation\": 0, \"opacity\": 1, \"html\": \"Illustrative data · editable cells and chart values\", \"fontSize\": 20, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 400, \"color\": \"#627561\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}], \"notes\": \"Illustrative sample data. Both the table and chart are native PowerPoint objects.\"}, {\"id\": \"art\", \"background\": \"#F7F8F2\", \"transition\": \"none\", \"elements\": [{\"id\": \"t-mv2r14to-fq9kr\", \"type\": \"text\", \"x\": 70, \"y\": 60, \"w\": 1140, \"h\": 85, \"rotation\": 0, \"opacity\": 1, \"html\": \"Some things become still.\", \"fontSize\": 48, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 650, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}, {\"id\": \"artwork\", \"type\": \"svg\", \"x\": 72, \"y\": 225, \"w\": 470, \"h\": 275, \"rotation\": 0, \"opacity\": 1, \"markup\": \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" width=\\\"470\\\" height=\\\"275\\\" viewBox=\\\"0 0 470 275\\\"><rect width=\\\"470\\\" height=\\\"275\\\" rx=\\\"18\\\" fill=\\\"#DFEAD4\\\"/><circle cx=\\\"180\\\" cy=\\\"137\\\" r=\\\"83\\\" fill=\\\"#568663\\\"/><circle cx=\\\"290\\\" cy=\\\"137\\\" r=\\\"83\\\" fill=\\\"#D5AE73\\\" fill-opacity=\\\"0.8\\\"/></svg>\"}, {\"id\": \"t-mv2r14to-g0arg\", \"type\": \"text\", \"x\": 622, \"y\": 230, \"w\": 520, \"h\": 230, \"rotation\": 0, \"opacity\": 1, \"html\": \"Artwork travels as a graphic.<br><br>Animations and interactivity<br>stay in the original bento file.\", \"fontSize\": 30, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 400, \"color\": \"#244835\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25, \"fx\": {\"enter\": \"fade-up\"}}, {\"id\": \"t-mv2r14to-hfl1l\", \"type\": \"text\", \"x\": 72, \"y\": 612, \"w\": 1100, \"h\": 50, \"rotation\": 0, \"opacity\": 1, \"html\": \"A copy for the next conversation. Keep the original for the full experience.\", \"fontSize\": 20, \"fontFamily\": \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\", \"fontWeight\": 400, \"color\": \"#627561\", \"align\": \"center\", \"valign\": \"middle\", \"lineHeight\": 1.25}], \"notes\": \"The SVG is a static graphic. The original file is the home for motion and interactive states.\"}]}"
diff --git a/convert/src/export.ts b/convert/src/export.ts
index ded9381b..2ab45932 100644
--- a/convert/src/export.ts
+++ b/convert/src/export.ts
@@ -18,6 +18,7 @@ export interface ExportResult {
bytes: Uint8Array
title: string
report: FidelityReport
+ stats: { slides: number; editable: number; pictures: number }
}
/**
@@ -26,7 +27,15 @@ export interface ExportResult {
* takes no passwords), a raw compact document (an authoring shape the app
* expands on load), and anything that is not bento/slides.
*/
-export async function bentoToPptx(input: string): Promise<ExportResult> {
+export interface ExportOptions {
+ /** a picture PowerPoint cannot take (WebP, …) → PNG data: URI, or null.
+ * Needs a browser; see ExportOpts.rasterise in pptx-write/index.ts. */
+ rasterise?: (dataUri: string) => Promise<string | null>
+ /** export interactive states as hidden slides (ExportOpts.includeStates) */
+ includeStates?: boolean
+}
+
+export async function bentoToPptx(input: string, options: ExportOptions = {}): Promise<ExportResult> {
const raw = readInput(input)
if (raw?.format === 'bento/enc')
throw new Error('this deck is password-protected — open it in Bento and use Save ▾ Save a copy without a password first')
@@ -34,7 +43,7 @@ export async function bentoToPptx(input: string): Promise<ExportResult> {
throw new Error('this is a compact authoring document — open it in Bento once and save it, then export the saved file')
if (raw?.format !== 'bento/slides')
throw new Error(`this is a ${String(raw?.format ?? 'non-Bento')} file; only bento/slides decks export to PowerPoint`)
- return docToPptx(JSON.stringify(raw))
+ return docToPptx(JSON.stringify(raw), options)
}
/**
@@ -42,17 +51,19 @@ export async function bentoToPptx(input: string): Promise<ExportResult> {
* slides' own parseDoc first, so the writer only ever sees a document the app
* itself would open.
*/
-export async function docToPptx(json: string): Promise<ExportResult> {
+export async function docToPptx(json: string, options: ExportOptions = {}): Promise<ExportResult> {
const doc = parseDoc(json)
if (!doc) throw new Error('the deck did not pass the format check')
// The deck's chart palette: what the app would give a new chart. The writer
// cannot derive it (it never imports an app), so it is passed in here.
// doc.theme.chartPalette still wins inside the writer when the deck has one.
- const { bytes, report } = await exportPptx(doc as unknown as ExportDoc, {
+ const { bytes, report, stats } = await exportPptx(doc as unknown as ExportDoc, {
chartPalette: deriveChartPalette(doc.theme.accent),
formulasIn: countFormulas,
+ ...(options.rasterise ? { rasterise: options.rasterise } : {}),
+ ...(options.includeStates ? { includeStates: true } : {}),
})
- return { bytes, title: doc.title, report }
+ return { bytes, title: doc.title, report, stats }
}
/** The document in a .bento.html, or document JSON as given. JSON is
diff --git a/convert/src/pairs.ts b/convert/src/pairs.ts
new file mode 100644
index 00000000..00e504ed
--- /dev/null
+++ b/convert/src/pairs.ts
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The conversion table: what a dropped file is, and every output the engine
+// can make from it. bento.page/convert is a view over this table and nothing
+// else, so a new format is a new ROW here, never a new page. A converter that
+// produces Markdown from a bento/spaces file, say, is one more entry in
+// CONVERSIONS with its own `accepts` and `run`.
+//
+// DOM-free, like the rest of convert/src. What only a browser can do (measure
+// text while expanding a compact document) comes in through `Env`, from the
+// page that hosts it.
+
+import { pptxToBento, LimitError } from './api.ts'
+import { bentoToPptx } from './export.ts'
+import { extractDoc, spliceIntoShell } from './deliver.ts'
+import type { FidelityReport } from './report.ts'
+import type { BentoDoc } from '../../slides/src/model.ts'
+
+// --- what was dropped --------------------------------------------------------
+
+/** A Bento document, from a .bento.html or as document JSON. */
+export interface BentoInput {
+ kind: 'bento'
+ name: string
+ /** where the document came from: a saved file, or JSON as given */
+ source: 'html' | 'json'
+ /** doc.format: 'bento/slides', 'bento/spaces', 'bento/dash', 'bento/type', 'bento/enc' */
+ format: string
+ /** the input text, as read */
+ text: string
+ /** the parsed document (untrusted: only read for detection and summary) */
+ doc: Record<string, unknown>
+ compact: boolean
+}
+
+export interface PptxInput {
+ kind: 'pptx'
+ name: string
+ bytes: Uint8Array
+}
+
+export interface UnknownInput {
+ kind: 'unknown'
+ name: string
+ /** why it was not recognised, in words for the person */
+ reason: string
+}
+
+export type Detected = BentoInput | PptxInput | UnknownInput
+
+const ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]
+const isZip = (b: Uint8Array) => ZIP_MAGIC.every((v, i) => b[i] === v)
+
+/** What a file is. Recognised by content, with the name only as a hint. */
+export function detect(name: string, bytes: Uint8Array): Detected {
+ if (isZip(bytes)) {
+ if (/\.pptx$/i.test(name)) return { kind: 'pptx', name, bytes }
+ return { kind: 'unknown', name, reason: /\.(xlsx|docx)$/i.test(name)
+ ? 'Excel and Word files are not converted yet. PowerPoint (.pptx) files are.'
+ : 'This is a zip archive, but not a PowerPoint (.pptx) file.' }
+ }
+ const text = new TextDecoder().decode(bytes)
+ const trimmed = text.replace(/^/, '').trimStart()
+ let doc: unknown
+ let source: 'html' | 'json'
+ if (trimmed.startsWith('{')) {
+ source = 'json'
+ try { doc = JSON.parse(trimmed) } catch {
+ return { kind: 'unknown', name, reason: 'This looks like JSON but does not parse.' }
+ }
+ } else {
+ source = 'html'
+ try { doc = extractDoc(text) } catch (e) {
+ return { kind: 'unknown', name, reason: /no #bento-doc/.test(String((e as Error).message))
+ ? 'This is not a Bento file. Drop a .bento.html, a Bento document’s JSON, or a PowerPoint (.pptx).'
+ : `This Bento file could not be read: ${(e as Error).message}.` }
+ }
+ }
+ const d = doc as Record<string, unknown>
+ if (!d || typeof d !== 'object' || Array.isArray(d) || typeof d.format !== 'string' || !d.format.startsWith('bento/'))
+ return { kind: 'unknown', name, reason: 'This JSON is not a Bento document (it has no bento/… format).' }
+ return { kind: 'bento', name, source, format: d.format, text, doc: d, compact: d.compact === true }
+}
+
+/** A one-line description of a recognised input, for the "your file" card. */
+export function describe(d: Detected): { title: string; meta: string } {
+ if (d.kind === 'pptx') return { title: d.name, meta: `PowerPoint presentation · ${size(d.bytes.length)}` }
+ if (d.kind === 'unknown') return { title: d.name, meta: d.reason }
+ const app = APP_NAMES[d.format] ?? d.format
+ if (d.format === 'bento/enc') return { title: d.name, meta: 'A password-protected Bento file' }
+ const title = typeof d.doc.title === 'string' && d.doc.title ? d.doc.title : d.name
+ const slides = Array.isArray(d.doc.slides) ? d.doc.slides.filter((s) => !(s as { stateOf?: unknown })?.stateOf).length : 0
+ const sz = d.doc.size as { width?: unknown; height?: unknown } | undefined
+ const dims = sz && Number.isFinite(sz.width) && Number.isFinite(sz.height) ? ` · ${sz.width} × ${sz.height} px` : ''
+ const what = d.format === 'bento/slides' && slides ? `${slides} slide${slides === 1 ? '' : 's'}${dims}` : app
+ const from = d.source === 'json' ? (d.compact ? ' · compact document JSON' : ' · document JSON') : ''
+ return { title, meta: `${what}${from}` }
+}
+
+const APP_NAMES: Record<string, string> = {
+ 'bento/slides': 'A bento/slides deck',
+ 'bento/spaces': 'A bento/spaces file',
+ 'bento/dash': 'A bento/dash workbook',
+ 'bento/type': 'A bento/type document',
+}
+
+const size = (n: number) => n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`
+
+// --- what it can become -------------------------------------------------------
+
+export interface Env {
+ /** the current signed bento/slides shell (deliver.ts fetchVerifiedShell) */
+ shell(): Promise<{ version: string; html: string }>
+ /** document JSON → a full, gated slides document, expanding a compact one.
+ * The page passes its own loader (convert/page/load-json.ts: slides'
+ * expansion and gate). `provisional` lists the slide id of each text box
+ * left at a provisional height (nothing measured it). Null when the format
+ * check refuses it. */
+ /** a picture PowerPoint cannot take → PNG data: URI (needs a canvas) */
+ rasterise?(dataUri: string): Promise<string | null>
+ loadDocJson?(json: string): { doc: BentoDoc; dropped: Array<{ path: string; reason: string }>; provisional?: string[] } | null
+}
+
+export interface Converted {
+ bytes: Uint8Array
+ fileName: string
+ mime: string
+ report: FidelityReport
+ /** shown as the result's stat tiles, in order */
+ stats: Array<{ label: string; value: number }>
+ /** one line under the file name, e.g. which shell it was built on */
+ meta?: string
+}
+
+export interface Conversion {
+ id: string
+ /** what the output is, for the person choosing ("PowerPoint (.pptx)") */
+ label: string
+ /** one line on what to expect */
+ hint: string
+ /** true, or why this input cannot take this path (shown, not hidden) */
+ accepts(d: Detected): boolean | string
+ /** does it fetch the signed shell? (the only network the page ever uses) */
+ network: boolean
+ /** yes/no choices this conversion takes, shown only where they apply */
+ flags?: Array<{ id: string; label: string; applies(d: Detected): boolean }>
+ run(d: Detected, env: Env, flags?: Record<string, boolean>): Promise<Converted>
+}
+
+const base = (name: string) => name.replace(/(\.bento)?\.(html?|json|pptx)$/i, '')
+const emptyReport = (): FidelityReport => ({ entries: [], counts: { carried: 0, approximated: 0, dropped: 0 }, provenance: {} })
+const enc = new TextEncoder()
+
+export const CONVERSIONS: Conversion[] = [
+ {
+ id: 'pptx-to-slides',
+ label: 'bento/slides deck (.bento.html)',
+ hint: 'Built on the latest bento/slides release, after its signature is checked.',
+ network: true,
+ accepts: (d) => d.kind === 'pptx',
+ async run(d, env) {
+ if (d.kind !== 'pptx') throw new Error('not a PowerPoint file')
+ const s = await env.shell()
+ const r = await pptxToBento(d.bytes, s.html)
+ const placeholders = r.report.entries.filter((e) => /-not-yet$/.test(e.code)).reduce((n, e) => n + e.count, 0)
+ return {
+ bytes: enc.encode(r.html), fileName: `${base(d.name)}.bento.html`, mime: 'text/html', report: r.report,
+ stats: [{ label: 'slides', value: r.slides }, { label: 'placeholders', value: placeholders }, { label: 'values removed', value: r.gated.length }],
+ meta: `Built on bento/slides ${s.version}, signature verified`,
+ }
+ },
+ },
+ {
+ id: 'slides-to-pptx',
+ label: 'PowerPoint (.pptx)',
+ hint: 'Text, shapes, pictures, tables, charts, links and speaker notes stay editable.',
+ network: false,
+ accepts: (d) => {
+ if (d.kind !== 'bento' || d.format !== 'bento/slides') return false
+ if (d.compact) return 'This is compact document JSON. Make it a deck first, then convert the deck.'
+ return true
+ },
+ flags: [{
+ id: 'states',
+ label: 'Include interactive states, as hidden slides that links lead to',
+ applies: (d) => d.kind === 'bento' && Array.isArray(d.doc.slides) && d.doc.slides.some((s) => !!(s as { stateOf?: unknown })?.stateOf),
+ }],
+ async run(d, env, flags = {}) {
+ if (d.kind !== 'bento') throw new Error('not a Bento document')
+ const r = await bentoToPptx(d.text, {
+ ...(env.rasterise ? { rasterise: (u: string) => env.rasterise!(u) } : {}),
+ ...(flags.states ? { includeStates: true } : {}),
+ })
+ return {
+ bytes: r.bytes, fileName: `${base(d.name)}.pptx`,
+ mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ report: r.report,
+ stats: [{ label: 'slides', value: r.stats.slides }, { label: 'editable objects', value: r.stats.editable }, { label: 'pictures', value: r.stats.pictures }],
+ }
+ },
+ },
+ {
+ id: 'json-to-slides',
+ label: 'bento/slides deck (.bento.html)',
+ hint: 'Turns document JSON (from an AI tool or “Copy document JSON”) into a deck you can open, built on the latest signed release.',
+ network: true,
+ accepts: (d) => d.kind === 'bento' && d.source === 'json' && d.format === 'bento/slides',
+ async run(d, env) {
+ if (d.kind !== 'bento') throw new Error('not a Bento document')
+ if (!env.loadDocJson) throw new Error('this host cannot expand document JSON')
+ const loaded = env.loadDocJson(d.text)
+ if (!loaded) throw new Error('the document did not pass the bento/slides format check')
+ const s = await env.shell()
+ const report = emptyReport()
+ for (const x of loaded.dropped) {
+ report.entries.push({ code: 'value-removed', verdict: 'dropped', where: x.path, detail: `a value the format does not allow was removed (${x.reason})`, count: 1 })
+ report.counts.dropped++
+ }
+ // slide numbers as the person sees them: states are not numbered
+ const linear = loaded.doc.slides.filter((sl) => !sl.stateOf)
+ const numberOf = new Map(linear.map((sl, i) => [sl.id, i + 1]))
+ for (const id of loaded.provisional ?? []) {
+ const n = numberOf.get(id)
+ const where = n ? `slide ${n}` : 'document'
+ const key = report.entries.find((e) => e.code === 'text-height-provisional' && e.where === where)
+ if (key) key.count++
+ else report.entries.push({ code: 'text-height-provisional', verdict: 'approximated', where, detail: 'text boxes without a height get a one-line height; select one in bento/slides and use Fit height to text', count: 1 })
+ report.counts.approximated++
+ }
+ const slides = linear.length
+ return {
+ bytes: enc.encode(spliceIntoShell(s.html, loaded.doc)), fileName: `${base(d.name)}.bento.html`, mime: 'text/html', report,
+ stats: [{ label: 'slides', value: slides }, { label: 'values removed', value: loaded.dropped.length }],
+ meta: `Built on bento/slides ${s.version}, signature verified`,
+ }
+ },
+ },
+]
+
+/** Every conversion that applies to this input: available ones, and ones that
+ * apply but cannot run, with why. Empty = nothing converts this input yet. */
+export function optionsFor(d: Detected): Array<{ conversion: Conversion; ok: true } | { conversion: Conversion; ok: false; why: string }> {
+ const out: Array<{ conversion: Conversion; ok: true } | { conversion: Conversion; ok: false; why: string }> = []
+ for (const c of CONVERSIONS) {
+ const a = c.accepts(d)
+ if (a === true) out.push({ conversion: c, ok: true })
+ else if (typeof a === 'string') out.push({ conversion: c, ok: false, why: a })
+ }
+ return out
+}
+
+/** Why nothing is offered for a recognised input, in words for the person. */
+export function nothingFor(d: Detected): string {
+ if (d.kind === 'unknown') return d.reason
+ if (d.kind === 'bento' && d.format === 'bento/enc')
+ return 'This file is password-protected. Open it in Bento, save a copy without a password, and convert that copy.'
+ if (d.kind === 'bento') return `There is no conversion for ${d.format} files yet.`
+ return 'There is no conversion for this file yet.'
+}
+
+export { LimitError }
diff --git a/convert/src/pptx-write/code.ts b/convert/src/pptx-write/code.ts
index 337955f3..50c02d76 100644
--- a/convert/src/pptx-write/code.ts
+++ b/convert/src/pptx-write/code.ts
@@ -1,21 +1,26 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
-// `code` elements → PowerPoint. NOT YET WRITTEN: today a code element is
-// reported as dropped and nothing is emitted. This file is the place to write
-// it; convert/CONTRIBUTING.md has the walkthrough.
+// `code` elements → an editable PowerPoint text box.
//
-// What a good first version looks like: a p:sp text box at the element's
-// frame, the content one paragraph per line, in a monospace face (the
-// element's fontFamily, else "Consolas"), at its fontSize, alignment and
-// colour. Syntax colouring is optional — a first version that drops it says
-// so with an 'approximated' entry ('code-colours-flattened'). textSp in
-// text.ts shows how a text box is built; shapes.ts emu() converts px.
-//
-// When it emits something, move 'code' from NOT_YET to MAPPED in
-// scripts/test-convert/pptx-coverage.ts, and add its own checks there.
+// One paragraph per line, in a monospace face that PowerPoint machines have
+// (fonts.ts: slides' monospace stack becomes Consolas), at the element's
+// size, colour, alignment and line height. What slides paints, kept:
+// - indentation: slides sets white-space: pre, so every space counts. The
+// text writer collapses ordinary whitespace (as the canvas does for
+// ordinary text), so spaces that would collapse become no-break spaces;
+// tabs expand to 8-column stops, the browser's default, which slides
+// does not change. Lines are line breaks within one paragraph.
+// - no wrapping: a long line runs on rather than folding (wrap="none").
+// - no fill: slides paints no background behind code.
+// - {{tokens}} stay literal: code is never a field.
+// What is lost, and reported: syntax colouring. The tokens' colours come from
+// the highlighting theme at render time; here the code is one colour, the
+// element's own ('code-colours-flattened').
import type { ElementWriter, ElFrame } from './contract.ts'
+import { textSp, type TextElIn } from './text.ts'
+import type { XNode, XChild } from '../xmlout.ts'
/** The fields of slides' CodeElement a writer reads (restated from
* slides/src/model.ts; the writer never imports an app). */
@@ -29,12 +34,69 @@ export interface CodeElIn extends ElFrame {
color: string
/** the code itself, lines separated by \n */
content: string
- /** the highlighting grammar and theme, by name (colours are optional) */
+ /** the highlighting grammar and theme, by name or asset */
grammarName?: string
+ grammarAssetId?: string
themeName?: string
+ themeAssetId?: string
+}
+
+const NBSP = ' '
+const TAB = 8
+
+const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+
+/** One source line as the text writer's html, every column kept. A space
+ * becomes a no-break space only where ordinary whitespace would collapse
+ * (at the start of a line, or after another space), so code copied back out
+ * of PowerPoint keeps ordinary spaces between words. */
+function lineHtml(line: string): string {
+ let out = ''
+ let col = 0
+ let prevSpace = true // a line start collapses like a preceding space
+ for (const ch of line.replace(/\r$/, '')) {
+ if (ch === '\t') {
+ const n = TAB - (col % TAB)
+ out += NBSP.repeat(n)
+ col += n
+ prevSpace = true
+ } else if (ch === ' ') {
+ out += prevSpace ? NBSP : ' '
+ col++
+ prevSpace = true
+ } else {
+ out += esc(ch)
+ col++
+ prevSpace = false
+ }
+ }
+ return out
+}
+
+/** Set an attribute on the first descendant with this name (the trees are
+ * plain data, so the integrator-style post-edit is safe). */
+function setOn(node: XNode, name: string, attrs: Record<string, string>): boolean {
+ if (node.name === name) { node.attrs = { ...(node.attrs ?? {}), ...attrs }; return true }
+ for (const k of (node.kids ?? []) as XChild[]) if (typeof k === 'object' && k && setOn(k as XNode, name, attrs)) return true
+ return false
}
-export const writeCode: ElementWriter<CodeElIn> = (_el, ctx) => {
- ctx.report.add('dropped', 'element-unsupported', ctx.where, "element type 'code' has no pptx mapping")
- return null
+export const writeCode: ElementWriter<CodeElIn> = (el, ctx) => {
+ const lines = (el.content ?? '').split('\n')
+ const text: TextElIn = {
+ id: el.id, morphId: el.morphId,
+ x: el.x, y: el.y, w: el.w, h: el.h, rotation: el.rotation, opacity: el.opacity,
+ html: lines.map(lineHtml).join('<br>'),
+ fontSize: el.fontSize, fontFamily: el.fontFamily, fontWeight: 400,
+ color: el.color, align: el.align, valign: el.valign, lineHeight: el.lineHeight,
+ }
+ // no `fields`: {{tokens}} in code stay literal; no `link`: the integrator wires it
+ const node = textSp(text, { shapeId: ctx.shapeId, themeFontFamily: ctx.theme.fontFamily, report: ctx.report, where: ctx.where })
+ if (!node) return null
+ setOn(node, 'a:bodyPr', { wrap: 'none' })
+ if (el.content?.trim() && (el.grammarName || el.grammarAssetId || el.themeName || el.themeAssetId)) {
+ ctx.report.add('approximated', 'code-colours-flattened', ctx.where,
+ 'code exports as editable text in one colour; its syntax highlighting is not carried')
+ }
+ return node
}
diff --git a/convert/src/pptx-write/embed.ts b/convert/src/pptx-write/embed.ts
index 21c3dcea..bb881ed2 100644
--- a/convert/src/pptx-write/embed.ts
+++ b/convert/src/pptx-write/embed.ts
@@ -1,23 +1,18 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
-// `embed` elements → PowerPoint. NOT YET WRITTEN: today an embed (a bento/dash
-// chart, a bento/type page, a web page) is reported as dropped and nothing is
-// emitted. This file is the place to write it; convert/CONTRIBUTING.md has the
-// walkthrough.
+// `embed` elements → a picture of their static view.
//
-// Every embed carries a static render in `view`: raw <svg> markup, or
-// "asset:<key>" naming the asset that holds it. That is what PowerPoint should
-// show. svgPic in media.ts already turns svg markup into a picture with the
-// right package wiring, so a first version can hand it the view and report
-// 'approximated' ('embed-static'): the slide shows the picture, but the live
-// document behind it does not travel. A web embed (app 'web') with no view
-// stays dropped.
-//
-// When it emits something, move 'embed' from NOT_YET to MAPPED in
-// scripts/test-convert/pptx-coverage.ts, and add its own checks there.
+// Every embed (a bento/dash chart, a bento/type page, a web page) carries a
+// static render in `view`: raw <svg> markup, or "asset:<key>" naming the asset
+// that holds it. That is what PowerPoint shows, placed by svgPic (media.ts)
+// with the same package wiring as any SVG. Reported as 'approximated'
+// ('embed-static'): the picture travels; the live document behind it, and
+// any live web frame, do not. An embed with no view (a web embed that never
+// rendered one) has nothing to show and is reported dropped.
import type { ElementWriter, ElFrame } from './contract.ts'
+import { svgPic } from './media.ts'
/** The fields of slides' EmbedElement a writer reads (restated from
* slides/src/model.ts; the writer never imports an app). */
@@ -31,7 +26,20 @@ export interface EmbedElIn extends ElFrame {
url?: string
}
-export const writeEmbed: ElementWriter<EmbedElIn> = (_el, ctx) => {
- ctx.report.add('dropped', 'element-unsupported', ctx.where, "element type 'embed' has no pptx mapping")
- return null
+const appName = (app: string) => (app === 'web' ? 'web page' : `${app} document`)
+
+export const writeEmbed: ElementWriter<EmbedElIn> = (el, ctx) => {
+ const view = typeof el.view === 'string' ? el.view.trim() : ''
+ const asset = view.startsWith('asset:') ? view.slice('asset:'.length) : undefined
+ const markup = asset ? ctx.media.assets[asset] ?? '' : view
+ if (!/^<svg[\s>]/i.test(markup.trimStart())) {
+ ctx.report.add('dropped', 'embed-no-view', ctx.where,
+ `an embedded ${appName(el.app)} has no picture to show, so it is left out`)
+ return null
+ }
+ const node = svgPic({ id: el.id, x: el.x, y: el.y, w: el.w, h: el.h, rotation: el.rotation, opacity: el.opacity, markup },
+ ctx.shapeId, ctx.where, ctx.media)
+ if (node) ctx.report.add('approximated', 'embed-static', ctx.where,
+ `an embedded ${appName(el.app)} shows as a picture; its live content and source do not travel`)
+ return node
}
diff --git a/convert/src/pptx-write/fonts.ts b/convert/src/pptx-write/fonts.ts
index d1758a25..f952aec1 100644
--- a/convert/src/pptx-write/fonts.ts
+++ b/convert/src/pptx-write/fonts.ts
@@ -29,7 +29,8 @@ const GENERIC: Record<string, string> = {
}
/**
- * System fonts that ship with ONE operating system and not with Office. A
+ * Fonts a PowerPoint machine is unlikely to have: system fonts that ship with
+ * ONE operating system and not with Office, and commercial coding fonts. A
* browser falls through a stack to the next family it has; PowerPoint takes
* one name and substitutes when it is missing. So naming 'SF Mono' (macOS
* only) gives Windows PowerPoint a proportional stand-in, while the stack's
@@ -43,6 +44,9 @@ const ONE_PLATFORM = new Set([
'roboto', 'roboto mono', 'ubuntu', 'ubuntu mono', 'cantarell', 'oxygen', 'fira sans',
'noto sans', 'noto color emoji', 'liberation mono', 'liberation sans', 'liberation serif',
'dejavu sans', 'dejavu sans mono', 'dejavu serif', 'droid sans', 'droid sans mono',
+ // commercial coding fonts no OS or Office installs; slides' own monospace
+ // stack names 'Berkeley Mono' before 'Consolas'
+ 'berkeley mono', 'operator mono', 'monolisa', 'pragmata pro', 'input mono', 'dank mono',
])
const families = (stack: string): string[] =>
diff --git a/convert/src/pptx-write/index.ts b/convert/src/pptx-write/index.ts
index 68203c43..f56f7834 100644
--- a/convert/src/pptx-write/index.ts
+++ b/convert/src/pptx-write/index.ts
@@ -48,7 +48,7 @@ import {
import { textSp, type FieldValues, type TextElIn } from './text.ts'
import { emu, parseColor, shapeNode, type ShapeIn } from './shapes.ts'
import {
- MediaStore, imagePic, svgPic, mediaPoster,
+ MediaStore, imagePic, svgPic, mediaPoster, rasterTargets, pictureSources,
type ImageIn, type MediaCtx, type MediaIn, type SvgIn,
} from './media.ts'
import { tableFrame } from './tables.ts'
@@ -140,11 +140,26 @@ export interface ExportOpts {
* (the scanner is app code: slides' maths/delimiters.ts), so the caller
* passes it, like chartPalette. Absent = not reported. */
formulasIn?: (html: string) => number
+ /** Turns a picture PowerPoint cannot take (WebP, AVIF, BMP, TIFF) into a
+ * PNG data: URI, or null when it cannot. Decoding images needs a browser
+ * (a canvas), and the writer has no DOM, so a host that has one passes it
+ * (bento.page/convert does). Absent = such pictures are reported dropped. */
+ rasterise?: (dataUri: string) => Promise<string | null>
+ /** Export interactive states too, as HIDDEN slides placed right after the
+ * slide they belong to, with links into a state landing on it. In a
+ * PowerPoint show, hidden slides are reached only by those links, and
+ * Next/Previous skip them, much as bento's ←/→ skip states. Default off:
+ * states are left out and links into one go to its parent. */
+ includeStates?: boolean
}
export interface PptxExport {
bytes: Uint8Array
report: FidelityReport
+ /** what landed in the package, for a host to show: slides, objects that
+ * stay editable in PowerPoint (shapes, text, connectors, tables, charts),
+ * and pictures (images, SVG, media posters) */
+ stats: { slides: number; editable: number; pictures: number }
}
// --- helpers ------------------------------------------------------------------
@@ -262,10 +277,15 @@ function appPropsXml(doc: ExportDoc): string {
export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise<PptxExport> {
const report = new Report()
- const exported = doc.slides.filter((s) => !s.stateOf)
- if (exported.length === 0) {
+ const linear = doc.slides.filter((s) => !s.stateOf)
+ if (linear.length === 0) {
throw new Error('exportPptx: the deck has no linear slides (only interactive states) — nothing to export')
}
+ // With includeStates, every slide in document order: slides keeps a state
+ // next to its parent, and a state whose parent is gone still has nowhere
+ // better to sit. Without, only the linear slides.
+ const states = doc.slides.filter((s) => !!s.stateOf)
+ const exported = opts.includeStates ? doc.slides.slice() : linear
const omitted = doc.slides.length - exported.length
// The deck's own fonts travel inside the .bento.html; a .pptx can embed
// fonts too, but this writer does not, so say which ones need installing.
@@ -279,13 +299,19 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
report.add('dropped', 'state-slides-omitted', 'document',
`${omitted} interactive state slide(s) omitted — a state is a click-reached variant, not a linear slide`)
}
+ if (opts.includeStates && states.length) {
+ report.add('approximated', 'states-as-hidden-slides', 'document',
+ `${states.length} interactive state slide(s) exported as hidden slides after the slide they belong to: links reach them, and the show skips them`)
+ }
// Slide id → exported slide number, with #88's degradation: a link into an
// omitted state retargets to the state's visible parent.
const slideNumbers = new Map<string, number>()
exported.forEach((s, i) => slideNumbers.set(s.id, i + 1))
for (const s of doc.slides) {
- if (s.stateOf) {
+ // only a state that was LEFT OUT borrows its parent's number; an exported
+ // state (includeStates) keeps its own, so links into it land on it
+ if (s.stateOf && !slideNumbers.has(s.id)) {
const parent = slideNumbers.get(s.stateOf)
if (parent) slideNumbers.set(s.id, parent)
}
@@ -302,6 +328,20 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const palette = doc.theme.chartPalette?.length ? doc.theme.chartPalette : opts.chartPalette
const assets = doc.assets ?? {}
+
+ // Pictures PowerPoint cannot take, each converted ONCE by the host's
+ // rasteriser before any slide is written, so imagePic stays synchronous.
+ // Whatever comes back must be a PNG data: URI; anything else counts as a
+ // failed conversion (reported as a drop where the picture was).
+ let converted: Map<string, string | null> | undefined
+ if (opts.rasterise) {
+ converted = new Map()
+ for (const src of rasterTargets(pictureSources(exported as never, assets))) {
+ let png: string | null = null
+ try { png = await opts.rasterise(src) } catch { png = null }
+ converted.set(src, typeof png === 'string' && /^data:image\/png[;,]/i.test(png) ? png : null)
+ }
+ }
const store = new MediaStore() // ONE per export: byte-dedup is cross-slide
const enc = new TextEncoder()
@@ -312,6 +352,7 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const extraOverrides: ContentTypeOverride[] = []
let chartCount = 0
let pageCounter = 0
+ const stats = { slides: exported.length, editable: 0, pictures: 0 }
for (let si = 0; si < exported.length; si++) {
const slide = exported[si]
@@ -322,7 +363,7 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
// Field values are author-typed strings that land verbatim in a:t —
// scrubbed like every other author-text ingestion point.
const fields: FieldValues = {
- page: pageCounter, pages,
+ page: pageCounter, pptxSlide: num, pages,
title: scrubC0(doc.title), date: now,
author: scrubC0(meta.author ?? ''), company: scrubC0(meta.company ?? ''),
subject: scrubC0(meta.subject ?? ''), event: scrubC0(meta.event ?? ''),
@@ -334,7 +375,7 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const rels: RelEntry[] = []
const nextRelId = (): string => `rId${++relSeq}`
rels.push(slideLayoutRel(nextRelId()))
- const mediaCtx: MediaCtx = { assets, store, rels, nextRelId, report }
+ const mediaCtx: MediaCtx = { assets, store, rels, nextRelId, report, converted }
/** el.link → an allocated rel. Reported and null when the target does not
* resolve (#88's missing-link-target) — a dangling r:id is a repair
@@ -369,7 +410,11 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const children: XChild[] = []
let shapeId = 2 // the spTree preamble owns id 1 (parts.ts)
const emit = (node: XNode | null): void => {
- if (node) { children.push(node); shapeId++ }
+ if (!node) return
+ children.push(node)
+ shapeId++
+ if (node.name === 'p:pic') stats.pictures++
+ else stats.editable++
}
for (const el of slide.elements) {
@@ -492,7 +537,7 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const part = slidePart(children, rels, {
bg: bgNode(slide.background, doc.theme.background, report, where),
- ...(slide.hidden ? { hidden: true } : {}),
+ ...(slide.hidden || slide.stateOf ? { hidden: true } : {}),
})
slideXml.push(part.xml)
slideRels.push(part.rels)
@@ -569,5 +614,5 @@ export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise
const problems = packageProblems(new Map(entries.map((e) => [e.name, e.data])))
if (problems.length) throw new Error(`the PowerPoint package failed its self-check (a bug in the writer): ${problems.join('; ')}`)
const bytes = await writeZip(entries, opts.at ? { at: opts.at } : {})
- return { bytes, report: report.build() }
+ return { bytes, report: report.build(), stats }
}
diff --git a/convert/src/pptx-write/media.ts b/convert/src/pptx-write/media.ts
index 6a0fc8d2..4ce128da 100644
--- a/convert/src/pptx-write/media.ts
+++ b/convert/src/pptx-write/media.ts
@@ -217,6 +217,10 @@ export class MediaStore {
export interface MediaCtx {
/** doc.assets — "asset:<key>" resolves here */
assets: Record<string, string>
+ /** pictures the host's rasteriser converted before the slides were
+ * written (see rasterTargets): original data: URI → PNG data: URI, or
+ * null when the conversion failed. Absent = no rasteriser. */
+ converted?: Map<string, string | null>
store: MediaStore
/** the slide's rel list; this module pushes image rels into it */
rels: RelEntry[]
@@ -307,8 +311,48 @@ const bentoName = (el: { id: string; morphId?: string }): string => `bento:${el.
* stretch mapping SILENTLY; the report entry is the difference between an
* approximation and a lie.
*/
+/** The source to write: the host's PNG when it converted this picture (and
+ * that is reported), else the original. Null = the conversion failed, and
+ * that is reported as the drop. */
+function convertedSrc(src: string, where: string, ctx: MediaCtx): string | null {
+ if (!ctx.converted?.has(src)) return src
+ const png = ctx.converted.get(src)
+ const mime = /^data:([^;,]+)/.exec(src)?.[1] ?? 'image'
+ if (!png) {
+ ctx.report.add('dropped', 'missing-image', where, `a ${mime} picture could not be converted to PNG; dropped`)
+ return null
+ }
+ ctx.report.add('approximated', 'image-converted-png', where,
+ `${mime} pictures were converted to PNG, which PowerPoint reads; they look the same, but the file is larger`)
+ return png
+}
+
+/** The data: URIs among these sources that PowerPoint cannot take but a
+ * rasteriser could turn into PNG: raster images outside EXT_BY_MIME (webp,
+ * avif, bmp, tiff…). SVG is excluded; it is placed as SVG. */
+export function rasterTargets(srcs: Iterable<string>): string[] {
+ const out = new Set<string>()
+ for (const src of srcs) {
+ const mime = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase()
+ if (mime && mime.startsWith('image/') && mime !== 'image/svg+xml' && !EXT_BY_MIME[mime]) out.add(src)
+ }
+ return [...out]
+}
+
+/** Every picture source an export may write: image elements and media
+ * posters, resolved through the assets. */
+export function pictureSources(slides: Array<{ elements: Array<{ type?: string; src?: string; poster?: string }> }>, assets: Record<string, string>): string[] {
+ const out: string[] = []
+ for (const sl of slides) for (const el of sl.elements) {
+ const ref = el.type === 'image' ? el.src : el.type === 'media' ? el.poster : undefined
+ if (ref) out.push(resolveSrc(assets, ref))
+ }
+ return out
+}
+
export function imagePic(el: ImageIn, shapeId: number, where: string, ctx: MediaCtx): XNode | null {
- const src = resolveSrc(ctx.assets, el.src)
+ const src = convertedSrc(resolveSrc(ctx.assets, el.src), where, ctx)
+ if (src === null) return null
if (!src) {
ctx.report.add('dropped', 'missing-image', where, 'image source is empty or its asset reference is dangling')
return null
@@ -325,7 +369,9 @@ export function imagePic(el: ImageIn, shapeId: number, where: string, ctx: Media
if (!partName) {
ctx.report.add('dropped', 'missing-image', where,
decoded
- ? `image format '${decoded.mime}' has no PowerPoint-safe extension; dropped`
+ ? (/^image\/(webp|avif|bmp|tiff?)$/i.test(decoded.mime)
+ ? `${decoded.mime} pictures need converting to PNG first, which this exporter cannot do on its own (bento.page/convert does it); dropped`
+ : `image format '${decoded.mime}' has no PowerPoint-safe extension; dropped`)
: 'image data: URI is malformed; dropped')
return null
}
@@ -408,7 +454,7 @@ export function mediaPoster(el: MediaIn, shapeId: number, where: string, ctx: Me
ctx.report.add('dropped', 'media-dropped', where,
`${el.kind} not exported (M-export-0 has no playable-media pipeline)` +
(el.poster ? '; its poster image stands in on the slide' : ''))
- const poster = el.poster ? resolveSrc(ctx.assets, el.poster) : ''
+ const poster = el.poster ? convertedSrc(resolveSrc(ctx.assets, el.poster), where, ctx) : ''
if (!poster) return null
if (poster.startsWith('data:')) {
const decoded = decodeDataUri(poster)
diff --git a/convert/src/pptx-write/shapes.ts b/convert/src/pptx-write/shapes.ts
index 3194e997..ac6f6200 100644
--- a/convert/src/pptx-write/shapes.ts
+++ b/convert/src/pptx-write/shapes.ts
@@ -302,13 +302,73 @@ function effectsOf(el: ShapeIn, report: Report, where: string): XNode | null {
// --- geometry ----------------------------------------------------------------
/**
- * a:custGeom from the SVG path subset bento emits (M/L/H/V/C/Q/Z, absolute
- * and relative; S/T resolved exactly via control-point reflection). Path
+ * An SVG elliptical arc as cubic Béziers (SVG 1.1 implementation notes F.6:
+ * endpoint to centre parameterisation, then one cubic per quarter turn or
+ * less, k = 4/3·tan(Δθ/4)). Exact to well under a pixel at slide scale.
+ * Returns [c1x, c1y, c2x, c2y, x, y] per segment; [] for a zero-length arc;
+ * null when a radius is 0 (the spec draws a straight line).
+ */
+export function arcToCubics(x1: number, y1: number, rx: number, ry: number, phiDeg: number,
+ largeArc: number, sweep: number, x2: number, y2: number): number[][] | null {
+ // a non-finite input (path data misread upstream) draws a line, and the
+ // caller's coordinate guard then stops the parse if the endpoint is bad too
+ if (![x1, y1, rx, ry, phiDeg, x2, y2].every(Number.isFinite)) return null
+ if (x1 === x2 && y1 === y2) return []
+ rx = Math.abs(rx); ry = Math.abs(ry)
+ if (rx === 0 || ry === 0) return null
+ const phi = (phiDeg * Math.PI) / 180
+ const cos = Math.cos(phi), sin = Math.sin(phi)
+ const dx = (x1 - x2) / 2, dy = (y1 - y2) / 2
+ const x1p = cos * dx + sin * dy
+ const y1p = -sin * dx + cos * dy
+ // radii too small for the endpoints are scaled up (F.6.6)
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
+ if (lambda > 1) { const k = Math.sqrt(lambda); rx *= k; ry *= k }
+ const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
+ const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
+ let coef = Math.sqrt(Math.max(0, num / den))
+ if (largeArc === sweep) coef = -coef
+ const cxp = (coef * rx * y1p) / ry
+ const cyp = (-coef * ry * x1p) / rx
+ const cx = cos * cxp - sin * cyp + (x1 + x2) / 2
+ const cy = sin * cxp + cos * cyp + (y1 + y2) / 2
+ const angle = (ux: number, uy: number, vx: number, vy: number) => {
+ const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
+ return a
+ }
+ const theta1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
+ let delta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
+ if (!sweep && delta > 0) delta -= 2 * Math.PI
+ else if (sweep && delta < 0) delta += 2 * Math.PI
+ if (!Number.isFinite(delta) || !Number.isFinite(cx) || !Number.isFinite(cy)) return null
+ const n = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2) - 1e-9))
+ const step = delta / n
+ const k = (4 / 3) * Math.tan(step / 4)
+ const out: number[][] = []
+ // a point on the ellipse at parameter t, and its derivative
+ const P = (t: number) => [cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos]
+ const D = (t: number) => [-rx * Math.sin(t) * cos - ry * Math.cos(t) * sin, -rx * Math.sin(t) * sin + ry * Math.cos(t) * cos]
+ for (let j = 0; j < n; j++) {
+ const t1 = theta1 + j * step, t2 = t1 + step
+ const [ax, ay] = P(t1), [bx, by] = P(t2)
+ const [dax, day] = D(t1), [dbx, dby] = D(t2)
+ out.push([ax + k * dax, ay + k * day, bx - k * dbx, by - k * dby, bx, by])
+ }
+ // land exactly on the requested endpoint
+ out[out.length - 1][4] = x2; out[out.length - 1][5] = y2
+ return out
+}
+
+/**
+ * a:custGeom from SVG path data (M/L/H/V/C/S/Q/T/A/Z, absolute and
+ * relative; S/T resolved exactly via control-point reflection, arcs as exact
+ * cubics via arcToCubics). Path
* coordinates are ST_AdjCoordinate — INTEGERS — so the path space is scaled
* to EMU (px * 9525): sub-pixel curve detail survives the integer floor.
- * Arcs (A) have no custGeom primitive; they degrade to a straight line to
- * the arc's endpoint and the report says so — as does any command letter
- * outside the vocabulary, which additionally stops the parse (continuing
+ * Arcs (A) have no custGeom primitive of the same shape (arcTo is
+ * centre-relative); they become cubic Béziers, which is exact enough to be
+ * no loss. Any command letter outside the vocabulary is reported and stops
+ * the parse (continuing
* past an unknown command means guessing at its argument count, and a
* miscounted queue turns every coordinate after it into garbage).
*/
@@ -318,7 +378,15 @@ function custGeomNode(el: ShapeIn, report: Report, where: string): XNode {
const ph = Math.max(emu(bh), 1)
const px = (v: number) => Math.round((v - bx) * EMU_PER_PX)
const py = (v: number) => Math.round((v - by) * EMU_PER_PX)
- const pt = (X: number, Y: number): XNode => x('a:pt', { x: px(X), y: py(Y) })
+ // A coordinate that is not a finite number (a path that runs out of
+ // arguments, or one this parser misreads) ends the parse at the last good
+ // segment and is reported, never written: xmlout refuses NaN, and one bad
+ // path must not cost the whole export.
+ class BadCoordinate extends Error {}
+ const pt = (X: number, Y: number): XNode => {
+ if (!Number.isFinite(X) || !Number.isFinite(Y)) throw new BadCoordinate()
+ return x('a:pt', { x: px(X), y: py(Y) })
+ }
const segs: XChild[] = []
let approx = false
@@ -333,9 +401,20 @@ function custGeomNode(el: ShapeIn, report: Report, where: string): XNode {
let pcx: number | null = null, pcy = 0 // previous cubic ctrl2 (for S)
let pqx: number | null = null, pqy = 0 // previous quad ctrl (for T)
const num = () => Number(tokens[i++])
+ // An arc flag is ONE digit, 0 or 1, and SVG lets flags run together with
+ // what follows ("a.4.4 0 00-.1-.2" is flags 0 and 0, then x -.1): a minifier
+ // writes them that way, and reading "00" as one number shifted every
+ // coordinate after it. Take the first digit and leave the rest queued.
+ const flag = (): number => {
+ const t = tokens[i]
+ // "00.267" tokenises as one decimal: flags 0 and 0, then x .267
+ if (t !== undefined && t.length > 1 && /^[01]/.test(t)) { tokens[i] = t.slice(1); return Number(t[0]) }
+ return num()
+ }
const isNum = () => i < tokens.length && !/^[A-Za-z]$/.test(tokens[i])
let stopped = false
+ try {
while (i < tokens.length && !stopped) {
const cmd = tokens[i++]
const rel = cmd === cmd.toLowerCase()
@@ -424,12 +503,13 @@ function custGeomNode(el: ShapeIn, report: Report, where: string): XNode {
break
case 'A':
while (isNum()) {
- num(); num(); num(); num(); num() // rx ry rot large-arc sweep: unused
+ const rx = num(), ry = num(), rot = num(), large = flag(), sw = flag()
const X = num() + (rel ? cx : 0)
const Y = num() + (rel ? cy : 0)
- segs.push(x('a:lnTo', undefined, [pt(X, Y)]))
+ const curves = arcToCubics(cx, cy, rx, ry, rot, large, sw, X, Y)
+ if (curves === null) segs.push(x('a:lnTo', undefined, [pt(X, Y)])) // zero radius: a line, per the spec
+ else for (const [a1, b1, a2, b2, a3, b3] of curves) segs.push(x('a:cubicBezTo', undefined, [pt(a1, b1), pt(a2, b2), pt(a3, b3)]))
cx = X; cy = Y
- approx = true
}
break
case 'Z':
@@ -442,13 +522,17 @@ function custGeomNode(el: ShapeIn, report: Report, where: string): XNode {
if (!keepsCubic) pcx = null
if (!keepsQuad) pqx = null
}
+ } catch (e) {
+ if (!(e instanceof BadCoordinate)) throw e
+ stopped = true
+ }
if (junk) {
approx = true
stopped = true
}
if (approx || stopped) {
report.add('approximated', 'path-approximated', where,
- 'path uses commands outside the M/L/H/V/C/S/Q/T/Z subset; arcs flattened to lines')
+ 'path data could not be fully read; the shape is drawn up to the point it stopped')
}
// A pathLst with zero commands is a repair dialog; an unusable d degrades
// to the element's box outline (visible, selectable, honestly reported).
diff --git a/convert/src/pptx-write/text.ts b/convert/src/pptx-write/text.ts
index bbcdaf55..3797bbd8 100644
--- a/convert/src/pptx-write/text.ts
+++ b/convert/src/pptx-write/text.ts
@@ -63,6 +63,11 @@ export interface TextElIn {
* (page = 1-based position among non-state slides). */
export interface FieldValues {
page: number
+ /** this slide's number as PowerPoint counts it (every slide, hidden ones
+ * included). Where it differs from `page` (bento counts only shown
+ * slides), {{page}} is written as fixed text, not a live slide-number
+ * field, which PowerPoint would recompute to the wrong number. */
+ pptxSlide?: number
pages: number
title: string
date: Date
@@ -278,6 +283,14 @@ function splitFields(text: string, ctx: FieldValues | undefined, onFrozen: (toke
const arg = m[2]
switch (m[1].toLowerCase()) {
case 'page':
+ if (ctx.pptxSlide !== undefined && ctx.pptxSlide !== ctx.page) {
+ // PowerPoint would number this slide differently (a hidden slide
+ // or a state comes before it): a live field would show its number,
+ // not bento's, so the page is fixed text, reported as frozen
+ pieces.push({ kind: 'text', text: pad(ctx.page, arg) })
+ onFrozen('page')
+ break
+ }
// the cached a:t honours the pad; the live field re-renders unpadded
// the moment PowerPoint recomputes — an approximation, reported below
pieces.push({ kind: 'fld', type: 'slidenum', cached: pad(ctx.page, arg), frozenPad: parseInt(arg ?? '', 10) > 0 })
diff --git a/convert/src/pptx-write/verify.ts b/convert/src/pptx-write/verify.ts
index 6bb1b078..afe1c867 100644
--- a/convert/src/pptx-write/verify.ts
+++ b/convert/src/pptx-write/verify.ts
@@ -42,7 +42,9 @@ export function brokenRels(parts: Parts): string[] {
const baseDir = name === '_rels/.rels' ? '' : name.slice(0, name.indexOf('/_rels/'))
for (const rel of kids(parseXml(dec.decode(data)), NS.rel, 'Relationship')) {
if (attr(rel, 'TargetMode') === 'External') continue
- const target = resolvePath(baseDir, attr(rel, 'Target') ?? '')
+ // a target starting with '/' is relative to the package root (OPC)
+ const raw = attr(rel, 'Target') ?? ''
+ const target = raw.startsWith('/') ? resolvePath('', raw.slice(1)) : resolvePath(baseDir, raw)
if (!parts.has(target)) broken.push(`${name} -> ${target}`)
}
}
@@ -85,7 +87,8 @@ export function packageProblems(parts: Parts): string[] {
const overrides = new Set(kids(ct, NS.ct, 'Override').map((o) => attr(o, 'PartName')))
const defaults = new Set(kids(ct, NS.ct, 'Default').map((d) => (attr(d, 'Extension') ?? '').toLowerCase()))
for (const name of parts.keys()) {
- if (name === '[Content_Types].xml') continue
+ // folder entries ('ppt/') are not parts; some zip writers add them
+ if (name === '[Content_Types].xml' || name.endsWith('/')) continue
const ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
if (!overrides.has(`/${name}`) && !defaults.has(ext)) out.push(`${name} has no content type`)
}
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index dae76cba..2d1d81e1 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10177,3 +10177,56 @@ neither a CSS generic nor a font only one operating system ships ('SF Mono',
becomes Consolas, which Office installs on Windows and macOS. A stack of
generics alone maps to a font every PowerPoint has (monospace → Courier New,
sans-serif → Arial). The deck's own fonts are never skipped.
+
+## 2026-10-10 — One conversion page, a table of pairs; every slides element exports
+
+**bento.page/convert replaces separate import and export pages.**
+`convert/src/pairs.ts` is the whole model: `detect()` says what a dropped
+file is (by content: a zip that is a .pptx, a .bento.html of any app,
+document JSON), and `CONVERSIONS` lists what each input can become. Pairs
+today: .pptx → deck; slides deck or JSON → .pptx; slides document JSON
+(compact or full) → deck. A pair that applies but cannot run says why
+(compact JSON → .pptx: "make it a deck first"). Another app's file, or a
+password-protected one, is told so plainly. A new format is a new row,
+never a new page. bento.page/import is a static, script-free redirect to
+/convert?from=pptx, because the slides menu and the 1.2.4 announcement link
+to it.
+
+**The page's guarantees are the import page's.** A CSP is built from the
+sha256 of the one inline script and style: `connect-src 'self'`, no
+`unsafe-inline`. The signed manifest and the shell it pins are the only
+requests, made only for a pair that builds a deck. No app shell carries any
+converter: `scripts/test-convert/boundary.ts` now inflates each BUILT
+shell's runtime (base-86) and fails on converter strings. A first version
+of that check read nothing and passed, so it now also requires that the
+runtime was actually read.
+
+**Document JSON on the page skips text measurement.** slides' own loader
+fits text boxes that a compact document left without a height by rendering
+them. On this page the renderer's inline styles are blocked by the page's
+own CSP, the deck's fonts aren't loaded, and it would add about 300 KB. So
+`convert/page/load-json.ts` runs the same expansion and gate without it, and
+reports each box left at a provisional height (`text-height-provisional`).
+
+**Every slides element type now exports** (maintainer's ruling, 2026-10-10;
+behaviours taken from an earlier library-based converter, none of its code):
+- `code` becomes editable text in Consolas, one line per source line.
+ Indentation is kept: spaces that would collapse become no-break spaces,
+ tabs expand to 8-column stops, and single spaces stay ordinary so copied
+ code pastes cleanly. Lost syntax colours are reported.
+- `embed` becomes a picture of its SVG view, reported as static. An embed
+ with no SVG view is reported dropped.
+- WebP, AVIF, BMP and TIFF pictures become PNG through `ExportOpts.rasterise`.
+ A host with a browser passes it (the page uses a canvas, data: URIs only,
+ at most 40 megapixels); the CLI has none and reports them dropped.
+- Interactive states, as an option (`includeStates`, `--states`, a checkbox
+ on the page), export as hidden slides right after their parent, with links
+ into a state landing on it.
+
+**Page numbers where PowerPoint counts differently.** bento numbers only
+shown slides; PowerPoint's live slide-number field counts hidden slides too.
+So `{{page}}` stays a live field only where PowerPoint's count equals
+bento's page. Elsewhere, after a hidden slide or a state, it is fixed text,
+reported as `text-field-frozen`. This was already wrong after any hidden
+slide before states existed.
+
diff --git a/scripts/build-import-page.mjs b/scripts/build-convert-page.mjs
similarity index 73%
rename from scripts/build-import-page.mjs
rename to scripts/build-convert-page.mjs
index 24016d1b..2d53d3d8 100644
--- a/scripts/build-import-page.mjs
+++ b/scripts/build-convert-page.mjs
@@ -2,13 +2,15 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
-// Build bento.page/import — the public .pptx → .bento.html page.
+// Build bento.page/convert — the one conversion page, many formats to many.
//
-// node scripts/build-import-page.mjs <out/index.html>
+// node scripts/build-convert-page.mjs <out/index.html>
//
-// Bundles convert/page/import-page.ts (which runs the same convert/src/api.ts
-// as the CLI) and inlines it into site-src/import.html, then writes a Content
+// Bundles convert/page/convert-page.ts (which runs the same convert/src as the
+// CLI) and inlines it into site-src/convert.html, then writes a Content
// Security Policy built from the SHA-256 of the exact inline script and style.
+// bento.page/import is a static redirect here (site-src/import.html), copied
+// by release.mjs; it carries no script at all.
//
// THE CSP IS THE PRIVACY PROMISE, ENFORCED. The page says the file never leaves
// the device. `connect-src 'self'` makes that the browser's rule rather than
@@ -29,13 +31,13 @@ import { fileURLToPath } from 'node:url'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const out = process.argv[2]
-if (!out) { console.error('usage: build-import-page.mjs <out/index.html>'); process.exit(2) }
+if (!out) { console.error('usage: build-convert-page.mjs <out/index.html>'); process.exit(2) }
const esbuild = path.join(root, 'slides/node_modules/.bin/esbuild')
-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-import-page-'))
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-convert-page-'))
const bundle = path.join(tmp, 'page.js')
const built = spawnSync(esbuild, [
- path.join(root, 'convert/page/import-page.ts'), '--bundle', '--format=esm', '--minify',
+ path.join(root, 'convert/page/convert-page.ts'), '--bundle', '--format=esm', '--minify',
'--platform=browser', '--target=es2022', '--log-level=error', `--outfile=${bundle}`,
], { encoding: 'utf8' })
if (built.status !== 0) { console.error(built.stderr); process.exit(1) }
@@ -47,9 +49,9 @@ fs.rmSync(tmp, { recursive: true, force: true })
const CLOSE = '</' + 'script'
if (js.toLowerCase().includes(CLOSE)) js = js.replace(/<\/(script)/gi, '<\\/$1')
-let html = fs.readFileSync(path.join(root, 'site-src/import.html'), 'utf8')
+let html = fs.readFileSync(path.join(root, 'site-src/convert.html'), 'utf8')
const style = /<style>([\s\S]*?)<\/style>/.exec(html)?.[1]
-if (style === undefined) { console.error('site-src/import.html has no <style> block'); process.exit(1) }
+if (style === undefined) { console.error('site-src/convert.html has no <style> block'); process.exit(1) }
const sha = (s) => `'sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}'`
const csp = [
@@ -68,8 +70,8 @@ const csp = [
// head (CSP included) into the output, so the inline script was no longer the
// script that had been hashed and the page's own CSP would have blocked it.
html = html
- .replace('<!--IMPORT_CSP-->', () => `<meta http-equiv="Content-Security-Policy" content="${csp}">`)
- .replace('<!--IMPORT_SCRIPT-->', () => `<script type="module">${js}</script>`)
+ .replace('<!--CONVERT_CSP-->', () => `<meta http-equiv="Content-Security-Policy" content="${csp}">`)
+ .replace('<!--CONVERT_SCRIPT-->', () => `<script type="module">${js}</script>`)
// Belt: the page must carry exactly one CSP, and the script it runs must be the
// one the CSP names. Cheap, and it is precisely the check that would have
@@ -82,4 +84,4 @@ if (inline !== js || !csp.includes(sha(inline)))
fs.mkdirSync(path.dirname(out), { recursive: true })
fs.writeFileSync(out, html)
-console.log(`import page: ${out} (${Math.round(html.length / 1024)}KB, script ${Math.round(js.length / 1024)}KB)`)
+console.log(`convert page: ${out} (${Math.round(html.length / 1024)}KB, script ${Math.round(js.length / 1024)}KB)`)
diff --git a/scripts/release.mjs b/scripts/release.mjs
index ec1bfbf5..c14b11c2 100644
--- a/scripts/release.mjs
+++ b/scripts/release.mjs
@@ -393,11 +393,14 @@ if (app.ownsSiteContent) {
execFileSync('node', [join(root, 'scripts/build-404-deck.mjs'), join(site, '404.bento.html')], { stdio: 'inherit' })
cpSync(join(root, 'site-src/404.html'), join(site, '404.html'))
- // /import — drop a .pptx, get a .bento.html back, converted in the visitor's
- // browser (convert/page + convert/src; nothing uploaded). Built into a single
- // page with a hash-based CSP (scripts/build-import-page.mjs). No shell carries
- // any of it: the converter lives on this page and nowhere else.
- execFileSync('node', [join(root, 'scripts/build-import-page.mjs'), join(site, 'import/index.html')], { stdio: 'inherit' })
+ // /convert — one page for every conversion (convert/page + convert/src;
+ // nothing uploaded), built into a single page with a hash-based CSP
+ // (scripts/build-convert-page.mjs). No shell carries any of it.
+ execFileSync('node', [join(root, 'scripts/build-convert-page.mjs'), join(site, 'convert/index.html')], { stdio: 'inherit' })
+ // /import — kept as a static, script-free redirect to /convert?from=pptx:
+ // the slides menu entry and the release announcement link to it.
+ mkdirSync(join(site, 'import'), { recursive: true })
+ cpSync(join(root, 'site-src/import.html'), join(site, 'import/index.html'))
// /q — "this QR code is a presentation" (deck lives in the URL fragment).
execFileSync('node', [join(root, 'scripts/build-qr-page.mjs'), join(site, 'q/index.html')], { stdio: 'inherit' })
diff --git a/scripts/test-convert/boundary.ts b/scripts/test-convert/boundary.ts
index 82912b47..847faf83 100644
--- a/scripts/test-convert/boundary.ts
+++ b/scripts/test-convert/boundary.ts
@@ -14,6 +14,9 @@
// there, and every reachable file is covered, not just the ones listed.
import { spawnSync } from 'node:child_process'
+import zlib from 'node:zlib'
+// @ts-expect-error plain .mjs helper, no types
+import { decode as b86decode } from '../lib/b86.mjs'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -62,16 +65,34 @@ for (const entry of ['convert/src/pptx.ts', 'convert/src/pptx-write/index.ts', '
ok(r.status === 0 && r.stdout.length > 1000 && hits.length === 0, `${entry} and all it reaches use no DOM global (${hits.join(', ') || 'none'})`)
}
-console.log('the PowerPoint writer stays off the import page')
+console.log('no app shell carries the converter')
{
- // bento.page/import bundles api.ts, never export.ts. These strings exist
- // only in the writer (package parts PowerPoint requires), so finding one
- // in the page's bundle means the writer leaked into it.
- const r = spawnSync(esbuild, [path.join(root, 'convert/page/import-page.ts'), '--bundle', '--format=esm', '--minify',
- '--platform=browser', '--log-level=error'], { encoding: 'utf8' })
- const leaked = ['presProps', 'notesMaster', 'tableStyles'].filter((w) => (r.stdout ?? '').includes(w))
- ok(r.status === 0 && r.stdout.length > 1000 && leaked.length === 0,
- `the page bundle carries no part of the writer (${leaked.join(', ') || 'none found'})`)
+ // The rule is about what SHIPS in a document. Source imports are checked
+ // above; this checks the built shells themselves, for any app that has
+ // been built. These strings exist only in the PowerPoint writer and the
+ // importer (package part names), never in an app.
+ const shells: Record<string, string> = {
+ slides: 'slides/dist-single/Bento_Slides.bento.html', dash: 'dash/dist-single/Bento_Dash.bento.html',
+ spaces: 'spaces/dist-single/Bento_Spaces.bento.html', type: 'type/dist-single/Bento_Type.bento.html',
+ }
+ const inCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS
+ let seen = 0
+ for (const [app, rel] of Object.entries(shells)) {
+ const f = path.join(root, rel)
+ if (!fs.existsSync(f)) continue
+ seen++
+ // the runtime ships deflated, so look inside the payloads, not the text
+ const html = fs.readFileSync(f, 'utf8')
+ // (base-86 since 1.1.1, base64 before; scripts/lib/b86.mjs is the codec)
+ const blocks = [...html.matchAll(/<script[^>]*type="bento\/deflate-(b64|b86)"[^>]*>([^<]*)<\/script>/g)]
+ const payloads = blocks.map((m) => zlib.inflateRawSync(m[1] === 'b86' ? Buffer.from(b86decode(m[2].trim())) : Buffer.from(m[2].trim(), 'base64')).toString('utf8')).join('\n')
+ // non-vacuous: the runtime really was found and inflated (an unreadable
+ // payload once made this check pass by looking at nothing)
+ ok(blocks.length > 0 && payloads.length > 100_000, `${app}: ${blocks.length} runtime payload(s) inflated, ${Math.round(payloads.length / 1024)} KB of code read`)
+ const hits = ['presProps.xml', 'notesMaster', 'ppt/slides/', 'slideLayout'].filter((w) => html.includes(w) || payloads.includes(w))
+ ok(hits.length === 0, `${app}: the built shell carries no converter (${hits.join(', ') || 'none found'})`)
+ }
+ ok(seen > 0 || !inCI, `checked ${seen} built shell(s)${seen ? '' : ' (none built locally; CI builds slides first)'}`)
}
console.log(`\n${checks - failures}/${checks} checks passed`)
diff --git a/scripts/test-convert/cli.ts b/scripts/test-convert/cli.ts
index ac4015eb..00c01af7 100644
--- a/scripts/test-convert/cli.ts
+++ b/scripts/test-convert/cli.ts
@@ -131,6 +131,19 @@ console.log('the report, and document JSON in')
ok(/morph-not-exported \(slide 1\)/.test(j.err), 'each report line names the slides it happened on')
}
+console.log('--states')
+{
+ const base = docOf(fs.readFileSync(imported, 'utf8'))
+ base.slides.push({ ...base.slides[0], id: 'st', stateOf: base.slides[0].id, notes: 'state' })
+ const f = path.join(tmp, 'states.bento.html')
+ fs.writeFileSync(f, deckWith(base))
+ const count = async (p: string) => [...(await readZip(new Uint8Array(fs.readFileSync(p)))).keys()].filter((k) => /^ppt\/slides\/slide\d+\.xml$/.test(k)).length
+ run([f, '--to', 'pptx', '-o', path.join(tmp, 'no-states.pptx')])
+ const r = run([f, '--to', 'pptx', '--states', '-o', path.join(tmp, 'states.pptx')])
+ const a = await count(path.join(tmp, 'no-states.pptx')), b = await count(path.join(tmp, 'states.pptx'))
+ ok(r.code === 0 && b === a + 1 && /states-as-hidden-slides/.test(r.err), `--states adds the state as a hidden slide (${a} → ${b} slides)`)
+}
+
console.log('export refusals, each saying what to do')
{
const refuse = (name: string, doc: unknown, want: RegExp, msg: string) => {
diff --git a/scripts/test-convert/import-page.ts b/scripts/test-convert/convert-page.ts
similarity index 75%
rename from scripts/test-convert/import-page.ts
rename to scripts/test-convert/convert-page.ts
index d2925dd4..8365377b 100644
--- a/scripts/test-convert/import-page.ts
+++ b/scripts/test-convert/convert-page.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
-// bento.page/import rig: the BUILT page keeps the promise it prints.
+// bento.page/convert rig: the BUILT page keeps the promise it prints, and
+// bento.page/import still lands there.
//
// The page says the file never leaves the device. The enforcement is its
// Content Security Policy — `connect-src 'self'` means the browser itself
@@ -32,9 +33,9 @@ function ok(cond: boolean, msg: string) {
}
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-import-rig-'))
-const out = path.join(tmp, 'import/index.html')
-const b = spawnSync(process.execPath, [path.join(root, 'scripts/build-import-page.mjs'), out], { encoding: 'utf8' })
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-convert-rig-'))
+const out = path.join(tmp, 'convert/index.html')
+const b = spawnSync(process.execPath, [path.join(root, 'scripts/build-convert-page.mjs'), out], { encoding: 'utf8' })
ok(b.status === 0 && fs.existsSync(out), `the page builds (exit ${b.status}${b.stderr ? ': ' + b.stderr.trim() : ''})`)
const html = fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : ''
const sha = (s: string) => `'sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}'`
@@ -62,9 +63,9 @@ const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)]
ok(scripts.length === 1 && !/\bsrc=/.test(scripts[0][1]), `one inline script, no src (${scripts.length})`)
const js = scripts[0]?.[2] ?? ''
ok(is('script-src', [sha(js)]), 'script-src is exactly the hash of the inline script')
-const styles = [...html.matchAll(/<style>([\s\S]*?)<\/style>/g)]
+const styles = [...html.replace(js, '').matchAll(/<style>([\s\S]*?)<\/style>/g)]
ok(styles.length === 1 && is('style-src', [sha(styles[0][1])]), 'one <style>, and style-src is exactly its hash')
-ok(!/\sstyle="/.test(html), 'no inline style attributes (the hashed policy would drop them)')
+ok(!/\sstyle="/.test(html.replace(js, '')), 'no inline style attributes (the hashed policy would drop them)')
ok(!/\son[a-z]+=/i.test(html.replace(js, '')), 'no inline event handlers')
console.log('what it loads')
@@ -81,6 +82,21 @@ ok(urls.every(u => u === 'https://bento.page/releases/slides/manifest.json'),
ok(!/\b(XMLHttpRequest|WebSocket|EventSource|sendBeacon|RTCPeerConnection)\b/.test(js), 'no second network API in the bundle')
ok(/nothing is uploaded|never leaves/i.test(markup), 'the page says so in words')
+console.log('what the page offers')
+ok(/id="sample"/.test(markup) && /A little more portable/.test(js), 'the sample deck is built in (nothing fetched for it)')
+ok(/<a [^>]*href="\/slides\/"/.test(markup), 'the header links the editor, like the rest of bento.page')
+
+console.log('bento.page/import still works')
+{
+ const redirect = fs.readFileSync(path.join(root, 'site-src/import.html'), 'utf8')
+ ok(!/<script/i.test(redirect), 'the /import page runs no script at all')
+ ok(/<meta http-equiv="refresh" content="0; url=\/convert\?from=pptx">/.test(redirect), 'it sends the browser to /convert?from=pptx at once')
+ ok(/<a href="\/convert\?from=pptx">/.test(redirect), 'and links there for a browser that ignores refresh')
+ ok(/content="default-src 'none'; base-uri 'none'; form-action 'none'"/.test(redirect), "its CSP allows nothing to load (default-src 'none')")
+ ok(/from'\) === 'pptx'/.test(fs.readFileSync(path.join(root, 'convert/page/convert-page.ts'), 'utf8')),
+ '/convert reads ?from=pptx and greets an /import visitor with the import wording')
+}
+
fs.rmSync(tmp, { recursive: true, force: true })
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-convert/pairs.ts b/scripts/test-convert/pairs.ts
new file mode 100644
index 00000000..0c0c642c
--- /dev/null
+++ b/scripts/test-convert/pairs.ts
@@ -0,0 +1,108 @@
+// @bundle — reaches slides' model, compact expander and gate (extensionless imports)
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The conversion table behind bento.page/convert, run under node: what each
+// input is recognised as, what it is offered, why something is refused, and
+// each pair run end to end. Running it here, with no DOM, is also the proof
+// that every conversion path is DOM-free (the page only adds the File API).
+
+import fs from 'node:fs'
+import path from 'node:path'
+import { detect, describe, optionsFor, nothingFor, CONVERSIONS, type Env } from '../../convert/src/pairs.ts'
+import { extractDoc } from '../../convert/src/deliver.ts'
+import { loadDocJson } from '../../convert/page/load-json.ts'
+import { SAMPLE_DECK } from '../../convert/page/sample-deck.ts'
+import { fxMinimal } from './_fixtures.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}`)
+}
+
+// Bundled rigs run from a temp copy, so find the repo from where we were run.
+let root = process.cwd()
+while (!fs.existsSync(path.join(root, 'scripts/test-convert')) && path.dirname(root) !== root) root = path.dirname(root)
+const shellPath = path.join(root, 'slides/dist-single/Bento_Slides.bento.html')
+const inCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS
+const haveShell = fs.existsSync(shellPath)
+if (!haveShell && inCI) { console.log(' FAIL no built slides shell — cannot skip in CI'); process.exit(1) }
+let shellCalls = 0
+const env: Env = {
+ async shell() { shellCalls++; return { version: 'local', html: fs.readFileSync(shellPath, 'utf8') } },
+ loadDocJson,
+}
+const enc = new TextEncoder()
+const ids = (d: ReturnType<typeof detect>) => optionsFor(d).filter((o) => o.ok).map((o) => o.conversion.id)
+const BLOCK = '<script type="application/bento+json" id="bento-doc">'
+const wrap = (doc: unknown) => `<!doctype html><html><head>${BLOCK}${JSON.stringify(doc).replace(/</g, '\\u003c')}</` + `script></head></html>`
+const sample = JSON.parse(SAMPLE_DECK)
+
+console.log('recognising inputs')
+const pptx = await fxMinimal()
+{
+ const d = detect('deck.pptx', pptx)
+ ok(d.kind === 'pptx' && JSON.stringify(ids(d)) === '["pptx-to-slides"]', `a .pptx is offered a bento/slides deck (${ids(d)})`)
+ ok(detect('deck.xlsx', pptx).kind === 'unknown', 'a zip that is not a .pptx is not taken for one')
+ const html = detect('deck.bento.html', enc.encode(wrap(sample)))
+ ok(html.kind === 'bento' && html.source === 'html' && JSON.stringify(ids(html)) === '["slides-to-pptx"]', `a .bento.html deck is offered PowerPoint (${ids(html)})`)
+ const json = detect('deck.json', enc.encode(SAMPLE_DECK))
+ ok(json.kind === 'bento' && json.source === 'json' && JSON.stringify(ids(json)) === '["slides-to-pptx","json-to-slides"]',
+ `document JSON is offered PowerPoint AND a deck (${ids(json)})`)
+ ok(describe(json).meta.startsWith('3 slides · 1280 × 720 px'), `the file card says what it is ("${describe(json).meta}")`)
+ const compact = detect('c.json', enc.encode(JSON.stringify({ format: 'bento/slides', compact: true, slides: [] })))
+ const c = optionsFor(compact)
+ const pp = c.find((o) => o.conversion.id === 'slides-to-pptx')
+ ok(!!pp && !pp.ok && /compact/.test(pp.why) && c.some((o) => o.ok && o.conversion.id === 'json-to-slides'),
+ 'compact JSON: PowerPoint is shown but explained, and making a deck is offered')
+ const spaces = detect('notes.bento.html', enc.encode(wrap({ format: 'bento/spaces', pages: [] })))
+ ok(spaces.kind === 'bento' && optionsFor(spaces).length === 0 && /^There is no conversion for bento\/spaces files yet\.$/.test(nothingFor(spaces)),
+ `another app's file is recognised and told plainly ("${nothingFor(spaces)}")`)
+ const locked = detect('locked.bento.html', enc.encode(wrap({ format: 'bento/enc', v: 1 })))
+ ok(optionsFor(locked).length === 0 && /password/.test(nothingFor(locked)), 'a password-protected file is told what to do')
+ ok(detect('x.html', enc.encode('<p>hello</p>')).kind === 'unknown', 'an ordinary web page is not a Bento file')
+ ok(detect('x.json', enc.encode('{"a":')).kind === 'unknown', 'broken JSON is refused in words')
+}
+
+console.log('choices a pair takes')
+{
+ const flagFor = (doc: unknown) => (CONVERSIONS.find((c) => c.id === 'slides-to-pptx')!.flags ?? []).filter((f) => f.applies(detect('d.json', enc.encode(JSON.stringify(doc))))).map((f) => f.id)
+ const withState = { ...sample, slides: [...sample.slides, { ...sample.slides[0], id: 'st', stateOf: sample.slides[0].id }] }
+ ok(JSON.stringify(flagFor(sample)) === '[]' && JSON.stringify(flagFor(withState)) === '["states"]',
+ 'the states choice is offered only for a deck that has states')
+ const c = CONVERSIONS.find((x) => x.id === 'slides-to-pptx')!
+ const d = detect('d.json', enc.encode(JSON.stringify(withState)))
+ const off = await c.run(d, env), on = await c.run(d, env, { states: true })
+ const n = (r: typeof off) => r.stats.find((s) => s.label === 'slides')!.value
+ ok(n(off) === 3 && n(on) === 4, `ticking it adds the state as a slide (${n(off)} → ${n(on)})`)
+}
+
+console.log('running each pair')
+{
+ const d = detect('sample.json', enc.encode(SAMPLE_DECK))
+ const toPptx = CONVERSIONS.find((c) => c.id === 'slides-to-pptx')!
+ shellCalls = 0
+ const r = await toPptx.run(d, env)
+ ok(r.fileName === 'sample.pptx' && r.bytes[0] === 0x50 && shellCalls === 0, `slides → .pptx needs no network (${r.fileName}, shell fetched ${shellCalls}×)`)
+ const st = Object.fromEntries(r.stats.map((s) => [s.label, s.value]))
+ ok(st.slides === 3 && st['editable objects'] > 10, `with stats (${JSON.stringify(st)})`)
+}
+if (haveShell) {
+ const toDeck = CONVERSIONS.find((c) => c.id === 'pptx-to-slides')!
+ const r = await toDeck.run(detect('deck.pptx', pptx), env)
+ const doc = extractDoc(new TextDecoder().decode(r.bytes)) as { format?: string }
+ ok(r.fileName === 'deck.bento.html' && doc.format === 'bento/slides', '.pptx → .bento.html builds a deck on the shell')
+ const json = CONVERSIONS.find((c) => c.id === 'json-to-slides')!
+ const compactDoc = { format: 'bento/slides', compact: true, title: 'C', slides: [{ elements: [{ type: 'text', html: 'Hello' }] }] }
+ const cr = await json.run(detect('c.json', enc.encode(JSON.stringify(compactDoc))), env)
+ const cdoc = extractDoc(new TextDecoder().decode(cr.bytes)) as { format?: string; slides?: unknown[] }
+ ok(cdoc.format === 'bento/slides' && cdoc.slides?.length === 1, 'compact JSON → .bento.html expands into a full deck')
+ ok(cr.report.entries.some((e) => e.code === 'text-height-provisional' && e.where === 'slide 1'),
+ 'a text box nothing measured is reported, on its slide')
+} else console.log(' ⚠ SKIPPED shell pairs — no built shell (cd slides && npm run build:single)')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-code-embed.ts b/scripts/test-convert/pptx-code-embed.ts
new file mode 100644
index 00000000..a1735c57
--- /dev/null
+++ b/scripts/test-convert/pptx-code-embed.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// code → editable text, embed → a picture of its view.
+//
+// node scripts/test-convert/pptx-code-embed.ts
+
+import { exportOne, exportDeck, deck, frame } from './_export-harness.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 MONO = "ui-monospace, 'SFMono-Regular', 'Berkeley Mono', 'Menlo', 'Consolas', monospace"
+const code = (content: string, extra: object = {}) => ({
+ type: 'code', fontSize: 19, fontFamily: MONO, align: 'left', valign: 'top', lineHeight: 1.62,
+ color: '#DCE3EC', content, grammarName: 'js', ...extra,
+})
+/** the visible lines of every text body: paragraphs and line breaks both end a line */
+const paras = (xml: string) => [...xml.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)].flatMap((m) =>
+ m[1].split(/<a:br>[\s\S]*?<\/a:br>|<a:br\/>/).map((l) => [...l.matchAll(/<a:t>([^<]*)<\/a:t>/g)].map((t) => t[1]).join('')))
+const NB = ' '
+
+console.log('code')
+{
+ const r = await exportOne(code('load(deck, (slides) => {\n render(slides)\n\tdone()\n})'))
+ const p = paras(r.slideXml)
+ ok(r.problems.length === 0 && /<p:sp>/.test(r.slideXml), 'a code element becomes a text shape, package clean')
+ ok(p.length === 4, `one line per source line (${p.length})`)
+ ok(p[1] === `${NB}${NB}render(slides)`, `leading spaces survive as no-break spaces (${JSON.stringify(p[1])})`)
+ ok(p[2] === `${NB.repeat(8)}done()`, `a tab expands to the next 8-column stop (${JSON.stringify(p[2])})`)
+ ok(/typeface="Consolas"/.test(r.slideXml) && !/ui-monospace|Berkeley/.test(r.slideXml), 'slides\' monospace stack is written as Consolas')
+ ok(/<a:bodyPr[^>]*wrap="none"/.test(r.slideXml), 'long lines do not wrap (wrap="none"), as in slides')
+ ok(/<a:srgbClr val="DCE3EC"/.test(r.slideXml), 'the element colour is kept')
+ ok(r.codes.has('code-colours-flattened') && !r.codes.has('element-unsupported'), 'lost syntax colours are reported, nothing else dropped')
+}
+{
+ const r = await exportOne(code('if (a < b && c > "d") {{page}}'))
+ ok(r.problems.length === 0 && paras(r.slideXml)[0] === 'if (a &lt; b &amp;&amp; c &gt; "d") {{page}}',
+ `<, & and > are escaped once, single spaces stay ordinary, {{tokens}} stay literal (${JSON.stringify(paras(r.slideXml)[0])})`)
+ const dbl = paras((await exportOne(code('a b'))).slideXml)[0]
+ ok(dbl === `a ${NB}b`, `a run of spaces keeps its width (${JSON.stringify(dbl)})`)
+ const plain = await exportOne(code('x', { grammarName: undefined }))
+ ok(!plain.codes.has('code-colours-flattened'), 'plain code with no highlighting reports no lost colours')
+ const empty = await exportOne(code(''))
+ ok(empty.problems.length === 0 && !empty.codes.has('code-colours-flattened'), 'an empty code box exports clean')
+}
+
+console.log('embed')
+const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10" fill="#f00"/></svg>'
+{
+ const r = await exportOne({ type: 'embed', app: 'bento/dash', view: SVG })
+ ok(r.problems.length === 0 && /<p:pic>/.test(r.slideXml) && [...r.parts.keys()].some((k) => /^ppt\/media\/.*\.svg$/.test(k)),
+ 'an embed becomes a picture with its SVG in the package')
+ ok(r.codes.has('embed-static') && /bento\/dash document shows as a picture/.test(r.report.entries.find((e) => e.code === 'embed-static')!.detail),
+ 'it is reported as a static picture, naming the app')
+}
+{
+ const d = deck([{ id: 'e1', ...frame(80, 80, 300, 200), type: 'embed', app: 'bento/type', view: 'asset:v1' }], { assets: { v1: SVG } })
+ const r = await exportDeck(d)
+ ok(r.problems.length === 0 && /<p:pic>/.test(r.slideXml), 'a view stored as an asset is found and placed')
+}
+{
+ const r = await exportOne({ type: 'embed', app: 'web', view: '', url: 'https://example.com' })
+ ok(r.problems.length === 0 && !/<p:pic>/.test(r.slideXml) && r.codes.has('embed-no-view'), 'an embed with no view is reported dropped, never silently')
+ const bad = await exportOne({ type: 'embed', app: 'web', view: '<img src=x onerror=alert(1)>' })
+ ok(!/<p:pic>/.test(bad.slideXml) && bad.codes.has('embed-no-view'), 'a view that is not SVG is not embedded')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-coverage.ts b/scripts/test-convert/pptx-coverage.ts
index 59a8c33a..4e799900 100644
--- a/scripts/test-convert/pptx-coverage.ts
+++ b/scripts/test-convert/pptx-coverage.ts
@@ -45,6 +45,9 @@ const SAMPLE: Record<string, object> = {
table: { type: 'table', columns: [{ w: 1 }], header: false, rows: [{ cells: [{ html: 'x' }] }], style: { radius: 0 } },
// media exports its poster as a picture; playback itself is not written yet
// (reported 'media-dropped' — a contributor task, see CONTRIBUTING.md)
+ code: { type: 'code', fontSize: 18, fontFamily: 'Menlo, monospace', align: 'left', valign: 'top',
+ lineHeight: 1.4, color: '#1E2A3A', content: 'let x = 1\nx += 1' },
+ embed: { type: 'embed', app: 'bento/dash', view: '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' },
media: { type: 'media', kind: 'video', src: 'data:video/mp4;base64,AAAA',
poster: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' },
}
@@ -52,11 +55,7 @@ const MAPPED = Object.keys(SAMPLE)
/** Types with no writer yet. Each is a task a contributor can take; see
* convert/CONTRIBUTING.md. Their writers report them dropped. */
-const NOT_YET: Record<string, object> = {
- code: { type: 'code', fontSize: 18, fontFamily: 'Menlo, monospace', align: 'left', valign: 'top',
- lineHeight: 1.4, color: '#1E2A3A', content: 'let x = 1\nx += 1' },
- embed: { type: 'embed', app: 'bento/dash', view: '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' },
-}
+const NOT_YET: Record<string, object> = {}
// --- what slides says exists -------------------------------------------------
const model = fs.readFileSync(path.join(root, 'slides/src/model.ts'), 'utf8')
@@ -104,6 +103,6 @@ console.log('a type nobody has heard of')
'an unknown future element type degrades to a report entry; the export still succeeds')
}
-console.log(`\nopen for contributors: ${Object.keys(NOT_YET).join(', ')}`)
+console.log(`\nopen for contributors: ${Object.keys(NOT_YET).join(', ') || 'none — every element type exports'}`)
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-raster.ts b/scripts/test-convert/pptx-raster.ts
new file mode 100644
index 00000000..92feb814
--- /dev/null
+++ b/scripts/test-convert/pptx-raster.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Pictures PowerPoint cannot take (WebP and kin) and the host's rasteriser.
+// The real rasteriser is a browser canvas (convert/page/rasterise.ts, driven
+// in the page's browser test); here a stand-in records what it was asked.
+//
+// node scripts/test-convert/pptx-raster.ts
+
+import { exportDeck, deck, frame, type Exported } from './_export-harness.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 PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
+const WEBP = 'data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=='
+const WEBP2 = 'data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAB=='
+const SVG = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='
+const img = (id: string, src: string) => ({ id, type: 'image', ...frame(80, 80, 200, 150), src, fit: 'fill' })
+
+function twoSlides() {
+ const d = deck([img('a', WEBP), img('b', PNG), img('c', 'asset:w')], { assets: { w: WEBP2 } })
+ d.slides.push({ id: 's2', background: '#ffffff', elements: [img('d', WEBP) as never,
+ { id: 'm', type: 'media', kind: 'video', src: 'data:video/mp4;base64,AAAA', poster: WEBP2, ...frame(300, 80, 200, 150) } as never,
+ img('e', SVG) as never] })
+ return d
+}
+const pics = (r: Exported, n: number) => (new TextDecoder().decode(r.parts.get(`ppt/slides/slide${n}.xml`)!).match(/<p:pic>/g) ?? []).length
+const where = (r: Exported, code: string) => r.report.entries.filter((e) => e.code === code).map((e) => e.where).sort()
+
+console.log('with a rasteriser')
+{
+ const asked: string[] = []
+ const r = await exportDeck(twoSlides(), { rasterise: async (u) => { asked.push(u); return PNG } })
+ ok(asked.length === 2 && asked.includes(WEBP) && asked.includes(WEBP2), `each distinct WebP is converted once (${asked.length} calls for 4 uses)`)
+ ok(!asked.some((u) => u.startsWith('data:image/png') || u.startsWith('data:image/svg')), 'PNG and SVG are never sent to the rasteriser')
+ ok(r.problems.length === 0 && pics(r, 1) === 3 && pics(r, 2) === 3, `every picture lands, package clean (slide 1: ${pics(r, 1)}, slide 2: ${pics(r, 2)})`)
+ ok(!r.codes.has('missing-image'), 'nothing is dropped')
+ ok(JSON.stringify(where(r, 'image-converted-png')) === '["slide 1","slide 2"]', `the conversion is reported on the slides it happened on (${where(r, 'image-converted-png')})`)
+ ok(![...r.parts.keys()].some((k) => /\.webp$/i.test(k)), 'no WebP part enters the package')
+}
+for (const [label, fn] of [
+ ['returns null', async () => null],
+ ['throws', async () => { throw new Error('decode failed') }],
+ ['returns something that is not a PNG', async () => 'data:image/jpeg;base64,AAAA'],
+] as Array<[string, (u: string) => Promise<string | null>]>) {
+ const r = await exportDeck(deck([img('a', WEBP)]), { rasterise: fn })
+ const e = r.report.entries.find((x) => x.code === 'missing-image')
+ ok(r.problems.length === 0 && pics(r, 1) === 0 && !!e && /could not be converted/.test(e.detail), `a rasteriser that ${label}: the picture is reported dropped, never written`)
+}
+
+console.log('without one (the CLI)')
+{
+ const r = await exportDeck(deck([img('a', WEBP)]))
+ const e = r.report.entries.find((x) => x.code === 'missing-image')
+ ok(r.problems.length === 0 && pics(r, 1) === 0 && !!e && /need converting to PNG/.test(e.detail) && /bento\.page\/convert/.test(e.detail),
+ `WebP is reported dropped, with where it can be converted ("${e?.detail}")`)
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-report.ts b/scripts/test-convert/pptx-report.ts
index 327fbb83..d6badd2c 100644
--- a/scripts/test-convert/pptx-report.ts
+++ b/scripts/test-convert/pptx-report.ts
@@ -57,6 +57,7 @@ for (const [stack, want] of [
['Georgia, serif', 'Georgia'],
['serif', 'Times New Roman'],
['Menlo', 'Menlo'],
+ ["ui-monospace, 'SFMono-Regular', 'Berkeley Mono', 'Menlo', 'Consolas', monospace", 'Consolas'],
['', 'Arial'],
] as Array<[string, string]>) ok(typefaceOf(stack) === want, `${JSON.stringify(stack)} → ${want} (got ${typefaceOf(stack)})`)
diff --git a/scripts/test-convert/pptx-shapes.ts b/scripts/test-convert/pptx-shapes.ts
index 2cb42412..a794db82 100644
--- a/scripts/test-convert/pptx-shapes.ts
+++ b/scripts/test-convert/pptx-shapes.ts
@@ -17,7 +17,7 @@ import { parseXml, kids, kid, attr, NS, type XElem } from '../../convert/src/xml
import { serialize, x } from '../../convert/src/xmlout.ts'
import { PML_XMLNS } from '../../convert/src/pptx-write/parts.ts'
import { Report } from '../../convert/src/report.ts'
-import {
+import { arcToCubics,
emu, xfrmNode, parseColor, solidFill, cssAngleToOoxml, shapeNode, type ShapeIn,
} from '../../convert/src/pptx-write/shapes.ts'
@@ -314,15 +314,57 @@ console.log('custGeom (path shapes)')
const el = shape({ shape: 'path', d: 'M0 0 A5 5 0 0 1 10 0 L10 5', pathBox: [0, 0, 10, 5] })
const sp = emit(el, r)
const path = kid(kid(kid(spPr(sp), NS.a, 'custGeom')!, NS.a, 'pathLst')!, NS.a, 'path')!
- ok(codes(r).includes('path-approximated'), 'NEGATIVE: an arc command reports path-approximated')
- const firstLn = kids(path, NS.a, 'lnTo')[0]
- const pt = kid(firstLn, NS.a, 'pt')!
- ok(attr(pt, 'x') === '95250' && attr(pt, 'y') === '0', 'NEGATIVE: the arc degrades to a line to its ENDPOINT — parseable geometry, not garbage')
+ // A5 5 0 0 1 10 0 from (0,0) is a half circle about (5,0): two quarter
+ // cubics, through (5,-5) (positive sweep, y down), ending exactly on (10,0)
+ ok(!codes(r).includes('path-approximated'), 'an arc is drawn exactly, so nothing is reported')
+ const cubs = kids(path, NS.a, 'cubicBezTo')
+ ok(cubs.length === 2, `a half-circle arc becomes two quarter-turn cubics (${cubs.length})`)
+ const end = (c: XElem) => kids(c, NS.a, 'pt')[2]
+ ok(attr(end(cubs[0]), 'x') === String(emu(5)) && attr(end(cubs[0]), 'y') === String(-emu(5)), `it passes through the top of the circle (${attr(end(cubs[0]), 'x')}, ${attr(end(cubs[0]), 'y')})`)
+ ok(attr(end(cubs[1]), 'x') === String(emu(10)) && attr(end(cubs[1]), 'y') === '0', 'and lands exactly on the arc endpoint')
const nums = path.children.filter((c) => typeof c !== 'string')
.flatMap((c) => kids(c as XElem, NS.a, 'pt'))
.flatMap((p) => [attr(p, 'x'), attr(p, 'y')])
ok(nums.every((n) => n !== undefined && /^-?\d+$/.test(n)), 'NEGATIVE: every emitted coordinate is a plain integer (no NaN leaked)')
}
+{
+ // a minifier writes arc flags run together: "0 01" is flags 0, 1 — read as
+ // one number they shifted every coordinate after them (and crashed export)
+ const a = new Report(), b = new Report()
+ const spread = emit(shape({ shape: 'path', d: 'M0 0 A5 5 0 0 1 10 0', pathBox: [0, 0, 10, 5] }), a)
+ const packed = emit(shape({ shape: 'path', d: 'M0 0a5 5 0 0110 0', pathBox: [0, 0, 10, 5] }), b)
+ const geo = (sp: XElem) => JSON.stringify(kid(kid(spPr(sp), NS.a, 'custGeom')!, NS.a, 'pathLst'))
+ ok(geo(spread) === geo(packed) && !codes(b).includes('path-approximated'), 'run-together arc flags ("0110 0") read as 0, 1, then 10 0')
+ // and where the flags run into a decimal: "00.5.5" is flags 0, 0, then .5 .5
+ const c = new Report(), d = new Report()
+ const spread2 = emit(shape({ shape: 'path', d: 'M0 0 a.5 .5 0 0 0 .5 .5', pathBox: [0, 0, 1, 1] }), c)
+ const packed2 = emit(shape({ shape: 'path', d: 'M0 0a.5.5 0 00.5.5', pathBox: [0, 0, 1, 1] }), d)
+ ok(geo(spread2) === geo(packed2) && !codes(d).includes('path-approximated'), 'flags run into a decimal ("00.5.5") read as 0, 0, then .5 .5')
+}
+{
+ // the side of the centre matters on any arc that is not a half circle:
+ // A10 10 0 0 1 10 10 from (0,0) is a quarter turn about (0,10), not (10,0)
+ const curves = arcToCubics(0, 0, 10, 10, 0, 0, 1, 10, 10)!
+ const [c] = curves
+ const mid = [0.125 * 0 + 0.375 * c[0] + 0.375 * c[2] + 0.125 * c[4], 0.125 * 0 + 0.375 * c[1] + 0.375 * c[3] + 0.125 * c[5]]
+ const dist = (x: number, y: number) => Math.hypot(mid[0] - x, mid[1] - y)
+ ok(curves.length === 1 && Math.abs(dist(0, 10) - 10) < 0.05 && Math.abs(dist(10, 0) - 10) > 1,
+ `a quarter arc curves about the right centre (midpoint ${mid.map((v) => v.toFixed(2))}, ${dist(0, 10).toFixed(3)} from (0,10))`)
+ // the same endpoints with sweep 0 turn the other way, about (10,0)
+ const [d] = arcToCubics(0, 0, 10, 10, 0, 0, 0, 10, 10)!
+ const m2 = [0.375 * d[0] + 0.375 * d[2] + 0.125 * d[4], 0.375 * d[1] + 0.375 * d[3] + 0.125 * d[5]]
+ ok(Math.abs(Math.hypot(m2[0] - 10, m2[1]) - 10) < 0.05 && Math.abs(Math.hypot(m2[0], m2[1] - 10) - 10) > 1,
+ `with sweep 0 it curves about the other centre (midpoint ${m2.map((v) => v.toFixed(2))})`)
+}
+{
+ // a path that runs out of arguments must not cost the whole export
+ const r = new Report()
+ const sp = emit(shape({ shape: 'path', d: 'M0 0 L10 0 C1 2 3', pathBox: [0, 0, 10, 5] }), r)
+ const path = kid(kid(kid(spPr(sp), NS.a, 'custGeom')!, NS.a, 'pathLst')!, NS.a, 'path')!
+ const nums = path.children.filter((c) => typeof c !== 'string').flatMap((c) => kids(c as XElem, NS.a, 'pt')).flatMap((p) => [attr(p, 'x'), attr(p, 'y')])
+ ok(codes(r).includes('path-approximated') && kids(path, NS.a, 'lnTo').length === 1 && nums.every((n) => /^-?\d+$/.test(n ?? '')),
+ 'a truncated path keeps its good segments, is reported, and writes no NaN')
+}
{
const r = new Report()
emit(shape({ shape: 'path', d: 'M0 0 W nonsense', pathBox: [0, 0, 10, 5] }), r)
diff --git a/scripts/test-convert/pptx-states.ts b/scripts/test-convert/pptx-states.ts
new file mode 100644
index 00000000..b169c9c3
--- /dev/null
+++ b/scripts/test-convert/pptx-states.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Interactive states: left out by default (links go to the parent), or with
+// includeStates, hidden slides right after their parent that links lead to.
+//
+// node scripts/test-convert/pptx-states.ts
+
+import { exportDeck, partText, frame, type Exported } from './_export-harness.ts'
+import type { ExportDoc } from '../../convert/src/pptx-write/index.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 text = (id: string, html: string) => ({ id, type: 'text', ...frame(80, 80, 400, 60), html, fontSize: 24,
+ fontFamily: 'Inter, sans-serif', fontWeight: 400, color: '#1e2a3a', align: 'left', valign: 'top', lineHeight: 1.2 })
+const button = (id: string, link: string) => ({ id, type: 'shape', ...frame(80, 300, 200, 60), shape: 'rect',
+ fill: '#ff7a59', stroke: '#000000', strokeWidth: 0, radius: 0, link })
+
+const doc = (): ExportDoc => ({
+ title: 'States', size: { width: 1280, height: 720 },
+ theme: { background: '#ffffff', color: '#1e2a3a', accent: '#ff7a59', fontFamily: 'Inter, sans-serif' },
+ slides: [
+ { id: 'a', background: '#ffffff', notes: 'A notes', elements: [text('t1', 'Page {{page}}'), button('b1', 'a-detail')] as never },
+ { id: 'a-detail', stateOf: 'a', background: '#ffffff', notes: 'detail notes', elements: [text('t2', 'Detail on {{page}}'), button('back', 'a')] as never },
+ { id: 'b', background: '#ffffff', elements: [text('t3', 'Page {{page}}'), button('b2', 'a-detail')] as never },
+ ],
+})
+
+/** slide n's link targets, as slide numbers */
+const jumps = (r: Exported, n: number) => [...partText(r.parts, `ppt/slides/_rels/slide${n}.xml.rels`).matchAll(/Target="\.\.\/slides\/slide(\d+)\.xml"/g)].map((m) => Number(m[1]))
+const hidden = (r: Exported, n: number) => /<p:sld\b[^>]*\bshow="0"/.test(partText(r.parts, `ppt/slides/slide${n}.xml`))
+const textOf = (r: Exported, n: number) => [...partText(r.parts, `ppt/slides/slide${n}.xml`).matchAll(/<a:t>([^<]*)<\/a:t>/g)].map((m) => m[1]).join('')
+const slideCount = (r: Exported) => [...r.parts.keys()].filter((k) => /^ppt\/slides\/slide\d+\.xml$/.test(k)).length
+
+console.log('default: states left out')
+{
+ const r = await exportDeck(doc())
+ ok(r.problems.length === 0 && slideCount(r) === 2, `2 slides (${slideCount(r)})`)
+ ok(JSON.stringify(jumps(r, 1)) === '[1]' && JSON.stringify(jumps(r, 2)) === '[1]', `links into the state go to its parent (slide 1: ${jumps(r, 1)}, slide 2: ${jumps(r, 2)})`)
+ ok(r.codes.has('state-slides-omitted') && !r.codes.has('states-as-hidden-slides'), 'reported as left out')
+}
+
+console.log('includeStates: hidden slides that links lead to')
+{
+ const r = await exportDeck(doc(), { includeStates: true })
+ ok(r.problems.length === 0 && slideCount(r) === 3, `3 slides, package clean (${slideCount(r)})`)
+ ok(/Detail on/.test(textOf(r, 2)), 'the state sits right after its parent (slide 2)')
+ ok(hidden(r, 2) && !hidden(r, 1) && !hidden(r, 3), 'the state is a hidden slide; the others are not')
+ ok(JSON.stringify(jumps(r, 1)) === '[2]' && JSON.stringify(jumps(r, 3)) === '[2]', `links into the state land on it (slide 1: ${jumps(r, 1)}, slide 3: ${jumps(r, 3)})`)
+ ok(JSON.stringify(jumps(r, 2)) === '[1]', `the state's own link back still reaches its parent (${jumps(r, 2)})`)
+ ok(/Page 1/.test(textOf(r, 1)) && /Detail on 1/.test(textOf(r, 2)) && /Page 2/.test(textOf(r, 3)),
+ `states take no page number of their own (${textOf(r, 2)}; ${textOf(r, 3)})`)
+ // PowerPoint numbers every slide, hidden ones too: where its number would
+ // differ from bento's page, the page is fixed text, not a live field
+ const live = (n: number) => /<a:fld [^>]*type="slidenum"/.test(partText(r.parts, `ppt/slides/slide${n}.xml`))
+ ok(live(1) && !live(2) && !live(3), `a live slide number only where PowerPoint counts the same (slide 1 live: ${live(1)}, 2: ${live(2)}, 3: ${live(3)})`)
+ ok(r.report.entries.some((e) => e.code === 'text-field-frozen' && e.where === 'slide 3'), 'the fixed page number is reported where it happened')
+ ok(r.parts.has('ppt/notesSlides/notesSlide2.xml') && /detail notes/.test(partText(r.parts, 'ppt/notesSlides/notesSlide2.xml')), "the state's speaker notes come along")
+ ok(r.codes.has('states-as-hidden-slides') && !r.codes.has('state-slides-omitted'), 'reported as hidden slides, not as left out')
+}
+
+console.log('a hidden slide (the same miscount, without any states)')
+{
+ const d = doc()
+ d.slides = [d.slides[0], { id: 'h', hidden: true, background: '#ffffff', elements: [] }, d.slides[2]]
+ const r = await exportDeck(d)
+ const live = (n: number) => /<a:fld [^>]*type="slidenum"/.test(partText(r.parts, `ppt/slides/slide${n}.xml`))
+ ok(/Page 2/.test(textOf(r, 3)) && !live(3) && live(1),
+ `after a hidden slide, bento's page 2 stays 2 as fixed text, where PowerPoint would count 3 (${textOf(r, 3)})`)
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-write.ts b/scripts/test-convert/pptx-write.ts
index aa5e6f54..70409208 100644
--- a/scripts/test-convert/pptx-write.ts
+++ b/scripts/test-convert/pptx-write.ts
@@ -399,6 +399,15 @@ console.log('negative controls')
noStyle.set('ppt/notesMasters/notesMaster1.xml', new TextEncoder().encode(
partText(parts, 'ppt/notesMasters/notesMaster1.xml').replace(/<p:notesStyle>[\s\S]*<\/p:notesStyle>/, '')))
ok(packageProblems(noStyle).some((p) => /notesStyle/.test(p)), 'NEGATIVE: the harness catches a notes master without notesStyle')
+ // not problems: a zip folder entry, and a rel target written from the
+ // package root ('/ppt/…'), which OPC allows and other writers use
+ const folder = new Map([...parts.entries()].flatMap(([k, v]) => k === 'ppt/presentation.xml' ? [['ppt/', new Uint8Array()], [k, v]] : [[k, v]])) as typeof parts
+ ok(packageProblems(folder).length === 0, 'a zip folder entry is not taken for an untyped part')
+ const abs = new Map(parts)
+ abs.set('ppt/_rels/presentation.xml.rels', new TextEncoder().encode(
+ partText(parts, 'ppt/_rels/presentation.xml.rels').replace(/Target="slides\/slide1\.xml"/, 'Target="/ppt/slides/slide1.xml"')))
+ ok(/Target="\/ppt\/slides\/slide1\.xml"/.test(partText(abs, 'ppt/_rels/presentation.xml.rels')) && packageProblems(abs).length === 0,
+ 'a rel target from the package root resolves')
const untyped = new Map(parts)
untyped.set('ppt/stray.bin', new Uint8Array([1]))
ok(packageProblems(untyped).some((p) => /stray\.bin has no content type/.test(p)), 'NEGATIVE: the harness catches an untyped part')
diff --git a/scripts/test-convert/rasterise.ts b/scripts/test-convert/rasterise.ts
new file mode 100644
index 00000000..c1e7501e
--- /dev/null
+++ b/scripts/test-convert/rasterise.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The page's rasteriser refuses a picture before anything decodes it when
+// its header declares more than MAX_PIXELS, or cannot be read: so a hostile
+// file can't make the browser's decoder allocate a giant bitmap. This pins
+// the header reader for each format, the cap, and the ORDER (the check runs
+// before `new Image()`). The decode itself runs in the page's browser test.
+//
+// node scripts/test-convert/rasterise.ts
+
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { imageSize } from '../../convert/page/image-size.ts'
+import { mayDecode, MAX_PIXELS } from '../../convert/page/rasterise.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 = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const bytes = (n: number) => new Uint8Array(n)
+const put = (b: Uint8Array, o: number, s: string) => { for (let i = 0; i < s.length; i++) b[o + i] = s.charCodeAt(i) }
+const be32 = (b: Uint8Array, o: number, v: number) => { b[o] = v >>> 24; b[o + 1] = (v >>> 16) & 255; b[o + 2] = (v >>> 8) & 255; b[o + 3] = v & 255 }
+const le32 = (b: Uint8Array, o: number, v: number) => { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = v >>> 24 }
+const le24 = (b: Uint8Array, o: number, v: number) => { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255 }
+const uri = (mime: string, b: Uint8Array) => `data:${mime};base64,${Buffer.from(b).toString('base64')}`
+
+function png(w: number, h: number) { const b = bytes(33); b[0] = 0x89; put(b, 1, 'PNG\r\n\x1a\n'); be32(b, 8, 13); put(b, 12, 'IHDR'); be32(b, 16, w); be32(b, 20, h); return b }
+function webpX(w: number, h: number) { const b = bytes(30); put(b, 0, 'RIFF'); put(b, 8, 'WEBP'); put(b, 12, 'VP8X'); le24(b, 24, w - 1); le24(b, 27, h - 1); return b }
+function webp8(w: number, h: number) { const b = bytes(30); put(b, 0, 'RIFF'); put(b, 8, 'WEBP'); put(b, 12, 'VP8 '); b[23] = 0x9d; b[24] = 1; b[25] = 0x2a; b[26] = w & 255; b[27] = (w >> 8) & 0x3f; b[28] = h & 255; b[29] = (h >> 8) & 0x3f; return b }
+function bmp(w: number, h: number) { const b = bytes(54); put(b, 0, 'BM'); le32(b, 18, w); le32(b, 22, -h); return b }
+function tiff(w: number, h: number, le: boolean) {
+ const b = bytes(40); put(b, 0, le ? 'II' : 'MM')
+ const w16 = (o: number, v: number) => { if (le) { b[o] = v & 255; b[o + 1] = v >> 8 } else { b[o] = v >> 8; b[o + 1] = v & 255 } }
+ const w32 = (o: number, v: number) => (le ? le32(b, o, v) : be32(b, o, v))
+ w16(2, 42); w32(4, 8); w16(8, 2)
+ w16(10, 256); w16(12, 4); w32(14, 1); w32(18, w)
+ w16(22, 257); w16(24, 4); w32(26, 1); w32(30, h)
+ return b
+}
+function avif(w: number, h: number) { const b = bytes(48); put(b, 4, 'ftyp'); put(b, 8, 'avif'); put(b, 24, 'ispe'); be32(b, 32, w); be32(b, 36, h); return b }
+
+console.log('reading sizes from headers')
+for (const [name, b, w, h] of [
+ ['PNG', png(640, 480), 640, 480],
+ ['WebP VP8X', webpX(9000, 6000), 9000, 6000],
+ ['WebP VP8', webp8(1200, 800), 1200, 800],
+ ['BMP (top-down, negative height)', bmp(300, 200), 300, 200],
+ ['TIFF little-endian', tiff(5000, 4000, true), 5000, 4000],
+ ['TIFF big-endian', tiff(5000, 4000, false), 5000, 4000],
+ ['AVIF (ispe)', avif(3840, 2160), 3840, 2160],
+] as Array<[string, Uint8Array, number, number]>) {
+ const s = imageSize(b)
+ ok(!!s && s.width === w && s.height === h, `${name}: ${w} × ${h} (${s ? `${s.width} × ${s.height}` : 'unread'})`)
+}
+// a real 1×1 lossless WebP, as browsers write it
+const REAL_WEBP = 'data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=='
+const real = imageSize(new Uint8Array(Buffer.from(REAL_WEBP.split(',')[1], 'base64')))
+ok(!!real && real.width === 1 && real.height === 1, `a real VP8L WebP reads as 1 × 1 (${real ? `${real.width} × ${real.height}` : 'unread'})`)
+
+console.log('the cap, before decoding')
+ok(MAX_PIXELS === 40_000_000, 'the cap is 40 megapixels')
+ok(mayDecode(REAL_WEBP) && mayDecode(uri('image/webp', webpX(6000, 6000))), 'pictures within the cap may decode (1×1, 6000×6000 = 36 MP)')
+ok(!mayDecode(uri('image/webp', webpX(16383, 16383))), 'a WebP header declaring 268 MP is refused before decoding')
+ok(!mayDecode(uri('image/png', png(10000, 4001))), 'just over the cap is refused (40.01 MP)')
+ok(!mayDecode(uri('image/tiff', tiff(100000, 100000, true))), 'a TIFF declaring 10 gigapixels is refused')
+ok(!mayDecode(uri('image/webp', bytes(64))) && !mayDecode('data:image/webp;base64,!!!') && !mayDecode('https://example.com/x.webp'),
+ 'an unreadable header, broken base64, or anything but a data: URI is refused')
+ok(!mayDecode(uri('image/png', png(0, 100))), 'a zero dimension is refused')
+
+console.log('the order')
+{
+ const src = fs.readFileSync(path.join(root, 'convert/page/rasterise.ts'), 'utf8')
+ const body = src.slice(src.indexOf('export async function rasteriseToPng'))
+ const check = body.indexOf('if (!mayDecode(dataUri)) return null'), decode = body.indexOf('new Image()')
+ ok(check > 0 && decode > check, 'rasteriseToPng refuses on the header check before it creates an Image to decode')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/site-src/convert.html b/site-src/convert.html
new file mode 100644
index 00000000..6a4f6229
--- /dev/null
+++ b/site-src/convert.html
@@ -0,0 +1,133 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<!--CONVERT_CSP-->
+<title>Convert a file — bento.page</title>
+<meta name="description" content="Open a PowerPoint deck in bento/slides, or save a bento/slides deck as PowerPoint. Converted on your device — nothing is uploaded.">
+<link rel="canonical" href="https://bento.page/convert">
+<meta name="theme-color" content="#0D1B2E">
+<meta property="og:type" content="website">
+<meta property="og:site_name" content="bento">
+<meta property="og:url" content="https://bento.page/convert">
+<meta property="og:title" content="Convert to and from bento">
+<meta property="og:description" content="PowerPoint in, PowerPoint out. Converted on your device — nothing is uploaded.">
+<meta property="og:image" content="https://bento.page/og.png">
+<meta name="twitter:card" content="summary_large_image">
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%2316273E'/%3E%3Crect x='5' y='5' width='7' height='22' rx='2.5' fill='%235E7699'/%3E%3Crect x='14' y='5' width='13' height='10' rx='2.5' fill='%23FF9E8A'/%3E%3Crect x='14' y='17' width='13' height='10' rx='2.5' fill='%23F0EBE0'/%3E%3C/svg%3E">
+<style>
+:root{
+ --ink:#0D1B2E; --panel:#16273E; --panel2:#1B2F49; --line:rgba(182,193,210,.16);
+ --text:rgba(196,206,221,.92); --dim:rgba(182,193,210,.62); --white:#F4F6F9;
+ --peach:#FF9E8A; --peach2:#ED8266; --steel:#5E7699; --bone:#F0EBE0; --bad:#FF8A8A;
+ --in:'Instrument Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
+ --fr:Fraunces,Georgia,'Times New Roman',serif;
+}
+*{margin:0;padding:0;box-sizing:border-box}
+body{background:var(--ink);color:var(--text);font-family:var(--in);line-height:1.6;-webkit-font-smoothing:antialiased}
+a{color:var(--peach)}
+button{font:inherit}
+.wrap{max-width:760px;margin:0 auto;padding:0 16px}
+header{border-bottom:1px solid var(--line)}
+.bar{display:flex;align-items:center;gap:16px;height:60px}
+.mark{display:flex;align-items:center;gap:11px;text-decoration:none;color:var(--white);font-weight:800;font-size:19.5px}
+.mark .sub{color:var(--dim);font-weight:500}
+.spacer{flex:1}
+.nav{color:var(--dim);text-decoration:none;font-weight:600;font-size:14px}
+h1{font-family:var(--fr);color:var(--white);font-size:clamp(28px,5vw,40px);line-height:1.15;margin:48px 0 12px}
+.lede{font-size:17px;margin-bottom:24px}
+.private{display:flex;gap:12px;align-items:flex-start;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:28px;font-size:14.5px}
+.private strong{color:var(--white)}
+.step{display:flex;align-items:baseline;gap:10px;color:var(--white);font-size:15px;font-weight:700;margin:28px 0 12px}
+.step .num{color:var(--peach);font-size:12.5px;font-weight:800;letter-spacing:.08em}
+#drop{display:block;border:2px dashed var(--line);border-radius:16px;padding:40px 20px;text-align:center;cursor:pointer;transition:border-color .15s,background .15s}
+#drop.over,#drop:hover{border-color:var(--peach);background:rgba(255,158,138,.05)}
+#drop strong{display:block;color:var(--white);font-size:18px;margin-bottom:6px}
+#drop input{position:absolute;width:1px;height:1px;opacity:0}
+#drop:focus-within{outline:2px solid var(--peach);outline-offset:3px}
+.hint{color:var(--dim);font-size:13.5px}
+.sample{margin-top:10px;font-size:13.5px;color:var(--dim)}
+.linkbtn{background:none;border:0;color:var(--peach);cursor:pointer;text-decoration:underline;text-underline-offset:3px;padding:2px}
+#source{margin-top:16px;padding:14px 16px;border:1px solid var(--line);border-radius:12px;background:var(--panel)}
+#source strong{color:var(--white);word-break:break-all}
+#source p{color:var(--dim);font-size:13.5px}
+#options{display:grid;gap:10px}
+.option{display:flex;gap:12px;align-items:flex-start;padding:14px 16px;border:1px solid var(--line);border-radius:12px;background:var(--panel);cursor:pointer}
+.option:has(input:checked){border-color:var(--peach)}
+.option input{accent-color:var(--peach);margin-top:5px;width:16px;height:16px;flex:none}
+.option b{color:var(--white);display:block}
+.option span{color:var(--dim);font-size:13.5px}
+.option.off{cursor:default;opacity:.62}
+.flag{display:flex;align-items:center;gap:8px;margin-top:8px;color:var(--text);font-size:13.5px}
+.flag input{accent-color:var(--peach);width:15px;height:15px}
+.btn{display:inline-block;background:var(--peach);color:var(--ink);font-weight:800;text-decoration:none;padding:12px 20px;border-radius:10px;border:0;cursor:pointer;margin:6px 0 4px}
+.btn:hover{background:var(--peach2)}
+.btn:disabled{background:var(--panel2);color:var(--dim);cursor:default}
+#convert{margin-top:16px}
+#status{margin:22px 0;padding:12px 16px;border-radius:10px;background:var(--panel)}
+#status[data-kind=error]{color:var(--bad);border:1px solid rgba(255,138,138,.35)}
+#result{margin:24px 0;padding:20px;border:1px solid var(--line);border-radius:14px;background:var(--panel)}
+#result h2{color:var(--white);font-size:19px;margin-bottom:4px;word-break:break-all}
+.meta{color:var(--dim);font-size:13.5px;margin:6px 0}
+.stats{display:flex;flex-wrap:wrap;gap:12px 28px;margin:16px 0}
+.stats div{display:flex;flex-direction:column}
+.stats strong{color:var(--white);font-size:26px;font-weight:700;line-height:1.2}
+.stats span{color:var(--dim);font-size:12.5px}
+.report{list-style:none;margin:12px 0 18px}
+.report li{padding:8px 0;border-top:1px solid var(--line);font-size:14.5px}
+.tag{display:inline-block;font-size:11.5px;font-weight:700;letter-spacing:.03em;text-transform:uppercase;padding:2px 7px;border-radius:5px;margin-right:6px;background:var(--panel2);color:var(--bone)}
+.dropped .tag{color:var(--bad)}
+.where,.n{color:var(--dim)}
+.nudge{margin-top:14px;padding:12px 14px;border-radius:10px;background:var(--panel2);font-size:14px}
+.nudge strong{color:var(--white)}
+.actions{display:flex;flex-wrap:wrap;align-items:center;gap:6px 16px}
+footer{border-top:1px solid var(--line);margin-top:56px;padding:22px 0;color:var(--dim);font-size:13px}
+[hidden]{display:none!important}
+</style>
+</head>
+<body>
+<header>
+ <div class="wrap bar">
+ <a class="mark" href="/">
+ <svg width="30" height="30" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="7" fill="#16273E"/><rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/><rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/><rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/></svg>
+ bento<span class="sub">/convert</span>
+ </a>
+ <div class="spacer"></div>
+ <a class="nav" href="/slides/">Open the editor</a>
+ </div>
+</header>
+
+<main class="wrap">
+ <h1 id="title">Convert to and from bento</h1>
+ <p class="lede" id="lede">Open a PowerPoint deck in bento/slides, or save a bento/slides deck as PowerPoint. Drop a file and choose what to make of it.</p>
+
+ <p class="private"><span aria-hidden="true">🔒</span><span><strong>Your file never leaves this device.</strong>
+ Conversion runs entirely in this browser tab. Nothing is uploaded, and this page runs no analytics.
+ When it makes a bento/slides deck, it downloads the latest bento/slides app and its signed release record, so that the app it puts your deck into is verified as genuine. Nothing else is downloaded.</span></p>
+
+ <h2 class="step"><span class="num">1</span> Choose a file</h2>
+ <label id="drop">
+ <strong id="drop-title">Drop a file here, or choose one</strong>
+ <span class="hint" id="drop-hint">A PowerPoint deck (.pptx), a bento/slides deck (.bento.html), or a deck’s document JSON. Up to <span id="limit">100 MB</span>.</span>
+ <input id="file" type="file" accept=".pptx,.html,.htm,.json,application/vnd.openxmlformats-officedocument.presentationml.presentation,text/html,application/json">
+ </label>
+ <p class="sample">Just looking? <button type="button" class="linkbtn" id="sample">Try it with a sample deck</button></p>
+ <div id="source" hidden><strong id="source-title"></strong><p id="source-meta"></p></div>
+
+ <section id="choose" hidden>
+ <h2 class="step"><span class="num">2</span> Choose what to make</h2>
+ <div id="options" role="radiogroup" aria-label="Convert to"></div>
+ <button type="button" class="btn" id="convert" disabled>Convert</button>
+ </section>
+
+ <div id="status" role="status" aria-live="polite" hidden></div>
+ <section id="result" aria-live="polite" hidden></section>
+
+ <p class="hint">Every conversion comes with a list of what changed and on which slides, so you know what to check before you share it.</p>
+</main>
+
+<footer><div class="wrap">bento — self-contained office documents · <a href="/help">Help</a> · <a href="https://github.com/nyblnet/bento">Source</a></div></footer>
+<!--CONVERT_SCRIPT-->
+</body>
+</html>
diff --git a/site-src/import.html b/site-src/import.html
index 86c0d554..a03f719a 100644
--- a/site-src/import.html
+++ b/site-src/import.html
@@ -3,96 +3,13 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
-<!--IMPORT_CSP-->
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; base-uri 'none'; form-action 'none'">
+<meta http-equiv="refresh" content="0; url=/convert?from=pptx">
<title>Open a PowerPoint deck in bento/slides — bento.page</title>
-<meta name="description" content="Turn a .pptx into a bento/slides deck: one self-contained HTML file you can edit and present in any browser. Converted on your device — nothing is uploaded.">
-<link rel="canonical" href="https://bento.page/import">
-<meta name="theme-color" content="#0D1B2E">
-<meta property="og:type" content="website">
-<meta property="og:site_name" content="bento">
-<meta property="og:url" content="https://bento.page/import">
-<meta property="og:title" content="Open a PowerPoint deck in bento/slides">
-<meta property="og:description" content="Converted on your device — nothing is uploaded.">
-<meta property="og:image" content="https://bento.page/og.png">
-<meta name="twitter:card" content="summary_large_image">
-<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%2316273E'/%3E%3Crect x='5' y='5' width='7' height='22' rx='2.5' fill='%235E7699'/%3E%3Crect x='14' y='5' width='13' height='10' rx='2.5' fill='%23FF9E8A'/%3E%3Crect x='14' y='17' width='13' height='10' rx='2.5' fill='%23F0EBE0'/%3E%3C/svg%3E">
-<style>
-:root{
- --ink:#0D1B2E; --panel:#16273E; --panel2:#1B2F49; --line:rgba(182,193,210,.16);
- --text:rgba(196,206,221,.92); --dim:rgba(182,193,210,.62); --white:#F4F6F9;
- --peach:#FF9E8A; --peach2:#ED8266; --steel:#5E7699; --bone:#F0EBE0; --bad:#FF8A8A;
- --in:'Instrument Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
- --fr:Fraunces,Georgia,'Times New Roman',serif;
-}
-*{margin:0;padding:0;box-sizing:border-box}
-body{background:var(--ink);color:var(--text);font-family:var(--in);line-height:1.6;-webkit-font-smoothing:antialiased}
-a{color:var(--peach)}
-.wrap{max-width:760px;margin:0 auto;padding:0 20px}
-header{border-bottom:1px solid var(--line)}
-.bar{display:flex;align-items:center;gap:16px;height:60px}
-.mark{display:flex;align-items:center;gap:11px;text-decoration:none;color:var(--white);font-weight:800;font-size:19.5px}
-.mark .sub{color:var(--dim);font-weight:500}
-.spacer{flex:1}
-.nav{color:var(--dim);text-decoration:none;font-weight:600;font-size:14px}
-h1{font-family:var(--fr);color:var(--white);font-size:clamp(28px,5vw,40px);line-height:1.15;margin:48px 0 12px}
-.lede{font-size:17px;margin-bottom:24px}
-.private{display:flex;gap:12px;align-items:flex-start;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:28px;font-size:14.5px}
-.private strong{color:var(--white)}
-#drop{display:block;border:2px dashed var(--line);border-radius:16px;padding:44px 20px;text-align:center;cursor:pointer;transition:border-color .15s,background .15s}
-#drop.over,#drop:hover{border-color:var(--peach);background:rgba(255,158,138,.05)}
-#drop strong{display:block;color:var(--white);font-size:18px;margin-bottom:6px}
-#drop input{position:absolute;width:1px;height:1px;opacity:0}
-.hint{color:var(--dim);font-size:13.5px}
-#status{margin:22px 0;padding:12px 16px;border-radius:10px;background:var(--panel)}
-#status[data-kind=error]{color:var(--bad);border:1px solid rgba(255,138,138,.35)}
-#result{margin:24px 0;padding:20px;border:1px solid var(--line);border-radius:14px;background:var(--panel)}
-#result h2{color:var(--white);font-size:19px;margin-bottom:4px;word-break:break-all}
-.meta{color:var(--dim);font-size:13.5px;margin:6px 0}
-.report{list-style:none;margin:12px 0 18px}
-.report li{padding:8px 0;border-top:1px solid var(--line);font-size:14.5px}
-.tag{display:inline-block;font-size:11.5px;font-weight:700;letter-spacing:.03em;text-transform:uppercase;padding:2px 7px;border-radius:5px;margin-right:6px;background:var(--panel2);color:var(--bone)}
-.dropped .tag{color:var(--bad)}
-.n{color:var(--dim)}
-.btn{display:inline-block;background:var(--peach);color:var(--ink);font-weight:800;text-decoration:none;padding:12px 20px;border-radius:10px;margin:6px 0 4px}
-.btn:hover{background:var(--peach2)}
-footer{border-top:1px solid var(--line);margin-top:56px;padding:22px 0;color:var(--dim);font-size:13px}
-</style>
+<link rel="canonical" href="https://bento.page/convert">
+<meta name="robots" content="noindex">
</head>
<body>
-<header>
- <div class="wrap bar">
- <a class="mark" href="/">
- <svg width="30" height="30" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="7" fill="#16273E"/><rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/><rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/><rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/></svg>
- bento<span class="sub">/import</span>
- </a>
- <div class="spacer"></div>
- <a class="nav" href="/slides/">Open the editor</a>
- </div>
-</header>
-
-<main class="wrap">
- <h1>Open a PowerPoint deck in bento/slides</h1>
- <p class="lede">Turn a .pptx into a bento/slides deck: one HTML file that edits and presents itself in any browser, with nothing to install.</p>
-
- <p class="private"><span aria-hidden="true">🔒</span><span><strong>Your file never leaves this device.</strong>
- Conversion runs entirely in this browser tab. Nothing is uploaded, and this page runs no analytics.
- The only things it downloads are the latest bento/slides app and its signed release record, so that the app it puts your deck into is verified as genuine.</span></p>
-
- <label id="drop">
- <strong>Drop a .pptx here, or choose one</strong>
- <span class="hint">PowerPoint presentations up to <span id="limit">100 MB</span></span>
- <input id="file" type="file" accept=".pptx,application/vnd.openxmlformats-officedocument.presentationml.presentation">
- </label>
-
- <div id="status" role="status" aria-live="polite" hidden></div>
- <section id="result" aria-live="polite" hidden></section>
-
- <p class="hint">What comes across: text, shapes, colours, pictures, where everything sits on each slide, and your speaker notes.
- What doesn't yet: tables and charts are marked with a placeholder box, and animations are not carried.
- The list after converting says exactly what changed in your deck.</p>
-</main>
-
-<footer><div class="wrap">bento — self-contained office documents · <a href="/help">Help</a> · <a href="https://github.com/nyblnet/bento">Source</a></div></footer>
-<!--IMPORT_SCRIPT-->
+<p>PowerPoint import has moved to <a href="/convert?from=pptx">bento.page/convert</a>.</p>
</body>
</html>
diff --git a/site-src/sitemap.xml b/site-src/sitemap.xml
index 95062401..42894a41 100644
--- a/site-src/sitemap.xml
+++ b/site-src/sitemap.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.w3.org/2000/sitemap/0.9">
<url><loc>https://bento.page/</loc><changefreq>weekly</changefreq><priority>1.0</priority></url>
- <url><loc>https://bento.page/import</loc><changefreq>monthly</changefreq><priority>0.7</priority></url>
+ <url><loc>https://bento.page/convert</loc><changefreq>monthly</changefreq><priority>0.7</priority></url>
<url><loc>https://bento.page/help</loc><changefreq>monthly</changefreq><priority>0.7</priority></url>
<url><loc>https://bento.page/agents.md</loc><changefreq>monthly</changefreq><priority>0.6</priority></url>
<url><loc>https://bento.page/guestbook/</loc><changefreq>daily</changefreq><priority>0.5</priority></url>