Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Kernel K1: move anim, save, autosave into kernel/ (pure code motion)

nyblnet13be0f82f4e8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3463dfd3..ae174441 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -43,6 +43,12 @@ jobs:
working-directory: slides
run: node_modules/.bin/tsc -b
+ - name: Typecheck kernel (standalone)
+ # Apps also typecheck kernel transitively through their imports; this
+ # catches kernel-only errors under the kernel's own flags.
+ working-directory: slides
+ run: node_modules/.bin/tsc -p ../kernel
+
- name: Build single-file shell
working-directory: slides
run: npm run build:single
diff --git a/kernel/README.md b/kernel/README.md
new file mode 100644
index 00000000..b468f72e
--- /dev/null
+++ b/kernel/README.md
@@ -0,0 +1,48 @@
+# Bento kernel
+
+The app-agnostic machinery every Bento app shares: document lifecycle
+(save/splice, `bento/enc` encryption, autosave/version history), signed
+self-update, the i18n engine, the animation engine, and charts-lite. The
+kernel/app boundary is defined in `docs/PLATFORM.md` §9 — the kernel never
+sees an app's content shape (slides, blocks, cells); it reads only the
+`KernelDoc` envelope (`src/doc.ts`).
+
+## How it's consumed
+
+Plain TypeScript source, no build step, no package.json. Apps import with
+relative paths and explicit `.ts` extensions:
+
+```ts
+import { anim } from '../../kernel/src/anim.ts'
+```
+
+— the one convention that works identically in vite, `tsc` (bundler
+resolution), and Node's native type stripping. In app code, prefer the app's
+facade modules (e.g. `slides/src/save.ts`) over importing the kernel
+directly; facades pin the app's configuration (and for i18n, guarantee
+catalog registration order).
+
+This is deliberately NOT an npm workspace: the kernel has zero dependencies,
+so a workspace buys nothing yet (decision in `docs/DECISIONS.md`). If a
+shared dependency ever appears, convert then, in one mechanical sweep.
+
+## Rules (see also AGENTS.md, docs/PARALLEL-WORK.md)
+
+- **Kernel-zone changes are serialized** — one PR at a time, reviewed against
+ the platform invariants. App work never edits kernel files in passing.
+- Nothing here may import from an app directory. The dependency direction is
+ app → kernel, only.
+- New envelope fields on `KernelDoc` are platform decisions, not
+ conveniences.
+- Frozen contracts that live here: the `#bento-doc` splice (save.ts), the
+ `bento/enc` envelope (save.ts), the update-manifest verification
+ (update.ts). Treat every byte as shipped-file compatibility surface.
+
+## Typecheck
+
+```sh
+slides/node_modules/.bin/tsc -p kernel
+```
+
+(CI runs this standalone; each app's `tsc -b` also typechecks kernel files
+transitively through its imports.)
diff --git a/kernel/src/anim.ts b/kernel/src/anim.ts
new file mode 100644
index 00000000..fed25db5
--- /dev/null
+++ b/kernel/src/anim.ts
@@ -0,0 +1,460 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento/Suite authors
+// Bento's animation engine — the in-house replacement for GSAP, sized to
+// exactly what the presenter and editor use:
+// anim.to / anim.fromTo(target, vars) with channels:
+// opacity, x / y (translate px), scale, color, strokeDashoffset,
+// attr: { fill, stop-color, offset, x1..y2, … } (colors interpolate),
+// motionPath: { path } (translate along an SVG path, relative),
+// plain numeric props on non-element targets (countUp state objects)
+// vars: duration (s), delay (s), ease ('none'|'linear'|'power1..3.in/out/
+// inOut'|'sine.inOut'), repeat (-1 = forever), yoyo, transformOrigin,
+// onUpdate, onComplete
+// anim.killTweensOf(target | targets), anim.getTweensOf(target) → .progress()
+// anim.setTimeScale(n) and manual clock (anim.manual/tick) for tests.
+//
+// Transform channels (y/scale/motionPath) compose through a per-element
+// registry and PRESERVE the model's rotate() applied by applyElementFrame.
+
+type EaseFn = (t: number) => number
+
+const pow = (n: number) => ({
+ in: (t: number) => t ** n,
+ out: (t: number) => 1 - (1 - t) ** n,
+ inOut: (t: number) => (t < 0.5 ? (2 * t) ** n / 2 : 1 - (2 - 2 * t) ** n / 2),
+})
+
+const EASES: Record<string, EaseFn> = {
+ none: (t) => t,
+ linear: (t) => t,
+ 'power1.in': pow(2).in, 'power1.out': pow(2).out, 'power1.inOut': pow(2).inOut,
+ 'power2.in': pow(3).in, 'power2.out': pow(3).out, 'power2.inOut': pow(3).inOut,
+ 'power3.in': pow(4).in, 'power3.out': pow(4).out, 'power3.inOut': pow(4).inOut,
+ 'sine.in': (t) => 1 - Math.cos((t * Math.PI) / 2),
+ 'sine.out': (t) => Math.sin((t * Math.PI) / 2),
+ 'sine.inOut': (t) => -(Math.cos(Math.PI * t) - 1) / 2,
+}
+
+// --- color + number interpolation --------------------------------------------
+
+const parseColor = (v: string): [number, number, number, number] | null => {
+ const m = v?.match(/rgba?\(([^)]+)\)/)
+ if (m) {
+ const p = m[1].split(/[\s,/]+/).map(Number)
+ return [p[0] || 0, p[1] || 0, p[2] || 0, Number.isFinite(p[3]) ? p[3] : 1]
+ }
+ let hex = (v ?? '').trim()
+ if (/^#[0-9a-fA-F]{3}$/.test(hex)) hex = '#' + [...hex.slice(1)].map((c) => c + c).join('')
+ if (/^#[0-9a-fA-F]{6,8}$/.test(hex)) {
+ return [
+ parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16),
+ hex.length === 9 ? parseInt(hex.slice(7, 9), 16) / 255 : 1,
+ ]
+ }
+ if (v === 'transparent' || v === 'none') return [0, 0, 0, 0]
+ return null
+}
+
+const mixColor = (a: [number, number, number, number], b: [number, number, number, number], t: number) =>
+ `rgba(${Math.round(a[0] + (b[0] - a[0]) * t)}, ${Math.round(a[1] + (b[1] - a[1]) * t)}, ${Math.round(
+ a[2] + (b[2] - a[2]) * t,
+ )}, ${Math.round((a[3] + (b[3] - a[3]) * t) * 1000) / 1000})`
+
+/** value-pair → interpolator string|number */
+function lerper(from: unknown, to: unknown): (t: number) => string | number {
+ if (typeof from === 'number' && typeof to === 'number') return (t) => from + (to - from) * t
+ const fc = parseColor(String(from))
+ const tc = parseColor(String(to))
+ if (fc && tc) return (t) => mixColor(fc, tc, t)
+ const fn = parseFloat(String(from))
+ const tn = parseFloat(String(to))
+ if (Number.isFinite(fn) && Number.isFinite(tn)) return (t) => fn + (tn - fn) * t
+ return (t) => (t < 1 ? String(from) : String(to))
+}
+
+// --- element transform composition --------------------------------------------
+
+interface XForm { x: number; y: number; scaleX: number; scaleY: number; baseRotate: string }
+const xforms = new WeakMap<Element, XForm>()
+
+function xformOf(el: HTMLElement | SVGElement): XForm {
+ let x = xforms.get(el)
+ if (!x) {
+ // preserve whatever rotate() the model frame applied (origin: center)
+ const m = (el.style.transform ?? '').match(/rotate\([^)]*\)/)
+ x = { x: 0, y: 0, scaleX: 1, scaleY: 1, baseRotate: m ? m[0] : '' }
+ xforms.set(el, x)
+ }
+ return x
+}
+
+function writeXform(el: HTMLElement | SVGElement) {
+ const x = xformOf(el)
+ const parts: string[] = []
+ if (x.x || x.y) parts.push(`translate(${x.x}px, ${x.y}px)`)
+ if (x.baseRotate) parts.push(x.baseRotate)
+ if (x.scaleX !== 1 || x.scaleY !== 1) parts.push(`scale(${x.scaleX}, ${x.scaleY})`)
+ el.style.transform = parts.join(' ')
+}
+
+/** applyElementFrame resets style.transform — forget our composition state. */
+export function resetXform(el: Element) {
+ xforms.delete(el)
+}
+
+// --- motion path sampling ------------------------------------------------------
+
+const SVG_NS = 'http://www.w3.org/2000/svg'
+
+/** on-curve anchor points of a path (the last coord pair of each M/L/C/Q). */
+function onCurvePoints(d: string): Array<{ x: number; y: number }> {
+ const out: Array<{ x: number; y: number }> = []
+ const re = /([MLCQ])([^MLCQZmlcqz]*)/gi
+ let m: RegExpExecArray | null
+ while ((m = re.exec(d))) {
+ const nums = (m[2].match(/-?\d*\.?\d+(?:e-?\d+)?/g) ?? []).map(Number)
+ if (nums.length >= 2) out.push({ x: nums[nums.length - 2], y: nums[nums.length - 1] })
+ }
+ return out
+}
+
+/**
+ * Warp time→arc-length so the element dwells at low-speed anchors and rushes
+ * at high-speed ones. `us` are the anchors' arc-length fractions (0..1),
+ * `speeds` their multipliers. Returns identity if the profile is uniform.
+ */
+function makeWarp(us: number[], speeds: number[]): (t: number) => number {
+ if (us.length < 2 || us.length !== speeds.length) return (t) => t
+ if (speeds.every((s) => Math.abs(s - speeds[0]) < 1e-3)) return (t) => t
+ const clampSp = (s: number) => Math.max(0.05, s)
+ const v = (u: number) => {
+ if (u <= us[0]) return clampSp(speeds[0])
+ if (u >= us[us.length - 1]) return clampSp(speeds[speeds.length - 1])
+ for (let i = 1; i < us.length; i++) {
+ if (u <= us[i]) {
+ const f = (u - us[i - 1]) / (us[i] - us[i - 1] || 1)
+ return clampSp(speeds[i - 1] + (speeds[i] - speeds[i - 1]) * f)
+ }
+ }
+ return clampSp(speeds[speeds.length - 1])
+ }
+ // cumulative traversal time T(u) = ∫ du/v ; normalise to [0,1], then invert
+ const M = 240
+ const T = new Float64Array(M + 1)
+ for (let j = 1; j <= M; j++) T[j] = T[j - 1] + (1 / M) / v((j - 0.5) / M)
+ const total = T[M] || 1
+ for (let j = 0; j <= M; j++) T[j] /= total
+ return (t) => {
+ t = Math.min(Math.max(t, 0), 1)
+ let lo = 0, hi = M
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (T[mid] < t) lo = mid + 1; else hi = mid }
+ if (lo === 0) return 0
+ const t0 = T[lo - 1], t1 = T[lo]
+ const f = (t - t0) / (t1 - t0 || 1)
+ return ((lo - 1) + f) / M
+ }
+}
+
+function samplePath(d: string, speeds?: number[]): ((t: number) => { x: number; y: number }) | null {
+ const svg = document.createElementNS(SVG_NS, 'svg')
+ svg.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden'
+ const path = document.createElementNS(SVG_NS, 'path')
+ path.setAttribute('d', d)
+ svg.appendChild(path)
+ document.body.appendChild(svg)
+ let total = 0
+ try { total = path.getTotalLength() } catch { /* bad path */ }
+ if (!Number.isFinite(total) || total <= 0) { svg.remove(); return null }
+ // pre-sample; keeps the probe svg out of the DOM during the animation
+ const N = Math.min(512, Math.max(64, Math.ceil(total / 3)))
+ const pts: Array<{ x: number; y: number }> = []
+ for (let i = 0; i <= N; i++) {
+ const p = path.getPointAtLength((total * i) / N)
+ pts.push({ x: p.x, y: p.y })
+ }
+ // variable speed: locate each anchor's arc-length fraction (nearest sample),
+ // then build a time-warp from the per-anchor speed multipliers
+ let warp: (t: number) => number = (t) => t
+ if (speeds && speeds.length >= 2) {
+ const anchors = onCurvePoints(d)
+ if (anchors.length === speeds.length) {
+ const us = anchors.map((a) => {
+ let best = 0, bestD = Infinity
+ for (let i = 0; i <= N; i++) {
+ const dx = pts[i].x - a.x, dy = pts[i].y - a.y
+ const dd = dx * dx + dy * dy
+ if (dd < bestD) { bestD = dd; best = i }
+ }
+ return best / N
+ })
+ warp = makeWarp(us, speeds)
+ }
+ }
+ svg.remove()
+ const geom = (u: number) => {
+ const f = Math.min(Math.max(u, 0), 1) * N
+ const i = Math.min(Math.floor(f), N - 1)
+ const k = f - i
+ return { x: pts[i].x + (pts[i + 1].x - pts[i].x) * k, y: pts[i].y + (pts[i + 1].y - pts[i].y) * k }
+ }
+ return (t) => geom(warp(t))
+}
+
+// --- the tween -----------------------------------------------------------------
+
+export interface TweenVars {
+ duration?: number
+ delay?: number
+ ease?: string
+ repeat?: number
+ yoyo?: boolean
+ overwrite?: string // accepted for call-site compat; overwrite is always per-channel
+ transformOrigin?: string
+ onUpdate?: () => void
+ onComplete?: () => void
+ [channel: string]: unknown
+}
+
+const CONTROL = new Set(['duration', 'delay', 'ease', 'repeat', 'yoyo', 'overwrite', 'transformOrigin', 'onUpdate', 'onComplete'])
+
+type Apply = (t: number) => void
+
+export class Tween {
+ private applies: Apply[] = []
+ private channels = new Set<string>()
+ private elapsed = 0 // seconds, excludes delay
+ private delay: number
+ private duration: number
+ private repeat: number
+ private yoyo: boolean
+ private ease: EaseFn
+ private vars: TweenVars
+ private from: Record<string, unknown> | null
+ private started = false
+ private dead = false
+ target: unknown
+
+ constructor(target: unknown, from: Record<string, unknown> | null, to: TweenVars) {
+ this.target = target
+ this.vars = to
+ this.from = from
+ this.duration = Math.max(to.duration ?? 0.5, 0.0001)
+ this.delay = to.delay ?? 0
+ this.repeat = to.repeat ?? 0
+ this.yoyo = !!to.yoyo
+ this.ease = EASES[to.ease ?? 'power1.out'] ?? EASES.linear
+ register(this)
+ // fromTo renders its from-state immediately (gsap immediateRender parity)
+ if (from) this.start()
+ tickerOn()
+ }
+
+ /** Build interpolators. With explicit from-values this runs at creation;
+ * otherwise lazily when the delay elapses (reading current values). */
+ private start() {
+ if (this.started || this.dead) return
+ this.started = true
+ const t = this.target
+ const from = this.from ?? {}
+ const isEl = t instanceof HTMLElement || t instanceof SVGElement
+ for (const [key, toVal] of Object.entries(this.vars)) {
+ if (CONTROL.has(key) || toVal === undefined) continue
+ this.channels.add(key)
+ if (!isEl) {
+ // plain object tween (countUp state)
+ const obj = t as Record<string, number>
+ const f = (from[key] as number) ?? obj[key] ?? 0
+ const lerp = lerper(f, toVal as number)
+ this.applies.push((p) => { obj[key] = lerp(p) as number })
+ continue
+ }
+ const el = t as HTMLElement
+ if (key === 'opacity') {
+ const f = from.opacity ?? parseFloat(getComputedStyle(el).opacity) ?? 1
+ const lerp = lerper(Number(f), Number(toVal))
+ this.applies.push((p) => { el.style.opacity = String(lerp(p)) })
+ } else if (key === 'x') {
+ const xf = xformOf(el)
+ const f = Number(from.x ?? xf.x)
+ const lerp = lerper(f, Number(toVal))
+ this.applies.push((p) => { xf.x = lerp(p) as number; writeXform(el) })
+ } else if (key === 'y') {
+ const x = xformOf(el)
+ const f = Number(from.y ?? x.y)
+ const lerp = lerper(f, Number(toVal))
+ this.applies.push((p) => { x.y = lerp(p) as number; writeXform(el) })
+ } else if (key === 'scale') {
+ const x = xformOf(el)
+ const f = Number(from.scale ?? x.scaleX)
+ const lerp = lerper(f, Number(toVal))
+ if (this.vars.transformOrigin) el.style.transformOrigin = String(this.vars.transformOrigin)
+ this.applies.push((p) => { const s = lerp(p) as number; x.scaleX = s; x.scaleY = s; writeXform(el) })
+ } else if (key === 'color') {
+ const f = String(from.color ?? getComputedStyle(el).color)
+ const lerp = lerper(f, String(toVal))
+ this.applies.push((p) => { el.style.color = String(lerp(p)) })
+ } else if (key === 'strokeDashoffset') {
+ const f = from.strokeDashoffset ?? getComputedStyle(el).strokeDashoffset
+ const lerp = lerper(parseFloat(String(f)) || 0, Number(toVal))
+ this.applies.push((p) => { el.style.strokeDashoffset = String(lerp(p)) })
+ } else if (key === 'attr') {
+ const toAttrs = toVal as Record<string, string | number>
+ const fromAttrs = (from.attr ?? {}) as Record<string, string | number>
+ for (const [name, tv] of Object.entries(toAttrs)) {
+ const fv = fromAttrs[name] ?? el.getAttribute(name) ?? 0
+ const lerp = lerper(fv, tv)
+ this.applies.push((p) => el.setAttribute(name, String(lerp(p))))
+ }
+ } else if (key === 'motionPath') {
+ const mp = toVal as { path: string; speeds?: number[] }
+ const d = mp.path
+ const sample = samplePath(d, mp.speeds)
+ if (sample) {
+ const x = xformOf(el)
+ this.applies.push((p) => {
+ const pt = sample(p)
+ x.x = pt.x
+ x.y = pt.y
+ writeXform(el)
+ })
+ }
+ }
+ }
+ // per-channel overwrite: a newer tween on the same target owns its channels
+ for (const other of tweensOf(this.target)) {
+ if (other === this || other.dead) continue
+ if ([...this.channels].some((c) => other.channels.has(c))) other.kill()
+ }
+ this.applies.forEach((a) => a(0))
+ }
+
+ /** 0..1 across the whole lifetime (repeats count as complete). */
+ progress(): number {
+ if (this.dead) return 1
+ if (this.repeat === -1) return 0
+ const total = this.duration * (1 + this.repeat)
+ return Math.min(this.elapsed / total, 1)
+ }
+
+ /** advance by dt seconds; returns false when finished */
+ tick(dt: number): boolean {
+ if (this.dead) return false
+ if (this.delay > 0) {
+ this.delay -= dt
+ if (this.delay > 0) return true
+ dt = -this.delay
+ this.delay = 0
+ }
+ if (!this.started) this.start()
+ this.elapsed += dt
+ const cycles = this.elapsed / this.duration
+ const isForever = this.repeat === -1
+ const done = !isForever && cycles >= 1 + this.repeat
+ let t: number
+ if (done) {
+ t = this.yoyo && (1 + this.repeat) % 2 === 0 ? 0 : 1
+ } else {
+ const c = Math.floor(cycles)
+ const frac = cycles - c
+ t = this.yoyo && c % 2 === 1 ? 1 - frac : frac
+ }
+ const eased = this.ease(t)
+ for (const a of this.applies) a(eased)
+ this.vars.onUpdate?.()
+ if (done) {
+ this.dead = true
+ unregister(this)
+ this.vars.onComplete?.()
+ return false
+ }
+ return true
+ }
+
+ kill() {
+ if (this.dead) return
+ this.dead = true
+ unregister(this)
+ }
+}
+
+// --- registry + ticker -----------------------------------------------------------
+
+const live = new Set<Tween>()
+const byTarget = new Map<unknown, Set<Tween>>()
+
+function register(tw: Tween) {
+ live.add(tw)
+ let set = byTarget.get(tw.target)
+ if (!set) byTarget.set(tw.target, (set = new Set()))
+ set.add(tw)
+}
+
+function unregister(tw: Tween) {
+ live.delete(tw)
+ const set = byTarget.get(tw.target)
+ set?.delete(tw)
+ if (set && !set.size) byTarget.delete(tw.target)
+}
+
+function tweensOf(target: unknown): Tween[] {
+ return [...(byTarget.get(target) ?? [])]
+}
+
+let running = false
+let last = 0
+let timeScale = 1
+let manual = false
+
+function tickerOn() {
+ if (running || manual) return
+ running = true
+ last = performance.now()
+ requestAnimationFrame(loop)
+}
+
+function loop(now: number) {
+ if (manual) { running = false; return }
+ // clamp long gaps (throttled tabs) so loops don't leap wildly
+ const dt = Math.min((now - last) / 1000, 0.25) * timeScale
+ last = now
+ for (const tw of [...live]) tw.tick(dt)
+ if (live.size) requestAnimationFrame(loop)
+ else running = false
+}
+
+// --- public api --------------------------------------------------------------------
+
+export const anim = {
+ to(target: unknown, vars: TweenVars): Tween {
+ return new Tween(target, null, vars)
+ },
+ fromTo(target: unknown, from: Record<string, unknown>, vars: TweenVars): Tween {
+ return new Tween(target, from, vars)
+ },
+ killTweensOf(target: unknown) {
+ const targets: unknown[] =
+ target instanceof NodeList || Array.isArray(target) ? [...(target as Iterable<unknown>)] : [target]
+ for (const t of targets) for (const tw of tweensOf(t)) tw.kill()
+ },
+ getTweensOf(target: unknown): Tween[] {
+ return tweensOf(target)
+ },
+ killAll() {
+ for (const tw of [...live]) tw.kill()
+ },
+ /** global playback rate (diagnostics/tests) */
+ setTimeScale(n: number) {
+ timeScale = n
+ },
+ /** manual clock for tests: stop the rAF loop and drive time by hand */
+ setManual(on: boolean) {
+ manual = on
+ if (!on) tickerOn()
+ },
+ tick(seconds: number) {
+ for (const tw of [...live]) tw.tick(seconds * timeScale)
+ },
+ get activeCount() {
+ return live.size
+ },
+}
diff --git a/kernel/src/autosave.ts b/kernel/src/autosave.ts
new file mode 100644
index 00000000..5ad9e117
--- /dev/null
+++ b/kernel/src/autosave.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento/Suite authors
+// Local auto-save + lightweight version history, backed by IndexedDB.
+//
+// Two concerns, one store:
+// · recovery — a single latest snapshot per docId, overwritten each cycle.
+// On reopen, if it differs from the file we loaded, we offer to restore
+// (the safety net for a crash / tab-close before a save, and the ONLY net
+// on browsers without the File System Access API).
+// · versions — a capped, throttled timeline of snapshots per docId, for the
+// "Version history" restore UI.
+//
+// Snapshots hold the plain document JSON (a few KB–tens of KB), NOT the ~430KB
+// HTML shell — restore re-injects via store.replaceDoc. Encrypted decks are
+// never snapshotted here (that would write plaintext to disk); their file
+// write-back stays encrypted.
+
+import type { KernelDoc } from './doc.ts'
+
+const DB_NAME = 'bento-autosave'
+const DB_VERSION = 1
+const RECOVERY = 'recovery'
+const VERSIONS = 'versions'
+const MAX_VERSIONS = 20 // per doc
+const PRUNE_DAYS = 30
+
+export interface Snapshot {
+ id?: number
+ docId: string
+ at: number
+ title: string
+ json: string
+}
+
+let dbPromise: Promise<IDBDatabase | null> | null = null
+
+function openDb(): Promise<IDBDatabase | null> {
+ if (dbPromise) return dbPromise
+ dbPromise = new Promise((resolve) => {
+ if (typeof indexedDB === 'undefined') { resolve(null); return }
+ let req: IDBOpenDBRequest
+ try { req = indexedDB.open(DB_NAME, DB_VERSION) } catch { resolve(null); return }
+ req.onupgradeneeded = () => {
+ const db = req.result
+ if (!db.objectStoreNames.contains(RECOVERY)) db.createObjectStore(RECOVERY, { keyPath: 'docId' })
+ if (!db.objectStoreNames.contains(VERSIONS)) {
+ const s = db.createObjectStore(VERSIONS, { keyPath: 'id', autoIncrement: true })
+ s.createIndex('docId', 'docId', { unique: false })
+ }
+ }
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => resolve(null)
+ })
+ return dbPromise
+}
+
+function tx<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T | null> {
+ return openDb().then((db) => {
+ if (!db) return null
+ return new Promise<T | null>((resolve) => {
+ let t: IDBTransaction
+ try { t = db.transaction(store, mode) } catch { resolve(null); return }
+ const req = fn(t.objectStore(store))
+ req.onsuccess = () => resolve(req.result as T)
+ req.onerror = () => resolve(null)
+ })
+ })
+}
+
+export async function putRecovery(doc: KernelDoc): Promise<void> {
+ await tx(RECOVERY, 'readwrite', (s) =>
+ s.put({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))
+}
+
+export async function getRecovery(docId: string): Promise<Snapshot | null> {
+ return (await tx<Snapshot>(RECOVERY, 'readonly', (s) => s.get(docId))) ?? null
+}
+
+export async function clearRecovery(docId: string): Promise<void> {
+ await tx(RECOVERY, 'readwrite', (s) => s.delete(docId))
+}
+
+/** Delete every version-history snapshot for a docId. Used when a deck is
+ * encrypted: the plaintext snapshots written before encryption was enabled must
+ * not linger in IndexedDB (they'd defeat the encryption the user just turned on). */
+export async function clearVersions(docId: string): Promise<void> {
+ const all = await listVersions(docId)
+ await Promise.all(all.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
+}
+
+export async function addVersion(doc: KernelDoc): Promise<void> {
+ await tx(VERSIONS, 'readwrite', (s) =>
+ s.add({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))
+ // prune to the newest MAX_VERSIONS for this doc
+ const all = await listVersions(doc.docId)
+ if (all.length > MAX_VERSIONS) {
+ const doomed = all.slice(MAX_VERSIONS)
+ await Promise.all(doomed.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
+ }
+}
+
+export async function listVersions(docId: string): Promise<Snapshot[]> {
+ const db = await openDb()
+ if (!db) return []
+ return new Promise((resolve) => {
+ let t: IDBTransaction
+ try { t = db.transaction(VERSIONS, 'readonly') } catch { resolve([]); return }
+ const idx = t.objectStore(VERSIONS).index('docId')
+ const out: Snapshot[] = []
+ const req = idx.openCursor(IDBKeyRange.only(docId))
+ req.onsuccess = () => {
+ const cur = req.result
+ if (cur) { out.push(cur.value as Snapshot); cur.continue() }
+ else resolve(out.sort((a, b) => b.at - a.at)) // newest first
+ }
+ req.onerror = () => resolve([])
+ })
+}
+
+/** Drop snapshots older than PRUNE_DAYS across all docs (housekeeping). */
+export async function pruneOld(): Promise<void> {
+ const cutoff = Date.now() - PRUNE_DAYS * 24 * 60 * 60 * 1000
+ const db = await openDb()
+ if (!db) return
+ for (const store of [VERSIONS, RECOVERY]) {
+ try {
+ const t = db.transaction(store, 'readwrite')
+ const req = t.objectStore(store).openCursor()
+ req.onsuccess = () => {
+ const cur = req.result
+ if (!cur) return
+ if ((cur.value as Snapshot).at < cutoff) cur.delete()
+ cur.continue()
+ }
+ } catch { /* best effort */ }
+ }
+}
diff --git a/kernel/src/doc.ts b/kernel/src/doc.ts
new file mode 100644
index 00000000..b9b4107f
--- /dev/null
+++ b/kernel/src/doc.ts
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento/Suite authors
+// The kernel document envelope — the ONLY doc fields kernel modules may read.
+// Every app's document model (bento/slides, bento/spaces, …) satisfies this
+// structurally; the kernel never sees an app's content shape (slides, blocks,
+// cells). Keep this interface minimal on purpose: adding a field here is a
+// platform decision (docs/PLATFORM.md §9), not a convenience.
+
+/** The envelope every Bento document carries (see docs/PLATFORM.md §3). */
+export interface KernelDoc {
+ /** Stable uuid minted at creation/load — never regenerated. */
+ docId: string
+ /** Document title (shown in window titles, save filenames). */
+ title: string
+}
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
new file mode 100644
index 00000000..86382c58
--- /dev/null
+++ b/kernel/src/save.ts
@@ -0,0 +1,280 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento/Suite authors
+// Self-saving: a Bento file writes itself back to disk with updated data.
+//
+// At boot (before the app mutates the DOM) we deep-clone the document. On save
+// we swap the clone's data block content for the current model JSON and
+// serialize the clone back to an HTML string — byte-for-byte the same app
+// shell, new document inside. TiddlyWiki pioneered this trick.
+
+import type { KernelDoc } from './doc.ts'
+
+const DATA_BLOCK_ID = 'bento-doc'
+// Split so the literal never appears in the bundle (it would terminate the
+// inline <script> that carries this very code inside a built Bento file).
+const SCRIPT_CLOSE = '</scr' + 'ipt>'
+
+let pristine: Document | null = null
+
+/** Call first thing at boot, before any DOM mutation. */
+export function capturePristine() {
+ pristine = document.cloneNode(true) as Document
+}
+
+export function readEmbeddedDoc(): string | null {
+ const block = document.getElementById(DATA_BLOCK_ID)
+ const text = block?.textContent?.trim()
+ return text || null
+}
+
+/** Serialize a raw data-block body into an app shell. */
+function serializeBody(shell: Document, body: string, title: string): string {
+ const clone = shell.cloneNode(true) as Document
+
+ let block = clone.getElementById(DATA_BLOCK_ID)
+ if (!block) {
+ block = clone.createElement('script')
+ block.setAttribute('type', 'application/bento+json')
+ block.id = DATA_BLOCK_ID
+ clone.head.appendChild(block)
+ }
+ // <-escape so the JSON can never contain "</script>" and break the file.
+ block.textContent = '\n' + body.replace(/</g, '\\u003c') + '\n'
+
+ const titleEl = clone.querySelector('title')
+ if (titleEl) titleEl.textContent = title + ' — Bento Slides'
+
+ const html = '<!DOCTYPE html>\n' + clone.documentElement.outerHTML
+ // Belt-and-braces: an unescaped close tag anywhere in generated output would
+ // corrupt the file; this should never trigger given the escaping above.
+ if (html.split(SCRIPT_CLOSE).length !== clone.querySelectorAll('script').length + 1) {
+ console.warn('bento: unexpected script-close count in serialized file')
+ }
+ return html
+}
+
+/**
+ * Serialize `doc` into an arbitrary app shell (a parsed Bento HTML document).
+ * Used with the boot-time pristine copy on every save, and by the self-update
+ * flow with a freshly fetched NEWER shell — same document, new app around it.
+ * PLAIN output — encryption-aware callers use serializeDocInto/serializeAuto.
+ */
+export function serializeWith(shell: Document, doc: KernelDoc): string {
+ return serializeBody(shell, JSON.stringify(doc), doc.title)
+}
+
+/** The full .bento.html file content with `doc` embedded (plain). */
+export function serializeFile(doc: KernelDoc): string {
+ if (!pristine) throw new Error('capturePristine() was not called at boot')
+ return serializeWith(pristine, doc)
+}
+
+// --- password encryption ----------------------------------------------------
+//
+// An encrypted file keeps the SAME plaintext #bento-doc block (the splice
+// contract old updaters rely on) — but the block holds a bento/enc envelope
+// instead of the document: AES-GCM-256 over the doc JSON, key derived from
+// the password with PBKDF2-SHA-256. The password is held in memory for the
+// session so ⌘S and self-update keep writing encrypted output.
+
+export interface EncEnvelope {
+ format: 'bento/enc'
+ v: 1
+ it: number
+ salt: string
+ iv: string
+ data: string
+}
+
+const ENC_ITERATIONS = 300_000
+
+const eb64 = {
+ enc(bytes: Uint8Array): string {
+ let s = ''
+ for (const b of bytes) s += String.fromCharCode(b)
+ return btoa(s)
+ },
+ dec(s: string): Uint8Array {
+ const b = atob(s)
+ const out = new Uint8Array(b.length)
+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)
+ return out
+ },
+}
+
+let encPassword: string | null = null
+
+/** Set (or clear with null) the password used for every subsequent save. */
+export function setEncryptionPassword(p: string | null) {
+ encPassword = p
+}
+
+export const isEncryptionActive = () => encPassword !== null
+
+/** Parse a data-block body as an encryption envelope; null if it is not one. */
+export function parseEnvelope(text: string): EncEnvelope | null {
+ try {
+ const env = JSON.parse(text)
+ if (env && env.format === 'bento/enc' && env.v === 1 && env.data && env.salt && env.iv) {
+ return env as EncEnvelope
+ }
+ } catch {
+ /* not an envelope */
+ }
+ return null
+}
+
+async function deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {
+ const material = await crypto.subtle.importKey(
+ 'raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey'])
+ return crypto.subtle.deriveKey(
+ { name: 'PBKDF2', hash: 'SHA-256', salt: salt as BufferSource, iterations },
+ material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
+}
+
+async function encryptBody(json: string, password: string): Promise<string> {
+ const salt = new Uint8Array(16)
+ const iv = new Uint8Array(12)
+ crypto.getRandomValues(salt)
+ crypto.getRandomValues(iv)
+ const key = await deriveKey(password, salt, ENC_ITERATIONS)
+ const ct = await crypto.subtle.encrypt(
+ { name: 'AES-GCM', iv: iv as BufferSource }, key, new TextEncoder().encode(json))
+ const env: EncEnvelope = {
+ format: 'bento/enc', v: 1, it: ENC_ITERATIONS,
+ salt: eb64.enc(salt), iv: eb64.enc(iv), data: eb64.enc(new Uint8Array(ct)),
+ }
+ return JSON.stringify(env)
+}
+
+/** Decrypt an envelope with a candidate password; null on wrong password. */
+export async function decryptEnvelope(env: EncEnvelope, password: string): Promise<string | null> {
+ try {
+ const key = await deriveKey(password, eb64.dec(env.salt), env.it || ENC_ITERATIONS)
+ const pt = await crypto.subtle.decrypt(
+ { name: 'AES-GCM', iv: eb64.dec(env.iv) as BufferSource }, key, eb64.dec(env.data) as BufferSource)
+ return new TextDecoder().decode(pt)
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Encryption-aware serialization into an arbitrary shell — THE path for
+ * saves and self-updates. Plain when no password is active.
+ */
+export async function serializeDocInto(shell: Document, doc: KernelDoc): Promise<string> {
+ const body = encPassword
+ ? await encryptBody(JSON.stringify(doc), encPassword)
+ : JSON.stringify(doc)
+ return serializeBody(shell, body, doc.title)
+}
+
+/** Encryption-aware serializeFile. */
+export async function serializeAuto(doc: KernelDoc): Promise<string> {
+ if (!pristine) throw new Error('capturePristine() was not called at boot')
+ return serializeDocInto(pristine, doc)
+}
+
+export function suggestedFileName(doc: KernelDoc, suffix = ''): string {
+ const base = doc.title.replace(/[^\w\d-]+/g, '_').replace(/^_+|_+$/g, '') || 'Untitled'
+ return `${base}${suffix ? `-${suffix}` : ''}.bento.html`
+}
+
+// --- writing to disk --------------------------------------------------------
+
+type SaveResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'
+
+interface FsFileHandle {
+ createWritable(): Promise<{ write(data: Blob): Promise<void>; close(): Promise<void> }>
+ name: string
+}
+
+let fileHandle: FsFileHandle | null = null
+
+const hasFsAccess = () => typeof (window as any).showSaveFilePicker === 'function'
+
+async function pickHandle(doc: KernelDoc, suffix = ''): Promise<FsFileHandle | null> {
+ try {
+ return await (window as any).showSaveFilePicker({
+ suggestedName: suggestedFileName(doc, suffix),
+ types: [{ description: 'Bento Slides', accept: { 'text/html': ['.html'] } }],
+ })
+ } catch (err: any) {
+ if (err?.name === 'AbortError') return null
+ throw err
+ }
+}
+
+async function writeHandle(handle: FsFileHandle, html: string) {
+ const writable = await handle.createWritable()
+ await writable.write(new Blob([html], { type: 'text/html' }))
+ await writable.close()
+}
+
+export function downloadFile(html: string, name: string) {
+ const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }))
+ const a = document.createElement('a')
+ a.href = url
+ a.download = name
+ a.click()
+ setTimeout(() => URL.revokeObjectURL(url), 5000)
+}
+
+/**
+ * Save the document. Chrome/Edge: File System Access API (picker on first
+ * save, silent rewrite after). Firefox/Safari: download a copy.
+ */
+export async function saveFile(doc: KernelDoc, forcePicker = false): Promise<SaveResult> {
+ const html = await serializeAuto(doc)
+ if (hasFsAccess()) {
+ if (forcePicker || !fileHandle) {
+ const handle = await pickHandle(doc)
+ if (!handle) return 'cancelled'
+ fileHandle = handle
+ await writeHandle(handle, html)
+ return 'saved-as'
+ }
+ await writeHandle(fileHandle, html)
+ return 'saved'
+ }
+ downloadFile(html, suggestedFileName(doc))
+ return 'downloaded'
+}
+
+export const currentFileName = () => fileHandle?.name ?? null
+
+// --- self-update writing ----------------------------------------------------
+
+/** Whether we hold a writable handle to the file (in-place update possible). */
+export const hasFileHandle = () => fileHandle !== null
+
+/** Overwrite the held file with arbitrary html (the freshly updated shell). */
+export async function writeUpdatedFile(html: string): Promise<void> {
+ if (!fileHandle) throw new Error('no file handle')
+ await writeHandle(fileHandle, html)
+}
+
+/**
+ * Save updated html via a picker (user points it at the file they have open,
+ * or anywhere else). Returns false if cancelled. Keeps the picked handle so
+ * subsequent ⌘S saves go to the same place.
+ */
+export async function writeUpdatedFileAs(
+ html: string,
+ doc: KernelDoc,
+ opts: { suffix?: string; keepHandle?: boolean } = {},
+): Promise<boolean> {
+ if (!hasFsAccess()) {
+ downloadFile(html, suggestedFileName(doc, opts.suffix))
+ return true
+ }
+ const handle = await pickHandle(doc, opts.suffix)
+ if (!handle) return false
+ // Share/export artifacts must NOT become the ⌘S target — otherwise the next
+ // save would overwrite e.g. a view-only copy with the FULL document (owner
+ // keys included). Only an explicit keepHandle retargets in-place saving.
+ if (opts.keepHandle) fileHandle = handle
+ await writeHandle(handle, html)
+ return true
+}
diff --git a/kernel/tsconfig.json b/kernel/tsconfig.json
new file mode 100644
index 00000000..f51f643a
--- /dev/null
+++ b/kernel/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "useDefineForClassFields": true,
+ "module": "ESNext",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/slides/src/anim.ts b/slides/src/anim.ts
index fed25db5..0f84bdb1 100644
--- a/slides/src/anim.ts
+++ b/slides/src/anim.ts
@@ -1,460 +1,6 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento/Suite authors
-// Bento's animation engine — the in-house replacement for GSAP, sized to
-// exactly what the presenter and editor use:
-// anim.to / anim.fromTo(target, vars) with channels:
-// opacity, x / y (translate px), scale, color, strokeDashoffset,
-// attr: { fill, stop-color, offset, x1..y2, … } (colors interpolate),
-// motionPath: { path } (translate along an SVG path, relative),
-// plain numeric props on non-element targets (countUp state objects)
-// vars: duration (s), delay (s), ease ('none'|'linear'|'power1..3.in/out/
-// inOut'|'sine.inOut'), repeat (-1 = forever), yoyo, transformOrigin,
-// onUpdate, onComplete
-// anim.killTweensOf(target | targets), anim.getTweensOf(target) → .progress()
-// anim.setTimeScale(n) and manual clock (anim.manual/tick) for tests.
-//
-// Transform channels (y/scale/motionPath) compose through a per-element
-// registry and PRESERVE the model's rotate() applied by applyElementFrame.
-
-type EaseFn = (t: number) => number
-
-const pow = (n: number) => ({
- in: (t: number) => t ** n,
- out: (t: number) => 1 - (1 - t) ** n,
- inOut: (t: number) => (t < 0.5 ? (2 * t) ** n / 2 : 1 - (2 - 2 * t) ** n / 2),
-})
-
-const EASES: Record<string, EaseFn> = {
- none: (t) => t,
- linear: (t) => t,
- 'power1.in': pow(2).in, 'power1.out': pow(2).out, 'power1.inOut': pow(2).inOut,
- 'power2.in': pow(3).in, 'power2.out': pow(3).out, 'power2.inOut': pow(3).inOut,
- 'power3.in': pow(4).in, 'power3.out': pow(4).out, 'power3.inOut': pow(4).inOut,
- 'sine.in': (t) => 1 - Math.cos((t * Math.PI) / 2),
- 'sine.out': (t) => Math.sin((t * Math.PI) / 2),
- 'sine.inOut': (t) => -(Math.cos(Math.PI * t) - 1) / 2,
-}
-
-// --- color + number interpolation --------------------------------------------
-
-const parseColor = (v: string): [number, number, number, number] | null => {
- const m = v?.match(/rgba?\(([^)]+)\)/)
- if (m) {
- const p = m[1].split(/[\s,/]+/).map(Number)
- return [p[0] || 0, p[1] || 0, p[2] || 0, Number.isFinite(p[3]) ? p[3] : 1]
- }
- let hex = (v ?? '').trim()
- if (/^#[0-9a-fA-F]{3}$/.test(hex)) hex = '#' + [...hex.slice(1)].map((c) => c + c).join('')
- if (/^#[0-9a-fA-F]{6,8}$/.test(hex)) {
- return [
- parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16),
- hex.length === 9 ? parseInt(hex.slice(7, 9), 16) / 255 : 1,
- ]
- }
- if (v === 'transparent' || v === 'none') return [0, 0, 0, 0]
- return null
-}
-
-const mixColor = (a: [number, number, number, number], b: [number, number, number, number], t: number) =>
- `rgba(${Math.round(a[0] + (b[0] - a[0]) * t)}, ${Math.round(a[1] + (b[1] - a[1]) * t)}, ${Math.round(
- a[2] + (b[2] - a[2]) * t,
- )}, ${Math.round((a[3] + (b[3] - a[3]) * t) * 1000) / 1000})`
-
-/** value-pair → interpolator string|number */
-function lerper(from: unknown, to: unknown): (t: number) => string | number {
- if (typeof from === 'number' && typeof to === 'number') return (t) => from + (to - from) * t
- const fc = parseColor(String(from))
- const tc = parseColor(String(to))
- if (fc && tc) return (t) => mixColor(fc, tc, t)
- const fn = parseFloat(String(from))
- const tn = parseFloat(String(to))
- if (Number.isFinite(fn) && Number.isFinite(tn)) return (t) => fn + (tn - fn) * t
- return (t) => (t < 1 ? String(from) : String(to))
-}
-
-// --- element transform composition --------------------------------------------
-
-interface XForm { x: number; y: number; scaleX: number; scaleY: number; baseRotate: string }
-const xforms = new WeakMap<Element, XForm>()
-
-function xformOf(el: HTMLElement | SVGElement): XForm {
- let x = xforms.get(el)
- if (!x) {
- // preserve whatever rotate() the model frame applied (origin: center)
- const m = (el.style.transform ?? '').match(/rotate\([^)]*\)/)
- x = { x: 0, y: 0, scaleX: 1, scaleY: 1, baseRotate: m ? m[0] : '' }
- xforms.set(el, x)
- }
- return x
-}
-
-function writeXform(el: HTMLElement | SVGElement) {
- const x = xformOf(el)
- const parts: string[] = []
- if (x.x || x.y) parts.push(`translate(${x.x}px, ${x.y}px)`)
- if (x.baseRotate) parts.push(x.baseRotate)
- if (x.scaleX !== 1 || x.scaleY !== 1) parts.push(`scale(${x.scaleX}, ${x.scaleY})`)
- el.style.transform = parts.join(' ')
-}
-
-/** applyElementFrame resets style.transform — forget our composition state. */
-export function resetXform(el: Element) {
- xforms.delete(el)
-}
-
-// --- motion path sampling ------------------------------------------------------
-
-const SVG_NS = 'http://www.w3.org/2000/svg'
-
-/** on-curve anchor points of a path (the last coord pair of each M/L/C/Q). */
-function onCurvePoints(d: string): Array<{ x: number; y: number }> {
- const out: Array<{ x: number; y: number }> = []
- const re = /([MLCQ])([^MLCQZmlcqz]*)/gi
- let m: RegExpExecArray | null
- while ((m = re.exec(d))) {
- const nums = (m[2].match(/-?\d*\.?\d+(?:e-?\d+)?/g) ?? []).map(Number)
- if (nums.length >= 2) out.push({ x: nums[nums.length - 2], y: nums[nums.length - 1] })
- }
- return out
-}
-
-/**
- * Warp time→arc-length so the element dwells at low-speed anchors and rushes
- * at high-speed ones. `us` are the anchors' arc-length fractions (0..1),
- * `speeds` their multipliers. Returns identity if the profile is uniform.
- */
-function makeWarp(us: number[], speeds: number[]): (t: number) => number {
- if (us.length < 2 || us.length !== speeds.length) return (t) => t
- if (speeds.every((s) => Math.abs(s - speeds[0]) < 1e-3)) return (t) => t
- const clampSp = (s: number) => Math.max(0.05, s)
- const v = (u: number) => {
- if (u <= us[0]) return clampSp(speeds[0])
- if (u >= us[us.length - 1]) return clampSp(speeds[speeds.length - 1])
- for (let i = 1; i < us.length; i++) {
- if (u <= us[i]) {
- const f = (u - us[i - 1]) / (us[i] - us[i - 1] || 1)
- return clampSp(speeds[i - 1] + (speeds[i] - speeds[i - 1]) * f)
- }
- }
- return clampSp(speeds[speeds.length - 1])
- }
- // cumulative traversal time T(u) = ∫ du/v ; normalise to [0,1], then invert
- const M = 240
- const T = new Float64Array(M + 1)
- for (let j = 1; j <= M; j++) T[j] = T[j - 1] + (1 / M) / v((j - 0.5) / M)
- const total = T[M] || 1
- for (let j = 0; j <= M; j++) T[j] /= total
- return (t) => {
- t = Math.min(Math.max(t, 0), 1)
- let lo = 0, hi = M
- while (lo < hi) { const mid = (lo + hi) >> 1; if (T[mid] < t) lo = mid + 1; else hi = mid }
- if (lo === 0) return 0
- const t0 = T[lo - 1], t1 = T[lo]
- const f = (t - t0) / (t1 - t0 || 1)
- return ((lo - 1) + f) / M
- }
-}
-
-function samplePath(d: string, speeds?: number[]): ((t: number) => { x: number; y: number }) | null {
- const svg = document.createElementNS(SVG_NS, 'svg')
- svg.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden'
- const path = document.createElementNS(SVG_NS, 'path')
- path.setAttribute('d', d)
- svg.appendChild(path)
- document.body.appendChild(svg)
- let total = 0
- try { total = path.getTotalLength() } catch { /* bad path */ }
- if (!Number.isFinite(total) || total <= 0) { svg.remove(); return null }
- // pre-sample; keeps the probe svg out of the DOM during the animation
- const N = Math.min(512, Math.max(64, Math.ceil(total / 3)))
- const pts: Array<{ x: number; y: number }> = []
- for (let i = 0; i <= N; i++) {
- const p = path.getPointAtLength((total * i) / N)
- pts.push({ x: p.x, y: p.y })
- }
- // variable speed: locate each anchor's arc-length fraction (nearest sample),
- // then build a time-warp from the per-anchor speed multipliers
- let warp: (t: number) => number = (t) => t
- if (speeds && speeds.length >= 2) {
- const anchors = onCurvePoints(d)
- if (anchors.length === speeds.length) {
- const us = anchors.map((a) => {
- let best = 0, bestD = Infinity
- for (let i = 0; i <= N; i++) {
- const dx = pts[i].x - a.x, dy = pts[i].y - a.y
- const dd = dx * dx + dy * dy
- if (dd < bestD) { bestD = dd; best = i }
- }
- return best / N
- })
- warp = makeWarp(us, speeds)
- }
- }
- svg.remove()
- const geom = (u: number) => {
- const f = Math.min(Math.max(u, 0), 1) * N
- const i = Math.min(Math.floor(f), N - 1)
- const k = f - i
- return { x: pts[i].x + (pts[i + 1].x - pts[i].x) * k, y: pts[i].y + (pts[i + 1].y - pts[i].y) * k }
- }
- return (t) => geom(warp(t))
-}
-
-// --- the tween -----------------------------------------------------------------
-
-export interface TweenVars {
- duration?: number
- delay?: number
- ease?: string
- repeat?: number
- yoyo?: boolean
- overwrite?: string // accepted for call-site compat; overwrite is always per-channel
- transformOrigin?: string
- onUpdate?: () => void
- onComplete?: () => void
- [channel: string]: unknown
-}
-
-const CONTROL = new Set(['duration', 'delay', 'ease', 'repeat', 'yoyo', 'overwrite', 'transformOrigin', 'onUpdate', 'onComplete'])
-
-type Apply = (t: number) => void
-
-export class Tween {
- private applies: Apply[] = []
- private channels = new Set<string>()
- private elapsed = 0 // seconds, excludes delay
- private delay: number
- private duration: number
- private repeat: number
- private yoyo: boolean
- private ease: EaseFn
- private vars: TweenVars
- private from: Record<string, unknown> | null
- private started = false
- private dead = false
- target: unknown
-
- constructor(target: unknown, from: Record<string, unknown> | null, to: TweenVars) {
- this.target = target
- this.vars = to
- this.from = from
- this.duration = Math.max(to.duration ?? 0.5, 0.0001)
- this.delay = to.delay ?? 0
- this.repeat = to.repeat ?? 0
- this.yoyo = !!to.yoyo
- this.ease = EASES[to.ease ?? 'power1.out'] ?? EASES.linear
- register(this)
- // fromTo renders its from-state immediately (gsap immediateRender parity)
- if (from) this.start()
- tickerOn()
- }
-
- /** Build interpolators. With explicit from-values this runs at creation;
- * otherwise lazily when the delay elapses (reading current values). */
- private start() {
- if (this.started || this.dead) return
- this.started = true
- const t = this.target
- const from = this.from ?? {}
- const isEl = t instanceof HTMLElement || t instanceof SVGElement
- for (const [key, toVal] of Object.entries(this.vars)) {
- if (CONTROL.has(key) || toVal === undefined) continue
- this.channels.add(key)
- if (!isEl) {
- // plain object tween (countUp state)
- const obj = t as Record<string, number>
- const f = (from[key] as number) ?? obj[key] ?? 0
- const lerp = lerper(f, toVal as number)
- this.applies.push((p) => { obj[key] = lerp(p) as number })
- continue
- }
- const el = t as HTMLElement
- if (key === 'opacity') {
- const f = from.opacity ?? parseFloat(getComputedStyle(el).opacity) ?? 1
- const lerp = lerper(Number(f), Number(toVal))
- this.applies.push((p) => { el.style.opacity = String(lerp(p)) })
- } else if (key === 'x') {
- const xf = xformOf(el)
- const f = Number(from.x ?? xf.x)
- const lerp = lerper(f, Number(toVal))
- this.applies.push((p) => { xf.x = lerp(p) as number; writeXform(el) })
- } else if (key === 'y') {
- const x = xformOf(el)
- const f = Number(from.y ?? x.y)
- const lerp = lerper(f, Number(toVal))
- this.applies.push((p) => { x.y = lerp(p) as number; writeXform(el) })
- } else if (key === 'scale') {
- const x = xformOf(el)
- const f = Number(from.scale ?? x.scaleX)
- const lerp = lerper(f, Number(toVal))
- if (this.vars.transformOrigin) el.style.transformOrigin = String(this.vars.transformOrigin)
- this.applies.push((p) => { const s = lerp(p) as number; x.scaleX = s; x.scaleY = s; writeXform(el) })
- } else if (key === 'color') {
- const f = String(from.color ?? getComputedStyle(el).color)
- const lerp = lerper(f, String(toVal))
- this.applies.push((p) => { el.style.color = String(lerp(p)) })
- } else if (key === 'strokeDashoffset') {
- const f = from.strokeDashoffset ?? getComputedStyle(el).strokeDashoffset
- const lerp = lerper(parseFloat(String(f)) || 0, Number(toVal))
- this.applies.push((p) => { el.style.strokeDashoffset = String(lerp(p)) })
- } else if (key === 'attr') {
- const toAttrs = toVal as Record<string, string | number>
- const fromAttrs = (from.attr ?? {}) as Record<string, string | number>
- for (const [name, tv] of Object.entries(toAttrs)) {
- const fv = fromAttrs[name] ?? el.getAttribute(name) ?? 0
- const lerp = lerper(fv, tv)
- this.applies.push((p) => el.setAttribute(name, String(lerp(p))))
- }
- } else if (key === 'motionPath') {
- const mp = toVal as { path: string; speeds?: number[] }
- const d = mp.path
- const sample = samplePath(d, mp.speeds)
- if (sample) {
- const x = xformOf(el)
- this.applies.push((p) => {
- const pt = sample(p)
- x.x = pt.x
- x.y = pt.y
- writeXform(el)
- })
- }
- }
- }
- // per-channel overwrite: a newer tween on the same target owns its channels
- for (const other of tweensOf(this.target)) {
- if (other === this || other.dead) continue
- if ([...this.channels].some((c) => other.channels.has(c))) other.kill()
- }
- this.applies.forEach((a) => a(0))
- }
-
- /** 0..1 across the whole lifetime (repeats count as complete). */
- progress(): number {
- if (this.dead) return 1
- if (this.repeat === -1) return 0
- const total = this.duration * (1 + this.repeat)
- return Math.min(this.elapsed / total, 1)
- }
-
- /** advance by dt seconds; returns false when finished */
- tick(dt: number): boolean {
- if (this.dead) return false
- if (this.delay > 0) {
- this.delay -= dt
- if (this.delay > 0) return true
- dt = -this.delay
- this.delay = 0
- }
- if (!this.started) this.start()
- this.elapsed += dt
- const cycles = this.elapsed / this.duration
- const isForever = this.repeat === -1
- const done = !isForever && cycles >= 1 + this.repeat
- let t: number
- if (done) {
- t = this.yoyo && (1 + this.repeat) % 2 === 0 ? 0 : 1
- } else {
- const c = Math.floor(cycles)
- const frac = cycles - c
- t = this.yoyo && c % 2 === 1 ? 1 - frac : frac
- }
- const eased = this.ease(t)
- for (const a of this.applies) a(eased)
- this.vars.onUpdate?.()
- if (done) {
- this.dead = true
- unregister(this)
- this.vars.onComplete?.()
- return false
- }
- return true
- }
-
- kill() {
- if (this.dead) return
- this.dead = true
- unregister(this)
- }
-}
-
-// --- registry + ticker -----------------------------------------------------------
-
-const live = new Set<Tween>()
-const byTarget = new Map<unknown, Set<Tween>>()
-
-function register(tw: Tween) {
- live.add(tw)
- let set = byTarget.get(tw.target)
- if (!set) byTarget.set(tw.target, (set = new Set()))
- set.add(tw)
-}
-
-function unregister(tw: Tween) {
- live.delete(tw)
- const set = byTarget.get(tw.target)
- set?.delete(tw)
- if (set && !set.size) byTarget.delete(tw.target)
-}
-
-function tweensOf(target: unknown): Tween[] {
- return [...(byTarget.get(target) ?? [])]
-}
-
-let running = false
-let last = 0
-let timeScale = 1
-let manual = false
-
-function tickerOn() {
- if (running || manual) return
- running = true
- last = performance.now()
- requestAnimationFrame(loop)
-}
-
-function loop(now: number) {
- if (manual) { running = false; return }
- // clamp long gaps (throttled tabs) so loops don't leap wildly
- const dt = Math.min((now - last) / 1000, 0.25) * timeScale
- last = now
- for (const tw of [...live]) tw.tick(dt)
- if (live.size) requestAnimationFrame(loop)
- else running = false
-}
-
-// --- public api --------------------------------------------------------------------
-
-export const anim = {
- to(target: unknown, vars: TweenVars): Tween {
- return new Tween(target, null, vars)
- },
- fromTo(target: unknown, from: Record<string, unknown>, vars: TweenVars): Tween {
- return new Tween(target, from, vars)
- },
- killTweensOf(target: unknown) {
- const targets: unknown[] =
- target instanceof NodeList || Array.isArray(target) ? [...(target as Iterable<unknown>)] : [target]
- for (const t of targets) for (const tw of tweensOf(t)) tw.kill()
- },
- getTweensOf(target: unknown): Tween[] {
- return tweensOf(target)
- },
- killAll() {
- for (const tw of [...live]) tw.kill()
- },
- /** global playback rate (diagnostics/tests) */
- setTimeScale(n: number) {
- timeScale = n
- },
- /** manual clock for tests: stop the rAF loop and drive time by hand */
- setManual(on: boolean) {
- manual = on
- if (!on) tickerOn()
- },
- tick(seconds: number) {
- for (const tw of [...live]) tw.tick(seconds * timeScale)
- },
- get activeCount() {
- return live.size
- },
-}
+// Facade: the animation engine lives in the shared kernel now (kernel/src/
+// anim.ts). This path stays alive so slides code (and in-flight branches)
+// keeps importing './anim' unchanged — see docs/PLATFORM.md §9.
+export * from '../../kernel/src/anim.ts'
diff --git a/slides/src/autosave.ts b/slides/src/autosave.ts
index e8c854ff..b28fa276 100644
--- a/slides/src/autosave.ts
+++ b/slides/src/autosave.ts
@@ -1,143 +1,19 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento/Suite authors
-// Local auto-save + lightweight version history, backed by IndexedDB.
+// Facade: the IndexedDB auto-save/version store lives in the shared kernel now
+// (kernel/src/autosave.ts). This path stays alive so slides code keeps
+// importing './autosave' unchanged — see docs/PLATFORM.md §9.
//
-// Two concerns, one store:
-// · recovery — a single latest snapshot per docId, overwritten each cycle.
-// On reopen, if it differs from the file we loaded, we offer to restore
-// (the safety net for a crash / tab-close before a save, and the ONLY net
-// on browsers without the File System Access API).
-// · versions — a capped, throttled timeline of snapshots per docId, for the
-// "Version history" restore UI.
-//
-// Snapshots hold the plain document JSON (a few KB–tens of KB), NOT the ~430KB
-// HTML shell — restore re-injects via store.replaceDoc. Encrypted decks are
-// never snapshotted here (that would write plaintext to disk); their file
-// write-back stays encrypted.
+// docContentKey stays HERE (not in the kernel): "what counts as content" is a
+// per-app model question — it reads slides-specific fields the kernel must
+// never see. Spaces/dash define their own beside their models.
import type { BentoDoc } from './model'
-const DB_NAME = 'bento-autosave'
-const DB_VERSION = 1
-const RECOVERY = 'recovery'
-const VERSIONS = 'versions'
-const MAX_VERSIONS = 20 // per doc
-const PRUNE_DAYS = 30
-
-export interface Snapshot {
- id?: number
- docId: string
- at: number
- title: string
- json: string
-}
-
-let dbPromise: Promise<IDBDatabase | null> | null = null
-
-function openDb(): Promise<IDBDatabase | null> {
- if (dbPromise) return dbPromise
- dbPromise = new Promise((resolve) => {
- if (typeof indexedDB === 'undefined') { resolve(null); return }
- let req: IDBOpenDBRequest
- try { req = indexedDB.open(DB_NAME, DB_VERSION) } catch { resolve(null); return }
- req.onupgradeneeded = () => {
- const db = req.result
- if (!db.objectStoreNames.contains(RECOVERY)) db.createObjectStore(RECOVERY, { keyPath: 'docId' })
- if (!db.objectStoreNames.contains(VERSIONS)) {
- const s = db.createObjectStore(VERSIONS, { keyPath: 'id', autoIncrement: true })
- s.createIndex('docId', 'docId', { unique: false })
- }
- }
- req.onsuccess = () => resolve(req.result)
- req.onerror = () => resolve(null)
- })
- return dbPromise
-}
-
-function tx<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T | null> {
- return openDb().then((db) => {
- if (!db) return null
- return new Promise<T | null>((resolve) => {
- let t: IDBTransaction
- try { t = db.transaction(store, mode) } catch { resolve(null); return }
- const req = fn(t.objectStore(store))
- req.onsuccess = () => resolve(req.result as T)
- req.onerror = () => resolve(null)
- })
- })
-}
+export * from '../../kernel/src/autosave.ts'
/** The content that actually matters for "did this change" — excludes volatile
* fields (modified timestamp, collab sync state) that churn without a real edit. */
export function docContentKey(doc: BentoDoc): string {
return JSON.stringify([doc.title, doc.size, doc.theme, doc.slides, doc.layouts ?? null, doc.fonts ?? null, doc.assets ?? null])
}
-
-export async function putRecovery(doc: BentoDoc): Promise<void> {
- await tx(RECOVERY, 'readwrite', (s) =>
- s.put({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))
-}
-
-export async function getRecovery(docId: string): Promise<Snapshot | null> {
- return (await tx<Snapshot>(RECOVERY, 'readonly', (s) => s.get(docId))) ?? null
-}
-
-export async function clearRecovery(docId: string): Promise<void> {
- await tx(RECOVERY, 'readwrite', (s) => s.delete(docId))
-}
-
-/** Delete every version-history snapshot for a docId. Used when a deck is
- * encrypted: the plaintext snapshots written before encryption was enabled must
- * not linger in IndexedDB (they'd defeat the encryption the user just turned on). */
-export async function clearVersions(docId: string): Promise<void> {
- const all = await listVersions(docId)
- await Promise.all(all.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
-}
-
-export async function addVersion(doc: BentoDoc): Promise<void> {
- await tx(VERSIONS, 'readwrite', (s) =>
- s.add({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))
- // prune to the newest MAX_VERSIONS for this doc
- const all = await listVersions(doc.docId)
- if (all.length > MAX_VERSIONS) {
- const doomed = all.slice(MAX_VERSIONS)
- await Promise.all(doomed.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
- }
-}
-
-export async function listVersions(docId: string): Promise<Snapshot[]> {
- const db = await openDb()
- if (!db) return []
- return new Promise((resolve) => {
- let t: IDBTransaction
- try { t = db.transaction(VERSIONS, 'readonly') } catch { resolve([]); return }
- const idx = t.objectStore(VERSIONS).index('docId')
- const out: Snapshot[] = []
- const req = idx.openCursor(IDBKeyRange.only(docId))
- req.onsuccess = () => {
- const cur = req.result
- if (cur) { out.push(cur.value as Snapshot); cur.continue() }
- else resolve(out.sort((a, b) => b.at - a.at)) // newest first
- }
- req.onerror = () => resolve([])
- })
-}
-
-/** Drop snapshots older than PRUNE_DAYS across all docs (housekeeping). */
-export async function pruneOld(): Promise<void> {
- const cutoff = Date.now() - PRUNE_DAYS * 24 * 60 * 60 * 1000
- const db = await openDb()
- if (!db) return
- for (const store of [VERSIONS, RECOVERY]) {
- try {
- const t = db.transaction(store, 'readwrite')
- const req = t.objectStore(store).openCursor()
- req.onsuccess = () => {
- const cur = req.result
- if (!cur) return
- if ((cur.value as Snapshot).at < cutoff) cur.delete()
- cur.continue()
- }
- } catch { /* best effort */ }
- }
-}
diff --git a/slides/src/save.ts b/slides/src/save.ts
index 4fd1f860..ea1d0a50 100644
--- a/slides/src/save.ts
+++ b/slides/src/save.ts
@@ -1,280 +1,6 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento/Suite authors
-// Self-saving: a Bento file writes itself back to disk with updated data.
-//
-// At boot (before the app mutates the DOM) we deep-clone the document. On save
-// we swap the clone's data block content for the current model JSON and
-// serialize the clone back to an HTML string — byte-for-byte the same app
-// shell, new document inside. TiddlyWiki pioneered this trick.
-
-import type { BentoDoc } from './model'
-
-const DATA_BLOCK_ID = 'bento-doc'
-// Split so the literal never appears in the bundle (it would terminate the
-// inline <script> that carries this very code inside a built Bento file).
-const SCRIPT_CLOSE = '</scr' + 'ipt>'
-
-let pristine: Document | null = null
-
-/** Call first thing at boot, before any DOM mutation. */
-export function capturePristine() {
- pristine = document.cloneNode(true) as Document
-}
-
-export function readEmbeddedDoc(): string | null {
- const block = document.getElementById(DATA_BLOCK_ID)
- const text = block?.textContent?.trim()
- return text || null
-}
-
-/** Serialize a raw data-block body into an app shell. */
-function serializeBody(shell: Document, body: string, title: string): string {
- const clone = shell.cloneNode(true) as Document
-
- let block = clone.getElementById(DATA_BLOCK_ID)
- if (!block) {
- block = clone.createElement('script')
- block.setAttribute('type', 'application/bento+json')
- block.id = DATA_BLOCK_ID
- clone.head.appendChild(block)
- }
- // <-escape so the JSON can never contain "</script>" and break the file.
- block.textContent = '\n' + body.replace(/</g, '\\u003c') + '\n'
-
- const titleEl = clone.querySelector('title')
- if (titleEl) titleEl.textContent = title + ' — Bento Slides'
-
- const html = '<!DOCTYPE html>\n' + clone.documentElement.outerHTML
- // Belt-and-braces: an unescaped close tag anywhere in generated output would
- // corrupt the file; this should never trigger given the escaping above.
- if (html.split(SCRIPT_CLOSE).length !== clone.querySelectorAll('script').length + 1) {
- console.warn('bento: unexpected script-close count in serialized file')
- }
- return html
-}
-
-/**
- * Serialize `doc` into an arbitrary app shell (a parsed Bento HTML document).
- * Used with the boot-time pristine copy on every save, and by the self-update
- * flow with a freshly fetched NEWER shell — same document, new app around it.
- * PLAIN output — encryption-aware callers use serializeDocInto/serializeAuto.
- */
-export function serializeWith(shell: Document, doc: BentoDoc): string {
- return serializeBody(shell, JSON.stringify(doc), doc.title)
-}
-
-/** The full .bento.html file content with `doc` embedded (plain). */
-export function serializeFile(doc: BentoDoc): string {
- if (!pristine) throw new Error('capturePristine() was not called at boot')
- return serializeWith(pristine, doc)
-}
-
-// --- password encryption ----------------------------------------------------
-//
-// An encrypted file keeps the SAME plaintext #bento-doc block (the splice
-// contract old updaters rely on) — but the block holds a bento/enc envelope
-// instead of the document: AES-GCM-256 over the doc JSON, key derived from
-// the password with PBKDF2-SHA-256. The password is held in memory for the
-// session so ⌘S and self-update keep writing encrypted output.
-
-export interface EncEnvelope {
- format: 'bento/enc'
- v: 1
- it: number
- salt: string
- iv: string
- data: string
-}
-
-const ENC_ITERATIONS = 300_000
-
-const eb64 = {
- enc(bytes: Uint8Array): string {
- let s = ''
- for (const b of bytes) s += String.fromCharCode(b)
- return btoa(s)
- },
- dec(s: string): Uint8Array {
- const b = atob(s)
- const out = new Uint8Array(b.length)
- for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)
- return out
- },
-}
-
-let encPassword: string | null = null
-
-/** Set (or clear with null) the password used for every subsequent save. */
-export function setEncryptionPassword(p: string | null) {
- encPassword = p
-}
-
-export const isEncryptionActive = () => encPassword !== null
-
-/** Parse a data-block body as an encryption envelope; null if it is not one. */
-export function parseEnvelope(text: string): EncEnvelope | null {
- try {
- const env = JSON.parse(text)
- if (env && env.format === 'bento/enc' && env.v === 1 && env.data && env.salt && env.iv) {
- return env as EncEnvelope
- }
- } catch {
- /* not an envelope */
- }
- return null
-}
-
-async function deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {
- const material = await crypto.subtle.importKey(
- 'raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey'])
- return crypto.subtle.deriveKey(
- { name: 'PBKDF2', hash: 'SHA-256', salt: salt as BufferSource, iterations },
- material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
-}
-
-async function encryptBody(json: string, password: string): Promise<string> {
- const salt = new Uint8Array(16)
- const iv = new Uint8Array(12)
- crypto.getRandomValues(salt)
- crypto.getRandomValues(iv)
- const key = await deriveKey(password, salt, ENC_ITERATIONS)
- const ct = await crypto.subtle.encrypt(
- { name: 'AES-GCM', iv: iv as BufferSource }, key, new TextEncoder().encode(json))
- const env: EncEnvelope = {
- format: 'bento/enc', v: 1, it: ENC_ITERATIONS,
- salt: eb64.enc(salt), iv: eb64.enc(iv), data: eb64.enc(new Uint8Array(ct)),
- }
- return JSON.stringify(env)
-}
-
-/** Decrypt an envelope with a candidate password; null on wrong password. */
-export async function decryptEnvelope(env: EncEnvelope, password: string): Promise<string | null> {
- try {
- const key = await deriveKey(password, eb64.dec(env.salt), env.it || ENC_ITERATIONS)
- const pt = await crypto.subtle.decrypt(
- { name: 'AES-GCM', iv: eb64.dec(env.iv) as BufferSource }, key, eb64.dec(env.data) as BufferSource)
- return new TextDecoder().decode(pt)
- } catch {
- return null
- }
-}
-
-/**
- * Encryption-aware serialization into an arbitrary shell — THE path for
- * saves and self-updates. Plain when no password is active.
- */
-export async function serializeDocInto(shell: Document, doc: BentoDoc): Promise<string> {
- const body = encPassword
- ? await encryptBody(JSON.stringify(doc), encPassword)
- : JSON.stringify(doc)
- return serializeBody(shell, body, doc.title)
-}
-
-/** Encryption-aware serializeFile. */
-export async function serializeAuto(doc: BentoDoc): Promise<string> {
- if (!pristine) throw new Error('capturePristine() was not called at boot')
- return serializeDocInto(pristine, doc)
-}
-
-export function suggestedFileName(doc: BentoDoc, suffix = ''): string {
- const base = doc.title.replace(/[^\w\d-]+/g, '_').replace(/^_+|_+$/g, '') || 'Untitled'
- return `${base}${suffix ? `-${suffix}` : ''}.bento.html`
-}
-
-// --- writing to disk --------------------------------------------------------
-
-type SaveResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'
-
-interface FsFileHandle {
- createWritable(): Promise<{ write(data: Blob): Promise<void>; close(): Promise<void> }>
- name: string
-}
-
-let fileHandle: FsFileHandle | null = null
-
-const hasFsAccess = () => typeof (window as any).showSaveFilePicker === 'function'
-
-async function pickHandle(doc: BentoDoc, suffix = ''): Promise<FsFileHandle | null> {
- try {
- return await (window as any).showSaveFilePicker({
- suggestedName: suggestedFileName(doc, suffix),
- types: [{ description: 'Bento Slides', accept: { 'text/html': ['.html'] } }],
- })
- } catch (err: any) {
- if (err?.name === 'AbortError') return null
- throw err
- }
-}
-
-async function writeHandle(handle: FsFileHandle, html: string) {
- const writable = await handle.createWritable()
- await writable.write(new Blob([html], { type: 'text/html' }))
- await writable.close()
-}
-
-export function downloadFile(html: string, name: string) {
- const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }))
- const a = document.createElement('a')
- a.href = url
- a.download = name
- a.click()
- setTimeout(() => URL.revokeObjectURL(url), 5000)
-}
-
-/**
- * Save the document. Chrome/Edge: File System Access API (picker on first
- * save, silent rewrite after). Firefox/Safari: download a copy.
- */
-export async function saveFile(doc: BentoDoc, forcePicker = false): Promise<SaveResult> {
- const html = await serializeAuto(doc)
- if (hasFsAccess()) {
- if (forcePicker || !fileHandle) {
- const handle = await pickHandle(doc)
- if (!handle) return 'cancelled'
- fileHandle = handle
- await writeHandle(handle, html)
- return 'saved-as'
- }
- await writeHandle(fileHandle, html)
- return 'saved'
- }
- downloadFile(html, suggestedFileName(doc))
- return 'downloaded'
-}
-
-export const currentFileName = () => fileHandle?.name ?? null
-
-// --- self-update writing ----------------------------------------------------
-
-/** Whether we hold a writable handle to the file (in-place update possible). */
-export const hasFileHandle = () => fileHandle !== null
-
-/** Overwrite the held file with arbitrary html (the freshly updated shell). */
-export async function writeUpdatedFile(html: string): Promise<void> {
- if (!fileHandle) throw new Error('no file handle')
- await writeHandle(fileHandle, html)
-}
-
-/**
- * Save updated html via a picker (user points it at the file they have open,
- * or anywhere else). Returns false if cancelled. Keeps the picked handle so
- * subsequent ⌘S saves go to the same place.
- */
-export async function writeUpdatedFileAs(
- html: string,
- doc: BentoDoc,
- opts: { suffix?: string; keepHandle?: boolean } = {},
-): Promise<boolean> {
- if (!hasFsAccess()) {
- downloadFile(html, suggestedFileName(doc, opts.suffix))
- return true
- }
- const handle = await pickHandle(doc, opts.suffix)
- if (!handle) return false
- // Share/export artifacts must NOT become the ⌘S target — otherwise the next
- // save would overwrite e.g. a view-only copy with the FULL document (owner
- // keys included). Only an explicit keepHandle retargets in-place saving.
- if (opts.keepHandle) fileHandle = handle
- await writeHandle(handle, html)
- return true
-}
+// Facade: self-save + bento/enc encryption live in the shared kernel now
+// (kernel/src/save.ts). This path stays alive so slides code keeps importing
+// './save' unchanged — see docs/PLATFORM.md §9.
+export * from '../../kernel/src/save.ts'
diff --git a/slides/vite.config.ts b/slides/vite.config.ts
index 166672d6..eb02eb39 100644
--- a/slides/vite.config.ts
+++ b/slides/vite.config.ts
@@ -13,6 +13,10 @@ export default defineConfig({
// compare against the release manifest. Single source: package.json.
define: { __APP_VERSION__: JSON.stringify(pkg.version) },
plugins: [...(process.env.SINGLEFILE ? [viteSingleFile()] : [])],
+ // Dev-only: allow serving ../kernel (shared TS-source kernel) — without a
+ // workspace root, vite's fs allow-list stops at the app dir. Build output
+ // is unaffected (rollup has no such restriction).
+ server: { fs: { allow: ['..'] } },
build: {
// Keep asset inlining aggressive; a Bento file must have zero external requests.
assetsInlineLimit: 100_000_000,