Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
bento/spaces 0.1.0 — the first release (#226)
nyblnet4bf6fa7e2b42
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 16b1d440..2a1264b6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -110,6 +110,33 @@ jobs:- name: Splice conformance gate (spaces)run: node scripts/shell-gate.mjs spaces/dist-single/Bento_Spaces.bento.html+ - name: Spaces i18n packed table is current+ # The per-locale catalogs are the source of truth; packed.ts is+ # generated and is what ships inside every saved file. A core catalog+ # cannot be corrected without a release, so an incomplete one fails the+ # build rather than shipping a half-translated interface.+ run: node scripts/build-spaces-i18n.mjs --check++ - name: Spaces model rig+ # Properties that fail SILENTLY, and that a shipped file cannot be+ # talked out of once it exists:+ # · the load contract — an unreadable document must never be replaced+ # by an empty one;+ # · format additivity, and id repair derived from the BYTES, so two+ # readers of one file agree on every id (links key on them);+ # · untrusted html is parsed INERT — a detached div still loads what+ # it creates, which made the sanitizer its own vector on the OPEN+ # path;+ # · opening a document touches no network, so a mailed space cannot+ # carry a tracking pixel;+ # · an encrypted space is never snapshotted to IndexedDB in the clear;+ # · find and replace quote ONE number — what is counted is what+ # changes.+ # The last four are source assertions: the behaviour needs a DOM, a+ # failing request, IndexedDB and a clock, but every one of those+ # mistakes is made in the source.+ run: node scripts/test-spaces-model.ts+# dash: the data app — same pipeline, same gate.- name: Install (dash)working-directory: dashdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 24144d53..faca69e0 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -1253,6 +1253,182 @@ CI-testable, but the registry drifting from the tree is. It pins `appId`against each app's own `configureApp()` call and the manifest URL against thepath the release publishes to.+## 2026-08-03 — An encrypted space is never written to disk in the clear++**Decision.** bento/spaces skips the autosave recovery snapshot while a space+is encrypted, and setting a password clears both the version timeline and the+recovery snapshot already written.++**The bug.** `main.ts` called `putRecovery(store.doc)` on a 2.5s debounce,+unconditionally. The snapshot is the document as plain JSON, so an encrypted+space wrote its full plaintext into IndexedDB every few seconds — defeating the+password completely, for the one author who has demonstrably asked for secrecy.+`about.ts` already cleared the version timeline when a password was set, which+made the gap easy to miss: half of it was handled, and the half that ran+continuously was not.++**`putRecovery` does not guard this, by design** — it is a kernel primitive and+the encryption state is app-side. That makes it a CALLER contract, and a caller+contract with no gate is a bug waiting for the next app. Slides holds the same+contract in its own autosave layer.++**Measured, on the built shell:** typing into a plaintext space put the marker+text in the `recovery` store within three seconds (correct — it is the only+backstop on iOS, where no browser can write back to a file). Setting a password+removed that row; every later edit wrote nothing; and the saved file was still+a `bento/enc` envelope with no plaintext anywhere in it.++**Guarded** by two source assertions in `scripts/test-spaces-model.ts`, both+negative-controlled. Same reasoning as the inert-parse guard above: the+behaviour needs IndexedDB and a real clock, the mistake is made at the call+site.++## 2026-08-03 — A space does not phone home when it is opened++**Decision.** bento/spaces renders a remote image `src` as a placeholder naming+the host, with a "Load this image" button. Only `asset:` and `data:` load+without asking. Consent is per-url, per-session, in memory, and never enters+the document.++**Measured.** A space carrying `<img src="https://…/pixel.png">`, opened from+`file://`, issued the request — observed via `PerformanceObserver`, one+`resource` entry, before any interaction. That is a tracking pixel: the+recipient's IP address and the moment they opened your document, delivered to+whoever authored the file. In a format whose entire premise is that you can+mail it to someone, it is the wrong default by a wide margin. It also breaks+PLATFORM §1 — no network required to open.++**Why it costs authors nothing.** The editor never writes a remote src. A+picked image is downscaled, interned by content hash, and stored as `asset:`.+Only hand- or agent-authored documents can carry a url, so the only documents+affected are exactly the ones where a reader should be asked.++**The predicate is an allowlist,** not a blocklist of `http:`. A relative path+is a real request on a static host; so are `//host/x`, `blob:`, `filesystem:`+and any scheme this build has not heard of. `isRemote()` lives in `model.ts`+(pure, testable in node) and returns false only for `asset:` and `data:`.++**Consent is VIEWER state, like locale and reduced motion.** Putting it in the+file would let the author decide whether the reader phones home, and would+carry one reader's decision to everyone the file is forwarded to. It is a plain+`Set` on the editor, it dies with the session, and the click does not commit —+so undo, the dirty flag and autosave never see it. All four verified.++**The placeholder names the host.** "Load images" with no indication of who is+being contacted is not consent. It also shows the `alt` text, which is now the+thing a reader actually reads when an image does not load — so the agent guide+tells agents to always write one, and to embed bytes rather than link them.++## 2026-08-03 — Untrusted html is parsed INERT; a detached div is not safe++**Decision.** All untrusted html in bento/spaces goes through+`sanitize.ts inertBody()`, which parses with `DOMParser` into an inert+document. `document.createElement('div').innerHTML = untrusted` is banned, and+`scripts/test-spaces-model.ts` refuses it in the source.++**Measured, in a browser, on the real shell over `file://`:**++| construction | `<img src="404" onerror="…">` |+|---|---|+| `document.createElement('div').innerHTML = …` | **FIRES** |+| `new DOMParser().parseFromString(…, 'text/html')` | inert |+| `<template>.innerHTML = …` | inert |+| `document.implementation.createHTMLDocument()` | inert |++A detached div reads as safe — nothing was inserted into the page — but the+elements it creates belong to the LIVE document, so their resources load. The+handler runs from a node that was never attached to anything.++**Why this was the worst possible instance of it.** The sanitizer has to parse+hostile markup before it can strip it, so the sanitizer was itself the vector,+and the payload ran BEFORE the strip. `sanitizeInline` is called at render time+(`render.ts`), so the trigger was *opening a space someone sent you* — no+click, no edit. Sanitizing at render rather than at load is otherwise the right+call (every path into the DOM is covered by one line); it just meant this bug+sat on the open path.++Four call sites had the shape: `sanitizeInline`, `textOf`, `render.ts`'s+code-block text extraction, and — found by the guard, not by reading —+`about.ts`'s markdown export, so "Export as Markdown" ran what it was+exporting.++**The guard is a source assertion,** like the `.href`-IDL one above it: the+behaviour needs a DOM and a failing network request, and the mistake is made in+the source. It caught the fourth site the moment it was written, which is the+argument for writing it that way.++**Verified after the fix,** on the built shell from `file://`, with the removed+construction kept in the same page as a control: only the control fired. No+`[onerror]`, no smuggled `<img>`, no `svg[onload]`, no `javascript:` href+reached the DOM; the `#p/` link survived, external links kept+`rel="noopener noreferrer"`, `<p>a</p><p>b</p>` still unwrapped to "a b", and+markdown export produced `alpha **bold** *it* \`c\` [link](#p/sd-home)`.++**One consequence to remember.** The sanitizer's host now lives in a different+document, so nodes it inserts must come from `el.ownerDocument`, not the global+`document`. DOM4 adopts implicitly, so the wrong one would work — which is+exactly why it is written explicitly and pinned by the rig.++## 2026-08-03 — Release notes, agent guides and tags are PER APP++**Decision.** `scripts/apps.mjs` gained `changelog` and `agents` per app. A+release reads its own app's changelog (`CHANGELOG.md` for slides,+`spaces/CHANGELOG.md` for spaces) and publishes its own agent guide at+`bento.page/<app>/agents.md`. Tags are prefixed for every app but slides.++**The bug this fixes.** `release.mjs` read `join(root, 'CHANGELOG.md')`+unconditionally, and that file's first line is "All notable changes to+**bento/slides**". The first spaces release would therefore have SIGNED slides'+release notes into the spaces manifest — and every shipped spaces file fetches+that manifest at launch and renders `notes` inline in the About dialog. So the+failure is not a build error; it is a correct-looking release that tells all of+one product's users about a different product's changes.++It is unrecoverable in the ordinary way. The notes are inside the signed+envelope, so fixing them means re-signing — and the updater enforces version+monotonicity, so the same version cannot be re-signed. The fix would be+burning a version number.++**Why it was invisible.** Every gate was app-scoped. The registry rig checked+`dir`, `shell` and `appId` against each app's own source of truth, and each+check passed for each app in isolation. The wrongness only exists in the PAIR:+two apps naming one file. That is now a single assertion — the set of+changelogs has the same size as the set of apps — plus, per app, "your+changelog has a section for the version being released, and that section has+bold lead-ins" (a section of pure prose signs EMPTY notes, which is the same+class of silent failure).++**`--print-notes`.** `node scripts/release.mjs --app <app> --print-notes`+prints exactly what would be signed and exits before anything is built, wiped+or signed. A one-way artifact should be readable before it is committed to;+this makes reading it a one-second step rather than an act of faith. It runs+ahead of the `site/` wipe, which is why `cmpVer` is a function declaration and+not a const arrow — the const is in the TDZ at that point in the file.++**Agent guides.** `docs/agents.md` already advertised+`bento.page/<app>/agents.md` as the convention, but only the site-root+`/agents.md` was ever written. Each app now publishes its own guide at the+advertised URL, and slides copies its own to `/agents.md` for compatibility —+the README and the harness `SKILL.md` point there, and that SKILL.md ships+inside a zip people upload to claude.ai, so the root URL is effectively frozen.+One source, two paths.++**Tags.** Slides has 23 tags in the bare `vX.Y.Z` form and is at 1.0.15;+spaces starts at 0.1.0. An unprefixed spaces tag would sort into the middle of+slides' history and permanently claim a version slides cannot reuse. Slides+keeps bare; everything else is `<app>-vX.Y.Z`.++**Reconciled with #234.** bento/dash hit the same bug independently and landed+a convention-based resolver (`<dir>/CHANGELOG.md`, else the root) while this was+in flight. Both now go through ONE `changelogPath()` in release.mjs — registry+field first, convention second, root last — used by the signing path and by+`--print-notes` alike, so what a release reports and what it reads cannot+drift. The registry states it explicitly for all three apps, and the rig+asserts each app RESOLVES to its own file, which is what keeps the root+fallback unreachable. That matters because the fallback is only harmless while+version numbers do not overlap: the day a second app reaches 1.0.x, an empty+manifest would quietly become a wrong one.+## 2026-08-03 — One bento/spaces file is one SPACE, and the reason is a save primitiveSpaces is a tree of pages in ONE `.bento.html`, with links as same-documentdiff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 0dd2e4ce..8f1400ae 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -31,9 +31,25 @@ verify the manifest signature against the public key embedded in every shell.## Cutting a release0. **Get the CHANGELOG right first — it is not just prose any more.** The- first FIVE bold lead-ins of the version's section become the `notes` in the+ first SIX bold lead-ins of the version's section become the `notes` in theSIGNED manifest, which shipped files show inline in the About dialog while- the reader decides whether to update. So:+ the reader decides whether to update.++ **Each app has its own changelog** (`scripts/apps.mjs` → `changelog`):+ slides reads the root `CHANGELOG.md`, spaces reads `spaces/CHANGELOG.md`.+ Every app read the root one until 2026-08-03, which would have signed+ slides' release notes into a spaces manifest and shown them to every spaces+ user. `scripts/test-release-apps.mjs` now pins the distinctness, and:++ ```sh+ node scripts/release.mjs --app spaces --print-notes+ ```++ prints exactly what would be signed and exits, touching nothing. Run it.+ The notes are the one artifact with no way back — they are inside the signed+ envelope, and re-signing a version is refused by the monotonicity check.++ So:- lead with what the release IS (features), not the last thing merged —entries otherwise sit in merge order and a stray fix ends up introducingthe release;@@ -44,16 +60,25 @@ verify the manifest signature against the public key embedded in every shell.if the bug never shipped, announcing it tells people about breakage theynever had. The commit history is the record for those.-1. Bump `slides/package.json` version (this becomes `APP_VERSION` in the- shell and the manifest version — single source of truth).+1. Bump **that app's** `package.json` version — `slides/package.json` or+ `spaces/package.json` (it becomes `APP_VERSION` in the shell and the+ manifest version — single source of truth). Apps version independently.2. Land it and tag. `main` is branch-protected and requires a pull request, sothe bump CANNOT be committed directly — open a small PR for it, merge, then- tag the merge commit:+ tag the merge commit.++ **Tags are per app.** Slides keeps the bare `vX.Y.Z` form it has used for+ 23 releases; every other app is prefixed:```sh- git tag vX.Y.Z <merge-sha>+ git tag vX.Y.Z <merge-sha> # slides+ git tag spaces-vX.Y.Z <merge-sha> # every other app```+ Slides is at 1.0.x and spaces starts at 0.1.0, so an unprefixed spaces tag+ would sort into the middle of slides' history and claim a version slides can+ never use again.+**Build from a clean checkout of that tag**, not from whatever the mainworking tree happens to be on. Several sessions may have their own branchesand uncommitted work there, and `git checkout <tag> -- .` in the wrong treediff --git a/docs/agents.md b/docs/agents.mdindex 5c26ab9c..953eee08 100644--- a/docs/agents.md+++ b/docs/agents.md@@ -5,9 +5,9 @@ guide matches the bento/slides shell of the same version. A deck's `#bento-doc`JSON is always the source of truth — if it was written by a newer shell it maycarry features beyond this guide; unknown keys are ignored, never fatal.-> **Bento is a suite.** Slides is the first app and the only one shipping-> today. **Spaces** (`bento/spaces`, notes) and **Dash** (`bento/dash`, data-> and sheets) are in development, and a word processor is planned. Each ships+> **Bento is a suite.** Slides is the first app; **Spaces**+> (`bento/spaces`, notes and wiki) ships alongside it. **Dash** (`bento/dash`,+> data and sheets) is in development, and a word processor is planned. Each ships> as its own self-contained distributable — `Bento_Slides.bento.html`,> `Bento_Spaces.bento.html`, and so on — with its own agent guide at> `bento.page/<app>/agents.md`. **This guide covers Slides only.** Before youdiff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdnew file mode 100644index 00000000..910ab96e--- /dev/null+++ b/docs/spaces-agents.md@@ -0,0 +1,182 @@+# bento/spaces — for AI agents++**Guide version `__APP_VERSION__`** · document format `bento/spaces` (v1).++A space (`*.bento.html`) is a self-contained HTML file holding **a tree of+pages**. The document lives in ONE plaintext block near the top:++```html+<script type="application/bento+json" id="bento-doc">+{ "format": "bento/spaces", ... }+</script>+```++Two ways to work with it:++1. **File harness** — edit the JSON inside `#bento-doc` in place. Escape every+ `<` as `<` so the block can never contain a literal `</script>`. Leave+ the rest of the file alone.+2. **In the browser** — `window.bento` (below). Prefer the patch calls over+ `loadDoc`: rewriting the whole document to append a paragraph clobbers+ concurrent edits and flattens undo to one entry.++```bash+curl -fsSL https://bento.page/releases/spaces/Bento_Spaces.bento.html -o "<Name>.bento.html"+```++The downloaded file's `#bento-doc` block is **empty**. Opened in a browser it+mints a starter space; on disk there is nothing to copy from. Write your+document into the empty block.++---++## The shape++```jsonc+{+ "format": "bento/spaces", "version": 1,+ "docId": "…", // minted once, NEVER regenerate it+ "title": "Team handbook",+ "home": "p-intro", // the page a reader lands on+ "theme": { "background": "#FFFFFF", "color": "#1E2A3A", "accent": "#F7A600",+ "fontFamily": "…", "measure": 720 },+ "pages": [ // FLAT, in pre-order+ {+ "id": "p-intro", "title": "Introduction", "icon": "👋",+ "parent": "p-parent", // optional — omit for a root page+ "blocks": [ // FLAT, in pre-order+ { "id": "b1", "type": "p", "html": "Hello <b>world</b>." }+ ]+ }+ ]+}+```++**Both arrays are flat and in pre-order; nesting is a `parent` field.** A child+always follows its parent, which is what lets one forward pass rebuild the+tree. Do not nest arrays inside arrays.++**Every id is unique across the WHOLE document and is never reused.** Links,+backlinks and (later) collaboration key on them. A duplicate is repaired+deterministically at load and reported — but a repaired id is a *new* id, so+anything pointing at the old one is now pointing at the wrong node. Emit+unique ids the first time.++## Block types++| `type` | fields | renders as |+|---|---|---|+| `p` | `html` | `<p>` |+| `h1` `h2` `h3` | `html` | `<h1>`…`<h3>` |+| `bullet` `number` | `html` | `<li>` inside a `<ul>`/`<ol>` — adjacent siblings group automatically |+| `todo` | `html`, `done` | `<li>` with a checkbox |+| `toggle` | `html`, `open` | a fold; blocks whose `parent` is its id are its body |+| `quote` | `html` | `<blockquote>` |+| `code` | `html` (plain text), `lang` | `<pre><code>` |+| `divider` | — | `<hr>` |+| `image` | `src` (see below), `alt`, `caption`, `width` (10–100 **%**), `w`/`h` (intrinsic px) | `<figure>` |+| `pagelink` | `page` | a card linking to another page |++`type` is a **string**, not a closed set: an unknown type survives a round trip+and renders its `html` as a fallback. Properties are **flat on the block** —+there is no `props` object.++## Images: embed them, don't link them++`src` takes three forms, and only two of them display without asking:++| `src` | on open |+|---|---|+| `asset:<key>` — a key in `doc.assets` | displays |+| `data:image/…;base64,…` | displays |+| `https://…`, `//host/…`, or a relative path | **placeholder** until the reader clicks "Load this image" |++A remote url is not fetched when a space is opened. Opening a document must+never tell a third party that it was opened — in a format built to be mailed,+that is a tracking pixel — and PLATFORM §1 requires that no network be needed+to open a file. The reader's consent is per-url, per-session, and never stored+in the document.++So **embed the bytes**. Put a data: URI in `doc.assets` under a key and+reference it as `asset:<key>`:++```jsonc+{+ "assets": { "img1": "data:image/webp;base64,UklGR…" },+ "pages": [{ "id": "p1", "title": "…", "blocks": [+ { "id": "b1", "type": "image", "src": "asset:img1",+ "alt": "Revenue by quarter", "w": 1200, "h": 800 }+ ] }]+}+```++Give `w`/`h` (the intrinsic pixel size) so the page does not reflow while the+image decodes, and always write `alt` — it is what a reader sees if the image+is remote and unloaded.++Keep images to 1600px on the longest edge and use WebP: that is what the+editor's own downscale does, and it is the difference between a space someone+can mail and one they cannot.++## Rich text++`html` is **inline only**: `b i u s em strong code a span mark sub sup br`.+Block structure is `type`, never markup — a `<p>` or `<div>` inside `html` is+always a mistake and is unwrapped at load.++Links are same-document fragments:++```json+{ "id": "b7", "type": "p", "html": "see <a href=\"#p/p-intro\">the intro</a>" }+```++`href` must match `^(https?:|mailto:|#p/)`. Anything else is stripped.++## What makes a space good rather than merely correct++| When the material is… | Reach for | Why |+|---|---|---|+| more than one topic | **separate pages**, not headings in one long page | the sidebar, ⌘K and backlinks all key on pages |+| a topic that belongs *under* another | `parent` on the page | the tree is the navigation |+| a reference to another page | an inline `#p/` link | it produces a backlink on the target automatically, at no cost |+| a list of sub-pages | one `pagelink` block each | a visible card beats a bare link for a hub page |+| steps someone will tick off | `todo` | state lives in the document, so it survives sharing |+| an aside, or detail most readers skip | `toggle` with its body as `parent` children | folds away, and always PRINTS expanded |+| anything you would print | remember toggles print open and archived pages are excluded | |++**The most-missed feature is backlinks.** They are derived — link to a page and+it lists the linker, with no maintenance. A space where pages only link *down*+the tree wastes the one thing this format does that a folder of files cannot.++## `window.bento`++```js+bento.doc // the live document+bento.pages() // [{id, title, parent, archived, blocks}]+bento.getPage(id) // one page, with its blocks+bento.search(q) // [{pageId, title, blockId}]+bento.newPage(title, parent?) // → new page id (one undo step)+bento.insertBlocks(pageId, afterId, [...]) // → new block ids (one undo step)+bento.loadDoc(json) // replace everything (one undo step)+bento.serialize() // the whole .bento.html file+bento.undo() / bento.redo()+bento.readonly // true = a locked or frozen file; writes no-op+```++`insertBlocks` and `newPage` each commit **one undoable step** and mint their+own ids. Use them in preference to `loadDoc` for anything incremental.++## Gotchas++- Escape `<` as `<` when writing the file block.+- Don't invent property names — unknown keys are preserved but ignored, so a+ typo means your styling silently does nothing.+- `docId` is the document's identity. Never regenerate it when editing.+- A `parent` naming something that does not exist is dropped at load: the page+ becomes a root page, the block re-homes. Not fatal, but not what you meant.+- `readonly: true` and a `policy` this build does not know both open **frozen**+ — the file round-trips byte-exact and edits are refused.+- A remote image `src` shows a placeholder until the reader asks for it. Embed+ the bytes as an `asset:` instead — see **Images** above.+- There is no collaboration yet. Two people editing two copies get two files+ and no merge.diff --git a/scripts/apps.mjs b/scripts/apps.mjsindex e6431a89..d8a20ca5 100644--- a/scripts/apps.mjs+++ b/scripts/apps.mjs@@ -24,6 +24,13 @@ export const APPS = {shell: 'Bento_Slides.bento.html',/** the whole bento.page site — landing, gallery, guides — is slides-derived today */ownsSiteContent: true,+ /** where this app's release notes come from. The notes ride in the SIGNED+ * manifest and are what a reader sees when offered an update, so an app+ * reading another app's changelog would tell every one of its users about+ * changes to a different product. */+ changelog: 'CHANGELOG.md',+ /** published at /<dir>/agents.md — the runnable half of "designed for AI" */+ agents: 'docs/agents.md',/** signed language packs exist for this app (docs/i18n-packs.md) */packs: true,},@@ -36,6 +43,8 @@ export const APPS = {// channel does not exist. Deferring packs is fine; deferring the CHANNEL// would not be (working/spaces-design.md §6.5).packs: false,+ changelog: 'spaces/CHANGELOG.md',+ agents: 'docs/spaces-agents.md',},dash: {appId: 'bento-dash',@@ -45,5 +54,6 @@ export const APPS = {// Same reasoning as spaces: no pack catalog yet, and deferring the CATALOG// is fine where deferring the CHANNEL would not be.packs: false,+ changelog: 'dash/CHANGELOG.md',},}diff --git a/scripts/build-spaces-i18n.mjs b/scripts/build-spaces-i18n.mjsnew file mode 100644index 00000000..e3b3cee2--- /dev/null+++ b/scripts/build-spaces-i18n.mjs@@ -0,0 +1,129 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Generates spaces/src/i18n/packed.ts from the per-locale catalogs.+//+// node scripts/build-spaces-i18n.mjs write the packed table+// node scripts/build-spaces-i18n.mjs --check fail if it is out of date (CI)+//+// WHY PACK. English-string-as-key means the source sentence is the key in every+// locale, so N plain catalogs store the same English text N times — and deflate+// cannot dedupe it, because the catalogs span far more than its 32KB window. At+// 116 strings across 8 locales that is tens of KB of duplicated English on a+// shell measured in tens of KB. The packed form stores each key ONCE with an+// array of translations by column, and `0` for "no translation, use English".+//+// The key universe is swept from the SOURCE, not from the catalogs, so a string+// added to the UI and forgotten in the catalogs shows up as missing rather than+// silently shipping English.++import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const srcDir = join(root, 'spaces/src')+const i18nDir = join(srcDir, 'i18n')+const OUT = join(i18nDir, 'packed.ts')++/** Locale columns, in order. English is the key, so it is not a column. */+export const LOCALES = ['ja', 'zh-Hans', 'zh-Hant', 'es', 'fr', 'de', 'it', 'pt']++/**+ * Every `t('…')` in the app source.+ *+ * Deliberately a scan of the SOURCE. build-i18n.mjs in slides carries a warning+ * that a regex once silently missed 54 of 650 entries, so this one anchors on+ * the call, handles both quote styles, and is checked by counting: if the sweep+ * ever returns fewer keys than the catalogs contain, that is reported too.+ */+function sweepKeys() {+ const keys = new Set()+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name)+ if (entry.isDirectory()) { if (entry.name !== 'i18n') walk(full); continue }+ if (!entry.name.endsWith('.ts')) continue+ const src = readFileSync(full, 'utf8')+ const re = /\bt\(\s*(['"])((?:\\.|(?!\1).)*)\1/g+ let m+ while ((m = re.exec(src))) keys.add(m[2].replace(/\\'/g, "'").replace(/\\"/g, '"'))+ }+ }+ walk(srcDir)+ return [...keys].sort()+}++/** Read one locale catalog by evaluating its object literal. */+function readCatalog(code) {+ const file = join(i18nDir, `${code}.ts`)+ if (!existsSync(file)) return {}+ const src = readFileSync(file, 'utf8')+ const start = src.indexOf('{', src.indexOf(`export const `))+ const end = src.lastIndexOf('}')+ if (start < 0 || end < 0) return {}+ // the catalogs are generated, so this is a literal object of string pairs+ return Function(`"use strict"; return (${src.slice(start, end + 1)})`)()+}++const keys = sweepKeys()+const catalogs = Object.fromEntries(LOCALES.map((c) => [c, readCatalog(c)]))++const rows = []+const missing = Object.fromEntries(LOCALES.map((c) => [c, 0]))+for (const key of keys) {+ const row = LOCALES.map((c) => {+ const v = catalogs[c][key]+ if (typeof v === 'string' && v.length) return v+ missing[c]+++ return 0+ })+ rows.push([key, row])+}++const body = `// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GENERATED by scripts/build-spaces-i18n.mjs — do not edit. Run it after+// changing a catalog or adding a t() string; CI fails if this is out of date.+//+// One row per English key: the key is stored ONCE and the translations follow+// by column. \`0\` means "no translation in that locale" and falls back to the+// English key, which is also the source text — so a missing entry degrades to+// a readable string rather than a blank.++export const PACKED_LOCALES = ${JSON.stringify(LOCALES)} as const++export const PACKED: Record<string, ReadonlyArray<string | 0>> = {+${rows.map(([k, r]) => ` ${JSON.stringify(k)}: ${JSON.stringify(r)},`).join('\n')}+}+`++const current = existsSync(OUT) ? readFileSync(OUT, 'utf8') : null+const report = LOCALES.map((c) => {+ const done = keys.length - missing[c]+ const pct = keys.length ? Math.round((done / keys.length) * 1000) / 10 : 100+ return ` ${c.padEnd(8)} ${String(done).padStart(3)}/${keys.length} ${pct}%`+}).join('\n')++if (process.argv.includes('--check')) {+ if (current !== body) {+ console.error('spaces packed.ts is out of date.\nRun: node scripts/build-spaces-i18n.mjs')+ process.exit(1)+ }+ // Core catalogs ship INSIDE every saved file and cannot be corrected without+ // a release, so an incomplete one is a build failure, not a warning.+ const short = LOCALES.filter((c) => missing[c] > 0)+ if (short.length) {+ console.error(`incomplete core catalogs: ${short.map((c) => `${c} (${missing[c]} missing)`).join(', ')}`)+ console.error(report)+ process.exit(1)+ }+ console.log(`spaces i18n up to date (${keys.length} strings × ${LOCALES.length} locales, all complete)`)+} else {+ mkdirSync(i18nDir, { recursive: true })+ writeFileSync(OUT, body)+ console.log(`packed ${keys.length} strings × ${LOCALES.length} locales -> ${OUT}`)+ console.log(report)+}diff --git a/scripts/release.mjs b/scripts/release.mjsindex 34a8a3c1..42236b5f 100644--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -18,6 +18,7 @@// CNAME bento.page// index.html placeholder landing page// <app>/index.html live demo (the shell itself)+// <app>/agents.md that app's AI-agent guide// releases/<app>/Bento_<App>.bento.html the download// releases/<app>/manifest.json signed update manifest// releases/slides/packs/*.pack.json language packs (slides only today)@@ -64,6 +65,20 @@ const published = process.env.BENTO_SITE_DIR? resolve(process.env.BENTO_SITE_DIR): resolve(root, '..', 'bento-site')+// `--print-notes` shows exactly what this release would sign into the manifest,+// then exits. Nothing is built, staged, wiped or signed.+//+// The notes are the one released artifact with no way back: they are inside the+// signed envelope, every shipped file fetches it at launch, and re-signing the+// same version is refused by the monotonicity check. Reading them once, before+// the key is touched, costs a second. (The function declarations below hoist.)+if (args.includes('--print-notes')) {+ const sections = changelogSections()+ console.log(`${app.appId} v${version} — from ${changelogPath()}\n`)+ console.log(releaseNotesString(sections) ?? '(no notes — the changelog has no section for this version)')+ process.exit(0)+}+if (!args.includes('--no-build')) {console.log(`Building ${app.appId} v${version}…`)execFileSync('npm', ['run', 'build:single'], { cwd: join(root, app.dir), stdio: 'inherit' })@@ -114,6 +129,22 @@ cpSync(shellSrc, join(site, `releases/${app.dir}/${app.shell}`))// The live demo IS the shell — opening it boots the editor with the starter doc.cpSync(shellSrc, join(site, `${app.dir}/index.html`))+// The agent guide, at the URL the guides themselves advertise:+// `bento.page/<app>/agents.md`. Stamped with this shell's version so the guide+// declares which feature set it matches (an agent can compare it against a+// document written by a newer shell).+//+// Slides ALSO publishes to the site root — see the ownsSiteContent block below.+// `/agents.md` is referenced by the README and by the harness SKILL.md, which+// people upload to claude.ai as a zip, so it is effectively frozen; this is the+// same compat shape as skills/bento-deck. Both copies come from one source.+if (app.agents && existsSync(join(root, app.agents))) {+ writeFileSync(+ join(site, `${app.dir}/agents.md`),+ readFileSync(join(root, app.agents), 'utf8').replace(/__APP_VERSION__/g, version),+ )+}+// CONFORMANCE GATE — old updaters are frozen code; every release must// satisfy the splice contract they rely on. The gate itself lives in// scripts/shell-gate.mjs (shared with CI, which runs it on every PR build).@@ -137,15 +168,31 @@ const key = opt('key', null)* so the whole changelog section would be a needless payload. Bold lead-ins* only — the headline of each entry — with the full text a link away.*/+/**+ * Where THIS app's release notes come from.+ *+ * The root CHANGELOG.md is slides' — it says so in its own first line — and its+ * versions are 1.0.x, so a second app releasing 0.1.0 matched nothing and+ * shipped a manifest with no notes at all. Worse, once two apps' version+ * numbers overlap, the fallback stops being empty and starts being WRONG: an+ * app would describe another product's changes to its own users, inside a+ * signed envelope that cannot be re-signed for the same version.+ *+ * So: the registry states it, the `<dir>/CHANGELOG.md` convention covers an app+ * that has not, and the root is the last resort. ONE resolver, used by both the+ * signing path and `--print-notes`, so what a release reports and what it reads+ * cannot drift. `scripts/test-release-apps.mjs` asserts every app resolves to+ * its own file, which is what keeps the last resort unreachable.+ */+function changelogPath() {+ if (app.changelog) return app.changelog+ const byConvention = `${app.dir}/CHANGELOG.md`+ return existsSync(join(root, byConvention)) ? byConvention : 'CHANGELOG.md'+}+function changelogSections() {// Every released section, newest first: [{ version, heads }]- //- // Per-app first. The root CHANGELOG.md is slides' — it says so in its own- // first line — and its versions are 1.0.x, so a second app releasing 0.1.0- // matched nothing and shipped a manifest with no notes at all. An app with- // its own CHANGELOG.md uses it; everything else falls back to the root.- const appCl = join(root, `${app.dir}/CHANGELOG.md`)- const cl = readFileSync(existsSync(appCl) ? appCl : join(root, 'CHANGELOG.md'), 'utf8')+ const cl = readFileSync(join(root, changelogPath()), 'utf8')const out = []const re = /^## \[(\d+\.\d+\.\d+)\][^\n]*$/gmconst marks = [...cl.matchAll(re)]@@ -157,7 +204,9 @@ function changelogSections() {return out}-const cmpVer = (a, b) => {+// A declaration, not a const arrow: `--print-notes` runs before this point in+// the file and relies on hoisting to reach it (a const would be in the TDZ).+function cmpVer(a, b) {const pa = a.split('.').map(Number), pb = b.split('.').map(Number)for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i]return 0@@ -285,13 +334,11 @@ if (app.ownsSiteContent) {// (each carries template:true; opening one mints a fresh, independent deck).execFileSync('node', [join(root, 'scripts/build-example-decks.mjs'), join(site, 'gallery')], { stdio: 'inherit' })- // The agent guide — the runnable version of the "designed for AI" claim.- // Stamp the current shell version so the guide declares which feature set it- // matches (agents can compare it to a deck written by a newer shell).- writeFileSync(- join(site, 'agents.md'),- readFileSync(join(root, 'docs/agents.md'), 'utf8').replace(/__APP_VERSION__/g, version),- )+ // The agent guide at the SITE ROOT — the compat URL. The per-app copy at+ // /slides/agents.md is written above, from the same source; this one exists+ // because the README and the harness SKILL.md point at /agents.md, and that+ // SKILL.md ships inside a zip people upload to claude.ai.+ cpSync(join(site, `${app.dir}/agents.md`), join(site, 'agents.md'))// The harness skill (canonical home: the Claude Code plugin at// plugins/bento-slides). Published three ways: the raw SKILL.md (curl// one-liner), a claude.ai-uploadable zip (must contain bento-slides/SKILL.md,diff --git a/scripts/test-release-apps.mjs b/scripts/test-release-apps.mjsindex 2a5b99af..c195618c 100644--- a/scripts/test-release-apps.mjs+++ b/scripts/test-release-apps.mjs@@ -16,6 +16,12 @@// · `dir` wrong → the release cannot find package.json. Loud, harmless.// · `shell` wrong → the build succeeds and staging copies a file that is// not there. Discovered mid-release.+// · `changelog` wrong → also silent, and it ships. The notes ride in the+// SIGNED manifest and are rendered inline by every+// file that finds an update, so an app pointed at+// another app's changelog tells all of its users about+// a product they do not have. (Every app read the root+// CHANGELOG until 2026-08-03.)// · `appId` wrong → the WORST case, and silent. A shipped shell verifies// the manifest's `app` against its own configureApp()// id (kernel/src/update.ts), so a mismatch signs and@@ -71,9 +77,47 @@ for (const [key, app] of Object.entries(APPS)) {// Exactly one app may own the shared bento.page content, or a release either// regenerates it from a shell it did not build, or nobody ever rebuilds it.ok(typeof app.ownsSiteContent === 'boolean', `${key}: declares ownsSiteContent`)++ // ---- release notes -------------------------------------------------------+ // The notes are lifted from the section matching THIS version and signed+ // into the manifest, so both halves have to line up before a release runs.+ // Resolved exactly as release.mjs resolves it: registry, then the+ // <dir>/CHANGELOG.md convention, then the root. The root is slides' file, so+ // reaching it from another app is the failure — these checks are what keep it+ // unreachable.+ const resolved = app.changelog+ ?? (existsSync(join(root, `${app.dir}/CHANGELOG.md`)) ? `${app.dir}/CHANGELOG.md` : 'CHANGELOG.md')+ const clPath = join(root, resolved)+ ok(existsSync(clPath), `${key}: resolves to a changelog that exists (${resolved})`)+ if (existsSync(clPath)) {+ const cl = readFileSync(clPath, 'utf8')+ // A section for the version being released, with at least one bold lead-in+ // — release.mjs harvests exactly those, so a section of prose signs EMPTY+ // notes and the reader gets a bare version number.+ const re = new RegExp(`^## \\[${pkg.version.replace(/\./g, '\\.')}\\][^\n]*$`, 'm')+ const m = re.exec(cl)+ ok(!!m, `${key}: the changelog has a section for the version being released (${pkg.version})`)+ if (m) {+ const next = cl.slice(m.index + m[0].length)+ const body = next.split(/^## \[/m)[0]+ ok(/^- \*\*(.+?)\*\*/ms.test(body.trim()),+ `${key}: that section has bold lead-ins (what release.mjs signs as the notes)`)+ }+ }++ // The agent guide is published at /<dir>/agents.md by that app's release.+ if (app.agents) ok(existsSync(join(root, app.agents)), `${key}: agent guide exists (${app.agents})`)ok(typeof app.packs === 'boolean', `${key}: declares whether it has a pack channel`)}+// The actual 2026-08-03 bug: two apps reading one file. Distinctness is the+// property, and it is one line — the wrongness was never visible in either+// app's own checks, only in the pair.+const cls = Object.entries(APPS).map(([k, a]) => [k, a.changelog+ ?? (existsSync(join(root, `${a.dir}/CHANGELOG.md`)) ? `${a.dir}/CHANGELOG.md` : 'CHANGELOG.md')])+ok(new Set(cls.map(([, c]) => c)).size === cls.length,+ `each app has its OWN changelog (${cls.map(([k, c]) => `${k}→${c}`).join(', ')})`)+const owners = Object.entries(APPS).filter(([, a]) => a.ownsSiteContent).map(([k]) => k)ok(owners.length === 1,`exactly one app owns the site content (got ${owners.length}: ${owners.join(', ') || 'none'})`)diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsnew file mode 100644index 00000000..eef917d0--- /dev/null+++ b/scripts/test-spaces-model.ts@@ -0,0 +1,346 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/spaces model rig.+//+// node scripts/test-spaces-model.ts+//+// WHAT THIS PROVES. Three properties, each of which fails silently and each of+// which is unrecoverable once files exist on disks.+//+// 1. THE LOAD CONTRACT. `parseDoc` must never hand back "here is an empty+// space" for a document it could not read. The scaffold did — it returned+// null for anything invalid and the caller fell back to the starter — so+// opening a slides file, or a document with one hand-edited typo, showed+// an empty space over live data, and the first ⌘S wrote it to disk.+// The ONLY path to the starter is an absent or empty block.+//+// 2. ADDITIVITY (PLATFORM §3). Unknown top-level fields, unknown per-node+// fields and unknown block TYPES all survive a round trip. There is no+// server to migrate anything, so a version that strips what it does not+// understand destroys documents written by a later one.+//+// 3. DETERMINISTIC ID REPAIR. Two readers of one file must agree on every+// id, because links, backlinks and future collaboration key on them. A+// repair derived from Math.random diverges two readers of the same bytes;+// one derived from docId does too, because `template: true` re-mints+// docId on every open.++import {+ parseDoc, buildIndex, docContentKey, homePage, FORMAT, isRemote,+ type SpacesDoc,+} from '../spaces/src/model.ts'+import { countOutsideTags, replaceOutsideTags } from '../spaces/src/findreplace.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const doc = (over: Record<string, unknown> = {}): string => JSON.stringify({+ format: FORMAT, version: 1, docId: 'd1', title: 'T',+ pages: [{ id: 'p1', title: 'One', blocks: [{ id: 'b1', type: 'p', html: 'hi' }] }],+ theme: {},+ ...over,+})++// ---- 1. the load contract --------------------------------------------------+ok(parseDoc('').ok === false && (parseDoc('') as any).err === 'empty',+ 'an empty block is the ONLY thing that yields the starter')+ok(parseDoc(' \n ').ok === false && (parseDoc(' ') as any).err === 'empty',+ 'whitespace counts as empty')++for (const [label, input, err] of [+ ['a slides document', JSON.stringify({ format: 'bento/slides', slides: [] }), 'format'],+ ['a hand-edited typo', '{"format":"bento/spaces", pages:[]}', 'json'],+ ['a JSON array', '[]', 'shape'],+ ['pages missing', JSON.stringify({ format: FORMAT }), 'shape'],+] as const) {+ const r = parseDoc(input)+ ok(r.ok === false && r.err === err, `${label} REFUSES with err="${err}" (never the starter)`)+}+{+ const r = parseDoc(JSON.stringify({ format: 'bento/slides', slides: [] }))+ ok(r.ok === false && 'found' in r && r.found === 'bento/slides',+ 'refusing names the format it actually found, so the message can say so')+}++// ---- 2. additivity ---------------------------------------------------------+{+ const r = parseDoc(doc({+ futureTopLevel: { a: 1 },+ pages: [{+ id: 'p1', title: 'One', futurePageField: 'keep',+ blocks: [+ { id: 'b1', type: 'p', html: 'hi', futureBlockField: 7 },+ { id: 'b2', type: 'kanban', html: 'fallback text', lanes: 3 },+ ],+ }],+ }))+ ok(r.ok, 'a document carrying unknown fields still parses')+ if (r.ok) {+ ok(JSON.stringify((r.doc as any).futureTopLevel) === '{"a":1}', 'an unknown TOP-LEVEL field survives')+ ok((r.doc.pages[0] as any).futurePageField === 'keep', 'an unknown PAGE field survives')+ ok((r.doc.pages[0].blocks[0] as any).futureBlockField === 7, 'an unknown BLOCK field survives')+ const kb = r.doc.pages[0].blocks[1]+ ok(kb.type === 'kanban' && (kb as any).lanes === 3, 'an unknown block TYPE survives with its data')+ ok(kb.html === 'fallback text', 'and keeps html, so an older build can still show something')+ }+}++// ---- frozen: a newer version opens read-only and byte-exact -----------------+{+ const r = parseDoc(doc({ version: 99 }))+ ok(r.ok && r.frozen === 'version', 'a newer format version opens FROZEN rather than being reinterpreted')+ const p = parseDoc(doc({ policy: 'bento-spaces-2' }))+ ok(p.ok && p.frozen === 'policy', 'an unrecognised policy opens FROZEN')+ // frozen means ids are NOT rewritten, even duplicates: we cannot know the+ // rules this file was written under, so we must not touch it+ const dup = parseDoc(doc({+ version: 99,+ pages: [{ id: 'p1', title: 'A', blocks: [{ id: 'x', type: 'p' }, { id: 'x', type: 'p' }] }],+ }))+ ok(dup.ok && dup.doc.pages[0].blocks.every((b) => b.id === 'x'),+ 'frozen documents keep even DUPLICATE ids untouched')+ ok(dup.ok && dup.repaired.length === 0, 'and report no repairs')+}++// ---- 3. deterministic id repair --------------------------------------------+{+ const dupes = doc({+ pages: [+ { id: 'p1', title: 'A', blocks: [{ id: 'b1', type: 'p', html: 'one' }, { id: 'b1', type: 'p', html: 'two' }] },+ { id: 'p1', title: 'B', blocks: [{ id: 'b9', type: 'p', html: 'three' }] },+ ],+ })+ const a = parseDoc(dupes)+ const b = parseDoc(dupes)+ ok(a.ok && b.ok, 'a document with duplicate ids still opens')+ if (a.ok && b.ok) {+ ok(JSON.stringify(a.doc.pages) === JSON.stringify(b.doc.pages),+ 'TWO READERS OF THE SAME BYTES PRODUCE THE SAME IDS')+ const ids = new Set<string>()+ let dup = false+ for (const p of a.doc.pages) { if (ids.has(p.id)) dup = true; ids.add(p.id); for (const bl of p.blocks) { if (ids.has(bl.id)) dup = true; ids.add(bl.id) } }+ ok(!dup, 'every id in the repaired document is unique across the WHOLE document')+ ok(a.doc.pages[0].id === 'p1', 'first occurrence in pre-order keeps the id')+ ok(a.doc.pages[1].id !== 'p1', 'the later duplicate is the one that moves')+ ok(a.repaired.length === 2, `repairs are REPORTED, never silent (got ${a.repaired.length})`)+ }+}+{+ // repair must not depend on docId: `template: true` re-mints it every open,+ // so a docId-derived id would give two readers of one file different ids+ const body = { pages: [{ id: 'p', title: 'A', blocks: [{ id: 'z', type: 'p' }, { id: 'z', type: 'p' }] }] }+ const one = parseDoc(doc({ ...body, docId: 'aaa' }))+ const two = parseDoc(doc({ ...body, docId: 'bbb' }))+ ok(one.ok && two.ok &&+ JSON.stringify(one.doc.pages[0].blocks.map((b) => b.id)) ===+ JSON.stringify(two.doc.pages[0].blocks.map((b) => b.id)),+ 'repair does NOT depend on docId (which template:true re-mints every open)')+}++// ---- dangling references ---------------------------------------------------+{+ const r = parseDoc(doc({+ pages: [{ id: 'p1', title: 'A', parent: 'nope', blocks: [{ id: 'b1', type: 'p', parent: 'gone' }] }],+ }))+ ok(r.ok && r.doc.pages[0].parent === undefined,+ 'a page whose parent does not exist becomes a ROOT page rather than vanishing')+ ok(r.ok && r.doc.pages[0].blocks[0].parent === undefined,+ 'a block whose owner does not exist is re-homed rather than never rendering')+}++// ---- the index -------------------------------------------------------------+{+ const r = parseDoc(doc({+ pages: [+ { id: 'home', title: 'Home', blocks: [{ id: 'h1', type: 'p', html: 'see <a href="#p/sub">Sub</a>' }] },+ { id: 'sub', title: 'Sub', parent: 'home', blocks: [{ id: 's1', type: 'pagelink', page: 'home' }] },+ ],+ }))+ ok(r.ok, 'the linked document parses')+ if (r.ok) {+ const ix = buildIndex(r.doc)+ ok(ix.backlinks.get('sub')?.length === 1, 'an inline #p/ link produces a backlink')+ ok(ix.backlinks.get('home')?.length === 1, 'a pagelink BLOCK produces a backlink too')+ ok(ix.children.get('home')?.[0].id === 'sub', 'the page tree nests by parent')+ ok(ix.children.get('')?.length === 1, 'and only true roots are at the root')+ ok(ix.block.get('s1')?.pageId === 'sub', 'a block resolves to its owning page')+ }+}++// ---- content key -----------------------------------------------------------+{+ const base = parseDoc(doc())+ const same = parseDoc(doc({ modified: '2026-01-01T00:00:00Z' }))+ ok(base.ok && same.ok && docContentKey(base.doc) === docContentKey(same.doc),+ 'docContentKey ignores volatile fields, so autosave does not see a phantom edit')+ const other = parseDoc(doc({ title: 'Different' }))+ ok(base.ok && other.ok && docContentKey(base.doc) !== docContentKey(other.doc),+ 'and it DOES see a real one')+}+{+ const r = parseDoc(doc({ home: 'p1' }))+ ok(r.ok && homePage(r.doc)?.id === 'p1', 'home names the landing page')+ const noHome = parseDoc(doc())+ ok(noHome.ok && homePage(noHome.doc)?.id === 'p1', 'and falls back to the first page')+}++// ---- the href allowlist is matched against the ATTRIBUTE, not the property --+// Measured: `a.href` returns the RESOLVED ABSOLUTE url, so from file:// a+// stored "#p/abc" reads back as "file:///…#p/abc" and fails an allowlist that+// passes on a static host — stripping every internal link in exactly the two+// environments this format exists for. A behavioural test needs a DOM; this+// pins the discipline in the source, where the mistake is made.+{+ const src = await import('node:fs').then((fs) =>+ fs.readFileSync(new URL('../spaces/src/sanitize.ts', import.meta.url), 'utf8'))+ ok(src.includes("getAttribute('href')"),+ 'sanitize.ts tests the href ATTRIBUTE')+ ok(!/\bel\.href\b|\ba\.href\b/.test(src),+ 'sanitize.ts never reads the .href IDL property (it resolves to an absolute URL)')+}++// ---- untrusted html is parsed INERT, never into a live element -------------+// Measured in a browser, 2026-08-03: `document.createElement('div').innerHTML =+// '<img src="404" onerror="…">'` FIRES the handler. The div is detached, but+// its elements belong to the live document, so the resource loads. `DOMParser`,+// `<template>` and `createHTMLDocument` are inert and do not.+//+// That made the SANITIZER its own vector: it must parse hostile markup before+// it can strip it, so the payload ran before the strip — at render time, on+// merely opening a space someone sent you. Two more call sites (textOf, and+// render.ts's code-block text extraction) had the same shape.+//+// Behavioural proof needs a DOM and a network failure; this pins the discipline+// in the source, where the mistake gets made. Any new html-parsing helper must+// go through inertBody().+{+ const fs = await import('node:fs')+ const read = (f: string) => fs.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')++ for (const f of ['sanitize.ts', 'render.ts', 'editor.ts', 'about.ts', 'main.ts']) {+ const src = read(f)+ // an element made with createElement, then fed innerHTML — the live-parse+ // shape. Assignments of ALREADY-SANITIZED html to a render target are fine+ // and read differently (`x.innerHTML = sanitizeInline(…)`), so the check is+ // on the raw-variable form.+ const live = /\.innerHTML\s*=\s*(html|raw|untrusted|b\.html|String\(html\))\b/.exec(src)+ ok(!live, `${f} never parses raw html into a live element (found: ${live?.[0] ?? 'none'})`)+ }++ const san = read('sanitize.ts')+ ok(/export function inertBody/.test(san), 'sanitize.ts exports inertBody()')+ ok(/new DOMParser\(\)\.parseFromString/.test(san), 'inertBody parses into an inert document')+ ok(/el\.ownerDocument\.createTextNode/.test(san),+ 'the unwrap gap node comes from the parsed document, not the live one')+ ok(!/const host = document\.createElement/.test(san),+ 'sanitizeInline does not host untrusted html in a live element')++ const ren = read('render.ts')+ ok(/inertBody\(/.test(ren), 'render.ts extracts code-block text through inertBody')+}++// ---- a document must not phone home when it is merely OPENED ---------------+// Measured: a space carrying <img src="https://…/pixel.png"> requested it on+// open. That is a tracking pixel in a format whose whole point is that you mail+// it — the recipient's IP and the moment they read your document, handed to+// whoever wrote the file — and it breaks PLATFORM §1 (no network required to+// open). Remote images now wait for the reader to ask.+//+// The predicate is an ALLOWLIST of the two local forms. A blocklist of `http:`+// would miss the cases that actually matter.+{+ for (const local of ['asset:sABC123', 'data:image/webp;base64,AAAA']) {+ ok(!isRemote(local), `${local.slice(0, 24)}… is local`)+ }+ for (const remote of [+ 'https://tracker.example/p.png',+ 'http://tracker.example/p.png',+ '//tracker.example/p.png', // protocol-relative+ 'photos/holiday.jpg', // relative — a real request on a host+ '/abs/path.png',+ 'HTTPS://Tracker.Example/p.png',+ 'blob:https://x/y',+ 'filesystem:https://x/y',+ ]) {+ ok(isRemote(remote), `${remote} is remote`)+ }+ ok(!isRemote(''), 'an empty src is not a remote fetch')++ // and the renderer must actually consult it+ const fs = await import('node:fs')+ const ren = fs.readFileSync(new URL('../spaces/src/render.ts', import.meta.url), 'utf8')+ ok(/isRemote\(rawSrc\)\s*&&\s*!opts\.allowRemote/.test(ren),+ 'render.ts gates remote images on the reader\'s consent')+ ok(!/allowRemote/.test(fs.readFileSync(new URL('../spaces/src/model.ts', import.meta.url), 'utf8')),+ 'consent is NOT a document field — it belongs to the reader, not the file')+}++// ---- an encrypted space is never written to disk in the clear ---------------+// The recovery snapshot is the document as plain JSON. `putRecovery` does NOT+// guard on encryption — the CALLER must — so an unguarded call site puts in+// IndexedDB precisely what the password exists to keep off the disk, every few+// seconds, for the one author who has demonstrably asked for secrecy.+//+// Measured before the guard: the marker text appeared in the `recovery` store+// within 3 seconds of typing. After: setting a password clears the snapshot+// already written, and later edits write none.+{+ const fs = await import('node:fs')+ const main = fs.readFileSync(new URL('../spaces/src/main.ts', import.meta.url), 'utf8')+ const about = fs.readFileSync(new URL('../spaces/src/about.ts', import.meta.url), 'utf8')++ // the debounce body must stand down when encryption is on+ const guarded = /if \(isEncryptionActive\(\)\) return[\s\S]{0,200}?putRecovery/.test(main)+ ok(guarded, 'main.ts skips the recovery snapshot while a space is encrypted')++ // and turning encryption ON must remove what was written before it+ ok(/clearVersions\(/.test(about) && /clearRecovery\(/.test(about),+ 'setting a password clears BOTH the version timeline and the recovery snapshot')+}++// ---- find & replace: the number shown IS the number changed ----------------+// Replace-all is destructive and lands in one commit, so the count in the+// readout, the count in the confirmation and the count of things that change+// must be one number. They were three: the readout counted matching BLOCKS+// ("2 found"), the dialog quoted that as "2 occurrences", and the sweep then+// changed 4. Counting from `textOf()` would have been wrong in the other+// direction — a needle split across markup reads as one word but cannot be+// replaced, so it would promise a change that never happens.+//+// Both functions now share one traversal, and this pins them together.+{+ const cases: Array<[string, number]> = [+ ['Widget and widget and WIDGET', 3], // case-insensitive+ ['a <b>widget</b> inside markup', 1], // inside a tag's content+ ['wid<b>get</b> split across tags', 0], // NOT replaceable, so not counted+ ['<b>widget</b><i>widget</i>', 2],+ ['nothing here', 0],+ ['widgetwidget', 2], // adjacent, no overlap-skipping+ ['<a href="https://widget.example">x</a>', 0], // an attribute is not text+ ]+ for (const [html, expect] of cases) {+ const n = countOutsideTags(html, 'widget')+ ok(n === expect, `count ${JSON.stringify(html).slice(0, 40)} → ${n} (expected ${expect})`)++ // the property that matters: whatever was counted is what changes+ const after = replaceOutsideTags(html, 'widget', 'gadget')+ const made = (after.match(/gadget/g) ?? []).length+ ok(made === expect, `…and replacing changes exactly ${expect} (changed ${made})`)+ }++ // an empty needle must never "match everything"+ ok(countOutsideTags('anything', '') === 0, 'an empty needle counts nothing')+ ok(replaceOutsideTags('anything', '', 'X') === 'anything', 'an empty needle replaces nothing')+ // markup must survive the sweep untouched+ ok(replaceOutsideTags('a <b class="x">widget</b>!', 'widget', 'gadget') === 'a <b class="x">gadget</b>!',+ 'tags and their attributes are preserved verbatim')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdnew file mode 100644index 00000000..b5fdbe6b--- /dev/null+++ b/spaces/CHANGELOG.md@@ -0,0 +1,63 @@+# Changelog++All notable changes to **bento/spaces**. The app version is baked into every+shell as `APP_VERSION` (from `spaces/package.json`) and shown in the About+dialog; a shipped file updates itself through the signed release channel.++This file is per-app on purpose. The notes ride inside the **signed** update+manifest and are what someone reads while deciding whether to rewrite their+file — so an app must never describe another app's changes.++The format (`bento/spaces`, version `1`) is additive and stable — every version+below opens files from every earlier version, and unknown fields are preserved.+Versions follow `0.MINOR.PATCH` while pre-1.0.++## [Unreleased]++## [0.1.0] — 2026-08-03++First release.++- **A space is one file: a tree of pages, in HTML you can mail.** Pages nest,+ the sidebar is the tree, and everything — text, images, structure, the editor+ itself — is in the single file you saved. No account, no server, no folder of+ attachments that goes missing when you forward it.++- **Writing that gets out of the way.** Markdown as you type — `# `, `- `,+ `1. `, `> `, `[] ` and `**bold**` each become the thing they describe — a `/`+ menu at the caret for every block type, a grip to drag blocks and pages into+ a new order, and `[[` to link a page by name, which offers to create that+ page if it does not exist yet.++- **Links go both ways.** Link to a page and that page lists who linked to it.+ Nothing to maintain: backlinks are derived, so a space stays navigable+ without anyone curating an index.++- **Find anything, and change it everywhere.** ⌘K jumps to any page or block+ by content; ⌘F finds and replaces across the whole space, not just the page+ you are looking at.++- **Images that do not make the file unmailable.** A phone photo is downscaled+ to fit the column before it is embedded, and the space says so — with the+ original one click away. Identical images are stored once. Measured: a 4.9 MB+ photograph embeds as 33 KB.++- **Reading view.** Hide the editing surface and read — or hand the file to+ someone else, who sees the same thing. Printing and PDF export follow the+ same rules: toggles print open, archived pages are excluded.++- **Nine languages.** English, Deutsch, Español, Français, Italiano,+ Português, 日本語, 中文 (简体 / 繁體). The interface follows the reader, not+ the document, so one file reads in each person's own language.++- **Archive rather than delete.** An archived page leaves the sidebar and the+ search results but stays in the file, restorable, because the file is the+ only copy there is.++- **A space does not phone home when you open it.** If a document references+ an image on the web, it is not fetched until you ask — the placeholder names+ the site first. Opening a file someone mailed you should not tell a third+ party that you read it, and nothing else in a space touches the network.++- **Password protection, autosave and recovery, signed self-update** —+ the platform guarantees, on the same terms as bento/slides.diff --git a/spaces/README.md b/spaces/README.mdindex 44c5edfa..be2d6bb8 100644--- a/spaces/README.md+++ b/spaces/README.md@@ -1,14 +1,14 @@# bento/spaces-A Notion/notes-like Bento app: one HTML file that is the document, the viewer-and the editor. **This is currently a SCAFFOLD** — it is on-platform and it-works end to end, but the app itself is deliberately minimal (a flat list of-text blocks) so that the kernel seam is legible and the real app can be grown-from a known-good starting point.+A notes/wiki app where **one HTML file is a whole space**: a tree of pages, the+reader that displays them, and the editor that writes them. No account, no+server, no sidecar folder — you can mail it, and the person who receives it can+read and edit it with nothing installed.-If you are an agent picking up spaces work: read `AGENTS.md`,-`docs/PLATFORM.md` and `docs/PARALLEL-WORK.md` first. `spaces/` is your-ownership zone; `kernel/` is not (kernel changes are serialized).+Agents: `docs/spaces-agents.md` is the working guide (published at+`bento.page/spaces/agents.md`). Before changing anything here read `AGENTS.md`,+`docs/PLATFORM.md` and `docs/PARALLEL-WORK.md`. `spaces/` is this app's+ownership zone; `kernel/` is not — kernel changes are serialized.## Run it@@ -19,36 +19,100 @@ npm run dev # dev server (port 5196 via .claude/launch.json)npm run build:single # → dist-single/Bento_Spaces.bento.html (the product)```-## What's wired (the reference for any new Bento app)--- **Self-contained single-file build** — the same vite + `postbuild-compress`- pipeline as slides, passing the splice conformance gate- (`node scripts/shell-gate.mjs spaces/dist-single/Bento_Spaces.bento.html`).-- **`configureApp()`** — app id, display name, and the app's own update- manifest path (`releases/spaces/manifest.json`).-- **Self-save** — `saveFile()` (File System Access, download fallback);- ⌘S and the Save button. The serialized file keeps its compressed runtime.-- **Autosave + recovery** — kernel IndexedDB store keyed by `docId`, with a- restore/discard banner when the last session ended unsaved.-- **i18n** — the kernel engine via a local facade; catalogs are empty for now,- which is fine because English strings are the keys.-- **AI round-trip** — `window.bento` exposes `doc`, `serialize()`,- `loadDoc(json)`.-- **Format discipline** — `parseDoc` validates `format === 'bento/spaces'`,- mints a `docId` when absent, preserves unknown fields, and rejects other- apps' documents.--## What is deliberately NOT wired yet--- **Collaboration.** No CRDT/relay. `docs/PLATFORM.md` §10 permits shipping- without collab rather than with a half-secure version. The sync engine is- currently slides-shaped (see `docs/DECISIONS.md`); genericizing it is its- own project.-- **Password encryption UI.** The kernel writes `bento/enc` envelopes and this- app detects them, but there is no unlock prompt yet — an encrypted file- reports rather than pretending.-- **Rich text, nested blocks, embeds, references.** The block model is one- flat `{id, text}` list. Grow it ADDITIVELY: every future version must still- open documents this one wrote.-- **Update UI.** `configureApp` declares the manifest path, but nothing checks- for updates yet, and no spaces release has been cut.+## The format++`bento/spaces` version 1. Additive and permanent: every future version opens+files this one wrote, and unknown fields survive a round trip untouched. There+is no server to migrate a file that someone has had on a disk for three years.++```jsonc+{+ "format": "bento/spaces", "version": 1,+ "docId": "…", // minted once, never regenerated+ "home": "p-intro",+ "pages": [ // FLAT, pre-order; nesting is `parent`+ { "id": "p-intro", "title": "Introduction", "icon": "…",+ "blocks": [ // FLAT, pre-order; nesting is `parent`+ { "id": "b1", "type": "p", "html": "Hello <b>world</b>." }+ ] }+ ]+}+```++Three decisions worth knowing before editing the model:++- **Both arrays are flat and in pre-order.** A child always follows its parent,+ so one forward pass rebuilds the tree. Nested arrays would make every+ operation recursive and every CRDT node ambiguous.+- **Block properties are flat on the block** (`done`, `open`, `src`, `lang`),+ not inside a `props` object. `type` is an open string: an unrecognised type+ round-trips and falls back to rendering its `html`.+- **`html` is inline-only** — `b i u s em strong code a span mark sub sup br`.+ Block structure is `type`, never markup. `src/sanitize.ts` unwraps anything+ else at load, and matches `href` against `getAttribute('href')` rather than+ `.href`, because the resolved property hides `javascript:` behind a base URL.++Ids are unique across the whole document and are never reused — links,+backlinks and future collaboration key on them. A duplicate is repaired+deterministically **from the bytes** (`repairId`), so two readers of one file+always agree on every id. `scripts/test-spaces-model.ts` pins that, plus the+load contract and format additivity.++## The parts++| File | What it owns |+|---|---|+| `src/model.ts` | the format, `buildIndex()` (tree, backlinks), id repair |+| `src/sanitize.ts` | the inline allowlist — the only thing between a file someone mailed you and script execution |+| `src/store.ts` | undo, and the **typing run** |+| `src/render.ts` | model → DOM, shared by the editor, reading view and print |+| `src/editor.ts` | topbar, sidebar, block menu, `[[` picker, ⌘K, ⌘F, archive |+| `src/assets.ts` | content-addressed images and the downscale |+| `src/about.ts` | updates, language, password, exports |+| `src/i18n/` | per-locale catalogs; `packed.ts` is generated and is what ships |++### The typing run++Slides sidesteps commit granularity because canvas text commits on blur. A+notes app may never blur — so a **run** is consecutive input in one block with+no structural op between. It takes one checkpoint at its first input and+mutates in place after that. It closes on idle, on the caret leaving the block,+on any structural change, on save, and on `replaceDoc`.++One run = one undo entry = later, one collaboration text batch. This single+policy sets undo granularity, autosave churn, the dirty flag and the future op+rate, which is why it lives in the store rather than in the editor.++### Links are fragments++`#p/<id>`, and navigation is `history.pushState(null, '', '#p/id')`. Measured:+from a `file://` opaque origin, `pushState` with a **fragment** is legal while+`pushState` with a **path** throws `SecurityError`. That is the whole reason+pages are one document rather than one file each.++## Platform guarantees this app honours++- **Splice contract** — `#bento-doc` stays plaintext with a stable id; the file+ survives DOMParser → splice → `outerHTML`. Gated by+ `node scripts/shell-gate.mjs spaces/dist-single/Bento_Spaces.bento.html`, the+ same check the release runs before signing.+- **No network to open, edit, read or save.** Updates are the only fetch, and+ they are opt-out.+- **Autosave + recovery** in a per-app IndexedDB database (`bento-spaces-…`);+ encrypted spaces are never snapshotted to disk in plaintext.+- **Signed self-update** against `releases/spaces/manifest.json`, with this+ app's own release notes (`spaces/CHANGELOG.md` — never another app's).+- **i18n** with English strings as keys; `scripts/build-spaces-i18n.mjs+ --check` fails the build if the packed table is stale or a core catalog is+ incomplete, because a catalog ships inside every saved file and cannot be+ corrected without a release.++## Not built yet++- **Collaboration.** No CRDT wiring. The sync engine is slides-shaped+ (composite `slideId ␟ elementId` node keys); spaces needs `pageId ␟ blockId`+ and a token RGA over `html`, which is the same shape — but genericizing it is+ its own project, and PLATFORM §10 permits shipping without collab rather than+ with a half-secure version.+- **Tables, embeds, and databases.** Deliberate: the format is permanent, so a+ block type ships when its model is right, not when its UI is ready.diff --git a/spaces/package.json b/spaces/package.jsonindex 5f693a99..b5d5cd60 100644--- a/spaces/package.json+++ b/spaces/package.json@@ -1,7 +1,7 @@{"name": "bento-spaces","private": true,- "version": "0.0.1",+ "version": "0.1.0","type": "module","license": "MIT","scripts": {diff --git a/spaces/src/about.ts b/spaces/src/about.tsnew file mode 100644index 00000000..597268c3--- /dev/null+++ b/spaces/src/about.ts@@ -0,0 +1,255 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The About surface: what this file is, updating it, its language, its+// password, and the ways out of it.+//+// PLATFORM §10 requires a signed self-update path, an encryption story and an+// AI round-trip. All three live behind one button, because a self-contained+// document has nowhere else to put them.++import { checkForUpdates, applyUpdate, APP_VERSION, type ReleaseInfo } from '../../kernel/src/update.ts'+import {+ setEncryptionPassword, isEncryptionActive, saveFile,+ canWriteInPlace, openedFileName,+} from '../../kernel/src/save.ts'+import { clearVersions, clearRecovery } from '../../kernel/src/autosave.ts'+import { t, localeChoices, locale, setLocale } from './i18n'+import { inertBody } from './sanitize'+import type { Store } from './store'++export interface AboutHooks {+ store: Store+ onRepaint: () => void+}++export function openAbout({ store, onRepaint }: AboutHooks): void {+ const back = document.createElement('div')+ back.className = 'sp-overlay'+ const card = document.createElement('div')+ card.className = 'sp-card sp-about'+ card.setAttribute('role', 'dialog')+ card.setAttribute('aria-label', t('About this space'))+ const close = () => back.remove()++ const h = (text: string) => {+ const n = document.createElement('h2')+ n.className = 'sp-card-h'+ n.textContent = text+ return n+ }+ const row = (label: string, node: HTMLElement) => {+ const r = document.createElement('div')+ r.className = 'sp-row'+ const s = document.createElement('span')+ s.textContent = label+ r.append(s, node)+ return r+ }+ const button = (label: string, fn: () => void, primary = false) => {+ const b = document.createElement('button')+ b.className = 'sp-btn' + (primary ? ' sp-primary' : '')+ b.textContent = label+ b.addEventListener('click', fn)+ return b+ }++ // ---- what this is ------------------------------------------------------+ card.append(h(t('This file')))+ const blurb = document.createElement('p')+ blurb.className = 'sp-about-blurb'+ const pages = store.doc.pages.length+ const blocks = store.doc.pages.reduce((n, p) => n + p.blocks.length, 0)+ blurb.textContent = t(+ 'bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.',+ { version: APP_VERSION, pages, blocks },+ )+ card.append(blurb)++ const fileName = openedFileName()+ if (fileName) card.append(row(t('File'), text(fileName)))+ if (!canWriteInPlace()) {+ const note = document.createElement('p')+ note.className = 'sp-note'+ // stated up front rather than discovered on the first save+ note.textContent = t('This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.')+ card.append(note)+ }++ // ---- updates -----------------------------------------------------------+ card.append(h(t('Updates')))+ const upStatus = document.createElement('p')+ upStatus.className = 'sp-note'+ upStatus.textContent = t('Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.')+ card.append(upStatus)++ const checkBtn = button(t('Check for updates'), async () => {+ upStatus.textContent = t('Checking…')+ let res: Awaited<ReturnType<typeof checkForUpdates>>+ try { res = await checkForUpdates() } catch { upStatus.textContent = t('Could not reach the update channel.'); return }+ if (res.status === 'current') { upStatus.textContent = t('You have the newest version ({v}).', { v: APP_VERSION }); return }+ if (res.status !== 'update') { upStatus.textContent = t('Could not verify an update, so nothing was changed.'); return }+ const rel: ReleaseInfo = res.release+ upStatus.textContent = t('Version {v} is available.', { v: rel.version })+ const apply = button(t('Update this file'), async () => {+ // the update writes a NEW file and leaves this one untouched, so a bad+ // update is undone by deleting the download+ await applyUpdate(rel, store.doc)+ upStatus.textContent = t('Downloaded. Open the new file — this one is unchanged.')+ }, true)+ card.insertBefore(apply, upStatus.nextSibling)+ })+ card.append(checkBtn)++ // ---- language ----------------------------------------------------------+ card.append(h(t('Language')))+ const sel = document.createElement('select')+ sel.className = 'sp-select'+ for (const c of localeChoices()) {+ const o = document.createElement('option')+ o.value = c.code+ o.textContent = c.label+ if (c.code === locale()) o.selected = true+ sel.append(o)+ }+ sel.addEventListener('change', () => {+ setLocale(sel.value)+ close()+ onRepaint()+ })+ card.append(row(t('Interface language'), sel))+ const langNote = document.createElement('p')+ langNote.className = 'sp-note'+ // the same rule as slides: language follows the READER, never the document+ langNote.textContent = t('Language follows whoever opens the file. It is never written into the document.')+ card.append(langNote)++ // ---- password ----------------------------------------------------------+ card.append(h(t('Password')))+ const pwNote = document.createElement('p')+ pwNote.className = 'sp-note'+ pwNote.textContent = isEncryptionActive()+ ? t('This space is encrypted. Saves stay encrypted.')+ : t('A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.')+ card.append(pwNote)++ card.append(button(isEncryptionActive() ? t('Remove password…') : t('Set a password…'), async () => {+ if (isEncryptionActive()) {+ if (!confirm(t('Remove the password? The next save writes the document in the clear.'))) return+ setEncryptionPassword(null)+ pwNote.textContent = t('Password removed. Save to write the space unencrypted.')+ return+ }+ const pw = prompt(t('Choose a password. There is no way to recover it.'))+ if (!pw) return+ setEncryptionPassword(pw)+ // Plaintext snapshots written BEFORE encryption was turned on would defeat+ // the encryption the author just enabled. Both stores: the version timeline+ // and the single recovery snapshot. From here on main.ts writes neither.+ await clearVersions(store.doc.docId)+ await clearRecovery(store.doc.docId)+ pwNote.textContent = t('Password set. Save to write the space encrypted.')+ }))++ // ---- ways out ----------------------------------------------------------+ card.append(h(t('Take it elsewhere')))+ const exports = document.createElement('div')+ exports.className = 'sp-actions'+ exports.append(+ button(t('Copy document JSON'), () => {+ void navigator.clipboard?.writeText(JSON.stringify(store.doc, null, 2))+ }),+ button(t('Export as Markdown'), () => downloadMarkdown(store)),+ button(t('Save a copy…'), () => { void saveFile(store.doc, true) }),+ )+ card.append(exports)+ const outNote = document.createElement('p')+ outNote.className = 'sp-note'+ outNote.textContent = t('A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.')+ card.append(outNote)++ card.append(button(t('Close'), close, true))++ back.append(card)+ back.addEventListener('mousedown', (e) => { if (e.target === back) close() })+ back.addEventListener('keydown', (e) => { if (e.key === 'Escape') close() })+ document.body.append(back)+ card.querySelector('button')?.focus()++ function text(s: string): HTMLElement {+ const n = document.createElement('span')+ n.className = 'sp-mono'+ n.textContent = s+ return n+ }+}++/**+ * Every page as one Markdown file.+ *+ * The renderer already emits semantic tags, so the mapping is direct — which+ * is the payoff for having refused divs-with-classes in the first place.+ */+export function toMarkdown(store: Store): string {+ const out: string[] = []+ const walk = (parent: string, depth: number) => {+ for (const page of store.index.children.get(parent) ?? []) {+ out.push(`${'#'.repeat(Math.min(depth + 1, 6))} ${page.title}`, '')+ for (const b of page.blocks) {+ const indent = b.parent ? ' ' : ''+ const text = htmlToMd(b.html ?? '')+ switch (b.type) {+ case 'h1': out.push(`# ${text}`); break+ case 'h2': out.push(`## ${text}`); break+ case 'h3': out.push(`### ${text}`); break+ case 'bullet': out.push(`${indent}- ${text}`); break+ case 'number': out.push(`${indent}1. ${text}`); break+ case 'todo': out.push(`${indent}- [${b.done ? 'x' : ' '}] ${text}`); break+ case 'quote': out.push(`> ${text}`); break+ case 'code': out.push('```' + String(b.lang ?? ''), text, '```'); break+ case 'divider': out.push('---'); break+ case 'toggle': out.push(`${indent}- ${text}`); break+ case 'image': out.push(`})`); break+ case 'pagelink': out.push(`→ [[${store.index.page.get(String(b.page))?.title ?? '?'}]]`); break+ default: out.push(text)+ }+ out.push('')+ }+ walk(page.id, depth + 1)+ }+ }+ walk('', 0)+ return out.join('\n').replace(/\n{3,}/g, '\n\n')+}++/** Inline html → inline markdown. Links become `[text](#p/id)` so a reader can+ * still see which page was meant even outside the space. */+function htmlToMd(html: string): string {+ // INERT parse — exporting must not run what it is exporting. A detached div+ // still loads its own resources, so `<img src="404" onerror>` in a block+ // would fire on "Download as Markdown". See sanitize.ts inertBody().+ const d = inertBody(html)+ const walk = (n: Node): string => {+ if (n.nodeType === Node.TEXT_NODE) return n.textContent ?? ''+ if (!(n instanceof HTMLElement)) return ''+ const inner = [...n.childNodes].map(walk).join('')+ switch (n.tagName) {+ case 'B': case 'STRONG': return `**${inner}**`+ case 'I': case 'EM': return `*${inner}*`+ case 'CODE': return `\`${inner}\``+ case 'S': return `~~${inner}~~`+ case 'BR': return '\n'+ case 'A': return `[${inner}](${n.getAttribute('href') ?? ''})`+ default: return inner+ }+ }+ return [...d.childNodes].map(walk).join('').trim()+}++export function downloadMarkdown(store: Store): void {+ const blob = new Blob([toMarkdown(store)], { type: 'text/markdown' })+ const a = document.createElement('a')+ a.href = URL.createObjectURL(blob)+ a.download = `${(store.doc.title || 'space').replace(/[^\w.-]+/g, '-')}.md`+ a.click()+ URL.revokeObjectURL(a.href)+}diff --git a/spaces/src/assets.ts b/spaces/src/assets.tsnew file mode 100644index 00000000..68f40f4e--- /dev/null+++ b/spaces/src/assets.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Images: content-addressed storage, and downscaling that says so.+//+// Images are the only thing that makes a space large — prose is essentially+// free — so this is where the file-size story is won or lost. Two decisions do+// the work: identical bytes are stored once, and a photo off a phone is+// downscaled before it travels, visibly and reversibly.++import type { SpacesDoc } from './model'++/** Longest edge kept when downscaling. Above this, detail is invisible in a+ * text column and costs megabytes. */+export const MAX_EDGE = 1600+/** Above this, ask before embedding rather than silently making a 30MB file. */+export const IMAGE_EMBED_BUDGET = 4 * 1024 * 1024+/** Where a space stops being comfortable to mail. Warn, never block. */+export const SPACE_WEIGHT_WARN = 25 * 1024 * 1024++/**+ * A content-addressed key.+ *+ * `s` = sha256 via crypto.subtle. `f` = a synchronous FNV-1a fallback, which+ * exists ONLY so a missing crypto.subtle degrades to "the image still inserts"+ * rather than throwing — not as support for insecure origins, where signed+ * update and bento/enc are dead too.+ *+ * The alg tag is IN the key so two builds never mint one key from two different+ * hashes. FNV-1a has little real entropy, and a collision in content-addressed+ * storage does not error — it DEDUPES, silently replacing image B with image A+ * in a file the author then mails. So interning always BYTE-COMPARES on a key+ * hit and mints a `~n` variant on mismatch, for both algorithms.+ */+async function contentKey(bytes: string): Promise<string> {+ const subtle = globalThis.crypto?.subtle+ if (subtle) {+ const buf = new TextEncoder().encode(bytes)+ const digest = await subtle.digest('SHA-256', buf)+ const b64 = btoa(String.fromCharCode(...new Uint8Array(digest)))+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+ return `s${b64.slice(0, 22)}`+ }+ let h = 0x811c9dc5+ for (let i = 0; i < bytes.length; i++) {+ h ^= bytes.charCodeAt(i)+ h = Math.imul(h, 0x01000193) >>> 0+ }+ return `f${h.toString(36)}`+}++/**+ * Put a data: URI in the asset table and return its `asset:` reference.+ *+ * ASYNC ON PURPOSE, and this is the important part: `crypto.subtle.digest`+ * cannot be awaited inside a synchronous commit callback. So the digest and+ * the byte-compare happen FIRST, and the caller then makes ONE synchronous+ * commit that writes the bytes and the reference together — which is what+ * makes an image insert a single undo step rather than two.+ */+export async function internAsset(doc: SpacesDoc, dataUri: string): Promise<string> {+ if (!dataUri.startsWith('data:')) return dataUri+ const assets = (doc.assets ??= {})+ const base = await contentKey(dataUri)+ let key = base+ for (let n = 1; ; n++) {+ const held = assets[key]+ if (held === undefined) break // free+ if (held === dataUri) return `asset:${key}` // genuinely the same image+ key = `${base}~${n}` // a collision, not a duplicate+ }+ assets[key] = dataUri+ return `asset:${key}`+}++/** Assets no block references any more. */+export function orphanAssets(doc: SpacesDoc): string[] {+ const used = new Set<string>()+ for (const p of doc.pages) {+ for (const b of p.blocks) {+ for (const v of [b.src, (b as Record<string, unknown>).poster]) {+ if (typeof v === 'string' && v.startsWith('asset:')) used.add(v.slice(6))+ }+ }+ }+ for (const f of doc.fonts ?? []) used.add(f.asset)+ return Object.keys(doc.assets ?? {}).filter((k) => !used.has(k))+}++/** Roughly what this document weighs, for the readout. */+export function docWeight(doc: SpacesDoc): number {+ let n = 0+ for (const v of Object.values(doc.assets ?? {})) n += v.length+ for (const p of doc.pages) for (const b of p.blocks) n += (b.html ?? '').length + 80+ return n+}++export interface PreparedImage {+ /** data: URI ready to intern */+ dataUri: string+ /** intrinsic size AFTER any downscale — holds the aspect box while decoding */+ w: number+ h: number+ /** false when the bytes were re-encoded, so the UI can say so and offer the original */+ original: boolean+ /** bytes before, for the badge */+ wasBytes: number+}++/**+ * Read a picked file and, if it is large, re-encode it smaller.+ *+ * A phone photo is 3–8 MB and 4000px wide; in a 720px text column that detail+ * is invisible and the megabytes travel with the file forever. Downscaling is+ * the difference between a space you can mail and one you cannot.+ *+ * It is REVERSIBLE and it says so: the block records `original: false`, the+ * editor badges it, and "Use the original" re-inserts the untouched bytes. A+ * silent quality change to someone's photograph would not be acceptable.+ */+export async function prepareImage(file: File | Blob): Promise<PreparedImage> {+ const raw = await blobToDataUri(file)+ const wasBytes = raw.length++ let bmp: ImageBitmap | null = null+ try { bmp = await createImageBitmap(file) } catch { /* not a decodable image */ }+ if (!bmp) return { dataUri: raw, w: 0, h: 0, original: true, wasBytes }++ const scale = Math.min(1, MAX_EDGE / Math.max(bmp.width, bmp.height))+ // small enough already, or an image whose bytes are already tiny: keep them.+ // Re-encoding a 40KB PNG as WebP can make it BIGGER and always loses fidelity.+ if (scale === 1 && raw.length < 600 * 1024) {+ const out = { dataUri: raw, w: bmp.width, h: bmp.height, original: true, wasBytes }+ bmp.close()+ return out+ }++ const w = Math.round(bmp.width * scale)+ const h = Math.round(bmp.height * scale)+ const canvas = document.createElement('canvas')+ canvas.width = w+ canvas.height = h+ const ctx = canvas.getContext('2d')+ if (!ctx) { bmp.close(); return { dataUri: raw, w: bmp.width, h: bmp.height, original: true, wasBytes } }+ ctx.drawImage(bmp, 0, 0, w, h)+ bmp.close()++ const encoded = await new Promise<Blob | null>((res) => canvas.toBlob(res, 'image/webp', 0.82))+ if (!encoded) return { dataUri: raw, w, h, original: true, wasBytes }+ const smaller = await blobToDataUri(encoded)+ // never let "optimising" make it bigger+ if (smaller.length >= raw.length) return { dataUri: raw, w, h, original: true, wasBytes }+ return { dataUri: smaller, w, h, original: false, wasBytes }+}++export function blobToDataUri(blob: Blob): Promise<string> {+ return new Promise((res, rej) => {+ const r = new FileReader()+ r.onload = () => res(String(r.result))+ r.onerror = () => rej(r.error)+ r.readAsDataURL(blob)+ })+}++export const humanBytes = (n: number): string =>+ n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB`+ : n >= 1024 ? `${Math.round(n / 1024)} KB`+ : `${n} B`diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsnew file mode 100644index 00000000..91c3398b--- /dev/null+++ b/spaces/src/editor.ts@@ -0,0 +1,1724 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The bento/spaces editor.+//+// The keyboard IS the interface here, so the keymap is specified rather than+// discovered, and every block is its own contentEditable host — never one big+// editable container. That is what keeps Selection block-scoped, so splitting+// and merging blocks can never re-mint an id, and ids are what links,+// backlinks and (later) collaboration key on.++import { type Block, newBlock, newPage } from './model'+import { Store } from './store'+import { renderPage } from './render'+import { canonicalize, sanitizeInline, textOf } from './sanitize'+import { countOutsideTags, replaceOutsideTags } from './findreplace'+import { t } from './i18n'+import { openAbout } from './about'+import { ICONS, type IconName } from './icons'+import { internAsset, prepareImage, humanBytes, IMAGE_EMBED_BUDGET, blobToDataUri } from './assets'++const CTRL = navigator.platform.toLowerCase().includes('mac') ? 'metaKey' : 'ctrlKey'++/** Markdown prefixes that convert a block as you type them. */+const AUTOFORMAT: Array<[RegExp, string, (b: Block) => void]> = [+ [/^# $/, 'h1', () => {}],+ [/^## $/, 'h2', () => {}],+ [/^### $/, 'h3', () => {}],+ [/^- $/, 'bullet', () => {}],+ [/^\* $/, 'bullet', () => {}],+ [/^1\. $/, 'number', () => {}],+ [/^> $/, 'quote', () => {}],+ [/^\[\] $/, 'todo', (b) => { b.done = false }],+ [/^\[ \] $/, 'todo', (b) => { b.done = false }],+ [/^```$/, 'code', () => {}],+ [/^--- $/, 'divider', () => {}],+]++const SLASH_ITEMS: Array<{ type: string; label: string; hint: string; icon: IconName }> = [+ { type: 'p', label: 'Text', hint: 'Plain paragraph', icon: 'text' },+ { type: 'h1', label: 'Heading 1', hint: '#', icon: 'h1' },+ { type: 'h2', label: 'Heading 2', hint: '##', icon: 'h2' },+ { type: 'h3', label: 'Heading 3', hint: '###', icon: 'h3' },+ { type: 'bullet', label: 'Bulleted list', hint: '-', icon: 'bullet' },+ { type: 'number', label: 'Numbered list', hint: '1.', icon: 'number' },+ { type: 'todo', label: 'To-do', hint: '[]', icon: 'todo' },+ { type: 'toggle', label: 'Toggle', hint: 'Collapsible section', icon: 'toggle' },+ { type: 'quote', label: 'Quote', hint: '>', icon: 'quote' },+ { type: 'code', label: 'Code', hint: '```', icon: 'code' },+ { type: 'divider', label: 'Divider', hint: '---', icon: 'divider' },+ { type: 'pagelink', label: 'Link to page', hint: 'A card that opens a page', icon: 'link' },+ { type: 'image', label: 'Image', hint: 'Embedded in the file', icon: 'image' },+]++export class Editor {+ readonly store: Store+ private root: HTMLElement+ private main!: HTMLElement+ private sidebar!: HTMLElement+ private statusEl!: HTMLElement+ private overlay: HTMLElement | null = null+ /** set while the editor is writing the DOM, so input handlers stand down */+ private painting = false+ /** reading view: the document without the machinery for changing it */+ private reading = false+ /**+ * Remote image urls this READER has agreed to load, this session only.+ *+ * Never persisted and never written to the document: consent belongs to the+ * person opening the file, and saving it would carry one reader's decision to+ * everyone the file is forwarded to. Re-opening asks again, which is the+ * correct default for something that leaks an IP address.+ */+ private allowedRemote = new Set<string>()+ private undoB: HTMLButtonElement | null = null+ private readB: HTMLButtonElement | null = null+ private redoB: HTMLButtonElement | null = null+ onSave: (() => void) | null = null+ onSaveAs: ((suffix: string) => void) | null = null+ onPrint: (() => void) | null = null++ constructor(root: HTMLElement, store: Store) {+ this.root = root+ this.store = store+ this.build()+ this.store.on('tree', () => this.paintTree())+ this.store.on('page', () => { this.paintPage(); this.paintTree() })+ this.store.on('doc', () => { this.status(t('Edited')); this.syncHistoryButtons() })+ window.addEventListener('popstate', () => this.fromHash())+ this.fromHash()+ }++ // ---- chrome -------------------------------------------------------------+ private build(): void {+ this.root.innerHTML = ''+ this.root.className = 'sp-app'++ const bar = el('header', 'sp-bar')+ const mark = el('span', 'sp-mark')+ mark.innerHTML = 'bento<span>/</span>spaces'++ // Pages panel toggle — on every width, like slides' Slides/Format toggles.+ // A sidebar you cannot put away is a sidebar you resent on a laptop.+ const pagesB = iconBtn('panelLeft', t('Pages — show or hide the page list'), () => this.toggleSidebar())+ pagesB.classList.add('sp-panel-toggle')++ const title = document.createElement('input')+ title.className = 'sp-doctitle'+ title.value = this.store.doc.title+ title.setAttribute('aria-label', t('Space name'))+ title.addEventListener('input', () => {+ this.store.runEdit('__title', () => { this.store.doc.title = title.value })+ document.title = `${title.value} — bento/spaces`+ })+ this.statusEl = el('span', 'sp-status')++ // insert — the block menu, reachable without knowing "/" exists+ const insert = this.dropdown('plus', t('Insert'), t('Insert a block — text, headings, lists, code, images'), (menu, close) => {+ for (const item of SLASH_ITEMS) {+ menu.append(this.menuItem(item.icon, t(item.label), t(item.hint), () => {+ close()+ const page = this.store.page+ if (!page) return+ const fresh = newBlock(item.type === 'pagelink' ? 'p' : item.type)+ this.store.commit(() => { page.blocks.push(fresh) })+ this.paintPage()+ if (item.type === 'pagelink') this.insertPageCard(fresh.id)+ else if (item.type === 'image') void this.pickImage(fresh.id)+ else this.focusBlock(fresh.id)+ }))+ }+ })++ const newPageB = iconBtn('page', t('New page (⌘⌥N)'), () => this.newPage())++ this.undoB = iconBtn('undo', t('Undo (⌘Z)'), () => { this.store.undo(); this.repaint() })+ this.redoB = iconBtn('redo', t('Redo (⇧⌘Z)'), () => { this.store.redo(); this.repaint() })++ const search = iconBtn('search', t('Search all pages (⌘K)'), () => this.openSearch())+ const printB = iconBtn('print', t('Print or save as PDF (⌘P)'), () => this.openPrint())+ this.readB = iconBtn('eye', t('Reading view — the pages without the editing tools'), () => this.toggleReading())+ const about = iconBtn('info', t('About this space'), () =>+ openAbout({ store: this.store, onRepaint: () => this.build() }))++ // save is a split control, as in slides: the common action, and the+ // less-common ways of writing this document somewhere else+ const saveB = iconBtn('save', t('Save (⌘S)'), () => this.onSave?.())+ saveB.classList.add('sp-primary')+ saveB.append(document.createTextNode(t('Save')))+ const saveMore = this.dropdown('chevronDown', '', t('Other ways to save'), (menu, close) => {+ menu.append(this.menuItem('copy', t('Save a copy…'), t('A second file — the original is left alone'), () => {+ close(); void this.saveAs('copy')+ }))+ menu.append(this.menuItem('markdown', t('Export as Markdown…'), t('Every page, as one .md file'), () => {+ close(); this.exportMarkdown()+ }))+ menu.append(this.menuItem('print', t('Print / PDF…'), t('The whole space, or just this page'), () => {+ close(); this.openPrint()+ }))+ menu.append(this.menuItem('lock', t('Password…'), t('Encrypt the document inside this file'), () => {+ close(); openAbout({ store: this.store, onRepaint: () => this.build() })+ }))+ })+ saveMore.classList.add('sp-caret')++ bar.append(pagesB, mark, title, this.statusEl, insert, newPageB,+ this.undoB, this.redoB, search, this.readB, printB, about, saveB, saveMore)++ this.sidebar = el('nav', 'sp-side')+ this.sidebar.setAttribute('aria-label', t('Pages'))+ this.main = el('main', 'sp-main')++ const body = el('div', 'sp-body')+ body.append(this.sidebar, this.main)+ this.root.append(bar, body)++ this.paintTree()+ this.paintPage()+ this.syncHistoryButtons()+ document.addEventListener('keydown', (e) => this.onKey(e), true)+ }++ /**+ * Reading view.+ *+ * Not a separate renderer — the SAME renderer with `editable` off, so what a+ * reader sees is what an editor sees minus the machinery. A second read-only+ * renderer would drift, and the drift would only show up in the view nobody+ * develops in.+ *+ * It is a VIEW, never a document state: nothing about it is written to the+ * file, so a space does not arrive locked because its author was reading when+ * they saved.+ */+ private toggleReading(force?: boolean): void {+ this.reading = force ?? !this.reading+ this.root.classList.toggle('sp-reading', this.reading)+ this.readB?.classList.toggle('sp-on', this.reading)+ this.readB?.setAttribute('aria-pressed', String(this.reading))+ document.querySelector('.sp-findbar')?.remove()+ this.paintPage()+ this.status(this.reading ? t('Reading view — press Esc or the eye to edit') : t('Editing'))+ }++ /** Undo/redo must LOOK unavailable when they are, or they read as broken. */+ private syncHistoryButtons(): void {+ if (this.undoB) this.undoB.disabled = !this.store.canUndo+ if (this.redoB) this.redoB.disabled = !this.store.canRedo+ }++ /** A topbar dropdown: button + menu, closed by choosing, Esc, or clicking away. */+ private dropdown(+ icon: IconName, label: string, tip: string,+ fill: (menu: HTMLElement, close: () => void) => void,+ ): HTMLElement {+ const wrap = el('div', 'sp-dd')+ const b = document.createElement('button')+ b.className = 'sp-btn'+ b.type = 'button'+ b.innerHTML = ICONS[icon]+ if (label) b.append(document.createTextNode(label))+ b.title = tip+ b.setAttribute('aria-label', tip)+ b.setAttribute('aria-haspopup', 'menu')+ const menu = el('div', 'sp-ddmenu')+ menu.setAttribute('role', 'menu')+ const close = () => { wrap.classList.remove('sp-open'); b.setAttribute('aria-expanded', 'false') }+ b.addEventListener('click', (e) => {+ e.stopPropagation()+ const open = !wrap.classList.contains('sp-open')+ for (const other of document.querySelectorAll('.sp-dd.sp-open')) other.classList.remove('sp-open')+ wrap.classList.toggle('sp-open', open)+ b.setAttribute('aria-expanded', String(open))+ if (open) { menu.innerHTML = ''; fill(menu, close) }+ })+ document.addEventListener('click', close)+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close() })+ wrap.append(b, menu)+ return wrap+ }++ private menuItem(icon: IconName, label: string, hint: string, onClick: () => void): HTMLElement {+ const b = document.createElement('button')+ b.className = 'sp-dditem'+ b.type = 'button'+ b.setAttribute('role', 'menuitem')+ b.innerHTML = `<span class="sp-result-ico">${ICONS[icon]}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(label)}</strong>` ++ (hint ? `<span>${escapeHtml(hint)}</span>` : '') + `</span>`+ b.addEventListener('click', (e) => { e.stopPropagation(); onClick() })+ return b+ }++ /** Open/close the page drawer on narrow screens, with a scrim to tap away. */+ private toggleSidebar(force?: boolean): void {+ const open = force ?? !this.sidebar.classList.contains('sp-open')+ this.sidebar.classList.toggle('sp-open', open)+ document.querySelector('.sp-scrim')?.remove()+ if (open) {+ const scrim = el('div', 'sp-scrim')+ scrim.addEventListener('click', () => this.toggleSidebar(false))+ document.body.append(scrim)+ }+ }++ status(msg: string): void {+ this.statusEl.textContent = msg+ this.statusEl.classList.add('sp-on')+ clearTimeout((this.statusEl as any)._t)+ ;(this.statusEl as any)._t = setTimeout(() => this.statusEl.classList.remove('sp-on'), 1800)+ }++ // ---- the page tree ------------------------------------------------------+ private paintTree(): void {+ const s = this.store+ this.sidebar.innerHTML = ''+ const head = el('div', 'sp-side-head')+ head.append(el('span', 'sp-side-title', t('Pages')))+ head.append(iconBtn('plus', t('New page (⌘⌥N)'), () => this.newPage()))+ this.sidebar.append(head)++ const list = el('ul', 'sp-tree')+ for (const { page, depth } of s.tree()) {+ if (page.archived) continue+ const li = document.createElement('li')+ li.style.paddingInlineStart = `${depth * 14}px`+ const a = document.createElement('a')+ a.href = `#p/${page.id}`+ a.className = 'sp-treelink' + (page.id === s.pageId ? ' sp-here' : '')+ const ico = el('span', 'sp-tree-ico')+ ico.innerHTML = pageIcon(page.icon)+ const label = document.createElement('span')+ label.textContent = page.title || t('Untitled')+ a.append(ico, label)+ a.draggable = true+ a.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(page.id); this.toggleSidebar(false) })+ a.addEventListener('dragstart', (e) => e.dataTransfer?.setData('text/bento-page', page.id))+ a.addEventListener('dragover', (e) => { e.preventDefault(); a.classList.add('sp-drop') })+ a.addEventListener('dragleave', () => a.classList.remove('sp-drop'))+ a.addEventListener('drop', (e) => {+ e.preventDefault(); a.classList.remove('sp-drop')+ const moved = e.dataTransfer?.getData('text/bento-page')+ if (moved && moved !== page.id) this.reparentPage(moved, page.id)+ })+ const more = document.createElement('button')+ more.className = 'sp-rowmore'+ more.type = 'button'+ more.innerHTML = ICONS.more+ more.title = t('Page options')+ more.setAttribute('aria-label', t('Page options'))+ more.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); this.openPageMenu(page.id, more) })+ a.append(more)++ li.append(a)+ list.append(li)+ }+ if (!list.childElementCount) list.append(el('li', 'sp-side-empty', t('No pages yet')))+ this.sidebar.append(list)++ // Archived pages are OUT OF THE WAY, never invisible: they are still+ // searchable and linkable, and someone about to share the file needs to be+ // able to see what is going with it.+ const archived = s.doc.pages.filter((p) => p.archived)+ if (archived.length) {+ const det = document.createElement('details')+ det.className = 'sp-archived'+ const sum = document.createElement('summary')+ sum.textContent = t('Archived ({n})', { n: archived.length })+ det.append(sum)+ const al = el('ul', 'sp-tree')+ for (const page of archived) {+ const li = document.createElement('li')+ const a = document.createElement('a')+ a.href = `#p/${page.id}`+ a.className = 'sp-treelink sp-arch-row' + (page.id === s.pageId ? ' sp-here' : '')+ const ico = el('span', 'sp-tree-ico')+ ico.innerHTML = pageIcon(page.icon)+ const label = document.createElement('span')+ label.textContent = page.title || t('Untitled')+ a.append(ico, label)+ a.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(page.id); this.toggleSidebar(false) })+ const un = document.createElement('button')+ un.className = 'sp-rowmore'+ un.type = 'button'+ un.innerHTML = ICONS.unarchive+ un.title = t('Restore to the page list')+ un.setAttribute('aria-label', t('Restore to the page list'))+ un.addEventListener('click', (e) => {+ e.preventDefault(); e.stopPropagation()+ s.commit(() => { const p = s.index.page.get(page.id); if (p) delete p.archived })+ })+ a.append(un)+ li.append(a)+ al.append(li)+ }+ det.append(al)+ this.sidebar.append(det)+ }++ // dropping on the empty area below the tree makes a page top-level again+ list.addEventListener('dragover', (e) => e.preventDefault())+ this.sidebar.addEventListener('drop', (e) => {+ if ((e.target as HTMLElement).closest('.sp-treelink')) return+ e.preventDefault()+ const moved = e.dataTransfer?.getData('text/bento-page')+ if (moved) this.reparentPage(moved, '')+ })+ }++ /** Re-parent a page, refusing a move that would make it its own ancestor. */+ private reparentPage(id: string, parent: string): void {+ if (id === parent) return+ for (let p: string | undefined = parent; p; p = this.store.index.page.get(p)?.parent) {+ if (p === id) { this.status(t('A page cannot contain itself')); return }+ }+ this.store.commit(() => {+ const page = this.store.index.page.get(id)+ if (!page) return+ if (parent) page.parent = parent+ else delete page.parent+ })+ }++ newPage(parent?: string): void {+ const page = newPage(t('Untitled'))+ if (parent) page.parent = parent+ this.store.commit(() => { this.store.doc.pages.push(page) })+ this.store.goToPage(page.id)+ afterPaint(() => {+ const h = this.main.querySelector<HTMLElement>('[data-page-title]')+ h?.focus()+ if (h) selectAll(h)+ })+ }++ // ---- the page -----------------------------------------------------------+ private paintPage(): void {+ const s = this.store+ const page = s.page+ this.main.innerHTML = ''+ if (!page) { this.main.append(el('p', 'sp-empty', t('This space has no pages.'))); return }++ this.painting = true+ const trail: string[] = []+ for (let p = page.parent; p; p = s.index.page.get(p)?.parent) {+ const owner = s.index.page.get(p)+ if (!owner) break+ trail.unshift(owner.id)+ if (trail.length > 4) break+ }+ const view = renderPage(page, s.doc, {+ editable: !s.readOnly && !this.reading,+ titleOf: (id) => s.index.page.get(id)?.title,+ allowRemote: (src) => this.allowedRemote.has(src),+ })+ // the icon lives beside the title, where changing it is discoverable+ const inner = view.querySelector('.sp-page-inner')+ if (inner && !s.readOnly && !this.reading) {+ const pick = document.createElement('button')+ pick.className = 'sp-pageicon'+ pick.type = 'button'+ pick.innerHTML = pageIcon(page.icon)+ pick.title = t('Change this page\'s icon')+ pick.setAttribute('aria-label', t('Change this page\'s icon'))+ pick.addEventListener('click', () => this.openIconPicker(page.id, pick))+ inner.prepend(pick)+ }++ if (trail.length) {+ const crumb = el('nav', 'sp-crumb')+ crumb.setAttribute('aria-label', t('Breadcrumb'))+ trail.forEach((id, i) => {+ if (i) crumb.append(Object.assign(document.createElement('span'), { textContent: '›' }))+ const a = document.createElement('a')+ a.href = `#p/${id}`+ a.textContent = s.index.page.get(id)?.title || t('Untitled')+ a.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(id) })+ crumb.append(a)+ })+ view.querySelector('.sp-page-inner')?.prepend(crumb)+ }+ this.main.append(view)+ this.wire(view)+ view.querySelector('.sp-page-inner')?.append(this.backlinks(page.id))+ this.painting = false+ }++ /**+ * The hover gutter.+ *+ * A block editor with no visible affordances is a guessing game: nothing on+ * screen says a block can be moved or that a new one can go here. These sit+ * OUTSIDE the text column so they never reflow the prose, and only appear on+ * hover so a page at rest is just the writing.+ */+ private addGutter(node: HTMLElement, blockId: string): void {+ const g = el('div', 'sp-gutter')+ const add = document.createElement('button')+ add.className = 'sp-ghost'+ add.type = 'button'+ add.innerHTML = ICONS.plus+ add.title = t('Add a block below')+ add.setAttribute('aria-label', t('Add a block below'))+ add.addEventListener('click', () => this.insertAfter(blockId))++ const grip = document.createElement('button')+ grip.className = 'sp-ghost'+ grip.type = 'button'+ grip.draggable = true+ grip.innerHTML = ICONS.grip+ grip.title = t('Drag to move, click for block options')+ grip.setAttribute('aria-label', t('Block options'))+ grip.addEventListener('click', () => this.openSlash(blockId, grip))+ grip.addEventListener('dragstart', (e) => {+ e.dataTransfer?.setData('text/bento-block', blockId)+ node.classList.add('sp-dragging')+ })+ grip.addEventListener('dragend', () => node.classList.remove('sp-dragging'))++ node.addEventListener('dragover', (e) => { e.preventDefault(); node.classList.add('sp-dropline') })+ node.addEventListener('dragleave', () => node.classList.remove('sp-dropline'))+ node.addEventListener('drop', (e) => {+ e.preventDefault()+ node.classList.remove('sp-dropline')+ const moved = e.dataTransfer?.getData('text/bento-block')+ if (moved && moved !== blockId) this.moveBlock(moved, blockId)+ })++ g.append(add, grip)+ node.prepend(g)+ }++ private insertAfter(blockId: string): void {+ const s = this.store+ const page = s.page+ if (!page) return+ const fresh = newBlock('p')+ const owner = s.block(blockId)+ if (owner?.parent) fresh.parent = owner.parent+ s.commit(() => {+ page.blocks.splice(page.blocks.findIndex((b) => b.id === blockId) + 1, 0, fresh)+ })+ this.paintPage()+ this.focusBlock(fresh.id)+ }++ /** Move a block (and anything nested under it) to sit after another. */+ private moveBlock(moved: string, after: string): void {+ const s = this.store+ const page = s.page+ if (!page) return+ const from = page.blocks.findIndex((b) => b.id === moved)+ if (from < 0) return+ // a subtree travels with its owner, or its children would be orphaned+ const kids: string[] = []+ const collect = (id: string) => {+ for (const b of page.blocks) if (b.parent === id) { kids.push(b.id); collect(b.id) }+ }+ collect(moved)+ if (kids.includes(after)) return // never drop a block inside its own subtree+ s.commit(() => {+ const group = [moved, ...kids].map((id) => page.blocks.find((b) => b.id === id)!).filter(Boolean)+ for (const b of group) page.blocks.splice(page.blocks.indexOf(b), 1)+ const at = page.blocks.findIndex((b) => b.id === after) + 1+ page.blocks.splice(at, 0, ...group)+ })+ this.paintPage()+ }++ /** Attach behaviour to a freshly painted page. */+ private wire(view: HTMLElement): void {+ const s = this.store++ const title = view.querySelector<HTMLElement>('[data-page-title]')+ if (title) {+ title.dataset.ph = t('Untitled')+ if (!title.textContent?.trim()) title.dataset.empty = '1'+ title.addEventListener('input', () => { if (title.textContent?.trim()) delete title.dataset.empty; else title.dataset.empty = '1' })+ }+ title?.addEventListener('input', () => {+ if (this.painting) return+ const id = title.dataset.pageTitle!+ s.runEdit(`title:${id}`, () => {+ const p = s.index.page.get(id)+ if (p) p.title = title.textContent ?? ''+ })+ this.paintTreeSoon()+ })++ for (const node of view.querySelectorAll<HTMLElement>('[data-block-id]')) {+ if (!s.readOnly && !this.reading) this.addGutter(node, node.dataset.blockId!)+ }++ for (const host of view.querySelectorAll<HTMLElement>('[data-edit]')) {+ const id = host.dataset.edit!+ host.dataset.ph = t('Type / for blocks, [[ to link a page')+ host.addEventListener('input', () => {+ if (this.painting) return+ delete host.dataset.empty+ s.runEdit(id, () => {+ const b = s.block(id)+ if (b) b.html = host.innerHTML+ })+ this.autoformat(id, host)+ })+ host.addEventListener('blur', () => {+ if (this.painting) return+ s.endRun()+ const b = s.block(id)+ if (b && b.html !== undefined) {+ const clean = canonicalize(b.html)+ if (clean !== b.html) { b.html = clean; host.innerHTML = clean }+ }+ })+ }++ for (const box of view.querySelectorAll<HTMLInputElement>('.sp-check')) {+ box.addEventListener('change', () => {+ const id = (box.closest('[data-block-id]') as HTMLElement).dataset.blockId!+ s.commit(() => { const b = s.block(id); if (b) b.done = box.checked }, { structure: false })+ box.closest('[data-block-id]')!.classList.toggle('sp-done', box.checked)+ })+ }++ for (const tw of view.querySelectorAll<HTMLElement>('.sp-twist')) {+ tw.addEventListener('click', () => {+ const id = (tw.closest('[data-block-id]') as HTMLElement).dataset.blockId!+ s.commit(() => { const b = s.block(id); if (b) b.open = !b.open })+ this.paintPage()+ })+ }++ // "Load this image" — the reader's consent to contact one remote host.+ // NOT a commit: nothing about the document changed, so this must not touch+ // undo, the dirty flag or autosave. It is view state, and it dies with the+ // session (see allowedRemote).+ for (const btn of view.querySelectorAll<HTMLElement>('[data-load-remote]')) {+ btn.addEventListener('click', (e) => {+ e.preventDefault()+ this.allowedRemote.add(btn.dataset.loadRemote!)+ this.paintPage()+ })+ }++ // an image can arrive by paste or by drop, not only through a menu+ view.addEventListener('paste', (e) => {+ const cur = this.blockAt(document.activeElement)+ if (e.clipboardData?.files?.length) {+ e.preventDefault()+ void this.imageFromTransfer(e.clipboardData, cur?.id)+ }+ })+ view.addEventListener('dragover', (e) => {+ if (e.dataTransfer?.types.includes('Files')) { e.preventDefault(); view.classList.add('sp-filedrop') }+ })+ view.addEventListener('dragleave', () => view.classList.remove('sp-filedrop'))+ view.addEventListener('drop', (e) => {+ if (!e.dataTransfer?.types.includes('Files')) return+ e.preventDefault()+ view.classList.remove('sp-filedrop')+ const near = (e.target as HTMLElement)?.closest?.('[data-block-id]') as HTMLElement | null+ void this.imageFromTransfer(e.dataTransfer, near?.dataset.blockId)+ })++ for (const fig of view.querySelectorAll<HTMLElement>('.sp-b-image')) {+ const id = fig.dataset.blockId!+ const b = s.block(id)+ const tools = el('div', 'sp-imgtools')+ const sizeBtn = document.createElement('button')+ sizeBtn.className = 'sp-btn'+ sizeBtn.type = 'button'+ sizeBtn.textContent = `${b?.width ?? 100}%`+ sizeBtn.title = t('Width in the text column')+ sizeBtn.addEventListener('click', () => {+ const steps = [100, 75, 50, 33]+ const cur = Number(b?.width ?? 100)+ const next = steps[(steps.indexOf(cur) + 1) % steps.length]+ s.commit(() => { const bb = s.block(id); if (bb) bb.width = next })+ this.paintPage()+ })+ tools.append(sizeBtn)+ // a re-encoded image says so, and offers the untouched bytes back+ if (b && b.original === false) {+ const badge = document.createElement('button')+ badge.className = 'sp-btn sp-badge'+ badge.type = 'button'+ badge.textContent = t('Resized')+ badge.title = t('This image was resized to keep the file small. Click to replace it with the original.')+ badge.addEventListener('click', () => void this.pickImage(id))+ tools.append(badge)+ }+ fig.append(tools)+ }++ // intra-space links navigate without leaving the document+ view.addEventListener('click', (e) => {+ const a = (e.target as HTMLElement).closest('a')+ if (!a) return+ const href = a.getAttribute('href') ?? ''+ if (href.startsWith('#p/')) { e.preventDefault(); s.goToPage(href.slice(3)) }+ })+ }++ private treeTimer: ReturnType<typeof setTimeout> | undefined+ private paintTreeSoon(): void {+ clearTimeout(this.treeTimer)+ this.treeTimer = setTimeout(() => this.paintTree(), 250)+ }++ /** What links here — derived, never stored. */+ private backlinks(pageId: string): HTMLElement {+ const s = this.store+ const refs = s.index.backlinks.get(pageId) ?? []+ const box = el('section', 'sp-backlinks')+ if (!refs.length) return box+ box.append(el('h2', 'sp-backlinks-h', t('Linked from')))+ const seen = new Set<string>()+ const ul = el('ul', 'sp-backlink-list')+ for (const r of refs) {+ if (seen.has(r.pageId)) continue+ seen.add(r.pageId)+ const from = s.index.page.get(r.pageId)+ if (!from) continue+ const li = document.createElement('li')+ const a = document.createElement('a')+ a.href = `#p/${from.id}`+ a.textContent = from.title || t('Untitled')+ a.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(from.id) })+ const snippet = textOf(s.index.block.get(r.blockId)?.block.html).slice(0, 120)+ li.append(a)+ if (snippet) li.append(el('span', 'sp-snippet', snippet))+ ul.append(li)+ }+ box.append(ul)+ return box+ }++ // ---- editing ------------------------------------------------------------+ private blockAt(node: Node | null): { id: string; host: HTMLElement } | null {+ const host = (node instanceof HTMLElement ? node : node?.parentElement)?.closest<HTMLElement>('[data-edit]')+ return host ? { id: host.dataset.edit!, host } : null+ }++ private focused(): { id: string; host: HTMLElement } | null {+ return this.blockAt(document.activeElement)+ }++ /** Markdown prefixes convert the block as they are typed. */+ private autoformat(id: string, host: HTMLElement): void {+ const text = host.textContent ?? ''+ for (const [re, type, extra] of AUTOFORMAT) {+ if (!re.test(text)) continue+ const s = this.store+ const b = s.block(id)+ if (!b || b.type === type) return+ s.commit(() => { b.type = type; b.html = ''; extra(b) })+ this.paintPage()+ this.focusBlock(id)+ return+ }+ }++ private focusBlock(id: string, atEnd = true): void {+ afterPaint(() => {+ const host = this.main.querySelector<HTMLElement>(`[data-edit="${CSS.escape(id)}"]`)+ if (!host) return+ host.focus()+ if (atEnd) caretToEnd(host)+ })+ }++ private onKey(e: KeyboardEvent): void {+ const s = this.store+ const mod = (e as any)[CTRL] as boolean++ if (mod && e.key.toLowerCase() === 'k' && !e.shiftKey) { e.preventDefault(); this.openSearch(); return }+ if (mod && e.key.toLowerCase() === 's') { e.preventDefault(); this.onSave?.(); return }+ if (mod && e.key.toLowerCase() === 'p') { e.preventDefault(); this.openPrint(); return }+ if (mod && e.key.toLowerCase() === 'f') { e.preventDefault(); this.openFind(); return }+ if (mod && e.altKey && e.key.toLowerCase() === 'n') { e.preventDefault(); this.newPage(); return }+ if (mod && e.key.toLowerCase() === 'z') {+ e.preventDefault()+ if (e.shiftKey) s.redo(); else s.undo()+ this.paintPage(); this.paintTree()+ return+ }+ if (e.key === 'Escape' && this.reading && !this.overlay) { e.preventDefault(); this.toggleReading(false); return }+ if (this.overlay) return // the overlay owns the keyboard while it is open++ const cur = this.focused()+ if (!cur) return+ const b = s.block(cur.id)+ if (!b) return++ // native undo must never diverge from the store's history+ if (mod && (e.key.toLowerCase() === 'y')) { e.preventDefault(); s.redo(); this.paintPage(); return }++ if (e.key === 'Enter' && !e.shiftKey && b.type !== 'code') {+ e.preventDefault()+ this.splitBlock(cur.id, cur.host)+ return+ }+ if (e.key === 'Backspace' && atStart(cur.host)) {+ const empty = !(cur.host.textContent ?? '').trim()+ if (b.type !== 'p' && empty) { e.preventDefault(); this.setType(cur.id, 'p'); return }+ e.preventDefault()+ this.mergeBack(cur.id)+ return+ }+ if (e.key === 'Tab') {+ e.preventDefault()+ this.indent(cur.id, !e.shiftKey)+ return+ }+ if (e.key === '/' && !(cur.host.textContent ?? '').trim()) {+ // a slash on an empty block opens the block menu+ setTimeout(() => this.openSlash(cur.id), 0)+ return+ }+ if (e.key === '[' && cur.host.textContent?.endsWith('[')) {+ setTimeout(() => this.openPagePicker(cur.id, cur.host), 0)+ return+ }+ if (mod && ['b', 'i', 'u'].includes(e.key.toLowerCase())) {+ e.preventDefault()+ document.execCommand(({ b: 'bold', i: 'italic', u: 'underline' } as any)[e.key.toLowerCase()])+ s.runEdit(cur.id, () => { const bb = s.block(cur.id); if (bb) bb.html = cur.host.innerHTML })+ return+ }+ }++ private splitBlock(id: string, host: HTMLElement): void {+ const s = this.store+ const b = s.block(id)+ if (!b) return+ const [before, after] = splitAtCaret(host)+ const fresh = newBlock(b.type === 'h1' || b.type === 'h2' || b.type === 'h3' ? 'p' : b.type, { html: after })+ if (b.type === 'todo') fresh.done = false+ if (b.parent) fresh.parent = b.parent+ s.commit(() => {+ b.html = before+ const page = s.page!+ page.blocks.splice(page.blocks.indexOf(b) + 1, 0, fresh)+ })+ this.paintPage()+ this.focusBlock(fresh.id, false)+ }++ private mergeBack(id: string): void {+ const s = this.store+ const page = s.page+ if (!page) return+ const i = page.blocks.findIndex((x) => x.id === id)+ if (i <= 0) return+ const prev = page.blocks[i - 1]+ const b = page.blocks[i]+ if (prev.type === 'divider') { s.commit(() => { page.blocks.splice(i - 1, 1) }); this.paintPage(); this.focusBlock(id); return }+ const at = (prev.html ?? '').length+ s.commit(() => {+ prev.html = (prev.html ?? '') + (b.html ?? '')+ // a merged-away parent would orphan its children — re-home them+ for (const child of page.blocks) if (child.parent === b.id) child.parent = prev.id+ page.blocks.splice(i, 1)+ })+ this.paintPage()+ afterPaint(() => {+ const host = this.main.querySelector<HTMLElement>(`[data-edit="${CSS.escape(prev.id)}"]`)+ if (host) { host.focus(); caretToOffset(host, at) }+ })+ }++ /** Tab sets `parent` to the previous sibling — one field write. */+ private indent(id: string, deeper: boolean): void {+ const s = this.store+ const page = s.page+ if (!page) return+ const i = page.blocks.findIndex((x) => x.id === id)+ const b = page.blocks[i]+ if (!b) return+ s.commit(() => {+ if (!deeper) {+ if (!b.parent) return+ const owner = page.blocks.find((x) => x.id === b.parent)+ if (owner?.parent) b.parent = owner.parent+ else delete b.parent+ return+ }+ // the nearest preceding block at the same level becomes the owner+ for (let j = i - 1; j >= 0; j--) {+ if (page.blocks[j].parent === b.parent) { b.parent = page.blocks[j].id; return }+ }+ })+ this.paintPage()+ this.focusBlock(id)+ }++ setType(id: string, type: string): void {+ this.store.commit(() => {+ const b = this.store.block(id)+ if (!b) return+ b.type = type+ if (type === 'todo' && b.done === undefined) b.done = false+ if (type === 'toggle' && b.open === undefined) b.open = true+ })+ this.paintPage()+ this.focusBlock(id)+ }++ // ---- overlays -----------------------------------------------------------+ private openOverlay(title: string, build: (body: HTMLElement, close: () => void) => void): void {+ this.closeOverlay()+ const back = el('div', 'sp-overlay')+ const card = el('div', 'sp-card')+ card.setAttribute('role', 'dialog')+ card.setAttribute('aria-label', title)+ const close = () => this.closeOverlay()+ build(card, close)+ back.append(card)+ back.addEventListener('mousedown', (e) => { if (e.target === back) close() })+ document.body.append(back)+ this.overlay = back+ const onEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); close() } }+ back.addEventListener('keydown', onEsc)+ card.querySelector<HTMLElement>('input,button,[tabindex]')?.focus()+ }++ private closeOverlay(): void {+ this.overlay?.remove()+ this.overlay = null+ }++ /** Anchor a popover to a rect, kept inside the viewport. */++ /** ⌘K — search every page, including collapsed toggles and archived pages. */+ openSearch(): void {+ const s = this.store+ this.openOverlay(t('Search'), (card, close) => {+ const input = document.createElement('input')+ input.className = 'sp-find'+ input.placeholder = t('Search all pages…')+ const results = el('ul', 'sp-results')+ const run = () => {+ const q = input.value.trim().toLowerCase()+ results.innerHTML = ''+ if (!q) return+ let n = 0+ for (const p of s.doc.pages) {+ const hits: string[] = []+ if (p.title.toLowerCase().includes(q)) hits.push(p.title)+ for (const b of p.blocks) {+ const text = textOf(b.html)+ if (text.toLowerCase().includes(q)) hits.push(text)+ if (hits.length > 2) break+ }+ if (!hits.length) continue+ if (++n > 30) break+ const li = document.createElement('li')+ const a = document.createElement('button')+ a.className = 'sp-result'+ a.innerHTML =+ `<span class="sp-result-ico">${ICONS.page}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(p.title || t('Untitled'))}` ++ (p.archived ? ` <em class="sp-arch">${t('archived')}</em>` : '') + `</strong>` ++ `<span>${escapeHtml(hits.slice(0, 2).join(' · ').slice(0, 140))}</span></span>`+ a.addEventListener('click', () => { close(); s.goToPage(p.id) })+ li.append(a)+ results.append(li)+ }+ if (!results.childElementCount) results.append(el('li', 'sp-noresult', t('Nothing found')))+ }+ input.addEventListener('input', run)+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') results.querySelector<HTMLElement>('.sp-result')?.click()+ })+ card.append(el('h2', 'sp-card-h', t('Search this space')), input, results)+ })+ }++ /**+ * The block menu, anchored where you are.+ *+ * A centred modal for "turn this line into a heading" loses the thing you+ * were pointing at. This opens beside the caret (or the gutter button that+ * summoned it), is driven entirely by the keyboard, and filters as you type+ * so `/h2` reaches a heading without the hand leaving the keys.+ */+ private openSlash(blockId: string, anchor?: HTMLElement): void {+ this.closeOverlay()+ const pop = el('div', 'sp-pop')+ pop.setAttribute('role', 'listbox')+ const find = document.createElement('input')+ find.className = 'sp-find'+ find.placeholder = t('Filter blocks…')+ const list = el('ul', 'sp-results')+ pop.append(find, list)++ let items = SLASH_ITEMS+ let sel = 0+ const commit = (item: typeof SLASH_ITEMS[number]) => {+ this.closeOverlay()+ const blk = this.store.block(blockId)+ // the "/" that opened the menu is a command, not content+ if (blk && (blk.html ?? '').trim() === '/') blk.html = ''+ if (item.type === 'pagelink') this.insertPageCard(blockId)+ else this.setType(blockId, item.type)+ }+ const paint = () => {+ list.innerHTML = ''+ items.forEach((item, i) => {+ const li = document.createElement('li')+ const b = document.createElement('button')+ b.className = 'sp-result' + (i === sel ? ' sp-sel' : '')+ b.type = 'button'+ b.setAttribute('role', 'option')+ b.innerHTML =+ `<span class="sp-result-ico">${ICONS[item.icon]}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(t(item.label))}</strong>` ++ `<span>${escapeHtml(t(item.hint))}</span></span>`+ b.addEventListener('click', () => commit(item))+ li.append(b)+ list.append(li)+ })+ if (!items.length) list.append(el('li', 'sp-noresult', t('No block matches')))+ }+ find.addEventListener('input', () => {+ const q = find.value.trim().toLowerCase()+ items = SLASH_ITEMS.filter((i) => t(i.label).toLowerCase().includes(q) || i.type.includes(q))+ sel = 0+ paint()+ })+ find.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowDown') { e.preventDefault(); sel = Math.min(sel + 1, items.length - 1); paint() }+ else if (e.key === 'ArrowUp') { e.preventDefault(); sel = Math.max(sel - 1, 0); paint() }+ else if (e.key === 'Enter') { e.preventDefault(); if (items[sel]) commit(items[sel]) }+ else if (e.key === 'Escape') { e.preventDefault(); this.closeOverlay(); this.focusBlock(blockId) }+ })+ paint()++ document.body.append(pop)+ this.overlay = pop+ place(pop, anchor ?? caretRect())+ find.focus()++ // clicking anywhere else dismisses, but not the first click that opened it+ setTimeout(() => {+ const away = (ev: MouseEvent) => {+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }+ }+ document.addEventListener('mousedown', away)+ }, 0)+ }++ private insertPageCard(blockId: string): void {+ this.openPagePicker(blockId, null, (pageId) => {+ this.store.commit(() => {+ const b = this.store.block(blockId)+ if (b) { b.type = 'pagelink'; b.page = pageId; b.html = '' }+ })+ this.paintPage()+ })+ }++ /** `[[` — pick a page, or make one, and link it inline. */+ private openPagePicker(blockId: string, host: HTMLElement | null, then?: (pageId: string) => void): void {+ const s = this.store+ this.openOverlay(t('Link to page'), (card, close) => {+ const input = document.createElement('input')+ input.className = 'sp-find'+ input.placeholder = t('Find or create a page…')+ const list = el('ul', 'sp-results')+ const choose = (pageId: string, title: string) => {+ close()+ if (then) { then(pageId); return }+ if (!host) return+ // the two "[" that opened the picker are not content+ const html = (host.innerHTML ?? '').replace(/\[?\[$/, '')+ const link = `<a href="#p/${pageId}">${escapeHtml(title)}</a> `+ s.commit(() => { const b = s.block(blockId); if (b) b.html = sanitizeInline(html + link) })+ this.paintPage()+ this.focusBlock(blockId)+ }+ const run = () => {+ const q = input.value.trim().toLowerCase()+ list.innerHTML = ''+ for (const p of s.doc.pages) {+ if (q && !p.title.toLowerCase().includes(q)) continue+ const li = document.createElement('li')+ const b = document.createElement('button')+ b.className = 'sp-result'+ b.type = 'button'+ b.innerHTML =+ `<span class="sp-result-ico">${ICONS.page}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(p.title || t('Untitled'))}</strong></span>`+ b.addEventListener('click', () => choose(p.id, p.title || t('Untitled')))+ li.append(b)+ list.append(li)+ if (list.childElementCount > 20) break+ }+ if (input.value.trim()) {+ const li = document.createElement('li')+ const b = document.createElement('button')+ b.className = 'sp-result sp-new'+ b.type = 'button'+ b.innerHTML =+ `<span class="sp-result-ico">${ICONS.plus}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(t('Create “{name}”', { name: input.value.trim() }))}</strong></span>`+ b.addEventListener('click', () => {+ const page = newPage(input.value.trim())+ s.commit(() => { s.doc.pages.push(page) })+ choose(page.id, page.title)+ })+ li.append(b)+ list.append(li)+ }+ }+ input.addEventListener('input', run)+ card.append(input, list)+ run()+ })+ }++ /** Pick a page icon from the stylised set. */+ private openIconPicker(pageId: string, anchor: HTMLElement): void {+ this.closeOverlay()+ const pop = el('div', 'sp-pop sp-iconpop')+ for (const name of PAGE_ICONS) {+ const b = document.createElement('button')+ b.className = 'sp-iconopt'+ b.type = 'button'+ b.innerHTML = ICONS[name]+ b.title = name+ b.setAttribute('aria-label', name)+ b.addEventListener('click', () => {+ this.closeOverlay()+ this.store.commit(() => {+ const p = this.store.index.page.get(pageId)+ if (p) p.icon = name+ })+ this.paintPage()+ })+ pop.append(b)+ }+ document.body.append(pop)+ this.overlay = pop+ place(pop, anchor)+ setTimeout(() => {+ const away = (ev: MouseEvent) => {+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }+ }+ document.addEventListener('mousedown', away)+ }, 0)+ }++ /** Rename, archive, or delete one page. */+ private openPageMenu(pageId: string, anchor: HTMLElement): void {+ const s = this.store+ const page = s.index.page.get(pageId)+ if (!page) return+ this.closeOverlay()+ const pop = el('div', 'sp-pop')+ pop.setAttribute('role', 'menu')++ pop.append(this.menuItem('edit', t('Rename'), '', () => {+ this.closeOverlay()+ s.goToPage(pageId)+ afterPaint(() => {+ const h = this.main.querySelector<HTMLElement>('[data-page-title]')+ if (h) { h.focus(); selectAll(h) }+ })+ }))++ pop.append(this.menuItem('plus', t('New page inside'), '', () => {+ this.closeOverlay()+ this.newPage(pageId)+ }))++ pop.append(this.menuItem(page.archived ? 'unarchive' : 'archive',+ page.archived ? t('Restore to the page list') : t('Archive'),+ page.archived ? '' : t('Out of the sidebar, still searchable and linkable'), () => {+ this.closeOverlay()+ s.commit(() => {+ const p = s.index.page.get(pageId)+ if (!p) return+ if (p.archived) delete p.archived+ else p.archived = true+ })+ }))++ pop.append(this.menuItem('trash', t('Delete…'), t('Links to it become dead'), () => {+ this.closeOverlay()+ this.deletePage(pageId)+ }))++ document.body.append(pop)+ this.overlay = pop+ place(pop, anchor)+ setTimeout(() => {+ const away = (ev: MouseEvent) => {+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }+ }+ document.addEventListener('mousedown', away)+ }, 0)+ }++ /**+ * Delete a page.+ *+ * Its children are re-homed to ITS parent rather than deleted with it —+ * removing a middle page should not silently take a subtree the author was+ * not looking at. Inbound links are counted in the confirmation, because+ * "this will break 4 links" is the fact that decides it.+ */+ private deletePage(pageId: string): void {+ const s = this.store+ const page = s.index.page.get(pageId)+ if (!page) return+ if (s.doc.pages.length <= 1) { this.status(t('A space needs at least one page')); return }+ const inbound = (s.index.backlinks.get(pageId) ?? []).length+ const kids = s.doc.pages.filter((p) => p.parent === pageId).length+ const parts = [t('Delete “{name}”?', { name: page.title || t('Untitled') })]+ if (inbound) parts.push(t('{n} link(s) to it will stop working.', { n: inbound }))+ if (kids) parts.push(t('{n} page(s) inside it move up a level.', { n: kids }))+ if (!confirm(parts.join('\n'))) return+ s.commit(() => {+ for (const p of s.doc.pages) if (p.parent === pageId) {+ if (page.parent) p.parent = page.parent+ else delete p.parent+ }+ s.doc.pages.splice(s.doc.pages.findIndex((p) => p.id === pageId), 1)+ if (s.doc.home === pageId) delete s.doc.home+ })+ this.repaint()+ }++ // ---- images --------------------------------------------------------------+ /** Choose a file and put it in the document. */+ async pickImage(blockId: string): Promise<void> {+ const input = document.createElement('input')+ input.type = 'file'+ input.accept = 'image/*'+ input.addEventListener('change', () => {+ const file = input.files?.[0]+ if (file) void this.placeImage(blockId, file)+ })+ input.click()+ }++ /**+ * Embed one image.+ *+ * Everything slow and asynchronous — reading, decoding, re-encoding, hashing+ * — happens BEFORE the commit, so the bytes and the reference land in ONE+ * synchronous mutation. That is what makes an image insert a single undo+ * step instead of a half-inserted block if something throws in between.+ */+ async placeImage(+ blockId: string | null,+ file: File | Blob,+ opts: { keepOriginal?: boolean; insertAfter?: string | null } = {},+ ): Promise<void> {+ const s = this.store+ this.status(t('Reading image…'))+ let prepared+ try {+ prepared = opts.keepOriginal+ ? { dataUri: await blobToDataUri(file), w: 0, h: 0, original: true, wasBytes: file.size }+ : await prepareImage(file)+ } catch {+ this.status(t('That file could not be read as an image'))+ return+ }++ if (prepared.dataUri.length > IMAGE_EMBED_BUDGET) {+ const ok = confirm(t(+ 'This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?',+ { size: humanBytes(prepared.dataUri.length) },+ ))+ if (!ok) { this.status(''); return }+ }++ const ref = await internAsset(s.doc, prepared.dataUri)+ const fill = (b: Block) => {+ b.type = 'image'+ b.src = ref+ b.html = ''+ if (prepared.w) { b.w = prepared.w; b.h = prepared.h }+ if (!prepared.original) b.original = false+ else delete b.original+ }+ // ONE commit, whether the block already exists or is being created here.+ // Creating it in a separate commit would make an inserted image take TWO+ // undos, the second of which removes a block the author never saw.+ s.commit(() => {+ if (blockId) { const b = s.block(blockId); if (b) fill(b) ; return }+ const page = s.page+ if (!page) return+ const fresh = newBlock('image')+ fill(fresh)+ const at = opts.insertAfter ? page.blocks.findIndex((b) => b.id === opts.insertAfter) + 1 : page.blocks.length+ page.blocks.splice(at < 1 ? page.blocks.length : at, 0, fresh)+ })+ this.paintPage()+ this.status(prepared.original+ ? t('Image added ({size})', { size: humanBytes(prepared.dataUri.length) })+ : t('Image added, resized to fit ({from} → {to})', {+ from: humanBytes(prepared.wasBytes), to: humanBytes(prepared.dataUri.length),+ }))+ }++ /** Drop or paste an image straight onto the page. */+ private async imageFromTransfer(dt: DataTransfer | null, afterId?: string): Promise<boolean> {+ const file = [...(dt?.files ?? [])].find((f) => f.type.startsWith('image/'))+ ?? [...(dt?.items ?? [])].filter((i) => i.type.startsWith('image/')).map((i) => i.getAsFile())[0]+ if (!file) return false+ if (!this.store.page) return false+ await this.placeImage(null, file, { insertAfter: afterId ?? null })+ return true+ }++ // ---- find and replace ----------------------------------------------------+ /**+ * ⌘F is OURS, not the browser's.+ *+ * Native find cannot see a collapsed toggle's body, cannot see a page that is+ * not currently rendered, and cannot see an archived page at all — which is+ * most of a space. So this searches the MODEL, jumps to each hit, expands+ * whatever was folded around it, and can replace across every page in one+ * undoable step.+ */+ openFind(): void {+ const s = this.store+ document.querySelector('.sp-findbar')?.remove()+ const bar = el('div', 'sp-findbar')+ bar.setAttribute('role', 'search')++ const q = document.createElement('input')+ q.className = 'sp-find'+ q.placeholder = t('Find in this space…')+ q.setAttribute('aria-label', t('Find'))++ const rep = document.createElement('input')+ rep.className = 'sp-find'+ rep.placeholder = t('Replace with…')+ rep.setAttribute('aria-label', t('Replace with'))++ const count = el('span', 'sp-findcount')+ const mk = (icon: IconName, label: string, fn: () => void) => {+ const b = document.createElement('button')+ b.className = 'sp-btn'+ b.type = 'button'+ b.innerHTML = ICONS[icon]+ b.title = label+ b.setAttribute('aria-label', label)+ b.addEventListener('click', fn)+ return b+ }++ // ONE ENTRY PER OCCURRENCE, not per block. The readout, the stepper and the+ // replace-all confirmation then all quote the same number — and it is the+ // number of things that will actually change, because it comes from the+ // routine that changes them (countOutsideTags / replaceOutsideTags share+ // mapTextChunks). Counting blocks meant "2 found" above a dialog offering+ // to replace 2, which then replaced 4.+ let hits: Array<{ pageId: string; blockId: string }> = []+ let at = -1++ const scan = () => {+ const needle = q.value+ hits = []+ at = -1+ if (needle) {+ for (const p of s.doc.pages) {+ for (const b of p.blocks) {+ const n = countOutsideTags(b.html, needle)+ for (let i = 0; i < n; i++) hits.push({ pageId: p.id, blockId: b.id })+ }+ }+ }+ count.textContent = hits.length ? t('{n} found', { n: hits.length }) : (needle ? t('none') : '')+ }++ const jump = (dir: 1 | -1) => {+ if (!hits.length) return+ at = (at + dir + hits.length) % hits.length+ const hit = hits[at]+ count.textContent = t('{i} of {n}', { i: at + 1, n: hits.length })++ // Unfold FIRST, then navigate — one paint, and no dependence on when a+ // repaint happens to land. Doing it the other way round meant reveal ran+ // against whichever page the store had reached by the next frame, and+ // the fold stayed shut.+ const opened = this.revealBlock(hit.pageId, hit.blockId)+ if (hit.pageId !== s.pageId) s.goToPage(hit.pageId)+ else if (opened) this.paintPage()++ afterPaint(() => {+ const node = this.main.querySelector<HTMLElement>(`[data-block-id="${CSS.escape(hit.blockId)}"]`)+ node?.scrollIntoView({ block: 'center', behavior: 'smooth' })+ // two occurrences in one block are two stops: restart the flash, or+ // the second step looks like the stepper did nothing+ node?.classList.remove('sp-hit')+ void node?.offsetWidth+ node?.classList.add('sp-hit')+ setTimeout(() => node?.classList.remove('sp-hit'), 1400)+ })+ }++ const replaceAll = () => {+ const needle = q.value+ if (!needle || !hits.length) return+ if (!confirm(t('Replace {n} occurrence(s) across the whole space?', { n: hits.length }))) return+ // ONE commit for the whole sweep: a replace-all a user has to undo forty+ // times is not undoable in any sense they care about+ s.commit(() => {+ for (const p of s.doc.pages) {+ for (const b of p.blocks) {+ if (!countOutsideTags(b.html, needle)) continue+ b.html = replaceOutsideTags(b.html!, needle, rep.value)+ }+ }+ })+ this.repaint()+ scan()+ this.status(t('Replaced'))+ }++ q.addEventListener('input', scan)+ q.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); jump(e.shiftKey ? -1 : 1) }+ if (e.key === 'Escape') { e.preventDefault(); bar.remove() }+ })+ rep.addEventListener('keydown', (e) => { if (e.key === 'Escape') bar.remove() })++ bar.append(q, mk('arrowUp', t('Previous (⇧⏎)'), () => jump(-1)),+ mk('arrowDown', t('Next (⏎)'), () => jump(1)), count,+ rep, mk('replace', t('Replace all'), replaceAll),+ mk('close', t('Close'), () => bar.remove()))+ this.root.append(bar)+ q.focus()+ scan()+ }++ /**+ * Open every toggle between a block and the top of its page, so a hit is+ * actually visible when we arrive at it.+ *+ * Takes the page id EXPLICITLY rather than reading the current page: the+ * caller may not have navigated yet, and depending on that ordering is what+ * broke this the first time. Returns whether anything changed, so the caller+ * can decide whether a repaint is owed.+ */+ private revealBlock(pageId: string, blockId: string): boolean {+ const s = this.store+ const page = s.index.page.get(pageId)+ if (!page) return false+ let changed = false+ let cur = page.blocks.find((b) => b.id === blockId)+ const guard = new Set<string>()+ while (cur?.parent && !guard.has(cur.parent)) {+ guard.add(cur.parent)+ const owner = page.blocks.find((b) => b.id === cur!.parent)+ if (!owner) break+ if (owner.type === 'toggle' && !owner.open) { owner.open = true; changed = true }+ cur = owner+ }+ // a fold opened to show a search hit is a VIEW change, not an edit: it is+ // mutated directly rather than through commit(), so searching never lands+ // on the undo stack or marks the document modified+ return changed+ }++ // ---- print ---------------------------------------------------------------+ /**+ * Printing is the ONLY export-to-PDF path, so it is a contract rather than a+ * stylesheet: what goes in, in what order, and what happens to the things a+ * screen can hide.+ *+ * Collapsed toggles print EXPANDED, always. Silently omitting content from a+ * printed handbook is a data-loss-shaped bug — the reader has no way to know+ * a paragraph was folded away.+ */+ openPrint(): void {+ const s = this.store+ this.openOverlay(t('Print'), (card, close) => {+ card.append(el('h2', 'sp-card-h', t('Print or save as PDF')))++ const scope = document.createElement('div')+ scope.className = 'sp-choices'+ let whole = true+ const choice = (label: string, hint: string, on: boolean, pick: () => void) => {+ const b = document.createElement('button')+ b.className = 'sp-choice' + (on ? ' sp-sel' : '')+ b.type = 'button'+ b.innerHTML = `<strong>${escapeHtml(label)}</strong><span>${escapeHtml(hint)}</span>`+ b.addEventListener('click', () => {+ pick()+ for (const o of scope.querySelectorAll('.sp-choice')) o.classList.remove('sp-sel')+ b.classList.add('sp-sel')+ })+ return b+ }+ const pageCount = s.doc.pages.filter((p) => !p.archived).length+ scope.append(+ choice(t('The whole space'), t('{n} pages, in sidebar order, with a contents page', { n: pageCount }), true, () => { whole = true }),+ choice(t('This page only'), s.page?.title || t('Untitled'), false, () => { whole = false }),+ )+ card.append(scope)++ const opts = document.createElement('div')+ opts.className = 'sp-optlist'+ const check = (label: string, hint: string, on: boolean) => {+ const l = document.createElement('label')+ l.className = 'sp-opt'+ const i = document.createElement('input')+ i.type = 'checkbox'+ i.checked = on+ l.append(i, Object.assign(document.createElement('span'), {+ innerHTML: `<strong>${escapeHtml(label)}</strong><span>${escapeHtml(hint)}</span>`,+ }))+ opts.append(l)+ return i+ }+ const wantArchived = check(t('Include archived pages'), t('Off by default — they were archived for a reason'), false)+ const wantContents = check(t('Contents page'), t('A list of every page, in order'), true)+ card.append(opts)++ const note = document.createElement('p')+ note.className = 'sp-note'+ note.textContent = t('Collapsed toggles always print open. Your browser\'s print dialog has the "Save as PDF" option.')+ card.append(note)++ const go = document.createElement('button')+ go.className = 'sp-btn sp-primary'+ go.textContent = t('Print…')+ go.addEventListener('click', () => {+ close()+ this.printNow({ whole, archived: wantArchived.checked, contents: wantContents.checked })+ })+ card.append(go)+ })+ }++ /**+ * Build a print-only rendering, print it, and take it away again.+ *+ * The screen shows ONE page; print needs all of them, so this renders a+ * separate tree rather than trying to make the editor's DOM serve both. It+ * is removed in `afterprint`, so nothing about the editor is left changed.+ */+ private printNow(opts: { whole: boolean; archived: boolean; contents: boolean }): void {+ const s = this.store+ const host = el('div', 'sp-printroot')+ host.style.direction = 'ltr'++ const pages = opts.whole+ ? s.tree().map((n) => n.page).filter((p) => opts.archived || !p.archived)+ : (s.page ? [s.page] : [])++ if (opts.whole && opts.contents) {+ const toc = el('section', 'sp-toc')+ toc.append(el('h1', 'sp-toc-h', s.doc.title || t('Contents')))+ const ul = el('ul', 'sp-toc-list')+ for (const { page, depth } of s.tree()) {+ if (!opts.archived && page.archived) continue+ const li = document.createElement('li')+ li.style.paddingInlineStart = `${depth * 16}px`+ li.textContent = page.title || t('Untitled')+ ul.append(li)+ }+ toc.append(ul)+ host.append(toc)+ }++ for (const page of pages) {+ host.append(renderPage(page, s.doc, {+ editable: false, forceOpen: true,+ titleOf: (id) => s.index.page.get(id)?.title,+ allowRemote: (src) => this.allowedRemote.has(src),+ }))+ }++ document.body.append(host)+ document.body.classList.add('sp-printing')+ const cleanup = () => {+ host.remove()+ document.body.classList.remove('sp-printing')+ window.removeEventListener('afterprint', cleanup)+ }+ window.addEventListener('afterprint', cleanup)+ // some engines return from print() before afterprint fires+ setTimeout(() => { if (document.body.contains(host)) cleanup() }, 60000)+ print()+ }++ private exportMarkdown(): void {+ this.onSaveAs?.('__markdown')+ }++ private async saveAs(suffix: string): Promise<void> {+ this.onSaveAs?.(suffix)+ }++ // ---- routing ------------------------------------------------------------+ private fromHash(): void {+ const m = location.hash.match(/^#p\/(.+)$/)+ if (m && this.store.index.page.has(m[1])) this.store.goToPage(m[1], { push: false })+ }++ repaint(): void { this.paintTree(); this.paintPage() }+}++// ---- small dom helpers ------------------------------------------------------+function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] {+ const n = document.createElement(tag)+ n.className = cls+ if (text) n.textContent = text+ return n+}++function iconBtn(name: IconName, label: string, onClick: () => void): HTMLButtonElement {+ const b = document.createElement('button')+ b.className = 'sp-btn'+ b.type = 'button'+ b.innerHTML = ICONS[name]+ b.title = label+ b.setAttribute('aria-label', label)+ b.addEventListener('click', onClick)+ return b+}++const escapeHtml = (s: string): string =>+ s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')++function atStart(host: HTMLElement): boolean {+ const sel = getSelection()+ if (!sel || !sel.rangeCount) return false+ const r = sel.getRangeAt(0)+ if (!r.collapsed) return false+ const probe = r.cloneRange()+ probe.selectNodeContents(host)+ probe.setEnd(r.startContainer, r.startOffset)+ return probe.toString().length === 0+}++function caretToEnd(host: HTMLElement): void {+ const r = document.createRange()+ r.selectNodeContents(host)+ r.collapse(false)+ const sel = getSelection()+ sel?.removeAllRanges()+ sel?.addRange(r)+}++function caretToOffset(host: HTMLElement, offset: number): void {+ const walker = document.createTreeWalker(host, NodeFilter.SHOW_TEXT)+ let seen = 0+ let node: Node | null+ while ((node = walker.nextNode())) {+ const len = node.textContent?.length ?? 0+ if (seen + len >= offset) {+ const r = document.createRange()+ r.setStart(node, offset - seen)+ r.collapse(true)+ const sel = getSelection()+ sel?.removeAllRanges()+ sel?.addRange(r)+ return+ }+ seen += len+ }+ caretToEnd(host)+}++function selectAll(host: HTMLElement): void {+ const r = document.createRange()+ r.selectNodeContents(host)+ const sel = getSelection()+ sel?.removeAllRanges()+ sel?.addRange(r)+}++/** Split a block's html at the caret, returning [before, after]. */+function splitAtCaret(host: HTMLElement): [string, string] {+ const sel = getSelection()+ if (!sel || !sel.rangeCount) return [host.innerHTML, '']+ const r = sel.getRangeAt(0)+ const after = r.cloneRange()+ after.selectNodeContents(host)+ after.setStart(r.endContainer, r.endOffset)+ const tail = after.cloneContents()+ const before = r.cloneRange()+ before.selectNodeContents(host)+ before.setEnd(r.startContainer, r.startOffset)+ const head = before.cloneContents()+ const wrap = (f: DocumentFragment) => { const d = document.createElement('div'); d.append(f); return d.innerHTML }+ return [sanitizeInline(wrap(head)), sanitizeInline(wrap(tail))]+}++/** Where the caret is, in viewport coordinates. */+function caretRect(): DOMRect {+ const sel = getSelection()+ if (sel && sel.rangeCount) {+ const r = sel.getRangeAt(0).getBoundingClientRect()+ if (r.width || r.height || r.top) return r+ }+ return new DOMRect(80, 120, 0, 0)+}++/** Place a popover near an anchor without letting it leave the viewport. */+function place(pop: HTMLElement, anchor: HTMLElement | DOMRect): void {+ const r = anchor instanceof HTMLElement ? anchor.getBoundingClientRect() : anchor+ const w = pop.offsetWidth || 260+ const h = pop.offsetHeight || 260+ let left = r.left+ let top = r.bottom + 6+ if (left + w > innerWidth - 8) left = Math.max(8, innerWidth - w - 8)+ if (top + h > innerHeight - 8) top = Math.max(8, r.top - h - 6)+ pop.style.left = `${Math.max(8, left)}px`+ pop.style.top = `${top}px`+}++/**+ * A page's icon.+ *+ * `icon` is a NAME from the stylised set. Older documents (and anything an+ * agent writes) may carry an emoji instead, so that still renders — but the+ * set is what the app offers, because a sidebar of twelve colour emoji reads+ * as a row of stickers rather than one interface.+ */+export function pageIcon(icon: string | undefined): string {+ if (!icon) return ICONS.page+ if (icon in ICONS) return ICONS[icon as IconName]+ return escapeHtml(icon) // an emoji, or anything else the file carried+}++/** The icons a page may choose from. */+export const PAGE_ICONS: IconName[] = [+ 'page', 'note', 'book', 'folder', 'inbox', 'star', 'tag', 'hash',+ 'compass', 'pen', 'scale', 'link', 'todo', 'code', 'image', 'archive',+]++/**+ * Replace text without touching markup.+ *+ * A naive string replace over `html` would happily rewrite a tag name or an+ * href — searching for "a" and replacing it would destroy every link on the+ * page. This walks the string and only substitutes OUTSIDE angle brackets.+ */++/**+ * Run after the next paint — but run REGARDLESS.+ *+ * `requestAnimationFrame` does not fire at all in a hidden tab, so anything+ * whose CORRECTNESS depends on it silently never happens: search a space,+ * switch tabs before the frame lands, come back, and the jump was never+ * completed. rAF is right when the page is visible (it is the only way to act+ * after layout); a timeout is the fallback that always arrives.+ */+export function afterPaint(fn: () => void): void {+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') { setTimeout(fn, 0); return }+ let done = false+ const once = () => { if (!done) { done = true; fn() } }+ requestAnimationFrame(once)+ setTimeout(once, 120) // rAF starved (throttled tab, background window)+}diff --git a/spaces/src/findreplace.ts b/spaces/src/findreplace.tsnew file mode 100644index 00000000..66e68c76--- /dev/null+++ b/spaces/src/findreplace.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Find and replace over inline html.+//+// Its own module, with NO DOM dependency, for one reason: the number the+// interface shows and the number of things that change must be the same+// number, and that is a property worth testing directly rather than by+// clicking. Both functions are built on one traversal, so they cannot drift.++/**+ * Walk the TEXT of an inline-html string, tag by tag, mapping each text chunk.+ *+ * THE single definition of "where a match can be", shared by counting and+ * replacing so the two can never disagree. A count derived any other way — from+ * `textOf()`, say — would promise replacements that cannot happen: `wid<b>get+ * </b>` reads as one word but is two chunks, so it counts once and replaces+ * never. Telling someone "3 found" and changing 2 is the bug this shape exists+ * to make impossible.+ */+function mapTextChunks(html: string, fn: (chunk: string) => string): string {+ const out: string[] = []+ let i = 0+ while (i < html.length) {+ const lt = html.indexOf('<', i)+ const chunk = lt < 0 ? html.slice(i) : html.slice(i, lt)+ out.push(fn(chunk))+ if (lt < 0) break+ const gt = html.indexOf('>', lt)+ if (gt < 0) { out.push(html.slice(lt)); break }+ out.push(html.slice(lt, gt + 1)) // the tag itself, untouched+ i = gt + 1+ }+ return out.join('')+}++/** How many times `needle` would actually be replaced in this block. */+export function countOutsideTags(html: string | undefined, needle: string): number {+ if (!html || !needle) return 0+ const lowerNeedle = needle.toLowerCase()+ let n = 0+ mapTextChunks(html, (chunk) => {+ const lower = chunk.toLowerCase()+ for (let from = 0; ;) {+ const at = lower.indexOf(lowerNeedle, from)+ if (at < 0) return chunk+ n+++ from = at + needle.length+ }+ })+ return n+}++export function replaceOutsideTags(html: string, needle: string, withText: string): string {+ if (!needle) return html+ // CASE-INSENSITIVE, to match the search that produced the count. A+ // case-sensitive replace behind a case-insensitive find is the worst kind of+ // mismatch: it reports "14 found" and quietly changes nine of them.+ const lowerNeedle = needle.toLowerCase()+ return mapTextChunks(html, (chunk) => {+ const lower = chunk.toLowerCase()+ let out = ''+ let from = 0+ for (;;) {+ const at = lower.indexOf(lowerNeedle, from)+ if (at < 0) { out += chunk.slice(from); return out }+ out += chunk.slice(from, at) + withText+ from = at + needle.length+ }+ })+}diff --git a/spaces/src/i18n.ts b/spaces/src/i18n.tsindex 0ab65a6a..6eea220a 100644--- a/spaces/src/i18n.ts+++ b/spaces/src/i18n.ts@@ -5,18 +5,70 @@// re-exports the engine, so registration is guaranteed to precede the first// t() call by ES module evaluation order.//-// SCAFFOLD: no translations yet — English-string-as-key means every string-// works untranslated, and catalogs can be added later without touching call-// sites. App code imports './i18n', never the kernel module directly.+// ENGLISH-STRING-AS-KEY (gettext style): the source sentence IS the key, so a+// missing entry falls back to readable English rather than a blank. Never call+// t() in a module-level const — it would freeze at import time, before the+// viewer's locale is resolved.-import { registerI18n } from '../../kernel/src/i18n.ts'+import { registerI18n, locale } from '../../kernel/src/i18n.ts'import type { LocaleChoice } from '../../kernel/src/i18n.ts'+import { PACKED, PACKED_LOCALES } from './i18n/packed'-const CHOICES: LocaleChoice[] = [{ code: 'en', label: 'English' }]+/** Offered in the About picker, each labelled in its own language. */+const CHOICES: LocaleChoice[] = [+ { code: 'en', label: 'English' },+ { code: 'ja', label: '日本語' },+ { code: 'zh-Hans', label: '简体中文' },+ { code: 'zh-Hant', label: '繁體中文' },+ { code: 'es', label: 'Español' },+ { code: 'fr', label: 'Français' },+ { code: 'de', label: 'Deutsch' },+ { code: 'it', label: 'Italiano' },+ { code: 'pt', label: 'Português' },+]-registerI18n({ catalogs: {}, choices: CHOICES })+registerI18n({+ packed: {+ locales: PACKED_LOCALES,+ table: PACKED,+ // Regional codes a browser actually reports, mapped onto a column. Without+ // these, a zh-TW reader falls all the way back to English despite the+ // traditional catalog being right there.+ alias: {+ zh: 'zh-Hans',+ 'zh-CN': 'zh-Hans',+ 'zh-SG': 'zh-Hans',+ 'zh-TW': 'zh-Hant',+ 'zh-HK': 'zh-Hant',+ 'zh-MO': 'zh-Hant',+ 'pt-BR': 'pt',+ 'pt-PT': 'pt',+ },+ },+ choices: CHOICES,+})export const LOCALE_CHOICES = CHOICESexport { t, locale, setLocale, i18nApi, localeChoices } from '../../kernel/src/i18n.ts'export type { Catalog } from '../../kernel/src/i18n.ts'++/** Languages whose CHROME reads right-to-left. */+const RTL = new Set(['ar', 'he', 'fa', 'ur', 'ps', 'sd', 'yi'])++export const isRtl = (code: string): boolean => RTL.has(code.split('-')[0].toLowerCase())++/**+ * Point the CHROME at the viewer's language (PLATFORM §8).+ *+ * Deliberately called AFTER capturePristine(): saves re-serialize the pristine+ * clone, so the dir/lang attributes never reach a saved file. Direction follows+ * the VIEWER; the DOCUMENT's own base direction is theme.dir, pinned on the+ * inner container by the renderer. Two different things that must never be+ * confused — a document does not mirror because its reader's UI does.+ */+export function applyDirection(): void {+ const code = locale()+ document.documentElement.lang = code+ document.documentElement.dir = isRtl(code) ? 'rtl' : 'ltr'+}diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsnew file mode 100644index 00000000..aaf8e97d--- /dev/null+++ b/spaces/src/i18n/de.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// German — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = Space (m., "der Space") — kept as a loanword the way the German slides catalog keeps "Deck", so the UI stays tied to the product name bento/spaces; "Bereich" would break that link · page = Seite · block = Block (pl. Blöcke)++import type { Catalog } from '../i18n'++export const de: Catalog = {+ "A list of every page, in order": "Eine Liste aller Seiten, der Reihe nach",+ "A page cannot contain itself": "Eine Seite kann sich nicht selbst enthalten",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Ein Passwort verschlüsselt das Dokument in der Datei. Es gibt keine Wiederherstellung — verlierst du es, ist der Space weg.",+ "A second file — the original is left alone": "Eine zweite Datei — das Original bleibt unberührt",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "Ein Space ist nie eine Sackgasse: Das ganze Dokument ist reines JSON in dieser Datei, und jede Seite lässt sich als Markdown exportieren.",+ "A space needs at least one page": "Ein Space braucht mindestens eine Seite",+ "About this space": "Über diesen Space",+ "Add a block below": "Block darunter hinzufügen",+ "Archive": "Archivieren",+ "Archived ({n})": "Archiviert ({n})",+ "Block options": "Block-Optionen",+ "Breadcrumb": "Pfadnavigation",+ "Change this page's icon": "Symbol dieser Seite ändern",+ "Check for updates": "Nach Updates suchen",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "Die Prüfung ist manuell und verifiziert: Der Download ist signiert, und seine Signatur wird gegen einen Schlüssel in dieser Datei geprüft, bevor irgendetwas überschrieben wird.",+ "Checking…": "Prüfe…",+ "Choose a password. There is no way to recover it.": "Wähle ein Passwort. Es lässt sich nicht wiederherstellen.",+ "Close": "Schließen",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Zugeklappte Toggle-Blöcke werden immer offen gedruckt. Im Druckdialog deines Browsers gibt es die Option „Als PDF speichern“.",+ "Contents": "Inhalt",+ "Contents page": "Inhaltsverzeichnis",+ "Copy document JSON": "Dokument-JSON kopieren",+ "Copy saved": "Kopie gespeichert",+ "Copy the document JSON": "Dokument-JSON kopieren",+ "Could not reach the update channel.": "Der Update-Kanal war nicht erreichbar.",+ "Could not verify an update, so nothing was changed.": "Ein Update ließ sich nicht verifizieren, daher wurde nichts geändert.",+ "Create “{name}”": "„{name}“ erstellen",+ "Delete “{name}”?": "„{name}“ löschen?",+ "Delete…": "Löschen…",+ "Discard": "Verwerfen",+ "Downloaded. Open the new file — this one is unchanged.": "Heruntergeladen. Öffne die neue Datei — diese hier bleibt unverändert.",+ "Drag to move, click for block options": "Ziehen zum Verschieben, klicken für Block-Optionen",+ "Edited": "Bearbeitet",+ "Editing": "Bearbeiten",+ "Encrypt the document inside this file": "Das Dokument in dieser Datei verschlüsseln",+ "Enter the password to open it.": "Gib das Passwort ein, um ihn zu öffnen.",+ "Every page, as one .md file": "Jede Seite, in einer .md-Datei",+ "Export as Markdown": "Als Markdown exportieren",+ "Export as Markdown…": "Als Markdown exportieren…",+ "File": "Datei",+ "Filter blocks…": "Blöcke filtern…",+ "Find": "Suchen",+ "Find in this space…": "In diesem Space suchen…",+ "Find or create a page…": "Seite finden oder erstellen…",+ "Image added ({size})": "Bild hinzugefügt ({size})",+ "Image added, resized to fit ({from} → {to})": "Bild hinzugefügt, passend verkleinert ({from} → {to})",+ "Include archived pages": "Archivierte Seiten einbeziehen",+ "Insert": "Einfügen",+ "Insert a block — text, headings, lists, code, images": "Block einfügen — Text, Überschriften, Listen, Code, Bilder",+ "Interface language": "Sprache der Oberfläche",+ "Language": "Sprache",+ "Language follows whoever opens the file. It is never written into the document.": "Die Sprache richtet sich danach, wer die Datei öffnet. Sie wird nie ins Dokument geschrieben.",+ "Link to page": "Seite verlinken",+ "Linked from": "Verlinkt von",+ "Links to it become dead": "Links darauf laufen ins Leere",+ "New page (⌘⌥N)": "Neue Seite (⌘⌥N)",+ "New page inside": "Neue Unterseite",+ "Next (⏎)": "Weiter (⏎)",+ "No block matches": "Kein Block passt",+ "No pages yet": "Noch keine Seiten",+ "Nothing found": "Nichts gefunden",+ "Off by default — they were archived for a reason": "Standardmäßig aus — sie wurden aus einem Grund archiviert",+ "Other ways to save": "Weitere Speicheroptionen",+ "Out of the sidebar, still searchable and linkable": "Weg aus der Seitenleiste, weiterhin auffindbar und verlinkbar",+ "Page options": "Seiten-Optionen",+ "Pages": "Seiten",+ "Pages — show or hide the page list": "Seiten — Seitenliste ein- oder ausblenden",+ "Password": "Passwort",+ "Password removed. Save to write the space unencrypted.": "Passwort entfernt. Speichere, um den Space unverschlüsselt zu schreiben.",+ "Password set. Save to write the space encrypted.": "Passwort gesetzt. Speichere, um den Space verschlüsselt zu schreiben.",+ "Password…": "Passwort…",+ "Previous (⇧⏎)": "Zurück (⇧⏎)",+ "Print": "Drucken",+ "Print / PDF…": "Drucken / PDF…",+ "Print or save as PDF": "Drucken oder als PDF speichern",+ "Print or save as PDF (⌘P)": "Drucken oder als PDF speichern (⌘P)",+ "Print…": "Drucken…",+ "Reading image…": "Lese Bild…",+ "Reading view — press Esc or the eye to edit": "Leseansicht — Esc oder das Auge zum Bearbeiten",+ "Reading view — the pages without the editing tools": "Leseansicht — die Seiten ohne Bearbeitungswerkzeuge",+ "Redo (⇧⌘Z)": "Wiederholen (⇧⌘Z)",+ "Remove password…": "Passwort entfernen…",+ "Remove the password? The next save writes the document in the clear.": "Das Passwort entfernen? Beim nächsten Speichern wird das Dokument im Klartext geschrieben.",+ "Rename": "Umbenennen",+ "Replace all": "Alle ersetzen",+ "Replace with": "Ersetzen durch",+ "Replace with…": "Ersetzen durch…",+ "Replace {n} occurrence(s) across the whole space?": "{n} Vorkommen im ganzen Space ersetzen?",+ "Replaced": "Ersetzt",+ "Resized": "Verkleinert",+ "Restore": "Wiederherstellen",+ "Restore to the page list": "Zurück in die Seitenliste",+ "Save": "Speichern",+ "Save (⌘S)": "Speichern (⌘S)",+ "Save a copy…": "Kopie speichern…",+ "Save an untouched copy…": "Unveränderte Kopie speichern…",+ "Saved": "Gespeichert",+ "Saved a new copy": "Neue Kopie gespeichert",+ "Saving…": "Speichere…",+ "Search": "Suche",+ "Search all pages (⌘K)": "Alle Seiten durchsuchen (⌘K)",+ "Search all pages…": "Alle Seiten durchsuchen…",+ "Search this space": "Diesen Space durchsuchen",+ "Set a password…": "Passwort festlegen…",+ "Space name": "Space-Name",+ "Take it elsewhere": "Woanders weitermachen",+ "That file could not be read as an image": "Diese Datei konnte nicht als Bild gelesen werden",+ "The document block is not shaped like a space — {detail}.": "Der Dokumentblock ist nicht wie ein Space aufgebaut — {detail}.",+ "The document block is not valid JSON — {detail}.": "Der Dokumentblock ist kein gültiges JSON — {detail}.",+ "The whole space": "Der ganze Space",+ "The whole space, or just this page": "Der ganze Space oder nur diese Seite",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "Dieser Browser kann nicht in die Datei zurückschreiben, deshalb entsteht bei jedem Speichern eine neue Kopie. Chrome und Edge auf dem Computer können direkt speichern.",+ "This file": "Diese Datei",+ "This file could not be opened": "Diese Datei konnte nicht geöffnet werden",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "Diese Datei nennt Regeln, die dieser Build nicht kennt. Sie ist schreibgeschützt geöffnet, damit nichts verloren geht.",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "Diese Datei wurde von einer neueren Version von bento/spaces geschrieben. Sie ist schreibgeschützt geöffnet, damit nichts verloren geht.",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "Dieses Bild ist {size} groß und reist in der Datei mit — die Datei wird für jeden, dem du sie schickst, entsprechend größer. Trotzdem einbetten?",+ "This image was resized to keep the file small. Click to replace it with the original.": "Dieses Bild wurde verkleinert, damit die Datei klein bleibt. Klicken, um es durch das Original zu ersetzen.",+ "This is not a bento/spaces document — {detail}.": "Dies ist kein bento/spaces-Dokument — {detail}.",+ "This page only": "Nur diese Seite",+ "This space has no pages.": "Dieser Space hat keine Seiten.",+ "This space is encrypted. Saves stay encrypted.": "Dieser Space ist verschlüsselt. Speichern bleibt verschlüsselt.",+ "This space is locked": "Dieser Space ist gesperrt",+ "Type / for blocks, [[ to link a page": "Tippe / für Blöcke, [[ für einen Seitenlink",+ "Undo (⌘Z)": "Rückgängig (⌘Z)",+ "Unlock": "Entsperren",+ "Unlocked, but the document inside could not be read.": "Entsperrt, aber das Dokument darin konnte nicht gelesen werden.",+ "Unsaved changes from a previous session were found.": "Nicht gespeicherte Änderungen aus einer früheren Sitzung gefunden.",+ "Untitled": "Ohne Titel",+ "Update this file": "Diese Datei aktualisieren",+ "Updates": "Updates",+ "Version {v} is available.": "Version {v} ist verfügbar.",+ "Width in the text column": "Breite in der Textspalte",+ "Wrong password — try again": "Falsches Passwort — bitte erneut versuchen",+ "You have the newest version ({v}).": "Du hast die neueste Version ({v}).",+ "archived": "archiviert",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} Seiten, {blocks} Blöcke. Das Dokument, der Editor und die Suche stecken alle in dieser einen Datei.",+ "none": "keine",+ "{i} of {n}": "{i} von {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "{n} doppelte oder fehlende IDs wurden repariert, damit Links und Seiten wieder gefunden werden.",+ "{n} found": "{n} Treffer",+ "{n} link(s) to it will stop working.": "{n} Links darauf funktionieren nicht mehr.",+ "{n} page(s) inside it move up a level.": "{n} Unterseiten rücken eine Ebene nach oben.",+ "{n} pages, in sidebar order, with a contents page": "{n} Seiten, in der Reihenfolge der Seitenleiste, mit Inhaltsverzeichnis",+ "Image from {host}": "Bild von {host}",+ "Not loaded — opening it would tell that site you opened this space.": "Nicht geladen — beim Laden erfährt diese Website, dass du diesen Space geöffnet hast.",+ "Load this image": "Dieses Bild laden",+}diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsnew file mode 100644index 00000000..82420c1c--- /dev/null+++ b/spaces/src/i18n/es.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Spanish — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = espacio · page = página · block = bloque++import type { Catalog } from '../i18n'++export const es: Catalog = {+ "A list of every page, in order": "Una lista de todas las páginas, en orden",+ "A page cannot contain itself": "Una página no puede contenerse a sí misma",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Una contraseña cifra el documento dentro del archivo. No hay forma de recuperarla — si la pierdes, el espacio desaparece.",+ "A second file — the original is left alone": "Un segundo archivo — el original queda intacto",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "Un espacio nunca es un callejón sin salida: todo el documento es JSON plano dentro de este archivo, y cada página se exporta como Markdown.",+ "A space needs at least one page": "Un espacio necesita al menos una página",+ "About this space": "Acerca de este espacio",+ "Add a block below": "Añadir un bloque debajo",+ "Archive": "Archivar",+ "Archived ({n})": "Archivadas ({n})",+ "Block options": "Opciones del bloque",+ "Breadcrumb": "Ruta de navegación",+ "Change this page's icon": "Cambiar el icono de esta página",+ "Check for updates": "Buscar actualizaciones",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La comprobación es manual y verificada: la descarga va firmada y su firma se contrasta con una clave que está dentro de este archivo antes de reescribir nada.",+ "Checking…": "Comprobando…",+ "Choose a password. There is no way to recover it.": "Elige una contraseña. No hay forma de recuperarla.",+ "Close": "Cerrar",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Los desplegables plegados siempre se imprimen abiertos. El diálogo de impresión de tu navegador tiene la opción «Guardar como PDF».",+ "Contents": "Índice",+ "Contents page": "Página de índice",+ "Copy document JSON": "Copiar JSON del documento",+ "Copy saved": "Copia guardada",+ "Copy the document JSON": "Copiar el JSON del documento",+ "Could not reach the update channel.": "No se pudo contactar con el canal de actualizaciones.",+ "Could not verify an update, so nothing was changed.": "No se pudo verificar la actualización, así que no se cambió nada.",+ "Create “{name}”": "Crear «{name}»",+ "Delete “{name}”?": "¿Eliminar «{name}»?",+ "Delete…": "Eliminar…",+ "Discard": "Descartar",+ "Downloaded. Open the new file — this one is unchanged.": "Descargado. Abre el archivo nuevo — este no ha cambiado.",+ "Drag to move, click for block options": "Arrastra para mover, haz clic para las opciones del bloque",+ "Edited": "Editado",+ "Editing": "Edición",+ "Encrypt the document inside this file": "Cifrar el documento dentro de este archivo",+ "Enter the password to open it.": "Introduce la contraseña para abrirlo.",+ "Every page, as one .md file": "Todas las páginas, en un solo archivo .md",+ "Export as Markdown": "Exportar como Markdown",+ "Export as Markdown…": "Exportar como Markdown…",+ "File": "Archivo",+ "Filter blocks…": "Filtrar bloques…",+ "Find": "Buscar",+ "Find in this space…": "Buscar en este espacio…",+ "Find or create a page…": "Buscar o crear una página…",+ "Image added ({size})": "Imagen añadida ({size})",+ "Image added, resized to fit ({from} → {to})": "Imagen añadida, redimensionada para que quepa ({from} → {to})",+ "Include archived pages": "Incluir páginas archivadas",+ "Insert": "Insertar",+ "Insert a block — text, headings, lists, code, images": "Insertar un bloque — texto, encabezados, listas, código, imágenes",+ "Interface language": "Idioma de la interfaz",+ "Language": "Idioma",+ "Language follows whoever opens the file. It is never written into the document.": "El idioma sigue a quien abre el archivo. Nunca se escribe en el documento.",+ "Link to page": "Enlazar a una página",+ "Linked from": "Enlazado desde",+ "Links to it become dead": "Los enlaces a ella dejan de funcionar",+ "New page (⌘⌥N)": "Nueva página (⌘⌥N)",+ "New page inside": "Nueva página dentro",+ "Next (⏎)": "Siguiente (⏎)",+ "No block matches": "Ningún bloque coincide",+ "No pages yet": "Aún no hay páginas",+ "Nothing found": "Sin resultados",+ "Off by default — they were archived for a reason": "Desactivado por defecto — por algo se archivaron",+ "Other ways to save": "Otras formas de guardar",+ "Out of the sidebar, still searchable and linkable": "Fuera de la barra lateral, pero aún se puede buscar y enlazar",+ "Page options": "Opciones de la página",+ "Pages": "Páginas",+ "Pages — show or hide the page list": "Páginas — mostrar u ocultar la lista de páginas",+ "Password": "Contraseña",+ "Password removed. Save to write the space unencrypted.": "Contraseña eliminada. Guarda para escribir el espacio sin cifrar.",+ "Password set. Save to write the space encrypted.": "Contraseña establecida. Guarda para escribir el espacio cifrado.",+ "Password…": "Contraseña…",+ "Previous (⇧⏎)": "Anterior (⇧⏎)",+ "Print": "Imprimir",+ "Print / PDF…": "Imprimir / PDF…",+ "Print or save as PDF": "Imprimir o guardar como PDF",+ "Print or save as PDF (⌘P)": "Imprimir o guardar como PDF (⌘P)",+ "Print…": "Imprimir…",+ "Reading image…": "Leyendo la imagen…",+ "Reading view — press Esc or the eye to edit": "Vista de lectura — pulsa Esc o el ojo para editar",+ "Reading view — the pages without the editing tools": "Vista de lectura — las páginas sin las herramientas de edición",+ "Redo (⇧⌘Z)": "Rehacer (⇧⌘Z)",+ "Remove password…": "Quitar contraseña…",+ "Remove the password? The next save writes the document in the clear.": "¿Quitar la contraseña? El próximo guardado escribe el documento sin cifrar.",+ "Rename": "Cambiar nombre",+ "Replace all": "Reemplazar todo",+ "Replace with": "Reemplazar por",+ "Replace with…": "Reemplazar por…",+ "Replace {n} occurrence(s) across the whole space?": "¿Reemplazar {n} coincidencia(s) en todo el espacio?",+ "Replaced": "Reemplazado",+ "Resized": "Redimensionada",+ "Restore": "Restaurar",+ "Restore to the page list": "Restaurar a la lista de páginas",+ "Save": "Guardar",+ "Save (⌘S)": "Guardar (⌘S)",+ "Save a copy…": "Guardar una copia…",+ "Save an untouched copy…": "Guardar una copia intacta…",+ "Saved": "Guardado",+ "Saved a new copy": "Se guardó una copia nueva",+ "Saving…": "Guardando…",+ "Search": "Buscar",+ "Search all pages (⌘K)": "Buscar en todas las páginas (⌘K)",+ "Search all pages…": "Buscar en todas las páginas…",+ "Search this space": "Buscar en este espacio",+ "Set a password…": "Establecer una contraseña…",+ "Space name": "Nombre del espacio",+ "Take it elsewhere": "Llévatelo a otra parte",+ "That file could not be read as an image": "No se pudo leer ese archivo como imagen",+ "The document block is not shaped like a space — {detail}.": "El bloque del documento no tiene la forma de un espacio — {detail}.",+ "The document block is not valid JSON — {detail}.": "El bloque del documento no es JSON válido — {detail}.",+ "The whole space": "Todo el espacio",+ "The whole space, or just this page": "Todo el espacio, o solo esta página",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "Este navegador no puede reescribir el archivo, así que cada guardado crea una copia nueva. Chrome y Edge en un ordenador sí pueden guardar en el sitio.",+ "This file": "Este archivo",+ "This file could not be opened": "No se pudo abrir este archivo",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "Este archivo declara reglas que esta versión no conoce. Está abierto en solo lectura para no perder nada.",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "Este archivo lo escribió una versión más reciente de bento/spaces. Está abierto en solo lectura para no perder nada.",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "Esta imagen pesa {size} y viaja dentro del archivo, que crecerá otro tanto para todos a quienes se lo envíes. ¿Incrustarla de todos modos?",+ "This image was resized to keep the file small. Click to replace it with the original.": "Esta imagen se redimensionó para mantener el archivo pequeño. Haz clic para reemplazarla por la original.",+ "This is not a bento/spaces document — {detail}.": "Esto no es un documento de bento/spaces — {detail}.",+ "This page only": "Solo esta página",+ "This space has no pages.": "Este espacio no tiene páginas.",+ "This space is encrypted. Saves stay encrypted.": "Este espacio está cifrado. Los guardados siguen cifrados.",+ "This space is locked": "Este espacio está bloqueado",+ "Type / for blocks, [[ to link a page": "Escribe / para bloques, [[ para enlazar una página",+ "Undo (⌘Z)": "Deshacer (⌘Z)",+ "Unlock": "Desbloquear",+ "Unlocked, but the document inside could not be read.": "Desbloqueado, pero no se pudo leer el documento de dentro.",+ "Unsaved changes from a previous session were found.": "Se encontraron cambios sin guardar de una sesión anterior.",+ "Untitled": "Sin título",+ "Update this file": "Actualizar este archivo",+ "Updates": "Actualizaciones",+ "Version {v} is available.": "Versión {v} disponible.",+ "Width in the text column": "Ancho en la columna de texto",+ "Wrong password — try again": "Contraseña incorrecta: inténtalo de nuevo",+ "You have the newest version ({v}).": "Tienes la versión más reciente ({v}).",+ "archived": "archivada",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} página(s), {blocks} bloque(s). El documento, el editor y la búsqueda están todos en este único archivo.",+ "none": "ninguna",+ "{i} of {n}": "{i} de {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "Se repararon {n} id(s) duplicados o ausentes para que los enlaces y las páginas funcionen.",+ "{n} found": "{n} encontrada(s)",+ "{n} link(s) to it will stop working.": "{n} enlace(s) a ella dejarán de funcionar.",+ "{n} page(s) inside it move up a level.": "{n} página(s) que contiene suben un nivel.",+ "{n} pages, in sidebar order, with a contents page": "{n} páginas, en el orden de la barra lateral, con una página de índice",+ "Image from {host}": "Imagen de {host}",+ "Not loaded — opening it would tell that site you opened this space.": "No cargada: al cargarla, ese sitio sabría que has abierto este espacio.",+ "Load this image": "Cargar esta imagen",+}diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsnew file mode 100644index 00000000..c140f3fe--- /dev/null+++ b/spaces/src/i18n/fr.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// French — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = espace (masculin) — « un espace », « cet espace », « tout l’espace » · page = page (féminin) — « une page », « les pages » · block = bloc (masculin) — « un bloc », « les blocs »++import type { Catalog } from '../i18n'++export const fr: Catalog = {+ "A list of every page, in order": "La liste de toutes les pages, dans l’ordre",+ "A page cannot contain itself": "Une page ne peut pas se contenir elle-même",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Un mot de passe chiffre le document à l’intérieur du fichier. Il n’y a aucune récupération — perdez-le et l’espace est perdu.",+ "A second file — the original is left alone": "Un second fichier — l’original reste intact",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "Un espace n’est jamais une impasse : tout le document est du JSON brut dans ce fichier, et chaque page s’exporte en Markdown.",+ "A space needs at least one page": "Un espace doit contenir au moins une page",+ "About this space": "À propos de cet espace",+ "Add a block below": "Ajouter un bloc en dessous",+ "Archive": "Archiver",+ "Archived ({n})": "Archivées ({n})",+ "Block options": "Options du bloc",+ "Breadcrumb": "Fil d’Ariane",+ "Change this page's icon": "Changer l’icône de cette page",+ "Check for updates": "Rechercher des mises à jour",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La vérification est manuelle et contrôlée : le téléchargement est signé, et sa signature est vérifiée avec une clé contenue dans ce fichier avant toute réécriture.",+ "Checking…": "Vérification…",+ "Choose a password. There is no way to recover it.": "Choisissez un mot de passe. Il est impossible de le récupérer.",+ "Close": "Fermer",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Les bascules repliées s’impriment toujours dépliées. La boîte d’impression de votre navigateur propose « Enregistrer au format PDF ».",+ "Contents": "Sommaire",+ "Contents page": "Page de sommaire",+ "Copy document JSON": "Copier le JSON du document",+ "Copy saved": "Copie enregistrée",+ "Copy the document JSON": "Copier le JSON du document",+ "Could not reach the update channel.": "Impossible de joindre le canal de mise à jour.",+ "Could not verify an update, so nothing was changed.": "Impossible de vérifier une mise à jour, rien n’a été modifié.",+ "Create “{name}”": "Créer « {name} »",+ "Delete “{name}”?": "Supprimer « {name} » ?",+ "Delete…": "Supprimer…",+ "Discard": "Ignorer",+ "Downloaded. Open the new file — this one is unchanged.": "Téléchargé. Ouvrez le nouveau fichier — celui-ci est inchangé.",+ "Drag to move, click for block options": "Glissez pour déplacer, cliquez pour les options du bloc",+ "Edited": "Modifié",+ "Editing": "Édition",+ "Encrypt the document inside this file": "Chiffrer le document à l’intérieur de ce fichier",+ "Enter the password to open it.": "Saisissez le mot de passe pour l’ouvrir.",+ "Every page, as one .md file": "Toutes les pages, en un seul fichier .md",+ "Export as Markdown": "Exporter en Markdown",+ "Export as Markdown…": "Exporter en Markdown…",+ "File": "Fichier",+ "Filter blocks…": "Filtrer les blocs…",+ "Find": "Rechercher",+ "Find in this space…": "Rechercher dans cet espace…",+ "Find or create a page…": "Trouver ou créer une page…",+ "Image added ({size})": "Image ajoutée ({size})",+ "Image added, resized to fit ({from} → {to})": "Image ajoutée, redimensionnée ({from} → {to})",+ "Include archived pages": "Inclure les pages archivées",+ "Insert": "Insérer",+ "Insert a block — text, headings, lists, code, images": "Insérer un bloc — texte, titres, listes, code, images",+ "Interface language": "Langue de l’interface",+ "Language": "Langue",+ "Language follows whoever opens the file. It is never written into the document.": "La langue suit la personne qui ouvre le fichier. Elle n’est jamais écrite dans le document.",+ "Link to page": "Lier à une page",+ "Linked from": "Liens entrants",+ "Links to it become dead": "Les liens vers elle seront rompus",+ "New page (⌘⌥N)": "Nouvelle page (⌘⌥N)",+ "New page inside": "Nouvelle page à l’intérieur",+ "Next (⏎)": "Suivant (⏎)",+ "No block matches": "Aucun bloc correspondant",+ "No pages yet": "Aucune page pour l’instant",+ "Nothing found": "Aucun résultat",+ "Off by default — they were archived for a reason": "Désactivé par défaut — elles ont été archivées pour une raison",+ "Other ways to save": "Autres façons d’enregistrer",+ "Out of the sidebar, still searchable and linkable": "Hors de la barre latérale, toujours dans la recherche et les liens",+ "Page options": "Options de la page",+ "Pages": "Pages",+ "Pages — show or hide the page list": "Pages — afficher ou masquer la liste",+ "Password": "Mot de passe",+ "Password removed. Save to write the space unencrypted.": "Mot de passe supprimé. Enregistrez pour écrire l’espace non chiffré.",+ "Password set. Save to write the space encrypted.": "Mot de passe défini. Enregistrez pour écrire l’espace chiffré.",+ "Password…": "Mot de passe…",+ "Previous (⇧⏎)": "Précédent (⇧⏎)",+ "Print": "Imprimer",+ "Print / PDF…": "Imprimer / PDF…",+ "Print or save as PDF": "Imprimer ou enregistrer en PDF",+ "Print or save as PDF (⌘P)": "Imprimer ou enregistrer en PDF (⌘P)",+ "Print…": "Imprimer…",+ "Reading image…": "Lecture de l’image…",+ "Reading view — press Esc or the eye to edit": "Vue lecture — appuyez sur Esc ou sur l’œil pour modifier",+ "Reading view — the pages without the editing tools": "Vue lecture — les pages sans les outils d’édition",+ "Redo (⇧⌘Z)": "Rétablir (⇧⌘Z)",+ "Remove password…": "Supprimer le mot de passe…",+ "Remove the password? The next save writes the document in the clear.": "Supprimer le mot de passe ? Le prochain enregistrement écrira le document en clair.",+ "Rename": "Renommer",+ "Replace all": "Tout remplacer",+ "Replace with": "Remplacer par",+ "Replace with…": "Remplacer par…",+ "Replace {n} occurrence(s) across the whole space?": "Remplacer {n} occurrence(s) dans tout l’espace ?",+ "Replaced": "Remplacé",+ "Resized": "Redimensionnée",+ "Restore": "Restaurer",+ "Restore to the page list": "Restaurer dans la liste des pages",+ "Save": "Enregistrer",+ "Save (⌘S)": "Enregistrer (⌘S)",+ "Save a copy…": "Enregistrer une copie…",+ "Save an untouched copy…": "Enregistrer une copie sans toucher à l’original…",+ "Saved": "Enregistré",+ "Saved a new copy": "Nouvelle copie enregistrée",+ "Saving…": "Enregistrement…",+ "Search": "Rechercher",+ "Search all pages (⌘K)": "Rechercher dans toutes les pages (⌘K)",+ "Search all pages…": "Rechercher dans toutes les pages…",+ "Search this space": "Rechercher dans cet espace",+ "Set a password…": "Définir un mot de passe…",+ "Space name": "Nom de l’espace",+ "Take it elsewhere": "Emportez-le ailleurs",+ "That file could not be read as an image": "Ce fichier n’a pas pu être lu comme une image",+ "The document block is not shaped like a space — {detail}.": "Le bloc de document n’a pas la forme d’un espace — {detail}.",+ "The document block is not valid JSON — {detail}.": "Le bloc de document n’est pas du JSON valide — {detail}.",+ "The whole space": "Tout l’espace",+ "The whole space, or just this page": "Tout l’espace, ou seulement cette page",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "Ce navigateur ne peut pas réécrire le fichier : chaque enregistrement crée donc une nouvelle copie. Chrome et Edge sur ordinateur enregistrent sur place.",+ "This file": "Ce fichier",+ "This file could not be opened": "Ce fichier n’a pas pu être ouvert",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "Ce fichier déclare des règles que cette version ne connaît pas. Il est ouvert en lecture seule pour ne rien perdre.",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "Ce fichier a été écrit par une version plus récente de bento/spaces. Il est ouvert en lecture seule pour ne rien perdre.",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "Cette image fait {size} et voyage dans le fichier, ce qui l’alourdit d’autant pour toutes les personnes à qui vous l’envoyez. L’intégrer quand même ?",+ "This image was resized to keep the file small. Click to replace it with the original.": "Cette image a été redimensionnée pour garder le fichier léger. Cliquez pour la remplacer par l’originale.",+ "This is not a bento/spaces document — {detail}.": "Ce n’est pas un document bento/spaces — {detail}.",+ "This page only": "Cette page seulement",+ "This space has no pages.": "Cet espace n’a aucune page.",+ "This space is encrypted. Saves stay encrypted.": "Cet espace est chiffré. Les enregistrements restent chiffrés.",+ "This space is locked": "Cet espace est verrouillé",+ "Type / for blocks, [[ to link a page": "Tapez / pour les blocs, [[ pour lier une page",+ "Undo (⌘Z)": "Annuler (⌘Z)",+ "Unlock": "Déverrouiller",+ "Unlocked, but the document inside could not be read.": "Déverrouillé, mais le document à l’intérieur n’a pas pu être lu.",+ "Unsaved changes from a previous session were found.": "Des modifications non enregistrées d’une session précédente ont été trouvées.",+ "Untitled": "Sans titre",+ "Update this file": "Mettre à jour ce fichier",+ "Updates": "Mises à jour",+ "Version {v} is available.": "La version {v} est disponible.",+ "Width in the text column": "Largeur dans la colonne de texte",+ "Wrong password — try again": "Mot de passe incorrect — réessayez",+ "You have the newest version ({v}).": "Vous avez la dernière version ({v}).",+ "archived": "archivée",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} page(s), {blocks} bloc(s). Le document, l’éditeur et la recherche tiennent tous dans ce seul fichier.",+ "none": "aucun",+ "{i} of {n}": "{i} sur {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "{n} id(s) en double ou manquant(s) ont été réparés pour que les liens et les pages se résolvent.",+ "{n} found": "{n} résultat(s)",+ "{n} link(s) to it will stop working.": "{n} lien(s) vers elle ne fonctionneront plus.",+ "{n} page(s) inside it move up a level.": "{n} page(s) qu’elle contient remonteront d’un niveau.",+ "{n} pages, in sidebar order, with a contents page": "{n} pages, dans l’ordre de la barre latérale, avec une page de sommaire",+ "Image from {host}": "Image provenant de {host}",+ "Not loaded — opening it would tell that site you opened this space.": "Non chargée : la charger indiquerait à ce site que vous avez ouvert cet espace.",+ "Load this image": "Charger cette image",+}diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsnew file mode 100644index 00000000..25677a80--- /dev/null+++ b/spaces/src/i18n/it.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Italian — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = spazio · page = pagina · block = blocco++import type { Catalog } from '../i18n'++export const it: Catalog = {+ "A list of every page, in order": "Un elenco di tutte le pagine, in ordine",+ "A page cannot contain itself": "Una pagina non può contenere sé stessa",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Una password cifra il documento dentro il file. Non c’è modo di recuperarla — se la perdi, lo spazio è perso.",+ "A second file — the original is left alone": "Un secondo file — l’originale resta intatto",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "Uno spazio non è mai un vicolo cieco: l’intero documento è JSON puro dentro questo file, e ogni pagina si esporta in Markdown.",+ "A space needs at least one page": "Uno spazio deve avere almeno una pagina",+ "About this space": "Informazioni su questo spazio",+ "Add a block below": "Aggiungi un blocco sotto",+ "Archive": "Archivia",+ "Archived ({n})": "Archiviate ({n})",+ "Block options": "Opzioni del blocco",+ "Breadcrumb": "Percorso di navigazione",+ "Change this page's icon": "Cambia l’icona di questa pagina",+ "Check for updates": "Cerca aggiornamenti",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La verifica è manuale e controllata: il download è firmato e la sua firma viene confrontata con una chiave contenuta in questo file prima che qualcosa venga riscritto.",+ "Checking…": "Verifica in corso…",+ "Choose a password. There is no way to recover it.": "Scegli una password. Non c’è modo di recuperarla.",+ "Close": "Chiudi",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "I blocchi comprimibili chiusi vengono sempre stampati aperti. La finestra di stampa del browser offre l’opzione «Salva come PDF».",+ "Contents": "Indice",+ "Contents page": "Pagina indice",+ "Copy document JSON": "Copia JSON del documento",+ "Copy saved": "Copia salvata",+ "Copy the document JSON": "Copia il JSON del documento",+ "Could not reach the update channel.": "Impossibile raggiungere il canale degli aggiornamenti.",+ "Could not verify an update, so nothing was changed.": "Impossibile verificare l’aggiornamento, quindi non è stato modificato nulla.",+ "Create “{name}”": "Crea «{name}»",+ "Delete “{name}”?": "Eliminare «{name}»?",+ "Delete…": "Elimina…",+ "Discard": "Ignora",+ "Downloaded. Open the new file — this one is unchanged.": "Scaricato. Apri il nuovo file — questo resta invariato.",+ "Drag to move, click for block options": "Trascina per spostare, clicca per le opzioni del blocco",+ "Edited": "Modificato",+ "Editing": "In modifica",+ "Encrypt the document inside this file": "Cifra il documento dentro questo file",+ "Enter the password to open it.": "Inserisci la password per aprirlo.",+ "Every page, as one .md file": "Tutte le pagine, in un unico file .md",+ "Export as Markdown": "Esporta come Markdown",+ "Export as Markdown…": "Esporta come Markdown…",+ "File": "File",+ "Filter blocks…": "Filtra i blocchi…",+ "Find": "Trova",+ "Find in this space…": "Trova in questo spazio…",+ "Find or create a page…": "Trova o crea una pagina…",+ "Image added ({size})": "Immagine aggiunta ({size})",+ "Image added, resized to fit ({from} → {to})": "Immagine aggiunta, ridimensionata ({from} → {to})",+ "Include archived pages": "Includi le pagine archiviate",+ "Insert": "Inserisci",+ "Insert a block — text, headings, lists, code, images": "Inserisci un blocco — testo, titoli, elenchi, codice, immagini",+ "Interface language": "Lingua dell’interfaccia",+ "Language": "Lingua",+ "Language follows whoever opens the file. It is never written into the document.": "La lingua segue chi apre il file. Non viene mai scritta nel documento.",+ "Link to page": "Collega a una pagina",+ "Linked from": "Collegata da",+ "Links to it become dead": "I collegamenti a questa pagina si interrompono",+ "New page (⌘⌥N)": "Nuova pagina (⌘⌥N)",+ "New page inside": "Nuova pagina interna",+ "Next (⏎)": "Successivo (⏎)",+ "No block matches": "Nessun blocco corrisponde",+ "No pages yet": "Ancora nessuna pagina",+ "Nothing found": "Nessun risultato",+ "Off by default — they were archived for a reason": "Disattivo per impostazione predefinita — sono state archiviate per un motivo",+ "Other ways to save": "Altri modi per salvare",+ "Out of the sidebar, still searchable and linkable": "Fuori dalla barra laterale, ma sempre ricercabile e collegabile",+ "Page options": "Opzioni della pagina",+ "Pages": "Pagine",+ "Pages — show or hide the page list": "Pagine — mostra o nascondi l’elenco delle pagine",+ "Password": "Password",+ "Password removed. Save to write the space unencrypted.": "Password rimossa. Salva per scrivere lo spazio non cifrato.",+ "Password set. Save to write the space encrypted.": "Password impostata. Salva per scrivere lo spazio cifrato.",+ "Password…": "Password…",+ "Previous (⇧⏎)": "Precedente (⇧⏎)",+ "Print": "Stampa",+ "Print / PDF…": "Stampa / PDF…",+ "Print or save as PDF": "Stampa o salva come PDF",+ "Print or save as PDF (⌘P)": "Stampa o salva come PDF (⌘P)",+ "Print…": "Stampa…",+ "Reading image…": "Lettura dell’immagine…",+ "Reading view — press Esc or the eye to edit": "Vista di lettura — premi Esc o l’occhio per modificare",+ "Reading view — the pages without the editing tools": "Vista di lettura — le pagine senza gli strumenti di modifica",+ "Redo (⇧⌘Z)": "Ripeti (⇧⌘Z)",+ "Remove password…": "Rimuovi password…",+ "Remove the password? The next save writes the document in the clear.": "Rimuovere la password? Il prossimo salvataggio scriverà il documento in chiaro.",+ "Rename": "Rinomina",+ "Replace all": "Sostituisci tutto",+ "Replace with": "Sostituisci con",+ "Replace with…": "Sostituisci con…",+ "Replace {n} occurrence(s) across the whole space?": "Sostituire {n} occorrenze in tutto lo spazio?",+ "Replaced": "Sostituite",+ "Resized": "Ridimensionata",+ "Restore": "Ripristina",+ "Restore to the page list": "Ripristina nell’elenco delle pagine",+ "Save": "Salva",+ "Save (⌘S)": "Salva (⌘S)",+ "Save a copy…": "Salva una copia…",+ "Save an untouched copy…": "Salva una copia senza toccare l’originale…",+ "Saved": "Salvato",+ "Saved a new copy": "Salvata una nuova copia",+ "Saving…": "Salvataggio…",+ "Search": "Cerca",+ "Search all pages (⌘K)": "Cerca in tutte le pagine (⌘K)",+ "Search all pages…": "Cerca in tutte le pagine…",+ "Search this space": "Cerca in questo spazio",+ "Set a password…": "Imposta una password…",+ "Space name": "Nome dello spazio",+ "Take it elsewhere": "Portalo altrove",+ "That file could not be read as an image": "Impossibile leggere quel file come immagine",+ "The document block is not shaped like a space — {detail}.": "Il blocco del documento non ha la forma di uno spazio — {detail}.",+ "The document block is not valid JSON — {detail}.": "Il blocco del documento non è JSON valido — {detail}.",+ "The whole space": "L’intero spazio",+ "The whole space, or just this page": "L’intero spazio, o solo questa pagina",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare sul posto.",+ "This file": "Questo file",+ "This file could not be opened": "Impossibile aprire questo file",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "Questo file dichiara regole che questa versione non conosce. È aperto in sola lettura per non perdere nulla.",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "Questo file è stato scritto da una versione più recente di bento/spaces. È aperto in sola lettura per non perdere nulla.",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "Questa immagine è di {size} e viaggia dentro il file, rendendolo altrettanto più grande per chiunque la riceva. Incorporarla comunque?",+ "This image was resized to keep the file small. Click to replace it with the original.": "Questa immagine è stata ridimensionata per mantenere il file leggero. Clicca per sostituirla con l’originale.",+ "This is not a bento/spaces document — {detail}.": "Questo non è un documento bento/spaces — {detail}.",+ "This page only": "Solo questa pagina",+ "This space has no pages.": "Questo spazio non ha pagine.",+ "This space is encrypted. Saves stay encrypted.": "Questo spazio è cifrato. I salvataggi restano cifrati.",+ "This space is locked": "Questo spazio è bloccato",+ "Type / for blocks, [[ to link a page": "Digita / per i blocchi, [[ per collegare una pagina",+ "Undo (⌘Z)": "Annulla (⌘Z)",+ "Unlock": "Sblocca",+ "Unlocked, but the document inside could not be read.": "Sbloccato, ma non è stato possibile leggere il documento all’interno.",+ "Unsaved changes from a previous session were found.": "Sono state trovate modifiche non salvate di una sessione precedente.",+ "Untitled": "Senza titolo",+ "Update this file": "Aggiorna questo file",+ "Updates": "Aggiornamenti",+ "Version {v} is available.": "È disponibile la versione {v}.",+ "Width in the text column": "Larghezza nella colonna di testo",+ "Wrong password — try again": "Password errata — riprova",+ "You have the newest version ({v}).": "Hai la versione più recente ({v}).",+ "archived": "archiviata",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · pagine: {pages}, blocchi: {blocks}. Il documento, l’editor e la ricerca sono tutti in questo unico file.",+ "none": "nessuno",+ "{i} of {n}": "{i} di {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "Riparati {n} id duplicati o mancanti, così link e pagine funzionano.",+ "{n} found": "risultati: {n}",+ "{n} link(s) to it will stop working.": "{n} collegamenti a questa pagina smetteranno di funzionare.",+ "{n} page(s) inside it move up a level.": "{n} pagine contenute salgono di un livello.",+ "{n} pages, in sidebar order, with a contents page": "{n} pagine, nell’ordine della barra laterale, con una pagina indice",+ "Image from {host}": "Immagine da {host}",+ "Not loaded — opening it would tell that site you opened this space.": "Non caricata: caricarla direbbe a quel sito che hai aperto questo spazio.",+ "Load this image": "Carica questa immagine",+}diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsnew file mode 100644index 00000000..0eb31a4e--- /dev/null+++ b/spaces/src/i18n/ja.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Japanese — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = スペース · page = ページ · block = ブロック++import type { Catalog } from '../i18n'++export const ja: Catalog = {+ "A list of every page, in order": "すべてのページを順番に並べた一覧",+ "A page cannot contain itself": "ページを自分自身に入れることはできません",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "パスワードはファイル内のドキュメントを暗号化します。復元手段はありません — 忘れたらこのスペースは失われます。",+ "A second file — the original is left alone": "2 つ目のファイル — 元のファイルはそのまま",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "スペースは行き止まりになりません。ドキュメント全体はこのファイル内のプレーンな JSON で、どのページも Markdown に書き出せます。",+ "A space needs at least one page": "スペースには少なくとも 1 ページが必要です",+ "About this space": "このスペースについて",+ "Add a block below": "下にブロックを追加",+ "Archive": "アーカイブ",+ "Archived ({n})": "アーカイブ済み({n})",+ "Block options": "ブロックのオプション",+ "Breadcrumb": "パンくずリスト",+ "Change this page's icon": "このページのアイコンを変更",+ "Check for updates": "更新を確認",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "確認は手動で、検証も行われます。ダウンロードには署名があり、何かを書き換える前にこのファイル内の鍵で署名を照合します。",+ "Checking…": "確認中…",+ "Choose a password. There is no way to recover it.": "パスワードを決めてください。復元する方法はありません。",+ "Close": "閉じる",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "折りたたんだトグルも印刷では必ず開いた状態になります。「PDF として保存」はブラウザの印刷ダイアログにあります。",+ "Contents": "目次",+ "Contents page": "目次ページ",+ "Copy document JSON": "ドキュメント JSON をコピー",+ "Copy saved": "コピーを保存しました",+ "Copy the document JSON": "ドキュメント JSON をコピー",+ "Could not reach the update channel.": "更新チャンネルに接続できませんでした。",+ "Could not verify an update, so nothing was changed.": "更新を検証できなかったため、何も変更していません。",+ "Create “{name}”": "「{name}」を作成",+ "Delete “{name}”?": "「{name}」を削除しますか?",+ "Delete…": "削除…",+ "Discard": "破棄",+ "Downloaded. Open the new file — this one is unchanged.": "ダウンロードしました。新しいファイルを開いてください — このファイルは変更されていません。",+ "Drag to move, click for block options": "ドラッグで移動、クリックでブロックのオプション",+ "Edited": "未保存",+ "Editing": "編集中",+ "Encrypt the document inside this file": "このファイル内のドキュメントを暗号化",+ "Enter the password to open it.": "開くにはパスワードを入力してください。",+ "Every page, as one .md file": "すべてのページを 1 つの .md ファイルに",+ "Export as Markdown": "Markdown で書き出す",+ "Export as Markdown…": "Markdown で書き出す…",+ "File": "ファイル",+ "Filter blocks…": "ブロックを絞り込む…",+ "Find": "検索",+ "Find in this space…": "このスペース内を検索…",+ "Find or create a page…": "ページを検索または作成…",+ "Image added ({size})": "画像を追加しました({size})",+ "Image added, resized to fit ({from} → {to})": "画像を追加し、収まるように縮小しました({from} → {to})",+ "Include archived pages": "アーカイブしたページを含める",+ "Insert": "挿入",+ "Insert a block — text, headings, lists, code, images": "ブロックを挿入 — テキスト、見出し、リスト、コード、画像",+ "Interface language": "表示言語",+ "Language": "言語",+ "Language follows whoever opens the file. It is never written into the document.": "言語はファイルを開いた人に従います。ドキュメントには書き込まれません。",+ "Link to page": "ページにリンク",+ "Linked from": "リンク元",+ "Links to it become dead": "このページへのリンクが切れます",+ "New page (⌘⌥N)": "新規ページ (⌘⌥N)",+ "New page inside": "この中に新規ページ",+ "Next (⏎)": "次へ (⏎)",+ "No block matches": "一致するブロックがありません",+ "No pages yet": "ページがまだありません",+ "Nothing found": "見つかりませんでした",+ "Off by default — they were archived for a reason": "既定ではオフ — アーカイブしたのには理由があります",+ "Other ways to save": "その他の保存方法",+ "Out of the sidebar, still searchable and linkable": "サイドバーから外れますが、検索もリンクもできます",+ "Page options": "ページのオプション",+ "Pages": "ページ",+ "Pages — show or hide the page list": "ページ — ページ一覧の表示/非表示",+ "Password": "パスワード",+ "Password removed. Save to write the space unencrypted.": "パスワードを削除しました。保存すると、このスペースは暗号化なしで書き込まれます。",+ "Password set. Save to write the space encrypted.": "パスワードを設定しました。保存すると、このスペースは暗号化して書き込まれます。",+ "Password…": "パスワード…",+ "Previous (⇧⏎)": "前へ (⇧⏎)",+ "Print": "印刷",+ "Print / PDF…": "印刷 / PDF…",+ "Print or save as PDF": "印刷または PDF として保存",+ "Print or save as PDF (⌘P)": "印刷または PDF として保存 (⌘P)",+ "Print…": "印刷…",+ "Reading image…": "画像を読み込み中…",+ "Reading view — press Esc or the eye to edit": "閲覧ビュー — Esc か目のアイコンで編集に戻ります",+ "Reading view — the pages without the editing tools": "閲覧ビュー — 編集ツールなしでページを表示",+ "Redo (⇧⌘Z)": "やり直す (⇧⌘Z)",+ "Remove password…": "パスワードを削除…",+ "Remove the password? The next save writes the document in the clear.": "パスワードを削除しますか?次回の保存でドキュメントは平文で書き込まれます。",+ "Rename": "名前を変更",+ "Replace all": "すべて置換",+ "Replace with": "置換後の文字列",+ "Replace with…": "置換後の文字列…",+ "Replace {n} occurrence(s) across the whole space?": "スペース全体で {n} 件を置換しますか?",+ "Replaced": "置換しました",+ "Resized": "縮小済み",+ "Restore": "復元",+ "Restore to the page list": "ページ一覧に戻す",+ "Save": "保存",+ "Save (⌘S)": "保存 (⌘S)",+ "Save a copy…": "コピーを保存…",+ "Save an untouched copy…": "元のままのコピーを保存…",+ "Saved": "保存しました",+ "Saved a new copy": "新しいコピーを保存しました",+ "Saving…": "保存中…",+ "Search": "検索",+ "Search all pages (⌘K)": "全ページを検索 (⌘K)",+ "Search all pages…": "全ページを検索…",+ "Search this space": "このスペースを検索",+ "Set a password…": "パスワードを設定…",+ "Space name": "スペース名",+ "Take it elsewhere": "外に持ち出す",+ "That file could not be read as an image": "そのファイルは画像として読み込めませんでした",+ "The document block is not shaped like a space — {detail}.": "ドキュメントブロックがスペースの形をしていません — {detail}。",+ "The document block is not valid JSON — {detail}.": "ドキュメントブロックが正しい JSON ではありません — {detail}。",+ "The whole space": "スペース全体",+ "The whole space, or just this page": "スペース全体、またはこのページだけ",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "このブラウザはファイルに書き戻せないため、保存のたびに新しいコピーができます。パソコンの Chrome と Edge なら直接上書き保存できます。",+ "This file": "このファイル",+ "This file could not be opened": "このファイルを開けませんでした",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "このファイルには、このビルドが知らないルールが宣言されています。何も失わないよう読み取り専用で開いています。",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "このファイルは新しいバージョンの bento/spaces で書かれています。何も失わないよう読み取り専用で開いています。",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "この画像は {size} あり、ファイルの中に一緒に入ります。その分、送る相手全員にとってファイルが大きくなります。それでも埋め込みますか?",+ "This image was resized to keep the file small. Click to replace it with the original.": "ファイルを小さく保つため、この画像は縮小されました。クリックすると元の画像に差し替えます。",+ "This is not a bento/spaces document — {detail}.": "これは bento/spaces のドキュメントではありません — {detail}。",+ "This page only": "このページだけ",+ "This space has no pages.": "このスペースにはページがありません。",+ "This space is encrypted. Saves stay encrypted.": "このスペースは暗号化されています。保存しても暗号化されたままです。",+ "This space is locked": "このスペースはロックされています",+ "Type / for blocks, [[ to link a page": "/ でブロック、[[ でページにリンク",+ "Undo (⌘Z)": "元に戻す (⌘Z)",+ "Unlock": "ロック解除",+ "Unlocked, but the document inside could not be read.": "ロックは解除しましたが、中のドキュメントを読み取れませんでした。",+ "Unsaved changes from a previous session were found.": "前回のセッションの未保存の変更が見つかりました。",+ "Untitled": "無題",+ "Update this file": "このファイルを更新",+ "Updates": "更新",+ "Version {v} is available.": "バージョン {v} が利用可能です。",+ "Width in the text column": "本文カラム内の幅",+ "Wrong password — try again": "パスワードが違います — もう一度お試しください",+ "You have the newest version ({v}).": "最新バージョンです ({v})。",+ "archived": "アーカイブ済み",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} ページ、{blocks} ブロック。ドキュメントもエディターも検索も、すべてこの 1 つのファイルの中にあります。",+ "none": "なし",+ "{i} of {n}": "{i} / {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "重複または欠落した id を {n} 件修復し、リンクとページが解決するようにしました。",+ "{n} found": "{n} 件",+ "{n} link(s) to it will stop working.": "このページへのリンク {n} 件が機能しなくなります。",+ "{n} page(s) inside it move up a level.": "中にある {n} ページが 1 つ上の階層に移動します。",+ "{n} pages, in sidebar order, with a contents page": "{n} ページをサイドバー順に、目次ページ付きで",+ "Image from {host}": "{host} の画像",+ "Not loaded — opening it would tell that site you opened this space.": "未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。",+ "Load this image": "この画像を読み込む",+}diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsnew file mode 100644index 00000000..b532c08a--- /dev/null+++ b/spaces/src/i18n/packed.ts@@ -0,0 +1,162 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GENERATED by scripts/build-spaces-i18n.mjs — do not edit. Run it after+// changing a catalog or adding a t() string; CI fails if this is out of date.+//+// One row per English key: the key is stored ONCE and the translations follow+// by column. `0` means "no translation in that locale" and falls back to the+// English key, which is also the source text — so a missing entry degrades to+// a readable string rather than a blank.++export const PACKED_LOCALES = ["ja","zh-Hans","zh-Hant","es","fr","de","it","pt"] as const++export const PACKED: Record<string, ReadonlyArray<string | 0>> = {+ "A list of every page, in order": ["すべてのページを順番に並べた一覧","按顺序列出的所有页面","依順序列出每一個頁面","Una lista de todas las páginas, en orden","La liste de toutes les pages, dans l’ordre","Eine Liste aller Seiten, der Reihe nach","Un elenco di tutte le pagine, in ordine","Uma lista de todas as páginas, por ordem"],+ "A page cannot contain itself": ["ページを自分自身に入れることはできません","页面不能包含自身","頁面不能包含自己","Una página no puede contenerse a sí misma","Une page ne peut pas se contenir elle-même","Eine Seite kann sich nicht selbst enthalten","Una pagina non può contenere sé stessa","Uma página não pode conter-se a si própria"],+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": ["パスワードはファイル内のドキュメントを暗号化します。復元手段はありません — 忘れたらこのスペースは失われます。","密码会加密文件内的文档。没有任何找回方式 — 密码丢了,空间就没了。","密碼會加密檔案內的文件。沒有任何復原方式 — 密碼一旦遺失,這個空間就沒了。","Una contraseña cifra el documento dentro del archivo. No hay forma de recuperarla — si la pierdes, el espacio desaparece.","Un mot de passe chiffre le document à l’intérieur du fichier. Il n’y a aucune récupération — perdez-le et l’espace est perdu.","Ein Passwort verschlüsselt das Dokument in der Datei. Es gibt keine Wiederherstellung — verlierst du es, ist der Space weg.","Una password cifra il documento dentro il file. Non c’è modo di recuperarla — se la perdi, lo spazio è perso.","Uma palavra-passe encripta o documento dentro do ficheiro. Não há recuperação — se a perder, o espaço desaparece."],+ "A second file — the original is left alone": ["2 つ目のファイル — 元のファイルはそのまま","另存一个新文件 — 原文件不动","第二個檔案 — 原檔案不受影響","Un segundo archivo — el original queda intacto","Un second fichier — l’original reste intact","Eine zweite Datei — das Original bleibt unberührt","Un secondo file — l’originale resta intatto","Um segundo ficheiro — o original fica intacto"],+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": ["スペースは行き止まりになりません。ドキュメント全体はこのファイル内のプレーンな JSON で、どのページも Markdown に書き出せます。","空间绝不是死胡同:整个文档就是这个文件里的纯 JSON,每个页面都能导出为 Markdown。","空間永遠不會是死路:整份文件就是此檔案中的純 JSON,每個頁面也都能匯出成 Markdown。","Un espacio nunca es un callejón sin salida: todo el documento es JSON plano dentro de este archivo, y cada página se exporta como Markdown.","Un espace n’est jamais une impasse : tout le document est du JSON brut dans ce fichier, et chaque page s’exporte en Markdown.","Ein Space ist nie eine Sackgasse: Das ganze Dokument ist reines JSON in dieser Datei, und jede Seite lässt sich als Markdown exportieren.","Uno spazio non è mai un vicolo cieco: l’intero documento è JSON puro dentro questo file, e ogni pagina si esporta in Markdown.","Um espaço nunca é um beco sem saída: todo o documento é JSON simples dentro deste ficheiro e todas as páginas se exportam para Markdown."],+ "A space needs at least one page": ["スペースには少なくとも 1 ページが必要です","空间至少要有一个页面","空間至少要有一個頁面","Un espacio necesita al menos una página","Un espace doit contenir au moins une page","Ein Space braucht mindestens eine Seite","Uno spazio deve avere almeno una pagina","Um espaço precisa de pelo menos uma página"],+ "About this space": ["このスペースについて","关于此空间","關於此空間","Acerca de este espacio","À propos de cet espace","Über diesen Space","Informazioni su questo spazio","Sobre este espaço"],+ "Add a block below": ["下にブロックを追加","在下方添加块","在下方新增區塊","Añadir un bloque debajo","Ajouter un bloc en dessous","Block darunter hinzufügen","Aggiungi un blocco sotto","Adicionar um bloco abaixo"],+ "Archive": ["アーカイブ","归档","封存","Archivar","Archiver","Archivieren","Archivia","Arquivar"],+ "Archived ({n})": ["アーカイブ済み({n})","已归档 ({n})","已封存 ({n})","Archivadas ({n})","Archivées ({n})","Archiviert ({n})","Archiviate ({n})","Arquivadas ({n})"],+ "Block options": ["ブロックのオプション","块选项","區塊選項","Opciones del bloque","Options du bloc","Block-Optionen","Opzioni del blocco","Opções do bloco"],+ "Breadcrumb": ["パンくずリスト","面包屑导航","階層路徑","Ruta de navegación","Fil d’Ariane","Pfadnavigation","Percorso di navigazione","Trilho de navegação"],+ "Change this page's icon": ["このページのアイコンを変更","更改此页面的图标","變更此頁面的圖示","Cambiar el icono de esta página","Changer l’icône de cette page","Symbol dieser Seite ändern","Cambia l’icona di questa pagina","Mudar o ícone desta página"],+ "Check for updates": ["更新を確認","检查更新","檢查更新","Buscar actualizaciones","Rechercher des mises à jour","Nach Updates suchen","Cerca aggiornamenti","Verificar atualizações"],+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": ["確認は手動で、検証も行われます。ダウンロードには署名があり、何かを書き換える前にこのファイル内の鍵で署名を照合します。","检查更新完全由你手动发起,并且经过验证:下载内容带有签名,改写任何内容之前,都会先用此文件内的密钥校验签名。","檢查是手動且經過驗證的:下載的檔案帶有簽章,在改寫任何內容之前,都會用此檔案內的金鑰驗證該簽章。","La comprobación es manual y verificada: la descarga va firmada y su firma se contrasta con una clave que está dentro de este archivo antes de reescribir nada.","La vérification est manuelle et contrôlée : le téléchargement est signé, et sa signature est vérifiée avec une clé contenue dans ce fichier avant toute réécriture.","Die Prüfung ist manuell und verifiziert: Der Download ist signiert, und seine Signatur wird gegen einen Schlüssel in dieser Datei geprüft, bevor irgendetwas überschrieben wird.","La verifica è manuale e controllata: il download è firmato e la sua firma viene confrontata con una chiave contenuta in questo file prima che qualcosa venga riscritto.","A verificação é manual e comprovada: a transferência é assinada e a sua assinatura é validada com uma chave dentro deste ficheiro antes de qualquer coisa ser reescrita."],+ "Checking…": ["確認中…","检查中…","檢查中…","Comprobando…","Vérification…","Prüfe…","Verifica in corso…","A verificar…"],+ "Choose a password. There is no way to recover it.": ["パスワードを決めてください。復元する方法はありません。","设置一个密码。它无法找回。","請設定密碼。沒有任何方法可以找回它。","Elige una contraseña. No hay forma de recuperarla.","Choisissez un mot de passe. Il est impossible de le récupérer.","Wähle ein Passwort. Es lässt sich nicht wiederherstellen.","Scegli una password. Non c’è modo di recuperarla.","Escolha uma palavra-passe. Não há forma de a recuperar."],+ "Close": ["閉じる","关闭","關閉","Cerrar","Fermer","Schließen","Chiudi","Fechar"],+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": ["折りたたんだトグルも印刷では必ず開いた状態になります。「PDF として保存」はブラウザの印刷ダイアログにあります。","折叠起来的折叠块打印时一律展开。浏览器的打印对话框里有“存为 PDF”选项。","收合的摺疊區塊列印時一律展開。「另存為 PDF」的選項在瀏覽器的列印對話方塊中。","Los desplegables plegados siempre se imprimen abiertos. El diálogo de impresión de tu navegador tiene la opción «Guardar como PDF».","Les bascules repliées s’impriment toujours dépliées. La boîte d’impression de votre navigateur propose « Enregistrer au format PDF ».","Zugeklappte Toggle-Blöcke werden immer offen gedruckt. Im Druckdialog deines Browsers gibt es die Option „Als PDF speichern“.","I blocchi comprimibili chiusi vengono sempre stampati aperti. La finestra di stampa del browser offre l’opzione «Salva come PDF».","Os blocos recolhidos são sempre impressos abertos. A janela de impressão do navegador tem a opção \"Guardar como PDF\"."],+ "Contents": ["目次","目录","目錄","Índice","Sommaire","Inhalt","Indice","Índice"],+ "Contents page": ["目次ページ","目录页","目錄頁","Página de índice","Page de sommaire","Inhaltsverzeichnis","Pagina indice","Página de índice"],+ "Copy document JSON": ["ドキュメント JSON をコピー","复制文档 JSON","複製文件 JSON","Copiar JSON del documento","Copier le JSON du document","Dokument-JSON kopieren","Copia JSON del documento","Copiar JSON do documento"],+ "Copy saved": ["コピーを保存しました","副本已保存","已儲存副本","Copia guardada","Copie enregistrée","Kopie gespeichert","Copia salvata","Cópia guardada"],+ "Copy the document JSON": ["ドキュメント JSON をコピー","复制此文档的 JSON","複製文件 JSON","Copiar el JSON del documento","Copier le JSON du document","Dokument-JSON kopieren","Copia il JSON del documento","Copiar o JSON do documento"],+ "Could not reach the update channel.": ["更新チャンネルに接続できませんでした。","无法连接更新通道。","無法連線到更新來源。","No se pudo contactar con el canal de actualizaciones.","Impossible de joindre le canal de mise à jour.","Der Update-Kanal war nicht erreichbar.","Impossibile raggiungere il canale degli aggiornamenti.","Não foi possível contactar o canal de atualizações."],+ "Could not verify an update, so nothing was changed.": ["更新を検証できなかったため、何も変更していません。","无法验证更新,因此未做任何改动。","無法驗證更新,因此未變更任何內容。","No se pudo verificar la actualización, así que no se cambió nada.","Impossible de vérifier une mise à jour, rien n’a été modifié.","Ein Update ließ sich nicht verifizieren, daher wurde nichts geändert.","Impossibile verificare l’aggiornamento, quindi non è stato modificato nulla.","Não foi possível verificar a atualização, por isso nada foi alterado."],+ "Create “{name}”": ["「{name}」を作成","创建“{name}”","建立「{name}」","Crear «{name}»","Créer « {name} »","„{name}“ erstellen","Crea «{name}»","Criar “{name}”"],+ "Delete “{name}”?": ["「{name}」を削除しますか?","要删除“{name}”吗?","要刪除「{name}」嗎?","¿Eliminar «{name}»?","Supprimer « {name} » ?","„{name}“ löschen?","Eliminare «{name}»?","Eliminar “{name}”?"],+ "Delete…": ["削除…","删除…","刪除…","Eliminar…","Supprimer…","Löschen…","Elimina…","Eliminar…"],+ "Discard": ["破棄","放弃","捨棄","Descartar","Ignorer","Verwerfen","Ignora","Descartar"],+ "Downloaded. Open the new file — this one is unchanged.": ["ダウンロードしました。新しいファイルを開いてください — このファイルは変更されていません。","已下载。请打开新文件 — 当前文件未改动。","已下載。請開啟新檔案 — 目前這個檔案未被更動。","Descargado. Abre el archivo nuevo — este no ha cambiado.","Téléchargé. Ouvrez le nouveau fichier — celui-ci est inchangé.","Heruntergeladen. Öffne die neue Datei — diese hier bleibt unverändert.","Scaricato. Apri il nuovo file — questo resta invariato.","Transferido. Abra o novo ficheiro — este fica inalterado."],+ "Drag to move, click for block options": ["ドラッグで移動、クリックでブロックのオプション","拖动可移动,点击打开块选项","拖曳可移動,點按開啟區塊選項","Arrastra para mover, haz clic para las opciones del bloque","Glissez pour déplacer, cliquez pour les options du bloc","Ziehen zum Verschieben, klicken für Block-Optionen","Trascina per spostare, clicca per le opzioni del blocco","Arraste para mover, clique para as opções do bloco"],+ "Edited": ["未保存","已编辑","已編輯","Editado","Modifié","Bearbeitet","Modificato","Editado"],+ "Editing": ["編集中","编辑中","編輯中","Edición","Édition","Bearbeiten","In modifica","Edição"],+ "Encrypt the document inside this file": ["このファイル内のドキュメントを暗号化","加密此文件内的文档","加密此檔案內的文件","Cifrar el documento dentro de este archivo","Chiffrer le document à l’intérieur de ce fichier","Das Dokument in dieser Datei verschlüsseln","Cifra il documento dentro questo file","Encriptar o documento dentro deste ficheiro"],+ "Enter the password to open it.": ["開くにはパスワードを入力してください。","输入密码以打开。","請輸入密碼以開啟。","Introduce la contraseña para abrirlo.","Saisissez le mot de passe pour l’ouvrir.","Gib das Passwort ein, um ihn zu öffnen.","Inserisci la password per aprirlo.","Introduza a palavra-passe para o abrir."],+ "Every page, as one .md file": ["すべてのページを 1 つの .md ファイルに","所有页面合并为一个 .md 文件","所有頁面合併為一個 .md 檔","Todas las páginas, en un solo archivo .md","Toutes les pages, en un seul fichier .md","Jede Seite, in einer .md-Datei","Tutte le pagine, in un unico file .md","Todas as páginas num único ficheiro .md"],+ "Export as Markdown": ["Markdown で書き出す","导出为 Markdown","匯出為 Markdown","Exportar como Markdown","Exporter en Markdown","Als Markdown exportieren","Esporta come Markdown","Exportar como Markdown"],+ "Export as Markdown…": ["Markdown で書き出す…","导出为 Markdown…","匯出為 Markdown…","Exportar como Markdown…","Exporter en Markdown…","Als Markdown exportieren…","Esporta come Markdown…","Exportar como Markdown…"],+ "File": ["ファイル","文件","檔案","Archivo","Fichier","Datei","File","Ficheiro"],+ "Filter blocks…": ["ブロックを絞り込む…","筛选块…","篩選區塊…","Filtrar bloques…","Filtrer les blocs…","Blöcke filtern…","Filtra i blocchi…","Filtrar blocos…"],+ "Find": ["検索","查找","尋找","Buscar","Rechercher","Suchen","Trova","Localizar"],+ "Find in this space…": ["このスペース内を検索…","在此空间中查找…","在此空間尋找…","Buscar en este espacio…","Rechercher dans cet espace…","In diesem Space suchen…","Trova in questo spazio…","Localizar neste espaço…"],+ "Find or create a page…": ["ページを検索または作成…","查找或新建页面…","尋找或建立頁面…","Buscar o crear una página…","Trouver ou créer une page…","Seite finden oder erstellen…","Trova o crea una pagina…","Encontrar ou criar uma página…"],+ "Image added ({size})": ["画像を追加しました({size})","已添加图片 ({size})","已新增圖片 ({size})","Imagen añadida ({size})","Image ajoutée ({size})","Bild hinzugefügt ({size})","Immagine aggiunta ({size})","Imagem adicionada ({size})"],+ "Image added, resized to fit ({from} → {to})": ["画像を追加し、収まるように縮小しました({from} → {to})","已添加图片,已缩放以适配 ({from} → {to})","已新增圖片,已縮小尺寸 ({from} → {to})","Imagen añadida, redimensionada para que quepa ({from} → {to})","Image ajoutée, redimensionnée ({from} → {to})","Bild hinzugefügt, passend verkleinert ({from} → {to})","Immagine aggiunta, ridimensionata ({from} → {to})","Imagem adicionada, redimensionada para caber ({from} → {to})"],+ "Image from {host}": ["{host} の画像","来自 {host} 的图片","來自 {host} 的圖片","Imagen de {host}","Image provenant de {host}","Bild von {host}","Immagine da {host}","Imagem de {host}"],+ "Include archived pages": ["アーカイブしたページを含める","包含已归档页面","包含已封存的頁面","Incluir páginas archivadas","Inclure les pages archivées","Archivierte Seiten einbeziehen","Includi le pagine archiviate","Incluir páginas arquivadas"],+ "Insert": ["挿入","插入","插入","Insertar","Insérer","Einfügen","Inserisci","Inserir"],+ "Insert a block — text, headings, lists, code, images": ["ブロックを挿入 — テキスト、見出し、リスト、コード、画像","插入块 — 文本、标题、列表、代码、图片","插入區塊 — 文字、標題、清單、程式碼、圖片","Insertar un bloque — texto, encabezados, listas, código, imágenes","Insérer un bloc — texte, titres, listes, code, images","Block einfügen — Text, Überschriften, Listen, Code, Bilder","Inserisci un blocco — testo, titoli, elenchi, codice, immagini","Inserir um bloco — texto, títulos, listas, código, imagens"],+ "Interface language": ["表示言語","界面语言","介面語言","Idioma de la interfaz","Langue de l’interface","Sprache der Oberfläche","Lingua dell’interfaccia","Idioma da interface"],+ "Language": ["言語","语言","語言","Idioma","Langue","Sprache","Lingua","Idioma"],+ "Language follows whoever opens the file. It is never written into the document.": ["言語はファイルを開いた人に従います。ドキュメントには書き込まれません。","语言跟随打开文件的人,绝不会写入文档。","語言取決於開啟檔案的人,永遠不會寫入文件中。","El idioma sigue a quien abre el archivo. Nunca se escribe en el documento.","La langue suit la personne qui ouvre le fichier. Elle n’est jamais écrite dans le document.","Die Sprache richtet sich danach, wer die Datei öffnet. Sie wird nie ins Dokument geschrieben.","La lingua segue chi apre il file. Non viene mai scritta nel documento.","O idioma segue quem abre o ficheiro. Nunca é escrito no documento."],+ "Link to page": ["ページにリンク","链接到页面","連結到頁面","Enlazar a una página","Lier à une page","Seite verlinken","Collega a una pagina","Ligar a uma página"],+ "Linked from": ["リンク元","链接来源","連結來源","Enlazado desde","Liens entrants","Verlinkt von","Collegata da","Ligado a partir de"],+ "Links to it become dead": ["このページへのリンクが切れます","指向它的链接会失效","指向它的連結會失效","Los enlaces a ella dejan de funcionar","Les liens vers elle seront rompus","Links darauf laufen ins Leere","I collegamenti a questa pagina si interrompono","As ligações para ela ficam quebradas"],+ "Load this image": ["この画像を読み込む","加载此图片","載入此圖片","Cargar esta imagen","Charger cette image","Dieses Bild laden","Carica questa immagine","Carregar esta imagem"],+ "New page (⌘⌥N)": ["新規ページ (⌘⌥N)","新建页面 (⌘⌥N)","新增頁面 (⌘⌥N)","Nueva página (⌘⌥N)","Nouvelle page (⌘⌥N)","Neue Seite (⌘⌥N)","Nuova pagina (⌘⌥N)","Nova página (⌘⌥N)"],+ "New page inside": ["この中に新規ページ","在其中新建页面","在其中新增頁面","Nueva página dentro","Nouvelle page à l’intérieur","Neue Unterseite","Nuova pagina interna","Nova página dentro desta"],+ "Next (⏎)": ["次へ (⏎)","下一个 (⏎)","下一個 (⏎)","Siguiente (⏎)","Suivant (⏎)","Weiter (⏎)","Successivo (⏎)","Seguinte (⏎)"],+ "No block matches": ["一致するブロックがありません","没有匹配的块","沒有符合的區塊","Ningún bloque coincide","Aucun bloc correspondant","Kein Block passt","Nessun blocco corrisponde","Nenhum bloco corresponde"],+ "No pages yet": ["ページがまだありません","还没有页面","尚無頁面","Aún no hay páginas","Aucune page pour l’instant","Noch keine Seiten","Ancora nessuna pagina","Ainda sem páginas"],+ "Not loaded — opening it would tell that site you opened this space.": ["未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。","未加载 — 加载会让该网站知道你打开了这个空间。","未載入 — 載入會讓該網站知道你開啟了這個空間。","No cargada: al cargarla, ese sitio sabría que has abierto este espacio.","Non chargée : la charger indiquerait à ce site que vous avez ouvert cet espace.","Nicht geladen — beim Laden erfährt diese Website, dass du diesen Space geöffnet hast.","Non caricata: caricarla direbbe a quel sito che hai aperto questo spazio.","Não carregada — carregá-la diria a esse site que você abriu este espaço."],+ "Nothing found": ["見つかりませんでした","没有结果","找不到結果","Sin resultados","Aucun résultat","Nichts gefunden","Nessun risultato","Nada encontrado"],+ "Off by default — they were archived for a reason": ["既定ではオフ — アーカイブしたのには理由があります","默认关闭 — 当初归档总是有原因的","預設關閉 — 它們被封存是有原因的","Desactivado por defecto — por algo se archivaron","Désactivé par défaut — elles ont été archivées pour une raison","Standardmäßig aus — sie wurden aus einem Grund archiviert","Disattivo per impostazione predefinita — sono state archiviate per un motivo","Desativado por predefinição — foram arquivadas por alguma razão"],+ "Other ways to save": ["その他の保存方法","其他保存方式","其他儲存方式","Otras formas de guardar","Autres façons d’enregistrer","Weitere Speicheroptionen","Altri modi per salvare","Outras formas de guardar"],+ "Out of the sidebar, still searchable and linkable": ["サイドバーから外れますが、検索もリンクもできます","移出侧边栏,仍可搜索和链接","移出側邊欄,仍可搜尋與連結","Fuera de la barra lateral, pero aún se puede buscar y enlazar","Hors de la barre latérale, toujours dans la recherche et les liens","Weg aus der Seitenleiste, weiterhin auffindbar und verlinkbar","Fuori dalla barra laterale, ma sempre ricercabile e collegabile","Fora da barra lateral, mas continua pesquisável e ligável"],+ "Page options": ["ページのオプション","页面选项","頁面選項","Opciones de la página","Options de la page","Seiten-Optionen","Opzioni della pagina","Opções da página"],+ "Pages": ["ページ","页面","頁面","Páginas","Pages","Seiten","Pagine","Páginas"],+ "Pages — show or hide the page list": ["ページ — ページ一覧の表示/非表示","页面 — 显示或隐藏页面列表","頁面 — 顯示或隱藏頁面清單","Páginas — mostrar u ocultar la lista de páginas","Pages — afficher ou masquer la liste","Seiten — Seitenliste ein- oder ausblenden","Pagine — mostra o nascondi l’elenco delle pagine","Páginas — mostrar ou ocultar a lista de páginas"],+ "Password": ["パスワード","密码","密碼","Contraseña","Mot de passe","Passwort","Password","Palavra-passe"],+ "Password removed. Save to write the space unencrypted.": ["パスワードを削除しました。保存すると、このスペースは暗号化なしで書き込まれます。","已移除密码。保存后空间将以未加密方式写入。","已移除密碼。儲存後空間將以未加密方式寫入。","Contraseña eliminada. Guarda para escribir el espacio sin cifrar.","Mot de passe supprimé. Enregistrez pour écrire l’espace non chiffré.","Passwort entfernt. Speichere, um den Space unverschlüsselt zu schreiben.","Password rimossa. Salva per scrivere lo spazio non cifrato.","Palavra-passe removida. Guarde para escrever o espaço sem encriptação."],+ "Password set. Save to write the space encrypted.": ["パスワードを設定しました。保存すると、このスペースは暗号化して書き込まれます。","已设置密码。保存后空间将以加密方式写入。","已設定密碼。儲存後空間將以加密方式寫入。","Contraseña establecida. Guarda para escribir el espacio cifrado.","Mot de passe défini. Enregistrez pour écrire l’espace chiffré.","Passwort gesetzt. Speichere, um den Space verschlüsselt zu schreiben.","Password impostata. Salva per scrivere lo spazio cifrato.","Palavra-passe definida. Guarde para escrever o espaço encriptado."],+ "Password…": ["パスワード…","密码…","密碼…","Contraseña…","Mot de passe…","Passwort…","Password…","Palavra-passe…"],+ "Previous (⇧⏎)": ["前へ (⇧⏎)","上一个 (⇧⏎)","上一個 (⇧⏎)","Anterior (⇧⏎)","Précédent (⇧⏎)","Zurück (⇧⏎)","Precedente (⇧⏎)","Anterior (⇧⏎)"],+ "Print": ["印刷","打印","列印","Imprimir","Imprimer","Drucken","Stampa","Imprimir"],+ "Print / PDF…": ["印刷 / PDF…","打印 / PDF…","列印 / PDF…","Imprimir / PDF…","Imprimer / PDF…","Drucken / PDF…","Stampa / PDF…","Imprimir / PDF…"],+ "Print or save as PDF": ["印刷または PDF として保存","打印或存为 PDF","列印或另存為 PDF","Imprimir o guardar como PDF","Imprimer ou enregistrer en PDF","Drucken oder als PDF speichern","Stampa o salva come PDF","Imprimir ou guardar como PDF"],+ "Print or save as PDF (⌘P)": ["印刷または PDF として保存 (⌘P)","打印或存为 PDF (⌘P)","列印或另存為 PDF (⌘P)","Imprimir o guardar como PDF (⌘P)","Imprimer ou enregistrer en PDF (⌘P)","Drucken oder als PDF speichern (⌘P)","Stampa o salva come PDF (⌘P)","Imprimir ou guardar como PDF (⌘P)"],+ "Print…": ["印刷…","打印…","列印…","Imprimir…","Imprimer…","Drucken…","Stampa…","Imprimir…"],+ "Reading image…": ["画像を読み込み中…","正在读取图片…","正在讀取圖片…","Leyendo la imagen…","Lecture de l’image…","Lese Bild…","Lettura dell’immagine…","A ler a imagem…"],+ "Reading view — press Esc or the eye to edit": ["閲覧ビュー — Esc か目のアイコンで編集に戻ります","阅读视图 — 按 Esc 或点击眼睛图标即可编辑","閱讀檢視 — 按 Esc 或眼睛圖示即可編輯","Vista de lectura — pulsa Esc o el ojo para editar","Vue lecture — appuyez sur Esc ou sur l’œil pour modifier","Leseansicht — Esc oder das Auge zum Bearbeiten","Vista di lettura — premi Esc o l’occhio per modificare","Vista de leitura — prima Esc ou o olho para editar"],+ "Reading view — the pages without the editing tools": ["閲覧ビュー — 編集ツールなしでページを表示","阅读视图 — 只有页面,没有编辑工具","閱讀檢視 — 只有頁面,沒有編輯工具","Vista de lectura — las páginas sin las herramientas de edición","Vue lecture — les pages sans les outils d’édition","Leseansicht — die Seiten ohne Bearbeitungswerkzeuge","Vista di lettura — le pagine senza gli strumenti di modifica","Vista de leitura — as páginas sem as ferramentas de edição"],+ "Redo (⇧⌘Z)": ["やり直す (⇧⌘Z)","重做 (⇧⌘Z)","重做 (⇧⌘Z)","Rehacer (⇧⌘Z)","Rétablir (⇧⌘Z)","Wiederholen (⇧⌘Z)","Ripeti (⇧⌘Z)","Refazer (⇧⌘Z)"],+ "Remove password…": ["パスワードを削除…","移除密码…","移除密碼…","Quitar contraseña…","Supprimer le mot de passe…","Passwort entfernen…","Rimuovi password…","Remover palavra-passe…"],+ "Remove the password? The next save writes the document in the clear.": ["パスワードを削除しますか?次回の保存でドキュメントは平文で書き込まれます。","要移除密码吗?下次保存会以明文写入文档。","要移除密碼嗎?下次儲存會以明文寫入文件。","¿Quitar la contraseña? El próximo guardado escribe el documento sin cifrar.","Supprimer le mot de passe ? Le prochain enregistrement écrira le document en clair.","Das Passwort entfernen? Beim nächsten Speichern wird das Dokument im Klartext geschrieben.","Rimuovere la password? Il prossimo salvataggio scriverà il documento in chiaro.","Remover a palavra-passe? Da próxima vez que guardar, o documento é escrito sem encriptação."],+ "Rename": ["名前を変更","重命名","重新命名","Cambiar nombre","Renommer","Umbenennen","Rinomina","Mudar o nome"],+ "Replace all": ["すべて置換","全部替换","全部取代","Reemplazar todo","Tout remplacer","Alle ersetzen","Sostituisci tutto","Substituir tudo"],+ "Replace with": ["置換後の文字列","替换为","取代為","Reemplazar por","Remplacer par","Ersetzen durch","Sostituisci con","Substituir por"],+ "Replace with…": ["置換後の文字列…","替换为…","取代為…","Reemplazar por…","Remplacer par…","Ersetzen durch…","Sostituisci con…","Substituir por…"],+ "Replace {n} occurrence(s) across the whole space?": ["スペース全体で {n} 件を置換しますか?","要在整个空间中替换 {n} 处吗?","要取代整個空間中的 {n} 處嗎?","¿Reemplazar {n} coincidencia(s) en todo el espacio?","Remplacer {n} occurrence(s) dans tout l’espace ?","{n} Vorkommen im ganzen Space ersetzen?","Sostituire {n} occorrenze in tutto lo spazio?","Substituir {n} ocorrência(s) em todo o espaço?"],+ "Replaced": ["置換しました","已替换","已取代","Reemplazado","Remplacé","Ersetzt","Sostituite","Substituído"],+ "Resized": ["縮小済み","已缩放","已縮小","Redimensionada","Redimensionnée","Verkleinert","Ridimensionata","Redimensionada"],+ "Restore": ["復元","恢复","還原","Restaurar","Restaurer","Wiederherstellen","Ripristina","Restaurar"],+ "Restore to the page list": ["ページ一覧に戻す","恢复到页面列表","還原到頁面清單","Restaurar a la lista de páginas","Restaurer dans la liste des pages","Zurück in die Seitenliste","Ripristina nell’elenco delle pagine","Restaurar para a lista de páginas"],+ "Save": ["保存","保存","儲存","Guardar","Enregistrer","Speichern","Salva","Guardar"],+ "Save (⌘S)": ["保存 (⌘S)","保存 (⌘S)","儲存 (⌘S)","Guardar (⌘S)","Enregistrer (⌘S)","Speichern (⌘S)","Salva (⌘S)","Guardar (⌘S)"],+ "Save a copy…": ["コピーを保存…","保存副本…","儲存副本…","Guardar una copia…","Enregistrer une copie…","Kopie speichern…","Salva una copia…","Guardar uma cópia…"],+ "Save an untouched copy…": ["元のままのコピーを保存…","另存副本,原文件不动…","儲存原封不動的副本…","Guardar una copia intacta…","Enregistrer une copie sans toucher à l’original…","Unveränderte Kopie speichern…","Salva una copia senza toccare l’originale…","Guardar uma cópia intacta…"],+ "Saved": ["保存しました","已保存","已儲存","Guardado","Enregistré","Gespeichert","Salvato","Guardado"],+ "Saved a new copy": ["新しいコピーを保存しました","已保存新副本","已儲存新副本","Se guardó una copia nueva","Nouvelle copie enregistrée","Neue Kopie gespeichert","Salvata una nuova copia","Nova cópia guardada"],+ "Saving…": ["保存中…","保存中…","儲存中…","Guardando…","Enregistrement…","Speichere…","Salvataggio…","A guardar…"],+ "Search": ["検索","搜索","搜尋","Buscar","Rechercher","Suche","Cerca","Pesquisar"],+ "Search all pages (⌘K)": ["全ページを検索 (⌘K)","搜索所有页面 (⌘K)","搜尋所有頁面 (⌘K)","Buscar en todas las páginas (⌘K)","Rechercher dans toutes les pages (⌘K)","Alle Seiten durchsuchen (⌘K)","Cerca in tutte le pagine (⌘K)","Pesquisar em todas as páginas (⌘K)"],+ "Search all pages…": ["全ページを検索…","搜索所有页面…","搜尋所有頁面…","Buscar en todas las páginas…","Rechercher dans toutes les pages…","Alle Seiten durchsuchen…","Cerca in tutte le pagine…","Pesquisar em todas as páginas…"],+ "Search this space": ["このスペースを検索","搜索此空间","搜尋此空間","Buscar en este espacio","Rechercher dans cet espace","Diesen Space durchsuchen","Cerca in questo spazio","Pesquisar neste espaço"],+ "Set a password…": ["パスワードを設定…","设置密码…","設定密碼…","Establecer una contraseña…","Définir un mot de passe…","Passwort festlegen…","Imposta una password…","Definir uma palavra-passe…"],+ "Space name": ["スペース名","空间名称","空間名稱","Nombre del espacio","Nom de l’espace","Space-Name","Nome dello spazio","Nome do espaço"],+ "Take it elsewhere": ["外に持ち出す","把内容带走","把內容帶走","Llévatelo a otra parte","Emportez-le ailleurs","Woanders weitermachen","Portalo altrove","Levar para outro lado"],+ "That file could not be read as an image": ["そのファイルは画像として読み込めませんでした","无法将该文件作为图片读取","無法將該檔案讀取為圖片","No se pudo leer ese archivo como imagen","Ce fichier n’a pas pu être lu comme une image","Diese Datei konnte nicht als Bild gelesen werden","Impossibile leggere quel file come immagine","Não foi possível ler esse ficheiro como imagem"],+ "The document block is not shaped like a space — {detail}.": ["ドキュメントブロックがスペースの形をしていません — {detail}。","文档数据块的结构不像一个空间 — {detail}。","檔案中的文件資料結構不像一個空間 — {detail}。","El bloque del documento no tiene la forma de un espacio — {detail}.","Le bloc de document n’a pas la forme d’un espace — {detail}.","Der Dokumentblock ist nicht wie ein Space aufgebaut — {detail}.","Il blocco del documento non ha la forma di uno spazio — {detail}.","O bloco do documento não tem a forma de um espaço — {detail}."],+ "The document block is not valid JSON — {detail}.": ["ドキュメントブロックが正しい JSON ではありません — {detail}。","文档数据块不是有效的 JSON — {detail}。","檔案中的文件資料不是有效的 JSON — {detail}。","El bloque del documento no es JSON válido — {detail}.","Le bloc de document n’est pas du JSON valide — {detail}.","Der Dokumentblock ist kein gültiges JSON — {detail}.","Il blocco del documento non è JSON valido — {detail}.","O bloco do documento não é JSON válido — {detail}."],+ "The whole space": ["スペース全体","整个空间","整個空間","Todo el espacio","Tout l’espace","Der ganze Space","L’intero spazio","Todo o espaço"],+ "The whole space, or just this page": ["スペース全体、またはこのページだけ","整个空间,或仅这一页","整個空間,或僅此頁面","Todo el espacio, o solo esta página","Tout l’espace, ou seulement cette page","Der ganze Space oder nur diese Seite","L’intero spazio, o solo questa pagina","Todo o espaço, ou apenas esta página"],+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルに書き戻せないため、保存のたびに新しいコピーができます。パソコンの Chrome と Edge なら直接上書き保存できます。","此浏览器无法写回原文件,因此每次保存都会生成新副本。电脑上的 Chrome 和 Edge 可以就地保存。","此瀏覽器無法寫回檔案,因此每次儲存都會產生新的副本。電腦版的 Chrome 和 Edge 可以就地儲存。","Este navegador no puede reescribir el archivo, así que cada guardado crea una copia nueva. Chrome y Edge en un ordenador sí pueden guardar en el sitio.","Ce navigateur ne peut pas réécrire le fichier : chaque enregistrement crée donc une nouvelle copie. Chrome et Edge sur ordinateur enregistrent sur place.","Dieser Browser kann nicht in die Datei zurückschreiben, deshalb entsteht bei jedem Speichern eine neue Kopie. Chrome und Edge auf dem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare sul posto.","Este navegador não consegue escrever de volta no ficheiro, por isso cada vez que guarda cria uma nova cópia. O Chrome e o Edge num computador conseguem guardar no local."],+ "This file": ["このファイル","此文件","此檔案","Este archivo","Ce fichier","Diese Datei","Questo file","Este ficheiro"],+ "This file could not be opened": ["このファイルを開けませんでした","无法打开此文件","無法開啟此檔案","No se pudo abrir este archivo","Ce fichier n’a pas pu être ouvert","Diese Datei konnte nicht geöffnet werden","Impossibile aprire questo file","Não foi possível abrir este ficheiro"],+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": ["このファイルには、このビルドが知らないルールが宣言されています。何も失わないよう読み取り専用で開いています。","此文件声明了此版本不认识的规则。已以只读方式打开,以免丢失任何内容。","此檔案宣告了這個版本不認識的規則。已以唯讀方式開啟,以免遺失任何內容。","Este archivo declara reglas que esta versión no conoce. Está abierto en solo lectura para no perder nada.","Ce fichier déclare des règles que cette version ne connaît pas. Il est ouvert en lecture seule pour ne rien perdre.","Diese Datei nennt Regeln, die dieser Build nicht kennt. Sie ist schreibgeschützt geöffnet, damit nichts verloren geht.","Questo file dichiara regole che questa versione non conosce. È aperto in sola lettura per non perdere nulla.","Este ficheiro declara regras que esta versão não conhece. Está aberto apenas para leitura para que nada se perca."],+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": ["このファイルは新しいバージョンの bento/spaces で書かれています。何も失わないよう読み取り専用で開いています。","此文件由更新版本的 bento/spaces 写入。已以只读方式打开,以免丢失任何内容。","此檔案是由較新版本的 bento/spaces 寫入的。已以唯讀方式開啟,以免遺失任何內容。","Este archivo lo escribió una versión más reciente de bento/spaces. Está abierto en solo lectura para no perder nada.","Ce fichier a été écrit par une version plus récente de bento/spaces. Il est ouvert en lecture seule pour ne rien perdre.","Diese Datei wurde von einer neueren Version von bento/spaces geschrieben. Sie ist schreibgeschützt geöffnet, damit nichts verloren geht.","Questo file è stato scritto da una versione più recente di bento/spaces. È aperto in sola lettura per non perdere nulla.","Este ficheiro foi escrito por uma versão mais recente do bento/spaces. Está aberto apenas para leitura para que nada se perca."],+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": ["この画像は {size} あり、ファイルの中に一緒に入ります。その分、送る相手全員にとってファイルが大きくなります。それでも埋め込みますか?","这张图片有 {size},会嵌在文件内部,你发给谁,文件对谁就大出这么多。仍要嵌入吗?","這張圖片有 {size},而且會跟著檔案一起走,你傳給的每個人拿到的檔案都會大這麼多。仍要嵌入嗎?","Esta imagen pesa {size} y viaja dentro del archivo, que crecerá otro tanto para todos a quienes se lo envíes. ¿Incrustarla de todos modos?","Cette image fait {size} et voyage dans le fichier, ce qui l’alourdit d’autant pour toutes les personnes à qui vous l’envoyez. L’intégrer quand même ?","Dieses Bild ist {size} groß und reist in der Datei mit — die Datei wird für jeden, dem du sie schickst, entsprechend größer. Trotzdem einbetten?","Questa immagine è di {size} e viaggia dentro il file, rendendolo altrettanto più grande per chiunque la riceva. Incorporarla comunque?","Esta imagem tem {size} e viaja dentro do ficheiro, tornando-o maior para todas as pessoas a quem o enviar. Incorporar mesmo assim?"],+ "This image was resized to keep the file small. Click to replace it with the original.": ["ファイルを小さく保つため、この画像は縮小されました。クリックすると元の画像に差し替えます。","为了让文件保持小巧,这张图片已被缩放。点击可换回原图。","這張圖片已縮小尺寸以保持檔案小巧。點按可換回原始圖片。","Esta imagen se redimensionó para mantener el archivo pequeño. Haz clic para reemplazarla por la original.","Cette image a été redimensionnée pour garder le fichier léger. Cliquez pour la remplacer par l’originale.","Dieses Bild wurde verkleinert, damit die Datei klein bleibt. Klicken, um es durch das Original zu ersetzen.","Questa immagine è stata ridimensionata per mantenere il file leggero. Clicca per sostituirla con l’originale.","Esta imagem foi redimensionada para manter o ficheiro pequeno. Clique para a substituir pela original."],+ "This is not a bento/spaces document — {detail}.": ["これは bento/spaces のドキュメントではありません — {detail}。","这不是 bento/spaces 文档 — {detail}。","這不是 bento/spaces 文件 — {detail}。","Esto no es un documento de bento/spaces — {detail}.","Ce n’est pas un document bento/spaces — {detail}.","Dies ist kein bento/spaces-Dokument — {detail}.","Questo non è un documento bento/spaces — {detail}.","Isto não é um documento bento/spaces — {detail}."],+ "This page only": ["このページだけ","仅此页面","僅此頁面","Solo esta página","Cette page seulement","Nur diese Seite","Solo questa pagina","Apenas esta página"],+ "This space has no pages.": ["このスペースにはページがありません。","此空间没有页面。","此空間沒有任何頁面。","Este espacio no tiene páginas.","Cet espace n’a aucune page.","Dieser Space hat keine Seiten.","Questo spazio non ha pagine.","Este espaço não tem páginas."],+ "This space is encrypted. Saves stay encrypted.": ["このスペースは暗号化されています。保存しても暗号化されたままです。","此空间已加密。保存时仍保持加密。","此空間已加密。往後的儲存也會維持加密。","Este espacio está cifrado. Los guardados siguen cifrados.","Cet espace est chiffré. Les enregistrements restent chiffrés.","Dieser Space ist verschlüsselt. Speichern bleibt verschlüsselt.","Questo spazio è cifrato. I salvataggi restano cifrati.","Este espaço está encriptado. Continua encriptado sempre que guardar."],+ "This space is locked": ["このスペースはロックされています","此空间已锁定","此空間已鎖定","Este espacio está bloqueado","Cet espace est verrouillé","Dieser Space ist gesperrt","Questo spazio è bloccato","Este espaço está bloqueado"],+ "Type / for blocks, [[ to link a page": ["/ でブロック、[[ でページにリンク","输入 / 插入块,[[ 链接页面","輸入 / 插入區塊,輸入 [[ 連結頁面","Escribe / para bloques, [[ para enlazar una página","Tapez / pour les blocs, [[ pour lier une page","Tippe / für Blöcke, [[ für einen Seitenlink","Digita / per i blocchi, [[ per collegare una pagina","Escreva / para blocos, [[ para ligar uma página"],+ "Undo (⌘Z)": ["元に戻す (⌘Z)","撤销 (⌘Z)","還原 (⌘Z)","Deshacer (⌘Z)","Annuler (⌘Z)","Rückgängig (⌘Z)","Annulla (⌘Z)","Desfazer (⌘Z)"],+ "Unlock": ["ロック解除","解锁","解鎖","Desbloquear","Déverrouiller","Entsperren","Sblocca","Desbloquear"],+ "Unlocked, but the document inside could not be read.": ["ロックは解除しましたが、中のドキュメントを読み取れませんでした。","已解锁,但无法读取其中的文档。","已解鎖,但無法讀取裡面的文件。","Desbloqueado, pero no se pudo leer el documento de dentro.","Déverrouillé, mais le document à l’intérieur n’a pas pu être lu.","Entsperrt, aber das Dokument darin konnte nicht gelesen werden.","Sbloccato, ma non è stato possibile leggere il documento all’interno.","Desbloqueado, mas não foi possível ler o documento lá dentro."],+ "Unsaved changes from a previous session were found.": ["前回のセッションの未保存の変更が見つかりました。","发现上一次会话未保存的更改。","發現上一次工作階段未儲存的變更。","Se encontraron cambios sin guardar de una sesión anterior.","Des modifications non enregistrées d’une session précédente ont été trouvées.","Nicht gespeicherte Änderungen aus einer früheren Sitzung gefunden.","Sono state trovate modifiche non salvate di una sessione precedente.","Foram encontradas alterações não guardadas de uma sessão anterior."],+ "Untitled": ["無題","未命名","未命名","Sin título","Sans titre","Ohne Titel","Senza titolo","Sem título"],+ "Update this file": ["このファイルを更新","更新此文件","更新此檔案","Actualizar este archivo","Mettre à jour ce fichier","Diese Datei aktualisieren","Aggiorna questo file","Atualizar este ficheiro"],+ "Updates": ["更新","更新","更新","Actualizaciones","Mises à jour","Updates","Aggiornamenti","Atualizações"],+ "Version {v} is available.": ["バージョン {v} が利用可能です。","版本 {v} 可用。","版本 {v} 可用。","Versión {v} disponible.","La version {v} est disponible.","Version {v} ist verfügbar.","È disponibile la versione {v}.","A versão {v} está disponível."],+ "Width in the text column": ["本文カラム内の幅","在正文栏中的宽度","相對於文字欄的寬度","Ancho en la columna de texto","Largeur dans la colonne de texte","Breite in der Textspalte","Larghezza nella colonna di testo","Largura na coluna de texto"],+ "Wrong password — try again": ["パスワードが違います — もう一度お試しください","密码错误 — 请重试","密碼錯誤 — 請重試","Contraseña incorrecta: inténtalo de nuevo","Mot de passe incorrect — réessayez","Falsches Passwort — bitte erneut versuchen","Password errata — riprova","Palavra-passe incorreta — tente novamente"],+ "You have the newest version ({v}).": ["最新バージョンです ({v})。","你已是最新版本 ({v})。","你已是最新版本 ({v})。","Tienes la versión más reciente ({v}).","Vous avez la dernière version ({v}).","Du hast die neueste Version ({v}).","Hai la versione più recente ({v}).","Já tem a versão mais recente ({v})."],+ "archived": ["アーカイブ済み","已归档","已封存","archivada","archivée","archiviert","archiviata","arquivada"],+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": ["bento/spaces {version} · {pages} ページ、{blocks} ブロック。ドキュメントもエディターも検索も、すべてこの 1 つのファイルの中にあります。","bento/spaces {version} · {pages} 个页面,{blocks} 个块。文档、编辑器和搜索全都在这一个文件里。","bento/spaces {version} · {pages} 個頁面、{blocks} 個區塊。文件、編輯器和搜尋全都在這一個檔案裡。","bento/spaces {version} · {pages} página(s), {blocks} bloque(s). El documento, el editor y la búsqueda están todos en este único archivo.","bento/spaces {version} · {pages} page(s), {blocks} bloc(s). Le document, l’éditeur et la recherche tiennent tous dans ce seul fichier.","bento/spaces {version} · {pages} Seiten, {blocks} Blöcke. Das Dokument, der Editor und die Suche stecken alle in dieser einen Datei.","bento/spaces {version} · pagine: {pages}, blocchi: {blocks}. Il documento, l’editor e la ricerca sono tutti in questo unico file.","bento/spaces {version} · {pages} página(s), {blocks} bloco(s). O documento, o editor e a pesquisa estão todos neste único ficheiro."],+ "none": ["なし","无","無","ninguna","aucun","keine","nessuno","nenhuma"],+ "{i} of {n}": ["{i} / {n}","第 {i} 个,共 {n} 个","{i} / {n}","{i} de {n}","{i} sur {n}","{i} von {n}","{i} di {n}","{i} de {n}"],+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": ["重複または欠落した id を {n} 件修復し、リンクとページが解決するようにしました。","已修复 {n} 个重复或缺失的 id,链接和页面现在都能正常解析。","已修復 {n} 個重複或遺失的 id,讓連結與頁面能正確對應。","Se repararon {n} id(s) duplicados o ausentes para que los enlaces y las páginas funcionen.","{n} id(s) en double ou manquant(s) ont été réparés pour que les liens et les pages se résolvent.","{n} doppelte oder fehlende IDs wurden repariert, damit Links und Seiten wieder gefunden werden.","Riparati {n} id duplicati o mancanti, così link e pagine funzionano.","Foram reparados {n} id(s) duplicados ou em falta para que as ligações e as páginas funcionem."],+ "{n} found": ["{n} 件","找到 {n} 个","找到 {n} 個","{n} encontrada(s)","{n} résultat(s)","{n} Treffer","risultati: {n}","{n} encontradas"],+ "{n} link(s) to it will stop working.": ["このページへのリンク {n} 件が機能しなくなります。","指向它的 {n} 个链接会失效。","指向它的 {n} 個連結將會失效。","{n} enlace(s) a ella dejarán de funcionar.","{n} lien(s) vers elle ne fonctionneront plus.","{n} Links darauf funktionieren nicht mehr.","{n} collegamenti a questa pagina smetteranno di funzionare.","{n} ligação(ões) para ela deixam de funcionar."],+ "{n} page(s) inside it move up a level.": ["中にある {n} ページが 1 つ上の階層に移動します。","其中的 {n} 个页面会上移一级。","其中的 {n} 個頁面會往上移一層。","{n} página(s) que contiene suben un nivel.","{n} page(s) qu’elle contient remonteront d’un niveau.","{n} Unterseiten rücken eine Ebene nach oben.","{n} pagine contenute salgono di un livello.","{n} página(s) dentro dela sobem um nível."],+ "{n} pages, in sidebar order, with a contents page": ["{n} ページをサイドバー順に、目次ページ付きで","{n} 个页面,按侧边栏顺序,并附一个目录页","{n} 個頁面,依側邊欄順序排列,並附目錄頁","{n} páginas, en el orden de la barra lateral, con una página de índice","{n} pages, dans l’ordre de la barre latérale, avec une page de sommaire","{n} Seiten, in der Reihenfolge der Seitenleiste, mit Inhaltsverzeichnis","{n} pagine, nell’ordine della barra laterale, con una pagina indice","{n} páginas, pela ordem da barra lateral, com uma página de índice"],+}diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsnew file mode 100644index 00000000..955d5ccf--- /dev/null+++ b/spaces/src/i18n/pt.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Portuguese — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = espaço · page = página · block = bloco++import type { Catalog } from '../i18n'++export const pt: Catalog = {+ "A list of every page, in order": "Uma lista de todas as páginas, por ordem",+ "A page cannot contain itself": "Uma página não pode conter-se a si própria",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Uma palavra-passe encripta o documento dentro do ficheiro. Não há recuperação — se a perder, o espaço desaparece.",+ "A second file — the original is left alone": "Um segundo ficheiro — o original fica intacto",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "Um espaço nunca é um beco sem saída: todo o documento é JSON simples dentro deste ficheiro e todas as páginas se exportam para Markdown.",+ "A space needs at least one page": "Um espaço precisa de pelo menos uma página",+ "About this space": "Sobre este espaço",+ "Add a block below": "Adicionar um bloco abaixo",+ "Archive": "Arquivar",+ "Archived ({n})": "Arquivadas ({n})",+ "Block options": "Opções do bloco",+ "Breadcrumb": "Trilho de navegação",+ "Change this page's icon": "Mudar o ícone desta página",+ "Check for updates": "Verificar atualizações",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "A verificação é manual e comprovada: a transferência é assinada e a sua assinatura é validada com uma chave dentro deste ficheiro antes de qualquer coisa ser reescrita.",+ "Checking…": "A verificar…",+ "Choose a password. There is no way to recover it.": "Escolha uma palavra-passe. Não há forma de a recuperar.",+ "Close": "Fechar",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Os blocos recolhidos são sempre impressos abertos. A janela de impressão do navegador tem a opção \"Guardar como PDF\".",+ "Contents": "Índice",+ "Contents page": "Página de índice",+ "Copy document JSON": "Copiar JSON do documento",+ "Copy saved": "Cópia guardada",+ "Copy the document JSON": "Copiar o JSON do documento",+ "Could not reach the update channel.": "Não foi possível contactar o canal de atualizações.",+ "Could not verify an update, so nothing was changed.": "Não foi possível verificar a atualização, por isso nada foi alterado.",+ "Create “{name}”": "Criar “{name}”",+ "Delete “{name}”?": "Eliminar “{name}”?",+ "Delete…": "Eliminar…",+ "Discard": "Descartar",+ "Downloaded. Open the new file — this one is unchanged.": "Transferido. Abra o novo ficheiro — este fica inalterado.",+ "Drag to move, click for block options": "Arraste para mover, clique para as opções do bloco",+ "Edited": "Editado",+ "Editing": "Edição",+ "Encrypt the document inside this file": "Encriptar o documento dentro deste ficheiro",+ "Enter the password to open it.": "Introduza a palavra-passe para o abrir.",+ "Every page, as one .md file": "Todas as páginas num único ficheiro .md",+ "Export as Markdown": "Exportar como Markdown",+ "Export as Markdown…": "Exportar como Markdown…",+ "File": "Ficheiro",+ "Filter blocks…": "Filtrar blocos…",+ "Find": "Localizar",+ "Find in this space…": "Localizar neste espaço…",+ "Find or create a page…": "Encontrar ou criar uma página…",+ "Image added ({size})": "Imagem adicionada ({size})",+ "Image added, resized to fit ({from} → {to})": "Imagem adicionada, redimensionada para caber ({from} → {to})",+ "Include archived pages": "Incluir páginas arquivadas",+ "Insert": "Inserir",+ "Insert a block — text, headings, lists, code, images": "Inserir um bloco — texto, títulos, listas, código, imagens",+ "Interface language": "Idioma da interface",+ "Language": "Idioma",+ "Language follows whoever opens the file. It is never written into the document.": "O idioma segue quem abre o ficheiro. Nunca é escrito no documento.",+ "Link to page": "Ligar a uma página",+ "Linked from": "Ligado a partir de",+ "Links to it become dead": "As ligações para ela ficam quebradas",+ "New page (⌘⌥N)": "Nova página (⌘⌥N)",+ "New page inside": "Nova página dentro desta",+ "Next (⏎)": "Seguinte (⏎)",+ "No block matches": "Nenhum bloco corresponde",+ "No pages yet": "Ainda sem páginas",+ "Nothing found": "Nada encontrado",+ "Off by default — they were archived for a reason": "Desativado por predefinição — foram arquivadas por alguma razão",+ "Other ways to save": "Outras formas de guardar",+ "Out of the sidebar, still searchable and linkable": "Fora da barra lateral, mas continua pesquisável e ligável",+ "Page options": "Opções da página",+ "Pages": "Páginas",+ "Pages — show or hide the page list": "Páginas — mostrar ou ocultar a lista de páginas",+ "Password": "Palavra-passe",+ "Password removed. Save to write the space unencrypted.": "Palavra-passe removida. Guarde para escrever o espaço sem encriptação.",+ "Password set. Save to write the space encrypted.": "Palavra-passe definida. Guarde para escrever o espaço encriptado.",+ "Password…": "Palavra-passe…",+ "Previous (⇧⏎)": "Anterior (⇧⏎)",+ "Print": "Imprimir",+ "Print / PDF…": "Imprimir / PDF…",+ "Print or save as PDF": "Imprimir ou guardar como PDF",+ "Print or save as PDF (⌘P)": "Imprimir ou guardar como PDF (⌘P)",+ "Print…": "Imprimir…",+ "Reading image…": "A ler a imagem…",+ "Reading view — press Esc or the eye to edit": "Vista de leitura — prima Esc ou o olho para editar",+ "Reading view — the pages without the editing tools": "Vista de leitura — as páginas sem as ferramentas de edição",+ "Redo (⇧⌘Z)": "Refazer (⇧⌘Z)",+ "Remove password…": "Remover palavra-passe…",+ "Remove the password? The next save writes the document in the clear.": "Remover a palavra-passe? Da próxima vez que guardar, o documento é escrito sem encriptação.",+ "Rename": "Mudar o nome",+ "Replace all": "Substituir tudo",+ "Replace with": "Substituir por",+ "Replace with…": "Substituir por…",+ "Replace {n} occurrence(s) across the whole space?": "Substituir {n} ocorrência(s) em todo o espaço?",+ "Replaced": "Substituído",+ "Resized": "Redimensionada",+ "Restore": "Restaurar",+ "Restore to the page list": "Restaurar para a lista de páginas",+ "Save": "Guardar",+ "Save (⌘S)": "Guardar (⌘S)",+ "Save a copy…": "Guardar uma cópia…",+ "Save an untouched copy…": "Guardar uma cópia intacta…",+ "Saved": "Guardado",+ "Saved a new copy": "Nova cópia guardada",+ "Saving…": "A guardar…",+ "Search": "Pesquisar",+ "Search all pages (⌘K)": "Pesquisar em todas as páginas (⌘K)",+ "Search all pages…": "Pesquisar em todas as páginas…",+ "Search this space": "Pesquisar neste espaço",+ "Set a password…": "Definir uma palavra-passe…",+ "Space name": "Nome do espaço",+ "Take it elsewhere": "Levar para outro lado",+ "That file could not be read as an image": "Não foi possível ler esse ficheiro como imagem",+ "The document block is not shaped like a space — {detail}.": "O bloco do documento não tem a forma de um espaço — {detail}.",+ "The document block is not valid JSON — {detail}.": "O bloco do documento não é JSON válido — {detail}.",+ "The whole space": "Todo o espaço",+ "The whole space, or just this page": "Todo o espaço, ou apenas esta página",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "Este navegador não consegue escrever de volta no ficheiro, por isso cada vez que guarda cria uma nova cópia. O Chrome e o Edge num computador conseguem guardar no local.",+ "This file": "Este ficheiro",+ "This file could not be opened": "Não foi possível abrir este ficheiro",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "Este ficheiro declara regras que esta versão não conhece. Está aberto apenas para leitura para que nada se perca.",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "Este ficheiro foi escrito por uma versão mais recente do bento/spaces. Está aberto apenas para leitura para que nada se perca.",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "Esta imagem tem {size} e viaja dentro do ficheiro, tornando-o maior para todas as pessoas a quem o enviar. Incorporar mesmo assim?",+ "This image was resized to keep the file small. Click to replace it with the original.": "Esta imagem foi redimensionada para manter o ficheiro pequeno. Clique para a substituir pela original.",+ "This is not a bento/spaces document — {detail}.": "Isto não é um documento bento/spaces — {detail}.",+ "This page only": "Apenas esta página",+ "This space has no pages.": "Este espaço não tem páginas.",+ "This space is encrypted. Saves stay encrypted.": "Este espaço está encriptado. Continua encriptado sempre que guardar.",+ "This space is locked": "Este espaço está bloqueado",+ "Type / for blocks, [[ to link a page": "Escreva / para blocos, [[ para ligar uma página",+ "Undo (⌘Z)": "Desfazer (⌘Z)",+ "Unlock": "Desbloquear",+ "Unlocked, but the document inside could not be read.": "Desbloqueado, mas não foi possível ler o documento lá dentro.",+ "Unsaved changes from a previous session were found.": "Foram encontradas alterações não guardadas de uma sessão anterior.",+ "Untitled": "Sem título",+ "Update this file": "Atualizar este ficheiro",+ "Updates": "Atualizações",+ "Version {v} is available.": "A versão {v} está disponível.",+ "Width in the text column": "Largura na coluna de texto",+ "Wrong password — try again": "Palavra-passe incorreta — tente novamente",+ "You have the newest version ({v}).": "Já tem a versão mais recente ({v}).",+ "archived": "arquivada",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} página(s), {blocks} bloco(s). O documento, o editor e a pesquisa estão todos neste único ficheiro.",+ "none": "nenhuma",+ "{i} of {n}": "{i} de {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "Foram reparados {n} id(s) duplicados ou em falta para que as ligações e as páginas funcionem.",+ "{n} found": "{n} encontradas",+ "{n} link(s) to it will stop working.": "{n} ligação(ões) para ela deixam de funcionar.",+ "{n} page(s) inside it move up a level.": "{n} página(s) dentro dela sobem um nível.",+ "{n} pages, in sidebar order, with a contents page": "{n} páginas, pela ordem da barra lateral, com uma página de índice",+ "Image from {host}": "Imagem de {host}",+ "Not loaded — opening it would tell that site you opened this space.": "Não carregada — carregá-la diria a esse site que você abriu este espaço.",+ "Load this image": "Carregar esta imagem",+}diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsnew file mode 100644index 00000000..157efc41--- /dev/null+++ b/spaces/src/i18n/zh-Hans.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Simplified Chinese — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = 空间 · page = 页面 · block = 块++import type { Catalog } from '../i18n'++export const zh_Hans: Catalog = {+ "A list of every page, in order": "按顺序列出的所有页面",+ "A page cannot contain itself": "页面不能包含自身",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "密码会加密文件内的文档。没有任何找回方式 — 密码丢了,空间就没了。",+ "A second file — the original is left alone": "另存一个新文件 — 原文件不动",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "空间绝不是死胡同:整个文档就是这个文件里的纯 JSON,每个页面都能导出为 Markdown。",+ "A space needs at least one page": "空间至少要有一个页面",+ "About this space": "关于此空间",+ "Add a block below": "在下方添加块",+ "Archive": "归档",+ "Archived ({n})": "已归档 ({n})",+ "Block options": "块选项",+ "Breadcrumb": "面包屑导航",+ "Change this page's icon": "更改此页面的图标",+ "Check for updates": "检查更新",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "检查更新完全由你手动发起,并且经过验证:下载内容带有签名,改写任何内容之前,都会先用此文件内的密钥校验签名。",+ "Checking…": "检查中…",+ "Choose a password. There is no way to recover it.": "设置一个密码。它无法找回。",+ "Close": "关闭",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "折叠起来的折叠块打印时一律展开。浏览器的打印对话框里有“存为 PDF”选项。",+ "Contents": "目录",+ "Contents page": "目录页",+ "Copy document JSON": "复制文档 JSON",+ "Copy saved": "副本已保存",+ "Copy the document JSON": "复制此文档的 JSON",+ "Could not reach the update channel.": "无法连接更新通道。",+ "Could not verify an update, so nothing was changed.": "无法验证更新,因此未做任何改动。",+ "Create “{name}”": "创建“{name}”",+ "Delete “{name}”?": "要删除“{name}”吗?",+ "Delete…": "删除…",+ "Discard": "放弃",+ "Downloaded. Open the new file — this one is unchanged.": "已下载。请打开新文件 — 当前文件未改动。",+ "Drag to move, click for block options": "拖动可移动,点击打开块选项",+ "Edited": "已编辑",+ "Editing": "编辑中",+ "Encrypt the document inside this file": "加密此文件内的文档",+ "Enter the password to open it.": "输入密码以打开。",+ "Every page, as one .md file": "所有页面合并为一个 .md 文件",+ "Export as Markdown": "导出为 Markdown",+ "Export as Markdown…": "导出为 Markdown…",+ "File": "文件",+ "Filter blocks…": "筛选块…",+ "Find": "查找",+ "Find in this space…": "在此空间中查找…",+ "Find or create a page…": "查找或新建页面…",+ "Image added ({size})": "已添加图片 ({size})",+ "Image added, resized to fit ({from} → {to})": "已添加图片,已缩放以适配 ({from} → {to})",+ "Include archived pages": "包含已归档页面",+ "Insert": "插入",+ "Insert a block — text, headings, lists, code, images": "插入块 — 文本、标题、列表、代码、图片",+ "Interface language": "界面语言",+ "Language": "语言",+ "Language follows whoever opens the file. It is never written into the document.": "语言跟随打开文件的人,绝不会写入文档。",+ "Link to page": "链接到页面",+ "Linked from": "链接来源",+ "Links to it become dead": "指向它的链接会失效",+ "New page (⌘⌥N)": "新建页面 (⌘⌥N)",+ "New page inside": "在其中新建页面",+ "Next (⏎)": "下一个 (⏎)",+ "No block matches": "没有匹配的块",+ "No pages yet": "还没有页面",+ "Nothing found": "没有结果",+ "Off by default — they were archived for a reason": "默认关闭 — 当初归档总是有原因的",+ "Other ways to save": "其他保存方式",+ "Out of the sidebar, still searchable and linkable": "移出侧边栏,仍可搜索和链接",+ "Page options": "页面选项",+ "Pages": "页面",+ "Pages — show or hide the page list": "页面 — 显示或隐藏页面列表",+ "Password": "密码",+ "Password removed. Save to write the space unencrypted.": "已移除密码。保存后空间将以未加密方式写入。",+ "Password set. Save to write the space encrypted.": "已设置密码。保存后空间将以加密方式写入。",+ "Password…": "密码…",+ "Previous (⇧⏎)": "上一个 (⇧⏎)",+ "Print": "打印",+ "Print / PDF…": "打印 / PDF…",+ "Print or save as PDF": "打印或存为 PDF",+ "Print or save as PDF (⌘P)": "打印或存为 PDF (⌘P)",+ "Print…": "打印…",+ "Reading image…": "正在读取图片…",+ "Reading view — press Esc or the eye to edit": "阅读视图 — 按 Esc 或点击眼睛图标即可编辑",+ "Reading view — the pages without the editing tools": "阅读视图 — 只有页面,没有编辑工具",+ "Redo (⇧⌘Z)": "重做 (⇧⌘Z)",+ "Remove password…": "移除密码…",+ "Remove the password? The next save writes the document in the clear.": "要移除密码吗?下次保存会以明文写入文档。",+ "Rename": "重命名",+ "Replace all": "全部替换",+ "Replace with": "替换为",+ "Replace with…": "替换为…",+ "Replace {n} occurrence(s) across the whole space?": "要在整个空间中替换 {n} 处吗?",+ "Replaced": "已替换",+ "Resized": "已缩放",+ "Restore": "恢复",+ "Restore to the page list": "恢复到页面列表",+ "Save": "保存",+ "Save (⌘S)": "保存 (⌘S)",+ "Save a copy…": "保存副本…",+ "Save an untouched copy…": "另存副本,原文件不动…",+ "Saved": "已保存",+ "Saved a new copy": "已保存新副本",+ "Saving…": "保存中…",+ "Search": "搜索",+ "Search all pages (⌘K)": "搜索所有页面 (⌘K)",+ "Search all pages…": "搜索所有页面…",+ "Search this space": "搜索此空间",+ "Set a password…": "设置密码…",+ "Space name": "空间名称",+ "Take it elsewhere": "把内容带走",+ "That file could not be read as an image": "无法将该文件作为图片读取",+ "The document block is not shaped like a space — {detail}.": "文档数据块的结构不像一个空间 — {detail}。",+ "The document block is not valid JSON — {detail}.": "文档数据块不是有效的 JSON — {detail}。",+ "The whole space": "整个空间",+ "The whole space, or just this page": "整个空间,或仅这一页",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "此浏览器无法写回原文件,因此每次保存都会生成新副本。电脑上的 Chrome 和 Edge 可以就地保存。",+ "This file": "此文件",+ "This file could not be opened": "无法打开此文件",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "此文件声明了此版本不认识的规则。已以只读方式打开,以免丢失任何内容。",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "此文件由更新版本的 bento/spaces 写入。已以只读方式打开,以免丢失任何内容。",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "这张图片有 {size},会嵌在文件内部,你发给谁,文件对谁就大出这么多。仍要嵌入吗?",+ "This image was resized to keep the file small. Click to replace it with the original.": "为了让文件保持小巧,这张图片已被缩放。点击可换回原图。",+ "This is not a bento/spaces document — {detail}.": "这不是 bento/spaces 文档 — {detail}。",+ "This page only": "仅此页面",+ "This space has no pages.": "此空间没有页面。",+ "This space is encrypted. Saves stay encrypted.": "此空间已加密。保存时仍保持加密。",+ "This space is locked": "此空间已锁定",+ "Type / for blocks, [[ to link a page": "输入 / 插入块,[[ 链接页面",+ "Undo (⌘Z)": "撤销 (⌘Z)",+ "Unlock": "解锁",+ "Unlocked, but the document inside could not be read.": "已解锁,但无法读取其中的文档。",+ "Unsaved changes from a previous session were found.": "发现上一次会话未保存的更改。",+ "Untitled": "未命名",+ "Update this file": "更新此文件",+ "Updates": "更新",+ "Version {v} is available.": "版本 {v} 可用。",+ "Width in the text column": "在正文栏中的宽度",+ "Wrong password — try again": "密码错误 — 请重试",+ "You have the newest version ({v}).": "你已是最新版本 ({v})。",+ "archived": "已归档",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} 个页面,{blocks} 个块。文档、编辑器和搜索全都在这一个文件里。",+ "none": "无",+ "{i} of {n}": "第 {i} 个,共 {n} 个",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "已修复 {n} 个重复或缺失的 id,链接和页面现在都能正常解析。",+ "{n} found": "找到 {n} 个",+ "{n} link(s) to it will stop working.": "指向它的 {n} 个链接会失效。",+ "{n} page(s) inside it move up a level.": "其中的 {n} 个页面会上移一级。",+ "{n} pages, in sidebar order, with a contents page": "{n} 个页面,按侧边栏顺序,并附一个目录页",+ "Image from {host}": "来自 {host} 的图片",+ "Not loaded — opening it would tell that site you opened this space.": "未加载 — 加载会让该网站知道你打开了这个空间。",+ "Load this image": "加载此图片",+}diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsnew file mode 100644index 00000000..be693a54--- /dev/null+++ b/spaces/src/i18n/zh-Hant.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Traditional Chinese — machine-drafted, native review welcome.+//+// The English string is the KEY: it must match the source byte-for-byte,+// including punctuation and curly quotes, or the lookup silently falls back+// to English forever. Placeholders in {braces} are substituted at runtime.+//+// Terms: space = 空間 · page = 頁面 · block = 區塊++import type { Catalog } from '../i18n'++export const zh_Hant: Catalog = {+ "A list of every page, in order": "依順序列出每一個頁面",+ "A page cannot contain itself": "頁面不能包含自己",+ "A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "密碼會加密檔案內的文件。沒有任何復原方式 — 密碼一旦遺失,這個空間就沒了。",+ "A second file — the original is left alone": "第二個檔案 — 原檔案不受影響",+ "A space is never a dead end: the whole document is plain JSON in this file, and every page exports as Markdown.": "空間永遠不會是死路:整份文件就是此檔案中的純 JSON,每個頁面也都能匯出成 Markdown。",+ "A space needs at least one page": "空間至少要有一個頁面",+ "About this space": "關於此空間",+ "Add a block below": "在下方新增區塊",+ "Archive": "封存",+ "Archived ({n})": "已封存 ({n})",+ "Block options": "區塊選項",+ "Breadcrumb": "階層路徑",+ "Change this page's icon": "變更此頁面的圖示",+ "Check for updates": "檢查更新",+ "Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "檢查是手動且經過驗證的:下載的檔案帶有簽章,在改寫任何內容之前,都會用此檔案內的金鑰驗證該簽章。",+ "Checking…": "檢查中…",+ "Choose a password. There is no way to recover it.": "請設定密碼。沒有任何方法可以找回它。",+ "Close": "關閉",+ "Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "收合的摺疊區塊列印時一律展開。「另存為 PDF」的選項在瀏覽器的列印對話方塊中。",+ "Contents": "目錄",+ "Contents page": "目錄頁",+ "Copy document JSON": "複製文件 JSON",+ "Copy saved": "已儲存副本",+ "Copy the document JSON": "複製文件 JSON",+ "Could not reach the update channel.": "無法連線到更新來源。",+ "Could not verify an update, so nothing was changed.": "無法驗證更新,因此未變更任何內容。",+ "Create “{name}”": "建立「{name}」",+ "Delete “{name}”?": "要刪除「{name}」嗎?",+ "Delete…": "刪除…",+ "Discard": "捨棄",+ "Downloaded. Open the new file — this one is unchanged.": "已下載。請開啟新檔案 — 目前這個檔案未被更動。",+ "Drag to move, click for block options": "拖曳可移動,點按開啟區塊選項",+ "Edited": "已編輯",+ "Editing": "編輯中",+ "Encrypt the document inside this file": "加密此檔案內的文件",+ "Enter the password to open it.": "請輸入密碼以開啟。",+ "Every page, as one .md file": "所有頁面合併為一個 .md 檔",+ "Export as Markdown": "匯出為 Markdown",+ "Export as Markdown…": "匯出為 Markdown…",+ "File": "檔案",+ "Filter blocks…": "篩選區塊…",+ "Find": "尋找",+ "Find in this space…": "在此空間尋找…",+ "Find or create a page…": "尋找或建立頁面…",+ "Image added ({size})": "已新增圖片 ({size})",+ "Image added, resized to fit ({from} → {to})": "已新增圖片,已縮小尺寸 ({from} → {to})",+ "Include archived pages": "包含已封存的頁面",+ "Insert": "插入",+ "Insert a block — text, headings, lists, code, images": "插入區塊 — 文字、標題、清單、程式碼、圖片",+ "Interface language": "介面語言",+ "Language": "語言",+ "Language follows whoever opens the file. It is never written into the document.": "語言取決於開啟檔案的人,永遠不會寫入文件中。",+ "Link to page": "連結到頁面",+ "Linked from": "連結來源",+ "Links to it become dead": "指向它的連結會失效",+ "New page (⌘⌥N)": "新增頁面 (⌘⌥N)",+ "New page inside": "在其中新增頁面",+ "Next (⏎)": "下一個 (⏎)",+ "No block matches": "沒有符合的區塊",+ "No pages yet": "尚無頁面",+ "Nothing found": "找不到結果",+ "Off by default — they were archived for a reason": "預設關閉 — 它們被封存是有原因的",+ "Other ways to save": "其他儲存方式",+ "Out of the sidebar, still searchable and linkable": "移出側邊欄,仍可搜尋與連結",+ "Page options": "頁面選項",+ "Pages": "頁面",+ "Pages — show or hide the page list": "頁面 — 顯示或隱藏頁面清單",+ "Password": "密碼",+ "Password removed. Save to write the space unencrypted.": "已移除密碼。儲存後空間將以未加密方式寫入。",+ "Password set. Save to write the space encrypted.": "已設定密碼。儲存後空間將以加密方式寫入。",+ "Password…": "密碼…",+ "Previous (⇧⏎)": "上一個 (⇧⏎)",+ "Print": "列印",+ "Print / PDF…": "列印 / PDF…",+ "Print or save as PDF": "列印或另存為 PDF",+ "Print or save as PDF (⌘P)": "列印或另存為 PDF (⌘P)",+ "Print…": "列印…",+ "Reading image…": "正在讀取圖片…",+ "Reading view — press Esc or the eye to edit": "閱讀檢視 — 按 Esc 或眼睛圖示即可編輯",+ "Reading view — the pages without the editing tools": "閱讀檢視 — 只有頁面,沒有編輯工具",+ "Redo (⇧⌘Z)": "重做 (⇧⌘Z)",+ "Remove password…": "移除密碼…",+ "Remove the password? The next save writes the document in the clear.": "要移除密碼嗎?下次儲存會以明文寫入文件。",+ "Rename": "重新命名",+ "Replace all": "全部取代",+ "Replace with": "取代為",+ "Replace with…": "取代為…",+ "Replace {n} occurrence(s) across the whole space?": "要取代整個空間中的 {n} 處嗎?",+ "Replaced": "已取代",+ "Resized": "已縮小",+ "Restore": "還原",+ "Restore to the page list": "還原到頁面清單",+ "Save": "儲存",+ "Save (⌘S)": "儲存 (⌘S)",+ "Save a copy…": "儲存副本…",+ "Save an untouched copy…": "儲存原封不動的副本…",+ "Saved": "已儲存",+ "Saved a new copy": "已儲存新副本",+ "Saving…": "儲存中…",+ "Search": "搜尋",+ "Search all pages (⌘K)": "搜尋所有頁面 (⌘K)",+ "Search all pages…": "搜尋所有頁面…",+ "Search this space": "搜尋此空間",+ "Set a password…": "設定密碼…",+ "Space name": "空間名稱",+ "Take it elsewhere": "把內容帶走",+ "That file could not be read as an image": "無法將該檔案讀取為圖片",+ "The document block is not shaped like a space — {detail}.": "檔案中的文件資料結構不像一個空間 — {detail}。",+ "The document block is not valid JSON — {detail}.": "檔案中的文件資料不是有效的 JSON — {detail}。",+ "The whole space": "整個空間",+ "The whole space, or just this page": "整個空間,或僅此頁面",+ "This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": "此瀏覽器無法寫回檔案,因此每次儲存都會產生新的副本。電腦版的 Chrome 和 Edge 可以就地儲存。",+ "This file": "此檔案",+ "This file could not be opened": "無法開啟此檔案",+ "This file declares rules this build does not know. It is open read-only so nothing is lost.": "此檔案宣告了這個版本不認識的規則。已以唯讀方式開啟,以免遺失任何內容。",+ "This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.": "此檔案是由較新版本的 bento/spaces 寫入的。已以唯讀方式開啟,以免遺失任何內容。",+ "This image is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": "這張圖片有 {size},而且會跟著檔案一起走,你傳給的每個人拿到的檔案都會大這麼多。仍要嵌入嗎?",+ "This image was resized to keep the file small. Click to replace it with the original.": "這張圖片已縮小尺寸以保持檔案小巧。點按可換回原始圖片。",+ "This is not a bento/spaces document — {detail}.": "這不是 bento/spaces 文件 — {detail}。",+ "This page only": "僅此頁面",+ "This space has no pages.": "此空間沒有任何頁面。",+ "This space is encrypted. Saves stay encrypted.": "此空間已加密。往後的儲存也會維持加密。",+ "This space is locked": "此空間已鎖定",+ "Type / for blocks, [[ to link a page": "輸入 / 插入區塊,輸入 [[ 連結頁面",+ "Undo (⌘Z)": "還原 (⌘Z)",+ "Unlock": "解鎖",+ "Unlocked, but the document inside could not be read.": "已解鎖,但無法讀取裡面的文件。",+ "Unsaved changes from a previous session were found.": "發現上一次工作階段未儲存的變更。",+ "Untitled": "未命名",+ "Update this file": "更新此檔案",+ "Updates": "更新",+ "Version {v} is available.": "版本 {v} 可用。",+ "Width in the text column": "相對於文字欄的寬度",+ "Wrong password — try again": "密碼錯誤 — 請重試",+ "You have the newest version ({v}).": "你已是最新版本 ({v})。",+ "archived": "已封存",+ "bento/spaces {version} · {pages} page(s), {blocks} block(s). The document, the editor and the search are all in this one file.": "bento/spaces {version} · {pages} 個頁面、{blocks} 個區塊。文件、編輯器和搜尋全都在這一個檔案裡。",+ "none": "無",+ "{i} of {n}": "{i} / {n}",+ "{n} duplicate or missing id(s) were repaired so links and pages resolve.": "已修復 {n} 個重複或遺失的 id,讓連結與頁面能正確對應。",+ "{n} found": "找到 {n} 個",+ "{n} link(s) to it will stop working.": "指向它的 {n} 個連結將會失效。",+ "{n} page(s) inside it move up a level.": "其中的 {n} 個頁面會往上移一層。",+ "{n} pages, in sidebar order, with a contents page": "{n} 個頁面,依側邊欄順序排列,並附目錄頁",+ "Image from {host}": "來自 {host} 的圖片",+ "Not loaded — opening it would tell that site you opened this space.": "未載入 — 載入會讓該網站知道你開啟了這個空間。",+ "Load this image": "載入此圖片",+}diff --git a/spaces/src/icons.ts b/spaces/src/icons.tsnew file mode 100644index 00000000..9a8a1338--- /dev/null+++ b/spaces/src/icons.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Minimal inline icon set (lucide-style, stroke = currentColor). No deps.+//+// Same construction and stroke weight as slides/src/icons.ts, deliberately:+// two apps in one suite that draw their chrome differently read as two+// products. Not imported from slides — PLATFORM §9 keeps the renderer and+// editor UX per-app, and a shared icon set would drag one app's additions into+// the other's bundle.++const svg = (body: string, viewBox = '0 0 24 24') =>+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`++export const ICONS = {+ search: svg('<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>'),+ save: svg('<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>'),+ info: svg('<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>'),+ menu: svg('<line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/>'),+ plus: svg('<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>'),+ grip: svg('<circle cx="9" cy="6" r="1.4" fill="currentColor" stroke="none"/><circle cx="15" cy="6" r="1.4" fill="currentColor" stroke="none"/><circle cx="9" cy="12" r="1.4" fill="currentColor" stroke="none"/><circle cx="15" cy="12" r="1.4" fill="currentColor" stroke="none"/><circle cx="9" cy="18" r="1.4" fill="currentColor" stroke="none"/><circle cx="15" cy="18" r="1.4" fill="currentColor" stroke="none"/>'),+ chevron: svg('<polyline points="9 18 15 12 9 6"/>'),+ page: svg('<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>'),+ link: svg('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'),+ trash: svg('<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>'),+ archive: svg('<rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><line x1="10" y1="14" x2="14" y2="14"/>'),++ // topbar+ undo: svg('<path d="M3 7v6h6"/><path d="M3 13a9 9 0 1 0 3-7.7L3 8"/>'),+ redo: svg('<path d="M21 7v6h-6"/><path d="M21 13a9 9 0 1 1-3-7.7L21 8"/>'),+ print: svg('<polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>'),+ panelLeft: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/>'),+ copy: svg('<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>'),+ markdown: svg('<rect x="2" y="5" width="20" height="14" rx="2"/><path d="M6 15V9l3 3 3-3v6"/><path d="M16 9v4"/><polyline points="14.5 12.5 16 14 17.5 12.5"/>'),+ lock: svg('<rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>'),+ chevronDown: svg('<polyline points="6 9 12 15 18 9"/>'),+ eye: svg('<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/>'),+ edit: svg('<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/>'),+ more: svg('<circle cx="12" cy="5" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="19" r="1.6" fill="currentColor" stroke="none"/>'),+ unarchive: svg('<rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><polyline points="9 15 12 12 15 15"/><line x1="12" y1="12" x2="12" y2="18"/>'),+ replace: svg('<path d="M14 4h5v5"/><path d="M19 4 5 18"/><path d="M9 4H5v4"/><path d="m15 15 4 4-4 4"/>'),+ arrowUp: svg('<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>'),+ arrowDown: svg('<line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/>'),+ close: svg('<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>'),+ sync: svg('<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>'),++ // PAGE ICONS — stylised, not colour emoji, so a sidebar of twelve pages+ // reads as one interface rather than a row of stickers.+ book: svg('<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>'),+ note: svg('<path d="M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9z"/><polyline points="15 3 15 9 21 9"/>'),+ inbox: svg('<polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>'),+ star: svg('<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26"/>'),+ folder: svg('<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>'),+ tag: svg('<path d="M20.59 13.41 12 22l-9-9V3h10l7.59 7.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>'),+ scale: svg('<path d="M12 3v18"/><path d="M5 7h14"/><path d="M5 7 2 14h6z"/><path d="M19 7l-3 7h6z"/><path d="M8 21h8"/>'),+ pen: svg('<path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><line x1="2" y1="2" x2="9.5" y2="9.5"/>'),+ compass: svg('<circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88"/>'),+ hash: svg('<line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/>'),++ // block-menu glyphs+ text: svg('<polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/>'),+ h1: svg('<path d="M4 4v16M12 4v16M4 12h8"/><path d="M17 9l3-2v13"/>'),+ h2: svg('<path d="M4 4v16M12 4v16M4 12h8"/><path d="M17 8a2.5 2.5 0 1 1 4 2l-4 5h4"/>'),+ h3: svg('<path d="M4 4v16M12 4v16M4 12h8"/><path d="M17 8a2.2 2.2 0 1 1 3 2 2.2 2.2 0 1 1-3 2"/>'),+ bullet: svg('<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1.4" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r="1.4" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r="1.4" fill="currentColor" stroke="none"/>'),+ number: svg('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><path d="M4 6h1V3.5"/><path d="M3.5 12.5h2L3.5 15h2"/>'),+ todo: svg('<polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>'),+ toggle: svg('<polyline points="9 6 15 12 9 18"/><line x1="19" y1="12" x2="21" y2="12"/>'),+ quote: svg('<path d="M6 17h3l2-4V7H5v6h3zM16 17h3l2-4V7h-6v6h3z"/>'),+ code: svg('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>'),+ divider: svg('<line x1="3" y1="12" x2="21" y2="12"/>'),+ image: svg('<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.5-3.5L6 23"/>'),+} as const++export type IconName = keyof typeof ICONSdiff --git a/spaces/src/main.ts b/spaces/src/main.tsindex bf869ae4..af2e4fef 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -1,25 +1,24 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors// Boot sequence for bento/spaces. Order matters: configure the app, then-// capture the pristine document BEFORE any DOM mutation — the captured copy-// is what gets re-serialized on save.-//-// SCAFFOLD: this is the reference wiring for a Bento app, deliberately small-// enough to read in one sitting. It exercises every kernel seam — app config,-// self-save, encryption-aware serialization, autosave/recovery, i18n, signed-// updates, the AI round-trip surface — so a new app can be grown from here-// rather than assembled from guesses. See docs/PLATFORM.md §10.+// capture the pristine document BEFORE any DOM mutation — the captured copy is+// what gets re-serialized on save.import './styles.css'import { configureApp, appConfig } from '../../kernel/src/app.ts'import {capturePristine, readEmbeddedDoc, serializeFile, serializeAuto,- saveFile, parseEnvelope,+ saveFile, parseEnvelope, canWriteInPlace, decryptEnvelope, setEncryptionPassword,+ isEncryptionActive,} from '../../kernel/src/save.ts'import { putRecovery, getRecovery, clearRecovery, pruneOld } from '../../kernel/src/autosave.ts'import { APP_VERSION } from '../../kernel/src/update.ts'-import { t } from './i18n'-import { parseDoc, starterDoc, docContentKey, uid, type SpacesDoc } from './model'+import { t, applyDirection } from './i18n'+import { parseDoc, docContentKey, uid, type SpacesDoc, type ParseResult } from './model'+import { starterDoc } from './starter'+import { Store } from './store'+import { Editor } from './editor'+import { downloadMarkdown } from './about'configureApp({appId: 'bento-spaces',@@ -28,163 +27,293 @@ configureApp({})capturePristine()+applyDirection()const embedded = readEmbeddedDoc()-// Encrypted files use the same bento/enc envelope as every Bento app; the-// scaffold has no password UI yet, so it reports rather than pretending.-if (embedded && parseEnvelope(embedded)) {- document.body.innerHTML =- `<div class="sp-gate"><h1>${t('This file is encrypted.')}</h1>` +- `<p>${t('Password unlocking is not implemented in this build yet.')}</p></div>`++const envelope = embedded ? parseEnvelope(embedded) : null++if (envelope) {+ void passwordGate()} else {- boot((embedded && parseDoc(embedded)) || starterDoc())+ const res = parseDoc(embedded ?? '')+ if (res.ok) {+ if (!res.doc.docId) res.doc.docId = uid('doc')+ boot(res.doc, res.repaired, res.frozen)+ } else if (res.err === 'empty') {+ // THE ONLY path to the starter. Anything else that failed to parse is+ // someone's data, and replacing it with an empty space would be a loss the+ // first ⌘S makes permanent.+ const doc = starterDoc()+ doc.docId = uid('doc')+ boot(doc, [], undefined)+ } else {+ refuse(res)+ }}-function boot(doc: SpacesDoc) {- document.title = `${doc.title} — ${appConfig().appName}`+/**+ * An encrypted space: ask, then boot.+ *+ * This MUST exist for as long as the About dialog can set a password —+ * otherwise encrypting a space locks its author out of it permanently, which+ * is the worst bug this app could have. The password is held in memory so+ * every later save stays encrypted.+ */+async function passwordGate(): Promise<void> {document.getElementById('bento-splash')?.remove()+ const wrap = document.createElement('div')+ wrap.className = 'sp-gate'+ const card = document.createElement('div')+ card.className = 'sp-gate-card'+ card.innerHTML = `<h1>${t('This space is locked')}</h1>` ++ `<p>${t('Enter the password to open it.')}</p>`+ const input = document.createElement('input')+ input.type = 'password'+ input.className = 'sp-find'+ input.autocomplete = 'current-password'+ const go = document.createElement('button')+ go.className = 'sp-btn sp-primary'+ go.textContent = t('Unlock')+ const err = document.createElement('p')+ err.className = 'sp-note'+ card.append(input, go, err)+ wrap.append(card)+ document.body.append(wrap)+ input.focus()- const app = document.getElementById('app')!- app.innerHTML =- `<header class="sp-bar">` +- `<span class="sp-mark">bento<span>/</span>spaces</span>` +- `<input class="sp-title" value="">` +- `<button class="sp-save">${t('Save')}</button>` +- `<span class="sp-ver">v${APP_VERSION}</span>` +- `</header><main class="sp-doc"></main>`-- const titleInput = app.querySelector<HTMLInputElement>('.sp-title')!- const main = app.querySelector<HTMLElement>('.sp-doc')!- titleInput.value = doc.title-- let saveTimer: number | undefined- /** Debounced autosave — a recovery snapshot survives a crash or tab close. */- const touch = () => {- doc.modified = new Date().toISOString()- clearTimeout(saveTimer)- saveTimer = setTimeout(() => void putRecovery(doc), 2500) as unknown as number+ const tryUnlock = async () => {+ const pass = input.value+ if (!pass) return+ go.disabled = true+ const json = await decryptEnvelope(envelope!, pass)+ go.disabled = false+ if (json === null) { err.textContent = t('Wrong password — try again'); input.select(); return }+ const res = parseDoc(json)+ if (!res.ok) { err.textContent = t('Unlocked, but the document inside could not be read.'); return }+ // held in memory so ⌘S and autosave keep writing encrypted+ setEncryptionPassword(pass)+ wrap.remove()+ if (!res.doc.docId) res.doc.docId = uid('doc')+ boot(res.doc, res.repaired, res.frozen)}+ go.addEventListener('click', () => { void tryUnlock() })+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') void tryUnlock() })+}- const render = () => {- main.innerHTML = ''- for (const block of doc.blocks) {- const el = document.createElement('p')- el.className = 'sp-block'- el.contentEditable = 'true'- el.textContent = block.text- el.dataset.id = block.id- el.addEventListener('input', () => {- block.text = el.textContent ?? ''- touch()- })- el.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- e.preventDefault()- const at = doc.blocks.indexOf(block)- const fresh = { id: uid(), text: '' }- doc.blocks.splice(at + 1, 0, fresh)- touch()- render()- focusBlock(fresh.id)- } else if (e.key === 'Backspace' && !el.textContent && doc.blocks.length > 1) {- e.preventDefault()- const at = doc.blocks.indexOf(block)- doc.blocks.splice(at, 1)- touch()- render()- focusBlock(doc.blocks[Math.max(0, at - 1)]?.id)- }- })- main.appendChild(el)- }- }+/**+ * A document we cannot read is NOT a reason to show an empty one.+ *+ * No editor, no autosave, and two ways out that do not require us to have+ * understood the file: keep the bytes exactly as they are, or take the JSON+ * somewhere else.+ */+function refuse(res: Extract<ParseResult, { ok: false }>): void {+ const detail = 'detail' in res ? res.detail : ''+ const what = res.err === 'format'+ ? t('This is not a bento/spaces document — {detail}.', { detail })+ : res.err === 'json'+ ? t('The document block is not valid JSON — {detail}.', { detail })+ : t('The document block is not shaped like a space — {detail}.', { detail })- const focusBlock = (id?: string) => {- if (!id) return- const el = main.querySelector<HTMLElement>(`[data-id="${id}"]`)- if (!el) return- el.focus()- const range = document.createRange()- range.selectNodeContents(el)- range.collapse(false)- const sel = getSelection()- sel?.removeAllRanges()- sel?.addRange(range)- }+ gate(t('This file could not be opened'), what, [+ [t('Save an untouched copy…'), () => {+ // the bytes as they are, NOT a re-serialization: we did not understand+ // this document, so we must not rewrite it+ const html = `<!DOCTYPE html>\n${document.documentElement.outerHTML}`+ const a = document.createElement('a')+ a.href = URL.createObjectURL(new Blob([html], { type: 'text/html' }))+ a.download = 'untouched-copy.bento.html'+ a.click()+ }],+ [t('Copy the document JSON'), () => { void navigator.clipboard?.writeText(embedded ?? '') }],+ ])- titleInput.addEventListener('input', () => {- doc.title = titleInput.value || 'Untitled'- document.title = `${doc.title} — ${appConfig().appName}`- touch()- })+ const pre = document.createElement('pre')+ pre.className = 'sp-gate-raw'+ pre.textContent = (embedded ?? '').slice(0, 400)+ document.querySelector('.sp-gate-card')?.append(pre)+}- const save = async () => {- const res = await saveFile(doc)- if (res !== 'cancelled') void clearRecovery(doc.docId)+function gate(title: string, body: string, actions: Array<[string, () => void]>): void {+ document.getElementById('bento-splash')?.remove()+ const wrap = document.createElement('div')+ wrap.className = 'sp-gate'+ const card = document.createElement('div')+ card.className = 'sp-gate-card'+ const h = document.createElement('h1')+ h.textContent = title+ const p = document.createElement('p')+ p.textContent = body+ card.append(h, p)+ for (const [label, fn] of actions) {+ const b = document.createElement('button')+ b.className = 'sp-btn sp-primary'+ b.textContent = label+ b.addEventListener('click', fn)+ card.append(b)}- app.querySelector('.sp-save')!.addEventListener('click', () => void save())- addEventListener('keydown', (e) => {- if ((e.metaKey || e.ctrlKey) && e.key === 's') {- e.preventDefault()- void save()- }- })+ wrap.append(card)+ document.body.append(wrap)+}- render()- void checkRecovery()- void pruneOld()+function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version'): void {+ document.title = `${doc.title} — ${appConfig().appName}`+ document.getElementById('bento-splash')?.remove()- /** If the last autosaved snapshot differs from the file we loaded, the- * previous session ended before a save — offer it back. */- async function checkRecovery() {- const snap = await getRecovery(doc.docId)- if (!snap) return- let prev: SpacesDoc | null = null- try {- prev = parseDoc(snap.json)- } catch {- return- }- if (!prev || docContentKey(prev) === docContentKey(doc)) return- const bar = document.createElement('div')- bar.className = 'sp-recover'- bar.innerHTML = `<span>${t('Unsaved changes from your last session were found.')}</span>`- const restore = document.createElement('button')- restore.textContent = t('Restore')- restore.addEventListener('click', () => {- doc = prev!- titleInput.value = doc.title- render()- bar.remove()- })- const discard = document.createElement('button')- discard.textContent = t('Discard')- discard.addEventListener('click', () => {- void clearRecovery(doc.docId)- bar.remove()+ const store = new Store(doc)+ if (frozen) store.readOnly = true+ const editor = new Editor(document.getElementById('app')!, store)++ if (frozen) {+ banner(frozen === 'version'+ ? t('This file was written by a newer version of bento/spaces. It is open read-only so nothing is lost.')+ : t('This file declares rules this build does not know. It is open read-only so nothing is lost.'))+ }+ if (repaired.length) {+ banner(t('{n} duplicate or missing id(s) were repaired so links and pages resolve.', { n: repaired.length }))+ }++ editor.onSave = () => { void doSave() }+ editor.onSaveAs = (suffix: string) => {+ if (suffix === '__markdown') { downloadMarkdown(store); return }+ store.endRun()+ // forcePicker = "Save a copy…": it always asks where, and the kernel keeps+ // the in-place handle pointed at the working file, so a later ⌘S does not+ // start overwriting the copy+ void saveFile(store.doc, true).then((res) => {+ if (res === 'saved') editor.status(t('Copy saved'))})- bar.append(restore, discard)- document.body.appendChild(bar)+ }+ async function doSave(): Promise<void> {+ store.endRun()+ editor.status(t('Saving…'))+ const res = await saveFile(store.doc)+ if (res === 'saved') {+ void clearRecovery(store.doc.docId)+ // "Saved" is doing real work here: on a browser without file-system+ // access this was a NEW download, and saying so is the difference+ // between understanding that and losing track of which copy is current+ editor.status(canWriteInPlace() ? t('Saved') : t('Saved a new copy'))+ } else {+ editor.status('')+ }}- // AI/tooling round-trip (docs/PLATFORM.md §7): the document JSON is the- // interchange unit, so agents can read and replace it without the file.+ // A recovery snapshot is the ONLY backstop on browsers with no file-system+ // access — which is every browser on iOS.+ //+ // NEVER for an encrypted space. The snapshot is the document as plain JSON,+ // so writing one puts in IndexedDB exactly what the password exists to keep+ // off the disk — and it would do it every few seconds, for the one author who+ // demonstrably cares. The kernel's putRecovery does not guard this; the+ // caller must (slides has the same contract).+ let timer: ReturnType<typeof setTimeout> | undefined+ store.on('doc', () => {+ clearTimeout(timer)+ if (isEncryptionActive()) return+ timer = setTimeout(() => { void putRecovery(store.doc) }, 2500)+ })+ void pruneOld()+ void offerRecovery(doc, store, editor)++ // ---- the AI round-trip (PLATFORM §7) -----------------------------------;(window as any).bento = {format: doc.format,- get doc() {- return doc+ get doc() { return store.doc },+ get readonly() { return store.readOnly },+ serialize: () => serializeFile(store.doc),+ serializeAuto: () => serializeAuto(store.doc),+ undo: () => { store.undo(); editor.repaint() },+ redo: () => { store.redo(); editor.repaint() },+ updates: { version: APP_VERSION },+ /** every page, flat — the shape an agent wants before it reads anything */+ pages: () => store.doc.pages.map((p) => ({+ id: p.id, title: p.title, parent: p.parent, archived: !!p.archived, blocks: p.blocks.length,+ })),+ getPage: (id: string) => store.doc.pages.find((p) => p.id === id) ?? null,+ search: (q: string) => {+ const needle = String(q).toLowerCase()+ const out: Array<{ pageId: string; title: string; blockId: string }> = []+ for (const p of store.doc.pages) {+ for (const b of p.blocks) {+ const text = (b.html ?? '').replace(/<[^>]+>/g, '')+ if (text.toLowerCase().includes(needle)) out.push({ pageId: p.id, title: p.title, blockId: b.id })+ }+ }+ return out},- serialize: () => serializeFile(doc),- serializeAuto: () => serializeAuto(doc),- loadDoc(json: string): boolean {- const next = parseDoc(json)- if (!next) return false- doc = next- titleInput.value = doc.title- document.title = `${doc.title} — ${appConfig().appName}`- render()- touch()+ /**+ * ONE undoable step. Without this an agent appending a paragraph has to+ * rewrite and reparse the whole space through loadDoc — clobbering+ * concurrent edits and flattening undo to a single entry.+ */+ insertBlocks: (pageId: string, afterId: string | null, blocks: unknown[]) => {+ const page = store.doc.pages.find((p) => p.id === pageId)+ if (!page || !Array.isArray(blocks)) return null+ const made = blocks.map((raw) => {+ const src = (raw ?? {}) as Record<string, unknown>+ return { ...src, id: uid('b'), type: String(src.type ?? 'p') }+ })+ store.commit(() => {+ const at = afterId ? page.blocks.findIndex((b) => b.id === afterId) + 1 : page.blocks.length+ page.blocks.splice(at < 1 ? page.blocks.length : at, 0, ...(made as any))+ })+ editor.repaint()+ return made.map((m) => m.id)+ },+ newPage: (title: string, parent?: string) => {+ const page = { id: uid('p'), title: String(title ?? 'Untitled'), blocks: [], ...(parent ? { parent } : {}) }+ store.commit(() => { store.doc.pages.push(page as any) })+ editor.repaint()+ return page.id+ },+ loadDoc: (json: string): boolean => {+ const r = parseDoc(json)+ if (!r.ok) return false+ store.replaceDoc(r.doc)+ editor.repaint()return true},}++ if (!canWriteInPlace()) {+ // stated rather than discovered — the product-defining limitation on iOS+ console.info('[bento/spaces] this browser cannot write back to the file; every save makes a new copy')+ }+}++function banner(text: string, actions: Array<[string, () => void]> = []): void {+ const bar = document.createElement('div')+ bar.className = 'sp-banner'+ const span = document.createElement('span')+ span.textContent = text+ bar.append(span)+ for (const [label, fn] of actions) {+ const b = document.createElement('button')+ b.className = 'sp-btn'+ b.textContent = label+ b.addEventListener('click', () => { fn(); bar.remove() })+ bar.append(b)+ }+ const close = document.createElement('button')+ close.className = 'sp-btn'+ close.textContent = '✕'+ close.setAttribute('aria-label', 'Dismiss')+ close.addEventListener('click', () => bar.remove())+ bar.append(close)+ document.body.prepend(bar)+}++/** A snapshot that differs from the file we loaded means a crash lost work. */+async function offerRecovery(doc: SpacesDoc, store: Store, editor: Editor): Promise<void> {+ const snap = await getRecovery(doc.docId)+ if (!snap) return+ let saved: SpacesDoc+ try { saved = JSON.parse(snap.json) as SpacesDoc } catch { return }+ if (docContentKey(saved) === docContentKey(doc)) return+ banner(t('Unsaved changes from a previous session were found.'), [+ [t('Restore'), () => { store.replaceDoc(saved); editor.repaint() }],+ [t('Discard'), () => { void clearRecovery(doc.docId) }],+ ])}diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex 1c766065..870496cd 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -3,91 +3,353 @@// The bento/spaces document model. This JSON is what lives inside the// #bento-doc block — the format IS the product (docs/PLATFORM.md §3).//-// SCAFFOLD: deliberately minimal — a flat list of text blocks. The real app-// grows a nested block tree, rich text, embeds and references. Grow it-// ADDITIVELY: every future version must still open documents written by this-// one, and unknown fields must be preserved rather than stripped.+// ONE FILE = ONE SPACE: a tree of pages, each holding a flat pre-order list of+// blocks. Links are same-document fragments (`#p/<pageId>`) resolved against a+// map built from this block, so they work from file://, from a mail+// attachment, on iOS, and in 2036 (docs/DECISIONS.md, 2026-08-03).+//+// ADDITIVE FOREVER (PLATFORM §3): unknown top-level fields, unknown per-node+// fields and unknown block TYPES all survive parse → serialize. An older build+// meeting a future 'kanban' block keeps it and renders its html fallback.+// There is no server; a break here is permanent.export const FORMAT = 'bento/spaces'export const FORMAT_VERSION = 1+/**+ * Rules that could ever CHANGE are pinned as VALUES, never inferred from+ * `version` — the SYNC_V lesson: discard what you cannot read rather than+ * misread it. The OPEN half of the union is load-bearing: an unrecognised+ * policy must PARSE, so the file opens and round-trips byte-exact with+ * canonicalization and id repair disabled.+ */+export type Policy = 'bento-spaces-1' | (string & {})++/**+ * Block types this build knows. `Block.type` is `string`, NOT this union —+ * an unknown type must survive a round-trip, so the type system must not be+ * able to express "only these".+ */+export type KnownBlockType =+ | 'p' | 'h1' | 'h2' | 'h3' | 'bullet' | 'number' | 'todo' | 'toggle'+ | 'quote' | 'code' | 'divider' | 'image' | 'pagelink'++/**+ * A block.+ *+ * PROPERTIES ARE FLAT, not nested under a `props` object, and that is a+ * correctness decision rather than a style one. Under collaboration each+ * (node, key) pair is one last-writer-wins register. With a nested `props` the+ * whole object is ONE register: measured, one author ticking `done` while+ * another sets a second field loses one of the two edits SILENTLY. Slides'+ * elements are flat for the same reason and keep both. Flattening costs+ * nothing now and is unrecoverable later, because the shape is in every file+ * ever saved.+ *+ * `html` is inline-only rich text (see sanitize.ts). Block STRUCTURE is+ * `type`, never markup — the renderer emits the semantic tag.+ */export interface Block {id: string- /** Plain text for now; rich inline content comes later, additively. */- text: string+ type: string+ /** inline-only html; canonicalised at typing-run close */+ html?: string+ /** nesting WITHIN a page: the id of the block that owns this one */+ parent?: string++ // ---- per-type fields, deliberately flat -------------------------------+ /** todo */+ done?: boolean+ /** code */+ lang?: string+ /** toggle: fold state AS SAVED is authorial intent, so it is document data.+ * Toggles always PRINT expanded — silently omitting content from a printed+ * handbook is a data-loss-shaped bug. */+ open?: boolean+ /** image: 'asset:<key>' | data: | https: */+ src?: string+ alt?: string+ caption?: string+ /** image width as a PERCENTAGE of the text column (10..100). No block+ * carries absolute px — the column width is a theme concern. */+ width?: number+ /** intrinsic px at insert: holds the aspect box while the image decodes */+ w?: number+ h?: number+ /** pagelink: the target page id */+ page?: string++ [extra: string]: unknown+}++export interface Page {+ id: string+ title: string+ /** page-tree nesting; absent = a root page */+ parent?: string+ /** one emoji, never a URL — a URL would be a network dependency */+ icon?: string+ /** flat, pre-order; nesting via Block.parent */+ blocks: Block[]+ /** out of the sidebar, still searchable and linkable, and ENUMERATED at+ * share time — an author archived a page precisely because it was sensitive */+ archived?: boolean+ created?: string+ edited?: string+ [extra: string]: unknown+}++export interface Theme {+ background: string+ color: string+ accent: string+ fontFamily: string+ headingFamily?: string+ /** text column width in px — DOCUMENT data: the same for every reader */+ measure?: number+ /** BASE direction of page CONTENT (PLATFORM §8's two-layer pin) */+ dir?: 'ltr' | 'rtl'}export interface SpacesDoc {format: typeof FORMATversion: number- /** Stable uuid, minted once and NEVER regenerated — the kernel envelope- * keys autosave/recovery and (later) sync on it. */+ /** absent ⇒ bento-spaces-1 */+ policy?: Policy+ /** minted once at creation/load, NEVER regenerated (PLATFORM §3) */docId: stringtitle: stringmodified?: string- blocks: Block[]- /** Anything a newer version wrote that this one doesn't understand is- * carried through untouched — see parseDoc. */+ /** flat, pre-order; nesting via Page.parent */+ pages: Page[]+ /** the page shown on open; absent ⇒ pages[0] */+ home?: string+ theme: Theme+ assets?: Record<string, string>+ fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>+ readonly?: boolean+ template?: boolean+ /** RESERVED — collaboration credentials, unused until collab ships */+ collab?: unknown[extra: string]: unknown}-export const uid = (p = 'b'): string =>- `${p}-${Math.random().toString(36).slice(2, 10)}`+export const uid = (p = 'b'): string => {+ const r = globalThis.crypto?.randomUUID?.()+ return r ? `${p}-${r.slice(0, 8)}` : `${p}-${Math.random().toString(36).slice(2, 10)}`+}-const newDocId = (): string =>- (globalThis.crypto?.randomUUID?.() ?? uid('doc'))+const newDocId = (): string => globalThis.crypto?.randomUUID?.() ?? uid('doc')/**- * Parse + validate a document from the data block. Returns null if this is- * not a bento/spaces document at all. Forward-compatible on purpose: unknown- * top-level fields survive the round-trip, and a missing docId is minted- * rather than treated as fatal.+ * Parse result — TAGGED, never null.+ *+ * `parseDoc` returning null let the caller fall back to the starter, which+ * means opening a slides file, or a document with one hand-edited typo, gave+ * you an EMPTY space over live data — and the first ⌘S wrote it to disk. The+ * only path to the starter is an absent or empty block.+ *+ * `frozen` means this build must not canonicalize html or repair ids: the file+ * declares rules this build does not have, so it round-trips byte-exact.+ * Sanitize still runs — that is a security control, not an interpretation.*/-export function parseDoc(json: string): SpacesDoc | null {+export type ParseResult =+ | { ok: true; doc: SpacesDoc; repaired: string[]; frozen?: 'policy' | 'version' }+ | { ok: false; err: 'empty' }+ | { ok: false; err: 'json' | 'format' | 'shape'; detail: string; found?: string }++const isObj = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object' && !Array.isArray(v)++/**+ * Deterministic id repair.+ *+ * Two readers of one file must agree on every id, so a replacement is derived+ * from the BYTES — never from `Math.random` (which diverges two readers, and+ * two future CRDT replicas on a node key) and never from `docId` (which+ * `template: true` re-mints on every open, so a docId-derived id gives two+ * readers of one file DIFFERENT ids: exactly the failure repair exists to+ * prevent).+ */+function repairId(scope: string, ordinal: number, content: string, salt = 0): string {+ let h = 0x811c9dc5+ const s = `${scope}${ordinal}${content}${salt}`+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i)+ h = Math.imul(h, 0x01000193) >>> 0+ }+ return `r-${h.toString(36)}`+}++export function parseDoc(json: string): ParseResult {+ if (!json || !json.trim()) return { ok: false, err: 'empty' }+let raw: unknowntry {raw = JSON.parse(json)- } catch {- return null+ } catch (e) {+ return { ok: false, err: 'json', detail: (e as Error).message }}- if (!raw || typeof raw !== 'object') return null- const d = raw as Record<string, unknown>- if (d.format !== FORMAT || !Array.isArray(d.blocks)) return null- return {- ...d,- format: FORMAT,- version: typeof d.version === 'number' ? d.version : FORMAT_VERSION,- docId: typeof d.docId === 'string' && d.docId ? d.docId : newDocId(),- title: typeof d.title === 'string' ? d.title : 'Untitled',- blocks: (d.blocks as unknown[]).map((b, i) => {- const blk = (b ?? {}) as Record<string, unknown>+ if (!isObj(raw)) return { ok: false, err: 'shape', detail: 'the document block is not a JSON object' }++ if (raw.format !== FORMAT) {+ return {+ ok: false,+ err: 'format',+ detail: `this document declares "${String(raw.format ?? '(nothing)')}"`,+ found: typeof raw.format === 'string' ? raw.format : undefined,+ }+ }+ if (!Array.isArray(raw.pages)) {+ return { ok: false, err: 'shape', detail: 'a bento/spaces document needs a "pages" array' }+ }++ const version = typeof raw.version === 'number' ? raw.version : FORMAT_VERSION+ const policy = typeof raw.policy === 'string' ? raw.policy : 'bento-spaces-1'+ const frozen: 'policy' | 'version' | undefined =+ version > FORMAT_VERSION ? 'version' : policy !== 'bento-spaces-1' ? 'policy' : undefined++ const repaired: string[] = []+ const seen = new Set<string>()+ /** first occurrence in pre-order keeps the id; later duplicates are repaired */+ const claim = (want: unknown, scope: string, ordinal: number, content: string): string => {+ const id = typeof want === 'string' && want ? want : ''+ if (id && !seen.has(id)) { seen.add(id); return id }+ if (frozen && id) return id // frozen: never rewrite, even a duplicate+ let salt = 0+ let next = repairId(scope, ordinal, content, salt)+ while (seen.has(next)) next = repairId(scope, ordinal, content, ++salt)+ seen.add(next)+ repaired.push(id || '(missing id)')+ return next+ }++ // Pages repair FIRST, in pre-order, so a block's owning page id is final+ // before its own replacement is derived from it.+ const pages: Page[] = (raw.pages as unknown[]).map((p, pi) => {+ const src = isObj(p) ? p : {}+ const title = typeof src.title === 'string' ? src.title : 'Untitled'+ const pid = claim(src.id, String(src.parent ?? ''), pi, title)+ const blocksRaw = Array.isArray(src.blocks) ? src.blocks : []+ const blocks: Block[] = blocksRaw.map((b, bi) => {+ const bs = isObj(b) ? b : {}+ const type = typeof bs.type === 'string' && bs.type ? bs.type : 'p'+ const html = typeof bs.html === 'string' ? bs.html : undefinedreturn {- ...blk,- id: typeof blk.id === 'string' && blk.id ? blk.id : uid(`b${i}`),- text: typeof blk.text === 'string' ? blk.text : '',+ ...bs,+ id: claim(bs.id, pid, bi, `${type}${html ?? ''}`),+ type,+ ...(html !== undefined ? { html } : {}),} as Block- }),+ })+ return { ...src, id: pid, title, blocks } as Page+ })++ // A parent naming something that does not exist is DROPPED rather than left+ // dangling: an unreachable page is worse than a root one, and a block whose+ // owner is absent would never render at all.+ const pageIds = new Set(pages.map((p) => p.id))+ for (const p of pages) {+ if (p.parent && !pageIds.has(p.parent)) delete p.parent+ const own = new Set(p.blocks.map((b) => b.id))+ for (const b of p.blocks) if (b.parent && !own.has(b.parent)) delete b.parent+ }++ const doc: SpacesDoc = {+ ...raw,+ format: FORMAT,+ version,+ docId: typeof raw.docId === 'string' && raw.docId ? raw.docId : newDocId(),+ title: typeof raw.title === 'string' ? raw.title : 'Untitled space',+ pages,+ theme: { ...defaultTheme(), ...(isObj(raw.theme) ? raw.theme : {}) },} as SpacesDoc++ return { ok: true, doc, repaired, ...(frozen ? { frozen } : {}) }}-/** What a freshly built bento/spaces file opens with. */-export function starterDoc(): SpacesDoc {+export function defaultTheme(): Theme {return {- format: FORMAT,- version: FORMAT_VERSION,- docId: newDocId(),- title: 'Untitled space',- blocks: [- { id: uid(), text: 'This whole page — the text, the editor, the app — is one HTML file.' },- { id: uid(), text: 'Type to edit. ⌘S saves the file back to disk, with your writing inside it.' },- { id: uid(), text: 'Press ⏎ at the end of a block to add another; ⌫ on an empty block removes it.' },- ],+ background: '#FFFFFF',+ color: '#1E2A3A',+ accent: '#F7A600',+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",+ measure: 720,}}-/** The content that matters for "did this change" — excludes volatile fields- * (modified) that churn without a real edit. Per-app by design: the kernel- * must not know what counts as content here (docs/PLATFORM.md §9). */+export const newBlock = (type = 'p', extra: Partial<Block> = {}): Block =>+ ({ id: uid('b'), type, html: '', ...extra })++export const newPage = (title = 'Untitled', extra: Partial<Page> = {}): Page =>+ ({ id: uid('p'), title, blocks: [newBlock()], ...extra })++/** Content that matters for "did this change" — excludes volatile fields. */export function docContentKey(doc: SpacesDoc): string {- return JSON.stringify([doc.title, doc.blocks])+ return JSON.stringify([doc.title, doc.home, doc.pages])+}++// ---- derived, NEVER stored -------------------------------------------------+// Stale the moment anything else writes the document (an agent editing+// #bento-doc, a version restore, a future CRDT apply). Derived at load.++export interface SpaceIndex {+ page: Map<string, Page>+ /** page id → child pages in order; '' = root */+ children: Map<string, Page[]>+ block: Map<string, { block: Block; pageId: string }>+ /** target page id → the blocks that link to it */+ backlinks: Map<string, Array<{ pageId: string; blockId: string }>>+}++/** Every `#p/<id>` href in a block's html. */+const LINK_RE = /href="#p\/([^"]+)"/g++const pushInto = <T>(m: Map<string, T[]>, k: string, v: T) => {+ const list = m.get(k)+ if (list) list.push(v)+ else m.set(k, [v])+}++export function buildIndex(doc: SpacesDoc): SpaceIndex {+ const page = new Map<string, Page>()+ const children = new Map<string, Page[]>()+ const block = new Map<string, { block: Block; pageId: string }>()+ const backlinks = new Map<string, Array<{ pageId: string; blockId: string }>>()++ for (const p of doc.pages) page.set(p.id, p)+ for (const p of doc.pages) {+ // a parent that does not resolve shows at root, never disappears+ pushInto(children, p.parent && page.has(p.parent) ? p.parent : '', p)+ for (const b of p.blocks) {+ block.set(b.id, { block: b, pageId: p.id })+ if (b.html) {+ for (const m of b.html.matchAll(LINK_RE)) {+ pushInto(backlinks, m[1], { pageId: p.id, blockId: b.id })+ }+ }+ if (b.type === 'pagelink' && typeof b.page === 'string') {+ pushInto(backlinks, b.page, { pageId: p.id, blockId: b.id })+ }+ }+ }+ return { page, children, block, backlinks }+}++/** The page a reader lands on. */+export const homePage = (doc: SpacesDoc): Page | undefined =>+ (doc.home ? doc.pages.find((p) => p.id === doc.home) : undefined) ?? doc.pages[0]++/**+ * Would loading this src touch the network?+ *+ * `asset:` is in the file and `data:` is the bytes themselves — neither leaves+ * the machine. Everything else does, INCLUDING a relative path (which resolves+ * against the document's own URL and is a real request on a static host), and+ * `//host/x`, and any scheme this build has never heard of. So the test is an+ * allowlist of the two local forms, not a blocklist of `http`.+ */+export function isRemote(src: string): boolean {+ if (!src) return false+ return !src.startsWith('asset:') && !src.startsWith('data:')}diff --git a/spaces/src/render.ts b/spaces/src/render.tsnew file mode 100644index 00000000..5def8052--- /dev/null+++ b/spaces/src/render.ts@@ -0,0 +1,303 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// model → DOM. ONE renderer for the editor, the reader, print and (later) the+// file-manager preview, so those surfaces can never disagree about what a+// document looks like.+//+// The renderer emits REAL SEMANTIC TAGS — h1..h3, ul/ol/li, blockquote,+// pre>code, figure — never divs with classes. That buys the screen-reader+// story, native ⌘F, print fidelity and lossless markdown export at once, from+// one decision.++import { type SpacesDoc, type Page, type Block, isRemote } from './model'+import { sanitizeInline, inertBody, esc } from './sanitize'+import { t } from './i18n'++export interface RenderOpts {+ /** editable per-block hosts (the editor); false for reader/print */+ editable?: boolean+ /** resolve a page id to its title, for link chips and pagelink blocks */+ titleOf?: (pageId: string) => string | undefined+ /** collapsed toggles render OPEN — print always passes this */+ forceOpen?: boolean+ /**+ * Has the READER agreed to load this remote url?+ *+ * A VIEWER-scoped decision, never a document field — the same rule as locale+ * and reduced motion. Putting consent in the file would mean the author+ * decides whether the reader phones home, which is precisely backwards, and+ * it would travel to the next person the file is mailed to.+ */+ allowRemote?: (src: string) => boolean+}++/** Blocks that group into one list element when adjacent. */+const LIST_OF: Record<string, 'ul' | 'ol'> = { bullet: 'ul', number: 'ol', todo: 'ul' }++const TAG_OF: Record<string, string> = {+ p: 'p', h1: 'h1', h2: 'h2', h3: 'h3', quote: 'blockquote',+ bullet: 'li', number: 'li', todo: 'li',+}++/**+ * Render one page's blocks.+ *+ * Nesting is `Block.parent`, and the array is pre-order, so a child always+ * follows its parent. That is what lets a single forward pass build the tree+ * without a lookup table.+ */+export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): DocumentFragment {+ const frag = document.createDocumentFragment()+ // stack of open containers, innermost last: [blockId, element]+ const stack: Array<[string, HTMLElement]> = []+ let list: { el: HTMLElement; kind: 'ul' | 'ol'; under: string } | null = null++ const hostFor = (parent: string | undefined): HTMLElement | DocumentFragment => {+ while (stack.length && stack[stack.length - 1][0] !== parent) stack.pop()+ return stack.length ? stack[stack.length - 1][1] : frag+ }++ for (const b of page.blocks) {+ const host = hostFor(b.parent)+ const kind = LIST_OF[b.type]++ // adjacent same-kind list items share one <ul>/<ol>+ if (kind) {+ if (!list || list.kind !== kind || list.under !== (b.parent ?? '')) {+ const el: HTMLElement = document.createElement(kind)+ el.className = 'sp-list'+ host.appendChild(el)+ list = { el, kind, under: b.parent ?? '' }+ }+ } else {+ list = null+ }++ const node = renderBlock(b, doc, opts)+ ;(kind && list ? list.el : host).appendChild(node)++ // a toggle owns the blocks whose parent is its id+ if (b.type === 'toggle') {+ const body = document.createElement('div')+ body.className = 'sp-toggle-body'+ if (!(opts.forceOpen || b.open)) body.hidden = true+ node.appendChild(body)+ stack.push([b.id, body])+ list = null+ }+ }+ return frag+}++export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HTMLElement {+ const type = b.type+ const el = document.createElement(TAG_OF[type] ?? 'div')+ el.dataset.blockId = b.id+ el.dataset.type = type+ el.className = `sp-b sp-b-${type}`++ switch (type) {+ case 'divider':+ el.className = 'sp-b sp-b-divider'+ el.appendChild(document.createElement('hr'))+ return el++ case 'code': {+ const pre = document.createElement('pre')+ const code = document.createElement('code')+ if (b.lang) code.className = `language-${esc(String(b.lang))}`+ code.textContent = textFromHtml(b.html)+ if (opts.editable) { code.contentEditable = 'true'; code.dataset.edit = b.id }+ pre.appendChild(code)+ el.appendChild(pre)+ return el+ }++ case 'image': {+ const fig = document.createElement('figure')+ const rawSrc = String(b.src ?? '')++ // A REMOTE image is not loaded until the reader asks for it.+ //+ // Measured: a space carrying <img src="https://…/pixel.png"> requests it+ // on open. In a format whose whole point is that you can mail it, that is+ // a tracking pixel — the recipient's IP and the moment they opened your+ // document, delivered to whoever wrote the file. It also breaks PLATFORM+ // §1: no network is required to open a document.+ //+ // This costs authors nothing, because the editor never writes a remote+ // src: picked images are downscaled, interned by content hash and stored+ // as `asset:`. Only hand- or agent-authored documents carry URLs, and for+ // those the reader gets a placeholder naming the host and a button. One+ // click, per image, informed — the model every mail client settled on.+ if (isRemote(rawSrc) && !opts.allowRemote?.(rawSrc)) {+ fig.appendChild(remoteImagePlaceholder(rawSrc, b, opts))+ if (b.caption) {+ const cap = document.createElement('figcaption')+ cap.innerHTML = sanitizeInline(String(b.caption))+ fig.appendChild(cap)+ }+ el.appendChild(fig)+ return el+ }++ const img = document.createElement('img')+ img.src = resolveSrc(rawSrc, doc)+ img.alt = String(b.alt ?? '')+ if (b.width) img.style.width = `${Math.max(10, Math.min(100, Number(b.width)))}%`+ // intrinsic size holds the aspect box while the image decodes, so the+ // page does not reflow under the reader's cursor+ if (b.w && b.h) { img.width = Number(b.w); img.height = Number(b.h) }+ fig.appendChild(img)+ if (b.caption) {+ const cap = document.createElement('figcaption')+ cap.innerHTML = sanitizeInline(String(b.caption))+ fig.appendChild(cap)+ }+ el.appendChild(fig)+ return el+ }++ case 'pagelink': {+ const a = document.createElement('a')+ const target = String(b.page ?? '')+ a.href = `#p/${target}`+ a.className = 'sp-pagecard'+ const title = opts.titleOf?.(target)+ a.textContent = title ?? '(missing page)'+ if (!title) a.classList.add('sp-dead')+ el.appendChild(a)+ return el+ }++ case 'todo': {+ const box = document.createElement('input')+ box.type = 'checkbox'+ box.checked = !!b.done+ box.className = 'sp-check'+ // the checkbox is a control, not text: it must not be inside the+ // editable host or typing would land in it+ el.appendChild(box)+ el.appendChild(inlineHost(b, opts))+ if (b.done) el.classList.add('sp-done')+ return el+ }++ case 'toggle': {+ const twist = document.createElement('button')+ twist.className = 'sp-twist'+ twist.type = 'button'+ twist.setAttribute('aria-expanded', String(!!(opts.forceOpen || b.open)))+ twist.setAttribute('aria-label', 'Toggle section')+ twist.textContent = '▸'+ el.appendChild(twist)+ el.appendChild(inlineHost(b, opts))+ return el+ }++ default:+ el.appendChild(inlineHost(b, opts))+ return el+ }+}++/** The editable text host. Per-block, never one big editable container — that+ * is what keeps Selection block-scoped and stops a merge re-minting ids. */+function inlineHost(b: Block, opts: RenderOpts): HTMLElement {+ const inner = document.createElement('span')+ inner.className = 'sp-text'+ inner.dataset.edit = b.id+ // direction is per-block from the CONTENT, inside a container pinned by the+ // document's theme.dir — PLATFORM §8's two-layer rule+ inner.dir = 'auto'+ if (opts.editable) inner.contentEditable = 'true'+ inner.innerHTML = sanitizeInline(b.html ?? '')+ if (!b.html) inner.dataset.empty = '1'+ return inner+}++// Untrusted html — parse INERT. A detached div still loads what it creates,+// so `<img src="404" onerror>` in a code block would run its handler here.+// See sanitize.ts inertBody().+const textFromHtml = (html: string | undefined): string => {+ if (!html) return ''+ return inertBody(html).textContent ?? ''+}++export function resolveSrc(src: string, doc: SpacesDoc): string {+ if (src.startsWith('asset:')) return doc.assets?.[src.slice(6)] ?? ''+ return src+}+++/** The host a reader is being asked to trust, or the raw src if it will not parse. */+function remoteHost(src: string): string {+ try { return new URL(src, 'https://x.invalid').host || src } catch { return src }+}++/**+ * What stands in for an unloaded remote image: what it is, WHERE it would come+ * from, and a button. Naming the host is the point — "load images" with no+ * indication of who is being contacted is not consent.+ */+function remoteImagePlaceholder(src: string, b: Block, opts: RenderOpts): HTMLElement {+ const box = document.createElement('div')+ box.className = 'sp-remote'+ box.dataset.remoteSrc = src++ const line = document.createElement('div')+ line.className = 'sp-remote-line'+ line.textContent = t('Image from {host}', { host: remoteHost(src) })+ box.appendChild(line)++ const why = document.createElement('div')+ why.className = 'sp-remote-why'+ why.textContent = t('Not loaded — opening it would tell that site you opened this space.')+ box.appendChild(why)++ const alt = String(b.alt ?? '')+ if (alt) {+ const a = document.createElement('div')+ a.className = 'sp-remote-alt'+ a.textContent = alt+ box.appendChild(a)+ }++ if (opts.editable !== false || opts.allowRemote) {+ const btn = document.createElement('button')+ btn.type = 'button'+ btn.className = 'sp-btn sp-remote-load'+ btn.textContent = t('Load this image')+ btn.dataset.loadRemote = src+ box.appendChild(btn)+ }+ return box+}++/**+ * A whole page, including its title. The OUTER wrapper stays ltr — scrollLeft+ * and every coordinate calculation change meaning under rtl — and the INNER+ * container carries the document's declared base direction.+ */+export function renderPage(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): HTMLElement {+ const art = document.createElement('article')+ art.className = 'sp-page'+ art.style.direction = 'ltr'++ const inner = document.createElement('div')+ inner.className = 'sp-page-inner'+ inner.dir = doc.theme.dir ?? 'ltr'+ if (doc.theme.measure) inner.style.maxWidth = `${doc.theme.measure}px`++ const h = document.createElement('h1')+ h.className = 'sp-title'+ h.dataset.pageTitle = page.id+ h.dir = 'auto'+ if (opts.editable) h.contentEditable = 'true'+ h.textContent = page.title+ inner.appendChild(h)++ inner.appendChild(renderBlocks(page, doc, opts))+ art.appendChild(inner)+ return art+}diff --git a/spaces/src/sanitize.ts b/spaces/src/sanitize.tsnew file mode 100644index 00000000..35cbadd1--- /dev/null+++ b/spaces/src/sanitize.ts@@ -0,0 +1,160 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Inline-html sanitizer + canonicalizer for block content.+//+// A block's `html` is INLINE ONLY. Block structure is `Block.type`, and the+// renderer emits the semantic tag — so a `<p>` or `<div>` inside a block's html+// is always a mistake, either a paste that smuggled structure in or a browser+// that inserted one during editing.+//+// This is a fork of slides' sanitizer, not a parameterisation, because the+// policies differ in BOTH directions: spaces must reject DIV/P (slides permits+// them) and spaces adds the suite's first attribute allowlist.++/** Inline tags a block may contain. Nothing here can carry block structure. */+const ALLOWED = new Set([+ 'B', 'I', 'U', 'S', 'EM', 'STRONG', 'CODE', 'BR', 'SPAN', 'MARK', 'SUB', 'SUP', 'A',+])++/**+ * The only attribute any tag may keep, and only on `A`.+ *+ * MATCHED AGAINST `getAttribute('href')`, NEVER the `.href` IDL property.+ *+ * `.href` returns the RESOLVED ABSOLUTE url, so from file:// the stored+ * `#p/abc` reads back as `file:///…/space.html#p/abc` and fails this test —+ * stripping every internal link — while on a static host it becomes+ * `https://…#p/abc` and passes. Measured. The bug would be invisible in the+ * environment an author develops in and total in the two environments the+ * format exists for (file://, and bento/tray on iOS).+ *+ * `#p/` is an intra-space page link. There is deliberately no second fragment+ * form: an undefined entry in this list is a one-way data hazard, because an+ * href written under a permissive build gets STRIPPED by a stricter later one,+ * silently, on the next edit that touches the block.+ */+const HREF_OK = /^(https?:|mailto:|#p\/)/i++/** Tags whose CONTENT should survive when the tag itself is dropped. */+const UNWRAP = new Set(['P', 'DIV', 'SECTION', 'ARTICLE', 'LI', 'UL', 'OL', 'H1', 'H2', 'H3', 'H4', 'BLOCKQUOTE', 'PRE', 'FONT'])++/**+ * Parse untrusted html into an INERT document, and never into a live element.+ *+ * `document.createElement('div').innerHTML = hostile` looks safe because the+ * div is detached. It is not: the elements it creates belong to the live+ * document, so their resources LOAD. `<img src="404" onerror="…">` runs its+ * handler from a div that was never inserted anywhere.+ *+ * Measured in the browser, 2026-08-03: detached div FIRES; `DOMParser`,+ * `<template>` and `createHTMLDocument` do not, and the markup survives intact+ * for cleaning either way.+ *+ * That made the sanitizer its own vector — it has to parse hostile markup+ * before it can strip it, so the payload ran BEFORE the strip, at render time,+ * on opening a space someone sent you. Every entry point for untrusted html+ * goes through here, which is why it is exported: `render.ts` needs it too.+ */+export function inertBody(html: string): HTMLElement {+ return new DOMParser().parseFromString(html, 'text/html').body+}++/**+ * Strip everything outside the allowlist, in place.+ *+ * Structure-carrying tags are UNWRAPPED (their text survives) rather than+ * deleted — losing a paragraph's words because it arrived wrapped in a `<p>`+ * would be the worst possible reading of "inline only".+ */+export function sanitizeInline(html: string): string {+ if (typeof document === 'undefined') return stripAllTags(html)+ const host = inertBody(html)++ const walk = (node: Node) => {+ for (const child of [...node.childNodes]) {+ if (child.nodeType === Node.TEXT_NODE) continue+ if (child.nodeType !== Node.ELEMENT_NODE) { child.remove(); continue }+ const el = child as HTMLElement+ const tag = el.tagName++ if (!ALLOWED.has(tag)) {+ walk(el)+ if (UNWRAP.has(tag)) {+ // a block boundary inside inline content becomes a space, not a join:+ // "<p>a</p><p>b</p>" must not become "ab"+ const needsGap = el.nextSibling || el.previousSibling+ while (el.firstChild) el.parentNode!.insertBefore(el.firstChild, el)+ // el.ownerDocument, not `document`: the host lives in the inert+ // parsed document now. Cross-document insert would work (DOM4 adopts+ // implicitly) but relying on that is a trap for the next edit.+ if (needsGap) el.parentNode!.insertBefore(el.ownerDocument.createTextNode(' '), el)+ }+ el.remove()+ continue+ }++ for (const attr of [...el.attributes]) {+ const keep = tag === 'A' && attr.name === 'href' && HREF_OK.test(attr.value)+ if (!keep) el.removeAttribute(attr.name)+ }+ // an <a> that lost its href is no longer a link — unwrap it+ if (tag === 'A' && !el.getAttribute('href')) {+ walk(el)+ while (el.firstChild) el.parentNode!.insertBefore(el.firstChild, el)+ el.remove()+ continue+ }+ // external links open away from the document; internal ones must not+ if (tag === 'A') {+ const href = el.getAttribute('href')!+ if (!href.startsWith('#')) { el.setAttribute('rel', 'noopener noreferrer'); el.setAttribute('target', '_blank') }+ }+ walk(el)+ }+ }+ walk(host)+ return host.innerHTML+}++/** No-DOM fallback (node tooling): drop every tag, keep the words. */+function stripAllTags(html: string): string {+ return html+ .replace(/<(p|div|br|li|h[1-6]|blockquote|pre)\b[^>]*>/gi, ' ')+ .replace(/<[^>]+>/g, '')+ .replace(/\s+/g, ' ')+ .trim()+}++/**+ * Canonical form, run at typing-run close (never mid-run — it would move the+ * caret).+ *+ * MUST BE IDEMPOTENT. A future materialize → DOM → re-serialize round trip+ * runs this again, and a canonicalizer that keeps changing its own output+ * would re-trip text merging on every keystroke.+ */+export function canonicalize(html: string): string {+ let out = sanitizeInline(html)+ // one pass of adjacent-run coalescing per tag, repeated to a fixed point so+ // <b>a</b><b>b</b><b>c</b> collapses fully+ for (let i = 0; i < 4; i++) {+ const before = out+ for (const tag of ['b', 'i', 'u', 's', 'em', 'strong', 'code', 'mark']) {+ out = out.replaceAll(`</${tag}><${tag}>`, '')+ }+ out = out.replace(/<(b|i|u|s|em|strong|code|mark)><\/\1>/g, '') // empty runs+ if (out === before) break+ }+ return out+}++/** Plain text of a block, for search and for markdown export. */+export function textOf(html: string | undefined): string {+ if (!html) return ''+ if (typeof document === 'undefined') return stripAllTags(html)+ return inertBody(html).textContent ?? ''+}++/** Escape for safe insertion as text. */+export const esc = (s: string): string =>+ s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')diff --git a/spaces/src/starter.ts b/spaces/src/starter.tsnew file mode 100644index 00000000..d0286c90--- /dev/null+++ b/spaces/src/starter.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// What a fresh bento/spaces file opens with.+//+// The brief slides set: the product demo, the launch asset and the feature+// tour in one — every claim it makes is proven by the feature making it. So+// the page that describes links CONTAINS a link, the page about sharing is+// reachable only through one, and the limits page says the awkward things out+// loud rather than letting them be discovered.++import { FORMAT, FORMAT_VERSION, defaultTheme, type SpacesDoc, type Block } from './model'++const b = (type: string, html = '', extra: Partial<Block> = {}): Block =>+ ({ id: `sd-${(seq++).toString(36)}`, type, html, ...extra })++let seq = 0++/** Deterministic ids: a generator must emit the same document twice. */+export function starterDoc(): SpacesDoc {+ seq = 0+ const P = {+ home: 'sd-home',+ links: 'sd-links',+ writing: 'sd-writing',+ limits: 'sd-limits',+ inbox: 'sd-inbox',+ }++ // the toggle is built first so its child can name its REAL id — a parent+ // pointing at an id that does not exist would render the child at top level+ const toggle = b('toggle', 'A toggle — click the triangle', { open: true })++ return {+ format: FORMAT,+ version: FORMAT_VERSION,+ docId: '', // minted at boot; a template mints a fresh one every open+ title: 'My space',+ home: P.home,+ theme: defaultTheme(),+ pages: [+ {+ id: P.home,+ title: 'Welcome',+ icon: 'compass',+ blocks: [+ b('p', 'This whole space — every page, the editor, the search — is <b>one HTML file</b>. No account, no server, nothing installed.'),+ b('h2', 'Try it'),+ b('todo', 'Type something on this line', { done: false }),+ b('todo', 'Press <code>⏎</code> to make a new block, <code>Tab</code> to indent it', { done: false }),+ b('todo', 'Press <code>/</code> on an empty line for headings, lists, quotes and code', { done: false }),+ b('todo', 'Press <code>⌘K</code> to search every page at once', { done: false }),+ b('p', 'Then press <code>⌘S</code>. The file on your disk now contains everything you just wrote.'),+ b('h2', 'What is here'),+ b('p', 'Three pages, and each one demonstrates the thing it describes:'),+ b('bullet', '<a href="#p/sd-links">Pages and links</a> — how a space holds more than one page'),+ b('bullet', '<a href="#p/sd-writing">Writing</a> — the blocks you can make'),+ b('bullet', '<a href="#p/sd-limits">Sharing & limits</a> — what this file can and cannot do'),+ b('p', 'The sidebar holds the whole tree. Drag a page onto another to nest it.'),+ ],+ },+ {+ id: P.links,+ title: 'Pages and links',+ icon: 'link',+ blocks: [+ b('p', 'A space is a <b>tree of pages</b>, not a single scroll. New page: the + in the sidebar, or <code>⌘⌥N</code>.'),+ b('h2', 'Linking'),+ b('p', 'Type <code>[[</code> anywhere to search your pages and drop a link in. If the page does not exist yet, the picker offers to make it.'),+ b('p', 'That link back to <a href="#p/sd-home">Welcome</a> was made exactly that way.'),+ b('h2', 'Backlinks'),+ b('p', 'Scroll to the bottom of any page and it tells you what links <i>to</i> it. Nothing to maintain — it is derived from the links themselves every time the page opens.'),+ b('p', 'This page links to <a href="#p/sd-writing">Writing</a>, so Writing lists this page underneath.'),+ b('h2', 'Why one file'),+ b('p', 'Links are page ids inside this document, so they resolve with the wifi off, from an email attachment, on a phone, and in ten years. A link between separate files could not do any of that.'),+ ],+ },+ {+ id: P.writing,+ title: 'Writing',+ icon: 'pen',+ blocks: [+ b('p', 'Markdown shortcuts convert as you type them.'),+ b('h2', 'Headings'),+ b('p', 'Type <code># </code>, <code>## </code> or <code>### </code> at the start of a line.'),+ b('h2', 'Lists'),+ b('bullet', '<code>- </code> makes a bullet'),+ b('bullet', 'and <code>Tab</code> nests it'),+ b('number', '<code>1. </code> makes a numbered list'),+ b('todo', '<code>[] </code> makes a checkbox', { done: false }),+ b('h2', 'Blocks that are not text'),+ b('quote', 'A quote — type <code>> </code>.'),+ b('code', 'const space = oneFile\n// ``` makes a code block', { lang: 'js' }),+ toggle,+ b('p', 'Anything indented under a toggle folds away with it.', { parent: toggle.id }),+ b('divider'),+ b('p', 'Inline: <b>⌘B</b>, <i>⌘I</i>, <u>⌘U</u>.'),+ ],+ },+ {+ id: P.limits,+ title: 'Sharing & limits',+ icon: 'scale',+ blocks: [+ b('p', 'Worth knowing before you rely on this.'),+ b('h2', 'Sharing is per file'),+ b('p', 'Sending someone this file sends them <b>the whole space</b> — every page, including any you archived. There is no per-page permission, because there is no server to enforce one.'),+ b('h2', 'Saving'),+ b('p', 'On Chrome and Edge, <code>⌘S</code> writes back to the file you opened. Everywhere else — Safari, Firefox, and every browser on iOS — the browser gives a page no way to write to its own file, so each save downloads a <b>new copy</b>. That is a browser limitation, not a setting.'),+ b('h2', 'Two people, two files'),+ b('p', 'If two people edit their own copy at the same time, there is no merge. They are two files. Live collaboration is coming; until it does, this is the honest position.'),+ b('h2', 'Size'),+ b('p', 'Text is essentially free — hundreds of pages of prose stay a small file. Images are what make it big, because they travel inside it.'),+ ],+ },+ {+ id: P.inbox,+ title: 'Inbox',+ icon: 'inbox',+ blocks: [+ b('p', 'A page to throw things into before they are worth filing.'),+ b('p', ''),+ ],+ },+ ],+ }+}diff --git a/spaces/src/store.ts b/spaces/src/store.tsnew file mode 100644index 00000000..739291ad--- /dev/null+++ b/spaces/src/store.ts@@ -0,0 +1,218 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Document state, undo history, and the TYPING RUN.+//+// Slides sidesteps commit granularity because canvas text commits on blur. A+// notes app may never blur, so this one policy sets undo granularity, autosave+// churn, the dirty flag, and later the collaboration op rate.+//+// A TYPING RUN is consecutive input in ONE block with no structural op between.+// It takes ONE checkpoint, at its first input; later inputs mutate in place. It+// closes on idle, on the caret leaving the block, on any structural change, on+// save, and on replaceDoc. One run = one undo entry = later, one text batch.++import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'++type Listener = () => void+type Event = 'doc' | 'page' | 'tree' | 'selection'++/** Idle that closes a run. Autosave debounces longer, so no snapshot lands mid-run. */+const RUN_IDLE_MS = 600+/** Undo is bounded by BYTES, not entries: at 200 pages, 100 whole-document+ * snapshots retain tens of MB. Assets are excluded from snapshots entirely. */+const UNDO_BUDGET = 24 * 1024 * 1024++interface Entry {+ json: string+ /** page in view when the entry was taken, so undo restores the view too */+ pageId: string+}++export class Store {+ doc: SpacesDoc+ index: SpaceIndex+ /** the page being viewed */+ pageId: string+ /** blocks currently selected at block level (Esc from text editing) */+ selection: string[] = []+ readOnly = false++ private undoStack: Entry[] = []+ private redoStack: Entry[] = []+ private listeners = new Map<Event, Set<Listener>>()+ private runBlock: string | null = null+ private runTimer: ReturnType<typeof setTimeout> | undefined++ constructor(doc: SpacesDoc) {+ this.doc = doc+ this.index = buildIndex(doc)+ this.pageId = homePage(doc)?.id ?? ''+ }++ // ---- events -------------------------------------------------------------+ on(ev: Event, fn: Listener): () => void {+ const set = this.listeners.get(ev) ?? new Set()+ set.add(fn)+ this.listeners.set(ev, set)+ return () => set.delete(fn)+ }++ emit(ev: Event): void {+ for (const fn of this.listeners.get(ev) ?? []) fn()+ }++ // ---- reads --------------------------------------------------------------+ get page(): Page | undefined {+ return this.index.page.get(this.pageId)+ }++ block(id: string): Block | undefined {+ return this.index.block.get(id)?.block+ }++ /** Pages in sidebar order: a depth-first walk of the page tree. */+ tree(parent = '', depth = 0): Array<{ page: Page; depth: number }> {+ const out: Array<{ page: Page; depth: number }> = []+ for (const p of this.index.children.get(parent) ?? []) {+ out.push({ page: p, depth })+ out.push(...this.tree(p.id, depth + 1))+ }+ return out+ }++ // ---- writes -------------------------------------------------------------+ /**+ * A structural change: one undoable step. Closes any open typing run first,+ * so the run's text and the structural edit never merge into one entry.+ */+ commit(mutate: () => void, opts: { structure?: boolean } = {}): void {+ if (this.readOnly) return+ this.endRun()+ this.checkpoint()+ mutate()+ this.reindex()+ this.emit('doc')+ if (opts.structure !== false) this.emit('tree')+ }++ /**+ * An input inside a typing run. The FIRST input in a block checkpoints;+ * every later one mutates in place.+ */+ runEdit(blockId: string, mutate: () => void): void {+ if (this.readOnly) return+ if (this.runBlock !== blockId) {+ this.endRun()+ this.checkpoint()+ this.runBlock = blockId+ }+ mutate()+ this.touch()+ clearTimeout(this.runTimer)+ this.runTimer = setTimeout(() => this.endRun(), RUN_IDLE_MS)+ }++ /** Close the current run, if any. Idempotent. */+ endRun(): void {+ clearTimeout(this.runTimer)+ if (!this.runBlock) return+ const id = this.runBlock+ this.runBlock = null+ this.emit('doc')+ void id+ }++ /** Model changed without a new undo entry (mid-run). */+ touch(): void {+ this.doc.modified = new Date().toISOString()+ this.reindex()+ }++ private reindex(): void {+ this.index = buildIndex(this.doc)+ if (!this.index.page.has(this.pageId)) this.pageId = homePage(this.doc)?.id ?? ''+ }++ // ---- history ------------------------------------------------------------+ private snapshot(): string {+ // assets are excluded: they are the largest thing in the document and never+ // change during an ordinary edit, so snapshotting them 100 times is waste+ const { assets: _assets, ...rest } = this.doc+ return JSON.stringify(rest)+ }++ checkpoint(): void {+ if (this.readOnly) return+ this.undoStack.push({ json: this.snapshot(), pageId: this.pageId })+ this.redoStack.length = 0+ let bytes = 0+ for (let i = this.undoStack.length - 1; i >= 0; i--) {+ bytes += this.undoStack[i].json.length+ if (bytes > UNDO_BUDGET) { this.undoStack.splice(0, i + 1); break }+ }+ }++ private restore(entry: Entry): void {+ const assets = this.doc.assets+ this.doc = { ...(JSON.parse(entry.json) as SpacesDoc), ...(assets ? { assets } : {}) }+ this.pageId = entry.pageId+ this.reindex()+ this.emit('doc')+ this.emit('tree')+ this.emit('page')+ }++ undo(): void {+ if (this.readOnly) return+ this.endRun()+ const entry = this.undoStack.pop()+ if (!entry) return+ this.redoStack.push({ json: this.snapshot(), pageId: this.pageId })+ this.restore(entry)+ }++ redo(): void {+ if (this.readOnly) return+ this.endRun()+ const entry = this.redoStack.pop()+ if (!entry) return+ this.undoStack.push({ json: this.snapshot(), pageId: this.pageId })+ this.restore(entry)+ }++ get canUndo(): boolean { return this.undoStack.length > 0 }+ get canRedo(): boolean { return this.redoStack.length > 0 }++ // ---- navigation ---------------------------------------------------------+ goToPage(id: string, opts: { push?: boolean } = {}): void {+ if (!this.index.page.has(id) || id === this.pageId) return+ this.pageId = id+ this.selection = []+ this.endRun()+ if (opts.push !== false && typeof history !== 'undefined') {+ // pushState with a FRAGMENT is legal from an opaque origin; pushState+ // with a PATH throws SecurityError there. Measured — this is why links+ // are fragments (docs/DECISIONS.md, 2026-08-03).+ try { history.pushState(null, '', `#p/${id}`) } catch { /* opaque origin edge */ }+ }+ this.emit('page')+ this.emit('tree')+ }++ select(ids: string[]): void {+ this.selection = ids+ this.emit('selection')+ }++ /** Replace the whole document — the AI round-trip and version restore path. */+ replaceDoc(next: SpacesDoc): void {+ this.endRun()+ this.checkpoint()+ this.doc = next+ this.reindex()+ this.pageId = homePage(next)?.id ?? ''+ this.emit('doc')+ this.emit('tree')+ this.emit('page')+ }+}diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 719ebb23..ad4269da 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -1,109 +1,493 @@-/* ————— bento/spaces chrome ————— */+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors+ bento/spaces chrome.++ Tokens, button shapes, menu shadows and radii are slides' (see+ slides/src/styles.css). Two apps in one suite that draw their chrome+ differently read as two products. What differs is only what the app IS: a+ reading column instead of a canvas. */+:root {--ink: #1e2a3a;- --muted: #6b7280;- --line: #e3e7ee;- --chrome: #f7f8fa;- --accent: #ff9e8a;+ --ink-2: #31445c;+ --chrome: #f5f7fa;+ --chrome-2: #eceff4;+ --line: #e3e8ef;+ --muted: #5b6472;+ --accent: #f7a600;+ --accent-ink: #7a5200;+ --blue: #5b8def;+ --radius: 10px;}-* { box-sizing: border-box; }+/* The editor chrome is LIGHT-ONLY, the same ruling slides made: on a dark-mode+ phone the engine renders NATIVE controls dark while our ink stays dark, so+ dropdowns read as blank. Pair with the color-scheme meta in index.html. */+:root { color-scheme: only light; }-body {- margin: 0;- background: #fff;+* { box-sizing: border-box; }+html, body {+ margin: 0; height: 100%;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;color: var(--ink);- font: 16px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;+ background: var(--chrome);+ overscroll-behavior: none;}+#app { height: 100%; }+:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; border-radius: 4px; }+select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; user-select: auto; }++/* ————— shell ————— */+.sp-app { height: 100%; display: flex; flex-direction: column; overflow: hidden; }.sp-bar {- display: flex;- align-items: center;- gap: 12px;- padding: 10px 18px;- border-bottom: 1px solid var(--line);- background: var(--chrome);- position: sticky;- top: 0;+ display: flex; align-items: center; gap: 6px;+ padding: 8px max(12px, env(safe-area-inset-right)) 8px max(12px, env(safe-area-inset-left));+ background: #fff; border-bottom: 1px solid var(--line);+ flex: 0 0 auto;+}+.sp-mark {+ font-weight: 700; font-size: 14px; letter-spacing: -0.01em;+ white-space: nowrap; padding-inline-end: 4px; user-select: none;}--.sp-mark { font-weight: 700; letter-spacing: -0.01em; }.sp-mark span { color: var(--accent); }+.sp-doctitle {+ flex: 1 1 auto; min-width: 0;+ font: inherit; font-size: 14px; font-weight: 600; color: var(--ink);+ background: transparent; border: 1px solid transparent;+ border-radius: 8px; padding: 5px 8px;+}+.sp-doctitle:hover { background: var(--chrome); }+.sp-doctitle:focus { background: #fff; border-color: var(--blue); outline: none; }+.sp-status {+ font-size: 12px; color: var(--muted); white-space: nowrap;+ opacity: 0; transition: opacity .18s;+}+.sp-status.sp-on { opacity: 1; }+.sp-spacer { flex: 1 1 auto; }++.sp-btn {+ display: inline-flex; align-items: center; gap: 6px;+ font: inherit; font-size: 13px; color: var(--ink-2);+ background: transparent; border: 1px solid transparent;+ border-radius: 8px; padding: 6px 9px; cursor: pointer; white-space: nowrap;+}+.sp-btn:hover { background: var(--chrome-2); }+.sp-btn:active { background: var(--line); }+.sp-btn svg { display: block; }+.sp-btn[disabled] { opacity: .45; cursor: default; }+.sp-primary { background: var(--ink); color: #fff; padding: 6px 14px; }+.sp-primary:hover { background: var(--ink-2); }+.sp-body { display: flex; flex: 1 1 auto; min-height: 0; }++/* ————— sidebar ————— */+.sp-side {+ flex: 0 0 244px; min-width: 0;+ border-inline-end: 1px solid var(--line); background: var(--chrome);+ overflow: auto; padding: 10px 8px max(16px, env(safe-area-inset-bottom));+}+.sp-side-head {+ display: flex; align-items: center; justify-content: space-between;+ padding: 2px 6px 8px;+}+.sp-side-title {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: 0.07em; color: var(--muted);+}+.sp-tree { list-style: none; margin: 0; padding: 0; }+.sp-tree li { position: relative; }+.sp-treelink {+ display: flex; align-items: center; gap: 7px;+ padding: 5px 8px; border-radius: 7px; color: var(--ink-2);+ text-decoration: none; font-size: 13.5px; line-height: 1.35;+}+.sp-treelink span {+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+.sp-treelink:hover { background: var(--chrome-2); }+.sp-treelink.sp-here { background: #fff; color: var(--ink); font-weight: 600; box-shadow: 0 1px 2px rgb(20 30 45 / .07); }+.sp-treelink.sp-drop { box-shadow: inset 0 0 0 2px var(--accent); }+.sp-tree-ico { flex: 0 0 auto; width: 16px; text-align: center; font-size: 13px; }+.sp-side-empty { color: var(--muted); font-size: 13px; padding: 10px; }++/* ————— the reading column ————— */+.sp-main {+ flex: 1 1 auto; overflow: auto; background: #fff;+ padding: 44px 28px 40vh;+}+.sp-page-inner { margin: 0 auto; }.sp-title {- flex: 1;- min-width: 0;- border: 1px solid transparent;- border-radius: 7px;- padding: 6px 8px;- font: inherit;- font-weight: 600;- background: transparent;- color: inherit;-}-.sp-title:hover { border-color: var(--line); }-.sp-title:focus { outline: none; border-color: var(--accent); background: #fff; }--.sp-bar button {- border: 1px solid var(--line);- background: #fff;- border-radius: 999px;- padding: 6px 14px;- font: inherit;- font-weight: 600;- cursor: pointer;+ font-size: 33px; line-height: 1.18; font-weight: 700;+ margin: 0 0 6px; letter-spacing: -0.02em;}-.sp-bar button:hover { background: var(--chrome); }+.sp-title:focus { outline: none; }+.sp-title[data-empty]::before { content: attr(data-ph); color: #b9c2ce; }+.sp-crumb { font-size: 12.5px; color: var(--muted); margin: 0 0 14px; display: flex; gap: 6px; align-items: center; }+.sp-crumb a { color: var(--muted); text-decoration: none; }+.sp-crumb a:hover { color: var(--ink); text-decoration: underline; }-.sp-ver { color: var(--muted); font-size: 12px; }+/* every block is a row with a hover gutter on its start edge */+.sp-b { position: relative; margin: 1px 0; padding: 3px 0; line-height: 1.65; }+.sp-gutter {+ position: absolute; inset-inline-start: -52px; top: 1px;+ display: flex; gap: 1px; opacity: 0; transition: opacity .12s;+}+.sp-b:hover > .sp-gutter, .sp-gutter:focus-within { opacity: 1; }+.sp-ghost {+ display: inline-flex; align-items: center; justify-content: center;+ width: 22px; height: 24px; padding: 0; border: 0; border-radius: 5px;+ color: #aab4c2; background: transparent; cursor: pointer;+}+.sp-ghost:hover { background: var(--chrome-2); color: var(--ink-2); }+.sp-ghost[draggable='true'] { cursor: grab; }+.sp-b.sp-dragging { opacity: .4; }+.sp-b.sp-dropline::after {+ content: ''; position: absolute; inset-inline: -8px; bottom: -2px; height: 2px;+ background: var(--blue); border-radius: 2px;+}-.sp-doc {- max-width: 720px;- margin: 0 auto;- padding: 40px 24px 30vh;+.sp-b-h1 { font-size: 25px; font-weight: 700; margin: 24px 0 2px; letter-spacing: -0.01em; }+.sp-b-h2 { font-size: 20px; font-weight: 700; margin: 20px 0 2px; }+.sp-b-h3 { font-size: 16.5px; font-weight: 700; margin: 16px 0 2px; }+.sp-b-quote {+ margin: 8px 0; padding: 2px 0 2px 15px;+ border-inline-start: 3px solid var(--line); color: var(--ink-2);}+.sp-b-divider { padding: 12px 0; }+.sp-b-divider hr { border: 0; border-top: 1px solid var(--line); margin: 0; }+.sp-list { margin: 2px 0; padding-inline-start: 24px; }+.sp-b-todo { list-style: none; margin-inline-start: -22px; }+.sp-b-todo.sp-done > .sp-text { text-decoration: line-through; color: var(--muted); }++.sp-b-todo, .sp-b-toggle { display: flex; align-items: flex-start; gap: 8px; }+/* a toggle's BODY is not a sibling column of its title — it wraps onto its own+ full-width line underneath, or the folded content sits beside the heading */+.sp-b-toggle { flex-wrap: wrap; }+.sp-b-todo > .sp-text, .sp-b-toggle > .sp-text { flex: 1 1 auto; }+.sp-check { flex: 0 0 auto; margin: 6px 0 0; accent-color: var(--ink); }-.sp-block {- margin: 0 0 14px;- padding: 4px 6px;- border-radius: 6px;- outline: none;+.sp-text { display: block; min-width: 1px; }+.sp-text:focus { outline: none; }+/* the prompt shows on the block you are IN, not on every empty one — a page of+ "Type / for blocks" reads as clutter, not as help */+.sp-text[data-empty]:focus::before { content: attr(data-ph); color: #b9c2ce; pointer-events: none; }++.sp-b-code pre {+ margin: 6px 0; padding: 12px 14px; overflow-x: auto;+ background: var(--chrome); border: 1px solid var(--line); border-radius: var(--radius);}-.sp-block:focus { background: var(--chrome); }-.sp-block:empty::before {- content: attr(data-placeholder);- color: var(--muted);+.sp-b-code code { font: 13px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }+.sp-b-code code:focus { outline: none; }++.sp-twist {+ flex: 0 0 auto; border: 0; background: transparent; color: var(--muted);+ cursor: pointer; padding: 3px 0 0; line-height: 1;+ transition: transform .14s;}+.sp-twist svg { display: block; }+.sp-twist[aria-expanded='true'] { transform: rotate(90deg); }+.sp-toggle-body { flex: 1 0 100%; padding-inline-start: 22px; }-.sp-recover {- position: fixed;- left: 50%;- bottom: 22px;- transform: translateX(-50%);- display: flex;- align-items: center;- gap: 10px;- background: #fff;- border: 1px solid var(--line);- box-shadow: 0 6px 24px rgb(20 30 45 / 0.14);- border-radius: 999px;- padding: 8px 10px 8px 16px;- font-size: 14px;-}-.sp-recover button {- border: 1px solid var(--line);+.sp-b-image figure { margin: 12px 0; }+.sp-b-image img { max-width: 100%; height: auto; border-radius: var(--radius); display: block; }+.sp-b-image figcaption { font-size: 13px; color: var(--muted); margin-top: 6px; }++.sp-pagecard {+ display: flex; align-items: center; gap: 9px;+ padding: 10px 12px; margin: 6px 0;+ border: 1px solid var(--line); border-radius: var(--radius);+ color: var(--ink); text-decoration: none; font-weight: 600; font-size: 14px;background: #fff;- border-radius: 999px;- padding: 5px 12px;- font: inherit;- cursor: pointer;}+.sp-pagecard:hover { background: var(--chrome); }+.sp-pagecard.sp-dead { color: var(--muted); font-style: italic; font-weight: 400; }++.sp-page a { color: var(--ink); text-decoration: underline; text-decoration-color: rgb(247 166 0 / .55); text-underline-offset: 2px; }+.sp-page a:hover { text-decoration-color: var(--accent); }++/* ————— backlinks ————— */+.sp-backlinks { padding-top: 16px; border-top: 1px solid var(--line); margin-top: 54px; }+.sp-backlinks:empty { display: none; }+.sp-backlinks-h {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: 0.07em; color: var(--muted); margin: 0 0 8px;+}+.sp-backlink-list { list-style: none; margin: 0; padding: 0; }+.sp-backlink-list li { margin: 5px 0; font-size: 13.5px; }+.sp-backlink-list a { font-weight: 600; text-decoration: none; color: var(--ink); }+.sp-backlink-list a:hover { text-decoration: underline; }+.sp-snippet { color: var(--muted); margin-inline-start: 8px; }++/* ————— menus + overlays ————— */+.sp-overlay {+ position: fixed; inset: 0; background: rgb(20 30 45 / .34);+ display: flex; align-items: flex-start; justify-content: center;+ padding-top: 11vh; z-index: 60;+}+.sp-card {+ width: min(560px, 92vw); max-height: 72vh; overflow: auto;+ background: #fff; border: 1px solid var(--line); border-radius: var(--radius);+ box-shadow: 0 18px 48px rgb(20 30 45 / .22); padding: 12px;+}+.sp-card-h {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: 0.07em; color: var(--muted); margin: 2px 4px 8px;+}+.sp-find {+ width: 100%; font: inherit; font-size: 14px; padding: 9px 11px; color: var(--ink);+ background: #fff; border: 1px solid var(--line); border-radius: 8px;+}+.sp-find:focus { border-color: var(--blue); outline: none; }+.sp-results { list-style: none; margin: 8px 0 0; padding: 0; }+.sp-result {+ display: flex; align-items: center; gap: 10px;+ width: 100%; text-align: start; font: inherit; color: var(--ink);+ background: transparent; border: 0; border-radius: 7px; padding: 8px 10px; cursor: pointer;+}+.sp-result:hover, .sp-result.sp-sel { background: var(--chrome-2); }+.sp-result-ico { flex: 0 0 auto; color: var(--muted); display: flex; }+.sp-result-txt { min-width: 0; }+.sp-result strong { display: block; font-size: 14px; font-weight: 600; }+.sp-result span {+ display: block; color: var(--muted); font-size: 12.5px;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+.sp-result.sp-new { color: var(--blue); }+.sp-noresult { color: var(--muted); padding: 12px 10px; font-size: 13.5px; }+.sp-arch { color: var(--muted); font-size: 11px; font-style: normal; }++/* the block menu is anchored to the caret, not centred on the screen */+.sp-pop {+ position: fixed; z-index: 60; width: 260px; max-height: 44vh; overflow: auto;+ background: #fff; border: 1px solid var(--line); border-radius: var(--radius);+ box-shadow: 0 12px 34px rgb(20 30 45 / .2); padding: 6px;+}++/* ————— banners + gates ————— */+.sp-banner {+ display: flex; align-items: center; gap: 10px; padding: 8px 14px;+ background: #fff6dd; color: var(--accent-ink);+ border-bottom: 1px solid rgb(247 166 0 / .35); font-size: 13.5px;+}+.sp-banner .sp-btn { color: var(--accent-ink); border-color: rgb(122 82 0 / .25); }+.sp-gate { position: fixed; inset: 0; display: grid; place-items: center; padding: 24px; background: var(--chrome); }+.sp-gate-card {+ max-width: 620px; background: #fff; padding: 26px;+ border: 1px solid var(--line); border-radius: var(--radius);+ box-shadow: 0 14px 40px rgb(20 30 45 / .12);+}+.sp-gate-card h1 { font-size: 21px; margin: 0 0 8px; letter-spacing: -0.01em; }+.sp-gate-card p { color: var(--muted); margin: 0 0 16px; font-size: 14px; }+.sp-gate-card .sp-btn { margin-inline-end: 8px; }+.sp-gate-card .sp-find { margin-bottom: 12px; }+.sp-gate-raw {+ margin-top: 16px; padding: 12px; max-height: 30vh; overflow: auto;+ background: var(--chrome); border: 1px solid var(--line); border-radius: 8px;+ font: 12px/1.5 ui-monospace, monospace; white-space: pre-wrap; color: var(--muted);+}+.sp-empty { color: var(--muted); }-.sp-gate {- max-width: 460px;- margin: 22vh auto;- text-align: center;- padding: 0 24px;+/* ————— about ————— */+.sp-about .sp-card-h { margin-top: 20px; }+.sp-about .sp-card-h:first-child { margin-top: 2px; }+.sp-about-blurb { margin: 0 4px 10px; font-size: 14px; }+.sp-note { color: var(--muted); font-size: 12.5px; margin: 6px 4px 10px; line-height: 1.55; }+.sp-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 4px; font-size: 14px; }+.sp-select { font: inherit; font-size: 13px; padding: 6px 8px; color: var(--ink); background: #fff; border: 1px solid var(--line); border-radius: 8px; }+.sp-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px 4px; }+.sp-mono { font: 12.5px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); }++/* ————— phone ————— */+.sp-menu { display: none; }+@media (max-width: 820px) {+ .sp-menu { display: inline-flex; }+ /* The drawer is simply absent until asked for. An animated off-canvas panel+ is nicer, and two attempts at one (a logical inset, then a transform) both+ failed to move under measurement — so this ships the version whose+ behaviour is obvious from the rule. A slide-in can come back with a test+ that proves it. */+ .sp-side { display: none; }+ .sp-side.sp-open {+ display: block; position: fixed; inset: 0 auto 0 0; width: 268px;+ z-index: 50; box-shadow: 0 0 50px rgb(20 30 45 / .3);+ padding-top: max(14px, env(safe-area-inset-top));+ }+ [dir='rtl'] .sp-side.sp-open { inset: 0 0 0 auto; }+ .sp-scrim { position: fixed; inset: 0; background: rgb(20 30 45 / .3); z-index: 45; }+ .sp-main { padding: 26px 18px 45vh; }+ .sp-gutter { display: none; } /* no hover on touch; long-press later */+ .sp-title { font-size: 27px; }+}++/* ————— print: the only export-to-PDF path, so it is a contract ————— */+@media print {+ .sp-bar, .sp-side, .sp-banner, .sp-gutter, .sp-scrim { display: none !important; }+ .sp-main { overflow: visible; padding: 0; background: #fff; }+ .sp-toggle-body[hidden] { display: block !important; } /* toggles print OPEN */+ .sp-b-h1, .sp-b-h2, .sp-b-h3, .sp-title { break-after: avoid; }+ .sp-b-code, .sp-b-image figure, .sp-b-quote { break-inside: avoid; }+ p, li { orphans: 2; widows: 2; }+}++/* ————— topbar dropdowns ————— */+.sp-dd { position: relative; }+.sp-ddmenu {+ display: none; position: absolute; top: calc(100% + 5px); inset-inline-start: 0;+ min-width: 250px; flex-direction: column; z-index: 60;+ background: #fff; border: 1px solid var(--line); border-radius: var(--radius);+ box-shadow: 0 12px 34px rgb(20 30 45 / .2); padding: 5px;+}+.sp-dd.sp-open .sp-ddmenu { display: flex; }+.sp-dd:last-child .sp-ddmenu { inset-inline-start: auto; inset-inline-end: 0; }+.sp-dditem {+ display: flex; align-items: center; gap: 10px; width: 100%;+ text-align: start; font: inherit; color: var(--ink);+ background: transparent; border: 0; border-radius: 7px;+ padding: 7px 9px; cursor: pointer;+}+.sp-dditem:hover { background: var(--chrome-2); }+.sp-dditem strong { display: block; font-size: 13.5px; font-weight: 600; }+.sp-dditem span span { display: block; color: var(--muted); font-size: 12px; }+.sp-caret .sp-btn { padding: 6px 5px; }+.sp-panel-toggle { display: inline-flex; }++/* ————— page icon ————— */+.sp-pageicon {+ display: inline-flex; align-items: center; justify-content: center;+ width: 34px; height: 34px; margin: 0 0 6px -4px; padding: 0;+ color: var(--muted); background: transparent;+ border: 1px solid transparent; border-radius: 8px; cursor: pointer;+}+.sp-pageicon:hover { background: var(--chrome-2); color: var(--ink); }+.sp-pageicon svg { width: 22px; height: 22px; }+.sp-iconpop { width: 232px; display: flex; flex-wrap: wrap; gap: 2px; }+.sp-iconopt {+ display: inline-flex; align-items: center; justify-content: center;+ width: 40px; height: 38px; padding: 0; color: var(--ink-2);+ background: transparent; border: 0; border-radius: 7px; cursor: pointer;+}+.sp-iconopt:hover { background: var(--chrome-2); }+.sp-tree-ico svg { width: 15px; height: 15px; display: block; }+.sp-tree-ico { display: flex; align-items: center; justify-content: center; color: var(--muted); }+.sp-treelink.sp-here .sp-tree-ico { color: var(--ink); }++/* ————— print sheet ————— */+.sp-choices { display: flex; gap: 8px; margin: 4px 0 12px; }+.sp-choice {+ flex: 1 1 0; text-align: start; font: inherit; color: var(--ink);+ background: #fff; border: 1px solid var(--line); border-radius: var(--radius);+ padding: 10px 12px; cursor: pointer;+}+.sp-choice:hover { background: var(--chrome); }+.sp-choice.sp-sel { border-color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); }+.sp-choice strong { display: block; font-size: 13.5px; }+.sp-choice span { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; }+.sp-optlist { display: flex; flex-direction: column; gap: 4px; margin-bottom: 6px; }+.sp-opt { display: flex; align-items: flex-start; gap: 9px; padding: 6px 4px; cursor: pointer; }+.sp-opt input { margin-top: 3px; accent-color: var(--ink); }+.sp-opt strong { display: block; font-size: 13.5px; font-weight: 500; }+.sp-opt span span { display: block; color: var(--muted); font-size: 12px; }++/* ————— print output ————— */+.sp-printroot { display: none; }+.sp-toc { break-after: page; }+.sp-toc-h { font-size: 26px; margin: 0 0 14px; }+.sp-toc-list { list-style: none; margin: 0; padding: 0; }+.sp-toc-list li { padding: 3px 0; border-bottom: 1px dotted var(--line); font-size: 14px; }+@media print {+ body.sp-printing > *:not(.sp-printroot) { display: none !important; }+ body.sp-printing .sp-printroot { display: block; }+ .sp-printroot .sp-page { break-after: page; }+ .sp-printroot .sp-page:last-child { break-after: auto; }+ .sp-printroot .sp-pageicon, .sp-printroot .sp-backlinks { display: none; }+ @page { margin: 18mm 16mm; }+}++/* ————— images ————— */+.sp-b-image { position: relative; }+.sp-imgtools {+ position: absolute; top: 8px; inset-inline-end: 8px;+ display: flex; gap: 4px; opacity: 0; transition: opacity .12s;+}+.sp-b-image:hover .sp-imgtools, .sp-imgtools:focus-within { opacity: 1; }+.sp-imgtools .sp-btn {+ background: rgb(255 255 255 / .94); border-color: var(--line);+ font-size: 12px; padding: 4px 8px;+ box-shadow: 0 2px 8px rgb(20 30 45 / .12);+}+.sp-imgtools .sp-badge { color: var(--accent-ink); }+.sp-b-image figure { position: relative; }+.sp-page.sp-filedrop { outline: 2px dashed var(--blue); outline-offset: 8px; border-radius: var(--radius); }++/* ————— page rows: the options button ————— */+.sp-treelink { position: relative; padding-inline-end: 26px; }+.sp-rowmore {+ position: absolute; inset-inline-end: 3px; top: 50%; transform: translateY(-50%);+ display: inline-flex; align-items: center; justify-content: center;+ width: 20px; height: 20px; padding: 0; border: 0; border-radius: 5px;+ color: var(--muted); background: transparent; cursor: pointer; opacity: 0;+}+.sp-treelink:hover .sp-rowmore, .sp-rowmore:focus { opacity: 1; }+.sp-rowmore:hover { background: rgb(20 30 45 / .1); color: var(--ink); }+.sp-rowmore svg { width: 14px; height: 14px; }++/* ————— archived ————— */+.sp-archived { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 8px; }+.sp-archived summary {+ font-size: 11px; font-weight: 600; text-transform: uppercase;+ letter-spacing: 0.07em; color: var(--muted); cursor: pointer;+ padding: 4px 6px; list-style: none;+}+.sp-archived summary::-webkit-details-marker { display: none; }+.sp-archived summary::before { content: '▸ '; }+.sp-archived[open] summary::before { content: '▾ '; }+.sp-arch-row { opacity: .72; }+.sp-arch-row:hover { opacity: 1; }++/* ————— find bar ————— */+.sp-findbar {+ position: absolute; top: 54px; inset-inline-end: 18px; z-index: 55;+ display: flex; align-items: center; gap: 6px; padding: 7px;+ background: #fff; border: 1px solid var(--line); border-radius: var(--radius);+ box-shadow: 0 12px 34px rgb(20 30 45 / .2);+}+.sp-findbar .sp-find { width: 190px; padding: 6px 9px; font-size: 13.5px; }+.sp-findcount { font-size: 12px; color: var(--muted); min-width: 68px; text-align: center; }+.sp-b.sp-hit { background: rgb(247 166 0 / .22); border-radius: 4px; transition: background .5s; }++/* ————— reading view ————— */+.sp-app.sp-reading .sp-main { padding-top: 56px; }+.sp-app.sp-reading .sp-doctitle { pointer-events: none; }+.sp-btn.sp-on { background: var(--chrome-2); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line); }+.sp-app.sp-reading .sp-page-inner { font-size: 17px; }+.sp-app.sp-reading .sp-title { margin-bottom: 18px; }++/* A remote image that has not been loaded. Deliberately quiet and boxy — it+ holds the place without pretending to be the picture. */+.sp-remote {+ border: 1px dashed var(--line);+ border-radius: 10px;+ padding: 18px 20px;+ background: var(--chrome-2);+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+}+.sp-remote-line { font-weight: 600; font-size: 14px; }+.sp-remote-why { font-size: 13px; color: var(--muted); max-width: 46ch; }+.sp-remote-alt { font-size: 13px; color: var(--muted); font-style: italic; }+.sp-remote-load {+ /* .sp-btn is transparent by design (the topbar is icon-only), so this one+ states itself: it asks the reader to make a decision. */+ margin-top: 6px;+ background: #fff;+ border-color: var(--line);+ color: var(--ink);+ font-weight: 550;+ padding: 7px 13px;}-.sp-gate h1 { font-size: 20px; margin: 0 0 8px; }-.sp-gate p { color: var(--muted); margin: 0; }+.sp-remote-load:hover { background: var(--chrome); border-color: var(--muted); }+/* Print shows the placeholder text, never a blank gap the reader can't explain. */+@media print { .sp-remote { border-color: #999; background: none; } .sp-remote-load { display: none; } }