Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: preference storage that cannot take the app down (#205)

nyblnetc1e8902745b0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8c8384af..47d79063 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -122,6 +122,15 @@ jobs:
# file carrying a script tag.
run: node scripts/test-preview.ts
+ - name: Guarded storage rig
+ # localStorage's absence is hostile: reading the PROPERTY throws, so
+ # `if (localStorage)` is itself the crash and one bare read at module
+ # scope takes the whole file down before it paints. Measured in a
+ # sandboxed iframe. The rig simulates each failure mode and pins the
+ # regression: importing a module that reads storage on load must not
+ # throw when storage does.
+ run: node scripts/test-storage.ts
+
- name: Model key tables match the format
# slides/src/modelkeys.generated.ts is derived from model.ts and drives
# validate()'s unknown-key check. A stale copy would report real
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5be66d32..d817627d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,17 @@ pre-1.0.
## [Unreleased]
+- **Fix: a deck opens where the browser refuses it storage.** With site data
+ blocked, inside some embedded webviews, or in any sandboxed frame, a Bento
+ file showed *"This file could not start"* and nothing else — because reading
+ the `localStorage` property (not calling a method on it, merely reading it)
+ throws in those contexts, and the very first thing the app did was read your
+ saved language. One unreadable preference cost you the whole document.
+
+ Preferences now fall back to their defaults instead: the deck opens and
+ behaves as it would for a first-time visitor. Anything you change during the
+ session works normally; it just is not remembered.
+
## [1.0.14] — 2026-08-02
- **Pan the canvas by dragging, and past the slide's edges.** The scrollbars
diff --git a/kernel/src/i18n.ts b/kernel/src/i18n.ts
index 2e201549..8c60615b 100644
--- a/kernel/src/i18n.ts
+++ b/kernel/src/i18n.ts
@@ -17,6 +17,9 @@
// resolving at module scope would run against an empty registry and silently
// fall everyone back to English. Registration also clears the memo.
+
+import { lsDel, lsGet, lsSet } from './storage.ts'
+
export type Catalog = Record<string, string>
export interface LocaleChoice { code: string; label: string }
@@ -170,7 +173,7 @@ const pseudo = (s: string): string =>
'⟧'
function resolve(): string {
- const saved = localStorage.getItem('bento-lang')
+ const saved = lsGet('bento-lang')
if (saved) return saved
const nav = navigator.language || 'en'
if (hasLocale(nav)) return nav
@@ -190,8 +193,8 @@ export const locale = (): string => activeLocale()
/** Persist the override and switch. Callers re-render their own UI. */
export function setLocale(code: string): void {
- if (code === 'en') localStorage.removeItem('bento-lang')
- else localStorage.setItem('bento-lang', code)
+ if (code === 'en') lsDel('bento-lang')
+ else lsSet('bento-lang', code)
current = code
}
diff --git a/kernel/src/storage.ts b/kernel/src/storage.ts
new file mode 100644
index 00000000..7afbb8de
--- /dev/null
+++ b/kernel/src/storage.ts
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Preference storage that cannot take the app down.
+//
+// WHY THIS EXISTS. `localStorage` is not always there, and the way it is absent
+// is worse than useful: reading the PROPERTY throws, before any method is
+// called. So the obvious defences are themselves the crash —
+//
+// if (localStorage) … // throws
+// if (typeof localStorage !== 'undefined') … // throws
+//
+// — and the only way to find out is to attempt it inside a `try`. One bare read
+// at module scope therefore takes the whole file down before it paints. That is
+// exactly what happened: `resolve()` in i18n.ts reads `bento-lang` on import, so
+// in a context without storage the shell caught the SecurityError and printed
+// "This file could not start" instead of opening the deck.
+//
+// The contexts where that happens are real, and none of them are exotic:
+//
+// · a sandboxed iframe without `allow-same-origin` (an opaque origin — no
+// localStorage, no IndexedDB, no caches)
+// · a browser set to block site data, or an embedded webview with storage
+// partitioned off
+// · Safari private browsing, historically, on write
+//
+// In every one of them a Bento file should open and work. Preferences are
+// preferences: not having them is what a first-time visitor looks like, which
+// is a path the app already handles well. Losing the DOCUMENT because we could
+// not read a language code is a bad trade.
+//
+// So: reads degrade to "unset", writes degrade to "did not stick", and nothing
+// throws. Both layers are guarded deliberately — the property access throws in
+// an opaque origin, and the methods can throw separately on quota.
+//
+// IndexedDB already does this (autosave.ts guards `indexedDB.open`), so the
+// gap this closes is localStorage, and specifically the READS: writes were
+// mostly defended already, because a full disk is the failure somebody hit
+// first. Reads are what run at boot.
+
+/** The Storage object, or null where the context refuses to hand one over. */
+function backing(): Storage | null {
+ try {
+ return globalThis.localStorage ?? null
+ } catch {
+ return null // opaque origin, site data blocked, storage partitioned off
+ }
+}
+
+/** A stored preference, or null when unset OR unavailable. Never throws. */
+export function lsGet(key: string): string | null {
+ try {
+ return backing()?.getItem(key) ?? null
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Store a preference. Returns whether it actually stuck, so a caller that
+ * cares (an explicit "remember this" affordance) can say so — most do not.
+ */
+export function lsSet(key: string, value: string): boolean {
+ try {
+ const s = backing()
+ if (!s) return false
+ s.setItem(key, value)
+ return true
+ } catch {
+ return false // quota, or a context that allows reads but refuses writes
+ }
+}
+
+/** Forget a preference. A no-op where there is nothing to forget from. */
+export function lsDel(key: string): void {
+ try {
+ backing()?.removeItem(key)
+ } catch {
+ /* nothing to remove from */
+ }
+}
+
+/**
+ * A JSON-shaped preference, falling back on anything unusable.
+ *
+ * Several call sites stored objects and each re-invented
+ * `JSON.parse(getItem(k) ?? '{}')` inside its own try — which meant a corrupt
+ * value and an unavailable store took different paths in different files. Here
+ * they are the same path: you get the fallback.
+ */
+export function lsJson<T>(key: string, fallback: T): T {
+ const raw = lsGet(key)
+ if (raw === null) return fallback
+ try {
+ const parsed = JSON.parse(raw)
+ return (parsed ?? fallback) as T
+ } catch {
+ return fallback // someone else's data, or a half-written value
+ }
+}
+
+/** Store a JSON-shaped preference. Returns whether it stuck. */
+export function lsSetJson(key: string, value: unknown): boolean {
+ try {
+ return lsSet(key, JSON.stringify(value))
+ } catch {
+ return false // circular, or otherwise not serialisable
+ }
+}
+
+/**
+ * Is persistent preference storage available at all?
+ *
+ * For UI that would otherwise promise something it cannot keep — "remember my
+ * name", a version-history panel. Not for guarding the accessors above: they
+ * are already safe, and a caller checking first would just be racing.
+ */
+export function storageAvailable(): boolean {
+ return backing() !== null
+}
diff --git a/kernel/src/update.ts b/kernel/src/update.ts
index 21eb721b..e7ec0374 100644
--- a/kernel/src/update.ts
+++ b/kernel/src/update.ts
@@ -25,6 +25,7 @@ import {
serializeDocInto, serializeAuto, suggestedFileName, downloadFile, openedFileName, fileBase,
hasFileHandle, writeUpdatedFile, writeUpdatedFileAs,
} from './save.ts'
+import { lsDel, lsGet, lsSet } from './storage.ts'
declare const __APP_VERSION__: string
@@ -41,23 +42,23 @@ export const APP_VERSION: string = typeof __APP_VERSION__ !== 'undefined' ? __AP
*/
export const offlineEnabled = (): boolean => {
try {
- return localStorage.getItem('bento-offline') === 'on'
+ return lsGet('bento-offline') === 'on'
} catch {
return false
}
}
export const setOffline = (on: boolean): void => {
try {
- localStorage.setItem('bento-offline', on ? 'on' : 'off')
+ lsSet('bento-offline', on ? 'on' : 'off')
} catch {
/* storage unavailable */
}
}
-export const autoCheckEnabled = (): boolean => localStorage.getItem('bento-auto-check') !== 'off'
+export const autoCheckEnabled = (): boolean => lsGet('bento-auto-check') !== 'off'
export const setAutoCheck = (on: boolean): void => {
- if (on) localStorage.removeItem('bento-auto-check')
- else localStorage.setItem('bento-auto-check', 'off')
+ if (on) lsDel('bento-auto-check')
+ else lsSet('bento-auto-check', 'off')
}
/** Where shipped files look for releases (per-app, from configureApp).
@@ -214,7 +215,7 @@ async function verifyManifest(raw: string): Promise<ReleaseInfo> {
/** Ask the release origin for the latest version. */
export async function checkForUpdates(manifestUrl?: string): Promise<UpdateCheck> {
- const url = manifestUrl ?? localStorage.getItem('bento-update-url') ?? updateManifestUrl()
+ const url = manifestUrl ?? lsGet('bento-update-url') ?? updateManifestUrl()
try {
const res = await fetch(url, { cache: 'no-store' })
if (!res.ok) throw new Error(`release server answered ${res.status}`)
diff --git a/scripts/test-storage.ts b/scripts/test-storage.ts
new file mode 100644
index 00000000..caac36dc
--- /dev/null
+++ b/scripts/test-storage.ts
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Guarded preference-storage rig.
+//
+// node scripts/test-storage.ts (Node ≥ 23.6 strips types natively)
+//
+// WHAT THIS PROVES. `localStorage` is not always available, and the way it is
+// absent is hostile: reading the PROPERTY throws, before any method is called.
+// So `if (localStorage)` and `typeof localStorage` are themselves the crash,
+// and a single bare read at module scope takes the whole file down before it
+// paints. Measured: in a sandboxed iframe without `allow-same-origin`, a deck
+// showed "This file could not start: Failed to read the 'localStorage'
+// property from 'Window'" — the shell caught it and gave up, because
+// `resolve()` in i18n.ts reads `bento-lang` on import.
+//
+// The contexts are ordinary: an opaque origin, a browser set to block site
+// data, an embedded webview with storage partitioned off, Safari private
+// browsing. In all of them a Bento file must still OPEN. Preferences are
+// preferences; losing the document because a language code was unreadable is
+// the wrong trade.
+//
+// So the rig simulates each way storage fails and asserts the accessors stay
+// quiet — including the case that actually broke, which is importing a module
+// that reads storage while merely being loaded.
+
+import { lsGet, lsSet, lsDel, lsJson, lsSetJson, storageAvailable } from '../kernel/src/storage.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}`)
+}
+
+/** Replace globalThis.localStorage for one scenario. */
+function withStorage(descriptor: PropertyDescriptor, fn: () => void) {
+ const had = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, ...descriptor })
+ try { fn() } finally {
+ if (had) Object.defineProperty(globalThis, 'localStorage', had)
+ else delete (globalThis as Record<string, unknown>).localStorage
+ }
+}
+
+/** A minimal in-memory Storage, optionally refusing writes (quota). */
+function fakeStorage(opts: { writable?: boolean } = {}) {
+ const map = new Map<string, string>()
+ return {
+ get length() { return map.size },
+ getItem: (k: string) => map.get(k) ?? null,
+ setItem: (k: string, v: string) => {
+ if (opts.writable === false) throw new Error('QuotaExceededError')
+ map.set(k, v)
+ },
+ removeItem: (k: string) => { map.delete(k) },
+ clear: () => map.clear(),
+ key: (i: number) => [...map.keys()][i] ?? null,
+ } as unknown as Storage
+}
+
+// ---- 1. the property itself throws (an opaque origin) -----------------------
+// This is the case that took the app down. `backing()` must swallow it.
+withStorage({ get() { throw new Error('SecurityError: The document is sandboxed and lacks the allow-same-origin flag') } }, () => {
+ ok(lsGet('bento-lang') === null, 'a throwing localStorage property reads as null, not an exception')
+ ok(lsSet('bento-lang', 'ja') === false, 'a write reports false rather than throwing')
+ ok(lsJson('bento-panel-open', { a: 1 }).a === 1, 'lsJson falls back when the property throws')
+ ok(storageAvailable() === false, 'storageAvailable is false')
+ let threw = false
+ try { lsDel('bento-lang') } catch { threw = true }
+ ok(!threw, 'lsDel is a no-op rather than an exception')
+})
+
+// ---- 2. no localStorage at all (node, some workers) -------------------------
+{
+ const had = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
+ delete (globalThis as Record<string, unknown>).localStorage
+ ok(lsGet('x') === null, 'an absent localStorage reads as null')
+ ok(lsSet('x', '1') === false, 'an absent localStorage refuses writes cleanly')
+ ok(storageAvailable() === false, 'storageAvailable is false when absent')
+ if (had) Object.defineProperty(globalThis, 'localStorage', had)
+}
+
+// ---- 3. a working store round-trips ----------------------------------------
+withStorage({ value: fakeStorage() }, () => {
+ ok(lsSet('bento-author', 'Ada') === true, 'a write to a working store reports true')
+ ok(lsGet('bento-author') === 'Ada', 'and reads back')
+ ok(storageAvailable() === true, 'storageAvailable is true')
+ lsDel('bento-author')
+ ok(lsGet('bento-author') === null, 'lsDel removes it')
+ ok(lsSetJson('bento-ed-panels', { left: 260 }) === true, 'lsSetJson stores')
+ ok(lsJson<{ left: number }>('bento-ed-panels', { left: 0 }).left === 260, 'lsJson reads it back')
+})
+
+// ---- 4. reads work, writes throw (quota, Safari private) --------------------
+withStorage({ value: fakeStorage({ writable: false }) }, () => {
+ ok(lsSet('k', 'v') === false, 'a quota failure reports false rather than throwing')
+ ok(lsGet('anything') === null, 'reads still work alongside a refusing write')
+})
+
+// ---- 5. corrupt JSON is somebody else's data, not a crash -------------------
+withStorage({ value: fakeStorage() }, () => {
+ lsSet('bento-panel-open', '{not json')
+ ok(lsJson('bento-panel-open', { safe: true }).safe === true, 'unparseable JSON falls back')
+ lsSet('bento-panel-open', 'null')
+ ok(lsJson('bento-panel-open', { safe: true }).safe === true, 'a stored null falls back rather than returning null')
+})
+
+// ---- 6. THE REGRESSION: importing a module that reads storage on load -------
+// i18n.ts calls resolve() at module scope, which reads `bento-lang`. Under a
+// throwing localStorage that import used to blow up the whole boot. Nothing
+// else in this rig would catch that, because it is not about the accessor's
+// return value — it is about whether the file can be loaded at all.
+await (async () => {
+ let error: unknown = null
+ const had = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ get() { throw new Error('SecurityError: sandboxed, lacks allow-same-origin') },
+ })
+ try {
+ const mod = await import('../kernel/src/i18n.ts')
+ ok(typeof mod.t === 'function', 'i18n imports under a throwing localStorage and exports t()')
+ ok(mod.t('Present') === 'Present', 'and t() falls back to English with no stored locale')
+ } catch (e) {
+ error = e
+ } finally {
+ if (had) Object.defineProperty(globalThis, 'localStorage', had)
+ else delete (globalThis as Record<string, unknown>).localStorage
+ }
+ ok(error === null, `importing i18n must not throw when storage does (${error ? String(error).slice(0, 90) : 'ok'})`)
+})()
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/src/editor/comments.ts b/slides/src/editor/comments.ts
index 6baf02a3..5d3771f0 100644
--- a/slides/src/editor/comments.ts
+++ b/slides/src/editor/comments.ts
@@ -9,24 +9,25 @@
import type { Store } from '../store'
import { uid, type Comment } from '../model'
import { t } from '../i18n'
+import { lsGet, lsSet } from '../../../kernel/src/storage.ts'
/** The commenter's name, remembered per browser (localStorage, never sent
* anywhere); asked for on first use. */
export function commentAuthor(): string | null {
- let name = localStorage.getItem('bento-author')
+ let name = lsGet('bento-author')
if (!name) {
name = window.prompt(t('Your name (shown on comments):'))?.trim() || ''
if (!name) return null
- localStorage.setItem('bento-author', name)
+ lsSet('bento-author', name)
}
return name
}
/** Re-ask for the name; existing threads keep their original author. */
export function changeCommentAuthor(): string | null {
- const next = window.prompt(t('Your name (shown on new comments):'), localStorage.getItem('bento-author') ?? '')?.trim()
+ const next = window.prompt(t('Your name (shown on new comments):'), lsGet('bento-author') ?? '')?.trim()
if (!next) return null
- localStorage.setItem('bento-author', next)
+ lsSet('bento-author', next)
return next
}
@@ -124,7 +125,7 @@ export class CommentsUI {
: typeof c.x === 'number' ? t('Comment · point ({x}, {y})', { x: c.x!, y: c.y! }) : t('Comment · slide')
const me = document.createElement('button')
me.className = 'ed-comment-me'
- me.textContent = t('you: {name} ✎', { name: localStorage.getItem('bento-author') ?? '—' })
+ me.textContent = t('you: {name} ✎', { name: lsGet('bento-author') ?? '—' })
me.title = t('Change the name used for your new comments and replies')
me.addEventListener('click', () => {
const next = changeCommentAuthor()
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 7ee57265..a239cc95 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -28,6 +28,7 @@ import { availablePacks, fetchPack, markFileSaved, packCoverage, packsInFile, st
import { injectFonts } from '../fonts'
import { appConfig } from '../../../kernel/src/app.ts'
import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
+import { lsGet, lsJson, lsSet } from '../../../kernel/src/storage.ts'
const i18nT = t
@@ -362,7 +363,7 @@ export class Editor {
// hint merely plays — so it keeps nudging until it's used). Hover replays it
// any time (CSS :hover). When the laps finish fading, just drop the class so
// hover takes over cleanly (a lingering class would replay on mouse-out).
- try { if (!localStorage.getItem('bento-slideshow-started')) pill.classList.add('ed-hint-pulse') } catch { /* storage off */ }
+ if (!lsGet('bento-slideshow-started')) pill.classList.add('ed-hint-pulse')
pill.addEventListener('animationend', (e) => {
if ((e as AnimationEvent).animationName !== 'ed-runner-fade') return
pill.classList.remove('ed-hint-pulse')
@@ -450,7 +451,7 @@ export class Editor {
private restorePanelWidths() {
try {
- const saved = JSON.parse(localStorage.getItem('bento-ed-panels') ?? '{}')
+ const saved = lsJson<Record<string, number>>('bento-ed-panels', {})
for (const side of ['left', 'right'] as const) {
const [min, max] = Editor.PANEL_BOUNDS[side]
if (typeof saved[side] === 'number') this.panelW[side] = Math.min(max, Math.max(min, saved[side]))
@@ -500,7 +501,7 @@ export class Editor {
handle.appendChild(toggle)
queueMicrotask(() => this.updatePanelChevrons())
const commit = () => {
- localStorage.setItem('bento-ed-panels', JSON.stringify(this.panelW))
+ lsSet('bento-ed-panels', JSON.stringify(this.panelW))
// thumbnails render at a width derived from the sidebar — refit them
if (side === 'left') this.rebuildSidebar()
}
@@ -1004,13 +1005,13 @@ export class Editor {
nameInput.type = 'text'
nameInput.placeholder = t('Guest')
try {
- nameInput.value = localStorage.getItem('bento-author') ?? ''
+ nameInput.value = lsGet('bento-author') ?? ''
} catch {
/* storage unavailable */
}
nameInput.addEventListener('change', () => {
try {
- localStorage.setItem('bento-author', nameInput.value.trim())
+ lsSet('bento-author', nameInput.value.trim())
} catch {
/* storage unavailable */
}
@@ -1040,7 +1041,7 @@ export class Editor {
else if (cme.v === 2 && cme.ownerPriv) { myRole = 'owner'; myPub = cme.owner }
else if (cme.v === 2 && cme.invite) {
myRole = 'editor'
- try { myPub = JSON.parse(localStorage.getItem(`bento-member-${this.store.doc.docId}`) ?? 'null')?.pub } catch { /* absent */ }
+ myPub = lsJson<{ pub?: string } | null>(`bento-member-${this.store.doc.docId}`, null)?.pub
} else if (cme.writerPriv) { myRole = 'editor'; myPub = cme.writerPub }
if (myRole) {
const label = div('ed-share-label')
@@ -1050,7 +1051,7 @@ export class Editor {
const who = document.createElement('span')
who.className = 'who'
let myName = t('Guest')
- try { myName = localStorage.getItem('bento-author') || myName } catch { /* ok */ }
+ myName = lsGet('bento-author') || myName
who.textContent = `${myName} (${t('you')})`
const where = document.createElement('span')
where.className = 'where'
@@ -1856,7 +1857,7 @@ export class Editor {
present(fromStart = false, fullscreen = true) {
if (this.presenting) return
// They've started a slideshow — retire the first-run nudge for good.
- try { localStorage.setItem('bento-slideshow-started', '1') } catch { /* storage off */ }
+ lsSet('bento-slideshow-started', '1')
document.querySelector('.ed-hint-pulse')?.classList.remove('ed-hint-pulse')
this.canvas.commitTextEdit()
this.presenting = true
@@ -2248,14 +2249,14 @@ export class Editor {
private noticeIfCannotWriteInPlace() {
if (canWriteInPlace()) return
- if (localStorage.getItem(SAVE_NOTICE_KEY) === 'seen') return
+ if (lsGet(SAVE_NOTICE_KEY) === 'seen') return
const bar = div('ed-recover')
const msg = document.createElement('span')
msg.textContent = t('This browser can’t rewrite files in place. ⌘S will download an updated copy instead — your work is also kept in this browser and offered back if you reopen.')
const ok = document.createElement('button')
ok.className = 'ed-btn ed-btn-primary'
ok.textContent = t('Got it')
- ok.addEventListener('click', () => { localStorage.setItem(SAVE_NOTICE_KEY, 'seen'); bar.remove() })
+ ok.addEventListener('click', () => { lsSet(SAVE_NOTICE_KEY, 'seen'); bar.remove() })
bar.append(msg, ok)
document.body.appendChild(bar)
}
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 88b37ea5..574b374d 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -13,6 +13,7 @@ import { CHART_PRESETS } from '../charts'
import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'
import { ICONS } from '../icons'
import { t } from '../i18n'
+import { lsJson, lsSet } from '../../../kernel/src/storage.ts'
// Hover help for panel rows, keyed by the RAW English label (translated at
// render). A missing entry means no tooltip — better silence than an echo.
@@ -181,7 +182,7 @@ export class PropsPanel {
*/
private applyAccordion() {
let openState: Record<string, boolean> = {}
- try { openState = JSON.parse(localStorage.getItem('bento-panel-open') ?? '{}') } catch { /* defaults */ }
+ openState = lsJson<Record<string, boolean>>('bento-panel-open', {})
const headers = [...this.host.querySelectorAll<HTMLElement>('.ed-section')]
for (const h of headers) {
const key = h.textContent ?? ''
@@ -204,7 +205,7 @@ export class PropsPanel {
const nowClosed = h.classList.toggle('closed')
body.style.display = nowClosed ? 'none' : ''
openState[key] = !nowClosed
- localStorage.setItem('bento-panel-open', JSON.stringify(openState))
+ lsSet('bento-panel-open', JSON.stringify(openState))
})
}
}
diff --git a/slides/src/packs.ts b/slides/src/packs.ts
index ac5834ee..4b7c496a 100644
--- a/slides/src/packs.ts
+++ b/slides/src/packs.ts
@@ -25,6 +25,7 @@ import { fetchPinned, verifySigned } from '../../kernel/src/update.ts'
// Extension-explicit like the kernel imports above, so this module also loads
// under plain node — scripts/test-packs.ts exercises the real thing.
import { PACKED } from './i18n/packed.ts'
+import { lsGet } from '../../kernel/src/storage.ts'
/**
* Where the release channel publishes the pack index and the packs.
@@ -33,7 +34,7 @@ import { PACKED } from './i18n/packed.ts'
* without a rebuild. (A URL, not pack data: nothing durable lives here.)
*/
const channel = (): string =>
- localStorage.getItem('bento-packs-url') ?? 'https://bento.page/releases/slides'
+ lsGet('bento-packs-url') ?? 'https://bento.page/releases/slides'
export interface PackListing {
lang: string
diff --git a/slides/src/present.ts b/slides/src/present.ts
index 022b005f..17e60bd5 100644
--- a/slides/src/present.ts
+++ b/slides/src/present.ts
@@ -13,6 +13,7 @@ import { morphKey } from './model'
import { applyElementFrame, gradientLineCoords, renderSlide } from './render'
import { paintSpeaker, setSpeakerWindow, speakerIdleBody, speakerWindow } from './screens'
import { t } from './i18n'
+import { lsGet, lsSet } from '../../kernel/src/storage.ts'
const MORPH_DURATION = 0.65
const MORPH_EASE = 'power2.inOut'
@@ -413,7 +414,7 @@ export function startPresentation(
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)')
const readMotionPref = (): boolean | null => {
try {
- const v = localStorage.getItem('bento-reduce-motion')
+ const v = lsGet('bento-reduce-motion')
return v === 'on' ? true : v === 'off' ? false : null
} catch { return null }
}
@@ -564,7 +565,7 @@ export function startPresentation(
const setReduceMotion = (on: boolean, persist = true) => {
reduceMotion = on
- if (persist) { try { localStorage.setItem('bento-reduce-motion', on ? 'on' : 'off') } catch { /* storage off */ } }
+ if (persist) lsSet('bento-reduce-motion', on ? 'on' : 'off')
overlay.classList.toggle('reduce-motion', on)
if (on) clearLaserTrail()
// Toast only on an explicit toggle (M / speaker button), not the silent
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
index b58fb658..ab7585fa 100644
--- a/slides/src/sync/online.ts
+++ b/slides/src/sync/online.ts
@@ -15,6 +15,7 @@ import type { BentoDoc } from '../model'
import type { Op, SyncStateJSON } from './crdt'
import type { Frame, RefusalCode, SyncSession, Transport } from './session'
import { offlineEnabled } from '../update'
+import { lsGet, lsSet } from '../../../kernel/src/storage.ts'
export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'
const SNAP_EVERY = 200 // ops between encrypted snapshot uploads
@@ -86,11 +87,11 @@ export async function mintInvite(ownerPrivB64: string, role: 'writer' | 'comment
export async function deviceIdentity(docId: string): Promise<{ pub: string; priv: string }> {
const k = `bento-member-${docId}`
try {
- const saved = localStorage.getItem(k)
+ const saved = lsGet(k)
if (saved) return JSON.parse(saved)
} catch { /* storage unavailable → ephemeral identity */ }
const id = await mintKeypair()
- try { localStorage.setItem(k, JSON.stringify(id)) } catch { /* ephemeral */ }
+ lsSet(k, JSON.stringify(id))
return id
}
@@ -142,7 +143,7 @@ export async function mintCollab(): Promise<CollabCreds> {
/** dev override for the relay host (e.g. ws://localhost:8787) */
export function syncHost(): string {
try {
- return localStorage.getItem('bento-sync-url') || DEFAULT_SYNC_HOST
+ return lsGet('bento-sync-url') || DEFAULT_SYNC_HOST
} catch {
return DEFAULT_SYNC_HOST
}
diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.ts
index 2b1be785..aa59ebe4 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -23,6 +23,7 @@ import { uid } from '../model'
import { SyncState, SYNC_V, BLOB_INLINE_MAX, type Op } from './crdt'
import { putBlob, getBlob, dataUriToBytes, bytesToDataUri, encodedSize, MAX_BLOB } from './blobs'
import { mintCollab } from './online'
+import { lsGet, lsJson } from '../../../kernel/src/storage.ts'
export interface PresenceInfo {
name: string
@@ -520,7 +521,7 @@ export class SyncSession {
private presence(): PresenceInfo {
let name = 'Guest'
try {
- name = localStorage.getItem('bento-author') || 'Guest'
+ name = lsGet('bento-author') || 'Guest'
} catch {
/* storage unavailable */
}
@@ -535,7 +536,7 @@ export class SyncSession {
else if (c.v === 2 && c.ownerPriv) { role = 'owner'; pub = c.owner }
else if (c.v === 2 && c.invite) {
role = 'editor'
- try { pub = JSON.parse(localStorage.getItem(`bento-member-${this.store.doc.docId}`) ?? 'null')?.pub } catch { /* absent */ }
+ pub = lsJson<{ pub?: string } | null>(`bento-member-${this.store.doc.docId}`, null)?.pub
} else if (c.writerPriv) { role = 'editor'; pub = c.writerPub }
}
return {