Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento/spaces round 2: callouts, highlighting, import, the agent surface — and eleven defects (#237)

nyblnetfd55c8f85843
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2a1264b6..c32db79c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -117,6 +117,15 @@ jobs:
# build rather than shipping a half-translated interface.
run: node scripts/build-spaces-i18n.mjs --check
+ - name: Spaces shell size ceiling
+ # A budget nobody measures is a wish. DECISIONS.md set a 100KB ceiling,
+ # the round finished at 108KB, and the same entry claimed the ceiling
+ # was "checked per feature from here" while shipping no mechanism — so
+ # the breach was found by a reviewer reading the number rather than by
+ # the build that caused it. Raising the ceiling is fine and expected;
+ # raising it SILENTLY is what this stops.
+ run: node scripts/test-spaces-size.mjs
+
- name: Spaces model rig
# Properties that fail SILENTLY, and that a shipped file cannot be
# talked out of once it exists:
@@ -290,3 +299,16 @@ jobs:
- name: CRDT convergence rig
# 40 seeds locally; deeper on CI where the seconds are free.
run: SEEDS=300 node scripts/test-sync.ts
+
+ - name: CRDT equivalence rig (baseline vs candidate, byte for byte)
+ # Convergence is the weaker property: an engine that converges with
+ # ITSELF while minting different bytes than the shipped engine passes
+ # the step above and silently splits every bento/slides file in the
+ # field. This step asserts byte-identity instead.
+ #
+ # IT PASSES TRIVIALLY TODAY — there is one engine, so the candidate
+ # import resolves to the baseline module and the run announces itself
+ # as a NO-OP. The signal in a NO-OP run is the self-test: four
+ # perturbed-but-convergent engines that this rig must catch. It goes
+ # live the moment sync parameterization repoints one import.
+ run: SEEDS=200 STEPS=60 ACTORS=4 node scripts/test-sync-equiv.ts
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index faca69e0..5a89776c 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,28 @@ Decision. Why. Pointers.
---
+## 2026-08-03 — Sync parameterization is gated on BYTE equivalence, not convergence
+
+Making `slides/src/sync/` serve spaces (`doc.pages[] → page.blocks[]`) by
+parameterizing it over a document-shape descriptor is the agreed approach — but
+`scripts/test-sync.ts` cannot police it. It proves CONVERGENCE: replicas of the
+SAME engine agree. An engine that converges beautifully with itself while
+minting different ops, position keys or lamport stamps than the shipped one
+sails straight through it, and then every bento/slides file in the field —
+each carrying persisted `SyncStateJSON` and talking to the deployed relay —
+silently splits from its own copies, unfixably.
+
+So the gate is `scripts/test-sync-equiv.ts`: run baseline and candidate off one
+seeded PRNG stream and assert the emitted BYTES are identical (op batches with
+field order, `SyncStateJSON`, materialized doc), per step, per actor, plus a
+scripted suite for `adopt`/`mergeSnapshot`/`fromJSON`/`missingFor`. It carries
+four convergent-but-different mutant engines as a self-test, because it passes
+trivially until the candidate import is repointed and a comparator that has
+never failed proves nothing. **No parameterization work merges without this rig
+green in LIVE mode.** Fixtures now live in `scripts/lib/sync-fixtures.ts`,
+shared by both rigs, so the two never drift into different opinions of what an
+edit is. Wired into CI beside the convergence rig.
+
## 2026-08-02 — dash budgets BYTES with consent, not rows with a refusal
**Supersedes the hard stop proposed in the dash design doc §3.2** (refuse at
@@ -1253,6 +1275,93 @@ 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 the
path the release publishes to.
+## 2026-08-03 — bento/spaces: the format decisions that must precede parallel work
+
+Five independent design reviews of bento/spaces proposed overlapping feature
+sets. Most of it is schedulable in any order. These are not: each is a place
+where two workstreams would otherwise invent conflicting PERMANENT shapes for
+the same thing, and the format has no server and no migration. Settled here so
+nobody has to guess. Nothing below ships this round except where noted.
+
+**1. Properties, tags and table columns are BLOCKS — never keys on `Page`.**
+Three reviews proposed three incompatible shapes for the same data: prefixed
+keys on the page (`p:status`), a `prop` block, and `Page.tags: string[]`.
+Ruling: `{ type: 'prop', key, value, vt, html }`. A `prop` block degrades
+losslessly on an older build — render.ts's `default:` branch renders its html —
+whereas an unknown `col:` key on a Page renders as *nothing at all* and is
+invisible to search, find-and-replace, undo and the block registry, all of
+which iterate `page.blocks`. Tags stay literal text in `html` with a derived
+index; no `page.tags` array. A markdown importer preserves YAML front matter as
+a `code` block with `lang: 'yaml'` and never invents `page.meta`.
+
+**2. Containers are one mechanism, declared once.** Tables, callouts and
+columns are all "a block that holds blocks", and three agents each generalising
+`renderBlocks`' host stack would make render.ts the conflict magnet
+PARALLEL-WORK names by name. The contract: `container: true` in the BlockSpec;
+a container gets NO gutter and NO inline text host (inside a `<tr>` either one
+fabricates a phantom cell); a child whose parent chain does not resolve renders
+as a plain block, never a stray `<td>`; and list grouping resets at every
+container boundary, or a bullet before a table adopts the first bullet after it.
+
+**3. A render-time transform may never decorate EDITABLE content.** The
+rendered DOM *is* the model here: editor.ts:575 writes `b.html =
+host.innerHTML` on every input. So any injected decoration is captured into the
+file on the next keystroke — and then the allowlist deletes it. Verified:
+sanitize.ts removes an element that is in neither ALLOWED nor UNWRAP *together
+with its children* (the child-lifting happens only inside the UNWRAP branch),
+so a rendered `<math>` costs both the rendering and the source text. Rule:
+render-time transforms are gated on `opts.editable === false`, or use the CSS
+Custom Highlight API, which touches no DOM. Slides solved the same problem by
+swapping the raw token back while editing; spaces has no equivalent and must
+not grow one by accident. This binds tag chips, inline math, mention
+highlighting and pasted-markup decoration.
+
+**4. `#p/<page>/<block>` is a legal href, tolerated from today.** Shipped in
+this round — see the commit that made `resolveAnchor` the one resolver. It
+could not wait: sanitize.ts's allowlist already admits the two-segment form, so
+such links can arrive in a file this build did not write, and its own comment
+records why a NEW fragment form can never be added later (a stricter build
+strips it on the next edit that touches the block). Addressing — actually
+scrolling to the block — comes whenever it comes; tolerance had to be now.
+
+**5. `Page.stencil`, not `Page.template`.** `SpacesDoc.template` is declared
+and documented in two comments as "re-mint docId on every open", and
+implemented by nothing. Page-level templates get the name `stencil` so the two
+meanings can never collide, and `doc.template` must either be implemented or
+have its comments deleted. A dead field with a documented meaning is more
+dangerous than an undocumented one.
+
+**6. The effective-parent rule.** A block's effective parent is `b.parent` iff
+that block exists in the same page's array AND appears strictly earlier in it;
+otherwise the block is a root block. Same for pages. This is total (nothing
+vanishes), acyclic by construction (every effective edge points backwards in
+the materialised order), orphan-free, and — the point — a pure READ-TIME
+function that mutates nothing, so two replicas that agree on the array agree on
+the tree. It is what makes concurrent re-parenting safe under collaboration
+without restricting what anyone can drag, and `renderBlocks`' host stack
+already implements a narrower version of it.
+
+**Shell ceiling for the round: 100KB compressed** (from 73KB). Spaces is 1/8th
+of slides' size and that is a feature, not an accident.
+
+*Amended 2026-08-04, after the round landed at 105KB.* Callouts (+4), syntax
+highlighting (+5), markdown import (+15) and the agent surface (+8) came in 5KB
+over. Raised to **110KB** rather than trimmed, and the reasoning is recorded so
+the next person can disagree with it: import is the migration path and is worth
+more than its bytes; the agent surface is the "designed for AI" claim made
+executable rather than asserted; and at 105KB spaces is still a fifth of
+slides. What is NOT allowed is discovering the breach at release time — the
+ceiling is checked per feature from here, and the next one has 5KB, not 5KB and
+a shrug.
+
+*Corrected 2026-08-04, same day.* That sentence shipped with NO MECHANISM
+behind it, and a reviewer found the gap by reading the number rather than the
+build failing. It is real now: `scripts/size-budgets.json` holds the ceiling,
+`scripts/test-spaces-size.mjs` enforces it, and CI runs it. Raising the ceiling
+is expected; raising it SILENTLY is what the check stops — the budget moves in
+the commit that spends the bytes, where a reviewer can see it. Recording an
+intention and calling it a rule is how the 100KB ceiling got missed at all.
+
## 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
@@ -1578,3 +1687,205 @@ feature that genuinely cannot be core (a licence that forbids bundling, or bytes
that dwarf the shell even after a first-party rewrite), or a demonstrated need
for third-party authorship. Absent those, the answer to "should this be an
extension?" is "should this be core, a separate artifact, or a skill?"
+
+## 2026-08-03 — Callout tones are GitHub's five, and the tone is never hue alone
+
+**Decision.** `bento/spaces` gains a `callout` block whose `tone` is one of
+`note` `tip` `important` `warning` `caution` — GitHub's alert vocabulary,
+spelled the way GitHub spells it. That makes markdown export the identity
+function (`tone` ⇄ `> [!TONE]`) instead of a mapping table, and a mapping table
+is exactly the kind of thing that can be got wrong once and then never
+corrected, because the wrong tone is already in files on disks.
+
+**Five, and no `success`.** Docusaurus's set (note/tip/info/warning/danger) and
+MkDocs' thirteen were the alternatives. The format is additive, so a sixth tone
+can be added later — this build renders an unknown one neutrally, labels it with
+its own word and preserves the string — while removing or renaming one is
+impossible. When the decision is one-way, ship the smaller set.
+
+**The icon is DERIVED from the tone, with an optional stored override.** Storing
+it always would freeze today's glyphs into every document written today and let
+the tone and the mark disagree (a "warning" wearing 🎉). The override exists
+because a celebration is a callout too, and it never changes what the tone
+means, in the styling or in the export.
+
+**Meaning is carried by shape and by a word, never by hue.** Each tone's mark is
+a different silhouette (circle, bulb, square, triangle, octagon) and its name is
+rendered beside it as real text, translated. The tints are decoration: amber,
+red and green are precisely the hues most colour-blind readers cannot separate,
+and print drops backgrounds by default anyway. Body text stays `--ink`, not the
+tone colour — a box exists to make a sentence more readable, not less.
+
+**Nesting is a registry fact now.** `BlockSpec.container` is `'fold'` (toggle) or
+`'always'` (callout); `render.ts` opens a body element from that rather than
+testing for the type name, and `mdQuoteChildren` drives the `> ` marker every
+descendant line needs (a GitHub alert ends at the first line without one, and
+a blank line between two blocks of one alert closes the box). ⏎ inside a callout
+puts the next line INSIDE it and ⌫ on an empty line takes you out — deliberately
+not extended to `toggle`, because a fold can be shut and a caret inside a shut
+fold is a lost line.
+
+Details: `spaces/src/blocks.ts` (the registry entry, `CALLOUT_TONES`,
+`mdLayout`), `spaces/src/render.ts` (`toneLabel`), and the callout section of
+`scripts/test-spaces-model.ts`.
+## 2026-08-03 — Code highlighting is in-house, offsets-only, and render-time
+
+**Decision.** `bento/spaces` highlights code with its own ~350-line lexer
+(`spaces/src/highlight.ts`), not a library, in eight languages: JavaScript,
+TypeScript, Python, Shell, JSON, YAML, SQL, HTML/XML, CSS. Everything else
+renders plain, deliberately.
+
+**Why no library.** highlight.js is ~120KB and the useful subset of Prism is
+~30KB+; the whole spaces shell was 72KB compressed. Either is the largest thing
+in a product whose premise is that you can mail the file. Measured after
+shipping ours: the lexer + painter + chip + palette cost **4.0KB compressed**,
+and all eight vocabularies together a further **1.4KB** — ~180 bytes per
+language, because keyword lists are lowercase ASCII and deflate eats them. So
+the machinery is the cost and languages are nearly free, which inverts the
+instinct to "support fewer languages to save space". It also means the honest
+reason to stop at eight is testing, not bytes.
+
+**Which eight.** What a working notebook accumulates — shell one-liners, a
+config file, a snippet from the codebase — not a survey of languages. Adding a
+curly-brace language is one keyword list; resist it anyway, because a language
+nobody tested renders *nearly* right, which is worse than the plain fallback.
+An unknown tag is kept verbatim in `lang`, so a `rust` block round-trips,
+exports as ```` ```rust ````, and lights up by itself if the lexer learns it.
+
+**THE TOKENIZER RETURNS OFFSETS, NEVER STRINGS.** A token is `{kind, a, b}` into
+the caller's text and the tokens partition `[0, len)` exactly. That is the
+security property, not tidiness: code in a space is text someone mailed you, and
+a highlighter that cannot produce a character cannot produce markup, whatever
+the input does. The painter walks the ranges and builds nodes with
+`createTextNode`; there is no constructed markup string anywhere in the path and
+therefore no escaper to get wrong — which is how every other highlighter on the
+web does it, and why they all need one. `scripts/test-spaces-model.ts` asserts
+the partition across every language over a corpus that includes `</script>`,
+`<img onerror>`, unterminated strings and lone backslashes.
+
+**Colour never enters the document.** `Block.html` stays the html-escaped plain
+text it always was, so the same block is the same bytes whether or not the
+reading build can highlight it, and reading view and print get their colour from
+the same `renderBlock` call the editor uses. The editor's code host is therefore
+read as `textContent` (not `innerHTML`, which now contains the colour spans) and
+written through `sanitize.ts escText`, which escapes `&`, `<`, `>` and *not* `"`
+— matching the html serializer exactly, so an untouched block never serializes
+differently from the save before it.
+
+**Highlighting a live contenteditable: reconcile, do not replace.** The painter
+diffs the token stream against the existing child nodes and mutates only what
+differs. The point is that on `input` the browser has ALREADY applied the
+keystroke, so re-tokenising usually yields byte-identical nodes: measured in
+Chrome on the built shell, typing in the middle of a line produced **one
+`characterData` mutation (the browser's own) and zero `childList` mutations**,
+and the caret moved 76 → 77 — untouched rather than restored. Only a keystroke
+that moves a token boundary restructures anything; typing `"` produced
+`childList` records and the caret went 79 → 80, restored by character offset.
+An explicit save/restore on every keystroke would have been simpler and wrong:
+assigning `Text.data` is specified to collapse a live range inside it to offset
+0, so the restore has to exist — it just must not be the common path. IME
+composition is skipped until `compositionend`; the model keeps up regardless.
+
+**Found while building this: every markdown trigger was dead.** A space typed at
+the end of a contenteditable line is inserted as U+00A0 so it cannot collapse.
+Measured: after typing `## `, `host.textContent` is `['#','#',160]`, so
+`/^## $/` never matched — `# `, `- `, `1. `, `> `, `[] ` and `--- ` had never
+fired since 0.1.0. `autoformat` now normalises the NBSP before testing (never in
+the model). This surfaced because the ```` ```lang ```` fence needs the same
+trailing space; the bare ```` ``` ```` trigger was changed to be
+space-completed, both for consistency with every other rule in that table and
+because there is no keystroke left to type the language into otherwise.
+
+**A trailing newline in an edited code block is Chrome, and it is bounded.**
+Measured on a bare `pre-wrap` contenteditable with no Bento code involved:
+inserting multi-line text yields one trailing `\n` (the caret placeholder), and
+it does not accumulate — seeded with `abc\n` and typed into, the result is
+`abcy\n`, still one. Left alone; the previous `innerHTML` read produced the same
+byte.
+## 2026-08-03 — Imported frontmatter is kept verbatim, not turned into properties
+
+**Decision.** `spaces/src/markdown.ts` puts a note's leading `---` YAML into a
+`code` block with `lang: 'yaml'` and `frontmatter: true`, nested inside a
+collapsed `toggle` at the top of the page. Nothing in it is parsed, and no key
+becomes a document field. The page title comes from a leading `# Heading` or
+else from the FILE NAME — never from a `title:` key.
+
+**Why not properties.** Spaces has no properties model, and this is the first
+feature that meets one. A schema invented inside an importer would be derived
+from whichever keys one person's vault happens to use (`tags`, `aliases`,
+`cssclass`, `publish`), and once files carry it there is no server to migrate
+them: the format is permanent. That would settle a design by accident, in the
+one place with the least information about it.
+
+**Why verbatim beats dropping or hiding it.** The yaml is the author's text and
+some of it is load-bearing (`aliases`, `permalink`). Kept as a code block it is
+visible, searchable by ⌘K and ⌘F, printable (toggles always print open), and it
+exports back out as a fenced yaml block. `frontmatter: true` is an additive
+marker, which is what makes the eventual adoption a mechanical sweep — find the
+marked blocks, parse them then, delete the toggle — rather than an archaeology
+exercise over prose.
+
+**Why the title ignores `title:`.** `[[wikilinks]]` resolve by FILE NAME, which
+is what Obsidian, Foam and Logseq all do. A title taken from frontmatter that
+disagrees with the file name produces a page nobody can link to by the name
+their other 300 notes use.
+
+**What would reopen this.** A properties model shipping. At that point these
+blocks are the migration input, and the marker is what makes them findable.
+## 2026-08-03 — The spaces agent surface: plans, tagged results, and a validator that stays quiet
+
+**Decision.** `window.bento` in bento/spaces gains `validate()`, `outline()`,
+`stats()` and the patch verbs `updateBlock`, `removeBlocks`, `moveBlock`,
+`updatePage`, `removePage` (`spaces/src/agent.ts`). Five rules were settled
+along the way, and each is the kind another agent could reasonably reverse.
+
+**A validator earns its severities by being silent.** The bar is not "few false
+positives", it is ZERO findings on the space every new file opens with —
+asserted in `scripts/test-spaces-model.ts`, which is the only baseline of
+"idiomatic" available. The corollary is what is NOT checked: unknown property
+names. Slides warns about them because its element schema is closed; here
+unknown fields are the mechanism by which a future build's data survives an
+older one, so warning about them would fire on documents working exactly as
+designed. An agent that gets warnings for good documents stops reading them.
+
+**Plan, then apply.** Every write verb returns `{ok, apply}` and the wrapper in
+`main.ts` runs `store.commit(apply)`. `commit` checkpoints undo BEFORE it
+mutates, so validating inside the commit would leave a refused patch with an
+undo entry that undoes nothing. Verified in the browser: three refusals of three
+kinds, then one undo, reaches the state before the last real edit. The split
+also makes the whole write path testable in node — no store, no DOM.
+
+**Tagged results for the new verbs; the old two keep their shapes.**
+`insertBlocks` (ids | null) and `newPage` (id | null) shipped in 0.1.0 and are
+in a published guide, so they stay. Everything added returns
+`{ok:false, err, detail}`, because "it did nothing and told you nothing" is the
+failure mode this whole surface exists to remove. For the same reason a patch
+naming `id` (or `blocks` on a page) is REFUSED rather than ignored.
+
+**An agent cannot write what the app could not have written.** `html` is
+sanitized on the way IN, not only on the way to the screen; a `code` block's
+html is escaped text instead (the renderer shows its textContent, so sanitizing
+would delete the sample being shown), and only when it carries live tags, which
+keeps a replayed patch from double-escaping. Values JSON cannot carry — a
+function, a Date, a Map, a cycle — are refused rather than vanishing at save.
+
+**A page is never left with zero blocks.** MEASURED in the built shell: a page
+with `blocks: []` renders 0 editable hosts, 0 gutters and 0 block nodes — the
+caret, the gutter and the `/` menu all hang off a block, so nobody can ever type
+in it, and the editor cannot produce one (`mergeBack` refuses at the first
+block). So `newPage` mints a paragraph as `model.newPage` always did,
+`removeBlocks` refills a page it empties, and `validate()` calls a zero-block
+page an ERROR. The old `bento.newPage()` created exactly this page.
+
+*Amended 2026-08-04.* That was measured against the EDITOR, which still
+cannot produce one. The markdown importer landed in the same tree and produced
+them freely — one per folder without a folder note, one per empty file, plus
+the invented root — and then navigated to one, so the first thing a vault
+import showed you was a page you could not put a caret in. An invariant proved
+for one writer is not proved for the next one; `planImport` now guarantees it
+too, at the single point where it returns.
+
+**Cost.** +8,040 bytes on the shipped shell (73,787 → 81,827; compressed
+payload 72KB → 79KB). Most of it is the finding messages, which are the
+product: a code with no explanation is not actionable. Anyone tempted to shrink
+this should shorten prose, not drop checks.
diff --git a/docs/spaces-agents.md b/docs/spaces-agents.md
index 910ab96e..db830898 100644
--- a/docs/spaces-agents.md
+++ b/docs/spaces-agents.md
@@ -71,8 +71,9 @@ unique ids the first time.
| `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 |
+| `callout` | `html`, `tone`, `icon` | a boxed note; blocks whose `parent` is its id are inside it |
| `quote` | `html` | `<blockquote>` |
-| `code` | `html` (plain text), `lang` | `<pre><code>` |
+| `code` | `html` (plain text), `lang` | `<pre><code>`, syntax-coloured |
| `divider` | — | `<hr>` |
| `image` | `src` (see below), `alt`, `caption`, `width` (10–100 **%**), `w`/`h` (intrinsic px) | `<figure>` |
| `pagelink` | `page` | a card linking to another page |
@@ -81,6 +82,28 @@ unique ids the first time.
and renders its `html` as a fallback. Properties are **flat on the block** —
there is no `props` object.
+### Callouts
+
+`tone` is one of `note` `tip` `important` `warning` `caution` — GitHub's alert
+names, so a callout exports as `> [!WARNING]` and reads back as the same tone.
+Absent means `note`. Like `type`, it is an open string: a tone this build does
+not know is kept, styled neutrally and labelled with its own word, so writing
+one is lossy in appearance only.
+
+`icon` is optional and is an **override**. Leave it out and the mark is derived
+from the tone, which is what keeps every warning in a document looking alike;
+set it to an emoji when the callout is not really about severity.
+
+```jsonc
+{ "id": "b7", "type": "callout", "tone": "warning",
+ "html": "The key is not recoverable." },
+{ "id": "b8", "type": "bullet", "parent": "b7", "html": "inside the box" }
+```
+A `code` block carrying `frontmatter: true` (usually `lang: "yaml"`, inside a
+collapsed toggle at the top of a page) is YAML frontmatter from an imported
+markdown file, kept verbatim. It is **not** a properties model — spaces has
+none yet — so read it if you like, but do not invent fields from it.
+
## Images: embed them, don't link them
`src` takes three forms, and only two of them display without asking:
@@ -118,6 +141,28 @@ 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.
+## Code blocks
+
+`html` is the source as **plain text**, html-escaped (`&` `<` `>` only) — never
+markup. Colour is applied when the page is drawn, so the document is identical
+whether or not this build can highlight the language.
+
+`lang` is a free string and is stored **exactly as you write it**. These tags
+are highlighted:
+
+`js` `ts` `py` `sh` `json` `yaml` `sql` `html` `css`
+
+plus the aliases you would reach for anyway — `javascript` `jsx` `typescript`
+`tsx` `python` `bash` `zsh` `shell` `yml` `postgres` `mysql` `xml` `svg`. Any
+other tag (`rust`, `go`, …) renders plain and is preserved: it exports as its
+own fence and starts highlighting by itself if a later build learns it. So tag
+the block honestly — never re-tag it as something close.
+
+```json
+{ "id": "b4", "type": "code", "lang": "sh",
+ "html": "curl -fsSL https://bento.page/… -o Notes.bento.html" }
+```
+
## Rich text
`html` is **inline only**: `b i u s em strong code a span mark sub sup br`.
@@ -142,6 +187,7 @@ Links are same-document fragments:
| 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 |
+| a warning the reader must not miss | `callout` with the `tone` that fits | it is boxed, named and legible in print and without colour vision — but three per page and none of them registers |
| 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
@@ -151,20 +197,175 @@ the tree wastes the one thing this format does that a folder of files cannot.
## `window.bento`
```js
+// read
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.outline() // the whole space as a tree
+bento.validate() // what is wrong or suspect
+bento.stats() // pages, blocks, words, bytes, biggest assets
+
+// write — each one is ONE undoable step
+bento.newPage(title, parent?) // → new page id, or null
+bento.insertBlocks(pageId, afterId, [...]) // → new block ids, or null
+bento.updateBlock(id, patch) // → {ok:true, id, page} | {ok:false, err}
+bento.removeBlocks([ids]) // → {ok:true, removed, missing, added}
+bento.moveBlock(id, {pageId?, afterId?, beforeId?, parent?})
+bento.updatePage(id, patch) // → {ok:true, id} | {ok:false, err}
+bento.removePage(id, {descendants?}) // → {ok:true, removed, rehomed, links}
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
+bento.readonly // true = a locked or frozen file; every write returns err:'readonly'
```
-`insertBlocks` and `newPage` each commit **one undoable step** and mint their
-own ids. Use them in preference to `loadDoc` for anything incremental.
+Use the patch verbs, not `loadDoc`. Rewriting the document to add a paragraph
+flattens undo to one entry and overwrites anything a person typed while you
+were thinking.
+
+**A refused write changes nothing at all — including undo history.** Every verb
+validates before it touches the document, so a rejected patch does not leave an
+empty step for someone to undo.
+
+### Results are tagged
+
+The verbs added after 0.1.0 return `{ok: true, …}` or `{ok: false, err, detail}`
+rather than `null`. `err` is one of `readonly`, `no-such-block`, `no-such-page`,
+`bad-patch`, `immutable`, `not-serializable`, `cycle`, `last-page`.
+`insertBlocks` and `newPage` keep their original shapes (ids, or `null`),
+because files and scripts already depend on them.
+
+Nothing is ever silently ignored. Sending `id` in a patch is an error, not a
+no-op; so is `blocks` in a page patch (block structure goes through the block
+verbs, which keep ids, nesting and undo coherent). In a patch, `null` **deletes**
+a field.
+
+### `bento.validate()`
+
+```js
+const { ok, counts, findings } = bento.validate()
+findings.filter(f => f.severity === 'error')
+```
+
+Each finding is `{code, severity, message, fix, page?, block?, path?}`. It
+reports duplicate and missing ids, a page inside its own subtree (which is the
+one way a page becomes unreachable), parents naming nothing, `#p/` links and
+`pagelink` cards pointing at pages that do not exist, unknown block types, block
+markup inside inline `html` (and markup that is dropped whole), hrefs outside the
+allowlist, images with no `alt`, no size, a missing `asset:` or a remote `src`,
+a `home` naming nothing, pages with no blocks, and assets nothing references.
+
+`ok` means no **errors**; warnings and info do not make a document invalid.
+Severity is meant literally, so that a clean document is silent: **`validate()`
+reports nothing at all on the space a fresh file opens with**, and the rig
+enforces that. If you get findings, they are about your document.
+
+It only reads. A finding is advice, never a refusal — `parseDoc` remains the
+thing that decides whether a document opens at all.
+
+Unknown *property names* are deliberately not reported: unknown fields are how
+this format carries a future version's data, and how you can park your own
+metadata on a block.
+
+### `bento.outline()`
+
+The whole space in one call instead of one `getPage` per page:
+
+```js
+bento.outline()
+// { title, docId, pages, blocks, words,
+// tree: [{ id, title, depth, parent?, icon?, archived?, home?,
+// blocks, words, headings: [{id, level, text}], links: [pageId] }] }
+```
+
+In sidebar order (depth-first). Headings carry their **block id**, so what comes
+back can be handed straight to `updateBlock` or `moveBlock`. `links` is what
+that page points at, which is the other half of the backlinks a reader sees.
+
+### `bento.stats()`
+
+```js
+bento.stats()
+// { pages, archived, blocks, words, characters, blockTypes, todos,
+// assets: {count, bytes, orphans, orphanBytes},
+// bytes: {document, assets, text},
+// biggest: [{key, bytes, mime, used}] }
+```
+
+This answers "why is this file 30 MB". It is always the images: prose is free
+(2,000 pages of it is about 5 MB). `used` is how many blocks reference that
+asset — `0` means it is dead weight, and deleting the key is pure savings. The
+app shell adds a fixed ~80 KB on top of `bytes.document`.
+
+### The patch verbs, exactly
+
+```js
+bento.insertBlocks(pageId, afterId, blocks)
+```
+Mints fresh ids — never yours — and inserts after `afterId` (`null` = the end of
+the page). An `afterId` that is not on that page is an **error**; it does not
+append somewhere else and report success. Blocks in one batch may nest inside
+each other: give them temporary `id`s and use those as `parent`, and the
+references are remapped to the minted ids.
+
+```js
+bento.updateBlock(id, {html, type, done, open, src, alt, …})
+```
+Changes fields on one block. `null` deletes a field. `id` is refused. `parent`
+must name a block on the same page and may not be inside the block's own
+subtree.
+
+```js
+bento.removeBlocks([id, …])
+```
+Takes the nested blocks with it — deleting a toggle deletes its body, because
+leaving blocks pointing at an id that no longer exists means they reappear,
+un-nested, at the next load. Ids that were not there come back in `missing`. If
+this empties a page, one blank paragraph is created and returned in `added` (a
+page with no blocks has nothing to put a caret in — nobody can type in it).
+
+```js
+bento.moveBlock(id, {pageId, afterId | beforeId, parent})
+```
+Moves a block and everything nested under it. Neither anchor = the end of the
+page. Moving across pages drops a `parent` that does not exist there; pass
+`parent` to re-nest deliberately, or `null` to un-nest.
+
+```js
+bento.updatePage(id, {title, icon, parent, archived, …})
+```
+`title` is plain text (it renders as text, so markup would show literally).
+`parent` may not be one of the page's own descendants. `archived: false`
+removes the key, which is what the editor writes.
+
+```js
+bento.removePage(id, {descendants: false})
+```
+By default the pages inside it move up a level rather than disappearing with it;
+`{descendants: true}` takes the subtree. `links` in the result counts the
+inbound links that just went dead. Removing every page is refused.
+
+### What you may write
+
+Everything an agent writes goes through the same sanitizer the editor uses, on
+the way IN: an agent cannot put into a file something this build could not have
+produced. `html` is reduced to the inline allowlist (a `<script>` does not
+survive), a `code` block's html is escaped text rather than markup, and a patch
+value JSON cannot carry — a function, a `Date`, a `Map`, a cycle — is refused
+rather than vanishing quietly at save time.
+
+## Before you finish — self-audit
+
+- [ ] `bento.validate()` clean of **errors**, and every warning either fixed or
+ a deliberate choice you could defend?
+- [ ] More than one topic? **Separate pages**, not headings in one long scroll.
+- [ ] Does anything link **across** the tree, or does everything only link down?
+ Backlinks are the feature a folder of files cannot have.
+- [ ] Every image `alt`-texted and embedded as an `asset:`?
+- [ ] **Have you opened it?** Click through the pages, fold the toggles, follow
+ the links. A space nobody read is not finished.
## Gotchas
@@ -174,6 +375,10 @@ own ids. Use them in preference to `loadDoc` for anything incremental.
- `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.
+ `validate()` names every one of them.
+- **Never write a page with an empty `blocks` array.** Nothing in it can take a
+ caret, so it is a page nobody can type in. Give it `[{ "type": "p", "html":
+ "" }]` — `bento.newPage()` does exactly that.
- `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
diff --git a/scripts/lib/sync-fixtures.ts b/scripts/lib/sync-fixtures.ts
new file mode 100644
index 00000000..44f60e60
--- /dev/null
+++ b/scripts/lib/sync-fixtures.ts
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Shared fixture machinery for the bento-sync rigs.
+//
+// Extracted VERBATIM from scripts/test-sync.ts so the convergence rig
+// (test-sync.ts) and the equivalence rig (test-sync-equiv.ts) generate the
+// SAME documents and the SAME mutations from the same seed. Two rigs with two
+// generators would be two different opinions about what "an edit" is, and the
+// equivalence rig's whole job is to be the convergence rig's stricter twin.
+//
+// Engine-free on purpose: nothing here imports crdt.ts, because the
+// equivalence rig loads TWO engines and neither may be baked into a fixture.
+
+export type Doc = any
+
+/** Anything the mutation generator needs from a replica. */
+export interface Mutator {
+ actor: string
+ counter: number
+}
+
+/** deterministic PRNG */
+export function mulberry32(seed: number) {
+ let t = seed >>> 0
+ return () => {
+ t += 0x6d2b79f5
+ let r = Math.imul(t ^ (t >>> 15), 1 | t)
+ r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r
+ return ((r ^ (r >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/** key-order-independent serialization (for "same value, different bytes") */
+export function stable(v: unknown): string {
+ if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`
+ if (v && typeof v === 'object') {
+ const o = v as Record<string, unknown>
+ return `{${Object.keys(o)
+ .sort()
+ .filter((k) => o[k] !== undefined)
+ .map((k) => `${JSON.stringify(k)}:${stable(o[k])}`)
+ .join(',')}}`
+ }
+ return JSON.stringify(v)
+}
+
+export function baseDoc(): Doc {
+ return {
+ format: 'bento/slides',
+ version: 1,
+ docId: 'doc-1',
+ title: 'Rig deck',
+ size: { width: 1600, height: 900 },
+ theme: { background: '#0D1B2E', color: '#F2F0EA', accent: '#FF9E8A', fontFamily: 'x' },
+ assets: { logo: '<svg/>' },
+ slides: [
+ {
+ id: 's1',
+ background: '#0D1B2E',
+ transition: 'none',
+ notes: '',
+ elements: [
+ { id: 's1-t1', type: 'text', x: 100, y: 100, w: 600, h: 80, rotation: 0, opacity: 1, html: 'Hello <b>world</b>', fontSize: 40, fontFamily: 'x', fontWeight: 700, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 },
+ { id: 's1-r1', type: 'shape', shape: 'rect', x: 200, y: 300, w: 200, h: 120, rotation: 0, opacity: 1, fill: '#FF9E8A', stroke: 'none', strokeWidth: 0, radius: 8 },
+ { id: 's1-r2', type: 'shape', shape: 'ellipse', x: 500, y: 300, w: 90, h: 90, rotation: 0, opacity: 1, fill: '#5E7699', stroke: 'none', strokeWidth: 0, radius: 0 },
+ // 'cast' appears on s1 AND s2 — the id-continuity morph idiom
+ // (starterdeck's sd-tile-*). Every random run exercises it.
+ { id: 'cast', type: 'text', x: 900, y: 100, w: 300, h: 60, rotation: 0, opacity: 1, html: 'Morph <b>me</b>', fontSize: 28, fontFamily: 'x', fontWeight: 700, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 },
+ ],
+ },
+ {
+ id: 's2',
+ background: '#F2F0EA',
+ transition: 'morph',
+ notes: 'second',
+ elements: [
+ { id: 's2-t1', type: 'text', x: 120, y: 120, w: 500, h: 60, rotation: 0, opacity: 1, html: 'Numbers &amp; facts', fontSize: 30, fontFamily: 'x', fontWeight: 400, color: '#111', align: 'left', valign: 'top', lineHeight: 1.3 },
+ { id: 'cast', type: 'text', x: 200, y: 500, w: 600, h: 120, rotation: 0, opacity: 1, html: 'Morph <b>me</b>', fontSize: 56, fontFamily: 'x', fontWeight: 700, color: '#111', align: 'left', valign: 'top', lineHeight: 1.2 },
+ ],
+ },
+ { id: 's3', background: '#16273E', transition: 'fade', notes: '', elements: [] },
+ ],
+ modified: 'never',
+ }
+}
+
+/** mutation menu — mirrors what the editor's commit sites do */
+export function randomMutation(r: Mutator, rnd: () => number): (doc: Doc) => void {
+ const pick = <T>(xs: T[]): T => xs[Math.floor(rnd() * xs.length)]
+ const kind = Math.floor(rnd() * 13)
+ return (doc: Doc) => {
+ const slides = doc.slides
+ const sl = pick(slides)
+ if (!sl && kind !== 8) return // remote deletes can empty the deck
+ switch (kind) {
+ case 0: // doc prop
+ doc.title = `Deck ${Math.floor(rnd() * 1000)}`
+ break
+ case 1: // theme (nested doc prop)
+ doc.theme = { ...doc.theme, accent: `#${Math.floor(rnd() * 0xffffff).toString(16).padStart(6, '0')}` }
+ break
+ case 2: // slide prop
+ sl.background = `#${Math.floor(rnd() * 0xffffff).toString(16).padStart(6, '0')}`
+ break
+ case 3: {
+ // element prop
+ const els = slides.flatMap((s: any) => s.elements)
+ if (!els.length) break
+ const el = pick(els)
+ el.x = Math.floor(rnd() * 1600)
+ el.y = Math.floor(rnd() * 900)
+ break
+ }
+ case 12: {
+ // REMOVE a property. The generator has never done this, and that gap
+ // is not hypothetical: a `set` op with `v` ABSENT crashed every
+ // receiving replica in a shipped release (scripts/test-crdt-delprop.ts),
+ // and 300 seeds of this rig missed it for months because assigning is
+ // the only mutation it knew. A property-based rig explores exactly the
+ // mutations it was taught, so an untaught one is a permanent blind spot
+ // rather than an unlikely one.
+ const els = slides.flatMap((s: any) => s.elements)
+ if (!els.length) break
+ const el = pick(els)
+ // optional properties only: deleting a required one is not a document
+ // any editor could produce, so it would be testing an impossible input
+ // OPTIONAL properties only. `rotation` and `opacity` are required in
+ // model.ts, so deleting them would test a document no editor could
+ // produce — an impossible input, whose failures teach nothing.
+ const removable = ['radius', 'shadow', 'link', 'group', 'morphId']
+ .filter((k) => el[k] !== undefined)
+ if (!removable.length) break
+ delete el[pick(removable)]
+ break
+ }
+ case 4: {
+ // insert element
+ const id = `${r.actor}-e${r.counter++}`
+ sl.elements.push({ id, type: 'shape', shape: 'rect', x: Math.floor(rnd() * 1000), y: Math.floor(rnd() * 700), w: 120, h: 80, rotation: 0, opacity: 1, fill: '#8FA3BF', stroke: 'none', strokeWidth: 0, radius: 4 })
+ break
+ }
+ case 5: {
+ // delete element
+ const s = pick(slides.filter((x: any) => x.elements.length)) as any
+ if (!s) break
+ s.elements.splice(Math.floor(rnd() * s.elements.length), 1)
+ break
+ }
+ case 6: {
+ // move element across slides. Target must not already carry the
+ // element's id: bare ids are unique WITHIN a slide (format
+ // invariant the editor upholds); duplication ACROSS slides is the
+ // morph idiom and legal.
+ const from = pick(slides.filter((x: any) => x.elements.length)) as any
+ if (!from || slides.length < 2) break
+ const i = Math.floor(rnd() * from.elements.length)
+ const to = pick(
+ slides.filter((x: any) => x !== from && !x.elements.some((e: any) => e.id === from.elements[i].id)),
+ ) as any
+ if (!to) break
+ const [el] = from.elements.splice(i, 1)
+ to.elements.splice(Math.floor(rnd() * (to.elements.length + 1)), 0, el)
+ break
+ }
+ case 7: {
+ // reorder elements (z-order)
+ if (sl.elements.length < 2) break
+ const i = Math.floor(rnd() * sl.elements.length)
+ const [el] = sl.elements.splice(i, 1)
+ sl.elements.splice(Math.floor(rnd() * (sl.elements.length + 1)), 0, el)
+ break
+ }
+ case 8: {
+ // insert slide
+ const id = `${r.actor}-s${r.counter++}`
+ slides.splice(Math.floor(rnd() * (slides.length + 1)), 0, {
+ id, background: '#123', transition: 'none', notes: '',
+ elements: [{ id: `${id}-t`, type: 'text', x: 50, y: 50, w: 300, h: 50, rotation: 0, opacity: 1, html: 'new', fontSize: 20, fontFamily: 'x', fontWeight: 400, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 }],
+ })
+ break
+ }
+ case 9: // delete slide
+ if (slides.length > 1) slides.splice(Math.floor(rnd() * slides.length), 1)
+ break
+ case 10: {
+ // reorder slides
+ if (slides.length < 2) break
+ const i = Math.floor(rnd() * slides.length)
+ const [s] = slides.splice(i, 1)
+ slides.splice(Math.floor(rnd() * (slides.length + 1)), 0, s)
+ break
+ }
+ case 11: {
+ // text edit
+ const els = slides.flatMap((s: any) => s.elements).filter((e: any) => typeof e.html === 'string')
+ if (!els.length) break
+ const el = pick(els)
+ const h: string = el.html
+ if (rnd() < 0.5 && h.length > 2) {
+ const i = Math.floor(rnd() * (h.length - 1))
+ el.html = h.slice(0, i) + h.slice(i + 1 + Math.floor(rnd() * Math.min(3, h.length - i - 1)))
+ } else {
+ const i = Math.floor(rnd() * (h.length + 1))
+ el.html = h.slice(0, i) + pick(['X', 'yz', ' q', '<i>!</i>', '&amp;']) + h.slice(i)
+ }
+ break
+ }
+ }
+ }
+}
diff --git a/scripts/size-budgets.json b/scripts/size-budgets.json
new file mode 100644
index 00000000..f5747b06
--- /dev/null
+++ b/scripts/size-budgets.json
@@ -0,0 +1,10 @@
+{
+ "//": "Ceilings for the single-file shells. Raise one IN THE COMMIT that needs the bytes, and say what bought them. Checked by scripts/test-spaces-size.mjs.",
+ "shells": {
+ "spaces": {
+ "path": "spaces/dist-single/Bento_Spaces.bento.html",
+ "max": 120832,
+ "//": "118 KiB. Raised from 114 KiB at 117218 B on 2026-08-05 for the static first-page preview (spaces/src/preview.ts): without it a saved space showed the boot splash to every reader that runs no script — QuickLook, iOS Files, Bento Tray. Reported from the field. The preview itself is per-SAVE and separately budgeted at 64KB."
+ }
+ }
+}
diff --git a/scripts/test-crdt-delprop.ts b/scripts/test-crdt-delprop.ts
index e722f47e..331e6055 100644
--- a/scripts/test-crdt-delprop.ts
+++ b/scripts/test-crdt-delprop.ts
@@ -96,5 +96,24 @@ for (const [label, extra] of REMOVALS) {
ok(threw === null, `a removal for an unknown node pends without throwing${threw ? ` (got ${threw})` : ''}`)
}
+// ---- the SECOND place the same defect lived ---------------------------------
+// The original fix went to the `set` handler, where the bug was found. The
+// identical line — JSON.stringify(v) sliced, with dbg's argument built eagerly
+// whether or not debugging is on — also sat in replayStash, and stayed there:
+// the fix went where the bug was, not everywhere the pattern was.
+//
+// IT IS NOT PINNED HERE, and that is deliberate rather than an omission. Two
+// hand-built resurrection scenarios failed to reach the line (they passed with
+// the fix REVERTED, which makes them worse than no test at all). What does
+// reach it is the convergence rig, once its generator was taught to remove
+// properties — measured: `node scripts/test-sync.ts` throws
+// "Cannot read properties of undefined (reading 'slice')" with the fix
+// reverted, and passes 45,368 checks with it.
+//
+// So the guard for this site is scripts/lib/sync-fixtures.ts case 12, and the
+// lesson is the generator's, not this file's: a property-based rig explores
+// exactly the mutations it was taught, and BOTH instances of this bug shipped
+// because removal was not one of them.
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.ts
index eef917d0..718c8c03 100644
--- a/scripts/test-spaces-model.ts
+++ b/scripts/test-spaces-model.ts
@@ -31,6 +31,14 @@ import {
type SpacesDoc,
} from '../spaces/src/model.ts'
import { countOutsideTags, replaceOutsideTags } from '../spaces/src/findreplace.ts'
+import { inlineHtml, parseNote, planImport } from '../spaces/src/markdown.ts'
+import { planUpdatePage } from '../spaces/src/agent.ts'
+import { tokenize, normLang, langLabel, CODE_LANGS } from '../spaces/src/highlight.ts'
+import { escText } from '../spaces/src/sanitize.ts'
+import {
+ SPECS, SPEC, MENU_SPECS, MD_SPECS, TAG_OF, LIST_OF, CALLOUT_TONES, mdLayout,
+} from '../spaces/src/blocks.ts'
+import type { Block } from '../spaces/src/model.ts'
let failures = 0
let checks = 0
@@ -223,7 +231,18 @@ for (const [label, input, err] of [
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']) {
+ // EVERY source file, globbed — never a hand-written list. The list version
+ // named the five files that existed when the hole was found, so findreplace.ts
+ // and blocks.ts (added days later) were never checked, and any new module
+ // could reintroduce the live-parse hole with the guard still green. A guard
+ // that only covers the code it was written against is a guard that expires.
+ const dir = new URL('../spaces/src/', import.meta.url)
+ const walk = (d: URL): string[] => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) =>
+ e.isDirectory() ? walk(new URL(`${e.name}/`, d)) : e.name.endsWith('.ts') ? [new URL(e.name, d).pathname.slice(dir.pathname.length)] : [])
+ const sources = walk(dir)
+ ok(sources.length >= 10 && sources.includes('findreplace.ts') && sources.includes('blocks.ts'),
+ `the guard globs every source file (${sources.length} found)`)
+ for (const f of sources) {
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
@@ -342,5 +361,709 @@ for (const [label, input, err] of [
'tags and their attributes are preserved verbatim')
}
+// ---- every topbar action stays reachable at every width --------------------
+// Measured at 375px before the ⋯ menu existed: the bar wanted 678px, so seven
+// of eleven controls sat off the right edge — Save among them. The file could
+// not be saved on a phone, and nothing said so: the controls were in the DOM,
+// laid out, and simply painted past the edge.
+//
+// The rule (slides' rule) is: drop text and fold, never scroll. The failure
+// mode to guard is not the CSS — it is the SECOND LIST: a ⋯ menu maintained by
+// hand as a copy of the desktop row drifts the first time either changes, and
+// the drift is invisible until someone opens the app on a phone.
+{
+ const fs = await import('node:fs')
+ const ed = fs.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')
+ const css = fs.readFileSync(new URL('../spaces/src/styles.css', import.meta.url), 'utf8')
+
+ ok(/const secondary: Array<\{/.test(ed), 'the secondary topbar actions are declared as ONE list')
+ ok(/secondary\.map\(/.test(ed), '…the inline row is built from that list')
+ ok(/for \(const a of secondary\)/.test(ed), '…and the ⋯ menu is built from the SAME list')
+
+ ok(/@media \(max-width: 720px\)/.test(css), 'there is a narrow-width breakpoint')
+ const narrow = css.slice(css.indexOf('@media (max-width: 720px)'))
+ ok(/\.sp-sec \{ display: none/.test(narrow), 'narrow hides the inline secondary row')
+ ok(/\.sp-more \{ display: inline-flex/.test(narrow), 'narrow reveals the ⋯ menu')
+
+ // the bar must never become a scroller — that hides the same controls, just
+ // less honestly, and it is the fix everyone reaches for first
+ const barRule = css.slice(css.indexOf('.sp-bar {'), css.indexOf('}', css.indexOf('.sp-bar {')))
+ ok(!/overflow-x:\s*(auto|scroll)/.test(barRule), 'the topbar does not scroll horizontally')
+
+ // a menu opened from the right end must open inward
+ ok(/\.sp-dd-end \.sp-ddmenu \{ inset-inline-start: auto; inset-inline-end: 0/.test(css),
+ 'right-end dropdowns open inward')
+ ok(/more\.classList\.add\('sp-more', 'sp-dd-end'\)/.test(ed) &&
+ /saveMore\.classList\.add\('sp-caret', 'sp-dd-end'\)/.test(ed),
+ '…and both right-end menus say so')
+}
+
+// ---- one declaration per block type ---------------------------------------
+// Adding a type used to mean five edits across four files — the renderer's tag
+// map and list map, the / menu, the markdown-autoformat table, and the markdown
+// exporter. Four out of five looked finished and exported as a bare paragraph.
+//
+// It is also the merge-conflict surface: several people adding block types in
+// parallel all edited the same four hot files. One registry, and each type is
+// an independent entry.
+{
+ ok(SPECS.length >= 13, `the registry holds every block type (${SPECS.length})`)
+ ok(new Set(SPECS.map((s) => s.type)).size === SPECS.length, 'block types are unique')
+ for (const sp of SPECS) {
+ ok(!!sp.label && !!sp.hint && !!sp.icon, `${sp.type}: has a label, hint and icon`)
+ ok(!!sp.tag, `${sp.type}: declares its semantic element`)
+ }
+
+ // a list item must actually be an <li>, or it renders outside its <ul>
+ for (const sp of SPECS.filter((s) => s.list)) {
+ ok(sp.tag === 'li', `${sp.type}: a list block is an <li> (got <${sp.tag}>)`)
+ }
+ // …and the derived map must keep CUSTOM list types, which is the mistake that
+ // would silently lift every to-do out of its list
+ ok(TAG_OF.todo === 'li', 'todo keeps its <li> despite rendering custom')
+ ok(LIST_OF.todo === 'ul' && LIST_OF.bullet === 'ul' && LIST_OF.number === 'ol',
+ 'the list map is derived correctly')
+
+ // the autoformat triggers, ALIASES INCLUDED — "- " and "* " both start a
+ // bullet, "[] " and "[ ] " both start a to-do. A registry that allowed one
+ // pattern per type would have dropped half of these silently.
+ const triggers = MD_SPECS.map(([re, type]) => `${re.source}=>${type}`).sort()
+ const expected = [
+ '^# $=>h1', '^## $=>h2', '^### $=>h3',
+ '^- $=>bullet', '^\\* $=>bullet',
+ '^1\\. $=>number', '^> $=>quote',
+ '^\\[\\] $=>todo', '^\\[ \\] $=>todo',
+ '^```(\\w*) $=>code', '^--- $=>divider',
+ '^\\[!(note|tip|important|warning|caution)\\] $=>callout',
+ ].sort()
+ ok(JSON.stringify(triggers) === JSON.stringify(expected),
+ `every markdown trigger survives the registry (${triggers.length} of ${expected.length})`)
+
+ // the to-do trigger must still initialise `done`, or the checkbox renders
+ // from an absent field
+ const todoInit = MD_SPECS.find(([, type]) => type === 'todo')?.[2]
+ const probe: Record<string, unknown> = {}
+ todoInit?.(probe as never)
+ ok(probe.done === false, 'the to-do trigger initialises done:false')
+
+ ok(MENU_SPECS.length === SPECS.length, 'every type is offered in the / menu')
+ ok(SPEC.get('futuretype') === undefined, 'an unknown type has no spec — and must still render as text')
+ ok(SPECS.filter((s) => s.type !== 'p').every((s) => !!s.toMd),
+ 'every type but plain text says how it exports to markdown')
+
+ // and the consumers must actually derive, rather than keeping a second copy
+ const fs = await import('node:fs')
+ const read = (f: string) => fs.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+ const ren = read('render.ts'), ed = read('editor.ts'), ab = read('about.ts')
+ ok(/import \{[^}]*\bTAG_OF\b[^}]*\bLIST_OF\b[^}]*\} from '\.\/blocks'/.test(ren) &&
+ !/const TAG_OF: Record/.test(ren) && !/const LIST_OF: Record/.test(ren),
+ 'render.ts derives its tag and list maps rather than repeating them')
+ ok(/const SLASH_ITEMS = MENU_SPECS/.test(ed), 'the / menu is the registry')
+ ok(/const AUTOFORMAT = MD_SPECS/.test(ed), 'autoformat is the registry')
+ ok(/SPEC\.get\(b\.type\)/.test(ab) && !/case 'bullet': out\.push/.test(ab),
+ 'markdown export is the registry, not a parallel switch')
+ // …including the SIXTH place a type used to have to be added by hand
+ ok(/SPEC\.get\(type\)\?\.init\?\.\(b\)/.test(ed) && !/type === 'todo' && b\.done === undefined/.test(ed),
+ 'converting a block seeds its fields from the registry, not from a list in setType')
+ // a container's body element is a registry fact, not a name test — the
+ // second container type is what turned `b.type === 'toggle'` into a bug
+ ok(/SPEC\.get\(b\.type\)\?\.container/.test(ren) && !/if \(b\.type === 'toggle'\) \{/.test(ren),
+ 'render.ts opens a container body from the registry, not from a hardcoded type name')
+}
+
+// ---- the callout block -----------------------------------------------------
+// Its TONE is a permanent vocabulary and its markdown is a blockquote, which is
+// the fragile part: a GitHub alert ends at the first line that is not "> ", so
+// a nested block or a blank line silently exports half a callout as loose prose
+// — and nothing about the document, the renderer or the type system notices.
+{
+ const spec = SPEC.get('callout')!
+ ok(!!spec && spec.tag === 'aside' && spec.container === 'always' && spec.text === true,
+ 'callout is an <aside> that holds text and always shows its children')
+ ok(CALLOUT_TONES.map((t) => t.tone).join() === 'note,tip,important,warning,caution',
+ 'the five tones are GitHub alert names, in escalation order')
+
+ // the tone the trigger NAMED, not a default
+ const fired = (typed: string): Block => {
+ const b: Block = { id: 'x', type: 'p' }
+ const rule = MD_SPECS.find(([re]) => re.test(typed))
+ if (!rule) return b // report a missing trigger, do not crash the rig
+ b.type = rule[1]
+ rule[2](b, rule[0].exec(typed)!)
+ return b
+ }
+ ok(fired('[!warning] ').type === 'callout' && fired('[!warning] ').tone === 'warning',
+ 'typing [!warning] makes a callout that is a warning')
+ ok(fired('[!CAUTION] ').tone === 'caution', 'the trigger is case-insensitive and stores lower case')
+ { const b: Block = { id: 'x', type: 'callout' }; spec.init!(b); ok(b.tone === 'note', 'a callout with no tone named is a note') }
+ // init also runs when an EXISTING block is converted, so it must not clobber
+ { const b: Block = { id: 'x', type: 'callout', tone: 'caution' }; spec.init!(b); ok(b.tone === 'caution', 'init never overwrites a tone that is already there') }
+
+ const md = (b: Partial<Block>, text = 'x') =>
+ spec.toMd!({ id: 'c', type: 'callout', ...b } as Block, text, '', () => undefined).join('\n')
+ ok(md({ tone: 'warning' }) === '> [!WARNING]\n> x', 'a callout exports as a GitHub alert')
+ ok(md({}) === '> [!NOTE]\n> x', 'an absent tone exports as NOTE')
+ ok(md({ tone: 'success' }) === '> [!SUCCESS]\n> x',
+ 'a tone this build does not know exports as the tone it IS — the word is not lost')
+ // the tone came out of a file someone mailed you
+ ok(md({ tone: 'evil]\n# heading' }).split('\n')[0] === '> [!EVILHEADING]',
+ 'a newline or bracket in a tone cannot break out of the alert tag')
+ ok(md({ tone: 'note' }, 'one\ntwo') === '> [!NOTE]\n> one\n> two',
+ 'every line of a multi-line callout stays inside the quote')
+ ok(md({ tone: 'note' }, '') === '> [!NOTE]\n>', 'an empty callout still closes its own line')
+
+ // …and the LAYOUT around it: markers on the subtree, no blank line inside
+ const page: Block[] = [
+ { id: 'a', type: 'p' },
+ { id: 'c', type: 'callout', tone: 'tip' },
+ { id: 'k1', type: 'bullet', parent: 'c' },
+ { id: 'k2', type: 'p', parent: 'c' },
+ { id: 'z', type: 'p' },
+ ]
+ const lay = mdLayout(page)
+ ok(lay[1].quote === '' && lay[2].quote === '> ' && lay[3].quote === '> ',
+ 'every block inside a callout carries the blockquote marker')
+ ok(lay[1].sep === '>' && lay[2].sep === '>',
+ 'blocks of one alert are separated by a bare ">" — a blank line would close the box')
+ ok(lay[3].sep === '' && lay[0].sep === '',
+ 'the alert ends with a real blank line, and does not start early')
+ ok(lay[2].indent === '' && lay[4].quote === '',
+ 'a callout child is the alert body, not an indented list item, and the box does not leak')
+ const nested = mdLayout([
+ { id: 'c', type: 'callout' }, { id: 'd', type: 'callout', parent: 'c' }, { id: 'e', type: 'p', parent: 'd' },
+ ])
+ ok(nested[1].quote === '> ' && nested[2].quote === '> > ' && nested[0].sep === '>',
+ 'a callout inside a callout nests its quotes')
+ // a hand-edited file can name a parent cycle; the renderer cannot loop but an
+ // ancestor walk can, and a hung export is a hung tab
+ const cyc = mdLayout([{ id: 'a', type: 'p', parent: 'b' }, { id: 'b', type: 'p', parent: 'a' }])
+ ok(cyc.length === 2, 'a parent cycle terminates instead of hanging the export')
+
+ // the tone NAME is localized in render.ts, because the i18n sweep only sees
+ // literal strings — a tone with no case there ships as an English word
+ const fs = await import('node:fs')
+ const ren = fs.readFileSync(new URL('../spaces/src/render.ts', import.meta.url), 'utf8')
+ for (const { tone } of CALLOUT_TONES) {
+ const cap = tone[0].toUpperCase() + tone.slice(1)
+ ok(new RegExp(`case '${tone}': return t\\('${cap}'\\)`).test(ren), `${tone}: its name is translated`)
+ }
+
+ // A callout's icon and a page's icon are both "a name from the set, or any
+ // other string as text", and both take the name out of a file someone mailed
+ // you. ICONS is an object literal, so `'toString' in ICONS` is TRUE and the
+ // lookup returns a FUNCTION, which then gets stringified into the page.
+ const ed = fs.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')
+ // comments stripped, or the sentence explaining the rule breaks the rule
+ const code = (s: string) => s.split('\n').filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l)).join('\n')
+ ok(!/\bin ICONS\b/.test(code(ren)) && !/\bin ICONS\b/.test(code(ed)),
+ 'an icon NAME from a document is matched with hasOwn, never `in` (which finds Object.prototype)')
+}
+
+// ---- four things that were wrong in a shipped file ------------------------
+{
+ const fs2 = await import('node:fs')
+ const rd = (f: string) => fs2.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+ const main = rd('main.ts'), ed = rd('editor.ts'), mod = rd('model.ts')
+
+ // 1. "Save a copy…" must not become the ⌘S target. saveFile(doc, true)
+ // ASSIGNS the picked handle to the module's in-place handle, so every
+ // later save wrote to the copy while the original stayed frozen at the
+ // moment it was taken. The code even carried a comment claiming the
+ // kernel did the opposite.
+ ok(/writeUpdatedFileAs\(html, store\.doc/.test(main),
+ 'a copy is written through writeUpdatedFileAs (keepHandle defaults false)')
+ // EVERY file, not just main.ts. The first version of this check read main.ts
+ // alone and passed while about.ts kept its own "Save a copy…" button calling
+ // saveFile(doc, true) — the same bug, in the same app, one file over.
+ {
+ const dir2 = new URL('../spaces/src/', import.meta.url)
+ const all = fs2.readdirSync(dir2).filter((f) => f.endsWith('.ts'))
+ // Comments stripped first: this file's own prose explains the bug it
+ // guards, and a scanner that reads comments flags the explanation. (The
+ // i18n sweep has the same trap — an example t('…') inside a comment adds a
+ // required key to all eight catalogs.)
+ const codeOnly = (src: string) => src
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*\/\/.*$/gm, '')
+ const offenders = all.filter((f) => /saveFile\([^)]*,\s*true\)/.test(codeOnly(rd(f))))
+ ok(offenders.length === 0,
+ `no file saves a copy through saveFile(doc, true), which retargets ⌘S (${offenders.join(', ') || 'none'})`)
+ }
+
+ // 2. doc.readonly was declared in the format and read by nothing: a space
+ // saved as a reading copy opened fully editable.
+ ok(/if \(frozen \|\| doc\.readonly\) store\.readOnly = true/.test(main),
+ 'doc.readonly opens the space read-only')
+
+ // 3. the agent API must not report ids for blocks it did not write —
+ // store.commit early-returns on a read-only document, and the ids came
+ // back anyway.
+ // Every write verb goes through ONE gate. It used to be a per-verb `if
+ // (store.readOnly) return null`, which is a guard the next verb forgets; the
+ // planner checks once, before applying anything, and says WHY rather than
+ // returning a bare null an agent cannot distinguish from "nothing matched".
+ ok(/function run<T extends object>\(plan: Plan<T>\): [^\n]*\{\s*\n\s*if \(store\.readOnly\)/.test(main),
+ 'every agent write verb is gated read-only in one place')
+ ok(/err: 'readonly'/.test(main), '…and refusing says why, rather than returning a bare null')
+ ok(/loadDoc: \(json: string\): boolean => \{\s*\n\s*if \(store\.readOnly\) return false/.test(main),
+ 'loadDoc refuses too — it replaces the whole document and does not go through the planner')
+
+ // 4. #p/<page>/<block> is ALREADY admissible under sanitize.ts's allowlist,
+ // so it can arrive in a file this build did not write. It used to resolve
+ // to nothing — not even the page — and produced a backlink keyed on a
+ // page id that does not exist.
+ ok(/private resolveAnchor\(/.test(ed), 'there is one anchor resolver')
+ ok(/const id = this\.resolveAnchor\(href\)/.test(ed), '…and clicks go through it')
+ ok(/function linkTarget\(/.test(mod) && /linkTarget\(m\[1\], page\)/.test(mod),
+ 'backlinks are keyed on the PAGE segment of a link target')
+}
+
+// ---- markdown triggers must survive a real keystroke -----------------------
+// A trailing space typed at the end of a contentEditable line is inserted as
+// U+00A0, not U+0020. So `/^## $/` matched nothing anyone typed and EVERY
+// markdown trigger was dead from 0.1.0 — in the feature the starter space
+// advertises on its Writing page.
+//
+// It survived because a test set `host.textContent` directly, with a real
+// space. That is not typing, and it is why this assertion is about the FIX
+// rather than the behaviour: the behaviour needs a browser and
+// execCommand('insertText'), which is the only way to reproduce the NBSP.
+{
+ const fs2 = await import('node:fs')
+ const ed = fs2.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')
+ const fn = ed.slice(ed.indexOf('private autoformat('), ed.indexOf('private autoformat(') + 1600)
+ ok(/replace\(\/\\u00a0\/g, ' '\)/.test(fn),
+ 'autoformat normalises U+00A0 before testing its patterns')
+ // …and only for the test: rewriting the author's text would be worse
+ ok(!/b\.html = .*replace\(\/\\u00a0/.test(ed),
+ '…and never rewrites the stored text to make a pattern match')
+}
+
+// ---- syntax highlighting: the tokenizer is TOTAL, and cannot emit text ------
+// Highlighting is applied at render time and must never touch the document, so
+// the guarantee has to be structural rather than a promise. `tokenize` returns
+// {kind, a, b} ranges into the caller's string — it has no way to produce a
+// character the input did not contain, let alone markup — and the tokens
+// PARTITION the input exactly. Sum the slices and you get the source back,
+// byte for byte, for every language, including on input designed to break a
+// lexer: an unterminated string, a lone backslash at EOF, a `</script>`, a
+// smuggled `<img onerror>`.
+//
+// The partition is also what makes the renderer's job safe: it walks the ranges
+// and builds one text node per token, so a bug here degrades to wrong COLOUR,
+// never to wrong text and never to markup.
+{
+ const LANGS = CODE_LANGS.map((l) => l.id)
+ ok(LANGS.length >= 9 && LANGS[0] === '', 'the picker offers plain text first, then the languages')
+
+ const corpus = [
+ '',
+ 'plain words with no syntax at all',
+ 'const a = 1 // done\n/* block\n comment */\nfoo("bar", `t${x}`)',
+ 'def f(x):\n """doc"""\n return {\'k\': [1, 2.5e-3, 0xff]}\n@dec\nclass C: pass',
+ '#!/bin/sh\nset -eu\necho "${HOME}/x" | grep -c \'a\' # trailing note\ncurl host/p#frag',
+ '{"a": 1, "b": [true, null], "c": {"d": "e"}}',
+ 'on: push\njobs:\n build:\n runs-on: ubuntu-latest # comment\n steps: []',
+ "SELECT * FROM t WHERE name = 'it''s' -- note\n/* x */ ORDER BY id DESC;",
+ '<!doctype html>\n<div class="a" data-x=\'y\'>text &amp; more</div><!-- c -->\n<br/>',
+ ':root { --x: 1; }\n.a:hover, #main { color: #1c4fb5; margin: -2.5rem 0 !important }\n@media print { }',
+ // hostile / degenerate
+ '</script><script>alert(1)</script>',
+ '<img src=x onerror="alert(1)">',
+ '"never closed',
+ "'\\",
+ '/* never closed',
+ '`multi\nline\ntemplate`',
+ '<div attr="never closed',
+ '<<<>>>< <',
+ '\r\n\t\u0000\u00a0',
+ '\\\\\\',
+ '𝔘𝔫𝔦 "🎉" — 中文 # x',
+ '#',
+ '@',
+ '$',
+ '0x',
+ '1e',
+ '...',
+ '---',
+ 'a'.repeat(5000),
+ ]
+
+ let bad = 0
+ let lossy = 0
+ let split = 0
+ let stringy = 0
+ for (const lang of [...LANGS, 'rust', 'NOT-A-LANGUAGE', 'JavaScript', '.py']) {
+ for (const text of corpus) {
+ const toks = tokenize(text, lang)
+ let at = 0
+ let joined = ''
+ for (const tk of toks) {
+ if (tk.a !== at || tk.b <= tk.a || tk.b > text.length) bad++
+ // a token carrying a STRING would be a way for markup to appear; the
+ // shape is the guarantee, so it is asserted rather than assumed
+ if (Object.values(tk).some((v) => typeof v !== 'number' && typeof v !== 'string')) stringy++
+ if (typeof (tk as Record<string, unknown>).text === 'string') stringy++
+ // never cut a surrogate pair in half — the renderer makes one text node
+ // per token, and half a pair renders as U+FFFD
+ if (tk.a > 0 && text.charCodeAt(tk.a - 1) >= 0xd800 && text.charCodeAt(tk.a - 1) <= 0xdbff) split++
+ joined += text.slice(tk.a, tk.b)
+ at = tk.b
+ }
+ if (at !== text.length) bad++
+ if (joined !== text) lossy++
+ }
+ }
+ ok(bad === 0, `tokens PARTITION the input exactly, for every language and every input (${bad} violations)`)
+ ok(lossy === 0, `reassembling the tokens reproduces the source byte for byte (${lossy} losses)`)
+ ok(stringy === 0, 'a token is offsets only — it carries no text, so it cannot carry markup')
+ ok(split === 0, 'no token boundary falls inside a surrogate pair')
+
+ // an unknown or absent language is ONE plain token, deliberately: the
+ // fallback has to look like a decision, not like a lexer that gave up midway
+ for (const lang of [undefined, '', 'rust', 'brainfuck', 42, null]) {
+ const toks = tokenize('let x = "s" // c', lang)
+ ok(toks.length === 1 && toks[0].k === '' && toks[0].a === 0 && toks[0].b === 16,
+ `lang=${JSON.stringify(lang)} renders as one plain run`)
+ }
+
+ // aliases people actually type in a fence
+ for (const [raw, want] of [
+ ['javascript', 'js'], ['JS', 'js'], [' tsx ', 'ts'], ['.py', 'py'], ['bash', 'sh'],
+ ['yml', 'yaml'], ['psql', 'sql'], ['svg', 'html'], ['rust', ''], ['', ''],
+ ] as const) {
+ ok(normLang(raw) === want, `normLang(${JSON.stringify(raw)}) = ${JSON.stringify(want)}`)
+ }
+ ok(langLabel('bash') === 'Shell', 'a known tag shows its language name')
+ ok(langLabel('rust') === 'rust', 'an UNKNOWN tag shows itself, so a plain block explains why it is plain')
+
+ /** The kind of the token covering `needle`'s first occurrence. */
+ const kindAt = (text: string, lang: string, needle: string, nth = 0): string => {
+ let at = -1
+ for (let i = 0; i <= nth; i++) at = text.indexOf(needle, at + 1)
+ const tk = tokenize(text, lang).find((t) => t.a <= at && t.b >= at + needle.length)
+ return tk ? tk.k : '?'
+ }
+
+ const cases: Array<[string, string, string, string]> = [
+ // language, source, needle, expected kind
+ ['js', 'const x = 1 // hi', 'const', 'k'],
+ ['js', 'const x = 1 // hi', '// hi', 'c'],
+ ['js', 'const x = 1 // hi', '1', 'n'],
+ ['js', 'f("a\\"b", 2)', '"a\\"b"', 's'],
+ ['js', 'x = `a\nb`', '`a\nb`', 's'],
+ ['js', 'JSON.parse(s)', 'JSON', 'l'],
+ ['ts', 'let a: string = "x"', 'string', 'l'],
+ ['py', 'def f():\n return None', 'def', 'k'],
+ ['py', 'x = """a\nb"""', '"""a\nb"""', 's'],
+ ['py', '@cache\ndef f(): pass', '@cache', 'k'],
+ ['sh', 'echo "$HOME"', 'echo', 'l'],
+ ['sh', 'echo $HOME', '$HOME', 'l'],
+ ['sh', 'curl host/p#frag', '#frag', ''], // NOT a comment
+ ['sh', 'ls # really a comment', '# really a comment', 'c'],
+ ['sh', "echo 'C:\\'", "'C:\\'", 's'], // no backslash escapes
+ ['json', '{"a": 1}', '"a"', 'p'], // a key, not a value
+ ['json', '{"a": "b"}', '"b"', 's'],
+ ['json', '{"a": null}', 'null', 'l'],
+ ['yaml', 'on: push', 'on', 'p'], // key beats the literal
+ ['yaml', 'x: on', 'on', 'l'],
+ ['yaml', 'runs-on: x', 'runs-on', 'p'],
+ ['sql', 'select * from t', 'select', 'k'],
+ ['sql', 'SELECT * FROM t', 'SELECT', 'k'], // case-insensitive
+ ['sql', "a = 'it''s'", "'it''s'", 's'],
+ ['sql', 'x -- note', '-- note', 'c'],
+ ['css', '.a { color: red }', 'color', 'p'],
+ ['css', '.a { color: #1c4fb5 }', '#1c4fb5', 'n'],
+ ['css', '#main { }', '#main', ''], // an id is not a colour
+ ['css', '@media print {}', '@media', 'k'],
+ ['css', 'a { margin: 10px }', '10px', 'n'],
+ ['html', '<div class="a">t</div>', '<div', 'k'],
+ ['html', '<div class="a">t</div>', 'class', 'p'],
+ ['html', '<div class="a">t</div>', '"a"', 's'],
+ ['html', '<div>text</div>', 'text', ''],
+ ['html', '<!-- c --><p>', '<!-- c -->', 'c'],
+ ]
+ for (const [lang, src, needle, want] of cases) {
+ const got = kindAt(src, lang, needle)
+ ok(got === want, `${lang}: ${JSON.stringify(needle)} in ${JSON.stringify(src).slice(0, 34)} → "${got}" (want "${want}")`)
+ }
+
+ // an unterminated string stops at the line, not at end of file: half-written
+ // code is the normal state of a code block, and one stray quote must not turn
+ // the rest of the block into a string while you are typing
+ {
+ const src = 'a = "oops\nb = 2\nc = 3'
+ ok(kindAt(src, 'js', '"oops') === 's' && kindAt(src, 'js', 'b = ') === '',
+ 'an unterminated string ends at the newline, not at end of file')
+ }
+}
+
+// ---- what a code block STORES is plain text, and it round-trips -------------
+// Colour is applied at render time; `Block.html` stays what it always was.
+// `escText` is what the editor writes back, and it must be the exact inverse of
+// the html parser's text decode — otherwise every save of an untouched block
+// differs from the one before it, forever, in a format with no server to fix it.
+{
+ const decode = (s: string): string =>
+ s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
+
+ const texts = [
+ 'const a = 1',
+ 'if (a < b && c > d) {}',
+ '</script><script>alert(1)</script>',
+ '<img src=x onerror="alert(1)">',
+ 'q = "double" and \'single\'',
+ 'a &amp; b', // already-escaped-looking text must survive
+ 'tab\there\nnewline\n\n',
+ '𝔘𝔫𝔦 🎉 中文',
+ ]
+ let round = 0
+ for (const s of texts) if (decode(escText(s)) !== s) round++
+ ok(round === 0, 'escText round-trips through an html text decode, exactly')
+ ok(!escText('say "hi"').includes('&quot;'),
+ 'escText leaves quotes alone — escaping them would make every save differ from the last')
+ ok(escText('a & b') === 'a &amp; b' && escText('<i>') === '&lt;i&gt;',
+ 'escText escapes &, < and > — so a code block can never close its own tag')
+
+ // and the whole document round-trips with code blocks in it
+ const withCode = doc({
+ pages: [{
+ id: 'p1', title: 'Code', blocks: [
+ { id: 'b1', type: 'code', lang: 'js', html: escText('const a = "<b>" // &') },
+ { id: 'b2', type: 'code', lang: 'rust', html: escText('fn main() {}') },
+ { id: 'b3', type: 'code', html: escText('no language at all') },
+ ],
+ }],
+ })
+ const r = parseDoc(withCode)
+ ok(r.ok, 'a document full of code blocks parses')
+ if (r.ok) {
+ ok(r.doc.pages[0].blocks[0].html === 'const a = "&lt;b&gt;" // &amp;',
+ 'a code block\'s html survives parse untouched')
+ ok(r.doc.pages[0].blocks[1].lang === 'rust',
+ 'a language this build cannot highlight is PRESERVED, not normalised away')
+ const again = parseDoc(JSON.stringify(r.doc))
+ ok(again.ok && JSON.stringify(again.doc.pages) === JSON.stringify(r.doc.pages),
+ 'and a second round trip changes nothing')
+ }
+}
+
+// ---- highlighting builds NODES, never a string of markup -------------------
+// The tokenizer cannot emit text (above), so the only place markup could enter
+// is the painter. It must build with createElement/createTextNode and assign
+// through textContent/Text.data — never innerHTML, which is how every other
+// highlighter on the web does it and why they all need their own escaper.
+{
+ const fs = await import('node:fs')
+ const read = (f: string) => fs.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+
+ const hl = read('highlight.ts')
+ ok(!/innerHTML|outerHTML|insertAdjacentHTML|document\./.test(hl),
+ 'highlight.ts touches no DOM at all — it is a pure string→ranges function')
+
+ const ren = read('render.ts')
+ const paint = /export function paintCode[\s\S]*?\n}\n/.exec(ren)?.[0] ?? ''
+ ok(paint.length > 0, 'render.ts exports paintCode')
+ ok(!/innerHTML/.test(paint), 'paintCode never assigns innerHTML')
+ ok(/createTextNode/.test(paint) && /createElement/.test(paint),
+ 'paintCode builds text nodes and elements')
+ ok(/text\.slice\(tk\.a, tk\.b\)/.test(paint),
+ 'every painted string is a SLICE OF THE INPUT, so colouring cannot invent a character')
+
+ // and the editor must read a code host as TEXT. Reading innerHTML there would
+ // write the colour spans into the document — a permanent format change for a
+ // render-time feature.
+ const ed = read('editor.ts')
+ const wireCode = /private wireCode[\s\S]*?\n }\n/.exec(ed)?.[0] ?? ''
+ ok(wireCode.length > 0, 'editor.ts has a dedicated code-block host')
+ ok(!/innerHTML/.test(wireCode) && /host\.textContent/.test(wireCode),
+ 'the code host is read as textContent — colour spans never reach the model')
+ ok(/escText\(text\)/.test(wireCode), 'and stored through escText')
+
+ // A code block is TEXT: Enter must insert a newline rather than split the
+ // block, because the model is now read from textContent and a `<br>` or a
+ // wrapping `<div>` (which is what some engines insert) would vanish from it.
+ ok(/b\.type === 'code'[\s\S]{0,400}insertText\('\\n'\)/.test(ed),
+ 'Enter inside a code block inserts a newline instead of splitting the block')
+
+ // THE TRAILING SPACE IS NOT A SPACE. Measured in Chrome on the built shell:
+ // after typing "## " into an empty block, `host.textContent` is
+ // ['#','#',160] — the engine inserts U+00A0 so the space cannot collapse — so
+ // `/^## $/` never matched and EVERY space-completed markdown trigger was
+ // dead. The ```lang fence needs the same trailing space, which is how this
+ // surfaced. The normalisation is applied to the test text only, never to the
+ // model.
+ ok(/replace\(\/\\u00a0\/g, ' '\)/.test(ed),
+ 'autoformat normalises the NBSP a browser inserts for a trailing space')
+ ok(!/\u00a0/.test(ed), 'and editor.ts carries no LITERAL invisible NBSP, which would not survive retyping')
+}
+
+// ---- one list, everywhere -------------------------------------------------
+// Four features merged in a day, built by agents who could not see each other's
+// work, and every one of them needed to know something the codebase already
+// knew. Each duplicate is a slow bug: the copy is right until the original
+// changes, and then it is wrong in a way nothing reports.
+{
+ const fs3 = await import('node:fs')
+ const rd3 = (f: string) => fs3.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+ const strip = (src: string) => src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
+
+ // the known block types come from the registry, not a second const
+ ok(!/KNOWN_BLOCK_TYPES = \[/.test(strip(rd3('model.ts'))),
+ 'model.ts does not keep a second list of block types')
+ ok(/SPECS\.map\(\(s\) => s\.type\)/.test(rd3('agent.ts')),
+ 'validate() derives known block types from the block registry')
+
+ // the unwrap policy comes from the sanitizer, not a lowercased copy
+ ok(/export const UNWRAP/.test(rd3('sanitize.ts')), 'the sanitizer exports its unwrap set')
+ ok(/\[\.\.\.UNWRAP\]/.test(rd3('agent.ts')),
+ 'validate() derives the unwrap set from the sanitizer rather than restating it')
+}
+
+// ---- five defects an adversarial review reproduced -------------------------
+// All five shipped with every gate green, which is the point: each lived in a
+// case the author's own spot-check did not reach.
+{
+ // 1. Display text must escape ONCE. Everything a hold() placeholder protects
+ // is final markup carrying its own escaping; everything else is escaped by
+ // the single esc() at the end. Link text, wikilink aliases, autolink text
+ // and image alt were escaped twice, so `[Q&A](…)` reached the file as
+ // `Q&amp;amp;A` and the reader saw the entity. Bold and italic were never
+ // affected — their text is outside any placeholder — which is exactly why
+ // "inline formatting survived" passed.
+ for (const [src, want] of [
+ ['[a & b](https://x)', 'a &amp; b'],
+ ['[[Note & co]]', 'Note &amp; co'],
+ ['![alt & x](https://y/p.png)', 'alt &amp; x'],
+ ['**bold & co**', 'bold &amp; co'],
+ ] as Array<[string, string]>) {
+ const got = inlineHtml(src)
+ ok(got.includes(want) && !got.includes('&amp;amp;'),
+ `${src} escapes once (${got.slice(0, 52)})`)
+ }
+
+ // 2. An image is neither a continuation target nor a parent: it has no html,
+ // so a continuation line wrote the literal string "undefined" into the
+ // document and hid the author's text everywhere except search.
+ const capt = parseNote('- ![a picture](pic.png)\n the caption line\n', 'f').blocks
+ ok(!JSON.stringify(capt).includes('undefined'), 'an image caption never writes "undefined" into the document')
+ ok(capt.some((b) => b.type === 'p' && b.html === 'the caption line'),
+ '…the line survives as its own paragraph')
+ ok(!capt.some((b) => b.parent && capt.find((x) => x.id === b.parent)?.type === 'image'),
+ '…and is never parented to the image, which is not a container')
+
+ // 3. No page arrives with zero blocks. A zero-block page has no editable
+ // host, no gutter and no / menu — and the importer navigated to one.
+ const plan = planImport(
+ [{ path: 'V/Home.md', text: '# Home\n\nhi' }, { path: 'V/Sub/A.md', text: '# A\n\nyo' }, { path: 'V/E.md', text: '' }] as never,
+ { rootTitle: 'V' } as never,
+ )
+ ok(plan.pages.every((p: { blocks: unknown[] }) => p.blocks.length > 0),
+ 'every imported page has at least one block, folders and empty files included')
+
+ // 4. A page cycle already in a file (parseDoc keeps it — it only drops
+ // parents naming no page) made the ancestor walk run forever. Measured:
+ // the call never returned and the tab died with its unsaved edits. The
+ // reachable path is the RECOMMENDED one — validate() reports the cycle,
+ // an agent re-homes a page to fix it, and that call hangs.
+ const cyc = parseDoc(JSON.stringify({
+ format: FORMAT, version: 1, docId: 'cyc', title: 'x', home: 'A',
+ pages: [
+ { id: 'A', title: 'A', parent: 'B', blocks: [{ id: 'a', type: 'p', html: 'a' }] },
+ { id: 'B', title: 'B', parent: 'A', blocks: [{ id: 'b', type: 'p', html: 'b' }] },
+ { id: 'C', title: 'C', blocks: [{ id: 'c', type: 'p', html: 'c' }] },
+ ],
+ }))
+ // Checked in the SOURCE as well as in behaviour: without the visited set the
+ // call never returns, so a regression HANGS this rig rather than failing it,
+ // and CI would time out with nothing useful to read. The behavioural check
+ // below still earns its place — it proves termination rather than the
+ // presence of a variable.
+ ok(/const seen = new Set<string>\(\)[\s\S]{0,220}!seen\.has\(up\)/.test(
+ (await import('node:fs')).readFileSync(new URL('../spaces/src/agent.ts', import.meta.url), 'utf8')),
+ 'the ancestor walk carries a visited set')
+
+ ok(cyc.ok, 'a document carrying a page cycle still loads')
+ if (cyc.ok) {
+ const t0 = Date.now()
+ planUpdatePage(cyc.doc as never, 'C', { parent: 'A' } as never)
+ ok(Date.now() - t0 < 1000, 'updatePage terminates on a page cycle instead of hanging the tab')
+ }
+
+ // 5. The markdown quote prefix is applied PER LINE, not per returned element
+ // — a code block's body is one multi-line string, and an unquoted 2nd line
+ // ends the blockquote and unterminates the fence.
+ const fsq = await import('node:fs')
+ const ab = fsq.readFileSync(new URL('../spaces/src/about.ts', import.meta.url), 'utf8')
+ ok(/flatMap\(\(l\) => l\.split\('\\n'\)\)/.test(ab),
+ 'markdown export quotes each LINE of a multi-line block')
+}
+
+// ---- the side panel behaves the way slides' does ---------------------------
+// Two apps in one suite should not teach two different panels. The control that
+// hides a panel belongs on the panel's own EDGE, and it must be visible without
+// hovering — the first version faded in on hover, so the way to hide the panel
+// was invisible until you happened to pass over a 5px strip.
+{
+ const fsp = await import('node:fs')
+ const ed = fsp.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')
+ const css = fsp.readFileSync(new URL('../spaces/src/styles.css', import.meta.url), 'utf8')
+ const ic = fsp.readFileSync(new URL('../spaces/src/icons.ts', import.meta.url), 'utf8')
+
+ ok(/makeResizer\(\)/.test(ed), 'the page list has a resizer strip')
+ ok(/col-resize/.test(css), '…that resizes')
+ ok(/dblclick[\s\S]{0,200}PANE_DEFAULT/.test(ed), '…double-click resets it to the default width')
+ ok(/PANE_MIN[\s\S]{0,400}PANE_MAX/.test(ed) || /Math\.min\(Editor\.PANE_MAX/.test(ed),
+ '…and the width is clamped')
+ ok(/localStorage\.setItem\('bento-sp-pane'/.test(ed),
+ 'the width is the READER\'s — localStorage, never the document')
+
+ ok(/sp-pane-tab/.test(css) && /sp-pane-closed/.test(css), 'the panel collapses from a tab on the strip')
+ const tabRule = css.slice(css.indexOf('.sp-pane-tab {'), css.indexOf('}', css.indexOf('.sp-pane-tab {')))
+ ok(!/opacity:\s*0\b/.test(tabRule), 'the collapse chevron is visible without hovering')
+ ok(/\.sp-side\.sp-pane-closed \+ \.sp-resizer \.sp-pane-tab/.test(css),
+ '…and stays reachable when the panel is closed, docked to the edge')
+
+ // the drawer breakpoint keeps its overlay behaviour: a 0px column on a phone
+ // would leave nothing to reopen from
+ ok(/isDrawer\(\)[\s\S]{0,120}max-width: 820px/.test(ed), 'below 820px the panel is a drawer, not a column')
+
+ // the suite's undo/redo, not a circular arrow that reads as "reload"
+ ok(/M9 14 4 9l5-5/.test(ic) && /m15 14 5-5-5-5/.test(ic),
+ 'undo/redo use the suite\'s glyphs')
+}
+
+// ---- a saved space shows its content to readers that run no script --------
+// The runtime ships deflated and inflates at boot, so with scripting off
+// nothing boots and the splash is never removed: every saved space appeared as
+// the bento boot animation to macOS QuickLook, iOS Files, Bento Tray and any
+// preview pane that renders HTML without executing it. Reported from the field.
+{
+ const fsv = await import('node:fs')
+ const rdv = (f: string) => fsv.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+ const main = rdv('main.ts'), pv = rdv('preview.ts')
+
+ ok(/registerPreview\(/.test(main), 'spaces registers a static first-page preview')
+ ok(/buildSpacePreview/.test(pv), '…built by preview.ts')
+
+ // A still has no runtime, so nothing in it may run, load or take input.
+ for (const tag of ['script', 'iframe', 'input', 'button', 'form', 'video', 'audio']) {
+ ok(new RegExp(`BANNED[^\n]*\\b${tag}\\b`).test(pv), `the preview strips <${tag}>`)
+ }
+ // …and it must never FETCH. A remote <img> here would phone home from a file
+ // manager — the remote-image consent rule, in a place nobody can consent.
+ ok(/'href', 'src', 'srcset'/.test(pv), 'the preview drops href and src')
+ ok(/startsWith\('data:'\)/.test(pv), '…keeping only images already inside the file')
+ ok(/attr\.name\.startsWith\('on'\)/.test(pv), 'and strips every on* handler')
+
+ // nothing to show is not the same as something to hide
+ ok(/if \(!doc\?\.pages\?\.length\) return null/.test(pv),
+ 'a document with no pages produces no preview rather than an empty box')
+
+ // budgeted: a courtesy must never be why a file is large
+ ok(/PREVIEW_BUDGET/.test(pv) && /byteLength\(built\) <= PREVIEW_BUDGET/.test(pv),
+ 'the preview is size-budgeted, with a title card as the fallback')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-spaces-size.mjs b/scripts/test-spaces-size.mjs
new file mode 100644
index 00000000..37fd4253
--- /dev/null
+++ b/scripts/test-spaces-size.mjs
@@ -0,0 +1,70 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The shell-size ceiling, enforced.
+//
+// node scripts/test-spaces-size.mjs [--update]
+//
+// WHY THIS EXISTS. docs/DECISIONS.md set a 100KB ceiling for bento/spaces and
+// the round finished at 108KB. That is not the failure — features were worth
+// their bytes and the ceiling was raised deliberately. The failure is that the
+// same entry said "the ceiling is checked per feature from here" and shipped NO
+// MECHANISM, so the breach was found by a reviewer reading the number, weeks of
+// features later, rather than by the build that caused it.
+//
+// A budget nobody measures is a wish. This measures it.
+//
+// It is a CEILING, not a target: a feature that needs bytes takes them and
+// raises the number here in the same commit, which is a two-line diff a
+// reviewer can see and argue with. What it stops is the drift nobody chose —
+// forty commits each costing 300 bytes.
+//
+// Spaces ships in ONE file that people mail to each other, and every byte is
+// paid on every open, on every phone, forever. Slides is 560KB because it grew
+// for a year without one of these.
+
+import { readFileSync, writeFileSync, statSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)))
+const BUDGETS = join(root, 'scripts/size-budgets.json')
+
+const budgets = JSON.parse(readFileSync(BUDGETS, 'utf8'))
+const update = process.argv.includes('--update')
+
+let failures = 0
+for (const [name, b] of Object.entries(budgets.shells)) {
+ const path = join(root, b.path)
+ let bytes
+ try { bytes = statSync(path).size } catch {
+ console.log(` skip ${name} — not built (${b.path})`)
+ continue
+ }
+ const pct = ((bytes / b.max) * 100).toFixed(1)
+ const head = `${name.padEnd(8)} ${String(bytes).padStart(7)} B of ${b.max} B (${pct}%)`
+
+ if (update) {
+ b.max = bytes
+ console.log(` set ${head} → new ceiling`)
+ continue
+ }
+ if (bytes > b.max) {
+ failures++
+ console.log(` FAIL ${head}`)
+ console.log(` over by ${bytes - b.max} B. Either give the bytes back, or raise`)
+ console.log(` "${name}".max in scripts/size-budgets.json IN THIS COMMIT and say`)
+ console.log(` in the message what bought them. Do not raise it silently.`)
+ } else {
+ console.log(` ok ${head}`)
+ }
+}
+
+if (update) {
+ writeFileSync(BUDGETS, `${JSON.stringify(budgets, null, 2)}\n`)
+ console.log('\nbudgets rewritten to the current sizes')
+ process.exit(0)
+}
+
+console.log(failures ? `\n${failures} shell(s) over budget` : '\nall shells within budget')
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-sync-equiv.ts b/scripts/test-sync-equiv.ts
new file mode 100644
index 00000000..325f8e9e
--- /dev/null
+++ b/scripts/test-sync-equiv.ts
@@ -0,0 +1,988 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// ===========================================================================
+// bento-sync ENGINE EQUIVALENCE rig — baseline vs candidate, BYTE for BYTE.
+//
+// node scripts/test-sync-equiv.ts (Node ≥ 23.6 strips types)
+// SEEDS=200 STEPS=60 ACTORS=4 node scripts/test-sync-equiv.ts
+// SEED_ONLY=17 node scripts/test-sync-equiv.ts (repro one seed)
+// MUTANT=pos-spread node scripts/test-sync-equiv.ts (see it fail)
+//
+// ┌───────────────────────────────────────────────────────────────────────┐
+// │ LOUD WARNING — AS OF THIS COMMIT THIS RIG PASSES TRIVIALLY. │
+// │ │
+// │ There is only ONE engine in the tree today, so the "candidate" │
+// │ import below resolves to the SAME MODULE as the baseline. Node │
+// │ dedupes it: baseline === candidate, literally the same object. A │
+// │ green run here currently proves NOTHING about parameterization — │
+// │ it proves the comparator runs. The rig announces this at startup │
+// │ (`NO-OP RUN`) and will announce `LIVE RUN` the moment the candidate │
+// │ import points somewhere else. Do not read a NO-OP green as safety. │
+// │ │
+// │ Because a never-failed comparator is worth nothing, the rig ends │
+// │ with a SELF-TEST: it builds four deliberately perturbed engines │
+// │ that are still perfectly CONVERGENT (scripts/test-sync.ts passes │
+// │ every one of them) and asserts that this rig catches all four. That │
+// │ is the part of a NO-OP run that does carry signal. │
+// └───────────────────────────────────────────────────────────────────────┘
+//
+// WHY THIS EXISTS. spaces is getting live collaboration by PARAMETERIZING
+// this engine over a document-shape descriptor (slides→elements becomes
+// pages→blocks) rather than forking it. Every bento/slides file in the
+// field already carries persisted SyncStateJSON and already talks to the
+// deployed relay. If parameterization changes ANY byte the engine mints —
+// an op, a frame, a snapshot, a fractional position key, a lamport
+// ordering — those files diverge from each other silently, in the field,
+// with no way to push a fix.
+//
+// scripts/test-sync.ts proves CONVERGENCE, which is strictly weaker: an
+// engine that converges beautifully with ITSELF while minting different
+// bytes than the shipped engine sails straight through it. (The four
+// self-test mutants below are exactly that engine.) This rig is the
+// missing property: the candidate must be OBSERVATIONALLY IDENTICAL to
+// what is already on disk.
+//
+// WHAT IT COMPARES, per step, for every actor:
+// 1. the op batch just emitted — JSON.stringify of the array, so field
+// ORDER inside each op counts (ops are minted as object literals, so
+// their key order is deterministic and observable on the wire);
+// 2. SyncStateJSON — JSON.stringify of toJSON(), so key insertion order
+// counts too (this is the blob stamped into doc.collab.sync; a
+// key-order-only difference is reported as such, not hidden);
+// 3. the materialized document — JSON.stringify of the live doc.
+// Plus a scripted scenario suite for the paths random runs never reach:
+// adopt(), mergeSnapshot(), fromJSON(), missingFor(), the pre-v2 reject,
+// the 300KB text RGA, and the duplicate-id morph idiom.
+//
+// DETERMINISM. One seeded PRNG stream (mulberry32, shared with
+// test-sync.ts via scripts/lib/sync-fixtures.ts) picks the whole schedule.
+// Each step's mutation is generated from its own sub-seed derived from
+// (seed, step), so a difference in how much randomness one side consumes
+// can never cascade. No Date.now, no unseeded Math.random anywhere: a
+// failure is reproducible from SEED_ONLY alone.
+
+import {
+ mulberry32,
+ stable,
+ baseDoc,
+ randomMutation,
+ type Doc,
+} from './lib/sync-fixtures.ts'
+
+import * as BASELINE_MODULE from '../slides/src/sync/crdt.ts'
+// ───────────────────────────────────────────────────────────────────────────
+// THE ONE LINE. When the parameterized engine lands, repoint THIS import (and
+// nothing else in this file) at it — e.g.
+// import * as CANDIDATE_MODULE from '../kernel/src/sync/crdt.ts'
+// and the rig turns from a NO-OP into the gate that protects every shipped
+// bento/slides file. If the candidate's entry point needs a shape descriptor,
+// bind it in `CANDIDATE` below (the Engine adapter is the seam).
+import * as CANDIDATE_MODULE from '../slides/src/sync/crdt.ts'
+// ───────────────────────────────────────────────────────────────────────────
+
+// ---------------------------------------------------------------------------
+// engine seam — the smallest structural surface both engines must present
+// ---------------------------------------------------------------------------
+
+type Op = any
+type StateJSON = any
+
+interface EngineState {
+ actor: string
+ lamport: number
+ pos: Record<string, { p: string; o: string; r: [number, string] }>
+ adopt(doc: Doc): void
+ diff(before: Doc, after: Doc, opts?: { text?: boolean }): Op[]
+ apply(doc: Doc, ops: Op[]): { changed: boolean; structure: boolean }
+ mergeSnapshot(doc: Doc, rdoc: Doc, rstate: StateJSON): { changed: boolean; structure: boolean }
+ missingFor(log: Op[], vv: Record<string, number>): Op[]
+ toJSON(): StateJSON
+ dead(id: string): boolean
+ readonly gappedActors: string[]
+}
+
+interface Engine {
+ label: string
+ SyncState: new (actor: string) => EngineState
+ fromJSON: (actor: string, j: StateJSON) => EngineState
+}
+
+type CrdtModule = typeof BASELINE_MODULE
+
+function engineOf(label: string, M: CrdtModule): Engine {
+ return {
+ label,
+ SyncState: M.SyncState as unknown as new (actor: string) => EngineState,
+ fromJSON: (a, j) => M.SyncState.fromJSON(a, j) as unknown as EngineState,
+ }
+}
+
+const BASELINE = engineOf('baseline', BASELINE_MODULE)
+const CANDIDATE = engineOf('candidate', CANDIDATE_MODULE)
+const IS_NOOP = (BASELINE_MODULE as unknown) === (CANDIDATE_MODULE as unknown)
+
+// ---------------------------------------------------------------------------
+// replicas and worlds (engine-parameterized twins of test-sync.ts's Replica)
+// ---------------------------------------------------------------------------
+
+class Replica {
+ doc: Doc
+ state: EngineState
+ shadow: string
+ log: Op[] = []
+ undoStack: string[] = []
+ counter = 0
+ actor: string
+ constructor(E: Engine, actor: string, doc: Doc = baseDoc()) {
+ this.actor = actor
+ this.doc = doc
+ this.state = new E.SyncState(actor)
+ this.state.adopt(this.doc)
+ this.shadow = JSON.stringify(this.doc)
+ }
+ mutate(fn: (doc: Doc) => void): Op[] {
+ this.undoStack.push(this.shadow)
+ fn(this.doc)
+ return this.flush()
+ }
+ undo(): Op[] {
+ const prev = this.undoStack.pop()
+ if (!prev) return []
+ this.doc = JSON.parse(prev)
+ return this.flush()
+ }
+ flush(): Op[] {
+ const ops = this.state.diff(JSON.parse(this.shadow), this.doc, { text: true })
+ this.shadow = JSON.stringify(this.doc)
+ this.log.push(...ops)
+ return ops
+ }
+ receive(ops: Op[]) {
+ this.state.apply(this.doc, ops)
+ this.log.push(...ops)
+ this.shadow = JSON.stringify(this.doc)
+ }
+ /** byte-exact: this is what lands in the saved file */
+ docBytes(): string {
+ return JSON.stringify(this.doc)
+ }
+ /** byte-exact: this is what lands in doc.collab.sync */
+ stateBytes(): string {
+ return JSON.stringify(this.state.toJSON())
+ }
+ /** key-order-independent view, for telling "reordered" from "different" */
+ docCanon(): string {
+ return stable(this.doc)
+ }
+ stateCanon(): string {
+ // EVERYTHING toJSON() emits, minus what is legitimately volatile — not a
+ // hand-picked list of the fields that existed when this was written. The
+ // listed version compared six keys, so a SEVENTH added by the very
+ // parameterization this rig exists to check would have been invisible to
+ // it: the rig would go green on an engine minting a field the baseline
+ // never mints. Deleting is the only direction that fails safe.
+ const j = this.state.toJSON() as unknown as Record<string, unknown>
+ const canon: Record<string, unknown> = { ...j }
+ // dead nodes' text is retained deliberately and is not part of the
+ // observable state (see crdt.ts's stash/replay); everything else counts.
+ canon.txt = Object.fromEntries(
+ Object.entries(j.txt as Record<string, unknown>).filter(([id]) => !this.state.dead(id)),
+ )
+ return stable(canon)
+ }
+}
+
+const qk = (f: number, t: number) => `${f}>${t}`
+
+class World {
+ reps: Replica[]
+ queues = new Map<string, Op[][]>()
+ constructor(E: Engine, n: number) {
+ this.reps = Array.from({ length: n }, (_, i) => new Replica(E, `a${i}`))
+ for (let f = 0; f < n; f++) for (let t = 0; t < n; t++) if (f !== t) this.queues.set(qk(f, t), [])
+ }
+}
+
+/** One scheduled action. Decided ONCE off the master stream, run on BOTH
+ * worlds — so the two engines are never asked different questions. */
+type Step =
+ | { t: 'mut'; actor: number; undo: boolean; mseed: number }
+ | { t: 'deliver'; edge: string }
+ | { t: 'idle' }
+
+/** @returns the actor touched and the ops that moved, or null if the world
+ * could not perform the step (queue shape diverged — itself a finding). */
+function exec(w: World, st: Step): { actor: number; ops: Op[] } | null {
+ if (st.t === 'idle') return { actor: -1, ops: [] }
+ if (st.t === 'mut') {
+ const r = w.reps[st.actor]
+ if (!r) return null
+ const ops = st.undo ? r.undo() : r.mutate(randomMutation(r, mulberry32(st.mseed)))
+ if (ops.length) {
+ for (let t = 0; t < w.reps.length; t++) {
+ if (t !== st.actor) w.queues.get(qk(st.actor, t))!.push(ops)
+ }
+ }
+ return { actor: st.actor, ops }
+ }
+ const q = w.queues.get(st.edge)
+ if (!q || !q.length) return null
+ const to = parseInt(st.edge.split('>')[1], 10)
+ const ops = q.shift()!
+ w.reps[to].receive(ops)
+ return { actor: to, ops }
+}
+
+// ---------------------------------------------------------------------------
+// divergence reporting — someone reads this at 1am
+// ---------------------------------------------------------------------------
+
+interface Div {
+ what: string
+ seed: number
+ step: number | string
+ actor: string
+ a: string
+ b: string
+ note?: string
+ repro?: string
+}
+
+let firstDiv: Div | null = null
+let divCount = 0
+
+/** first differing character, with context on both sides */
+function byteDiff(a: string, b: string): string {
+ let i = 0
+ while (i < a.length && i < b.length && a[i] === b[i]) i++
+ const lo = Math.max(0, i - 60)
+ const cut = (s: string) => JSON.stringify(s.slice(lo, i + 100))
+ return [
+ ` first difference at byte ${i} (lengths ${a.length} / ${b.length})`,
+ ` baseline : …${cut(a)}`,
+ ` candidate: …${cut(b)}`,
+ ].join('\n')
+}
+
+/** structural paths where two parsed JSON values differ (capped) */
+function pathDiff(a: string, b: string, limit = 12): string {
+ let av: unknown, bv: unknown
+ try {
+ av = JSON.parse(a)
+ bv = JSON.parse(b)
+ } catch {
+ return ''
+ }
+ const out: string[] = []
+ const shorten = (v: unknown) => {
+ const s = JSON.stringify(v)
+ return s === undefined ? 'undefined' : s.length > 90 ? s.slice(0, 90) + '…' : s
+ }
+ const walk = (x: any, y: any, path: string) => {
+ if (out.length >= limit) return
+ if (x === y) return
+ const xo = x && typeof x === 'object'
+ const yo = y && typeof y === 'object'
+ if (!xo || !yo || Array.isArray(x) !== Array.isArray(y)) {
+ if (JSON.stringify(x) !== JSON.stringify(y)) out.push(` ${path || '<root>'}: ${shorten(x)} ≠ ${shorten(y)}`)
+ return
+ }
+ const keys = [...new Set([...Object.keys(x), ...Object.keys(y)])]
+ for (const k of keys) {
+ // element node keys are composite (slideId U+001F elementId) — an
+ // invisible separator in a debug path is a trap, so show it escaped
+ const kk = k.replace(/[\u0000-\u001f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)
+ const p = Array.isArray(x) ? `${path}[${kk}]` : path ? `${path}.${kk}` : kk
+ if (!(k in x)) { out.push(` ${p}: <absent> ≠ ${shorten(y[k])}`); continue }
+ if (!(k in y)) { out.push(` ${p}: ${shorten(x[k])} ≠ <absent>`); continue }
+ walk(x[k], y[k], p)
+ if (out.length >= limit) return
+ }
+ // same values, different key order → the bytes differ, the meaning doesn't
+ if (!out.length && Object.keys(x).join(',') !== Object.keys(y).join(',')) {
+ out.push(` ${path || '<root>'}: same entries, DIFFERENT KEY ORDER`)
+ }
+ }
+ walk(av, bv, '')
+ return out.length ? ' diverging paths:\n' + out.join('\n') : ''
+}
+
+function reportDiv(d: Div) {
+ console.error('')
+ console.error(' ╭─ DIVERGENCE ──────────────────────────────────────────────')
+ console.error(` │ what : ${d.what}`)
+ if (d.seed) console.error(` │ seed : ${d.seed}`)
+ console.error(` │ step : ${d.step}`)
+ if (d.actor !== '-') console.error(` │ actor : ${d.actor}`)
+ if (d.note) console.error(` │ note : ${d.note}`)
+ console.error(
+ ` │ reproduce : ${d.repro ?? `SEED_ONLY=${d.seed} STEPS=${STEPS} ACTORS=${ACTORS} node scripts/test-sync-equiv.ts`}`,
+ )
+ console.error(' ╰───────────────────────────────────────────────────────────')
+ console.error(byteDiff(d.a, d.b))
+ const p = pathDiff(d.a, d.b)
+ if (p) console.error(p)
+}
+
+/** @returns true when it diverged */
+function cmp(what: string, seed: number, step: number | string, actor: string, a: string, b: string, canon?: [string, string], repro?: string): boolean {
+ if (a === b) return false
+ divCount++
+ const note = canon && canon[0] === canon[1] ? 'KEY ORDER ONLY — same values, different serialized order' : undefined
+ const d: Div = { what, seed, step, actor, a, b, note, repro }
+ if (!firstDiv) {
+ firstDiv = d
+ reportDiv(d)
+ }
+ return true
+}
+
+// ---------------------------------------------------------------------------
+// the random equivalence run
+// ---------------------------------------------------------------------------
+
+const SEEDS = parseInt(process.env.SEEDS ?? '60', 10)
+const SEED_ONLY = process.env.SEED_ONLY ? parseInt(process.env.SEED_ONLY, 10) : 0
+const STEPS = parseInt(process.env.STEPS ?? '80', 10)
+const ACTORS = parseInt(process.env.ACTORS ?? '3', 10)
+
+/**
+ * Run one seed against both engines in lockstep.
+ * @returns true when the two engines stayed byte-identical.
+ */
+function equivSeed(A: Engine, B: Engine, seed: number, steps: number, actors: number): boolean {
+ const rnd = mulberry32(seed * 7919)
+ const wa = new World(A, actors)
+ const wb = new World(B, actors)
+
+ // the file as adopted, before anything happens: this is where a changed
+ // spreadKey / adoption order shows up first
+ for (let i = 0; i < actors; i++) {
+ if (checkActor(seed, 'adopt', wa, wb, i)) return false
+ }
+
+ for (let s = 0; s < steps; s++) {
+ // ---- decide the step off the master stream (baseline world's shape) ----
+ let st: Step
+ const dice = rnd()
+ if (dice < 0.45) {
+ const actor = Math.floor(rnd() * actors)
+ const undo = rnd() < 0.06
+ st = { t: 'mut', actor, undo, mseed: (seed * 1_000_003 + s * 7919 + 17) >>> 0 }
+ } else {
+ const edges = [...wa.queues.entries()].filter(([, q]) => q.length)
+ st = edges.length ? { t: 'deliver', edge: edges[Math.floor(rnd() * edges.length)][0] } : { t: 'idle' }
+ }
+
+ // ---- run it on both ----------------------------------------------------
+ const ra = exec(wa, st)
+ const rb = exec(wb, st)
+ if (!ra || !rb) {
+ cmp('step could not be replayed (queue shape diverged)', seed, s, st.t === 'mut' ? `a${st.actor}` : st.t,
+ JSON.stringify({ ran: !!ra, step: st, queues: [...wa.queues].map(([k, q]) => [k, q.length]) }),
+ JSON.stringify({ ran: !!rb, step: st, queues: [...wb.queues].map(([k, q]) => [k, q.length]) }))
+ return false
+ }
+
+ // 1. the ops this step moved, field order included
+ const label = st.t === 'mut' ? (st.undo ? 'undo' : 'mutate') : 'deliver'
+ if (cmp(`ops emitted (${label})`, seed, s, `a${ra.actor}`, JSON.stringify(ra.ops), JSON.stringify(rb.ops))) {
+ return false
+ }
+ // 2 + 3. every actor's state and doc
+ for (let i = 0; i < actors; i++) if (checkActor(seed, s, wa, wb, i)) return false
+ }
+
+ // ---- drain to quiescence, comparing all the way -------------------------
+ let moved = true
+ let d = 0
+ while (moved) {
+ moved = false
+ for (const [key, q] of wa.queues) {
+ if (!q.length) continue
+ moved = true
+ const st: Step = { t: 'deliver', edge: key }
+ const ra = exec(wa, st)
+ const rb = exec(wb, st)
+ if (!ra || !rb) {
+ cmp('drain could not be replayed (queue shape diverged)', seed, `drain:${d}`, key, String(!!ra), String(!!rb))
+ return false
+ }
+ if (cmp('ops emitted (drain)', seed, `drain:${d}`, `a${ra.actor}`, JSON.stringify(ra.ops), JSON.stringify(rb.ops))) return false
+ for (let i = 0; i < actors; i++) if (checkActor(seed, `drain:${d}`, wa, wb, i)) return false
+ d++
+ }
+ }
+ return true
+}
+
+function checkActor(seed: number, step: number | string, wa: World, wb: World, i: number): boolean {
+ const a = wa.reps[i]
+ const b = wb.reps[i]
+ const sa = a.stateBytes()
+ const sb = b.stateBytes()
+ if (sa !== sb) {
+ cmp('SyncStateJSON', seed, step, a.actor, sa, sb, [a.stateCanon(), b.stateCanon()])
+ return true
+ }
+ const da = a.docBytes()
+ const db = b.docBytes()
+ if (da !== db) {
+ cmp('materialized document', seed, step, a.actor, da, db, [a.docCanon(), b.docCanon()])
+ return true
+ }
+ return false
+}
+
+// ---------------------------------------------------------------------------
+// scripted scenarios — the code paths a random walk never reaches
+// ---------------------------------------------------------------------------
+
+type Transcript = Array<[string, string]>
+interface Scenario {
+ name: string
+ run: (E: Engine) => Transcript
+}
+
+const J = (v: unknown) => JSON.stringify(v)
+const snap = (t: Transcript, label: string, r: Replica) => {
+ t.push([`${label}/state`, r.stateBytes()])
+ t.push([`${label}/doc`, r.docBytes()])
+}
+
+const SCENARIOS: Scenario[] = [
+ {
+ // The single highest-risk parameterization site: adopt() derives every
+ // fractional position key for a file that has never synced. Change it and
+ // two copies of one shipped file stop agreeing about order.
+ name: 'adopt: fresh file → deterministic pos keys',
+ run: (E) => {
+ const t: Transcript = []
+ const r = new Replica(E, 'A')
+ snap(t, 'adopt', r)
+ const big: Doc = baseDoc()
+ for (let i = 0; i < 25; i++) {
+ big.slides.push({ id: `x${i}`, background: '#000', transition: 'none', notes: '', elements: Array.from({ length: 1 + (i % 7) }, (_, j) => ({ id: `x${i}-${j}`, type: 'shape', shape: 'rect', x: j, y: i, w: 10, h: 10, rotation: 0, opacity: 1, fill: '#111', stroke: 'none', strokeWidth: 0, radius: 0 })) })
+ }
+ const r2 = new Replica(E, 'A', big)
+ snap(t, 'adopt-wide', r2)
+ return t
+ },
+ },
+ {
+ name: 'scripted edits: one replica, every op kind',
+ run: (E) => {
+ const t: Transcript = []
+ const r = new Replica(E, 'A')
+ const steps: Array<[string, (d: Doc) => void]> = [
+ ['doc-prop', (d) => { d.title = 'Scripted' }],
+ ['nested-doc-prop', (d) => { d.theme = { ...d.theme, accent: '#123456' } }],
+ ['asset', (d) => { d.assets = { ...d.assets, mark: '<svg id="m"/>' } }],
+ ['slide-prop', (d) => { d.slides[0].background = '#abcdef' }],
+ ['el-prop', (d) => { d.slides[0].elements[1].x = 640 }],
+ ['el-insert', (d) => d.slides[0].elements.push({ id: 'new-1', type: 'shape', shape: 'rect', x: 1, y: 2, w: 30, h: 40, rotation: 0, opacity: 1, fill: '#0f0', stroke: 'none', strokeWidth: 0, radius: 2 })],
+ ['el-reorder', (d) => { const [e] = d.slides[0].elements.splice(0, 1); d.slides[0].elements.push(e) }],
+ ['el-move-slide', (d) => { const [e] = d.slides[0].elements.splice(0, 1); d.slides[2].elements.push(e) }],
+ ['el-delete', (d) => { d.slides[0].elements.splice(0, 1) }],
+ ['slide-insert', (d) => d.slides.splice(1, 0, { id: 'ins-1', background: '#222', transition: 'none', notes: 'n', elements: [{ id: 'ins-1-t', type: 'text', x: 0, y: 0, w: 100, h: 20, rotation: 0, opacity: 1, html: 'hi', fontSize: 12, fontFamily: 'x', fontWeight: 400, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 }] })],
+ ['slide-reorder', (d) => { const [s] = d.slides.splice(0, 1); d.slides.push(s) }],
+ ['slide-delete', (d) => { d.slides.splice(0, 1) }],
+ ['text-edit', (d) => { const e = d.slides.flatMap((s: any) => s.elements).find((x: any) => typeof x.html === 'string'); if (e) e.html = 'pre ' + e.html + ' post' }],
+ ['undo-ish', (d) => { d.title = 'Scripted' }],
+ ]
+ for (const [label, fn] of steps) {
+ const ops = r.mutate(fn)
+ t.push([`${label}/ops`, J(ops)])
+ snap(t, label, r)
+ }
+ t.push(['undo/ops', J(r.undo())])
+ snap(t, 'undo', r)
+ return t
+ },
+ },
+ {
+ name: 'gap buffering + catch-up',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const b1 = A.mutate((d) => { d.title = 'one' })
+ const b2 = A.mutate((d) => { d.title = 'two' })
+ const b3 = A.mutate((d) => { d.title = 'three' })
+ t.push(['batches', J([b1, b2, b3])])
+ B.receive(b3)
+ t.push(['gapped', J(B.state.gappedActors)])
+ snap(t, 'held', B)
+ B.receive(b1)
+ snap(t, 'first', B)
+ B.receive(b2)
+ snap(t, 'drained', B)
+ t.push(['gapped-after', J(B.state.gappedActors)])
+ return t
+ },
+ },
+ {
+ name: 'undo resurrects a deleted slide',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const del = A.mutate((d) => d.slides.splice(1, 1))
+ t.push(['del/ops', J(del)])
+ B.receive(del)
+ snap(t, 'B-deleted', B)
+ const res = A.undo()
+ t.push(['undo/ops', J(res)])
+ B.receive(res)
+ snap(t, 'B-resurrected', B)
+ snap(t, 'A-resurrected', A)
+ return t
+ },
+ },
+ {
+ name: 'move-out vs slide-delete cascade',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const mv = A.mutate((d) => {
+ const s1 = d.slides.find((s: any) => s.id === 's1')
+ const s3 = d.slides.find((s: any) => s.id === 's3')
+ const i = s1.elements.findIndex((e: any) => e.id === 's1-r1')
+ const [el] = s1.elements.splice(i, 1)
+ s3.elements.push(el)
+ })
+ const del = B.mutate((d) => d.slides.splice(0, 1))
+ t.push(['mv/ops', J(mv)])
+ t.push(['del/ops', J(del)])
+ A.receive(del)
+ B.receive(mv)
+ snap(t, 'A', A)
+ snap(t, 'B', B)
+ return t
+ },
+ },
+ {
+ name: 'RGA: concurrent text edits merge',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const ea = A.mutate((d) => { const el = d.slides[0].elements[0]; el.html = 'START ' + el.html })
+ const eb = B.mutate((d) => { const el = d.slides[0].elements[0]; el.html = el.html + ' END' })
+ t.push(['ea', J(ea)])
+ t.push(['eb', J(eb)])
+ A.receive(eb)
+ B.receive(ea)
+ snap(t, 'A', A)
+ snap(t, 'B', B)
+ // same-position runs
+ const C = new Replica(E, 'C')
+ const D = new Replica(E, 'D')
+ const ec = C.mutate((d) => (d.slides[0].elements[0].html = 'Hello ABC <b>world</b>'))
+ const ed = D.mutate((d) => (d.slides[0].elements[0].html = 'Hello XYZ <b>world</b>'))
+ C.receive(ed)
+ D.receive(ec)
+ snap(t, 'C', C)
+ snap(t, 'D', D)
+ return t
+ },
+ },
+ {
+ name: 'snapshot merge (offline fork, late joiner)',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ A.mutate((d) => (d.title = 'A says'))
+ A.mutate((d) => d.slides[0].elements.push({ id: 'A-x', type: 'shape', shape: 'rect', x: 5, y: 5, w: 10, h: 10, rotation: 0, opacity: 1, fill: '#333', stroke: 'none', strokeWidth: 0, radius: 0 }))
+ B.mutate((d) => (d.slides[2].background = '#654321'))
+ B.mutate((d) => d.slides.splice(1, 1))
+ const aDoc = JSON.parse(JSON.stringify(A.doc))
+ const aState = JSON.parse(JSON.stringify(A.state.toJSON()))
+ const bDoc = JSON.parse(JSON.stringify(B.doc))
+ const bState = JSON.parse(JSON.stringify(B.state.toJSON()))
+ t.push(['A-merge', J(A.state.mergeSnapshot(A.doc, bDoc, bState))])
+ A.shadow = JSON.stringify(A.doc)
+ t.push(['B-merge', J(B.state.mergeSnapshot(B.doc, aDoc, aState))])
+ B.shadow = JSON.stringify(B.doc)
+ snap(t, 'A', A)
+ snap(t, 'B', B)
+ const C = new Replica(E, 'C')
+ t.push(['C-join', J(C.state.mergeSnapshot(C.doc, JSON.parse(JSON.stringify(A.doc)), A.state.toJSON()))])
+ snap(t, 'C', C)
+ return t
+ },
+ },
+ {
+ name: 'op-log catch-up (missingFor)',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const batches = [
+ A.mutate((d) => (d.title = 'x1')),
+ A.mutate((d) => (d.slides[0].background = '#222222')),
+ A.mutate((d) => d.slides[0].elements.push({ id: 'A-q', type: 'shape', shape: 'rect', x: 9, y: 9, w: 10, h: 10, rotation: 0, opacity: 1, fill: '#444', stroke: 'none', strokeWidth: 0, radius: 0 })),
+ ]
+ B.receive(batches[0])
+ const missing = B.state.missingFor(A.log, B.state.toJSON().vv)
+ t.push(['missing', J(missing)])
+ B.receive(missing)
+ snap(t, 'B', B)
+ return t
+ },
+ },
+ {
+ name: 'state serialization round-trip + pre-v2 reject',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ A.mutate((d) => (d.title = 'persisted'))
+ A.mutate((d) => d.slides[0].elements.push({ id: 'p-1', type: 'shape', shape: 'rect', x: 4, y: 4, w: 10, h: 10, rotation: 0, opacity: 1, fill: '#555', stroke: 'none', strokeWidth: 0, radius: 0 }))
+ const saved = A.stateBytes()
+ t.push(['saved', saved])
+ const restored = E.fromJSON('A', JSON.parse(saved))
+ t.push(['restored', JSON.stringify(restored.toJSON())])
+ // an offline fork rejoining: restored state must defend its edits
+ const forked = new Replica(E, 'F')
+ forked.doc = JSON.parse(JSON.stringify(A.doc))
+ forked.state = E.fromJSON('F', JSON.parse(saved))
+ forked.shadow = JSON.stringify(forked.doc)
+ t.push(['fork/ops', J(forked.mutate((d) => (d.title = 'forked offline')))])
+ snap(t, 'fork', forked)
+ // pre-v2 blobs are discarded on sight
+ const legacy = { lamport: 9, vv: { Z: 4 }, regs: { 'cast x': [9, 'Z'] }, pos: {}, births: {}, tombs: {}, txt: {}, stash: {}, limbo: {} }
+ t.push(['legacy-fromJSON', JSON.stringify(E.fromJSON('A', legacy as StateJSON).toJSON())])
+ const L = new Replica(E, 'L')
+ t.push(['legacy-merge', J(L.state.mergeSnapshot(L.doc, baseDoc(), legacy as StateJSON))])
+ snap(t, 'legacy', L)
+ return t
+ },
+ },
+ {
+ name: 'duplicate element id across slides (morph idiom)',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const castOn = (d: Doc, sid: string) =>
+ d.slides.find((s: any) => s.id === sid).elements.find((e: any) => e.id === 'cast')
+ const ea = A.mutate((d) => (castOn(d, 's1').html = 'ONE ' + castOn(d, 's1').html))
+ const eb = B.mutate((d) => (castOn(d, 's2').html = castOn(d, 's2').html + ' TWO'))
+ t.push(['ea', J(ea)])
+ t.push(['eb', J(eb)])
+ A.receive(eb)
+ B.receive(ea)
+ snap(t, 'A', A)
+ snap(t, 'B', B)
+ // colliding moves onto one slide
+ const C = new Replica(E, 'C')
+ const D = new Replica(E, 'D')
+ const mv = (d: Doc, from: string) => {
+ const f = d.slides.find((s: any) => s.id === from)
+ const s3 = d.slides.find((s: any) => s.id === 's3')
+ const i = f.elements.findIndex((e: any) => e.id === 'cast')
+ const [el] = f.elements.splice(i, 1)
+ s3.elements.push(el)
+ }
+ const mc = C.mutate((d) => mv(d, 's1'))
+ const md = D.mutate((d) => mv(d, 's2'))
+ C.receive(md)
+ D.receive(mc)
+ snap(t, 'C', C)
+ snap(t, 'D', D)
+ return t
+ },
+ },
+ {
+ name: 'large text (300KB) tokenizes and merges',
+ run: (E) => {
+ const t: Transcript = []
+ const A = new Replica(E, 'A')
+ const B = new Replica(E, 'B')
+ const big = 'word '.repeat(60_000)
+ const ea = A.mutate((d) => { d.slides[0].elements[0].html = big + ' AAA' })
+ const eb = B.mutate((d) => { d.slides[0].elements[0].html = d.slides[0].elements[0].html + ' BBB' })
+ A.receive(eb)
+ B.receive(ea)
+ // full bytes would be ~10MB of transcript; the merged text and the RGA
+ // token stream are captured by hash + shape, which is still byte-exact
+ // detection (any change to either changes the hash)
+ t.push(['ea-shape', J(ea.map((o: any) => [o.op, o.l, o.s, (o.ins ?? []).length, (o.del ?? []).length, o.base?.length ?? 0]))])
+ t.push(['eb-shape', J(eb.map((o: any) => [o.op, o.l, o.s, (o.ins ?? []).length, (o.del ?? []).length, o.base?.length ?? 0]))])
+ t.push(['A-doc-hash', hash(A.docBytes())])
+ t.push(['A-state-hash', hash(A.stateBytes())])
+ t.push(['B-doc-hash', hash(B.docBytes())])
+ t.push(['B-state-hash', hash(B.stateBytes())])
+ t.push(['merged-html', A.doc.slides[0].elements[0].html.slice(-40) + '|' + A.doc.slides[0].elements[0].html.length])
+ return t
+ },
+ },
+]
+
+/** FNV-1a — only for the one scenario whose byte transcript is megabytes */
+function hash(s: string): string {
+ let h = 0x811c9dc5
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i)
+ h = Math.imul(h, 0x01000193) >>> 0
+ }
+ return h.toString(16).padStart(8, '0') + ':' + s.length
+}
+
+function runScenarios(A: Engine, B: Engine): boolean {
+ let allOk = true
+ const repro = 'RANDOM=0 node scripts/test-sync-equiv.ts (scenarios are fixed scripts — no seed involved)'
+ for (const sc of SCENARIOS) {
+ const ta = sc.run(A)
+ const tb = sc.run(B)
+ if (ta.length !== tb.length) {
+ cmp(`scenario "${sc.name}" transcript length`, 0, sc.name, '-', J(ta.map((x) => x[0])), J(tb.map((x) => x[0])), undefined, repro)
+ allOk = false
+ continue
+ }
+ for (let i = 0; i < ta.length; i++) {
+ if (ta[i][0] !== tb[i][0] || ta[i][1] !== tb[i][1]) {
+ cmp(`scenario "${sc.name}" → ${ta[i][0]}`, 0, sc.name, '-', ta[i][1], tb[i][1], undefined, repro)
+ allOk = false
+ break
+ }
+ }
+ if (!allOk) break
+ }
+ return allOk
+}
+
+// ---------------------------------------------------------------------------
+// SELF-TEST: engines that CONVERGE but do not MATCH
+//
+// Each mutant is a legal, self-consistent, fully convergent CRDT — every one
+// of them passes scripts/test-sync.ts — that mints different bytes than the
+// shipped engine. They are the exact failure mode parameterization risks, and
+// they are the only evidence a NO-OP run can offer that this rig works.
+// ---------------------------------------------------------------------------
+
+type MutantName = 'pos-spread' | 'lamport-skew' | 'op-field-order' | 'state-key-order'
+
+const MUTANT_WHY: Record<MutantName, string> = {
+ 'pos-spread': 'adopt() derives different (but still order-preserving) fractional keys',
+ 'lamport-skew': 'one extra lamport tick per diff — same order, different stamps',
+ 'op-field-order': 'ops carry identical fields in a different serialization order',
+ 'state-key-order': 'SyncStateJSON.regs serialized in a different key order',
+}
+
+function mutantEngine(M: CrdtModule, name: MutantName): Engine {
+ const Base = M.SyncState as any
+ let Cls: any
+ switch (name) {
+ case 'pos-spread':
+ Cls = class extends Base {
+ adopt(doc: Doc) {
+ super.adopt(doc)
+ for (const k of Object.keys(this.pos)) {
+ const p = this.pos[k]
+ // only the null-register keys adoption itself minted; 'M' prefix
+ // is order-preserving, so materialized order is unchanged
+ if (p.r[0] === 0 && p.r[1] === '' && !p.o.startsWith('M')) p.o = 'M' + p.o
+ }
+ }
+ }
+ break
+ case 'lamport-skew':
+ Cls = class extends Base {
+ diff(before: Doc, after: Doc, opts: { text?: boolean } = {}) {
+ this.lamport++
+ return super.diff(before, after, opts)
+ }
+ }
+ break
+ case 'op-field-order':
+ Cls = class extends Base {
+ diff(before: Doc, after: Doc, opts: { text?: boolean } = {}) {
+ return super.diff(before, after, opts).map((op: Op) => {
+ const out: any = {}
+ for (const k of Object.keys(op).reverse()) out[k] = op[k]
+ return out
+ })
+ }
+ }
+ break
+ case 'state-key-order':
+ Cls = class extends Base {
+ toJSON() {
+ const j = super.toJSON()
+ return { ...j, regs: Object.fromEntries(Object.entries(j.regs).reverse()) }
+ }
+ }
+ break
+ }
+ return {
+ label: `mutant:${name}`,
+ SyncState: Cls,
+ // crdt.ts's `static fromJSON` constructs `new SyncState(actor)` literally —
+ // not `new this(actor)` — so a subclass cannot be produced through it, and
+ // this returned an UNMUTATED engine. Every scenario that round-trips state
+ // therefore tested the baseline against itself while reporting mutant
+ // coverage, which is the one lie a self-test must not tell.
+ //
+ // Re-pointing the prototype is a test-harness liberty, taken here rather
+ // than changing one word in the shipped engine: this step's whole
+ // acceptance criterion is that `git diff slides/ kernel/ server/` is empty.
+ fromJSON: (a, j) => {
+ const base = M.SyncState.fromJSON(a, j)
+ Object.setPrototypeOf(base, Cls.prototype)
+ return base as unknown as EngineState
+ },
+ }
+}
+
+/** does this engine converge with ITSELF? (what test-sync.ts asks) */
+function convergesWithItself(E: Engine, seeds: number, steps: number, actors: number): boolean {
+ for (let seed = 1; seed <= seeds; seed++) {
+ const rnd = mulberry32(seed * 7919)
+ const w = new World(E, actors)
+ for (let s = 0; s < steps; s++) {
+ const dice = rnd()
+ if (dice < 0.45) {
+ const actor = Math.floor(rnd() * actors)
+ exec(w, { t: 'mut', actor, undo: rnd() < 0.06, mseed: (seed * 1_000_003 + s * 7919 + 17) >>> 0 })
+ } else {
+ const edges = [...w.queues.entries()].filter(([, q]) => q.length)
+ if (edges.length) exec(w, { t: 'deliver', edge: edges[Math.floor(rnd() * edges.length)][0] })
+ }
+ }
+ let moved = true
+ while (moved) {
+ moved = false
+ for (const [key, q] of w.queues) {
+ if (!q.length) continue
+ moved = true
+ exec(w, { t: 'deliver', edge: key })
+ }
+ }
+ const doc0 = w.reps[0].docCanon()
+ const st0 = w.reps[0].stateCanon()
+ for (let i = 1; i < actors; i++) {
+ if (w.reps[i].docCanon() !== doc0 || w.reps[i].stateCanon() !== st0) return false
+ }
+ }
+ return true
+}
+
+/**
+ * Which comparator fires first on this mutant? The caller stubs console.error
+ * (a mutant's diffs are expected noise), and the global divergence bookkeeping
+ * is saved and restored so a self-test never colours the real verdict.
+ */
+function whatCatches(A: Engine, B: Engine, seeds: number, steps: number, actors: number): string[] {
+ const caught = new Set<string>()
+ const saveFirst = firstDiv
+ const saveCount = divCount
+ for (let seed = 1; seed <= seeds; seed++) {
+ firstDiv = null
+ if (!equivSeed(A, B, seed, steps, actors)) {
+ if (firstDiv) caught.add((firstDiv as Div).what.replace(/ \(.*\)$/, ''))
+ }
+ }
+ if (!runScenarios(A, B)) caught.add('scenario')
+ firstDiv = saveFirst
+ divCount = saveCount
+ return [...caught]
+}
+
+// ---------------------------------------------------------------------------
+// main
+// ---------------------------------------------------------------------------
+
+const t0 = process.hrtime.bigint()
+const ms = (from: bigint) => Number(process.hrtime.bigint() - from) / 1e6
+
+console.log('bento-sync equivalence rig — baseline vs candidate, byte for byte')
+if (IS_NOOP) {
+ console.log('')
+ console.log(' ############################################################')
+ console.log(' # NO-OP RUN. The candidate import resolves to the SAME #')
+ console.log(' # module as the baseline (they are === at runtime), so #')
+ console.log(' # the comparison below is vacuous BY CONSTRUCTION. Green #')
+ console.log(' # here says nothing about any parameterized engine — it #')
+ console.log(' # only says the comparator runs. The SELF-TEST at the end #')
+ console.log(' # is the part with signal. Repoint the CANDIDATE_MODULE #')
+ console.log(' # import (one line, marked in the header) to go LIVE. #')
+ console.log(' ############################################################')
+ console.log('')
+} else {
+ console.log('')
+ console.log(` LIVE RUN — candidate is a distinct module (${CANDIDATE.label}).`)
+ console.log('')
+}
+
+const MUTANT = process.env.MUTANT as MutantName | undefined
+const candidate = MUTANT ? mutantEngine(CANDIDATE_MODULE, MUTANT) : CANDIDATE
+if (MUTANT) console.log(` MUTANT=${MUTANT} — candidate deliberately perturbed: ${MUTANT_WHY[MUTANT]}\n`)
+
+let failed = false
+
+// --- scenarios -------------------------------------------------------------
+if (process.env.SCENARIOS !== '0') {
+ const t = process.hrtime.bigint()
+ const okScen = runScenarios(BASELINE, candidate)
+ console.log(`scripted scenarios: ${SCENARIOS.length} scripts, ${okScen ? 'identical' : 'DIVERGED'} (${ms(t).toFixed(0)}ms)`)
+ if (!okScen) failed = true
+}
+
+// --- random runs -----------------------------------------------------------
+if (process.env.RANDOM !== '0') {
+ const t = process.hrtime.bigint()
+ const from = SEED_ONLY || 1
+ const to = SEED_ONLY || SEEDS
+ let run = 0
+ let bad = false
+ for (let seed = from; seed <= to; seed++) {
+ run++
+ if (!equivSeed(BASELINE, candidate, seed, STEPS, ACTORS)) {
+ bad = true
+ failed = true
+ break
+ }
+ }
+ console.log(
+ `random runs: ${run} of ${to - from + 1} seed(s) × ${STEPS} steps × ${ACTORS} actors — ` +
+ `${bad ? 'DIVERGED' : 'identical'} (${ms(t).toFixed(0)}ms)`,
+ )
+}
+
+// --- self-test -------------------------------------------------------------
+if (process.env.SELFTEST !== '0' && !MUTANT) {
+ console.log('')
+ console.log('self-test — engines that CONVERGE but do not MATCH:')
+ const suppress = console.error
+ const names: MutantName[] = ['pos-spread', 'lamport-skew', 'op-field-order', 'state-key-order']
+ for (const name of names) {
+ const mut = mutantEngine(BASELINE_MODULE, name)
+ const converges = convergesWithItself(mut, 4, 60, 3)
+ console.error = () => {} // the mutants' diffs are expected noise
+ const caught = whatCatches(BASELINE, mut, 4, 60, 3)
+ console.error = suppress
+ const good = converges && caught.length > 0
+ if (!good) failed = true
+ console.log(
+ ` ${good ? '✓' : '✗'} ${name.padEnd(16)} converges: ${converges ? 'yes' : 'NO'} ` +
+ `→ test-sync.ts would ${converges ? 'PASS' : 'fail'} it; ` +
+ `this rig catches it via [${caught.join(', ') || 'NOTHING — RIG IS BLIND'}]`,
+ )
+ console.log(` (${MUTANT_WHY[name]})`)
+ }
+}
+
+console.log('')
+if (failed) {
+ console.log(`FAILED — ${divCount} divergence(s); the first is printed above.`)
+} else if (IS_NOOP) {
+ console.log(`PASS (trivially — candidate === baseline). total ${ms(t0).toFixed(0)}ms`)
+} else {
+ console.log(`PASS — candidate is byte-identical to baseline. total ${ms(t0).toFixed(0)}ms`)
+}
+process.exit(failed ? 1 : 0)
diff --git a/scripts/test-sync.ts b/scripts/test-sync.ts
index afc4e30d..f7a90909 100644
--- a/scripts/test-sync.ts
+++ b/scripts/test-sync.ts
@@ -16,6 +16,10 @@
import { SyncState, keyBetween, spreadKey, tokenize, materialize } from '../slides/src/sync/crdt.ts'
import type { Op } from '../slides/src/sync/crdt.ts'
+// Generator + fixtures are SHARED with scripts/test-sync-equiv.ts (the
+// byte-equivalence rig) — one opinion about what a document and an edit are.
+import { mulberry32, stable, baseDoc, randomMutation } from './lib/sync-fixtures.ts'
+import type { Doc } from './lib/sync-fixtures.ts'
let failures = 0
let checks = 0
@@ -27,30 +31,6 @@ function ok(cond: boolean, msg: string) {
}
}
-// deterministic PRNG
-function mulberry32(seed: number) {
- let t = seed >>> 0
- return () => {
- t += 0x6d2b79f5
- let r = Math.imul(t ^ (t >>> 15), 1 | t)
- r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r
- return ((r ^ (r >>> 14)) >>> 0) / 4294967296
- }
-}
-
-function stable(v: unknown): string {
- if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`
- if (v && typeof v === 'object') {
- const o = v as Record<string, unknown>
- return `{${Object.keys(o)
- .sort()
- .filter((k) => o[k] !== undefined)
- .map((k) => `${JSON.stringify(k)}:${stable(o[k])}`)
- .join(',')}}`
- }
- return JSON.stringify(v)
-}
-
// ---------------------------------------------------------------------------
// keyBetween / spreadKey / tokenize unit properties
// ---------------------------------------------------------------------------
@@ -110,48 +90,6 @@ function stable(v: unknown): string {
// simulated replicas
// ---------------------------------------------------------------------------
-type Doc = any
-
-function baseDoc(): Doc {
- return {
- format: 'bento/slides',
- version: 1,
- docId: 'doc-1',
- title: 'Rig deck',
- size: { width: 1600, height: 900 },
- theme: { background: '#0D1B2E', color: '#F2F0EA', accent: '#FF9E8A', fontFamily: 'x' },
- assets: { logo: '<svg/>' },
- slides: [
- {
- id: 's1',
- background: '#0D1B2E',
- transition: 'none',
- notes: '',
- elements: [
- { id: 's1-t1', type: 'text', x: 100, y: 100, w: 600, h: 80, rotation: 0, opacity: 1, html: 'Hello <b>world</b>', fontSize: 40, fontFamily: 'x', fontWeight: 700, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 },
- { id: 's1-r1', type: 'shape', shape: 'rect', x: 200, y: 300, w: 200, h: 120, rotation: 0, opacity: 1, fill: '#FF9E8A', stroke: 'none', strokeWidth: 0, radius: 8 },
- { id: 's1-r2', type: 'shape', shape: 'ellipse', x: 500, y: 300, w: 90, h: 90, rotation: 0, opacity: 1, fill: '#5E7699', stroke: 'none', strokeWidth: 0, radius: 0 },
- // 'cast' appears on s1 AND s2 — the id-continuity morph idiom
- // (starterdeck's sd-tile-*). Every random run exercises it.
- { id: 'cast', type: 'text', x: 900, y: 100, w: 300, h: 60, rotation: 0, opacity: 1, html: 'Morph <b>me</b>', fontSize: 28, fontFamily: 'x', fontWeight: 700, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 },
- ],
- },
- {
- id: 's2',
- background: '#F2F0EA',
- transition: 'morph',
- notes: 'second',
- elements: [
- { id: 's2-t1', type: 'text', x: 120, y: 120, w: 500, h: 60, rotation: 0, opacity: 1, html: 'Numbers &amp; facts', fontSize: 30, fontFamily: 'x', fontWeight: 400, color: '#111', align: 'left', valign: 'top', lineHeight: 1.3 },
- { id: 'cast', type: 'text', x: 200, y: 500, w: 600, h: 120, rotation: 0, opacity: 1, html: 'Morph <b>me</b>', fontSize: 56, fontFamily: 'x', fontWeight: 700, color: '#111', align: 'left', valign: 'top', lineHeight: 1.2 },
- ],
- },
- { id: 's3', background: '#16273E', transition: 'fade', notes: '', elements: [] },
- ],
- modified: 'never',
- }
-}
-
class Replica {
doc: Doc
state: SyncState
@@ -204,109 +142,6 @@ class Replica {
}
}
-// mutation menu — mirrors what the editor's commit sites do
-function randomMutation(r: Replica, rnd: () => number): (doc: Doc) => void {
- const pick = <T>(xs: T[]): T => xs[Math.floor(rnd() * xs.length)]
- const kind = Math.floor(rnd() * 12)
- return (doc: Doc) => {
- const slides = doc.slides
- const sl = pick(slides)
- if (!sl && kind !== 8) return // remote deletes can empty the deck
- switch (kind) {
- case 0: // doc prop
- doc.title = `Deck ${Math.floor(rnd() * 1000)}`
- break
- case 1: // theme (nested doc prop)
- doc.theme = { ...doc.theme, accent: `#${Math.floor(rnd() * 0xffffff).toString(16).padStart(6, '0')}` }
- break
- case 2: // slide prop
- sl.background = `#${Math.floor(rnd() * 0xffffff).toString(16).padStart(6, '0')}`
- break
- case 3: {
- // element prop
- const els = slides.flatMap((s: any) => s.elements)
- if (!els.length) break
- const el = pick(els)
- el.x = Math.floor(rnd() * 1600)
- el.y = Math.floor(rnd() * 900)
- break
- }
- case 4: {
- // insert element
- const id = `${r.actor}-e${r.counter++}`
- sl.elements.push({ id, type: 'shape', shape: 'rect', x: Math.floor(rnd() * 1000), y: Math.floor(rnd() * 700), w: 120, h: 80, rotation: 0, opacity: 1, fill: '#8FA3BF', stroke: 'none', strokeWidth: 0, radius: 4 })
- break
- }
- case 5: {
- // delete element
- const s = pick(slides.filter((x: any) => x.elements.length)) as any
- if (!s) break
- s.elements.splice(Math.floor(rnd() * s.elements.length), 1)
- break
- }
- case 6: {
- // move element across slides. Target must not already carry the
- // element's id: bare ids are unique WITHIN a slide (format
- // invariant the editor upholds); duplication ACROSS slides is the
- // morph idiom and legal.
- const from = pick(slides.filter((x: any) => x.elements.length)) as any
- if (!from || slides.length < 2) break
- const i = Math.floor(rnd() * from.elements.length)
- const to = pick(
- slides.filter((x: any) => x !== from && !x.elements.some((e: any) => e.id === from.elements[i].id)),
- ) as any
- if (!to) break
- const [el] = from.elements.splice(i, 1)
- to.elements.splice(Math.floor(rnd() * (to.elements.length + 1)), 0, el)
- break
- }
- case 7: {
- // reorder elements (z-order)
- if (sl.elements.length < 2) break
- const i = Math.floor(rnd() * sl.elements.length)
- const [el] = sl.elements.splice(i, 1)
- sl.elements.splice(Math.floor(rnd() * (sl.elements.length + 1)), 0, el)
- break
- }
- case 8: {
- // insert slide
- const id = `${r.actor}-s${r.counter++}`
- slides.splice(Math.floor(rnd() * (slides.length + 1)), 0, {
- id, background: '#123', transition: 'none', notes: '',
- elements: [{ id: `${id}-t`, type: 'text', x: 50, y: 50, w: 300, h: 50, rotation: 0, opacity: 1, html: 'new', fontSize: 20, fontFamily: 'x', fontWeight: 400, color: '#fff', align: 'left', valign: 'top', lineHeight: 1.2 }],
- })
- break
- }
- case 9: // delete slide
- if (slides.length > 1) slides.splice(Math.floor(rnd() * slides.length), 1)
- break
- case 10: {
- // reorder slides
- if (slides.length < 2) break
- const i = Math.floor(rnd() * slides.length)
- const [s] = slides.splice(i, 1)
- slides.splice(Math.floor(rnd() * (slides.length + 1)), 0, s)
- break
- }
- case 11: {
- // text edit
- const els = slides.flatMap((s: any) => s.elements).filter((e: any) => typeof e.html === 'string')
- if (!els.length) break
- const el = pick(els)
- const h: string = el.html
- if (rnd() < 0.5 && h.length > 2) {
- const i = Math.floor(rnd() * (h.length - 1))
- el.html = h.slice(0, i) + h.slice(i + 1 + Math.floor(rnd() * Math.min(3, h.length - i - 1)))
- } else {
- const i = Math.floor(rnd() * (h.length + 1))
- el.html = h.slice(0, i) + pick(['X', 'yz', ' q', '<i>!</i>', '&amp;']) + h.slice(i)
- }
- break
- }
- }
- }
-}
-
// ---------------------------------------------------------------------------
// random convergence runs
// ---------------------------------------------------------------------------
diff --git a/slides/src/sync/crdt.ts b/slides/src/sync/crdt.ts
index 33dcb301..aad5f415 100644
--- a/slides/src/sync/crdt.ts
+++ b/slides/src/sync/crdt.ts
@@ -895,7 +895,15 @@ export class SyncState {
// stale guard: the parked value must belong to the CURRENT register —
// a newer set that applied elsewhere supersedes it
if (cmpReg(ent.r, r) !== 0) continue
- dbg(id, `stash-replay ${k} := ${JSON.stringify(ent.v).slice(0, 40)}`)
+ // String(): a REMOVAL parks an entry with no `v`, and
+ // JSON.stringify(undefined) is undefined — `.slice` on that throws, and
+ // dbg's argument is built eagerly whether or not debugging is on. This is
+ // the SAME defect fixed at the `set` site above, in the second place it
+ // occurs: the fix went where the bug was found rather than everywhere the
+ // pattern was, and the rig covered the found site only. Reached whenever a
+ // property removal is stashed during a node's dead window and replayed on
+ // resurrection.
+ dbg(id, `stash-replay ${k} := ${String(JSON.stringify(ent.v)).slice(0, 40)}`)
if ('v' in ent) node[k] = clone(ent.v)
else delete node[k]
if (k === 'html') delete this.txt[id]
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index b5fdbe6b..c77858d8 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -14,6 +14,62 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
## [Unreleased]
+- **Callouts.** A boxed note, tip, important, warning or caution — `/callout`,
+ the Insert menu, or type `[!warning] ` on an empty line. Press ⏎ inside one
+ and the next line goes in with it; an empty line and ⌫ takes you back out.
+ Click the mark to change which kind it is, or to give it an emoji of your own.
+ The kind is named in words as well as coloured, so it survives a
+ black-and-white printout and reads correctly without colour vision, and it
+ exports as a GitHub alert (`> [!WARNING]`) with its nested blocks intact — including multi-line ones, which the first version quietly broke: a nested code block left its 2nd line unquoted, which ends the blockquote and unterminates the fence.
+- **Code blocks are highlighted**, in eight languages — JavaScript, TypeScript,
+ Python, Shell, JSON, YAML, SQL, HTML/XML and CSS — with a plain rendering for
+ everything else. No library: the whole lexer, painter and palette cost 5.4KB
+ in the shell, where highlight.js alone is ~120KB. Colour is applied when the
+ page is drawn and never enters the document, so a highlighted block is the
+ same bytes on disk as an unhighlighted one, and reading view and print show
+ exactly what the editor shows.
+
+- **A code block says what it is, and you can change it.** Hover a block for its
+ language chip; the fence takes the language with it, so ` ```py ` opens a
+ Python block. A language this build cannot highlight is kept as written —
+ ` ```rust ` still round-trips, still exports as ` ```rust `, and will light up
+ by itself when the lexer learns it.
+
+- **Fixed: markdown shortcuts did not fire.** A space typed at the end of a
+ line is inserted by the browser as a non-breaking space, so `# `, `- `, `1. `,
+ `> `, `[] ` and `--- ` never matched their triggers. All of them work now.
+
+- **Fixed: Enter and Tab inside a code block.** Enter adds a line instead of
+ splitting the block, and Tab indents by two spaces instead of re-parenting the
+ block in the page tree.
+- **Import the notes you already have.** Drop a folder of `.md` files onto the
+ window — or pick them — and each file becomes a page, the folder tree becomes
+ the page tree, and `[[wikilinks]]` between the files become real links you can
+ click. An Obsidian vault arrives with its structure intact: headings, lists,
+ to-dos, quotes, fenced code with its language, dividers and inline
+ `**bold**` / `*italic*` / `` `code` `` / `~~strike~~` / `[links](url)`.
+ Frontmatter is kept verbatim in a folded block rather than being interpreted,
+ because spaces has no properties model yet and inventing one in an importer
+ would settle it by accident. Include the image files in the selection and
+ they are embedded; an image the browser cannot open keeps its path as text
+ instead of becoming a broken picture. The whole import is one undo step, and
+ pages are always ADDED — nothing already in the space is replaced.
+- **A space can be authored by an agent without flying blind.** `window.bento`
+ gains `validate()` — every duplicate id, dead link, unknown block type,
+ un-`alt`-ed image, orphaned asset and unreachable page, each with a severity
+ and a fix — plus `outline()` (the whole tree, with headings, in one call) and
+ `stats()` (where the bytes went, biggest assets first). `validate()` is
+ silent on a good document; that is enforced by the test rig against the space
+ every new file opens with.
+
+- **Structured edits instead of rewriting the file.** `updateBlock`,
+ `removeBlocks`, `moveBlock`, `updatePage` and `removePage` join
+ `insertBlocks`, each one undoable step, each refusing rather than silently
+ ignoring what it cannot do. A refused edit leaves no undo entry behind.
+ Everything an agent writes goes through the editor's own sanitizer first, so
+ the API cannot put anything in a file that the app itself could not have
+ written.
+
## [0.1.0] — 2026-08-03
First release.
diff --git a/spaces/README.md b/spaces/README.md
index be2d6bb8..df6fac10 100644
--- a/spaces/README.md
+++ b/spaces/README.md
@@ -52,6 +52,12 @@ Three decisions worth knowing before editing the model:
else at load, and matches `href` against `getAttribute('href')` rather than
`.href`, because the resolved property hides `javascript:` behind a base URL.
+A `code` block's `html` is its source as **plain text**, html-escaped. Syntax
+colour is applied when the page is drawn (`src/highlight.ts` → `paintCode` in
+`src/render.ts`) and never enters the document, so the same block is the same
+bytes whether or not the reading build knows the language — and an unknown
+`lang` is preserved verbatim rather than normalised away.
+
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
@@ -66,7 +72,10 @@ load contract and format additivity.
| `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/highlight.ts` | the code lexer — text → `{kind, a, b}` ranges, no DOM, no strings |
+| `src/markdown.ts` | markdown → blocks, the folder tree → the page tree, `[[wikilinks]]` → `#p/` links. Pure and DOM-free, so the import is tested in node |
| `src/editor.ts` | topbar, sidebar, block menu, `[[` picker, ⌘K, ⌘F, archive |
+| `src/agent.ts` | the agent surface — `validate()`, `outline()`, `stats()`, and the patch verbs behind `window.bento` |
| `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 |
@@ -83,6 +92,22 @@ 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.
+### Getting notes in
+
+Drop a folder of `.md` files on the window, or use Pages → import. Each file
+becomes a page, folders become the page tree, and `[[wikilinks]]` are resolved
+**after every page exists**, by file name first and page title second — a
+target outside the import stays as the literal `[[Name]]` rather than silently
+un-linking. The parse (`src/markdown.ts`) is pure and DOM-free; the browser
+half (`editor.ts importFiles`) reads image bytes, runs `sanitizeInline` over
+every block, and commits the whole import in ONE step. Frontmatter is kept
+verbatim in a marked block — the reasoning is in `docs/DECISIONS.md`.
+
+An image referenced by a relative path is resolved against the files that were
+actually selected; when it is not there, the block becomes text quoting the
+path, because a browser cannot open `../attachments/x.png` and a broken `<img>`
+would be a lie about what is in the file.
+
### Links are fragments
`#p/<id>`, and navigation is `history.pushState(null, '', '#p/id')`. Measured:
diff --git a/spaces/index.html b/spaces/index.html
index fbf7bb31..5885103f 100644
--- a/spaces/index.html
+++ b/spaces/index.html
@@ -18,27 +18,33 @@
<script type="application/bento+json" id="bento-doc"></script>
</head>
<body>
- <div id="bento-splash">
- <div class="sp-splash-mark">bento<span>/</span>spaces</div>
+ <!-- splash: pure CSS, paints before the bundle parses; main.ts dismisses it -->
+ <div id="bento-splash" aria-hidden="true">
+ <div class="bs-mark"><i class="bs-a"></i><i class="bs-b"></i><i class="bs-c"></i></div>
+ <div class="bs-word"><b>Bento</b>/Spaces</div>
+ <div class="bs-bar"><i></i></div>
</div>
<style>
- #bento-splash {
- position: fixed;
- inset: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- background: #fff;
- z-index: 9999;
- transition: opacity 0.45s ease;
- font: 600 20px/1.4 ui-sans-serif, system-ui, -apple-system, sans-serif;
- color: #1e2a3a;
- }
- #bento-splash.done { opacity: 0; pointer-events: none; }
- .sp-splash-mark span { color: #ff9e8a; }
- @media (prefers-reduced-motion: reduce) {
- #bento-splash { transition: none; }
- }
+#bento-splash{position:fixed;inset:0;z-index:9999;display:grid;place-content:center;justify-items:center;gap:26px;background:radial-gradient(130% 90% at 50% 38%,#1c2c44 0%,#101c2c 58%,#0a1220 100%);pointer-events:none;transition:opacity .5s ease;animation:bsAuto .6s ease 9s both}
+#bento-splash.done{opacity:0}
+.bs-mark{position:relative;width:104px;height:104px;border-radius:24px;background:#16273e;box-shadow:0 0 56px rgba(255,238,214,.26),0 10px 34px rgba(0,0,0,.55);overflow:hidden;animation:bsIn .7s cubic-bezier(.22,1.4,.36,1) both,bsFloat 3.4s ease-in-out .9s infinite}
+.bs-mark i{position:absolute;border-radius:9px;opacity:0;animation:bsTile .55s cubic-bezier(.25,1.5,.45,1) both}
+.bs-b{left:12px;top:12px;width:24px;height:80px;background:#5e7699;animation-delay:.18s}
+.bs-a{right:12px;top:12px;width:50px;height:37px;background:#ff9e8a;animation-delay:.3s}
+.bs-c{right:12px;bottom:12px;width:50px;height:37px;background:#f0ebe0;animation-delay:.42s}
+.bs-mark:after{content:"";position:absolute;inset:0;background:linear-gradient(115deg,transparent 38%,rgba(255,255,255,.35) 50%,transparent 62%);transform:translateX(-130%);animation:bsSheen 1s ease 1.05s both}
+.bs-word{font:600 15px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;color:#e8edf4;letter-spacing:.42em;text-transform:uppercase;text-indent:.42em;animation:bsUp .6s ease .55s both}
+.bs-word b{color:#ff9e8a;font-weight:800}
+.bs-bar{width:124px;height:2px;border-radius:1px;background:rgba(255,255,255,.13);overflow:hidden;animation:bsUp .5s ease .85s both}
+.bs-bar i{display:block;width:44%;height:100%;border-radius:1px;background:linear-gradient(90deg,#ff9e8a,#ffbca8);animation:bsScan 1.1s cubic-bezier(.45,0,.55,1) 1s infinite alternate}
+@keyframes bsIn{from{transform:scale(.55) rotate(-8deg);opacity:0}}
+@keyframes bsTile{from{transform:translateY(28px) scale(.6);opacity:0}to{transform:none;opacity:1}}
+@keyframes bsSheen{to{transform:translateX(130%)}}
+@keyframes bsFloat{50%{transform:translateY(-5px)}}
+@keyframes bsUp{from{opacity:0;transform:translateY(10px)}}
+@keyframes bsScan{from{transform:translateX(-30%)}to{transform:translateX(210%)}}
+@keyframes bsAuto{to{opacity:0;visibility:hidden}}
+@media (prefers-reduced-motion:reduce){#bento-splash,#bento-splash *,.bs-mark:after{animation-duration:.01ms;animation-delay:0ms;animation-iteration-count:1}}
</style>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
diff --git a/spaces/src/about.ts b/spaces/src/about.ts
index 597268c3..8dc7a407 100644
--- a/spaces/src/about.ts
+++ b/spaces/src/about.ts
@@ -9,20 +9,33 @@
import { checkForUpdates, applyUpdate, APP_VERSION, type ReleaseInfo } from '../../kernel/src/update.ts'
import {
- setEncryptionPassword, isEncryptionActive, saveFile,
+ setEncryptionPassword, isEncryptionActive,
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 { inertBody, esc } from './sanitize'
+import { SPEC, mdLayout } from './blocks'
import type { Store } from './store'
export interface AboutHooks {
store: Store
onRepaint: () => void
+ /**
+ * "Save a copy…", supplied by the caller.
+ *
+ * NOT saveFile(doc, true) here. That path assigns the picked handle to the
+ * kernel's in-place handle, so every later ⌘S writes to the copy — the bug
+ * fixed in the topbar's copy button, which this second button then kept
+ * alive because the guard only read main.ts. One implementation, two
+ * buttons, and the assertion now reads every file.
+ */
+ onSaveCopy: () => void
+ /** open the markdown importer — the way IN, opposite the ways out below */
+ onImport?: () => void
}
-export function openAbout({ store, onRepaint }: AboutHooks): void {
+export function openAbout({ store, onRepaint, onSaveCopy, onImport }: AboutHooks): void {
const back = document.createElement('div')
back.className = 'sp-overlay'
const card = document.createElement('div')
@@ -54,6 +67,23 @@ export function openAbout({ store, onRepaint }: AboutHooks): void {
}
// ---- what this is ------------------------------------------------------
+ // The same head slides uses: the suite's mark, the app, the version, and a
+ // gentle route back to the site. A dialog that opens with a section heading
+ // does not tell you what you are looking at.
+ const head = document.createElement('div')
+ head.className = 'sp-about-head'
+ head.innerHTML =
+ '<a class="sp-about-logo" href="https://bento.page" target="_blank" rel="noopener">' +
+ '<svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true">' +
+ '<rect width="32" height="32" rx="7" fill="#16273E"/>' +
+ '<rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/>' +
+ '<rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/>' +
+ '<rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/>' +
+ '</svg><div><b>bento<span style="color:#FF9E8A">/</span>spaces</b>' +
+ `<span>v${APP_VERSION} · ${esc(t('format v{v}', { v: String(store.doc.version ?? 1) }))}</span></div></a>`
+ head.querySelector('a')?.setAttribute('title', t('Visit bento.page (opens in a new tab)'))
+ card.append(head)
+
card.append(h(t('This file')))
const blurb = document.createElement('p')
blurb.className = 'sp-about-blurb'
@@ -150,6 +180,18 @@ export function openAbout({ store, onRepaint }: AboutHooks): void {
pwNote.textContent = t('Password set. Save to write the space encrypted.')
}))
+ // ---- the way in ---------------------------------------------------------
+ // Beside the ways out on purpose: a format that can only be left is a
+ // format nobody arrives in.
+ if (onImport) {
+ card.append(h(t('Bring notes in')))
+ card.append(button(t('Import Markdown…'), () => { close(); onImport() }))
+ const inNote = document.createElement('p')
+ inNote.className = 'sp-note'
+ inNote.textContent = t('A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.')
+ card.append(inNote)
+ }
+
// ---- ways out ----------------------------------------------------------
card.append(h(t('Take it elsewhere')))
const exports = document.createElement('div')
@@ -159,7 +201,7 @@ export function openAbout({ store, onRepaint }: AboutHooks): void {
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) }),
+ button(t('Save a copy…'), () => { close(); onSaveCopy() }),
)
card.append(exports)
const outNote = document.createElement('p')
@@ -194,26 +236,33 @@ export function toMarkdown(store: Store): 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 ? ' ' : ''
+ // Indent, blockquote markers and what separates one block from the next
+ // are properties of the TREE, not of a block, so they come from the
+ // registry in one pass (blocks.ts mdLayout).
+ const layout = mdLayout(page.blocks)
+ page.blocks.forEach((b, i) => {
+ const { quote, indent, sep } = layout[i]
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(`![${String(b.alt ?? '')}](${String(b.src ?? '')})`); break
- case 'pagelink': out.push(`→ [[${store.index.page.get(String(b.page))?.title ?? '?'}]]`); break
- default: out.push(text)
- }
- out.push('')
- }
+ // From the block registry, so a new type exports correctly the moment
+ // it is declared. An UNKNOWN type — a file written by a newer build —
+ // falls through to its text, which is the honest default.
+ const spec = SPEC.get(b.type)
+ const lines = spec?.toMd
+ ? spec.toMd(b, text, indent, (id) => store.index.page.get(id)?.title)
+ : [text]
+ // PER LINE, not per returned element. A spec returns ELEMENTS, and an
+ // element can hold newlines: a code block's body is one multi-line
+ // string, and htmlToMd turns <br> into a newline in ordinary text. Any
+ // such child inside a callout left its 2nd..nth lines unquoted, which
+ // ENDS the blockquote — the GitHub alert stops there, a nested fence is
+ // left unterminated, and the rest of the callout falls out of the box
+ // as broken prose. The callout's own toMd split on \n; nothing else did.
+ //
+ // An empty line inside a quote must be a bare '>', never '> ' and never
+ // blank: a blank line closes the blockquote.
+ out.push(...lines.flatMap((l) => l.split('\n')).map((l) => (l ? quote + l : quote.trimEnd())))
+ out.push(sep)
+ })
walk(page.id, depth + 1)
}
}
diff --git a/spaces/src/agent.ts b/spaces/src/agent.ts
new file mode 100644
index 00000000..e7ebbcfd
--- /dev/null
+++ b/spaces/src/agent.ts
@@ -0,0 +1,926 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The agent surface: what `window.bento` reports, and how it is patched.
+//
+// WHY THIS EXISTS. An agent authoring a space is working blind in a way a human
+// author is not. Everything that goes wrong here goes wrong SILENTLY: a link to
+// a page that was renamed away still looks like a link in the JSON, a `<p>` in
+// a block's html is unwrapped at render with no complaint, an unknown block
+// type falls back to its text, an `asset:` reference that nothing points at is
+// just megabytes. None of it throws, and none of it is visible in the document
+// the agent just wrote. `validate()` is the pass that says so out loud.
+//
+// The other half is writing. Before this, the only structural verbs were
+// `insertBlocks` and `newPage`; everything else meant `loadDoc(JSON.stringify(
+// wholeDocument))`, which flattens undo to one entry, clobbers whatever a human
+// typed while the agent was thinking, and re-mints nothing but is trusted with
+// everything. The verbs here are each ONE undoable step and touch only what
+// they name.
+//
+// THE INVARIANT THAT SHAPES THIS FILE: an agent must not be able to write a
+// document this build could not itself have produced. So html goes through the
+// sanitizer on the way IN (not only on the way to the screen), a patch value
+// that JSON cannot carry is refused rather than silently dropped at save time,
+// and a page can never be left with zero blocks — the editor has no way to
+// place a caret in one, so it would be a page nobody can ever type in again.
+//
+// PLAN/APPLY. Every write verb returns a PLAN: it validates against the
+// document and hands back a thunk. `store.commit` checkpoints undo BEFORE it
+// mutates, so planning inside a commit would mean a refused patch still pushed
+// an undo entry that undoes nothing. Planning first also makes the whole write
+// path testable in node, where there is no store and no DOM.
+
+import { type SpacesDoc, type Page, type Block, buildIndex, isRemote, newBlock, uid } from './model.ts'
+import { SPECS, SPEC } from './blocks.ts'
+import { sanitizeInline, textOf, inertBody, esc, UNWRAP } from './sanitize.ts'
+import { orphanAssets, humanBytes } from './assets.ts'
+
+// ---------------------------------------------------------------------------
+// shared helpers
+// ---------------------------------------------------------------------------
+
+// The block REGISTRY is the one list of known types (blocks.ts). A second
+// const here would drift the first time someone adds a block type — which is
+// precisely what the registry exists to prevent, and validate() reporting a
+// real type as unknown would have an agent 'fix' working documents.
+const KNOWN_BLOCK_TYPES = SPECS.map((s) => s.type)
+const KNOWN = new Set<string>(KNOWN_BLOCK_TYPES)
+
+const words = (s: string): number => (s.trim() ? s.trim().split(/\s+/).length : 0)
+
+const utf8len = (s: string): number =>
+ typeof TextEncoder !== 'undefined' ? new TextEncoder().encode(s).length : s.length
+
+export interface BlockAt { block: Block; page: Page; index: number }
+
+export function findBlock(doc: SpacesDoc, id: string): BlockAt | null {
+ for (const page of doc.pages) {
+ const index = page.blocks.findIndex((b) => b.id === id)
+ if (index >= 0) return { block: page.blocks[index], page, index }
+ }
+ return null
+}
+
+/** Every block nested under `id` on its page, at any depth. */
+function descendants(page: Page, id: string): Set<string> {
+ const out = new Set<string>()
+ let grew = true
+ // the array is pre-order, but a hand-written document need not be, so this
+ // sweeps to a fixed point rather than trusting the order
+ while (grew) {
+ grew = false
+ for (const b of page.blocks) {
+ if (b.parent && (b.parent === id || out.has(b.parent)) && !out.has(b.id)) {
+ out.add(b.id)
+ grew = true
+ }
+ }
+ }
+ return out
+}
+
+/**
+ * Would JSON.stringify carry this value unchanged?
+ *
+ * A function, a DOM node, a Map or a Date all assign fine and then either
+ * VANISH at save time or throw on a cycle — either way the failure surfaces
+ * hours later, in the file, with no clue where it came from. The format is
+ * additive, so unknown keys are welcome; unknown SHAPES are not.
+ */
+export function jsonSafe(v: unknown, depth = 0): boolean {
+ if (v === null) return true
+ const t = typeof v
+ if (t === 'string' || t === 'boolean') return true
+ if (t === 'number') return Number.isFinite(v as number)
+ if (depth > 12) return false
+ if (Array.isArray(v)) return v.every((x) => jsonSafe(x, depth + 1))
+ if (t === 'object') {
+ const proto = Object.getPrototypeOf(v)
+ if (proto !== Object.prototype && proto !== null) return false
+ return Object.values(v as Record<string, unknown>).every((x) => jsonSafe(x, depth + 1))
+ }
+ return false
+}
+
+const hasElements = (html: string): boolean =>
+ typeof document === 'undefined'
+ ? /<[a-z][a-z0-9]*(\s|\/|>)/i.test(html)
+ : !!inertBody(html).querySelector('*')
+
+/**
+ * The stored form of a block's html, as the EDITOR would have stored it.
+ *
+ * Rich blocks are sanitized inline html. A `code` block is different: the
+ * renderer takes its textContent, and a contentEditable `<code>` stores what
+ * you type ESCAPED — so `<div>` in a code block lives in the file as
+ * `&lt;div&gt;`. Sanitizing code would delete the sample someone was showing,
+ * so code is escaped instead, and only when it actually carries live tags:
+ * already-escaped text passes through untouched, which keeps this idempotent
+ * (a patch replayed twice must not double-escape).
+ */
+export function normalizeHtml(html: string, type: string): string {
+ if (type === 'code') return hasElements(html) ? esc(html) : html
+ return sanitizeInline(html)
+}
+
+/** A page title renders as TEXT, so markup in one would show literally. */
+export const plainTitle = (v: unknown): string => textOf(String(v ?? ''))
+
+// ---------------------------------------------------------------------------
+// validate()
+// ---------------------------------------------------------------------------
+
+export type Severity = 'error' | 'warning' | 'info'
+
+export interface Finding {
+ /** stable machine-readable code, e.g. 'broken-link' */
+ code: string
+ severity: Severity
+ /** what is wrong, in one line, actionable on its own */
+ message: string
+ /** how to fix it */
+ fix: string
+ page?: string
+ block?: string
+ /** the field it is about, when it is about one */
+ path?: string
+}
+
+export interface ValidateResult {
+ /** no errors. Warnings and info do not make a document invalid. */
+ ok: boolean
+ counts: Record<Severity, number>
+ findings: Finding[]
+}
+
+/** Inline tags a block may keep (sanitize.ts ALLOWED, lowercased). */
+const INLINE_OK = new Set(['b', 'i', 'u', 's', 'em', 'strong', 'code', 'br', 'span', 'mark', 'sub', 'sup', 'a'])
+/** Tags the sanitizer unwraps: the tag goes, the words stay (sanitize.ts UNWRAP). */
+// Derived from the sanitizer, never restated: this list IS what sanitizeInline
+// unwraps, and a copy would drift the moment that policy changes.
+const UNWRAPPED = new Set([...UNWRAP].map((t) => t.toLowerCase()))
+
+const TAG_RE = /<\/?([a-z][a-z0-9]*)\b/gi
+const LINK_RE = /href\s*=\s*["']([^"']*)["']/gi
+
+/**
+ * WHAT IS DELIBERATELY NOT CHECKED: unknown property names.
+ *
+ * Slides warns about them, because its element schema is closed. This format's
+ * unknown fields are a FEATURE — they are how a future build's data survives an
+ * older one, and how an agent parks its own metadata on a block. Warning about
+ * them would fire on documents that are working exactly as designed, and a
+ * validator that cries wolf on good documents is one an agent learns to skip.
+ */
+export function validateDoc(doc: SpacesDoc): ValidateResult {
+ const findings: Finding[] = []
+ const add = (f: Finding) => findings.push(f)
+ const pages = Array.isArray(doc.pages) ? doc.pages : []
+ const assets = doc.assets ?? {}
+
+ if (!pages.length) {
+ add({ code: 'no-pages', severity: 'error', message: 'This space has no pages.',
+ fix: 'Add at least one page — the reader shows "This space has no pages." until there is one.' })
+ }
+
+ // ---- identity ----------------------------------------------------------
+ // Every id is unique across the WHOLE document: links, backlinks and (later)
+ // collaboration key on them. parseDoc repairs duplicates deterministically,
+ // but a repaired id is a NEW id, so whatever pointed at the old one is now
+ // pointing somewhere else. Emitting them unique is the only way to keep the
+ // references an author wrote.
+ const seen = new Set<string>()
+ const claim = (id: unknown, where: Pick<Finding, 'page' | 'block'>, what: string) => {
+ if (typeof id !== 'string' || !id) {
+ add({ ...where, code: 'missing-id', severity: 'error', path: 'id',
+ message: `A ${what} has no id.`,
+ fix: 'Give it a unique string id. Loading assigns one derived from the bytes, which is not the id you meant to link to.' })
+ return
+ }
+ if (seen.has(id)) {
+ add({ ...where, code: 'duplicate-id', severity: 'error', path: 'id',
+ message: `The id "${id}" is used more than once. Ids are unique across the whole document, not per page.`,
+ fix: 'Rename the later one. Loading repairs it to a derived id, which silently breaks every link that pointed at it.' })
+ return
+ }
+ seen.add(id)
+ }
+ for (const p of pages) {
+ claim(p.id, { page: p.id }, 'page')
+ for (const b of Array.isArray(p.blocks) ? p.blocks : []) claim(b.id, { page: p.id, block: b.id }, 'block')
+ }
+
+ const pageIx = new Map(pages.map((p) => [p.id, p]))
+
+ // ---- the page tree ------------------------------------------------------
+ for (const p of pages) {
+ if (p.parent && !pageIx.has(p.parent)) {
+ add({ page: p.id, code: 'no-such-page-parent', severity: 'warning', path: 'parent',
+ message: `Page "${p.title}" names parent "${p.parent}", which is not a page in this space.`,
+ fix: 'Point parent at a real page id, or remove it. Loading drops it and the page becomes a root page.' })
+ }
+ // a parent CHAIN that loops never reaches the root, so the page is not in
+ // the sidebar at all — the one way a page can be genuinely unreachable
+ const walked = new Set<string>([p.id])
+ for (let up = p.parent; up; up = pageIx.get(up)?.parent) {
+ if (walked.has(up)) {
+ add({ page: p.id, code: 'page-cycle', severity: 'error', path: 'parent',
+ message: `Page "${p.title}" is inside its own subtree, so the tree never reaches the root and the page never appears in the sidebar.`,
+ fix: 'Break the loop: give it a parent outside its own descendants, or none.' })
+ break
+ }
+ walked.add(up)
+ }
+ }
+ if (doc.home && !pageIx.has(doc.home)) {
+ add({ code: 'no-such-home', severity: 'warning', path: 'home',
+ message: `home names "${doc.home}", which is not a page in this space.`,
+ fix: 'Set home to a real page id. Readers land on the first page instead, which may not be the one you wrote to be landed on.' })
+ }
+
+ // ---- pages and blocks ---------------------------------------------------
+ const usedAssets = new Set<string>()
+ for (const p of pages) {
+ const blocks = Array.isArray(p.blocks) ? p.blocks : []
+ const own = new Set(blocks.map((b) => b.id))
+
+ if (!blocks.length) {
+ // Not cosmetic: the editor's caret, gutter and / menu all hang off a
+ // block, so a page with none cannot be typed into at all. The editor
+ // never produces one — model.newPage() always mints a paragraph.
+ add({ page: p.id, code: 'no-blocks', severity: 'error', path: 'blocks',
+ message: `Page "${p.title}" has no blocks, so there is nothing in it to put a caret in — it cannot be typed into.`,
+ fix: 'Give it at least one block, e.g. { "type": "p", "html": "" }.' })
+ } else if (!blocks.some((b) => textOf(b.html).trim() || b.type === 'image' || b.type === 'pagelink' || b.type === 'divider')) {
+ add({ page: p.id, code: 'empty-page', severity: 'info',
+ message: `Page "${p.title}" has blocks but no content.`,
+ fix: 'Write something, or remove the page. A deliberately blank page (an inbox, a stub) is fine — this is only a note.' })
+ }
+
+ for (const b of blocks) {
+ const at = { page: p.id, block: b.id }
+
+ if (!KNOWN.has(b.type)) {
+ add({ ...at, code: 'unknown-block-type', severity: 'warning', path: 'type',
+ message: `"${b.type}" is not a block type this build renders — it falls back to showing its html as plain text.`,
+ fix: `Use one of: ${KNOWN_BLOCK_TYPES.join(', ')}. The block and its fields survive untouched either way, so a future build can render it.` })
+ }
+
+ if (b.parent && !own.has(b.parent)) {
+ add({ ...at, code: 'no-such-block-parent', severity: 'warning', path: 'parent',
+ message: `Block parent "${b.parent}" is not a block on this page — nesting only works inside one page.`,
+ fix: 'Name a block on the same page, or drop parent. Loading drops it and the block un-nests.' })
+ }
+
+ // ---- html ----------------------------------------------------------
+ if (typeof b.html === 'string' && b.html.includes('<')) {
+ const unwrapped: string[] = []
+ const dropped: string[] = []
+ for (const m of b.html.matchAll(TAG_RE)) {
+ const tag = m[1].toLowerCase()
+ if (INLINE_OK.has(tag)) continue
+ if (UNWRAPPED.has(tag)) { if (!unwrapped.includes(tag)) unwrapped.push(tag) }
+ else if (!dropped.includes(tag)) dropped.push(tag)
+ }
+ if (b.type === 'code' && (unwrapped.length || dropped.length)) {
+ add({ ...at, code: 'markup-in-code', severity: 'warning', path: 'html',
+ message: `A code block's html is plain TEXT — the renderer shows its textContent, so <${(unwrapped[0] ?? dropped[0])}> disappears and takes its markup with it.`,
+ fix: 'Escape it: write &lt;div&gt; rather than <div>. That is what typing into a code block stores.' })
+ } else if (b.type !== 'code') {
+ if (unwrapped.length) {
+ add({ ...at, code: 'block-markup', severity: 'warning', path: 'html',
+ message: `html is inline only, and carries block markup (<${unwrapped.join('>, <')}>). The tags are unwrapped at render and the structure is lost.`,
+ fix: 'Split it into separate blocks — structure is Block.type, never markup.' })
+ }
+ if (dropped.length) {
+ add({ ...at, code: 'dropped-markup', severity: 'error', path: 'html',
+ message: `<${dropped.join('>, <')}> is outside the inline allowlist, so the tag AND everything inside it is removed before anything is shown. That content is invisible to every reader.`,
+ fix: 'Use a block type that can carry it (image, code, quote), or inline tags only: b i u s em strong code a span mark sub sup br.' })
+ }
+ }
+ for (const m of b.html.matchAll(LINK_RE)) {
+ const href = m[1]
+ if (href.startsWith('#p/')) {
+ // The SAME last-slash rule the resolver and the backlink index use
+ // (editor.resolveAnchor / model.linkTarget): `#p/<page>/<block>` is
+ // a legal href — sanitize.ts admits it and navigation resolves it to
+ // the page — so looking the whole remainder up as a page id reported
+ // every block anchor as a broken link, at severity ERROR, with a fix
+ // ("remove the link") that would destroy a working link. An agent
+ // acting on a false error does more damage than one told nothing.
+ const raw = href.slice(3)
+ const cut = raw.lastIndexOf('/')
+ const target = pageIx.has(raw) || cut <= 0 ? raw : raw.slice(0, cut)
+ if (!pageIx.has(target)) {
+ add({ ...at, code: 'broken-link', severity: 'error', path: 'html',
+ message: `Links to page "${target}", which does not exist — the link renders and does nothing when clicked.`,
+ fix: 'Point it at a real page id, create that page, or remove the link.' })
+ }
+ } else if (!/^(https?:|mailto:)/i.test(href)) {
+ add({ ...at, code: 'dead-href', severity: 'warning', path: 'html',
+ message: `href "${href.slice(0, 40)}" is outside the allowlist (https:, mailto:, #p/), so the sanitizer drops the link and leaves only its text.`,
+ fix: 'Use #p/<pageId> for a page in this space, or an https:/mailto: url.' })
+ }
+ }
+ }
+
+ // ---- per type --------------------------------------------------------
+ if (b.type === 'pagelink') {
+ const target = typeof b.page === 'string' ? b.page : ''
+ if (!target || !pageIx.has(target)) {
+ add({ ...at, code: 'broken-link', severity: 'error', path: 'page',
+ message: `A pagelink card points at "${target || '(nothing)'}", which is not a page — it renders as "(missing page)".`,
+ fix: 'Set page to a real page id, or remove the block.' })
+ }
+ }
+
+ const src = typeof b.src === 'string' ? b.src : ''
+ if (src.startsWith('asset:')) usedAssets.add(src.slice(6))
+ if (b.type === 'image') {
+ if (!src) {
+ add({ ...at, code: 'image-no-src', severity: 'error', path: 'src',
+ message: 'An image block has no src, so nothing renders.',
+ fix: 'Set src to asset:<key>, or a data: URI.' })
+ } else if (src.startsWith('asset:') && !(src.slice(6) in assets)) {
+ add({ ...at, code: 'missing-asset', severity: 'error', path: 'src',
+ message: `src references asset "${src.slice(6)}", which is not in doc.assets — nothing renders.`,
+ fix: 'Add the data: URI to doc.assets under that key, or point src at one that is there.' })
+ } else if (isRemote(src)) {
+ add({ ...at, code: 'remote-image', severity: 'warning', path: 'src',
+ message: `src is remote (${src.slice(0, 48)}), so it shows a placeholder naming the host until the reader clicks "Load this image". Opening a document never contacts a third party.`,
+ fix: 'Embed the bytes: put the data: URI in doc.assets and reference it as asset:<key>.' })
+ }
+ if (!String(b.alt ?? '').trim()) {
+ add({ ...at, code: 'image-no-alt', severity: 'warning', path: 'alt',
+ message: 'This image has no alt text — screen readers get nothing, and alt is what a reader SEES if the image is remote and unloaded.',
+ fix: 'Write what the image shows, in a sentence.' })
+ }
+ if (!b.w || !b.h) {
+ add({ ...at, code: 'image-no-size', severity: 'info', path: 'w',
+ message: 'No intrinsic w/h, so the page reflows under the reader as the image decodes.',
+ fix: 'Set w and h to the image\'s pixel size.' })
+ }
+ }
+ }
+ }
+
+ // ---- assets --------------------------------------------------------------
+ for (const f of doc.fonts ?? []) {
+ if (f.asset && !(f.asset in assets)) {
+ add({ code: 'missing-asset', severity: 'error', path: `fonts.${f.family}`,
+ message: `Font "${f.family}" names asset "${f.asset}", which is not in doc.assets — the face never loads and text silently falls back.`,
+ fix: 'Add the woff2 data: URI under that key, or drop the font entry.' })
+ }
+ usedAssets.add(f.asset)
+ }
+ const orphans = orphanAssets(doc)
+ if (orphans.length) {
+ // ONE finding, not one per key: an author who deleted a photo-heavy page
+ // has dozens, and the actionable fact is the total.
+ let bytes = 0
+ for (const k of orphans) bytes += (assets[k] ?? '').length
+ add({ code: 'orphan-asset', severity: 'info', path: 'assets',
+ message: `${orphans.length} asset(s) (${humanBytes(bytes)}) are in doc.assets but referenced by nothing.`,
+ fix: `Delete these keys to shrink the file: ${orphans.slice(0, 8).join(', ')}${orphans.length > 8 ? ', …' : ''}` })
+ }
+
+ const counts: Record<Severity, number> = { error: 0, warning: 0, info: 0 }
+ for (const f of findings) counts[f.severity]++
+ return { ok: counts.error === 0, counts, findings }
+}
+
+// ---------------------------------------------------------------------------
+// outline()
+// ---------------------------------------------------------------------------
+
+export interface OutlineHeading { id: string; level: 1 | 2 | 3; text: string }
+
+export interface OutlineNode {
+ id: string
+ title: string
+ /** 0 for a root page */
+ depth: number
+ parent?: string
+ icon?: string
+ archived?: true
+ /** the landing page */
+ home?: true
+ blocks: number
+ words: number
+ headings?: OutlineHeading[]
+ /** page ids this page links to, deduped — inline #p/ links and pagelink cards */
+ links?: string[]
+}
+
+export interface OutlineResult {
+ title: string
+ docId: string
+ pages: number
+ blocks: number
+ words: number
+ tree: OutlineNode[]
+}
+
+/**
+ * The whole space in one call, in sidebar order.
+ *
+ * Orientation used to cost one `getPage` per page — for a 200-page handbook
+ * that is 200 round trips and the entire document in context, to answer "where
+ * does the onboarding material live". Headings carry their block id so the
+ * answer is directly actionable: what comes back can be passed straight to
+ * updateBlock or moveBlock.
+ */
+export function outlineDoc(doc: SpacesDoc): OutlineResult {
+ const ix = buildIndex(doc)
+ const tree: OutlineNode[] = []
+ const emitted = new Set<string>()
+
+ const node = (p: Page, depth: number): OutlineNode => {
+ const headings: OutlineHeading[] = []
+ const links: string[] = []
+ let w = 0
+ for (const b of p.blocks) {
+ const text = textOf(b.html)
+ w += words(text)
+ if (b.type === 'h1' || b.type === 'h2' || b.type === 'h3') {
+ headings.push({ id: b.id, level: Number(b.type.slice(1)) as 1 | 2 | 3, text })
+ }
+ if (b.type === 'pagelink' && typeof b.page === 'string' && !links.includes(b.page)) links.push(b.page)
+ for (const m of (b.html ?? '').matchAll(/href\s*=\s*["']#p\/([^"']+)["']/g)) {
+ if (!links.includes(m[1])) links.push(m[1])
+ }
+ }
+ return {
+ id: p.id, title: p.title, depth,
+ ...(p.parent ? { parent: p.parent } : {}),
+ ...(p.icon ? { icon: p.icon } : {}),
+ ...(p.archived ? { archived: true as const } : {}),
+ ...(doc.home === p.id ? { home: true as const } : {}),
+ blocks: p.blocks.length,
+ words: w,
+ ...(headings.length ? { headings } : {}),
+ ...(links.length ? { links } : {}),
+ }
+ }
+
+ const walk = (parent: string, depth: number) => {
+ for (const p of ix.children.get(parent) ?? []) {
+ if (emitted.has(p.id)) continue // a parent cycle would otherwise recurse forever
+ emitted.add(p.id)
+ tree.push(node(p, depth))
+ walk(p.id, depth + 1)
+ }
+ }
+ walk('', 0)
+ // A page inside its own subtree is in no walk from the root. It is still in
+ // the file and still linkable, so it must appear here — an outline that
+ // silently omits pages is worse than no outline. validate() names the cycle.
+ for (const p of doc.pages) if (!emitted.has(p.id)) tree.push(node(p, 0))
+
+ return {
+ title: doc.title,
+ docId: doc.docId,
+ pages: doc.pages.length,
+ blocks: doc.pages.reduce((n, p) => n + p.blocks.length, 0),
+ words: tree.reduce((n, t) => n + t.words, 0),
+ tree,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// stats()
+// ---------------------------------------------------------------------------
+
+export interface AssetStat { key: string; bytes: number; mime: string; used: number }
+
+export interface StatsResult {
+ pages: number
+ archived: number
+ blocks: number
+ words: number
+ characters: number
+ blockTypes: Record<string, number>
+ todos: { done: number; total: number }
+ assets: { count: number; bytes: number; orphans: number; orphanBytes: number }
+ /** UTF-8 bytes of the document JSON. The shell adds a fixed ~600 KB on top. */
+ bytes: { document: number; assets: number; text: number }
+ /** the ten largest assets, biggest first */
+ biggest: AssetStat[]
+}
+
+/**
+ * Where the weight is — the call that answers "why is this file 30MB".
+ *
+ * Prose is free (2,000 pages of it is ~5MB); images are the entire story, and
+ * an asset nothing references costs exactly as much as one that does. So the
+ * breakdown is by asset, largest first, with a use count beside each.
+ */
+export function statsDoc(doc: SpacesDoc): StatsResult {
+ const assets = doc.assets ?? {}
+ const blockTypes: Record<string, number> = {}
+ const use = new Map<string, number>()
+ const todos = { done: 0, total: 0 }
+ let blocks = 0
+ let wordCount = 0
+ let characters = 0
+ let textBytes = 0
+
+ for (const p of doc.pages) {
+ for (const b of p.blocks) {
+ blocks++
+ blockTypes[b.type] = (blockTypes[b.type] ?? 0) + 1
+ if (b.type === 'todo') { todos.total++; if (b.done) todos.done++ }
+ const text = textOf(b.html)
+ wordCount += words(text)
+ characters += text.length
+ textBytes += utf8len(b.html ?? '')
+ for (const v of [b.src, (b as Record<string, unknown>).poster]) {
+ if (typeof v === 'string' && v.startsWith('asset:')) {
+ const k = v.slice(6)
+ use.set(k, (use.get(k) ?? 0) + 1)
+ }
+ }
+ }
+ }
+ for (const f of doc.fonts ?? []) use.set(f.asset, (use.get(f.asset) ?? 0) + 1)
+
+ let assetBytes = 0
+ const each: AssetStat[] = []
+ for (const [key, value] of Object.entries(assets)) {
+ // a data: URI is ASCII, so length IS bytes and this stays O(1) per asset
+ const bytes = value.length
+ assetBytes += bytes
+ each.push({ key, bytes, mime: /^data:([^;,]+)/.exec(value)?.[1] ?? 'unknown', used: use.get(key) ?? 0 })
+ }
+ each.sort((a, b) => b.bytes - a.bytes)
+ const orphans = each.filter((a) => !a.used)
+
+ return {
+ pages: doc.pages.length,
+ archived: doc.pages.filter((p) => p.archived).length,
+ blocks,
+ words: wordCount,
+ characters,
+ blockTypes,
+ todos,
+ assets: {
+ count: each.length,
+ bytes: assetBytes,
+ orphans: orphans.length,
+ orphanBytes: orphans.reduce((n, a) => n + a.bytes, 0),
+ },
+ bytes: { document: utf8len(JSON.stringify(doc)), assets: assetBytes, text: textBytes },
+ biggest: each.slice(0, 10),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// the write verbs
+// ---------------------------------------------------------------------------
+
+export type Plan<T> = ({ ok: true; apply: () => void } & T) | PlanError
+
+export interface PlanError {
+ ok: false
+ /** machine-readable: 'readonly' | 'no-such-block' | 'no-such-page' | 'bad-patch' |
+ * 'immutable' | 'not-serializable' | 'cycle' | 'last-page' */
+ err: string
+ detail?: string
+}
+
+const fail = (err: string, detail?: string): PlanError => ({ ok: false, err, ...(detail ? { detail } : {}) })
+
+const isPatch = (v: unknown): v is Record<string, unknown> =>
+ !!v && typeof v === 'object' && !Array.isArray(v)
+
+/** Split a patch into writes and deletes; `null`/`undefined` means delete. */
+function splitPatch(patch: Record<string, unknown>): { sets: Record<string, unknown>; dels: string[] } | PlanError {
+ const sets: Record<string, unknown> = {}
+ const dels: string[] = []
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null || v === undefined) { dels.push(k); continue }
+ if (!jsonSafe(v)) {
+ return fail('not-serializable', `"${k}" holds something JSON cannot carry (a function, a DOM node, a Date, a cycle). It would vanish or throw at save time.`)
+ }
+ sets[k] = v
+ }
+ return { sets, dels }
+}
+
+/**
+ * Insert blocks into a page. Ids are minted here, never taken from the caller,
+ * so an agent cannot collide with an id that already exists in the document.
+ *
+ * Because the ids are re-minted, a block in the batch could not previously name
+ * another block in the same batch as its `parent` — the id it would have to
+ * name does not exist yet. So `parent` is REMAPPED against the batch's own
+ * supplied ids: send a toggle and its body in one call and the nesting holds.
+ * A parent that resolves to neither the batch nor the page is dropped, because
+ * a dangling parent renders un-nested and is deleted at the next load anyway.
+ *
+ * `afterId` naming a block that is not on the page is an ERROR, not an append.
+ * It used to append silently, which put the content somewhere the agent did not
+ * ask for and reported success.
+ */
+export function planInsertBlocks(
+ doc: SpacesDoc, pageId: string, afterId: string | null, blocks: unknown,
+): Plan<{ ids: string[]; page: string }> {
+ if (!Array.isArray(blocks)) return fail('bad-patch', 'pass an array of blocks')
+ const page = doc.pages.find((p) => p.id === pageId)
+ if (!page) return fail('no-such-page', String(pageId))
+ if (afterId != null && !page.blocks.some((b) => b.id === afterId)) {
+ return fail('no-such-block', `"${afterId}" is not a block on page "${pageId}"`)
+ }
+
+ const remap = new Map<string, string>()
+ const made: Block[] = []
+ for (const raw of blocks) {
+ if (raw != null && !jsonSafe(raw)) return fail('not-serializable', 'a block holds something JSON cannot carry')
+ const src = isPatch(raw) ? raw : {}
+ const type = typeof src.type === 'string' && src.type ? src.type : 'p'
+ const b = { ...src, id: uid('b'), type } as Block
+ if (typeof src.id === 'string' && src.id) remap.set(src.id, b.id)
+ if (typeof b.html === 'string') b.html = normalizeHtml(b.html, type)
+ made.push(b)
+ }
+ for (const b of made) {
+ if (typeof b.parent !== 'string') continue
+ const within = remap.get(b.parent)
+ if (within) b.parent = within
+ else if (!page.blocks.some((x) => x.id === b.parent)) delete b.parent
+ }
+
+ return {
+ ok: true, ids: made.map((b) => b.id), page: page.id,
+ apply() {
+ const at = afterId == null ? page.blocks.length : page.blocks.findIndex((b) => b.id === afterId) + 1
+ page.blocks.splice(at, 0, ...made)
+ },
+ }
+}
+
+/**
+ * Change fields on one block. `null` deletes a field.
+ *
+ * `id` is refused rather than ignored: a silent no-op on the one field that
+ * links, backlinks and undo all key on is how an agent ends up believing it
+ * renamed something.
+ */
+export function planUpdateBlock(doc: SpacesDoc, id: string, patch: unknown): Plan<{ id: string; page: string }> {
+ if (!isPatch(patch)) return fail('bad-patch', 'patch must be an object of block fields')
+ const at = findBlock(doc, id)
+ if (!at) return fail('no-such-block', id)
+ if ('id' in patch) return fail('immutable', 'a block id never changes — links, backlinks and undo key on it')
+
+ const { block, page } = at
+ const type = 'type' in patch ? patch.type : block.type
+ if (typeof type !== 'string' || !type) return fail('bad-patch', 'type must be a non-empty string')
+
+ if ('parent' in patch && patch.parent != null) {
+ const owner = String(patch.parent)
+ if (owner === id) return fail('cycle', 'a block cannot be its own parent')
+ if (!page.blocks.some((b) => b.id === owner)) return fail('no-such-block', `parent "${owner}" is not a block on page "${page.id}"`)
+ if (descendants(page, id).has(owner)) return fail('cycle', `parent "${owner}" is nested inside "${id}"`)
+ }
+
+ const split = splitPatch(patch)
+ if ('ok' in split) return split
+ const { sets, dels } = split
+ if (dels.includes('type')) return fail('bad-patch', 'type cannot be deleted; set it to another type instead')
+
+ if (typeof sets.html === 'string') sets.html = normalizeHtml(sets.html, type)
+ else if (sets.type && typeof block.html === 'string' && (sets.type === 'code') !== (block.type === 'code')) {
+ // code stores escaped text and everything else stores inline html, so a
+ // retype in either direction has to re-normalize what is already there
+ sets.html = normalizeHtml(block.html, type)
+ }
+
+ return {
+ ok: true, id, page: page.id,
+ apply() {
+ for (const k of dels) delete (block as Record<string, unknown>)[k]
+ const retyped = typeof sets.type === 'string' && sets.type !== block.type
+ Object.assign(block, sets)
+ // A TYPE CHANGE RUNS THE REGISTRY'S init, exactly as the editor's setType
+ // does. Without it an agent-written callout has no `tone` and an
+ // agent-written to-do has no `done` — documents the app itself could not
+ // have produced, from the API whose whole promise is that it produces
+ // documents the app could have produced.
+ if (retyped) SPEC.get(block.type)?.init?.(block)
+ },
+ }
+}
+
+/**
+ * Remove blocks, with anything nested under them.
+ *
+ * The cascade is not a convenience: a toggle's body is `parent`-linked, so
+ * deleting the toggle alone would leave blocks pointing at an id that no longer
+ * exists — loading re-homes them and they reappear, un-nested, in a document
+ * the agent believed it had emptied.
+ *
+ * A page emptied down to nothing gets one fresh paragraph, because the editor's
+ * caret, gutter and / menu all hang off a block: a page with none can never be
+ * typed into again.
+ */
+export function planRemoveBlocks(doc: SpacesDoc, ids: unknown): Plan<{ removed: string[]; missing: string[]; added: string[] }> {
+ if (!Array.isArray(ids)) return fail('bad-patch', 'pass an array of block ids')
+ const perPage = new Map<Page, Set<string>>()
+ const missing: string[] = []
+ const removed: string[] = []
+
+ for (const raw of ids) {
+ const id = String(raw)
+ const at = findBlock(doc, id)
+ if (!at) { missing.push(id); continue }
+ const set = perPage.get(at.page) ?? new Set<string>()
+ perPage.set(at.page, set)
+ for (const victim of [id, ...descendants(at.page, id)]) {
+ if (!set.has(victim)) { set.add(victim); removed.push(victim) }
+ }
+ }
+
+ const refills: Array<[Page, Block]> = []
+ for (const [page, set] of perPage) {
+ if (page.blocks.every((b) => set.has(b.id))) refills.push([page, newBlock('p')])
+ }
+
+ return {
+ ok: true, removed, missing, added: refills.map(([, b]) => b.id),
+ apply() {
+ for (const [page, set] of perPage) page.blocks = page.blocks.filter((b) => !set.has(b.id))
+ for (const [page, fresh] of refills) page.blocks.push(fresh)
+ },
+ }
+}
+
+export interface MoveTarget {
+ /** the page to move to; omit to stay on the current one */
+ pageId?: string
+ /** place it after this block */
+ afterId?: string
+ /** place it before this block (wins over afterId) */
+ beforeId?: string
+ /** re-nest under this block; null clears nesting */
+ parent?: string | null
+}
+
+/**
+ * Move a block, with its nested blocks, within or across pages.
+ *
+ * Neither anchor given = the end of the page, which is what `insertBlocks(page,
+ * null, …)` already means. `beforeId` exists because otherwise the first
+ * position in a page is unreachable.
+ */
+export function planMoveBlock(doc: SpacesDoc, id: string, to: unknown): Plan<{ id: string; pageId: string; moved: string[] }> {
+ if (to !== undefined && !isPatch(to)) return fail('bad-patch', 'pass { pageId?, afterId?, beforeId?, parent? }')
+ const spec = (to ?? {}) as MoveTarget
+ const at = findBlock(doc, id)
+ if (!at) return fail('no-such-block', id)
+ const from = at.page
+
+ const dest = spec.pageId ? doc.pages.find((p) => p.id === spec.pageId) : from
+ if (!dest) return fail('no-such-page', String(spec.pageId))
+
+ const kin = descendants(from, id)
+ const group = from.blocks.filter((b) => b.id === id || kin.has(b.id))
+ const anchorId = spec.beforeId ?? spec.afterId
+ if (anchorId != null) {
+ if (kin.has(String(anchorId)) || String(anchorId) === id) return fail('cycle', 'a block cannot be moved inside its own subtree')
+ if (!dest.blocks.some((b) => b.id === anchorId)) return fail('no-such-block', `"${anchorId}" is not a block on page "${dest.id}"`)
+ }
+
+ let parent: string | null | undefined = spec.parent
+ if (parent != null) {
+ const owner = String(parent)
+ if (owner === id || kin.has(owner)) return fail('cycle', 'a block cannot be nested under itself')
+ if (!dest.blocks.some((b) => b.id === owner)) return fail('no-such-block', `parent "${owner}" is not a block on page "${dest.id}"`)
+ } else if (parent === undefined) {
+ // keep the nesting only while it still names something on the destination
+ // page — carried across pages it would be a parent that does not exist,
+ // which renders un-nested and is dropped at the next load
+ parent = at.block.parent && dest.blocks.some((b) => b.id === at.block.parent) ? at.block.parent : null
+ }
+
+ return {
+ ok: true, id, pageId: dest.id, moved: group.map((b) => b.id),
+ apply() {
+ from.blocks = from.blocks.filter((b) => !group.includes(b))
+ if (parent) at.block.parent = parent
+ else delete at.block.parent
+ const anchor = anchorId != null ? dest.blocks.findIndex((b) => b.id === anchorId) : -1
+ const cut = anchor < 0 ? dest.blocks.length : spec.beforeId != null ? anchor : anchor + 1
+ dest.blocks.splice(cut, 0, ...group)
+ },
+ }
+}
+
+/**
+ * Change a page's own fields. `blocks` is refused — block structure goes
+ * through insertBlocks/updateBlock/removeBlocks/moveBlock, each of which keeps
+ * ids, nesting and undo coherent; assigning the array wholesale keeps none of
+ * them.
+ */
+export function planUpdatePage(doc: SpacesDoc, id: string, patch: unknown): Plan<{ id: string }> {
+ if (!isPatch(patch)) return fail('bad-patch', 'patch must be an object of page fields')
+ const page = doc.pages.find((p) => p.id === id)
+ if (!page) return fail('no-such-page', id)
+ if ('id' in patch) return fail('immutable', 'a page id never changes — every #p/ link and backlink keys on it')
+ if ('blocks' in patch) return fail('immutable', 'use insertBlocks / updateBlock / removeBlocks / moveBlock for block structure')
+
+ const split = splitPatch(patch)
+ if ('ok' in split) return split
+ const { sets, dels } = split
+
+ if ('title' in sets) {
+ // the title renders as textContent, so markup in it would show literally
+ sets.title = plainTitle(sets.title)
+ }
+ if ('parent' in sets) {
+ const owner = String(sets.parent)
+ if (owner === id) return fail('cycle', 'a page cannot contain itself')
+ if (!doc.pages.some((p) => p.id === owner)) return fail('no-such-page', `parent "${owner}"`)
+ // BOUNDED. A cycle already in the document (A.parent=B, B.parent=A)
+ // survives parseDoc — it only drops parents that name no page — so it
+ // arrives from any hand-edited or mailed file, and this walk ran forever:
+ // measured, the call never returns and the tab dies with every unsaved edit
+ // in it. The reachable sequence is the RECOMMENDED one — validate() reports
+ // `page-cycle`, the agent re-homes a page to fix it, and that call hangs.
+ // validateDoc next door already carries this set.
+ const seen = new Set<string>()
+ for (let up: string | undefined = owner; up && !seen.has(up); up = doc.pages.find((p) => p.id === up)?.parent) {
+ seen.add(up)
+ if (up === id) return fail('cycle', `"${owner}" is inside "${id}"`)
+ }
+ sets.parent = owner
+ }
+ if ('archived' in sets) {
+ // the editor DELETES the key rather than writing false, and two spellings
+ // of "not archived" in saved files is the kind of drift that costs a
+ // format its simplicity
+ if (sets.archived) sets.archived = true
+ else { delete sets.archived; dels.push('archived') }
+ }
+
+ return {
+ ok: true, id,
+ apply() {
+ for (const k of dels) delete (page as Record<string, unknown>)[k]
+ Object.assign(page, sets)
+ },
+ }
+}
+
+export interface RemovePageOpts {
+ /** delete the pages nested under it too; default re-homes them a level up */
+ descendants?: boolean
+}
+
+/**
+ * Remove a page.
+ *
+ * Children are re-homed to the removed page's parent by default — the editor's
+ * rule, and for its reason: deleting a middle page should not silently take a
+ * subtree nobody was looking at. `{ descendants: true }` is the explicit way to
+ * take the subtree.
+ *
+ * `links` in the result counts the inbound links that just went dead. There is
+ * no undoing someone else's expectation of what a link meant, so the number is
+ * reported rather than the removal refused.
+ */
+export function planRemovePage(doc: SpacesDoc, id: string, opts: RemovePageOpts = {}): Plan<{ removed: string[]; rehomed: number; links: number }> {
+ const page = doc.pages.find((p) => p.id === id)
+ if (!page) return fail('no-such-page', id)
+ if (doc.pages.length <= 1) return fail('last-page', 'a space needs at least one page')
+
+ const doomed = new Set<string>([id])
+ if (opts.descendants) {
+ let grew = true
+ while (grew) {
+ grew = false
+ for (const p of doc.pages) {
+ if (p.parent && doomed.has(p.parent) && !doomed.has(p.id)) { doomed.add(p.id); grew = true }
+ }
+ }
+ }
+ if (doomed.size >= doc.pages.length) return fail('last-page', 'that would remove every page in the space')
+
+ const rehome = opts.descendants ? [] : doc.pages.filter((p) => p.parent === id)
+ const ix = buildIndex(doc)
+ let links = 0
+ for (const gone of doomed) {
+ for (const ref of ix.backlinks.get(gone) ?? []) if (!doomed.has(ref.pageId)) links++
+ }
+
+ return {
+ ok: true, removed: [...doomed], rehomed: rehome.length, links,
+ apply() {
+ for (const p of rehome) {
+ if (page.parent) p.parent = page.parent
+ else delete p.parent
+ }
+ doc.pages = doc.pages.filter((p) => !doomed.has(p.id))
+ if (doc.home && doomed.has(doc.home)) delete doc.home
+ },
+ }
+}
diff --git a/spaces/src/blocks.ts b/spaces/src/blocks.ts
new file mode 100644
index 00000000..9975048d
--- /dev/null
+++ b/spaces/src/blocks.ts
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The block-type registry: ONE declaration per type.
+//
+// Adding a block type used to mean editing four files in five places — the
+// renderer's tag map and list map, the / menu, the markdown-autoformat table,
+// and the markdown exporter — with nothing connecting them. A type added to
+// four of the five looked finished and silently exported as a bare paragraph.
+//
+// Now each type is one entry here and every consumer derives from it. That is
+// worth stating as a rule rather than a convenience: several people (and
+// several agents) add block types in parallel, and a registry turns four
+// simultaneous edits to the same hot files into four independent entries.
+//
+// PURE DATA — no DOM, no imports from render.ts or editor.ts. That keeps the
+// dependency arrow one-way (consumers import the registry, never the reverse)
+// and lets a node test read it directly.
+//
+// Types with genuinely custom layout (image, todo, toggle, pagelink, code,
+// divider) still have their rendering in render.ts and say so with
+// `custom: true`; everything the registry can express lives here.
+
+import type { Block } from './model'
+import type { IconName } from './icons'
+
+export interface BlockSpec {
+ type: string
+ /**
+ * Menu label and hint, in ENGLISH.
+ *
+ * Not translated here: t() at module scope freezes the string at import,
+ * before the reader's locale is known (CLAUDE.md). English IS the key, so
+ * consumers call t(spec.label) at render time.
+ */
+ label: string
+ hint: string
+ icon: IconName
+ /**
+ * Markdown prefixes that turn the block being typed into this type.
+ *
+ * A LIST, because the real ones have aliases: `- ` and `* ` both start a
+ * bullet, `[] ` and `[ ] ` both start a to-do. Collapsing those to one
+ * pattern each would quietly drop half the triggers people already use.
+ */
+ md?: RegExp[]
+ /**
+ * Fields a block of this type needs beyond id/type.
+ *
+ * MUST NOT CLOBBER a value that is already there: this runs both on a fresh
+ * block and when an EXISTING block is converted (editor.setType), and a
+ * bullet turned into a to-do must not lose a `done` someone had already
+ * ticked. `m` is the markdown trigger's match, so a trigger can carry a
+ * value — `[!warning] ` sets the tone it named.
+ */
+ init?: (b: Block, m?: RegExpMatchArray) => void
+ /** Semantic element, when the default renderer (tag + inline text) applies. */
+ tag?: string
+ /** Adjacent siblings of the same kind share one list element. */
+ list?: 'ul' | 'ol'
+ /**
+ * This type owns the blocks whose `parent` is its id, and the renderer gives
+ * it a body element to hold them.
+ *
+ * `'fold'` means the body is hidden unless `open` — the `toggle` idiom.
+ * `'always'` means it is never hidden, which is the whole difference between
+ * a callout and a toggle and is why this is a value rather than a boolean.
+ */
+ container?: 'always' | 'fold'
+ /**
+ * In markdown, this type's whole subtree lives inside its blockquote.
+ *
+ * A GitHub alert is a blockquote: the box ends at the first line that does
+ * not start with `>`, and everything after it renders as loose prose. So a
+ * container that exports as one needs every descendant line marked, which is
+ * what mdLayout() below works out.
+ */
+ mdQuoteChildren?: boolean
+ /** Rendered by a dedicated case in render.ts, not by tag + inline host. */
+ custom?: boolean
+ /** Carries editable inline html. False for divider, image, pagelink. */
+ text?: boolean
+ /** Hidden from the / menu (a type reachable only another way). */
+ unlisted?: boolean
+ /**
+ * Markdown export. `text` is the block's inline html already converted to
+ * inline markdown; `indent` is set for a nested block. Absent = the text
+ * alone, which is also what an UNKNOWN type gets.
+ */
+ toMd?: (b: Block, text: string, indent: string, titleOf: (id: string) => string | undefined) => string[]
+}
+
+export const SPECS: BlockSpec[] = [
+ {
+ type: 'p', label: 'Text', hint: 'Plain paragraph', icon: 'text',
+ tag: 'p', text: true,
+ },
+ {
+ type: 'h1', label: 'Heading 1', hint: '#', icon: 'h1',
+ tag: 'h1', text: true, md: [/^# $/],
+ toMd: (_b, text) => [`# ${text}`],
+ },
+ {
+ type: 'h2', label: 'Heading 2', hint: '##', icon: 'h2',
+ tag: 'h2', text: true, md: [/^## $/],
+ toMd: (_b, text) => [`## ${text}`],
+ },
+ {
+ type: 'h3', label: 'Heading 3', hint: '###', icon: 'h3',
+ tag: 'h3', text: true, md: [/^### $/],
+ toMd: (_b, text) => [`### ${text}`],
+ },
+ {
+ type: 'bullet', label: 'Bulleted list', hint: '-', icon: 'bullet',
+ tag: 'li', list: 'ul', text: true, md: [/^- $/, /^\* $/],
+ toMd: (_b, text, indent) => [`${indent}- ${text}`],
+ },
+ {
+ type: 'number', label: 'Numbered list', hint: '1.', icon: 'number',
+ tag: 'li', list: 'ol', text: true, md: [/^1\. $/],
+ toMd: (_b, text, indent) => [`${indent}1. ${text}`],
+ },
+ {
+ type: 'todo', label: 'To-do', hint: '[]', icon: 'todo',
+ tag: 'li', list: 'ul', text: true, custom: true,
+ md: [/^\[\] $/, /^\[ \] $/],
+ init: (b) => { if (b.done === undefined) b.done = false },
+ toMd: (b, text, indent) => [`${indent}- [${b.done ? 'x' : ' '}] ${text}`],
+ },
+ {
+ type: 'toggle', label: 'Toggle', hint: 'Collapsible section', icon: 'toggle',
+ tag: 'div', text: true, custom: true, container: 'fold',
+ init: (b) => { if (b.open === undefined) b.open = true },
+ toMd: (_b, text, indent) => [`${indent}- ${text}`],
+ },
+ {
+ type: 'callout', label: 'Callout', hint: 'A note, tip or warning', icon: 'callout',
+ // <aside> is the semantic element, and inside our <article class="sp-page">
+ // it maps to role=generic rather than to a `complementary` LANDMARK (that
+ // mapping only applies to a top-level aside). So a page of callouts does
+ // not fill a screen-reader's landmark list with fifteen entries.
+ tag: 'aside', text: true, custom: true, container: 'always', mdQuoteChildren: true,
+ // `> ` converts to a quote at the space, so `> [!NOTE] ` can never be typed
+ // as one trigger — MEASURED, the block is already a quote by the time the
+ // bracket arrives. The trigger is therefore the tag ALONE, which fires just
+ // as well in the quote it lands in as on an empty paragraph.
+ md: [/^\[!(note|tip|important|warning|caution)\] $/i],
+ init: (b, m) => {
+ const named = m?.[1]?.toLowerCase()
+ if (named) b.tone = named
+ else if (b.tone === undefined) b.tone = 'note'
+ },
+ toMd: (b, text) => {
+ // The tone comes from a file someone MAILED you. A newline or a `]` in it
+ // would end the alert tag early and turn the rest of the callout into
+ // prose, so the exported tag is the sanitised form — while `b.tone` in
+ // the document is left exactly as it was found.
+ const tag = String(b.tone ?? 'note').toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 24) || 'NOTE'
+ // one `> ` per LINE: htmlToMd turns <br> into a newline, and a bare
+ // newline inside a blockquote ends it
+ return [`> [!${tag}]`, ...(text ? text.split('\n') : ['']).map((l) => (l ? `> ${l}` : '>'))]
+ },
+ },
+ {
+ type: 'quote', label: 'Quote', hint: '>', icon: 'quote',
+ tag: 'blockquote', text: true, md: [/^> $/],
+ toMd: (_b, text) => [`> ${text}`],
+ },
+ {
+ type: 'code', label: 'Code', hint: '``` ', icon: 'code',
+ tag: 'div', text: true, custom: true,
+ // The fence CARRIES ITS LANGUAGE: ```py, ```sh, ```json.
+ //
+ // Completed by a SPACE, where a bare ``` used to convert on the third
+ // backtick. A deliberate change to an existing trigger: every other rule
+ // here is space-completed (`# `, `- `, `> `, `--- `), and while ```
+ // converted instantly there was no keystroke left in which to type the
+ // language — which is the muscle memory everyone brings from GitHub and
+ // every other markdown box.
+ //
+ // The tag is stored VERBATIM, never normalised. `lang` is document data, so
+ // a language this build cannot highlight still round-trips, still exports
+ // as ```rust, and lights up by itself the day the lexer learns it.
+ md: [/^```(\w*) $/],
+ init: (b, m) => { const lang = m?.[1]; if (lang) b.lang = lang },
+ toMd: (b, text) => ['```' + String(b.lang ?? ''), text, '```'],
+ },
+ {
+ type: 'divider', label: 'Divider', hint: '---', icon: 'divider',
+ tag: 'div', custom: true, md: [/^--- $/],
+ toMd: () => ['---'],
+ },
+ {
+ type: 'pagelink', label: 'Link to page', hint: 'A card that opens a page', icon: 'link',
+ tag: 'div', custom: true,
+ toMd: (b, _text, _indent, titleOf) => [`→ [[${titleOf(String(b.page)) ?? '?'}]]`],
+ },
+ {
+ type: 'image', label: 'Image', hint: 'Embedded in the file', icon: 'image',
+ tag: 'div', custom: true,
+ toMd: (b) => [`![${String(b.alt ?? '')}](${String(b.src ?? '')})`],
+ },
+]
+
+/**
+ * Callout tones — a PERMANENT vocabulary.
+ *
+ * These five are GitHub's alert types, spelled exactly as GitHub spells them,
+ * so `tone` → `> [!TONE]` and back is the IDENTITY function. Every other
+ * candidate set (Docusaurus's note/tip/info/warning/danger, MkDocs' thirteen)
+ * needs a mapping table in the exporter, and a mapping table is a thing that
+ * can be got wrong once and then cannot be corrected — the wrong tone would
+ * already be in files on disks.
+ *
+ * FIVE, not thirteen, and no `success`: the format is additive, so a sixth tone
+ * can be added later and older builds will render it neutrally and keep both
+ * the word and its spelling (render.ts). Removing or renaming one is
+ * impossible. When a decision is one-way, ship the smaller set.
+ *
+ * The MARK IS A SHAPE, not a hue: circle, bulb, square, triangle, octagon. With
+ * the tone's name spelled out beside it, a callout is identifiable with no
+ * colour vision at all, on a black-and-white printout, and at a glance. The
+ * tints are decoration and carry no meaning on their own — deliberately, since
+ * amber/red/green are the pair-of-hues most readers cannot separate.
+ *
+ * There is deliberately no `label` here. The i18n sweep reads t() calls with a
+ * LITERAL STRING out of the source, so a label sitting in a data table ships
+ * English in all eight locales — which is exactly what has happened to the
+ * block MENU labels above. Tone names are written out as t() calls in render.ts,
+ * and a check in scripts/test-spaces-model.ts fails if a tone here has no case
+ * there.
+ */
+export interface ToneSpec {
+ tone: string
+ icon: IconName
+}
+
+export const CALLOUT_TONES: ToneSpec[] = [
+ { tone: 'note', icon: 'toneNote' },
+ { tone: 'tip', icon: 'toneTip' },
+ { tone: 'important', icon: 'toneImportant' },
+ { tone: 'warning', icon: 'toneWarning' },
+ { tone: 'caution', icon: 'toneCaution' },
+]
+
+export const TONE: ReadonlyMap<string, ToneSpec> = new Map(CALLOUT_TONES.map((t) => [t.tone, t]))
+
+/** Lookup by type. An UNKNOWN type returns undefined and must still render — a
+ * file written by a newer build opens here, and it opens as text. */
+export const SPEC: ReadonlyMap<string, BlockSpec> = new Map(SPECS.map((s) => [s.type, s]))
+
+/** The / menu and the Insert dropdown, in declaration order. */
+export const MENU_SPECS = SPECS.filter((s) => !s.unlisted)
+
+/** Markdown autoformat rules, derived so a type cannot have a menu entry and
+ * no trigger by accident — or a trigger nobody can find in a menu. */
+export type MdRule = [RegExp, string, (b: Block, m?: RegExpMatchArray) => void]
+
+export const MD_SPECS: MdRule[] =
+ SPECS.flatMap((s) => (s.md ?? []).map((re) => [re, s.type, s.init ?? (() => {})] as MdRule))
+
+/**
+ * `type -> semantic element`, for EVERY type.
+ *
+ * `custom` says the renderer fills the element itself; it does not change what
+ * the element IS. `todo` is both custom and an `li` — filtering custom types
+ * out of this map would silently move to-do items out of their list.
+ */
+export const TAG_OF: Record<string, string> =
+ Object.fromEntries(SPECS.filter((s) => s.tag).map((s) => [s.type, s.tag!]))
+
+/** Types whose adjacent siblings share one <ul>/<ol>. */
+export const LIST_OF: Record<string, 'ul' | 'ol'> =
+ Object.fromEntries(SPECS.filter((s) => s.list).map((s) => [s.type, s.list!]))
+
+/**
+ * How each block's markdown lines are decorated, for one page's flat list.
+ *
+ * The three parts a line needs that a single block cannot know on its own:
+ * `quote` (the `> ` markers that keep it inside the alert it belongs to),
+ * `indent` (list nesting), and `sep` (what goes BETWEEN this block and the
+ * next — a blank line normally, but a bare `>` inside an alert, because a blank
+ * line closes a blockquote and would split one callout into a box followed by
+ * loose text).
+ *
+ * It lives here, not in the exporter, for two reasons: it is derived entirely
+ * from registry facts (`mdQuoteChildren`), and about.ts drags in the kernel's
+ * update and save modules, so a node test cannot import it to check any of
+ * this. This is the part with the edge cases, so this is the part that has to
+ * be reachable from a test.
+ */
+export function mdLayout(blocks: Block[]): Array<{ quote: string; indent: string; sep: string }> {
+ const byId = new Map(blocks.map((b) => [b.id, b]))
+ // HOP-CAPPED: `parent` is a plain id in a file anyone can hand-edit, so two
+ // blocks can name each other. The renderer is a pre-order pass and cannot
+ // loop; an ancestor walk can, and would hang an export of a document that
+ // displays perfectly well.
+ const owners = (b: Block): Block[] => {
+ const chain: Block[] = []
+ for (let o = b.parent ? byId.get(b.parent) : undefined; o && chain.length < 32; o = o.parent ? byId.get(o.parent) : undefined) chain.push(o)
+ return chain
+ }
+ const wraps = (b: Block | undefined): boolean => !!b && SPEC.get(b.type)?.mdQuoteChildren === true
+ const alert = (b: Block): string | undefined => owners(b).find(wraps)?.id
+ const depth = (b: Block): number => owners(b).filter(wraps).length
+
+ return blocks.map((b, i) => {
+ const parent = b.parent ? byId.get(b.parent) : undefined
+ // Inside a callout a child is the alert's BODY, not a nested list item.
+ // Indenting it makes GitHub read it as a nested list — or, at four spaces,
+ // as a code block.
+ const indent = parent && !wraps(parent) ? ' ' : ''
+ const next = blocks[i + 1]
+ // "same alert" compares the alert the NEXT block is in against the alert
+ // this one IS or is in, so a callout and its first child are joined, and so
+ // are two children of one callout — but two adjacent callouts are not.
+ const mine = wraps(b) ? b.id : alert(b)
+ const sep = next && alert(next) && alert(next) === mine ? '> '.repeat(depth(next)).trimEnd() : ''
+ return { quote: '> '.repeat(depth(b)), indent, sep }
+ })
+}
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 91c3398b..7c19cbfc 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -10,46 +10,42 @@
import { type Block, newBlock, newPage } from './model'
import { Store } from './store'
-import { renderPage } from './render'
-import { canonicalize, sanitizeInline, textOf } from './sanitize'
+import { renderPage, toneLabel, paintCode } from './render'
+import { CODE_LANGS, langLabel, normLang } from './highlight'
+import { canonicalize, escText, sanitizeInline, textOf } from './sanitize'
+import { MENU_SPECS, MD_SPECS, SPEC, CALLOUT_TONES } from './blocks'
+import { planImport, type SourceFile } from './markdown'
import { countOutsideTags, replaceOutsideTags } from './findreplace'
import { t } from './i18n'
import { openAbout } from './about'
+import { canWriteInPlace } from '../../kernel/src/save.ts'
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', () => {}],
-]
+// Markdown autoformat and the / menu both come from the block registry
+// (blocks.ts), so a type cannot end up with a menu entry and no trigger, or a
+// trigger that no menu mentions.
+const AUTOFORMAT = MD_SPECS
+
+const SLASH_ITEMS = MENU_SPECS
+/** What counts as a note when a folder is dropped on the app. */
+const NOTE_EXT = /\.(md|markdown|mdown|mkd)$/i
+
+/**
+ * When an import stops embedding images by itself and ASKS.
+ *
+ * A vault's attachment folder is unbounded — 400MB of screenshots is ordinary
+ * — and a space is something you mail. But the house rule for size is warn,
+ * never block (assets.ts SPACE_WEIGHT_WARN), so this is one question at one
+ * threshold, not a ceiling: answer yes and the rest embed too.
+ */
+const IMPORT_IMAGE_BUDGET = 12 * 1024 * 1024
+
+/** A picked or dropped file, with the path it had on disk. */
+interface PickedFile { path: string; file: File }
-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
@@ -73,7 +69,14 @@ export class Editor {
private allowedRemote = new Set<string>()
private undoB: HTMLButtonElement | null = null
private readB: HTMLButtonElement | null = null
- private redoB: HTMLButtonElement | null = null
+ private redoB!: HTMLButtonElement
+ private dirtyDot!: HTMLElement
+ private paneTab: HTMLButtonElement | null = null
+ private static readonly PANE_MIN = 150
+ private static readonly PANE_MAX = 420
+ private static readonly PANE_DEFAULT = 244
+ private paneW = Editor.PANE_DEFAULT
+ private paneClosed = false
onSave: (() => void) | null = null
onSaveAs: ((suffix: string) => void) | null = null
onPrint: (() => void) | null = null
@@ -81,10 +84,17 @@ export class Editor {
constructor(root: HTMLElement, store: Store) {
this.root = root
this.store = store
+ // the reader's panel, restored — never the document's
+ try {
+ const w = Number(localStorage.getItem('bento-sp-pane'))
+ if (Number.isFinite(w) && w > 0) this.paneW = Math.min(Editor.PANE_MAX, Math.max(Editor.PANE_MIN, w))
+ this.paneClosed = localStorage.getItem('bento-sp-pane-closed') === '1'
+ } catch { /* storage throws on a locked-down origin; the defaults are fine */ }
this.build()
+ if (this.paneClosed) this.sidebar.classList.add('sp-pane-closed')
this.store.on('tree', () => this.paintTree())
this.store.on('page', () => { this.paintPage(); this.paintTree() })
- this.store.on('doc', () => { this.status(t('Edited')); this.syncHistoryButtons() })
+ this.store.on('doc', () => { this.status(t('Edited')); this.syncHistoryButtons(); this.syncDirty() })
window.addEventListener('popstate', () => this.fromHash())
this.fromHash()
}
@@ -95,8 +105,21 @@ export class Editor {
this.root.className = 'sp-app'
const bar = el('header', 'sp-bar')
- const mark = el('span', 'sp-mark')
- mark.innerHTML = 'bento<span>/</span>spaces'
+ // THE SUITE'S MARK, and the way into About — the same control slides has.
+ // A wordmark that is only decoration wastes the one place everyone looks
+ // for "what is this file, and what version": there was no route to About
+ // except a ⋯ menu nobody opens.
+ const mark = el('button', 'sp-mark')
+ ;(mark as HTMLButtonElement).type = 'button'
+ mark.innerHTML =
+ '<svg class="sp-mark-svg" viewBox="0 0 32 32" width="20" height="20" aria-hidden="true">' +
+ '<rect width="32" height="32" rx="7" fill="#16273E"/>' +
+ '<rect x="5" y="5" width="7" height="22" rx="2.5" fill="#5E7699"/>' +
+ '<rect x="14" y="5" width="13" height="10" rx="2.5" fill="#FF9E8A"/>' +
+ '<rect x="14" y="17" width="13" height="10" rx="2.5" fill="#F0EBE0"/>' +
+ '</svg><b class="sp-mark-word">bento<span>/</span>spaces</b>'
+ mark.title = t('About bento/spaces — version, updates, language, password')
+ mark.addEventListener('click', () => this.openAbout())
// 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.
@@ -121,6 +144,7 @@ export class Editor {
const page = this.store.page
if (!page) return
const fresh = newBlock(item.type === 'pagelink' ? 'p' : item.type)
+ SPEC.get(fresh.type)?.init?.(fresh)
this.store.commit(() => { page.blocks.push(fresh) })
this.paintPage()
if (item.type === 'pagelink') this.insertPageCard(fresh.id)
@@ -130,22 +154,64 @@ export class Editor {
}
})
- 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() }))
+
+ // SECONDARY ACTIONS, declared ONCE.
+ //
+ // Measured at 375px before this existed: the bar wanted 678px, so seven of
+ // eleven controls sat off the right edge — including Save. On a phone the
+ // file could not be saved at all.
+ //
+ // Below the breakpoint these collapse into the ⋯ menu and the inline copies
+ // are hidden. One list feeds both, because a phone menu maintained by hand
+ // as a copy of the desktop row drifts the first time either one changes.
+ const secondary: Array<{
+ icon: IconName
+ label: string
+ hint: string
+ run: () => void
+ keep?: (b: HTMLButtonElement) => void
+ }> = [
+ { icon: 'page', label: t('New page'), hint: '⌘⌥N', run: () => this.newPage() },
+ { icon: 'eye', label: t('Reading view'), hint: t('The pages without the editing tools'),
+ run: () => this.toggleReading(),
+ keep: (b) => { this.readB = b } },
+ { icon: 'print', label: t('Print or save as PDF'), hint: '⌘P', run: () => this.openPrint() },
+ { icon: 'info', label: t('About this space'), hint: t('Version, language, password, exports'),
+ run: () => this.openAbout() },
+ ]
+
+ const inlineSecondary = secondary.map((a) => {
+ const b = iconBtn(a.icon, a.hint && a.hint.length < 12 ? `${a.label} (${a.hint})` : a.label, a.run)
+ b.classList.add('sp-sec')
+ a.keep?.(b)
+ return b
+ })
+
+ const more = this.dropdown('more', '', t('More'), (menu, close) => {
+ for (const a of secondary) {
+ menu.append(this.menuItem(a.icon, a.label, a.hint, () => { close(); a.run() }))
+ }
+ })
+ more.classList.add('sp-more', 'sp-dd-end')
// 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 saveLabel = document.createElement('span')
+ saveLabel.className = 'sp-savelabel'
+ saveLabel.textContent = t('Save')
+ saveB.append(saveLabel)
+ // The unsaved dot lives ON Save, as in slides: the place you look to find
+ // out whether you need to press it is the button itself.
+ this.dirtyDot = el('span', 'sp-dirty')
+ this.dirtyDot.title = canWriteInPlace()
+ ? t('Unsaved changes — ⌘S rewrites this file')
+ : t('Unsaved changes — ⌘S downloads an updated copy')
+ saveB.append(this.dirtyDot)
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')
@@ -157,26 +223,51 @@ export class Editor {
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() })
+ close(); this.openAbout()
}))
})
- saveMore.classList.add('sp-caret')
+ saveMore.classList.add('sp-caret', 'sp-dd-end')
+
+ // LEFT = the document (mark · title · save state · history), RIGHT = doing
+ // things with it. Same grouping as slides, so the two apps do not teach two
+ // different toolbars.
+ const history = el('div', 'sp-group sp-group-history')
+ history.append(this.undoB, this.redoB)
+ const saveGroup = el('div', 'sp-split')
+ saveGroup.append(saveB, saveMore)
+ const right = el('div', 'sp-group sp-group-right')
+ right.append(insert, search, ...inlineSecondary, more, saveGroup)
- bar.append(pagesB, mark, title, this.statusEl, insert, newPageB,
- this.undoB, this.redoB, search, this.readB, printB, about, saveB, saveMore)
+ bar.append(pagesB, mark, title, this.statusEl, history, right)
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)
+ body.append(this.sidebar, this.makeResizer(), this.main)
this.root.append(bar, body)
+ this.applyPaneWidth()
+ this.syncPaneChevron()
this.paintTree()
this.paintPage()
this.syncHistoryButtons()
+ this.syncDirty()
document.addEventListener('keydown', (e) => this.onKey(e), true)
+
+ // Dropping notes anywhere on the app imports them — the sidebar, the
+ // topbar, the grey around the page. The page's own drop handler takes
+ // images and stands down for markdown, so the two never both fire.
+ this.root.addEventListener('dragover', (e) => {
+ if (e.dataTransfer?.types.includes('Files')) e.preventDefault()
+ })
+ this.root.addEventListener('drop', (e) => {
+ if (!isImportDrop(e.dataTransfer)) return
+ e.preventDefault()
+ const picked = collectDrop(e.dataTransfer)
+ void picked.then((files) => this.importFiles(files))
+ })
}
/**
@@ -202,6 +293,11 @@ export class Editor {
}
/** Undo/redo must LOOK unavailable when they are, or they read as broken. */
+ /** The dot on Save, and the only place the file's state is visible. */
+ syncDirty(): void {
+ this.dirtyDot?.classList.toggle('sp-on', this.store.dirty)
+ }
+
private syncHistoryButtons(): void {
if (this.undoB) this.undoB.disabled = !this.store.canUndo
if (this.redoB) this.redoB.disabled = !this.store.canRedo
@@ -251,7 +347,94 @@ export class Editor {
}
/** Open/close the page drawer on narrow screens, with a scrim to tap away. */
+ /**
+ * The strip between the page list and the page: drag to resize, chevron to
+ * collapse, double-click to reset. Slides' pattern, and its reasoning — the
+ * control that hides a panel belongs ON the panel's edge, where you are
+ * already looking, not in a toolbar across the room.
+ *
+ * The width is the reader's, so it lives in localStorage, never the document.
+ */
+ private makeResizer(): HTMLElement {
+ const handle = el('div', 'sp-resizer')
+ handle.title = t('Drag to resize · double-click to reset')
+
+ const tab = document.createElement('button')
+ tab.className = 'sp-pane-tab'
+ tab.type = 'button'
+ tab.addEventListener('click', (e) => { e.stopPropagation(); this.togglePane() })
+ this.paneTab = tab
+ handle.append(tab)
+
+ handle.addEventListener('mousedown', (down) => {
+ if (down.target === tab) return // the chevron is a click, not a drag
+ if (this.paneClosed) return
+ down.preventDefault()
+ const startX = down.clientX
+ const startW = this.paneW
+ this.sidebar.classList.add('sp-noanim')
+ document.body.classList.add('sp-col-resizing')
+ const move = (ev: MouseEvent) => {
+ // clientX is physical; which way widens depends on the edge the panel
+ // is docked to, and RTL swaps that over.
+ const dx = ev.clientX - startX
+ const widens = document.dir === 'rtl' ? -dx : dx
+ this.paneW = Math.min(Editor.PANE_MAX, Math.max(Editor.PANE_MIN, startW + widens))
+ this.applyPaneWidth()
+ }
+ const up = () => {
+ window.removeEventListener('mousemove', move)
+ window.removeEventListener('mouseup', up)
+ this.sidebar.classList.remove('sp-noanim')
+ document.body.classList.remove('sp-col-resizing')
+ try { localStorage.setItem('bento-sp-pane', String(this.paneW)) } catch { /* storage can throw */ }
+ }
+ window.addEventListener('mousemove', move)
+ window.addEventListener('mouseup', up)
+ })
+
+ handle.addEventListener('dblclick', () => {
+ this.paneW = Editor.PANE_DEFAULT
+ this.applyPaneWidth()
+ try { localStorage.setItem('bento-sp-pane', String(this.paneW)) } catch { /* storage can throw */ }
+ })
+ return handle
+ }
+
+ private applyPaneWidth(): void {
+ this.sidebar.style.setProperty('--sp-panew', `${this.paneW}px`)
+ }
+
+ private syncPaneChevron(): void {
+ if (!this.paneTab) return
+ // points the way it will MOVE the panel, which is the only thing a chevron
+ // can usefully mean
+ const rtl = document.dir === 'rtl'
+ const closing = this.paneClosed !== rtl
+ this.paneTab.innerHTML = closing ? ICONS.chevronRight : ICONS.chevronLeft
+ this.paneTab.title = this.paneClosed ? t('Show the page list ([)') : t('Hide the page list ([)')
+ this.paneTab.setAttribute('aria-label', this.paneTab.title)
+ this.paneTab.setAttribute('aria-expanded', String(!this.paneClosed))
+ }
+
+ /** Collapse or restore the page list. On a phone it is a drawer instead. */
+ togglePane(force?: boolean): void {
+ if (this.isDrawer()) { this.toggleSidebar(force); return }
+ this.paneClosed = force !== undefined ? !force : !this.paneClosed
+ this.sidebar.classList.toggle('sp-pane-closed', this.paneClosed)
+ this.syncPaneChevron()
+ try { localStorage.setItem('bento-sp-pane-closed', this.paneClosed ? '1' : '0') } catch { /* storage can throw */ }
+ }
+
+ private isDrawer(): boolean {
+ return window.matchMedia('(max-width: 820px)').matches
+ }
+
private toggleSidebar(force?: boolean): void {
+ // Below the drawer breakpoint the panel is an overlay, not a column: the
+ // page needs the whole width, so collapsing to a 0px column would leave
+ // nothing to reopen it from.
+ if (!this.isDrawer()) { this.togglePane(force); return }
const open = force ?? !this.sidebar.classList.contains('sp-open')
this.sidebar.classList.toggle('sp-open', open)
document.querySelector('.sp-scrim')?.remove()
@@ -275,6 +458,10 @@ export class Editor {
this.sidebar.innerHTML = ''
const head = el('div', 'sp-side-head')
head.append(el('span', 'sp-side-title', t('Pages')))
+ // import sits beside "new page" because that is where pages come from,
+ // and because the moment someone wants it is the moment they see an empty
+ // sidebar next to a folder of notes they already have
+ head.append(iconBtn('markdown', t('Import Markdown files or a folder…'), () => this.openImport()))
head.append(iconBtn('plus', t('New page (⌘⌥N)'), () => this.newPage()))
this.sidebar.append(head)
@@ -552,6 +739,9 @@ export class Editor {
for (const host of view.querySelectorAll<HTMLElement>('[data-edit]')) {
const id = host.dataset.edit!
+ // A code block's host holds TEXT, not inline html, and carries colour
+ // that must never reach the model. It gets its own wiring.
+ if (s.block(id)?.type === 'code') { this.wireCode(id, host); continue }
host.dataset.ph = t('Type / for blocks, [[ to link a page')
host.addEventListener('input', () => {
if (this.painting) return
@@ -581,6 +771,23 @@ export class Editor {
})
}
+ // the callout's own mark and name ARE the control that changes them — a
+ // tone buried in a menu is a tone nobody ever changes
+ // Reading view is READ-ONLY, and this loop is the one that forgot: the
+ // renderer already emits an inert <span> when !opts.editable, so the wiring
+ // contradicted the renderer's own intent and a click in reading view
+ // committed a tone change — undo entry, dirty flag and all. The gutter and
+ // language loops guard the same way.
+ if (!this.store.readOnly && !this.reading) {
+ for (const chip of view.querySelectorAll<HTMLElement>('.sp-callout-chip')) {
+ chip.addEventListener('click', (e) => {
+ e.preventDefault()
+ const id = (chip.closest('[data-block-id]') as HTMLElement).dataset.blockId!
+ this.openTonePicker(id, chip)
+ })
+ }
+ }
+
for (const tw of view.querySelectorAll<HTMLElement>('.sp-twist')) {
tw.addEventListener('click', () => {
const id = (tw.closest('[data-block-id]') as HTMLElement).dataset.blockId!
@@ -615,12 +822,33 @@ export class Editor {
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')
+ // markdown (or a folder) is an IMPORT: leave it for the app-level
+ // handler rather than rummaging through it for an image
+ if (isImportDrop(e.dataTransfer)) return
+ e.preventDefault()
const near = (e.target as HTMLElement)?.closest?.('[data-block-id]') as HTMLElement | null
void this.imageFromTransfer(e.dataTransfer, near?.dataset.blockId)
})
+ // The language chip. It belongs to the EDITOR, not the renderer: a reader
+ // and a printed page get the colours, not the control that changes them.
+ if (!s.readOnly && !this.reading) {
+ for (const node of view.querySelectorAll<HTMLElement>('.sp-b-code')) {
+ const id = node.dataset.blockId!
+ const chip = document.createElement('button')
+ chip.className = 'sp-btn sp-langchip'
+ chip.type = 'button'
+ // the RAW tag when this build cannot highlight it, so a `rust` block
+ // says "rust" and its plain rendering reads as a gap, not a bug
+ chip.textContent = langLabel(s.block(id)?.lang) || t('Plain text')
+ chip.title = t('Language — what this block is highlighted as')
+ chip.setAttribute('aria-label', t('Language — what this block is highlighted as'))
+ chip.addEventListener('click', () => this.openLangPicker(id, chip))
+ node.append(chip)
+ }
+ }
+
for (const fig of view.querySelectorAll<HTMLElement>('.sp-b-image')) {
const id = fig.dataset.blockId!
const b = s.block(id)
@@ -656,10 +884,101 @@ export class Editor {
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)) }
+ if (!href.startsWith('#p/')) return
+ // through the same resolver as the address bar, so a block anchor
+ // navigates to its page instead of doing nothing at all
+ e.preventDefault()
+ const id = this.resolveAnchor(href)
+ if (id) s.goToPage(id)
})
}
+ /**
+ * A code block's editable host.
+ *
+ * TWO THINGS DIFFER from every other block, and both are load-bearing.
+ *
+ * The MODEL takes `textContent`, not `innerHTML`. The host now contains
+ * colour spans; reading innerHTML would write them into `b.html` and the
+ * document would carry presentation — a format change, permanent, for a
+ * feature that is supposed to be render-only. What is stored is the same
+ * html-escaped plain text a code block has always stored, so files written
+ * before highlighting existed and files written after are indistinguishable.
+ *
+ * The COLOUR is repainted synchronously on input, and `paintCode` reconciles
+ * rather than replacing — see its comment. Measured on the built shell: an
+ * insertion in the middle of a line changes no token boundary, so the paint
+ * performs zero DOM mutations and the caret is untouched. Only a keystroke
+ * that restructures the token stream costs a caret restore, and then the
+ * offset is exact because the reconcile is the only thing that moved it.
+ *
+ * Canonicalization is deliberately NOT run here (the generic host runs it on
+ * blur): it exists to tidy inline markup, and a code block has none.
+ */
+ private wireCode(id: string, host: HTMLElement): void {
+ const s = this.store
+ // An IME composition lives in nodes the engine owns; re-tokenising
+ // mid-composition destroys them and drops the half-typed word. The model
+ // keeps up regardless — only the colour waits for compositionend.
+ let composing = false
+ const sync = (paint: boolean): void => {
+ const text = host.textContent ?? ''
+ s.runEdit(id, () => { const b = s.block(id); if (b) b.html = escText(text) })
+ if (!paint) return
+ const at = caretIndexIn(host)
+ if (paintCode(host, text, s.block(id)?.lang) && at !== null) caretToOffset(host, at)
+ }
+ host.addEventListener('compositionstart', () => { composing = true })
+ host.addEventListener('compositionend', () => { composing = false; sync(true) })
+ host.addEventListener('input', () => { if (!this.painting) sync(!composing) })
+ host.addEventListener('blur', () => { if (!this.painting) s.endRun() })
+ }
+
+ /** Choose what a code block is highlighted as. */
+ private openLangPicker(blockId: string, anchor: HTMLElement): void {
+ const s = this.store
+ if (s.readOnly || this.reading) return
+ this.closeOverlay()
+ const pop = el('div', 'sp-pop sp-langpop')
+ pop.setAttribute('role', 'menu')
+ this.trapAndClose(pop, () => this.focusBlock(blockId))
+ // An UNKNOWN tag matches NO row. `rust` renders plain, but it is not the
+ // same thing as plain: ticking "Plain text" for it would say the tag is
+ // already gone, and the next click would quietly delete it.
+ const raw = String(s.block(blockId)?.lang ?? '').trim()
+ const cur = normLang(raw)
+ const unknown = !!raw && !cur
+ for (const { id, label } of CODE_LANGS) {
+ const b = document.createElement('button')
+ b.className = 'sp-dditem' + (!unknown && id === cur ? ' sp-sel' : '')
+ b.type = 'button'
+ b.setAttribute('role', 'menuitem')
+ b.append(Object.assign(document.createElement('strong'), {
+ textContent: label || t('Plain text'),
+ }))
+ b.addEventListener('click', () => {
+ this.closeOverlay()
+ s.commit(() => {
+ const blk = s.block(blockId)
+ if (!blk) return
+ if (id) blk.lang = id
+ else delete blk.lang
+ })
+ 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)
+ }
+
private treeTimer: ReturnType<typeof setTimeout> | undefined
private paintTreeSoon(): void {
clearTimeout(this.treeTimer)
@@ -704,15 +1023,45 @@ export class Editor {
return this.blockAt(document.activeElement)
}
- /** Markdown prefixes convert the block as they are typed. */
+ /**
+ * Markdown prefixes convert the block as they are typed.
+ *
+ * THE TRAILING SPACE IS NOT A SPACE. A space typed at the end of a
+ * contenteditable line is inserted by the engine as U+00A0, so that it does
+ * not collapse — measured in Chrome on the built shell: after typing "## ",
+ * `host.textContent` is `['#','#',160]` and `/^## $/` does not match it.
+ * Every space-completed trigger in the table above was therefore dead, which
+ * is most of them. Normalising here (never in the model — the block's html is
+ * cleared by the conversion anyway) fixes all of them at once.
+ */
private autoformat(id: string, host: HTMLElement): void {
- const text = host.textContent ?? ''
+ // A trailing space typed at the end of a contentEditable line is inserted
+ // by the browser as U+00A0, not U+0020 — otherwise it would collapse and
+ // the caret would appear not to move. So `/^## $/` never matched anything a
+ // person typed, and every markdown trigger in this app was dead from the
+ // first release: measured in the built shell, `# `, `## `, `- `, `1. `,
+ // `> ` and `[] ` all arrived as [.., 160] and converted nothing.
+ //
+ // It survived a test because the test assigned `host.textContent` directly
+ // — with a real space, which is a path no keystroke takes. Drive
+ // autoformat with execCommand('insertText'), or it proves nothing.
+ //
+ // Normalised for the TEST only. The model keeps whatever the browser put
+ // there; rewriting the author's text to make a pattern match would be a
+ // cure worse than the disease.
+ const text = (host.textContent ?? '').replace(/\u00a0/g, ' ')
for (const [re, type, extra] of AUTOFORMAT) {
- if (!re.test(text)) continue
+ // the MATCH, not just a test: a trigger may name a value, as
+ // `[!warning] ` names the tone the callout is about to have
+ const m = re.exec(text)
+ if (!m) 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) })
+ // `b.type === type` alone would stop `[!caution] ` from re-toning a
+ // callout that is already a callout
+ if (!b) return
+ if (b.type === type && m.length < 2) return
+ s.commit(() => { b.type = type; b.html = ''; extra(b, m) })
this.paintPage()
this.focusBlock(id)
return
@@ -737,6 +1086,10 @@ export class Editor {
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 }
+ // `[` collapses the page list, as in slides. Bare, not modified: it only
+ // reaches here when nothing is being edited (the text path returns above,
+ // where `[` is the page-link trigger).
+ if (!mod && e.key === '[') { e.preventDefault(); this.togglePane(); return }
if (mod && e.key.toLowerCase() === 'z') {
e.preventDefault()
if (e.shiftKey) s.redo(); else s.undo()
@@ -754,6 +1107,25 @@ export class Editor {
// native undo must never diverge from the store's history
if (mod && (e.key.toLowerCase() === 'y')) { e.preventDefault(); s.redo(); this.paintPage(); return }
+ // A CODE BLOCK IS TEXT, so the block-editor keymap does not apply to it.
+ // Enter is a newline (not a block split), Tab is an indent (not a
+ // re-parent — indenting the block in the page tree is never what someone
+ // pressing Tab inside source code meant), and /, [[ and ⌘B are off.
+ //
+ // Enter is handled EXPLICITLY rather than left to the engine: what the
+ // browser inserts into a contenteditable varies (a `\n`, a `<br>`, a
+ // wrapping `<div>`), and only the first survives reading the host's
+ // textContent, which is now how the model is written. execCommand keeps
+ // the caret and fires the `input` event that repaints the colour.
+ if (b.type === 'code') {
+ // Shift is not a modifier here: there is no "soft break" in source code,
+ // so both Enters are the same newline.
+ if (e.key === 'Enter') { e.preventDefault(); insertText('\n'); return }
+ if (e.key === 'Tab') { e.preventDefault(); if (!e.shiftKey) insertText(' '); return }
+ if (e.key === '/' || e.key === '[') return
+ if (mod && ['b', 'i', 'u'].includes(e.key.toLowerCase())) { e.preventDefault(); return }
+ }
+
if (e.key === 'Enter' && !e.shiftKey && b.type !== 'code') {
e.preventDefault()
this.splitBlock(cur.id, cur.host)
@@ -762,6 +1134,15 @@ export class Editor {
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 }
+ // …and the way OUT of a container is the same key that got you in.
+ // Without this, ⏎ puts a line inside a callout and backspace merges it
+ // into the callout's own text, so the only exit is Shift-Tab — which
+ // nobody finds. Empty line + backspace = out, as in every outliner.
+ if (empty && b.parent && SPEC.get(s.block(b.parent)?.type ?? '')?.container === 'always') {
+ e.preventDefault()
+ this.indent(cur.id, false)
+ return
+ }
e.preventDefault()
this.mergeBack(cur.id)
return
@@ -793,9 +1174,19 @@ export class Editor {
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
+ const heading = b.type === 'h1' || b.type === 'h2' || b.type === 'h3'
+ // ⏎ INSIDE AN ALWAYS-OPEN CONTAINER GOES IN, not after.
+ //
+ // A callout's second line belongs in the callout; making a second empty
+ // callout instead is what everyone who has used one expects not to happen,
+ // and it is also the only thing that makes nesting discoverable without
+ // knowing that Tab does it. Deliberately NOT extended to `toggle`: a fold
+ // can be shut, and putting the caret inside a shut fold loses the line.
+ const into = SPEC.get(b.type)?.container === 'always'
+ const fresh = newBlock(heading || into ? 'p' : b.type, { html: after })
+ SPEC.get(fresh.type)?.init?.(fresh)
+ if (into) fresh.parent = b.id
+ else if (b.parent) fresh.parent = b.parent
s.commit(() => {
b.html = before
const page = s.page!
@@ -858,8 +1249,10 @@ export class Editor {
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
+ // the registry seeds the type's own fields (blocks.ts `init`), so a new
+ // block type does not need a line here as well — this was the fifth place
+ // a type had to be added, and the one that was easiest to forget
+ SPEC.get(type)?.init?.(b)
})
this.paintPage()
this.focusBlock(id)
@@ -888,6 +1281,30 @@ export class Editor {
this.overlay = null
}
+ /**
+ * Make a popover dismissible and reachable from the keyboard.
+ *
+ * The tone and language pickers set `this.overlay` and installed only a
+ * mousedown-away listener — and `onKey` early-returns while an overlay is
+ * open, so Escape did nothing and Tab walked off into the page behind. That
+ * is a keyboard trap: a menu you can open without a mouse and cannot close
+ * without one. The slash menu got this right by focusing its own input; these
+ * two have no input, so the popover itself takes focus.
+ */
+ private trapAndClose(pop: HTMLElement, returnTo?: () => void): void {
+ pop.tabIndex = -1
+ pop.addEventListener('keydown', (e) => {
+ if (e.key !== 'Escape') return
+ e.preventDefault()
+ e.stopPropagation()
+ this.closeOverlay()
+ returnTo?.()
+ })
+ // focus AFTER the browser has laid the popover out, or the focus is lost to
+ // the element the click came from
+ afterPaint(() => pop.focus())
+ }
+
/** Anchor a popover to a rect, kept inside the viewport. */
/** ⌘K — search every page, including collapsed toggles and archived pages. */
@@ -1110,6 +1527,77 @@ export class Editor {
}, 0)
}
+ /**
+ * Which kind of callout this is, and (optionally) a glyph of your own.
+ *
+ * Five tones and one field, anchored on the chip you clicked. The icon is a
+ * plain text box rather than an emoji grid: the system emoji picker is one
+ * keystroke away on every platform this runs on, and a grid of our own would
+ * be a few KB to ship a worse one.
+ */
+ private openTonePicker(blockId: string, anchor: HTMLElement): void {
+ const s = this.store
+ const b = s.block(blockId)
+ if (!b || s.readOnly || this.reading) return
+ this.closeOverlay()
+ const pop = el('div', 'sp-pop sp-tonepop')
+ pop.setAttribute('role', 'menu')
+ this.trapAndClose(pop, () => this.focusBlock(blockId))
+
+ const current = String(b.tone ?? 'note')
+ for (const tone of CALLOUT_TONES) {
+ const btn = document.createElement('button')
+ btn.className = 'sp-dditem sp-toneopt' + (tone.tone === current ? ' sp-sel' : '')
+ btn.type = 'button'
+ btn.setAttribute('role', 'menuitemradio')
+ btn.setAttribute('aria-checked', String(tone.tone === current))
+ btn.innerHTML =
+ `<span class="sp-result-ico sp-tone-${tone.tone}">${ICONS[tone.icon]}</span>` +
+ `<span class="sp-result-txt"><strong>${escapeHtml(toneLabel(tone.tone))}</strong></span>`
+ btn.addEventListener('click', () => {
+ this.closeOverlay()
+ s.commit(() => { const bb = s.block(blockId); if (bb) bb.tone = tone.tone })
+ this.paintPage()
+ })
+ pop.append(btn)
+ }
+
+ const row = el('label', 'sp-tonerow')
+ const icon = document.createElement('input')
+ icon.className = 'sp-find sp-toneicon'
+ icon.value = typeof b.icon === 'string' ? b.icon : ''
+ icon.maxLength = 16
+ icon.placeholder = t('Leave it empty to use the tone mark')
+ icon.setAttribute('aria-label', t('Callout icon'))
+ // `change`, not `input`: one commit when the field is done with, rather
+ // than one undo entry per keystroke of a pasted emoji
+ icon.addEventListener('change', () => {
+ const v = icon.value.trim()
+ s.commit(() => {
+ const bb = s.block(blockId)
+ if (!bb) return
+ if (v) bb.icon = v
+ else delete bb.icon
+ })
+ this.paintPage()
+ })
+ icon.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); icon.blur(); this.closeOverlay() }
+ })
+ row.append(el('span', 'sp-tonelabel', t('Icon')), icon)
+ pop.append(row)
+
+ 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
@@ -1276,6 +1764,223 @@ export class Editor {
return true
}
+ // ---- importing existing notes ---------------------------------------------
+ /**
+ * The way in.
+ *
+ * Two pickers rather than one, because a browser input is EITHER
+ * `multiple` files OR `webkitdirectory` — there is no control that offers
+ * both — and a folder is what a vault actually is. Dropping works for both
+ * and is the gesture most people reach for first, so it is stated here
+ * rather than left to be discovered.
+ */
+ openImport(): void {
+ this.openOverlay(t('Import Markdown'), (card, close) => {
+ card.append(el('h2', 'sp-card-h', t('Import Markdown')))
+
+ const what = document.createElement('p')
+ what.className = 'sp-note'
+ what.textContent = t('Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.')
+ card.append(what)
+
+ const zone = el('div', 'sp-dropzone', t('Drop .md files or a folder here'))
+ zone.addEventListener('dragover', (e) => { e.preventDefault(); zone.classList.add('sp-drop') })
+ zone.addEventListener('dragleave', () => zone.classList.remove('sp-drop'))
+ zone.addEventListener('drop', (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ zone.classList.remove('sp-drop')
+ const picked = collectDrop(e.dataTransfer)
+ close()
+ void picked.then((files) => this.importFiles(files))
+ })
+ card.append(zone)
+
+ const pick = (folder: boolean) => {
+ const input = document.createElement('input')
+ input.type = 'file'
+ input.multiple = true
+ if (folder) input.webkitdirectory = true
+ else input.accept = '.md,.markdown,.mdown,.mkd,image/*'
+ input.addEventListener('change', () => {
+ close()
+ // webkitRelativePath is the folder tree; a plain multi-select has
+ // none, and those files import as a flat set of pages
+ void this.importFiles([...(input.files ?? [])]
+ .map((file) => ({ path: file.webkitRelativePath || file.name, file })))
+ })
+ input.click()
+ }
+
+ const acts = el('div', 'sp-actions')
+ acts.append(
+ plainBtn(t('Choose .md files…'), () => pick(false), true),
+ plainBtn(t('Choose a folder…'), () => pick(true)),
+ )
+ card.append(acts)
+
+ const imgs = document.createElement('p')
+ imgs.className = 'sp-note'
+ // said BEFORE the import, because it is the one thing a browser cannot
+ // do for them: it has no way to open `../attachments/x.png` itself
+ imgs.textContent = t('Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.')
+ card.append(imgs)
+ })
+ }
+
+ /**
+ * Import, in ONE undoable step.
+ *
+ * Everything slow or asynchronous — reading files, decoding and re-encoding
+ * images, hashing them — happens BEFORE the commit, so the pages, the blocks
+ * and the asset references land in one synchronous mutation. The same reason
+ * `placeImage` is shaped this way: a half-applied import is not something a
+ * single ⌘Z could put back.
+ */
+ async importFiles(picked: PickedFile[]): Promise<void> {
+ const s = this.store
+ if (s.readOnly) { this.status(t('This file is open read-only')); return }
+ const notes = picked.filter((p) => NOTE_EXT.test(p.path))
+ if (!notes.length) { this.status(t('No Markdown files in that selection')); return }
+ if (notes.length > 500 &&
+ !confirm(t('That is {n} files — importing them all may take a moment. Continue?', { n: notes.length }))) return
+
+ this.status(t('Reading {n} file(s)…', { n: notes.length }))
+ let files: SourceFile[]
+ try {
+ files = await Promise.all(notes.map(async (p) => ({ path: p.path, text: await p.file.text() })))
+ } catch {
+ this.status(t('Those files could not be read'))
+ return
+ }
+
+ // pages this space already has, so an incremental import links INTO it
+ const existing = new Map<string, string>()
+ for (const page of s.doc.pages) {
+ const key = page.title.trim().toLowerCase()
+ if (key && !existing.has(key)) existing.set(key, page.id)
+ }
+ const plan = planImport(files, {
+ rootTitle: t('Imported notes'),
+ resolveExisting: (target) => existing.get(target),
+ })
+
+ // ---- images ------------------------------------------------------------
+ // A relative path in a .md file names a file on the author's disk, and a
+ // browser cannot open it — no filesystem access, and the space will be
+ // mailed away from that disk anyway. So it is resolved against what was
+ // ACTUALLY selected, and when that fails the reference becomes visible
+ // text instead of an <img> that can only ever be broken.
+ const media = new Map<string, File>()
+ const byName = new Map<string, File>()
+ for (const p of picked) {
+ if (NOTE_EXT.test(p.path)) continue
+ const key = normPath(p.path)
+ if (!media.has(key)) media.set(key, p.file)
+ const name = key.slice(key.lastIndexOf('/') + 1)
+ if (!byName.has(name)) byName.set(name, p.file)
+ }
+
+ let embedded = 0
+ let embeddedBytes = 0
+ let unresolved = 0
+ let declined = 0
+ let keepEmbedding = true
+ let asked = false
+ for (const img of plan.images) {
+ const ref = decodePath(img.ref)
+ const file = media.get(joinPath(img.dir, ref)) ?? byName.get(ref.slice(ref.lastIndexOf('/') + 1).toLowerCase())
+ if (file && keepEmbedding && embeddedBytes > IMPORT_IMAGE_BUDGET && !asked) {
+ asked = true
+ keepEmbedding = confirm(t(
+ 'The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?',
+ { size: humanBytes(embeddedBytes) },
+ ))
+ }
+ if (file && keepEmbedding) {
+ try {
+ const prepared = await prepareImage(file)
+ img.block.src = await internAsset(s.doc, prepared.dataUri)
+ if (prepared.w) { img.block.w = prepared.w; img.block.h = prepared.h }
+ if (!prepared.original) img.block.original = false
+ embedded++
+ embeddedBytes += prepared.dataUri.length
+ continue
+ } catch { /* not a decodable image — fall through and say so */ }
+ }
+ // the two ways to arrive here are different facts, and the report says
+ // which: we could not find/read it, or you asked us to stop
+ if (file && !keepEmbedding) declined++
+ else unresolved++
+ img.block.type = 'p'
+ delete img.block.src
+ delete img.block.alt
+ img.block.html = `<em>${escapeHtml(t('Image not imported'))}: </em><code>${escapeHtml(img.ref)}</code>`
+ }
+
+ // THE security gate. Everything above builds html from someone's files;
+ // this is the app's real policy, with a real parser, run once over every
+ // block before any of it reaches the document (see markdown.ts's header).
+ for (const page of plan.pages) {
+ for (const b of page.blocks) if (b.html) b.html = sanitizeInline(b.html)
+ }
+
+ s.commit(() => { s.doc.pages.push(...plan.pages) })
+ if (plan.pages[0]) s.goToPage(plan.pages[0].id)
+ this.repaint()
+ this.status(t('Imported'))
+
+ this.openOverlay(t('Import Markdown'), (card, close) => {
+ card.append(el('h2', 'sp-card-h', t('Imported')))
+ const lines: string[] = [
+ t('{pages} page(s) and {blocks} block(s) added from {files} file(s).',
+ { pages: plan.stats.pages, blocks: plan.stats.blocks, files: plan.stats.files }),
+ ]
+ if (plan.stats.linked || plan.stats.dangling) {
+ lines.push(t('{n} of {total} wikilink(s) resolved.',
+ { n: plan.stats.linked, total: plan.stats.linked + plan.stats.dangling }))
+ // two sentences, not one: "1 of 1 resolved, the rest are text" is a
+ // sentence about nothing
+ if (plan.stats.dangling) lines.push(t('The rest name notes that were not in the selection, and are left as text.'))
+ }
+ // A shared NAME is the one import outcome the reader cannot see for
+ // themselves: the links look fine and point at the wrong note.
+ if (plan.stats.duplicateNames) {
+ lines.push(t('{n} note name(s) appear more than once, so links naming them all went to the first.',
+ { n: plan.stats.duplicateNames }))
+ }
+ if (plan.stats.frontmatter) {
+ lines.push(t('{n} page(s) had frontmatter, kept verbatim in a folded block.', { n: plan.stats.frontmatter }))
+ }
+ if (plan.stats.tables) {
+ lines.push(t('{n} table(s) kept as text: there is no table block in this format yet.', { n: plan.stats.tables }))
+ }
+ if (embedded) lines.push(t('{n} image(s) embedded ({size}).', { n: embedded, size: humanBytes(embeddedBytes) }))
+ if (unresolved) {
+ lines.push(t('{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.', { n: unresolved }))
+ }
+ if (declined) {
+ lines.push(t('{n} image(s) were left as paths because embedding stopped there.', { n: declined }))
+ }
+ if (plan.stats.remoteImages) {
+ lines.push(t('{n} image(s) point at the web. Nothing loads until a reader asks.', { n: plan.stats.remoteImages }))
+ }
+ // "removes the pages", NOT "puts the space back exactly as it was".
+ // Measured: after ⌘Z the pages are byte-identical to before, but the
+ // image bytes stay — undo snapshots deliberately exclude `assets`
+ // (store.ts), and pruning them on undo would break REDO, which
+ // re-inserts blocks pointing at those very keys.
+ lines.push(t('⌘Z removes the imported pages again.'))
+ for (const line of lines) {
+ const p = document.createElement('p')
+ p.className = 'sp-note'
+ p.textContent = line
+ card.append(p)
+ }
+ card.append(plainBtn(t('Close'), close, true))
+ })
+ }
+
// ---- find and replace ----------------------------------------------------
/**
* ⌘F is OURS, not the browser's.
@@ -1419,7 +2124,11 @@ export class Editor {
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 }
+ // ANY fold, from the registry — not a `type === 'toggle'` test. The
+ // merge commit claimed containers were registry data; this one survived,
+ // latent only because toggle is the sole 'fold' today. A ⌘K or ⌘F hit
+ // inside the second fold type would land on a block nobody could see.
+ if (SPEC.get(owner.type)?.container === 'fold' && !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
@@ -1532,7 +2241,7 @@ export class Editor {
for (const page of pages) {
host.append(renderPage(page, s.doc, {
- editable: false, forceOpen: true,
+ editable: false, forceOpen: true, printing: true,
titleOf: (id) => s.index.page.get(id)?.title,
allowRemote: (src) => this.allowedRemote.has(src),
}))
@@ -1559,10 +2268,52 @@ export class Editor {
this.onSaveAs?.(suffix)
}
+ /** One About, one copy path — both entry points route through saveAs('copy'). */
+ private openAbout(): void {
+ openAbout({
+ store: this.store,
+ onRepaint: () => this.build(),
+ onSaveCopy: () => { void this.saveAs('copy') },
+ onImport: () => this.openImport(),
+ })
+ }
+
// ---- routing ------------------------------------------------------------
+ /**
+ * `#p/<page>` today, and `#p/<page>/<block>` tolerated for later.
+ *
+ * The allowlist in sanitize.ts already ADMITS the two-segment form (its
+ * pattern is `#p/`), so links of that shape can be written into a file right
+ * now — and this resolver silently did nothing with them: `index.page.has`
+ * failed on the whole string and the click did not even fall back to the
+ * page. Every block link written by any future build would be dead in every
+ * file saved before that build existed.
+ *
+ * Tolerance costs three lines and cannot be added later on the sender's
+ * behalf: sanitize.ts records why a NEW fragment form is a one-way hazard —
+ * an href written under a permissive build gets STRIPPED by a stricter one on
+ * the next edit that touches the block. So it is accepted now and addressed
+ * (scrolling to the block) whenever that ships.
+ *
+ * Prefer the WHOLE remainder as a page id: minted ids never contain a slash,
+ * but an author-supplied one may.
+ */
+ private resolveAnchor(hash: string): string | null {
+ const m = hash.match(/^#p\/(.+)$/)
+ if (!m) return null
+ const whole = m[1]
+ if (this.store.index.page.has(whole)) return whole
+ const cut = whole.lastIndexOf('/')
+ if (cut > 0) {
+ const page = whole.slice(0, cut)
+ if (this.store.index.page.has(page)) return page
+ }
+ return null
+ }
+
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 })
+ const id = this.resolveAnchor(location.hash)
+ if (id) this.store.goToPage(id, { push: false })
}
repaint(): void { this.paintTree(); this.paintPage() }
@@ -1590,6 +2341,103 @@ function iconBtn(name: IconName, label: string, onClick: () => void): HTMLButton
const escapeHtml = (s: string): string =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
+/** Type text at the caret, through the engine, so the caret and `input` follow. */
+const insertText = (s: string): void => { document.execCommand('insertText', false, s) }
+
+/** Where the caret is inside a host, as a character offset. Null if it is not. */
+function caretIndexIn(host: HTMLElement): number | null {
+ const sel = getSelection()
+ if (!sel || !sel.rangeCount) return null
+ const r = sel.getRangeAt(0)
+ if (!r.collapsed || !host.contains(r.startContainer)) return null
+ const probe = r.cloneRange()
+ probe.selectNodeContents(host)
+ probe.setEnd(r.startContainer, r.startOffset)
+ return probe.toString().length
+}
+
+function plainBtn(label: string, onClick: () => void, primary = false): HTMLButtonElement {
+ const b = document.createElement('button')
+ b.className = 'sp-btn' + (primary ? ' sp-primary' : '')
+ b.type = 'button'
+ b.textContent = label
+ b.addEventListener('click', onClick)
+ return b
+}
+
+// ---- dropped files ----------------------------------------------------------
+
+const normPath = (p: string): string =>
+ p.replace(/\\/g, '/').replace(/^\.?\//, '').replace(/\/+/g, '/').toLowerCase()
+
+/** `dir` + a relative reference, with `..` and `.` collapsed. Lowercased: the
+ * case in a markdown link and the case on disk disagree often enough that
+ * matching exactly would fail for reasons nobody could see. */
+function joinPath(dir: string, ref: string): string {
+ const parts = (ref.startsWith('/') ? ref.slice(1) : `${dir}/${ref}`).split('/')
+ const out: string[] = []
+ for (const seg of parts) {
+ if (!seg || seg === '.') continue
+ if (seg === '..') out.pop()
+ else out.push(seg)
+ }
+ return out.join('/').toLowerCase()
+}
+
+/** `my%20photo.png` is one file name, not two — editors percent-encode spaces. */
+function decodePath(ref: string): string {
+ try { return decodeURI(ref) } catch { return ref }
+}
+
+/**
+ * Everything under a drop, including whole folders.
+ *
+ * `dataTransfer.items` is EMPTIED the moment this handler yields, so every
+ * entry is taken synchronously and only then walked. `dataTransfer.files`
+ * carries a dropped folder as one nameless entry, which is why the entry API
+ * is used at all: without it, dragging a vault onto the window does nothing.
+ */
+async function collectDrop(dt: DataTransfer | null): Promise<PickedFile[]> {
+ if (!dt) return []
+ const entries = [...dt.items].map((i) => i.webkitGetAsEntry?.() ?? null).filter(Boolean) as FileSystemEntry[]
+ // the fallback takes its path the same way the picker does, so the two
+ // routes into importFiles cannot disagree about where a path comes from
+ if (!entries.length) return [...dt.files].map((file) => ({ path: file.webkitRelativePath || file.name, file }))
+ const out: PickedFile[] = []
+ for (const entry of entries) await walkEntry(entry, '', out, 0)
+ return out
+}
+
+async function walkEntry(entry: FileSystemEntry, base: string, out: PickedFile[], depth: number): Promise<void> {
+ // .obsidian, .git, .trash: configuration and deleted notes, never the notes
+ // someone means to import
+ if (entry.name.startsWith('.')) return
+ const path = base ? `${base}/${entry.name}` : entry.name
+ if (entry.isFile) {
+ const file = await new Promise<File | null>((res) =>
+ (entry as FileSystemFileEntry).file(res, () => res(null)))
+ if (file) out.push({ path, file })
+ return
+ }
+ if (depth > 12) return // a symlink loop is not worth hanging the tab for
+ const reader = (entry as FileSystemDirectoryEntry).createReader()
+ for (;;) {
+ // readEntries hands back at most 100 at a time and signals the end with an
+ // empty batch — reading it once silently truncates a folder of 300 notes
+ const batch = await new Promise<FileSystemEntry[]>((res) =>
+ reader.readEntries(res, () => res([])))
+ if (!batch.length) break
+ for (const child of batch) await walkEntry(child, path, out, depth + 1)
+ }
+}
+
+/** Is this drop an IMPORT (markdown, or any folder) rather than an image? */
+function isImportDrop(dt: DataTransfer | null): boolean {
+ if (!dt) return false
+ if ([...dt.files].some((f) => NOTE_EXT.test(f.name))) return true
+ return [...dt.items].some((i) => i.webkitGetAsEntry?.()?.isDirectory)
+}
+
function atStart(host: HTMLElement): boolean {
const sel = getSelection()
if (!sel || !sel.rangeCount) return false
@@ -1688,7 +2536,12 @@ function place(pop: HTMLElement, anchor: HTMLElement | DOMRect): void {
*/
export function pageIcon(icon: string | undefined): string {
if (!icon) return ICONS.page
- if (icon in ICONS) return ICONS[icon as IconName]
+ // hasOwn, not `in`: `'toString' in ICONS` is TRUE and resolves to a
+ // FUNCTION, so an icon name of "toString" or "constructor" in a mailed file
+ // returned native source text and skipped the escape below. Not markup, so
+ // not an injection — but it is author-supplied data reaching the page
+ // unescaped, and the next lookup table indexed this way might not be so lucky.
+ if (Object.hasOwn(ICONS, icon)) return ICONS[icon as IconName]
return escapeHtml(icon) // an emoji, or anything else the file carried
}
diff --git a/spaces/src/highlight.ts b/spaces/src/highlight.ts
new file mode 100644
index 00000000..9bee1768
--- /dev/null
+++ b/spaces/src/highlight.ts
@@ -0,0 +1,408 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Syntax highlighting for `code` blocks — ours, because nobody's fits.
+//
+// SIZE IS THE DESIGN. highlight.js is ~120KB and the useful subset of Prism is
+// ~30KB; the whole spaces shell was 72KB compressed. Either library would be
+// the largest thing in the product, in a format whose entire premise is that
+// you can mail the file. So this is a small lexer covering the languages people
+// actually paste into notes, and everything else degrades to plain text.
+//
+// MEASURED on the built shell: the lexer, the painter, the chip and the colours
+// together cost 4.0KB compressed, and ALL EIGHT vocabularies together cost a
+// further 1.4KB — about 180 bytes per language, because keyword lists are
+// lowercase ascii and deflate eats them. So the expensive part is the machinery
+// and the languages are nearly free, which is the opposite of the intuition
+// that says "support fewer languages to save space".
+//
+// THE OUTPUT IS OFFSETS, NEVER STRINGS. A token is `{k, a, b}` — a kind and a
+// half-open range into the caller's text. `tokenize` is TOTAL: the tokens
+// partition [0, text.length) exactly, in order, with no gaps and no overlap.
+// That is not tidiness, it is the security property. Code in a space is text
+// someone mailed you; a highlighter that cannot produce a string cannot produce
+// markup, whatever the input does. `scripts/test-spaces-model.ts` asserts the
+// partition over a hostile corpus, in every language, and the renderer builds
+// nodes with `createTextNode` from those ranges.
+//
+// WHICH LANGUAGES, AND WHY THESE. The set is what a working notebook actually
+// accumulates — shell one-liners, a config file, a snippet from the codebase —
+// not a survey of programming languages:
+//
+// js/ts the most-pasted family, and this codebase's own
+// py the other one
+// sh every notes app is half terminal commands
+// json configs, API responses, and it is nearly free given the lexer
+// yaml CI files and manifests, the other config people paste
+// sql queries are exactly the thing you keep notes about
+// html including xml/svg — its own scanner, tags are not tokens
+// css the last of the everyday web three
+//
+// The C-family scanner below is parameterised, so a new curly-brace language is
+// one keyword list (~150 bytes). Resist adding them anyway: a language nobody
+// tested renders *nearly* right, which is worse than the plain fallback, and
+// the fallback is designed to look deliberate rather than broken.
+//
+// WHAT IT DELIBERATELY DOES NOT DO: no semantic anything (a type is not a
+// keyword), no nested grammars (js inside `<script>`, interpolation inside a
+// template literal or an f-string, code inside a YAML block scalar — all stay
+// one token), no HTML entities. Each of those costs bytes to get right and
+// nothing to get wrong.
+
+export type Kind =
+ | '' // plain
+ | 'c' // comment
+ | 's' // string
+ | 'n' // number, and css hex colours
+ | 'k' // keyword, and markup tags
+ | 'l' // literal / builtin, and shell variables
+ | 'p' // property: object key, attribute name, css property
+
+export interface Token { k: Kind; a: number; b: number }
+
+interface Lang {
+ label: string
+ /** line-comment openers */
+ lc?: string[]
+ /** block comment, open and close */
+ bc?: [string, string]
+ /** characters that open a string */
+ q?: string
+ /** python ''' and """ */
+ triple?: boolean
+ /** `'` strings take no backslash escapes; a doubled `''` stays inside */
+ rawSq?: boolean
+ /** keywords, space separated */
+ kw?: string
+ /** literals and builtins, space separated */
+ lit?: string
+ /** keywords match without regard to case (SQL) */
+ ci?: boolean
+ /** a word or string followed by `:` is a property */
+ keys?: boolean
+ /** `$NAME` and `${…}` */
+ vars?: boolean
+ /** `-` is a word character (css properties, yaml keys) */
+ dash?: boolean
+ /** `@name` is a keyword (css at-rules, python decorators) */
+ at?: boolean
+ /** `#rrggbb` is a colour, so a number */
+ hex?: boolean
+ /** tags and attributes, not words and punctuation */
+ markup?: boolean
+ /** built on first use — the catalogs ship as strings so deflate can see them */
+ kset?: Set<string>
+ lset?: Set<string>
+}
+
+const JS_KW =
+ 'as async await break case catch class const continue debugger declare default delete do else enum ' +
+ 'export extends finally for from function get if implements import in infer instanceof interface is ' +
+ 'keyof let namespace new of private protected public readonly return satisfies set static super ' +
+ 'switch this throw try type typeof var void while with yield'
+
+const LANGS: Record<string, Lang> = {
+ js: {
+ label: 'JavaScript',
+ lc: ['//'], bc: ['/*', '*/'], q: '\'"`',
+ kw: JS_KW,
+ lit: 'true false null undefined NaN Infinity console document window globalThis process require ' +
+ 'module exports Promise Array Object String Number Boolean Math JSON Symbol Map Set WeakMap Error ' +
+ 'RegExp Date parseInt parseFloat setTimeout setInterval fetch',
+ },
+ ts: {
+ label: 'TypeScript',
+ lc: ['//'], bc: ['/*', '*/'], q: '\'"`',
+ kw: JS_KW + ' abstract override unique asserts',
+ lit: 'true false null undefined NaN Infinity console document window globalThis process require ' +
+ 'module exports Promise Array Object String Number Boolean Math JSON Symbol Map Set Error ' +
+ 'string number boolean any unknown never object symbol bigint',
+ },
+ py: {
+ label: 'Python',
+ lc: ['#'], q: '\'"', triple: true, at: true,
+ kw: 'and as assert async await break class continue def del elif else except finally for from ' +
+ 'global if import in is lambda nonlocal not or pass raise return try while with yield match case',
+ lit: 'True False None self cls print len range str int float bool bytes list dict set tuple open ' +
+ 'type super isinstance issubclass enumerate zip map filter sum min max abs round sorted reversed ' +
+ 'repr format input __init__ __name__ __main__',
+ },
+ sh: {
+ label: 'Shell',
+ lc: ['#'], q: '\'"', rawSq: true, vars: true,
+ kw: 'if then else elif fi for while until do done case esac in function return select break ' +
+ 'continue local export declare readonly',
+ lit: 'echo cd pwd ls cp mv rm mkdir rmdir touch cat head tail grep sed awk find xargs sort uniq wc ' +
+ 'chmod chown ln df du ps kill sudo set unset read source alias exit eval exec trap wait shift ' +
+ 'test printf true false git npm node curl docker make ssh tar',
+ },
+ json: {
+ label: 'JSON',
+ q: '"', keys: true,
+ lit: 'true false null',
+ },
+ yaml: {
+ label: 'YAML',
+ lc: ['#'], q: '\'"', rawSq: true, keys: true, dash: true,
+ lit: 'true false null yes no on off True False Null',
+ },
+ sql: {
+ label: 'SQL',
+ lc: ['--'], bc: ['/*', '*/'], q: '\'"', rawSq: true, ci: true,
+ kw: 'select from where group by order having limit offset insert into values update set delete ' +
+ 'create table view materialized index drop alter add column primary key foreign references ' +
+ 'unique check not null default join inner left right full outer cross on using as union all ' +
+ 'except intersect distinct case when then else end and or in like ilike between exists is asc ' +
+ 'desc with recursive returning constraint cascade begin commit rollback transaction grant ' +
+ 'revoke explain analyze if temporary replace',
+ lit: 'int integer bigint smallint serial bigserial text varchar char boolean bool date timestamp ' +
+ 'timestamptz time interval numeric decimal real double precision float json jsonb uuid bytea ' +
+ 'array enum true false null count sum avg min max coalesce nullif greatest least now ' +
+ 'current_timestamp current_date extract cast substring length lower upper trim',
+ },
+ css: {
+ label: 'CSS',
+ bc: ['/*', '*/'], q: '\'"', keys: true, dash: true, at: true, hex: true,
+ kw: 'important',
+ lit: 'inherit initial revert unset none auto currentColor transparent var calc url rgb rgba hsl ' +
+ 'hsla min max clamp',
+ },
+ html: { label: 'HTML', markup: true },
+}
+
+/**
+ * What a reader can pick, in the order the picker shows them. Plain text is
+ * first because it is the default, and because "no highlighting" has to look
+ * like a choice rather than a failure.
+ */
+export const CODE_LANGS: ReadonlyArray<{ id: string; label: string }> =
+ ['', ...Object.keys(LANGS)].map((id) => ({ id, label: id ? LANGS[id].label : '' }))
+
+/**
+ * Aliases people actually write in a fence. Everything unlisted falls through
+ * to plain — including a language we could nearly render, which is the point:
+ * `lang` is preserved in the model either way, so a later build can light it up
+ * without anyone re-tagging their blocks.
+ */
+const ALIAS: Record<string, string> = {
+ javascript: 'js', jsx: 'js', mjs: 'js', cjs: 'js', node: 'js',
+ typescript: 'ts', tsx: 'ts',
+ python: 'py', python3: 'py', py3: 'py',
+ bash: 'sh', zsh: 'sh', shell: 'sh', console: 'sh', terminal: 'sh', ksh: 'sh',
+ yml: 'yaml',
+ postgres: 'sql', postgresql: 'sql', psql: 'sql', mysql: 'sql', sqlite: 'sql',
+ xml: 'html', svg: 'html', xhtml: 'html', htm: 'html',
+}
+
+/** The language id this build will actually highlight with, or '' for plain. */
+export function normLang(lang: unknown): string {
+ if (typeof lang !== 'string') return ''
+ const k = lang.trim().toLowerCase().replace(/^\./, '')
+ const id = ALIAS[k] ?? k
+ return id in LANGS ? id : ''
+}
+
+/** The chip's label: a known language's name, or whatever the file said. */
+export function langLabel(lang: unknown): string {
+ const id = normLang(lang)
+ if (id) return LANGS[id].label
+ return typeof lang === 'string' ? lang.trim() : ''
+}
+
+const WORD = /[A-Za-z_$]/
+const WORDC = /[\w$]/
+const DIGIT = /[0-9]/
+const HEX = /^[0-9a-fA-F]+$/
+const NAMEC = /[\w:.-]/
+
+const words = (s: string | undefined): Set<string> => new Set(s ? s.split(' ') : [])
+
+export function tokenize(text: string, lang?: unknown): Token[] {
+ const out: Token[] = []
+ const n = text.length
+ if (!n) return out
+
+ /** Adjacent runs of the same kind coalesce, so plain text is one node. */
+ const push = (k: Kind, a: number, b: number): void => {
+ if (b <= a) return
+ const last = out[out.length - 1]
+ if (last && last.k === k && last.b === a) last.b = b
+ else out.push({ k, a, b })
+ }
+
+ const L = LANGS[normLang(lang)]
+ if (!L) { push('', 0, n); return out }
+ if (L.markup) { scanMarkup(text, push); return out }
+
+ if (!L.kset) { L.kset = words(L.kw); L.lset = words(L.lit) }
+ const kset = L.kset
+ const lset = L.lset!
+
+ /** Is the next non-blank character a `:`? Then that word was a key. */
+ const keyAhead = (j: number): boolean => {
+ while (j < n && (text[j] === ' ' || text[j] === '\t')) j++
+ return text[j] === ':'
+ }
+
+ let i = 0
+ while (i < n) {
+ const c = text[i]
+
+ // block comment — first, so `/*` never reads as an operator
+ if (L.bc && text.startsWith(L.bc[0], i)) {
+ const e = text.indexOf(L.bc[1], i + L.bc[0].length)
+ const end = e < 0 ? n : e + L.bc[1].length // unterminated runs to EOF
+ push('c', i, end); i = end; continue
+ }
+
+ if (L.lc) {
+ let hit = false
+ for (const op of L.lc) {
+ if (!text.startsWith(op, i)) continue
+ // `#` only opens a comment at the start of a word. Otherwise every URL
+ // fragment in a shell script — `curl host/x#frag` — eats its line.
+ if (op === '#' && i > 0 && /[\w$/.\-"']/.test(text[i - 1])) continue
+ hit = true; break
+ }
+ if (hit) {
+ let e = text.indexOf('\n', i)
+ if (e < 0) e = n
+ push('c', i, e); i = e; continue
+ }
+ }
+
+ // shell variables, before the word rule — `$` is a word character in js
+ if (L.vars && c === '$') {
+ let j = i + 1
+ if (text[j] === '{') { const e = text.indexOf('}', j); j = e < 0 ? n : e + 1 }
+ else if (text[j] === '(') { j += 1 }
+ else while (j < n && WORDC.test(text[j])) j++
+ push(j > i + 1 ? 'l' : '', i, Math.max(j, i + 1)); i = Math.max(j, i + 1); continue
+ }
+
+ if (L.at && c === '@') {
+ let j = i + 1
+ while (j < n && WORDC.test(text[j])) j++
+ push(j > i + 1 ? 'k' : '', i, Math.max(j, i + 1)); i = Math.max(j, i + 1); continue
+ }
+
+ // a css colour. `#main` is not hex, so a selector stays plain.
+ if (L.hex && c === '#') {
+ let j = i + 1
+ while (j < n && WORDC.test(text[j])) j++
+ if (j > i + 1 && HEX.test(text.slice(i + 1, j))) { push('n', i, j); i = j; continue }
+ }
+
+ if (L.q && L.q.includes(c)) {
+ const end = scanString(text, i, c, L)
+ // in a keyed language a quoted key is a key, not a value: JSON is
+ // otherwise a wall of one colour
+ push(L.keys && keyAhead(end) ? 'p' : 's', i, end)
+ i = end; continue
+ }
+
+ if (DIGIT.test(c) || (c === '.' && DIGIT.test(text[i + 1] ?? ''))) {
+ let j = i + 1
+ // `[\w.]` swallows the unit in `10px` and the radix in `0xff`, which is
+ // what you want to see; `1e-9` needs the sign after an exponent
+ while (j < n && (/[\w.]/.test(text[j]) || (/[eE]/.test(text[j - 1]) && /[+-]/.test(text[j])))) j++
+ push('n', i, j); i = j; continue
+ }
+
+ if (WORD.test(c) || (L.dash && c === '-')) {
+ let j = i + 1
+ while (j < n && (WORDC.test(text[j]) || (L.dash && text[j] === '-'))) j++
+ const w = text.slice(i, j)
+ const key = L.ci ? w.toLowerCase() : w
+ let k: Kind = ''
+ if (L.keys && keyAhead(j)) k = 'p'
+ else if (kset.has(key)) k = 'k'
+ else if (lset.has(key)) k = 'l'
+ push(k, i, j); i = j; continue
+ }
+
+ push('', i, i + 1); i++
+ }
+ return out
+}
+
+/**
+ * A string, from its opening quote to just past its closing one.
+ *
+ * An UNTERMINATED string ends at the newline, not at end-of-file, in every
+ * language whose strings are single-line. Half-written code is the normal state
+ * of a code block in a notes app, and running one stray quote to the bottom of
+ * the block turns the rest of it green while you type.
+ */
+function scanString(text: string, i: number, q: string, L: Lang): number {
+ const n = text.length
+ if (L.triple && text.startsWith(q + q + q, i)) {
+ const e = text.indexOf(q + q + q, i + 3)
+ return e < 0 ? n : e + 3
+ }
+ const raw = L.rawSq && q === '\''
+ const multi = q === '`' || raw
+ let j = i + 1
+ while (j < n) {
+ const d = text[j]
+ if (d === '\\' && !raw) { j += 2; continue }
+ if (d === q) {
+ // `''` inside a raw single-quoted string is an escaped quote (SQL)
+ if (raw && text[j + 1] === q) { j += 2; continue }
+ return j + 1
+ }
+ if (d === '\n' && !multi) return j
+ j++
+ }
+ return n
+}
+
+/**
+ * Markup is not words and punctuation, so it gets its own scanner: text is
+ * text, and only what is inside `<…>` has structure. Tag name and its angle
+ * bracket are one token — colouring the bracket separately reads as noise at
+ * 13px.
+ */
+function scanMarkup(text: string, push: (k: Kind, a: number, b: number) => void): void {
+ const n = text.length
+ let i = 0
+ while (i < n) {
+ const lt = text.indexOf('<', i)
+ if (lt < 0) { push('', i, n); return }
+ push('', i, lt)
+
+ if (text.startsWith('<!--', lt)) {
+ const e = text.indexOf('-->', lt)
+ const end = e < 0 ? n : e + 3
+ push('c', lt, end); i = end; continue
+ }
+ if (text[lt + 1] === '!' || text[lt + 1] === '?') { // doctype, xml decl
+ const e = text.indexOf('>', lt)
+ const end = e < 0 ? n : e + 1
+ push('c', lt, end); i = end; continue
+ }
+
+ let j = lt + 1
+ if (text[j] === '/') j++
+ const nameAt = j
+ while (j < n && NAMEC.test(text[j])) j++
+ if (j === nameAt) { push('', lt, lt + 1); i = lt + 1; continue } // a bare `<`
+ push('k', lt, j)
+
+ while (j < n && text[j] !== '>') {
+ const c = text[j]
+ if (c === '"' || c === '\'') {
+ const e = text.indexOf(c, j + 1)
+ const end = e < 0 ? n : e + 1
+ push('s', j, end); j = end; continue
+ }
+ if (NAMEC.test(c)) {
+ let e = j
+ while (e < n && NAMEC.test(text[e])) e++
+ push('p', j, e); j = e; continue
+ }
+ push('', j, j + 1); j++
+ }
+ if (j < n) { push('k', j, j + 1); j++ } // the closing `>`
+ i = j
+ }
+}
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index aaf8e97d..50255490 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -23,6 +23,9 @@ export const de: Catalog = {
"Archived ({n})": "Archiviert ({n})",
"Block options": "Block-Optionen",
"Breadcrumb": "Pfadnavigation",
+ "Callout icon": "Symbol des Hinweisfelds",
+ "Caution": "Achtung",
+ "Change the kind of callout": "Art des Hinweisfelds ändern",
"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.",
@@ -55,14 +58,18 @@ export const de: Catalog = {
"Find": "Suchen",
"Find in this space…": "In diesem Space suchen…",
"Find or create a page…": "Seite finden oder erstellen…",
+ "Icon": "Symbol",
"Image added ({size})": "Bild hinzugefügt ({size})",
"Image added, resized to fit ({from} → {to})": "Bild hinzugefügt, passend verkleinert ({from} → {to})",
+ "Important": "Wichtig",
"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 — what this block is highlighted as": "Sprache — wie dieser Block hervorgehoben wird",
"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.",
+ "Leave it empty to use the tone mark": "Leer lassen, um das Symbol der Art zu verwenden",
"Link to page": "Seite verlinken",
"Linked from": "Verlinkt von",
"Links to it become dead": "Links darauf laufen ins Leere",
@@ -71,6 +78,7 @@ export const de: Catalog = {
"Next (⏎)": "Weiter (⏎)",
"No block matches": "Kein Block passt",
"No pages yet": "Noch keine Seiten",
+ "Note": "Hinweis",
"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",
@@ -82,6 +90,7 @@ export const de: Catalog = {
"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…",
+ "Plain text": "Nur Text",
"Previous (⇧⏎)": "Zurück (⇧⏎)",
"Print": "Drucken",
"Print / PDF…": "Drucken / PDF…",
@@ -134,6 +143,7 @@ export const de: Catalog = {
"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",
+ "Tip": "Tipp",
"Type / for blocks, [[ to link a page": "Tippe / für Blöcke, [[ für einen Seitenlink",
"Undo (⌘Z)": "Rückgängig (⌘Z)",
"Unlock": "Entsperren",
@@ -143,6 +153,7 @@ export const de: Catalog = {
"Update this file": "Diese Datei aktualisieren",
"Updates": "Updates",
"Version {v} is available.": "Version {v} ist verfügbar.",
+ "Warning": "Warnung",
"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}).",
@@ -158,4 +169,51 @@ export const de: Catalog = {
"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",
+ "New page": "Neue Seite",
+ "Redo": "Wiederholen",
+ "Reading view": "Leseansicht",
+ "The pages without the editing tools": "Die Seiten ohne die Bearbeitungswerkzeuge",
+ "Version, language, password, exports": "Version, Sprache, Passwort, Export",
+ "More": "Mehr",
+ "Copy saved — you are still editing the original": "Kopie gespeichert — du bearbeitest weiterhin das Original",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "Dies ist eine Lesekopie. Sie öffnet sich zum Lesen; nichts, was du hier tust, ändert die Datei.",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "Ein Ordner voller .md-Dateien wird zu Seiten — samt Ordnerbaum und den [[Wikilinks]] dazwischen.",
+ "Bring notes in": "Notizen hereinholen",
+ "Choose .md files…": ".md-Dateien wählen…",
+ "Choose a folder…": "Ordner wählen…",
+ "Drop .md files or a folder here": ".md-Dateien oder einen Ordner hierher ziehen",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "Jede .md-Datei wird eine Seite, Ordner werden zum Seitenbaum, [[Wikilinks]] werden echte Links. Seiten kommen hinzu — nichts hier wird ersetzt.",
+ "Image not imported": "Bild nicht importiert",
+ "Import Markdown": "Markdown importieren",
+ "Import Markdown files or a folder…": "Markdown-Dateien oder einen Ordner importieren…",
+ "Import Markdown…": "Markdown importieren…",
+ "Imported": "Importiert",
+ "Imported notes": "Importierte Notizen",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "Nimm die Bilddateien mit, dann werden sie gleich eingebettet. Ein Bild, das dieser Browser nicht öffnen kann, bleibt als Pfad stehen statt als kaputtes Bild.",
+ "No Markdown files in that selection": "Keine Markdown-Dateien in dieser Auswahl",
+ "Reading {n} file(s)…": "Lese {n} Datei(en)…",
+ "That is {n} files — importing them all may take a moment. Continue?": "Das sind {n} Dateien — der Import kann einen Moment dauern. Fortfahren?",
+ "This file is open read-only": "Diese Datei ist schreibgeschützt geöffnet",
+ "Those files could not be read": "Diese Dateien konnten nicht gelesen werden",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} Bild(er) ließen sich nicht öffnen; ihre Pfade bleiben als Text. Importiere noch einmal, diesmal mit den Bilddateien.",
+ "{n} image(s) embedded ({size}).": "{n} Bild(er) eingebettet ({size}).",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} Bild(er) zeigen ins Web. Nichts wird geladen, bevor ein Leser darum bittet.",
+ "{n} of {total} wikilink(s) resolved.": "{n} von {total} Wikilink(s) aufgelöst.",
+ "The rest name notes that were not in the selection, and are left as text.": "Der Rest nennt Notizen, die nicht in der Auswahl waren, und bleibt als Text stehen.",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} Seite(n) hatten Frontmatter — wortgetreu in einem zugeklappten Block erhalten.",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} Tabelle(n) als Text übernommen: Dieses Format hat noch keinen Tabellenblock.",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{pages} Seite(n) und {blocks} Block/Blöcke aus {files} Datei(en) hinzugefügt.",
+ "⌘Z removes the imported pages again.": "Mit ⌘Z verschwinden die importierten Seiten wieder.",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "Die Bilder in diesen Notizen ergeben bisher {size}, und sie reisen alle in der Datei mit. Weiter einbetten?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} Bild(er) blieben als Pfad stehen, weil das Einbetten dort endete.",
+ "About bento/spaces — version, updates, language, password": "Über bento/spaces — Version, Updates, Sprache, Passwort",
+ "Unsaved changes — ⌘S rewrites this file": "Ungespeicherte Änderungen — ⌘S schreibt diese Datei neu",
+ "Unsaved changes — ⌘S downloads an updated copy": "Ungespeicherte Änderungen — ⌘S lädt eine aktualisierte Kopie herunter",
+ "format v{v}": "Format v{v}",
+ "Visit bento.page (opens in a new tab)": "bento.page besuchen (öffnet in neuem Tab)",
+ "Drag to resize · double-click to reset": "Ziehen zum Anpassen · Doppelklick setzt zurück",
+ "Show the page list ([)": "Seitenliste einblenden ([)",
+ "Hide the page list ([)": "Seitenliste ausblenden ([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} Notiznamen kommen mehrfach vor — Links mit diesem Namen führen alle zur ersten.",
}
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index 82420c1c..e664411d 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -23,6 +23,9 @@ export const es: Catalog = {
"Archived ({n})": "Archivadas ({n})",
"Block options": "Opciones del bloque",
"Breadcrumb": "Ruta de navegación",
+ "Callout icon": "Icono del aviso",
+ "Caution": "Precaución",
+ "Change the kind of callout": "Cambiar el tipo de aviso",
"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.",
@@ -55,14 +58,18 @@ export const es: Catalog = {
"Find": "Buscar",
"Find in this space…": "Buscar en este espacio…",
"Find or create a page…": "Buscar o crear una página…",
+ "Icon": "Icono",
"Image added ({size})": "Imagen añadida ({size})",
"Image added, resized to fit ({from} → {to})": "Imagen añadida, redimensionada para que quepa ({from} → {to})",
+ "Important": "Importante",
"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 — what this block is highlighted as": "Lenguaje — cómo se colorea este bloque",
"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.",
+ "Leave it empty to use the tone mark": "Déjalo vacío para usar el símbolo del tipo",
"Link to page": "Enlazar a una página",
"Linked from": "Enlazado desde",
"Links to it become dead": "Los enlaces a ella dejan de funcionar",
@@ -71,6 +78,7 @@ export const es: Catalog = {
"Next (⏎)": "Siguiente (⏎)",
"No block matches": "Ningún bloque coincide",
"No pages yet": "Aún no hay páginas",
+ "Note": "Nota",
"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",
@@ -82,6 +90,7 @@ export const es: Catalog = {
"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…",
+ "Plain text": "Texto sin formato",
"Previous (⇧⏎)": "Anterior (⇧⏎)",
"Print": "Imprimir",
"Print / PDF…": "Imprimir / PDF…",
@@ -134,6 +143,7 @@ export const es: Catalog = {
"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",
+ "Tip": "Consejo",
"Type / for blocks, [[ to link a page": "Escribe / para bloques, [[ para enlazar una página",
"Undo (⌘Z)": "Deshacer (⌘Z)",
"Unlock": "Desbloquear",
@@ -143,6 +153,7 @@ export const es: Catalog = {
"Update this file": "Actualizar este archivo",
"Updates": "Actualizaciones",
"Version {v} is available.": "Versión {v} disponible.",
+ "Warning": "Advertencia",
"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}).",
@@ -158,4 +169,51 @@ export const es: Catalog = {
"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",
+ "New page": "Nueva página",
+ "Redo": "Rehacer",
+ "Reading view": "Vista de lectura",
+ "The pages without the editing tools": "Las páginas sin las herramientas de edición",
+ "Version, language, password, exports": "Versión, idioma, contraseña, exportaciones",
+ "More": "Más",
+ "Copy saved — you are still editing the original": "Copia guardada: sigues editando el original",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "Esta es una copia de lectura. Se abre para leer; nada de lo que hagas aquí cambia el archivo.",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "Una carpeta de archivos .md se convierte en páginas, con el árbol de carpetas y los [[wikilinks]] intactos.",
+ "Bring notes in": "Traer notas",
+ "Choose .md files…": "Elegir archivos .md…",
+ "Choose a folder…": "Elegir una carpeta…",
+ "Drop .md files or a folder here": "Suelta aquí archivos .md o una carpeta",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "Cada archivo .md se convierte en una página, las carpetas forman el árbol de páginas y los [[wikilinks]] se vuelven enlaces reales. Las páginas se añaden: aquí no se reemplaza nada.",
+ "Image not imported": "Imagen no importada",
+ "Import Markdown": "Importar Markdown",
+ "Import Markdown files or a folder…": "Importar archivos Markdown o una carpeta…",
+ "Import Markdown…": "Importar Markdown…",
+ "Imported": "Importado",
+ "Imported notes": "Notas importadas",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "Incluye los archivos de imagen y también se incrustan. Una imagen que este navegador no puede abrir se conserva como su ruta, no como una imagen rota.",
+ "No Markdown files in that selection": "No hay archivos Markdown en esa selección",
+ "Reading {n} file(s)…": "Leyendo {n} archivo(s)…",
+ "That is {n} files — importing them all may take a moment. Continue?": "Son {n} archivos: importarlos todos puede tardar un momento. ¿Continuar?",
+ "This file is open read-only": "Este archivo está abierto en solo lectura",
+ "Those files could not be read": "No se pudieron leer esos archivos",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} imagen(es) no se pudieron abrir, así que sus rutas quedan como texto. Vuelve a importar incluyendo los archivos de imagen.",
+ "{n} image(s) embedded ({size}).": "{n} imagen(es) incrustada(s) ({size}).",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} imagen(es) apuntan a la web. No se carga nada hasta que un lector lo pida.",
+ "{n} of {total} wikilink(s) resolved.": "{n} de {total} wikilink(s) resueltos.",
+ "The rest name notes that were not in the selection, and are left as text.": "El resto nombra notas que no estaban en la selección y se dejan como texto.",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} página(s) tenían frontmatter, conservado tal cual en un bloque plegado.",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabla(s) conservadas como texto: este formato aún no tiene bloque de tabla.",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{pages} página(s) y {blocks} bloque(s) añadidos desde {files} archivo(s).",
+ "⌘Z removes the imported pages again.": "⌘Z vuelve a quitar las páginas importadas.",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "Las imágenes de estas notas suman ya {size} y todas viajan dentro del archivo. ¿Seguir incrustándolas?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} imagen(es) quedaron como rutas porque la incrustación se detuvo ahí.",
+ "About bento/spaces — version, updates, language, password": "Acerca de bento/spaces: versión, actualizaciones, idioma, contraseña",
+ "Unsaved changes — ⌘S rewrites this file": "Cambios sin guardar: ⌘S reescribe este archivo",
+ "Unsaved changes — ⌘S downloads an updated copy": "Cambios sin guardar: ⌘S descarga una copia actualizada",
+ "format v{v}": "formato v{v}",
+ "Visit bento.page (opens in a new tab)": "Visitar bento.page (se abre en una pestaña nueva)",
+ "Drag to resize · double-click to reset": "Arrastra para redimensionar · doble clic para restablecer",
+ "Show the page list ([)": "Mostrar la lista de páginas ([)",
+ "Hide the page list ([)": "Ocultar la lista de páginas ([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} nombre(s) de nota se repiten, así que los enlaces con ese nombre fueron todos al primero.",
}
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index c140f3fe..084c881a 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -23,6 +23,9 @@ export const fr: Catalog = {
"Archived ({n})": "Archivées ({n})",
"Block options": "Options du bloc",
"Breadcrumb": "Fil d’Ariane",
+ "Callout icon": "Icône de l'encadré",
+ "Caution": "Attention",
+ "Change the kind of callout": "Changer le type d'encadré",
"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.",
@@ -55,14 +58,18 @@ export const fr: Catalog = {
"Find": "Rechercher",
"Find in this space…": "Rechercher dans cet espace…",
"Find or create a page…": "Trouver ou créer une page…",
+ "Icon": "Icône",
"Image added ({size})": "Image ajoutée ({size})",
"Image added, resized to fit ({from} → {to})": "Image ajoutée, redimensionnée ({from} → {to})",
+ "Important": "Important",
"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 — what this block is highlighted as": "Langage — la coloration de ce bloc",
"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.",
+ "Leave it empty to use the tone mark": "Laissez vide pour utiliser le symbole du type",
"Link to page": "Lier à une page",
"Linked from": "Liens entrants",
"Links to it become dead": "Les liens vers elle seront rompus",
@@ -71,6 +78,7 @@ export const fr: Catalog = {
"Next (⏎)": "Suivant (⏎)",
"No block matches": "Aucun bloc correspondant",
"No pages yet": "Aucune page pour l’instant",
+ "Note": "Note",
"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",
@@ -82,6 +90,7 @@ export const fr: Catalog = {
"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…",
+ "Plain text": "Texte brut",
"Previous (⇧⏎)": "Précédent (⇧⏎)",
"Print": "Imprimer",
"Print / PDF…": "Imprimer / PDF…",
@@ -134,6 +143,7 @@ export const fr: Catalog = {
"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é",
+ "Tip": "Astuce",
"Type / for blocks, [[ to link a page": "Tapez / pour les blocs, [[ pour lier une page",
"Undo (⌘Z)": "Annuler (⌘Z)",
"Unlock": "Déverrouiller",
@@ -143,6 +153,7 @@ export const fr: Catalog = {
"Update this file": "Mettre à jour ce fichier",
"Updates": "Mises à jour",
"Version {v} is available.": "La version {v} est disponible.",
+ "Warning": "Avertissement",
"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}).",
@@ -158,4 +169,51 @@ export const fr: Catalog = {
"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",
+ "New page": "Nouvelle page",
+ "Redo": "Rétablir",
+ "Reading view": "Mode lecture",
+ "The pages without the editing tools": "Les pages sans les outils d'édition",
+ "Version, language, password, exports": "Version, langue, mot de passe, exports",
+ "More": "Plus",
+ "Copy saved — you are still editing the original": "Copie enregistrée — vous modifiez toujours l'original",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "Ceci est une copie de lecture. Elle s'ouvre en lecture ; rien de ce que vous faites ici ne modifie le fichier.",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "Un dossier de fichiers .md devient des pages, avec l’arborescence et les [[wikilinks]] intacts.",
+ "Bring notes in": "Faire entrer des notes",
+ "Choose .md files…": "Choisir des fichiers .md…",
+ "Choose a folder…": "Choisir un dossier…",
+ "Drop .md files or a folder here": "Déposez ici des fichiers .md ou un dossier",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "Chaque fichier .md devient une page, les dossiers deviennent l’arborescence des pages, et les [[wikilinks]] deviennent de vrais liens. Les pages s’ajoutent — rien n’est remplacé.",
+ "Image not imported": "Image non importée",
+ "Import Markdown": "Importer du Markdown",
+ "Import Markdown files or a folder…": "Importer des fichiers Markdown ou un dossier…",
+ "Import Markdown…": "Importer du Markdown…",
+ "Imported": "Importé",
+ "Imported notes": "Notes importées",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "Ajoutez les fichiers image et ils sont intégrés eux aussi. Une image que ce navigateur ne peut pas ouvrir reste sous forme de chemin, plutôt qu’en image cassée.",
+ "No Markdown files in that selection": "Aucun fichier Markdown dans cette sélection",
+ "Reading {n} file(s)…": "Lecture de {n} fichier(s)…",
+ "That is {n} files — importing them all may take a moment. Continue?": "Cela fait {n} fichiers — tout importer peut prendre un moment. Continuer ?",
+ "This file is open read-only": "Ce fichier est ouvert en lecture seule",
+ "Those files could not be read": "Ces fichiers n’ont pas pu être lus",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} image(s) n’ont pas pu être ouvertes ; leurs chemins restent en texte. Réimportez en incluant les fichiers image.",
+ "{n} image(s) embedded ({size}).": "{n} image(s) intégrée(s) ({size}).",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} image(s) pointent vers le web. Rien ne se charge tant qu’un lecteur ne le demande pas.",
+ "{n} of {total} wikilink(s) resolved.": "{n} wikilien(s) sur {total} résolus.",
+ "The rest name notes that were not in the selection, and are left as text.": "Les autres désignent des notes absentes de la sélection et restent en texte.",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} page(s) avaient un frontmatter, conservé tel quel dans un bloc replié.",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} tableau(x) conservés en texte : ce format n’a pas encore de bloc tableau.",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{pages} page(s) et {blocks} bloc(s) ajoutés depuis {files} fichier(s).",
+ "⌘Z removes the imported pages again.": "⌘Z supprime à nouveau les pages importées.",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "Les images de ces notes font déjà {size}, et elles voyagent toutes dans le fichier. Continuer à les intégrer ?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} image(s) restent sous forme de chemin, l’intégration s’étant arrêtée là.",
+ "About bento/spaces — version, updates, language, password": "À propos de bento/spaces — version, mises à jour, langue, mot de passe",
+ "Unsaved changes — ⌘S rewrites this file": "Modifications non enregistrées — ⌘S réécrit ce fichier",
+ "Unsaved changes — ⌘S downloads an updated copy": "Modifications non enregistrées — ⌘S télécharge une copie à jour",
+ "format v{v}": "format v{v}",
+ "Visit bento.page (opens in a new tab)": "Aller sur bento.page (nouvel onglet)",
+ "Drag to resize · double-click to reset": "Glisser pour redimensionner · double-clic pour réinitialiser",
+ "Show the page list ([)": "Afficher la liste des pages ([)",
+ "Hide the page list ([)": "Masquer la liste des pages ([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} nom(s) de note apparaissent plusieurs fois : les liens portant ce nom pointent tous vers le premier.",
}
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index 25677a80..fee3309e 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -23,6 +23,9 @@ export const it: Catalog = {
"Archived ({n})": "Archiviate ({n})",
"Block options": "Opzioni del blocco",
"Breadcrumb": "Percorso di navigazione",
+ "Callout icon": "Icona del riquadro",
+ "Caution": "Attenzione",
+ "Change the kind of callout": "Cambia il tipo di riquadro",
"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.",
@@ -55,14 +58,18 @@ export const it: Catalog = {
"Find": "Trova",
"Find in this space…": "Trova in questo spazio…",
"Find or create a page…": "Trova o crea una pagina…",
+ "Icon": "Icona",
"Image added ({size})": "Immagine aggiunta ({size})",
"Image added, resized to fit ({from} → {to})": "Immagine aggiunta, ridimensionata ({from} → {to})",
+ "Important": "Importante",
"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 — what this block is highlighted as": "Linguaggio — come viene evidenziato questo blocco",
"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.",
+ "Leave it empty to use the tone mark": "Lascia vuoto per usare il simbolo del tipo",
"Link to page": "Collega a una pagina",
"Linked from": "Collegata da",
"Links to it become dead": "I collegamenti a questa pagina si interrompono",
@@ -71,6 +78,7 @@ export const it: Catalog = {
"Next (⏎)": "Successivo (⏎)",
"No block matches": "Nessun blocco corrisponde",
"No pages yet": "Ancora nessuna pagina",
+ "Note": "Nota",
"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",
@@ -82,6 +90,7 @@ export const it: Catalog = {
"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…",
+ "Plain text": "Testo semplice",
"Previous (⇧⏎)": "Precedente (⇧⏎)",
"Print": "Stampa",
"Print / PDF…": "Stampa / PDF…",
@@ -134,6 +143,7 @@ export const it: Catalog = {
"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",
+ "Tip": "Suggerimento",
"Type / for blocks, [[ to link a page": "Digita / per i blocchi, [[ per collegare una pagina",
"Undo (⌘Z)": "Annulla (⌘Z)",
"Unlock": "Sblocca",
@@ -143,6 +153,7 @@ export const it: Catalog = {
"Update this file": "Aggiorna questo file",
"Updates": "Aggiornamenti",
"Version {v} is available.": "È disponibile la versione {v}.",
+ "Warning": "Avviso",
"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}).",
@@ -158,4 +169,51 @@ export const it: Catalog = {
"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",
+ "New page": "Nuova pagina",
+ "Redo": "Ripristina",
+ "Reading view": "Vista di lettura",
+ "The pages without the editing tools": "Le pagine senza gli strumenti di modifica",
+ "Version, language, password, exports": "Versione, lingua, password, esportazioni",
+ "More": "Altro",
+ "Copy saved — you are still editing the original": "Copia salvata: stai ancora modificando l'originale",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "Questa è una copia di lettura. Si apre in lettura; nulla di ciò che fai qui modifica il file.",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "Una cartella di file .md diventa pagine, con l’albero delle cartelle e i [[wikilink]] intatti.",
+ "Bring notes in": "Portare dentro le note",
+ "Choose .md files…": "Scegli file .md…",
+ "Choose a folder…": "Scegli una cartella…",
+ "Drop .md files or a folder here": "Trascina qui file .md o una cartella",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "Ogni file .md diventa una pagina, le cartelle diventano l’albero delle pagine e i [[wikilink]] diventano link veri. Le pagine si aggiungono: qui non viene sostituito nulla.",
+ "Image not imported": "Immagine non importata",
+ "Import Markdown": "Importa Markdown",
+ "Import Markdown files or a folder…": "Importa file Markdown o una cartella…",
+ "Import Markdown…": "Importa Markdown…",
+ "Imported": "Importato",
+ "Imported notes": "Note importate",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "Includi anche i file immagine e vengono incorporati. Un’immagine che questo browser non riesce ad aprire resta come percorso, invece che come immagine rotta.",
+ "No Markdown files in that selection": "Nessun file Markdown in questa selezione",
+ "Reading {n} file(s)…": "Lettura di {n} file…",
+ "That is {n} files — importing them all may take a moment. Continue?": "Sono {n} file — importarli tutti può richiedere un momento. Continuare?",
+ "This file is open read-only": "Questo file è aperto in sola lettura",
+ "Those files could not be read": "Non è stato possibile leggere quei file",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} immagini non si sono potute aprire: i loro percorsi restano come testo. Importa di nuovo includendo i file immagine.",
+ "{n} image(s) embedded ({size}).": "{n} immagini incorporate ({size}).",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} immagini puntano al web. Non si carica nulla finché un lettore non lo chiede.",
+ "{n} of {total} wikilink(s) resolved.": "{n} wikilink su {total} risolti.",
+ "The rest name notes that were not in the selection, and are left as text.": "Gli altri nominano note che non erano nella selezione e restano come testo.",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} pagine avevano un frontmatter, conservato alla lettera in un blocco richiuso.",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabelle conservate come testo: questo formato non ha ancora un blocco tabella.",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{pages} pagine e {blocks} blocchi aggiunti da {files} file.",
+ "⌘Z removes the imported pages again.": "⌘Z rimuove di nuovo le pagine importate.",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "Le immagini di queste note sono già {size} e viaggiano tutte dentro il file. Continuare a incorporarle?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} immagini restano come percorsi perché l’incorporamento si è fermato lì.",
+ "About bento/spaces — version, updates, language, password": "Informazioni su bento/spaces — versione, aggiornamenti, lingua, password",
+ "Unsaved changes — ⌘S rewrites this file": "Modifiche non salvate — ⌘S riscrive questo file",
+ "Unsaved changes — ⌘S downloads an updated copy": "Modifiche non salvate — ⌘S scarica una copia aggiornata",
+ "format v{v}": "formato v{v}",
+ "Visit bento.page (opens in a new tab)": "Vai su bento.page (si apre in una nuova scheda)",
+ "Drag to resize · double-click to reset": "Trascina per ridimensionare · doppio clic per reimpostare",
+ "Show the page list ([)": "Mostra l'elenco delle pagine ([)",
+ "Hide the page list ([)": "Nascondi l'elenco delle pagine ([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} nome/i di nota compaiono più volte, quindi i link con quel nome puntano tutti al primo.",
}
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index 0eb31a4e..db1eaf82 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -23,6 +23,9 @@ export const ja: Catalog = {
"Archived ({n})": "アーカイブ済み({n})",
"Block options": "ブロックのオプション",
"Breadcrumb": "パンくずリスト",
+ "Callout icon": "囲みのアイコン",
+ "Caution": "注意",
+ "Change the kind of callout": "囲みの種類を変更",
"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.": "確認は手動で、検証も行われます。ダウンロードには署名があり、何かを書き換える前にこのファイル内の鍵で署名を照合します。",
@@ -55,14 +58,18 @@ export const ja: Catalog = {
"Find": "検索",
"Find in this space…": "このスペース内を検索…",
"Find or create a page…": "ページを検索または作成…",
+ "Icon": "アイコン",
"Image added ({size})": "画像を追加しました({size})",
"Image added, resized to fit ({from} → {to})": "画像を追加し、収まるように縮小しました({from} → {to})",
+ "Important": "重要",
"Include archived pages": "アーカイブしたページを含める",
"Insert": "挿入",
"Insert a block — text, headings, lists, code, images": "ブロックを挿入 — テキスト、見出し、リスト、コード、画像",
"Interface language": "表示言語",
"Language": "言語",
+ "Language — what this block is highlighted as": "言語 — このブロックを何として色分けするか",
"Language follows whoever opens the file. It is never written into the document.": "言語はファイルを開いた人に従います。ドキュメントには書き込まれません。",
+ "Leave it empty to use the tone mark": "空のままにすると種類の記号を使います",
"Link to page": "ページにリンク",
"Linked from": "リンク元",
"Links to it become dead": "このページへのリンクが切れます",
@@ -71,6 +78,7 @@ export const ja: Catalog = {
"Next (⏎)": "次へ (⏎)",
"No block matches": "一致するブロックがありません",
"No pages yet": "ページがまだありません",
+ "Note": "メモ",
"Nothing found": "見つかりませんでした",
"Off by default — they were archived for a reason": "既定ではオフ — アーカイブしたのには理由があります",
"Other ways to save": "その他の保存方法",
@@ -82,6 +90,7 @@ export const ja: Catalog = {
"Password removed. Save to write the space unencrypted.": "パスワードを削除しました。保存すると、このスペースは暗号化なしで書き込まれます。",
"Password set. Save to write the space encrypted.": "パスワードを設定しました。保存すると、このスペースは暗号化して書き込まれます。",
"Password…": "パスワード…",
+ "Plain text": "プレーンテキスト",
"Previous (⇧⏎)": "前へ (⇧⏎)",
"Print": "印刷",
"Print / PDF…": "印刷 / PDF…",
@@ -134,6 +143,7 @@ export const ja: Catalog = {
"This space has no pages.": "このスペースにはページがありません。",
"This space is encrypted. Saves stay encrypted.": "このスペースは暗号化されています。保存しても暗号化されたままです。",
"This space is locked": "このスペースはロックされています",
+ "Tip": "ヒント",
"Type / for blocks, [[ to link a page": "/ でブロック、[[ でページにリンク",
"Undo (⌘Z)": "元に戻す (⌘Z)",
"Unlock": "ロック解除",
@@ -143,6 +153,7 @@ export const ja: Catalog = {
"Update this file": "このファイルを更新",
"Updates": "更新",
"Version {v} is available.": "バージョン {v} が利用可能です。",
+ "Warning": "警告",
"Width in the text column": "本文カラム内の幅",
"Wrong password — try again": "パスワードが違います — もう一度お試しください",
"You have the newest version ({v}).": "最新バージョンです ({v})。",
@@ -158,4 +169,51 @@ export const ja: Catalog = {
"Image from {host}": "{host} の画像",
"Not loaded — opening it would tell that site you opened this space.": "未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。",
"Load this image": "この画像を読み込む",
+ "New page": "新規ページ",
+ "Redo": "やり直す",
+ "Reading view": "閲覧ビュー",
+ "The pages without the editing tools": "編集ツールのないページ表示",
+ "Version, language, password, exports": "バージョン・言語・パスワード・書き出し",
+ "More": "その他",
+ "Copy saved — you are still editing the original": "コピーを保存しました — 編集中なのは引き続き元のファイルです",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "これは閲覧用のコピーです。読むために開きます。ここでの操作はファイルを変更しません。",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "「.md」ファイルのフォルダーがページになります。フォルダー階層も [[ウィキリンク]] もそのままです。",
+ "Bring notes in": "ノートを取り込む",
+ "Choose .md files…": ".md ファイルを選ぶ…",
+ "Choose a folder…": "フォルダーを選ぶ…",
+ "Drop .md files or a folder here": ".md ファイルかフォルダーをここにドロップ",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": ".md ファイルは 1 つずつページになり、フォルダーはページのツリーに、[[ウィキリンク]] は本物のリンクになります。ページは追加されるだけで、今あるものは置き換わりません。",
+ "Image not imported": "画像は取り込まれていません",
+ "Import Markdown": "Markdown を読み込む",
+ "Import Markdown files or a folder…": "Markdown ファイルまたはフォルダーを読み込む…",
+ "Import Markdown…": "Markdown を読み込む…",
+ "Imported": "読み込みました",
+ "Imported notes": "読み込んだノート",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "画像ファイルも一緒に選べば、そのまま埋め込まれます。このブラウザーが開けない画像は、壊れた画像ではなくパスのまま残ります。",
+ "No Markdown files in that selection": "選択に Markdown ファイルがありません",
+ "Reading {n} file(s)…": "{n} 個のファイルを読み込み中…",
+ "That is {n} files — importing them all may take a moment. Continue?": "{n} 個のファイルがあります。すべて読み込むには少し時間がかかります。続けますか?",
+ "This file is open read-only": "このファイルは読み取り専用で開いています",
+ "Those files could not be read": "それらのファイルは読み込めませんでした",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} 個の画像を開けなかったため、そのパスをテキストとして残しました。画像ファイルも含めてもう一度読み込んでください。",
+ "{n} image(s) embedded ({size}).": "{n} 個の画像を埋め込みました({size})。",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} 個の画像はウェブを指しています。読み手が求めるまで何も読み込みません。",
+ "{n} of {total} wikilink(s) resolved.": "{total} 個のウィキリンクのうち {n} 個を解決しました。",
+ "The rest name notes that were not in the selection, and are left as text.": "残りは選択に含まれていないノートを指しており、テキストのまま残ります。",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} ページにフロントマターがありました。折りたたみブロックにそのまま保存しています。",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} 個の表はテキストとして保存しました。この形式にはまだ表ブロックがありません。",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{files} 個のファイルから {pages} ページ・{blocks} ブロックを追加しました。",
+ "⌘Z removes the imported pages again.": "⌘Z で、読み込んだページを取り消せます。",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "これらのノートの画像はすでに {size} あり、すべてファイルの中を一緒に運ばれます。埋め込みを続けますか?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} 個の画像は、そこで埋め込みを止めたためパスのまま残りました。",
+ "About bento/spaces — version, updates, language, password": "bento/spaces について — バージョン・更新・言語・パスワード",
+ "Unsaved changes — ⌘S rewrites this file": "未保存の変更 — ⌘S でこのファイルを書き換えます",
+ "Unsaved changes — ⌘S downloads an updated copy": "未保存の変更 — ⌘S で更新版をダウンロードします",
+ "format v{v}": "フォーマット v{v}",
+ "Visit bento.page (opens in a new tab)": "bento.page を開く(新しいタブ)",
+ "Drag to resize · double-click to reset": "ドラッグで幅を変更 · ダブルクリックで既定に戻す",
+ "Show the page list ([)": "ページ一覧を表示([)",
+ "Hide the page list ([)": "ページ一覧を隠す([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} 件のノート名が重複しているため、その名前のリンクはすべて最初のノートに向いています。",
}
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index b532c08a..49216894 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -12,29 +12,37 @@
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 folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": ["「.md」ファイルのフォルダーがページになります。フォルダー階層も [[ウィキリンク]] もそのままです。","一个装满 .md 文件的文件夹会变成页面,文件夹层级和 [[wiki 链接]] 都保留下来。","一個裝滿 .md 檔案的資料夾會變成頁面,資料夾層級和 [[wiki 連結]] 都會保留。","Una carpeta de archivos .md se convierte en páginas, con el árbol de carpetas y los [[wikilinks]] intactos.","Un dossier de fichiers .md devient des pages, avec l’arborescence et les [[wikilinks]] intacts.","Ein Ordner voller .md-Dateien wird zu Seiten — samt Ordnerbaum und den [[Wikilinks]] dazwischen.","Una cartella di file .md diventa pagine, con l’albero delle cartelle e i [[wikilink]] intatti.","Uma pasta de ficheiros .md transforma-se em páginas, com a árvore de pastas e os [[wikilinks]] intactos."],
"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 bento/spaces — version, updates, language, password": ["bento/spaces について — バージョン・更新・言語・パスワード","关于 bento/spaces — 版本、更新、语言、密码","關於 bento/spaces — 版本、更新、語言、密碼","Acerca de bento/spaces: versión, actualizaciones, idioma, contraseña","À propos de bento/spaces — version, mises à jour, langue, mot de passe","Über bento/spaces — Version, Updates, Sprache, Passwort","Informazioni su bento/spaces — versione, aggiornamenti, lingua, password","Acerca do bento/spaces — versão, atualizações, idioma, palavra-passe"],
"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"],
+ "Bring notes in": ["ノートを取り込む","把笔记带进来","把筆記帶進來","Traer notas","Faire entrer des notes","Notizen hereinholen","Portare dentro le note","Trazer notas para cá"],
+ "Callout icon": ["囲みのアイコン","标注图标","標註圖示","Icono del aviso","Icône de l'encadré","Symbol des Hinweisfelds","Icona del riquadro","Ícone do destaque"],
+ "Caution": ["注意","当心","當心","Precaución","Attention","Achtung","Attenzione","Cuidado"],
+ "Change the kind of callout": ["囲みの種類を変更","更改标注类型","變更標註類型","Cambiar el tipo de aviso","Changer le type d'encadré","Art des Hinweisfelds ändern","Cambia il tipo di riquadro","Alterar o tipo de destaque"],
"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 .md files…": [".md ファイルを選ぶ…","选择 .md 文件…","選擇 .md 檔案…","Elegir archivos .md…","Choisir des fichiers .md…",".md-Dateien wählen…","Scegli file .md…","Escolher ficheiros .md…"],
+ "Choose a folder…": ["フォルダーを選ぶ…","选择文件夹…","選擇資料夾…","Elegir una carpeta…","Choisir un dossier…","Ordner wählen…","Scegli una cartella…","Escolher uma pasta…"],
"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 saved — you are still editing the original": ["コピーを保存しました — 編集中なのは引き続き元のファイルです","副本已保存 — 你仍在编辑原文件","副本已儲存 — 你仍在編輯原始檔案","Copia guardada: sigues editando el original","Copie enregistrée — vous modifiez toujours l'original","Kopie gespeichert — du bearbeitest weiterhin das Original","Copia salvata: stai ancora modificando l'originale","Cópia guardada — continuas a editar o original"],
"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."],
@@ -44,6 +52,9 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
+ "Drag to resize · double-click to reset": ["ドラッグで幅を変更 · ダブルクリックで既定に戻す","拖动可调整宽度 · 双击恢复默认","拖曳可調整寬度 · 雙擊還原預設","Arrastra para redimensionar · doble clic para restablecer","Glisser pour redimensionner · double-clic pour réinitialiser","Ziehen zum Anpassen · Doppelklick setzt zurück","Trascina per ridimensionare · doppio clic per reimpostare","Arrasta para redimensionar · duplo clique para repor"],
+ "Drop .md files or a folder here": [".md ファイルかフォルダーをここにドロップ","把 .md 文件或文件夹拖到这里","把 .md 檔案或資料夾拖到這裡","Suelta aquí archivos .md o una carpeta","Déposez ici des fichiers .md ou un dossier",".md-Dateien oder einen Ordner hierher ziehen","Trascina qui file .md o una cartella","Largue aqui ficheiros .md ou uma pasta"],
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": [".md ファイルは 1 つずつページになり、フォルダーはページのツリーに、[[ウィキリンク]] は本物のリンクになります。ページは追加されるだけで、今あるものは置き換わりません。","每个 .md 文件变成一个页面,文件夹变成页面树,[[wiki 链接]] 变成真正的链接。页面是新增的——已有内容不会被替换。","每個 .md 檔案變成一個頁面,資料夾變成頁面樹,[[wiki 連結]] 變成真正的連結。頁面是新增的——既有內容不會被取代。","Cada archivo .md se convierte en una página, las carpetas forman el árbol de páginas y los [[wikilinks]] se vuelven enlaces reales. Las páginas se añaden: aquí no se reemplaza nada.","Chaque fichier .md devient une page, les dossiers deviennent l’arborescence des pages, et les [[wikilinks]] deviennent de vrais liens. Les pages s’ajoutent — rien n’est remplacé.","Jede .md-Datei wird eine Seite, Ordner werden zum Seitenbaum, [[Wikilinks]] werden echte Links. Seiten kommen hinzu — nichts hier wird ersetzt.","Ogni file .md diventa una pagina, le cartelle diventano l’albero delle pagine e i [[wikilink]] diventano link veri. Le pagine si aggiungono: qui non viene sostituito nulla.","Cada ficheiro .md passa a ser uma página, as pastas passam a ser a árvore de páginas e os [[wikilinks]] passam a ser ligações verdadeiras. As páginas são acrescentadas — nada aqui é substituído."],
"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"],
@@ -56,25 +67,41 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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…"],
+ "Hide the page list ([)": ["ページ一覧を隠す([)","隐藏页面列表([)","隱藏頁面清單([)","Ocultar la lista de páginas ([)","Masquer la liste des pages ([)","Seitenliste ausblenden ([)","Nascondi l'elenco delle pagine ([)","Ocultar a lista de páginas ([)"],
+ "Icon": ["アイコン","图标","圖示","Icono","Icône","Symbol","Icona","Ícone"],
"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}"],
+ "Image not imported": ["画像は取り込まれていません","图片未导入","圖片未匯入","Imagen no importada","Image non importée","Bild nicht importiert","Immagine non importata","Imagem não importada"],
+ "Import Markdown": ["Markdown を読み込む","导入 Markdown","匯入 Markdown","Importar Markdown","Importer du Markdown","Markdown importieren","Importa Markdown","Importar Markdown"],
+ "Import Markdown files or a folder…": ["Markdown ファイルまたはフォルダーを読み込む…","导入 Markdown 文件或文件夹…","匯入 Markdown 檔案或資料夾…","Importar archivos Markdown o una carpeta…","Importer des fichiers Markdown ou un dossier…","Markdown-Dateien oder einen Ordner importieren…","Importa file Markdown o una cartella…","Importar ficheiros Markdown ou uma pasta…"],
+ "Import Markdown…": ["Markdown を読み込む…","导入 Markdown…","匯入 Markdown…","Importar Markdown…","Importer du Markdown…","Markdown importieren…","Importa Markdown…","Importar Markdown…"],
+ "Important": ["重要","重要","重要","Importante","Important","Wichtig","Importante","Importante"],
+ "Imported": ["読み込みました","已导入","已匯入","Importado","Importé","Importiert","Importato","Importado"],
+ "Imported notes": ["読み込んだノート","导入的笔记","匯入的筆記","Notas importadas","Notes importées","Importierte Notizen","Note importate","Notas importadas"],
"Include archived pages": ["アーカイブしたページを含める","包含已归档页面","包含已封存的頁面","Incluir páginas archivadas","Inclure les pages archivées","Archivierte Seiten einbeziehen","Includi le pagine archiviate","Incluir páginas arquivadas"],
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": ["画像ファイルも一緒に選べば、そのまま埋め込まれます。このブラウザーが開けない画像は、壊れた画像ではなくパスのまま残ります。","把图片文件一起选上,它们也会被嵌入。这个浏览器打不开的图片会以路径的形式保留,而不是一张坏掉的图。","把圖片檔案一起選取,它們也會一併嵌入。這個瀏覽器打不開的圖片會以路徑的形式保留,而不是一張破圖。","Incluye los archivos de imagen y también se incrustan. Una imagen que este navegador no puede abrir se conserva como su ruta, no como una imagen rota.","Ajoutez les fichiers image et ils sont intégrés eux aussi. Une image que ce navigateur ne peut pas ouvrir reste sous forme de chemin, plutôt qu’en image cassée.","Nimm die Bilddateien mit, dann werden sie gleich eingebettet. Ein Bild, das dieser Browser nicht öffnen kann, bleibt als Pfad stehen statt als kaputtes Bild.","Includi anche i file immagine e vengono incorporati. Un’immagine che questo browser non riesce ad aprire resta come percorso, invece che come immagine rotta.","Inclua os ficheiros de imagem e também são incorporados. Uma imagem que este navegador não consegue abrir fica como o seu caminho, em vez de uma imagem partida."],
"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."],
+ "Language — what this block is highlighted as": ["言語 — このブロックを何として色分けするか","语言 — 这个块按什么语言着色","語言 — 這個區塊以什麼語言上色","Lenguaje — cómo se colorea este bloque","Langage — la coloration de ce bloc","Sprache — wie dieser Block hervorgehoben wird","Linguaggio — come viene evidenziato questo blocco","Linguagem — como este bloco é realçado"],
+ "Leave it empty to use the tone mark": ["空のままにすると種類の記号を使います","留空则使用该类型的标记","留空則使用該類型的標記","Déjalo vacío para usar el símbolo del tipo","Laissez vide pour utiliser le symbole du type","Leer lassen, um das Symbol der Art zu verwenden","Lascia vuoto per usare il simbolo del tipo","Deixe vazio para usar o símbolo do tipo"],
"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"],
+ "More": ["その他","更多","更多","Más","Plus","Mehr","Altro","Mais"],
+ "New page": ["新規ページ","新建页面","新增頁面","Nueva página","Nouvelle page","Neue Seite","Nuova pagina","Nova página"],
"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 Markdown files in that selection": ["選択に Markdown ファイルがありません","所选内容里没有 Markdown 文件","所選項目中沒有 Markdown 檔案","No hay archivos Markdown en esa selección","Aucun fichier Markdown dans cette sélection","Keine Markdown-Dateien in dieser Auswahl","Nessun file Markdown in questa selezione","Não há ficheiros Markdown nessa seleção"],
"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."],
+ "Note": ["メモ","备注","備註","Nota","Note","Hinweis","Nota","Nota"],
"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"],
@@ -86,15 +113,16 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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…"],
+ "Plain text": ["プレーンテキスト","纯文本","純文字","Texto sin formato","Texte brut","Nur Text","Testo semplice","Texto simples"],
"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": ["閲覧ビュー","阅读视图","閱讀檢視","Vista de lectura","Mode lecture","Leseansicht","Vista di lettura","Modo de leitura"],
"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"],
+ "Reading {n} file(s)…": ["{n} 個のファイルを読み込み中…","正在读取 {n} 个文件…","正在讀取 {n} 個檔案…","Leyendo {n} archivo(s)…","Lecture de {n} fichier(s)…","Lese {n} Datei(en)…","Lettura di {n} file…","A ler {n} ficheiro(s)…"],
"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."],
@@ -119,44 +147,69 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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…"],
+ "Show the page list ([)": ["ページ一覧を表示([)","显示页面列表([)","顯示頁面清單([)","Mostrar la lista de páginas ([)","Afficher la liste des pages ([)","Seitenliste einblenden ([)","Mostra l'elenco delle pagine ([)","Mostrar a lista de páginas ([)"],
"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"],
+ "That is {n} files — importing them all may take a moment. Continue?": ["{n} 個のファイルがあります。すべて読み込むには少し時間がかかります。続けますか?","一共 {n} 个文件,全部导入需要一点时间。继续吗?","共 {n} 個檔案,全部匯入需要一點時間。要繼續嗎?","Son {n} archivos: importarlos todos puede tardar un momento. ¿Continuar?","Cela fait {n} fichiers — tout importer peut prendre un moment. Continuer ?","Das sind {n} Dateien — der Import kann einen Moment dauern. Fortfahren?","Sono {n} file — importarli tutti può richiedere un momento. Continuare?","São {n} ficheiros — importar todos pode demorar um momento. Continuar?"],
"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 images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": ["これらのノートの画像はすでに {size} あり、すべてファイルの中を一緒に運ばれます。埋め込みを続けますか?","这些笔记里的图片已经有 {size},而且都会随文件一起走。继续嵌入吗?","這些筆記裡的圖片已經有 {size},而且都會隨檔案一起走。要繼續嵌入嗎?","Las imágenes de estas notas suman ya {size} y todas viajan dentro del archivo. ¿Seguir incrustándolas?","Les images de ces notes font déjà {size}, et elles voyagent toutes dans le fichier. Continuer à les intégrer ?","Die Bilder in diesen Notizen ergeben bisher {size}, und sie reisen alle in der Datei mit. Weiter einbetten?","Le immagini di queste note sono già {size} e viaggiano tutte dentro il file. Continuare a incorporarle?","As imagens destas notas já somam {size} e viajam todas dentro do ficheiro. Continuar a incorporá-las?"],
+ "The pages without the editing tools": ["編集ツールのないページ表示","不带编辑工具的页面","不含編輯工具的頁面","Las páginas sin las herramientas de edición","Les pages sans les outils d'édition","Die Seiten ohne die Bearbeitungswerkzeuge","Le pagine senza gli strumenti di modifica","As páginas sem as ferramentas de edição"],
+ "The rest name notes that were not in the selection, and are left as text.": ["残りは選択に含まれていないノートを指しており、テキストのまま残ります。","其余指向不在所选范围内的笔记,保留为文字。","其餘指向不在所選範圍內的筆記,保留為文字。","El resto nombra notas que no estaban en la selección y se dejan como texto.","Les autres désignent des notes absentes de la sélection et restent en texte.","Der Rest nennt Notizen, die nicht in der Auswahl waren, und bleibt als Text stehen.","Gli altri nominano note che non erano nella selezione e restano come testo.","Os restantes nomeiam notas que não estavam na seleção e ficam como texto."],
"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 is open read-only": ["このファイルは読み取り専用で開いています","这个文件以只读方式打开","這個檔案以唯讀方式開啟","Este archivo está abierto en solo lectura","Ce fichier est ouvert en lecture seule","Diese Datei ist schreibgeschützt geöffnet","Questo file è aperto in sola lettura","Este ficheiro está aberto apenas para leitura"],
"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 a reading copy. It opens for reading; nothing you do here changes the file.": ["これは閲覧用のコピーです。読むために開きます。ここでの操作はファイルを変更しません。","这是一份阅读副本。它以阅读方式打开;你在此处的操作不会更改文件。","這是一份閱讀副本。它以閱讀方式開啟;你在此處的操作不會變更檔案。","Esta es una copia de lectura. Se abre para leer; nada de lo que hagas aquí cambia el archivo.","Ceci est une copie de lecture. Elle s'ouvre en lecture ; rien de ce que vous faites ici ne modifie le fichier.","Dies ist eine Lesekopie. Sie öffnet sich zum Lesen; nichts, was du hier tust, ändert die Datei.","Questa è una copia di lettura. Si apre in lettura; nulla di ciò che fai qui modifica il file.","Esta é uma cópia de leitura. Abre para leitura; nada do que fizeres aqui altera o ficheiro."],
"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"],
+ "Those files could not be read": ["それらのファイルは読み込めませんでした","这些文件无法读取","這些檔案無法讀取","No se pudieron leer esos archivos","Ces fichiers n’ont pas pu être lus","Diese Dateien konnten nicht gelesen werden","Non è stato possibile leggere quei file","Não foi possível ler esses ficheiros"],
+ "Tip": ["ヒント","提示","提示","Consejo","Astuce","Tipp","Suggerimento","Dica"],
"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."],
+ "Unsaved changes — ⌘S downloads an updated copy": ["未保存の変更 — ⌘S で更新版をダウンロードします","未保存的更改 — ⌘S 会下载更新后的副本","未儲存的變更 — ⌘S 會下載更新後的副本","Cambios sin guardar: ⌘S descarga una copia actualizada","Modifications non enregistrées — ⌘S télécharge une copie à jour","Ungespeicherte Änderungen — ⌘S lädt eine aktualisierte Kopie herunter","Modifiche non salvate — ⌘S scarica una copia aggiornata","Alterações não guardadas — ⌘S transfere uma cópia atualizada"],
+ "Unsaved changes — ⌘S rewrites this file": ["未保存の変更 — ⌘S でこのファイルを書き換えます","未保存的更改 — ⌘S 会重写此文件","未儲存的變更 — ⌘S 會重寫此檔案","Cambios sin guardar: ⌘S reescribe este archivo","Modifications non enregistrées — ⌘S réécrit ce fichier","Ungespeicherte Änderungen — ⌘S schreibt diese Datei neu","Modifiche non salvate — ⌘S riscrive questo file","Alterações não guardadas — ⌘S reescreve este ficheiro"],
"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."],
+ "Version, language, password, exports": ["バージョン・言語・パスワード・書き出し","版本、语言、密码、导出","版本、語言、密碼、匯出","Versión, idioma, contraseña, exportaciones","Version, langue, mot de passe, exports","Version, Sprache, Passwort, Export","Versione, lingua, password, esportazioni","Versão, idioma, senha, exportações"],
+ "Visit bento.page (opens in a new tab)": ["bento.page を開く(新しいタブ)","访问 bento.page(在新标签页打开)","造訪 bento.page(在新分頁開啟)","Visitar bento.page (se abre en una pestaña nueva)","Aller sur bento.page (nouvel onglet)","bento.page besuchen (öffnet in neuem Tab)","Vai su bento.page (si apre in una nuova scheda)","Visitar bento.page (abre num novo separador)"],
+ "Warning": ["警告","警告","警告","Advertencia","Avertissement","Warnung","Avviso","Aviso"],
"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."],
+ "format v{v}": ["フォーマット v{v}","格式 v{v}","格式 v{v}","formato v{v}","format v{v}","Format v{v}","formato v{v}","formato v{v}"],
"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} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": ["{n} 個の画像を開けなかったため、そのパスをテキストとして残しました。画像ファイルも含めてもう一度読み込んでください。","{n} 张图片打不开,它们的路径以文字保留。请把图片文件一并选上再导入一次。","{n} 張圖片打不開,它們的路徑以文字保留。請連同圖片檔案一起再匯入一次。","{n} imagen(es) no se pudieron abrir, así que sus rutas quedan como texto. Vuelve a importar incluyendo los archivos de imagen.","{n} image(s) n’ont pas pu être ouvertes ; leurs chemins restent en texte. Réimportez en incluant les fichiers image.","{n} Bild(er) ließen sich nicht öffnen; ihre Pfade bleiben als Text. Importiere noch einmal, diesmal mit den Bilddateien.","{n} immagini non si sono potute aprire: i loro percorsi restano come testo. Importa di nuovo includendo i file immagine.","{n} imagem(ns) não puderam ser abertas, por isso os caminhos ficam como texto. Importe de novo com os ficheiros de imagem incluídos."],
+ "{n} image(s) embedded ({size}).": ["{n} 個の画像を埋め込みました({size})。","已嵌入 {n} 张图片({size})。","已嵌入 {n} 張圖片({size})。","{n} imagen(es) incrustada(s) ({size}).","{n} image(s) intégrée(s) ({size}).","{n} Bild(er) eingebettet ({size}).","{n} immagini incorporate ({size}).","{n} imagem(ns) incorporada(s) ({size})."],
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": ["{n} 個の画像はウェブを指しています。読み手が求めるまで何も読み込みません。","{n} 张图片指向网络。在读者主动请求之前不会加载。","{n} 張圖片指向網路。在讀者主動要求之前不會載入。","{n} imagen(es) apuntan a la web. No se carga nada hasta que un lector lo pida.","{n} image(s) pointent vers le web. Rien ne se charge tant qu’un lecteur ne le demande pas.","{n} Bild(er) zeigen ins Web. Nichts wird geladen, bevor ein Leser darum bittet.","{n} immagini puntano al web. Non si carica nulla finché un lettore non lo chiede.","{n} imagem(ns) apontam para a web. Nada é carregado até um leitor pedir."],
+ "{n} image(s) were left as paths because embedding stopped there.": ["{n} 個の画像は、そこで埋め込みを止めたためパスのまま残りました。","{n} 张图片以路径形式保留,因为嵌入到此为止。","{n} 張圖片以路徑形式保留,因為嵌入到此為止。","{n} imagen(es) quedaron como rutas porque la incrustación se detuvo ahí.","{n} image(s) restent sous forme de chemin, l’intégration s’étant arrêtée là.","{n} Bild(er) blieben als Pfad stehen, weil das Einbetten dort endete.","{n} immagini restano come percorsi perché l’incorporamento si è fermato lì.","{n} imagem(ns) ficaram como caminhos porque a incorporação parou aí."],
"{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} note name(s) appear more than once, so links naming them all went to the first.": ["{n} 件のノート名が重複しているため、その名前のリンクはすべて最初のノートに向いています。","有 {n} 个笔记名称重复,因此指向该名称的链接都指向了第一个。","有 {n} 個筆記名稱重複,因此指向該名稱的連結都指向了第一個。","{n} nombre(s) de nota se repiten, así que los enlaces con ese nombre fueron todos al primero.","{n} nom(s) de note apparaissent plusieurs fois : les liens portant ce nom pointent tous vers le premier.","{n} Notiznamen kommen mehrfach vor — Links mit diesem Namen führen alle zur ersten.","{n} nome/i di nota compaiono più volte, quindi i link con quel nome puntano tutti al primo.","{n} nome(s) de nota aparecem mais de uma vez, por isso as ligações com esse nome foram todas para a primeira."],
+ "{n} of {total} wikilink(s) resolved.": ["{total} 個のウィキリンクのうち {n} 個を解決しました。","{total} 个 wiki 链接中解析了 {n} 个。","{total} 個 wiki 連結中解析了 {n} 個。","{n} de {total} wikilink(s) resueltos.","{n} wikilien(s) sur {total} résolus.","{n} von {total} Wikilink(s) aufgelöst.","{n} wikilink su {total} risolti.","{n} de {total} wikilink(s) resolvidos."],
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": ["{n} ページにフロントマターがありました。折りたたみブロックにそのまま保存しています。","{n} 个页面带有 frontmatter,已原样保存在折叠块里。","{n} 個頁面帶有 frontmatter,已原樣保存在摺疊區塊裡。","{n} página(s) tenían frontmatter, conservado tal cual en un bloque plegado.","{n} page(s) avaient un frontmatter, conservé tel quel dans un bloc replié.","{n} Seite(n) hatten Frontmatter — wortgetreu in einem zugeklappten Block erhalten.","{n} pagine avevano un frontmatter, conservato alla lettera in un blocco richiuso.","{n} página(s) tinham frontmatter, guardado tal e qual num bloco fechado."],
"{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"],
+ "{n} table(s) kept as text: there is no table block in this format yet.": ["{n} 個の表はテキストとして保存しました。この形式にはまだ表ブロックがありません。","{n} 个表格按原文保留为文字:这个格式还没有表格块。","{n} 個表格按原文保留為文字:這個格式還沒有表格區塊。","{n} tabla(s) conservadas como texto: este formato aún no tiene bloque de tabla.","{n} tableau(x) conservés en texte : ce format n’a pas encore de bloc tableau.","{n} Tabelle(n) als Text übernommen: Dieses Format hat noch keinen Tabellenblock.","{n} tabelle conservate come testo: questo formato non ha ancora un blocco tabella.","{n} tabela(s) ficaram como texto: este formato ainda não tem bloco de tabela."],
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": ["{files} 個のファイルから {pages} ページ・{blocks} ブロックを追加しました。","从 {files} 个文件新增了 {pages} 个页面、{blocks} 个块。","從 {files} 個檔案新增了 {pages} 個頁面、{blocks} 個區塊。","{pages} página(s) y {blocks} bloque(s) añadidos desde {files} archivo(s).","{pages} page(s) et {blocks} bloc(s) ajoutés depuis {files} fichier(s).","{pages} Seite(n) und {blocks} Block/Blöcke aus {files} Datei(en) hinzugefügt.","{pages} pagine e {blocks} blocchi aggiunti da {files} file.","{pages} página(s) e {blocks} bloco(s) acrescentados a partir de {files} ficheiro(s)."],
+ "⌘Z removes the imported pages again.": ["⌘Z で、読み込んだページを取り消せます。","按 ⌘Z 可以把导入的页面再撤销掉。","按 ⌘Z 可以把匯入的頁面再撤銷掉。","⌘Z vuelve a quitar las páginas importadas.","⌘Z supprime à nouveau les pages importées.","Mit ⌘Z verschwinden die importierten Seiten wieder.","⌘Z rimuove di nuovo le pagine importate.","⌘Z remove novamente as páginas importadas."],
}
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index 955d5ccf..9598a3ca 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -23,6 +23,9 @@ export const pt: Catalog = {
"Archived ({n})": "Arquivadas ({n})",
"Block options": "Opções do bloco",
"Breadcrumb": "Trilho de navegação",
+ "Callout icon": "Ícone do destaque",
+ "Caution": "Cuidado",
+ "Change the kind of callout": "Alterar o tipo de destaque",
"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.",
@@ -55,14 +58,18 @@ export const pt: Catalog = {
"Find": "Localizar",
"Find in this space…": "Localizar neste espaço…",
"Find or create a page…": "Encontrar ou criar uma página…",
+ "Icon": "Ícone",
"Image added ({size})": "Imagem adicionada ({size})",
"Image added, resized to fit ({from} → {to})": "Imagem adicionada, redimensionada para caber ({from} → {to})",
+ "Important": "Importante",
"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 — what this block is highlighted as": "Linguagem — como este bloco é realçado",
"Language follows whoever opens the file. It is never written into the document.": "O idioma segue quem abre o ficheiro. Nunca é escrito no documento.",
+ "Leave it empty to use the tone mark": "Deixe vazio para usar o símbolo do tipo",
"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",
@@ -71,6 +78,7 @@ export const pt: Catalog = {
"Next (⏎)": "Seguinte (⏎)",
"No block matches": "Nenhum bloco corresponde",
"No pages yet": "Ainda sem páginas",
+ "Note": "Nota",
"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",
@@ -82,6 +90,7 @@ export const pt: Catalog = {
"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…",
+ "Plain text": "Texto simples",
"Previous (⇧⏎)": "Anterior (⇧⏎)",
"Print": "Imprimir",
"Print / PDF…": "Imprimir / PDF…",
@@ -134,6 +143,7 @@ export const pt: Catalog = {
"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",
+ "Tip": "Dica",
"Type / for blocks, [[ to link a page": "Escreva / para blocos, [[ para ligar uma página",
"Undo (⌘Z)": "Desfazer (⌘Z)",
"Unlock": "Desbloquear",
@@ -143,6 +153,7 @@ export const pt: Catalog = {
"Update this file": "Atualizar este ficheiro",
"Updates": "Atualizações",
"Version {v} is available.": "A versão {v} está disponível.",
+ "Warning": "Aviso",
"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}).",
@@ -158,4 +169,51 @@ export const pt: Catalog = {
"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",
+ "New page": "Nova página",
+ "Redo": "Refazer",
+ "Reading view": "Modo de leitura",
+ "The pages without the editing tools": "As páginas sem as ferramentas de edição",
+ "Version, language, password, exports": "Versão, idioma, senha, exportações",
+ "More": "Mais",
+ "Copy saved — you are still editing the original": "Cópia guardada — continuas a editar o original",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "Esta é uma cópia de leitura. Abre para leitura; nada do que fizeres aqui altera o ficheiro.",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "Uma pasta de ficheiros .md transforma-se em páginas, com a árvore de pastas e os [[wikilinks]] intactos.",
+ "Bring notes in": "Trazer notas para cá",
+ "Choose .md files…": "Escolher ficheiros .md…",
+ "Choose a folder…": "Escolher uma pasta…",
+ "Drop .md files or a folder here": "Largue aqui ficheiros .md ou uma pasta",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "Cada ficheiro .md passa a ser uma página, as pastas passam a ser a árvore de páginas e os [[wikilinks]] passam a ser ligações verdadeiras. As páginas são acrescentadas — nada aqui é substituído.",
+ "Image not imported": "Imagem não importada",
+ "Import Markdown": "Importar Markdown",
+ "Import Markdown files or a folder…": "Importar ficheiros Markdown ou uma pasta…",
+ "Import Markdown…": "Importar Markdown…",
+ "Imported": "Importado",
+ "Imported notes": "Notas importadas",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "Inclua os ficheiros de imagem e também são incorporados. Uma imagem que este navegador não consegue abrir fica como o seu caminho, em vez de uma imagem partida.",
+ "No Markdown files in that selection": "Não há ficheiros Markdown nessa seleção",
+ "Reading {n} file(s)…": "A ler {n} ficheiro(s)…",
+ "That is {n} files — importing them all may take a moment. Continue?": "São {n} ficheiros — importar todos pode demorar um momento. Continuar?",
+ "This file is open read-only": "Este ficheiro está aberto apenas para leitura",
+ "Those files could not be read": "Não foi possível ler esses ficheiros",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} imagem(ns) não puderam ser abertas, por isso os caminhos ficam como texto. Importe de novo com os ficheiros de imagem incluídos.",
+ "{n} image(s) embedded ({size}).": "{n} imagem(ns) incorporada(s) ({size}).",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} imagem(ns) apontam para a web. Nada é carregado até um leitor pedir.",
+ "{n} of {total} wikilink(s) resolved.": "{n} de {total} wikilink(s) resolvidos.",
+ "The rest name notes that were not in the selection, and are left as text.": "Os restantes nomeiam notas que não estavam na seleção e ficam como texto.",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} página(s) tinham frontmatter, guardado tal e qual num bloco fechado.",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabela(s) ficaram como texto: este formato ainda não tem bloco de tabela.",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "{pages} página(s) e {blocks} bloco(s) acrescentados a partir de {files} ficheiro(s).",
+ "⌘Z removes the imported pages again.": "⌘Z remove novamente as páginas importadas.",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "As imagens destas notas já somam {size} e viajam todas dentro do ficheiro. Continuar a incorporá-las?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} imagem(ns) ficaram como caminhos porque a incorporação parou aí.",
+ "About bento/spaces — version, updates, language, password": "Acerca do bento/spaces — versão, atualizações, idioma, palavra-passe",
+ "Unsaved changes — ⌘S rewrites this file": "Alterações não guardadas — ⌘S reescreve este ficheiro",
+ "Unsaved changes — ⌘S downloads an updated copy": "Alterações não guardadas — ⌘S transfere uma cópia atualizada",
+ "format v{v}": "formato v{v}",
+ "Visit bento.page (opens in a new tab)": "Visitar bento.page (abre num novo separador)",
+ "Drag to resize · double-click to reset": "Arrasta para redimensionar · duplo clique para repor",
+ "Show the page list ([)": "Mostrar a lista de páginas ([)",
+ "Hide the page list ([)": "Ocultar a lista de páginas ([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "{n} nome(s) de nota aparecem mais de uma vez, por isso as ligações com esse nome foram todas para a primeira.",
}
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index 157efc41..c5fa0165 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -23,6 +23,9 @@ export const zh_Hans: Catalog = {
"Archived ({n})": "已归档 ({n})",
"Block options": "块选项",
"Breadcrumb": "面包屑导航",
+ "Callout icon": "标注图标",
+ "Caution": "当心",
+ "Change the kind of callout": "更改标注类型",
"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.": "检查更新完全由你手动发起,并且经过验证:下载内容带有签名,改写任何内容之前,都会先用此文件内的密钥校验签名。",
@@ -55,14 +58,18 @@ export const zh_Hans: Catalog = {
"Find": "查找",
"Find in this space…": "在此空间中查找…",
"Find or create a page…": "查找或新建页面…",
+ "Icon": "图标",
"Image added ({size})": "已添加图片 ({size})",
"Image added, resized to fit ({from} → {to})": "已添加图片,已缩放以适配 ({from} → {to})",
+ "Important": "重要",
"Include archived pages": "包含已归档页面",
"Insert": "插入",
"Insert a block — text, headings, lists, code, images": "插入块 — 文本、标题、列表、代码、图片",
"Interface language": "界面语言",
"Language": "语言",
+ "Language — what this block is highlighted as": "语言 — 这个块按什么语言着色",
"Language follows whoever opens the file. It is never written into the document.": "语言跟随打开文件的人,绝不会写入文档。",
+ "Leave it empty to use the tone mark": "留空则使用该类型的标记",
"Link to page": "链接到页面",
"Linked from": "链接来源",
"Links to it become dead": "指向它的链接会失效",
@@ -71,6 +78,7 @@ export const zh_Hans: Catalog = {
"Next (⏎)": "下一个 (⏎)",
"No block matches": "没有匹配的块",
"No pages yet": "还没有页面",
+ "Note": "备注",
"Nothing found": "没有结果",
"Off by default — they were archived for a reason": "默认关闭 — 当初归档总是有原因的",
"Other ways to save": "其他保存方式",
@@ -82,6 +90,7 @@ export const zh_Hans: Catalog = {
"Password removed. Save to write the space unencrypted.": "已移除密码。保存后空间将以未加密方式写入。",
"Password set. Save to write the space encrypted.": "已设置密码。保存后空间将以加密方式写入。",
"Password…": "密码…",
+ "Plain text": "纯文本",
"Previous (⇧⏎)": "上一个 (⇧⏎)",
"Print": "打印",
"Print / PDF…": "打印 / PDF…",
@@ -134,6 +143,7 @@ export const zh_Hans: Catalog = {
"This space has no pages.": "此空间没有页面。",
"This space is encrypted. Saves stay encrypted.": "此空间已加密。保存时仍保持加密。",
"This space is locked": "此空间已锁定",
+ "Tip": "提示",
"Type / for blocks, [[ to link a page": "输入 / 插入块,[[ 链接页面",
"Undo (⌘Z)": "撤销 (⌘Z)",
"Unlock": "解锁",
@@ -143,6 +153,7 @@ export const zh_Hans: Catalog = {
"Update this file": "更新此文件",
"Updates": "更新",
"Version {v} is available.": "版本 {v} 可用。",
+ "Warning": "警告",
"Width in the text column": "在正文栏中的宽度",
"Wrong password — try again": "密码错误 — 请重试",
"You have the newest version ({v}).": "你已是最新版本 ({v})。",
@@ -158,4 +169,51 @@ export const zh_Hans: Catalog = {
"Image from {host}": "来自 {host} 的图片",
"Not loaded — opening it would tell that site you opened this space.": "未加载 — 加载会让该网站知道你打开了这个空间。",
"Load this image": "加载此图片",
+ "New page": "新建页面",
+ "Redo": "重做",
+ "Reading view": "阅读视图",
+ "The pages without the editing tools": "不带编辑工具的页面",
+ "Version, language, password, exports": "版本、语言、密码、导出",
+ "More": "更多",
+ "Copy saved — you are still editing the original": "副本已保存 — 你仍在编辑原文件",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "这是一份阅读副本。它以阅读方式打开;你在此处的操作不会更改文件。",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "一个装满 .md 文件的文件夹会变成页面,文件夹层级和 [[wiki 链接]] 都保留下来。",
+ "Bring notes in": "把笔记带进来",
+ "Choose .md files…": "选择 .md 文件…",
+ "Choose a folder…": "选择文件夹…",
+ "Drop .md files or a folder here": "把 .md 文件或文件夹拖到这里",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "每个 .md 文件变成一个页面,文件夹变成页面树,[[wiki 链接]] 变成真正的链接。页面是新增的——已有内容不会被替换。",
+ "Image not imported": "图片未导入",
+ "Import Markdown": "导入 Markdown",
+ "Import Markdown files or a folder…": "导入 Markdown 文件或文件夹…",
+ "Import Markdown…": "导入 Markdown…",
+ "Imported": "已导入",
+ "Imported notes": "导入的笔记",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "把图片文件一起选上,它们也会被嵌入。这个浏览器打不开的图片会以路径的形式保留,而不是一张坏掉的图。",
+ "No Markdown files in that selection": "所选内容里没有 Markdown 文件",
+ "Reading {n} file(s)…": "正在读取 {n} 个文件…",
+ "That is {n} files — importing them all may take a moment. Continue?": "一共 {n} 个文件,全部导入需要一点时间。继续吗?",
+ "This file is open read-only": "这个文件以只读方式打开",
+ "Those files could not be read": "这些文件无法读取",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} 张图片打不开,它们的路径以文字保留。请把图片文件一并选上再导入一次。",
+ "{n} image(s) embedded ({size}).": "已嵌入 {n} 张图片({size})。",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} 张图片指向网络。在读者主动请求之前不会加载。",
+ "{n} of {total} wikilink(s) resolved.": "{total} 个 wiki 链接中解析了 {n} 个。",
+ "The rest name notes that were not in the selection, and are left as text.": "其余指向不在所选范围内的笔记,保留为文字。",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} 个页面带有 frontmatter,已原样保存在折叠块里。",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} 个表格按原文保留为文字:这个格式还没有表格块。",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "从 {files} 个文件新增了 {pages} 个页面、{blocks} 个块。",
+ "⌘Z removes the imported pages again.": "按 ⌘Z 可以把导入的页面再撤销掉。",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "这些笔记里的图片已经有 {size},而且都会随文件一起走。继续嵌入吗?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} 张图片以路径形式保留,因为嵌入到此为止。",
+ "About bento/spaces — version, updates, language, password": "关于 bento/spaces — 版本、更新、语言、密码",
+ "Unsaved changes — ⌘S rewrites this file": "未保存的更改 — ⌘S 会重写此文件",
+ "Unsaved changes — ⌘S downloads an updated copy": "未保存的更改 — ⌘S 会下载更新后的副本",
+ "format v{v}": "格式 v{v}",
+ "Visit bento.page (opens in a new tab)": "访问 bento.page(在新标签页打开)",
+ "Drag to resize · double-click to reset": "拖动可调整宽度 · 双击恢复默认",
+ "Show the page list ([)": "显示页面列表([)",
+ "Hide the page list ([)": "隐藏页面列表([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "有 {n} 个笔记名称重复,因此指向该名称的链接都指向了第一个。",
}
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index be693a54..5366ee16 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -23,6 +23,9 @@ export const zh_Hant: Catalog = {
"Archived ({n})": "已封存 ({n})",
"Block options": "區塊選項",
"Breadcrumb": "階層路徑",
+ "Callout icon": "標註圖示",
+ "Caution": "當心",
+ "Change the kind of callout": "變更標註類型",
"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.": "檢查是手動且經過驗證的:下載的檔案帶有簽章,在改寫任何內容之前,都會用此檔案內的金鑰驗證該簽章。",
@@ -55,14 +58,18 @@ export const zh_Hant: Catalog = {
"Find": "尋找",
"Find in this space…": "在此空間尋找…",
"Find or create a page…": "尋找或建立頁面…",
+ "Icon": "圖示",
"Image added ({size})": "已新增圖片 ({size})",
"Image added, resized to fit ({from} → {to})": "已新增圖片,已縮小尺寸 ({from} → {to})",
+ "Important": "重要",
"Include archived pages": "包含已封存的頁面",
"Insert": "插入",
"Insert a block — text, headings, lists, code, images": "插入區塊 — 文字、標題、清單、程式碼、圖片",
"Interface language": "介面語言",
"Language": "語言",
+ "Language — what this block is highlighted as": "語言 — 這個區塊以什麼語言上色",
"Language follows whoever opens the file. It is never written into the document.": "語言取決於開啟檔案的人,永遠不會寫入文件中。",
+ "Leave it empty to use the tone mark": "留空則使用該類型的標記",
"Link to page": "連結到頁面",
"Linked from": "連結來源",
"Links to it become dead": "指向它的連結會失效",
@@ -71,6 +78,7 @@ export const zh_Hant: Catalog = {
"Next (⏎)": "下一個 (⏎)",
"No block matches": "沒有符合的區塊",
"No pages yet": "尚無頁面",
+ "Note": "備註",
"Nothing found": "找不到結果",
"Off by default — they were archived for a reason": "預設關閉 — 它們被封存是有原因的",
"Other ways to save": "其他儲存方式",
@@ -82,6 +90,7 @@ export const zh_Hant: Catalog = {
"Password removed. Save to write the space unencrypted.": "已移除密碼。儲存後空間將以未加密方式寫入。",
"Password set. Save to write the space encrypted.": "已設定密碼。儲存後空間將以加密方式寫入。",
"Password…": "密碼…",
+ "Plain text": "純文字",
"Previous (⇧⏎)": "上一個 (⇧⏎)",
"Print": "列印",
"Print / PDF…": "列印 / PDF…",
@@ -134,6 +143,7 @@ export const zh_Hant: Catalog = {
"This space has no pages.": "此空間沒有任何頁面。",
"This space is encrypted. Saves stay encrypted.": "此空間已加密。往後的儲存也會維持加密。",
"This space is locked": "此空間已鎖定",
+ "Tip": "提示",
"Type / for blocks, [[ to link a page": "輸入 / 插入區塊,輸入 [[ 連結頁面",
"Undo (⌘Z)": "還原 (⌘Z)",
"Unlock": "解鎖",
@@ -143,6 +153,7 @@ export const zh_Hant: Catalog = {
"Update this file": "更新此檔案",
"Updates": "更新",
"Version {v} is available.": "版本 {v} 可用。",
+ "Warning": "警告",
"Width in the text column": "相對於文字欄的寬度",
"Wrong password — try again": "密碼錯誤 — 請重試",
"You have the newest version ({v}).": "你已是最新版本 ({v})。",
@@ -158,4 +169,51 @@ export const zh_Hant: Catalog = {
"Image from {host}": "來自 {host} 的圖片",
"Not loaded — opening it would tell that site you opened this space.": "未載入 — 載入會讓該網站知道你開啟了這個空間。",
"Load this image": "載入此圖片",
+ "New page": "新增頁面",
+ "Redo": "重做",
+ "Reading view": "閱讀檢視",
+ "The pages without the editing tools": "不含編輯工具的頁面",
+ "Version, language, password, exports": "版本、語言、密碼、匯出",
+ "More": "更多",
+ "Copy saved — you are still editing the original": "副本已儲存 — 你仍在編輯原始檔案",
+ "This is a reading copy. It opens for reading; nothing you do here changes the file.": "這是一份閱讀副本。它以閱讀方式開啟;你在此處的操作不會變更檔案。",
+ // markdown import
+ "A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": "一個裝滿 .md 檔案的資料夾會變成頁面,資料夾層級和 [[wiki 連結]] 都會保留。",
+ "Bring notes in": "把筆記帶進來",
+ "Choose .md files…": "選擇 .md 檔案…",
+ "Choose a folder…": "選擇資料夾…",
+ "Drop .md files or a folder here": "把 .md 檔案或資料夾拖到這裡",
+ "Each .md file becomes a page, folders become the page tree, and [[wikilinks]] become real links. Pages are added — nothing here is replaced.": "每個 .md 檔案變成一個頁面,資料夾變成頁面樹,[[wiki 連結]] 變成真正的連結。頁面是新增的——既有內容不會被取代。",
+ "Image not imported": "圖片未匯入",
+ "Import Markdown": "匯入 Markdown",
+ "Import Markdown files or a folder…": "匯入 Markdown 檔案或資料夾…",
+ "Import Markdown…": "匯入 Markdown…",
+ "Imported": "已匯入",
+ "Imported notes": "匯入的筆記",
+ "Include the image files and they are embedded too. An image this browser cannot open is kept as its path rather than as a broken picture.": "把圖片檔案一起選取,它們也會一併嵌入。這個瀏覽器打不開的圖片會以路徑的形式保留,而不是一張破圖。",
+ "No Markdown files in that selection": "所選項目中沒有 Markdown 檔案",
+ "Reading {n} file(s)…": "正在讀取 {n} 個檔案…",
+ "That is {n} files — importing them all may take a moment. Continue?": "共 {n} 個檔案,全部匯入需要一點時間。要繼續嗎?",
+ "This file is open read-only": "這個檔案以唯讀方式開啟",
+ "Those files could not be read": "這些檔案無法讀取",
+ "{n} image(s) could not be opened, so their paths are kept as text. Import again with the image files included.": "{n} 張圖片打不開,它們的路徑以文字保留。請連同圖片檔案一起再匯入一次。",
+ "{n} image(s) embedded ({size}).": "已嵌入 {n} 張圖片({size})。",
+ "{n} image(s) point at the web. Nothing loads until a reader asks.": "{n} 張圖片指向網路。在讀者主動要求之前不會載入。",
+ "{n} of {total} wikilink(s) resolved.": "{total} 個 wiki 連結中解析了 {n} 個。",
+ "The rest name notes that were not in the selection, and are left as text.": "其餘指向不在所選範圍內的筆記,保留為文字。",
+ "{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} 個頁面帶有 frontmatter,已原樣保存在摺疊區塊裡。",
+ "{n} table(s) kept as text: there is no table block in this format yet.": "{n} 個表格按原文保留為文字:這個格式還沒有表格區塊。",
+ "{pages} page(s) and {blocks} block(s) added from {files} file(s).": "從 {files} 個檔案新增了 {pages} 個頁面、{blocks} 個區塊。",
+ "⌘Z removes the imported pages again.": "按 ⌘Z 可以把匯入的頁面再撤銷掉。",
+ "The images in these notes come to {size} so far, and they all travel inside the file. Keep embedding them?": "這些筆記裡的圖片已經有 {size},而且都會隨檔案一起走。要繼續嵌入嗎?",
+ "{n} image(s) were left as paths because embedding stopped there.": "{n} 張圖片以路徑形式保留,因為嵌入到此為止。",
+ "About bento/spaces — version, updates, language, password": "關於 bento/spaces — 版本、更新、語言、密碼",
+ "Unsaved changes — ⌘S rewrites this file": "未儲存的變更 — ⌘S 會重寫此檔案",
+ "Unsaved changes — ⌘S downloads an updated copy": "未儲存的變更 — ⌘S 會下載更新後的副本",
+ "format v{v}": "格式 v{v}",
+ "Visit bento.page (opens in a new tab)": "造訪 bento.page(在新分頁開啟)",
+ "Drag to resize · double-click to reset": "拖曳可調整寬度 · 雙擊還原預設",
+ "Show the page list ([)": "顯示頁面清單([)",
+ "Hide the page list ([)": "隱藏頁面清單([)",
+ "{n} note name(s) appear more than once, so links naming them all went to the first.": "有 {n} 個筆記名稱重複,因此指向該名稱的連結都指向了第一個。",
}
diff --git a/spaces/src/icons.ts b/spaces/src/icons.ts
index 9a8a1338..efa46776 100644
--- a/spaces/src/icons.ts
+++ b/spaces/src/icons.ts
@@ -25,8 +25,10 @@ export const ICONS = {
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"/>'),
+ // The suite's undo/redo, character for character from slides. The circular
+ // arrows that were here read as "reload", which is a different promise.
+ undo: svg('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>'),
+ redo: svg('<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>'),
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"/>'),
@@ -35,6 +37,8 @@ export const ICONS = {
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"/>'),
+ chevronLeft: svg('<path d="m15 18-6-6 6-6"/>'),
+ chevronRight: svg('<path d="m9 18 6-6-6-6"/>'),
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"/>'),
@@ -68,6 +72,17 @@ export const ICONS = {
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"/>'),
+ callout: svg('<rect x="3" y="5" width="18" height="14" rx="2"/><line x1="7" y1="5" x2="7" y2="19"/><line x1="11" y1="10" x2="17" y2="10"/><line x1="11" y1="14" x2="15" y2="14"/>'),
+
+ // CALLOUT TONE MARKS — one distinct SILHOUETTE each (circle, bulb, square,
+ // triangle, octagon), because the tone must be readable without colour
+ // vision and on a black-and-white printout. Hue is decoration here; shape and
+ // the spelled-out tone name are what carry the meaning.
+ toneNote: svg('<circle cx="12" cy="12" r="9"/><line x1="12" y1="16" x2="12" y2="11"/><line x1="12" y1="8" x2="12.01" y2="8"/>'),
+ toneTip: svg('<path d="M9 18h6"/><path d="M10 21.5h4"/><path d="M15.1 14c.2-1 .7-1.7 1.4-2.5A4.7 4.7 0 0 0 18 8a6 6 0 0 0-12 0c0 1 .2 2.2 1.5 3.5.7.8 1.2 1.5 1.4 2.5"/>'),
+ toneImportant: svg('<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="12" y1="7.5" x2="12" y2="13"/><line x1="12" y1="16.5" x2="12.01" y2="16.5"/>'),
+ toneWarning: svg('<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/><line x1="12" y1="9.5" x2="12" y2="14"/><line x1="12" y1="17" x2="12.01" y2="17"/>'),
+ toneCaution: svg('<polygon points="7.9 2.5 16.1 2.5 21.5 7.9 21.5 16.1 16.1 21.5 7.9 21.5 2.5 16.1 2.5 7.9"/><line x1="12" y1="7.5" x2="12" y2="12.5"/><line x1="12" y1="16" x2="12.01" y2="16"/>'),
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
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index af2e4fef..5cd9b23a 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -7,15 +7,24 @@
import './styles.css'
import { configureApp, appConfig } from '../../kernel/src/app.ts'
import {
- capturePristine, readEmbeddedDoc, serializeFile, serializeAuto,
+ capturePristine, readEmbeddedDoc, serializeFile, serializeAuto, registerPreview,
saveFile, parseEnvelope, canWriteInPlace, decryptEnvelope, setEncryptionPassword,
+ writeUpdatedFileAs,
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, applyDirection } from './i18n'
-import { parseDoc, docContentKey, uid, type SpacesDoc, type ParseResult } from './model'
+import { parseDoc, docContentKey, uid, newPage, type SpacesDoc, type ParseResult } from './model'
+import {
+ validateDoc, outlineDoc, statsDoc,
+ planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock, planUpdatePage, planRemovePage,
+ plainTitle,
+ type Plan, type PlanError,
+} from './agent'
import { starterDoc } from './starter'
+import { textOf } from './sanitize'
+import { buildSpacePreview } from './preview'
import { Store } from './store'
import { Editor } from './editor'
import { downloadMarkdown } from './about'
@@ -26,6 +35,13 @@ configureApp({
manifestUrl: 'https://bento.page/releases/spaces/manifest.json',
})
+// Every save writes a still render of the home page into the shell, for the
+// readers that run no script: macOS QuickLook, iOS Files, Bento Tray, and any
+// preview pane that renders HTML without executing it. Without this the runtime
+// never inflates, the splash is never removed, and a saved space shows a boot
+// animation where its content should be. See preview.ts.
+registerPreview((doc) => buildSpacePreview(doc as unknown as SpacesDoc))
+
capturePristine()
applyDirection()
@@ -162,9 +178,20 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
document.getElementById('bento-splash')?.remove()
const store = new Store(doc)
- if (frozen) store.readOnly = true
+ // `doc.readonly` was declared in the format and read by NOTHING: a space
+ // saved as a reading copy opened fully editable, so the one property the
+ // sender chose was the one the file did not keep. It is not a security
+ // boundary — anyone can edit the JSON — but a file that says it is a reading
+ // copy must behave like one for the person who opens it.
+ //
+ // `frozen` is the other, unrelated reason to lock: this build does not
+ // understand the file and must not rewrite it.
+ if (frozen || doc.readonly) store.readOnly = true
const editor = new Editor(document.getElementById('app')!, store)
+ if (!frozen && doc.readonly) {
+ banner(t('This is a reading copy. It opens for reading; nothing you do here changes the file.'))
+ }
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.')
@@ -178,17 +205,34 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
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'))
- })
+ // "Save a copy…" must leave you editing the ORIGINAL. That is what the
+ // label promises, and the file you go on typing into should never silently
+ // become the backup you just took.
+ //
+ // This used to call saveFile(doc, true), under a comment claiming the
+ // kernel kept the in-place handle pointed at the working file. It does the
+ // opposite: saveFile ASSIGNS the picked handle to the module's in-place
+ // handle (kernel/src/save.ts), so every later ⌘S wrote to the copy while
+ // the original stayed frozen at the moment it was copied. The guarantee the
+ // comment described lives in writeUpdatedFileAs, whose keepHandle defaults
+ // to false — slides learned the same lesson when a share export became the
+ // ⌘S target and the next save overwrote it with the full document.
+ //
+ // The status line was dead too: saveFile returns 'saved-as' down the
+ // forcePicker path, never 'saved', so the confirmation never appeared.
+ void serializeAuto(store.doc)
+ .then((html) => writeUpdatedFileAs(html, store.doc, { suffix: suffix === 'copy' ? 'copy' : suffix }))
+ .then((ok) => { if (ok) editor.status(t('Copy saved — you are still editing the original')) })
}
async function doSave(): Promise<void> {
store.endRun()
editor.status(t('Saving…'))
const res = await saveFile(store.doc)
+ if (res === 'saved' || res === 'saved-as' || res === 'downloaded') {
+ // the document is on disk now — the dot goes out
+ store.dirty = false
+ editor.syncDirty()
+ }
if (res === 'saved') {
void clearRecovery(store.doc.docId)
// "Saved" is doing real work here: on a browser without file-system
@@ -218,6 +262,22 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
void offerRecovery(doc, store, editor)
// ---- the AI round-trip (PLATFORM §7) -----------------------------------
+ //
+ // Every write verb is ONE undoable step, and every one of them runs its plan
+ // FIRST: `store.commit` checkpoints undo before it mutates, so planning
+ // inside the commit would leave an undo entry behind for a patch that was
+ // refused. A refused patch changes nothing at all, including history.
+ function run<T extends object>(plan: Plan<T>): ({ ok: true } & T) | PlanError {
+ if (store.readOnly) {
+ return { ok: false, err: 'readonly', detail: 'this file is open read-only; nothing was changed' }
+ }
+ if (!plan.ok) return plan
+ const { apply, ...rest } = plan
+ store.commit(apply)
+ editor.repaint()
+ return rest as { ok: true } & T
+ }
+
;(window as any).bento = {
format: doc.format,
get doc() { return store.doc },
@@ -237,38 +297,59 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
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, '')
+ // textOf DECODES entities; a tag-strip does not. On a block reading
+ // "a &amp; b" the old regex searched "a &amp; b", so it missed the
+ // text the reader can see and matched text that is not there.
+ const text = textOf(b.html)
if (text.toLowerCase().includes(needle)) out.push({ pageId: p.id, title: p.title, blockId: b.id })
}
}
return out
},
+ /** what is WRONG or SUSPECT — see agent.ts */
+ validate: (target?: SpacesDoc) => validateDoc(target ?? store.doc),
+ /** the whole space as a tree, for orienting in one call */
+ outline: (target?: SpacesDoc) => outlineDoc(target ?? store.doc),
+ /** where the bytes are */
+ stats: (target?: SpacesDoc) => statsDoc(target ?? store.doc),
+
/**
* 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.
+ *
+ * Keeps its original return shape (new ids, or null) because it shipped
+ * that way; the verbs below it return tagged results.
*/
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)
+ const res = run(planInsertBlocks(store.doc, pageId, afterId ?? null, blocks))
+ return res.ok ? res.ids : null
},
+ updateBlock: (id: string, patch: unknown) => run(planUpdateBlock(store.doc, id, patch)),
+ removeBlocks: (ids: unknown) => run(planRemoveBlocks(store.doc, ids)),
+ moveBlock: (id: string, to: unknown) => run(planMoveBlock(store.doc, id, to)),
+ updatePage: (id: string, patch: unknown) => run(planUpdatePage(store.doc, id, patch)),
+ removePage: (id: string, opts?: { descendants?: boolean }) =>
+ run(planRemovePage(store.doc, id, opts ?? {})),
+
+ /**
+ * A page carries one empty paragraph, exactly as the editor's own New page
+ * does. A page with no blocks has nothing to put a caret in — no gutter, no
+ * / menu, no way to type — so an agent creating one would hand a human a
+ * page they cannot write in.
+ */
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) })
+ if (store.readOnly) return null
+ // a parent that names nothing would silently make this a ROOT page; say
+ // no instead, so the caller finds out now rather than in the sidebar
+ if (parent && !store.doc.pages.some((p) => p.id === parent)) return null
+ const page = newPage(plainTitle(title) || 'Untitled', parent ? { parent } : {})
+ store.commit(() => { store.doc.pages.push(page) })
editor.repaint()
return page.id
},
loadDoc: (json: string): boolean => {
+ if (store.readOnly) return false
const r = parseDoc(json)
if (!r.ok) return false
store.replaceDoc(r.doc)
diff --git a/spaces/src/markdown.ts b/spaces/src/markdown.ts
new file mode 100644
index 00000000..5c645e7d
--- /dev/null
+++ b/spaces/src/markdown.ts
@@ -0,0 +1,682 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Markdown → the bento/spaces block model: how an existing pile of notes
+// becomes a space. Nobody adopts a notes app they cannot get their notes into.
+//
+// PURE, and deliberately DOM-FREE, so the whole of it runs in node under
+// `scripts/test-spaces-model.ts`. The cases that decide whether an Obsidian
+// vault survives the trip — wikilinks across hundreds of files, frontmatter,
+// nested lists, a folder tree — are cheap to assert there and miserable to
+// click through in a browser.
+//
+// IT DOES NOT SANITIZE. Raw inline html is reduced to an allowlisted skeleton
+// here so this module needs no parser; `sanitizeInline` — the app's real
+// policy, with a real one — runs over every block in the importer afterwards.
+// One security gate, in the place that already has the tests for it.
+
+// `.ts` extensions ON PURPOSE: this module is imported directly by
+// `scripts/test-spaces-model.ts`, which node resolves without a bundler.
+import { type Block, type Page, uid } from './model.ts'
+import { esc } from './sanitize.ts'
+
+/** A tab indents four columns. Nothing here depends on the exact number; it
+ * only has to be the same everywhere so nesting is consistent. */
+const TAB = ' '
+
+/** Inline tags a raw html span may keep — sanitize.ts's ALLOWED, minus the
+ * ability to carry attributes. Restated rather than imported because that
+ * module's set is a DOM-side control and this one is a parser convenience;
+ * if they ever diverge, the sanitizer still wins, because it runs last. */
+const INLINE_OK = new Set(['b', 'i', 'u', 's', 'em', 'strong', 'code', 'br', 'span', 'mark', 'sub', 'sup'])
+
+/**
+ * The href a wikilink carries between parsing and resolution.
+ *
+ * `#w/` never reaches a saved document: `resolveWikilinks` rewrites every one
+ * before the blocks are committed, and `sanitizeInline` would strip any that
+ * somehow survived — its allowlist is `https?:`, `mailto:` and `#p/`. So the
+ * worst a bug in resolution can do is lose a link; it can never write one that
+ * points somewhere unexpected.
+ */
+const WIKI_SCHEME = '#w/'
+
+// ---- inline ----------------------------------------------------------------
+
+/** One raw html tag, reduced to what the model allows, or null to drop it. */
+function cleanRawTag(tag: string): string | null {
+ const m = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)([^>]*?)\/?>$/.exec(tag)
+ if (!m) return null
+ const close = m[1] === '/'
+ const name = m[2].toLowerCase()
+ if (name === 'a') {
+ if (close) return '</a>'
+ const h = /href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[3])
+ const url = (h?.[1] ?? h?.[2] ?? h?.[3] ?? '').trim()
+ return /^(https?:|mailto:)/i.test(url) ? `<a href="${esc(url)}">` : null
+ }
+ if (!INLINE_OK.has(name)) return null
+ return close ? `</${name}>` : `<${name}>`
+}
+
+/**
+ * Inline markdown → inline html.
+ *
+ * Everything this emits as MARKUP is parked in a placeholder first, so the
+ * final pass can escape the whole remaining string in one go: text the author
+ * typed can never turn into a tag, and a tag we generated can never be
+ * double-escaped. Placeholders are `\u0000<n>\u0000` — digits, so they survive
+ * escaping untouched, and the input's own NULs are dropped up front.
+ */
+export function inlineHtml(src: string): string {
+ const held: string[] = []
+ const hold = (html: string): string => `\u0000${held.push(html) - 1}\u0000`
+ let s = src.replace(/\u0000/g, '')
+
+ // code spans first: their content is literal, so nothing below may see it
+ s = s.replace(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g, (_m, _t, code: string) =>
+ hold(`<code>${esc(code.replace(/^ (.*) $/, '$1'))}</code>`))
+
+ // backslash escapes — held as text so the marker cannot re-trigger below
+ s = s.replace(/\\([\\`*_{}[\]()#+\-.!~>|=])/g, (_m, ch: string) => hold(esc(ch)))
+
+ // <https://…> before the raw-tag sweep, which would otherwise eat it
+ // DISPLAY TEXT IS NOT ESCAPED HERE.
+ //
+ // Everything a hold() placeholder protects is final markup and must carry its
+ // own escaping. Everything OUTSIDE a placeholder is ordinary text, and the
+ // single esc(s) at the end of this function escapes all of it exactly once.
+ // Escaping display text here too ran it through twice: `[Q&A](…)` was written
+ // into the file as `Q&amp;amp;A`, and the reader saw the entity. Bold, italic
+ // and code were never affected — their text stays outside any placeholder —
+ // which is why a spot-check of "inline formatting survived" passed.
+ s = s.replace(/<((?:https?|mailto):[^>\s]+)>/gi, (_m, url: string) =>
+ hold(`<a href="${esc(url)}">`) + url + hold('</a>'))
+
+ // Raw inline html. A `</a>` is only kept when an `<a>` was kept: dropping a
+ // link whose href we refuse (javascript:, obsidian:) must not leave its
+ // closing tag behind for the sanitizer to trip over.
+ let openA = 0
+ s = s.replace(/<\/?[a-zA-Z][^<>]*>/g, (tag) => {
+ const ok = cleanRawTag(tag)
+ if (!ok) return ''
+ if (ok === '</a>' && openA === 0) return ''
+ if (ok.startsWith('<a ')) openA++
+ else if (ok === '</a>') openA--
+ return hold(ok)
+ })
+
+ // ![[embed]] and [[wikilink|alias]] before ordinary links: an embed of a
+ // note is just a link to it, because there is no transclusion in the model
+ s = s.replace(/!?\[\[([^\]]+)\]\]/g, (_m, inner: string) => {
+ const [target, alias] = splitOnce(inner, '|')
+ return hold(`<a href="${WIKI_SCHEME}${encodeURIComponent(target.trim())}">`) +
+ (alias ?? target).trim() + hold('</a>')
+ })
+
+ // an inline image cannot be a block, and the model has no inline <img>: keep
+ // the alt text, and keep the address as a link when there is one to follow
+ s = s.replace(/!\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"[^"]*")?\s*\)/g,
+ (_m, alt: string, url: string) => /^(https?:|data:)/i.test(url)
+ ? hold(`<a href="${esc(url)}">`) + (alt || url) + hold('</a>')
+ : (alt || url))
+
+ // A link whose address the model cannot keep (relative paths, `obsidian://`,
+ // `file:`) is left as the markdown the author wrote, address and all. The
+ // sanitizer would strip such an href anyway, and text that still says where
+ // it pointed beats a link that silently lost its destination.
+ s = s.replace(/\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"[^"]*")?\s*\)/g,
+ (m: string, text: string, url: string) =>
+ /^(https?:|mailto:)/i.test(url)
+ ? hold(`<a href="${esc(url)}">`) + text + hold('</a>')
+ : m)
+
+ s = s.replace(/~~([\s\S]+?)~~/g, (_m, x: string) => hold('<s>') + x + hold('</s>'))
+ s = s.replace(/==([\s\S]+?)==/g, (_m, x: string) => hold('<mark>') + x + hold('</mark>'))
+ s = s.replace(/\*\*(?=\S)([\s\S]+?)\*\*/g, (_m, x: string) => hold('<strong>') + x + hold('</strong>'))
+ s = s.replace(/(^|[^\w\\])__(?=\S)([\s\S]+?)__(?!\w)/g,
+ (_m, pre: string, x: string) => pre + hold('<strong>') + x + hold('</strong>'))
+ s = s.replace(/(^|[^*\w])\*(?=\S)([^*]+?)\*/g,
+ (_m, pre: string, x: string) => pre + hold('<em>') + x + hold('</em>'))
+ // `_` only outside a word, or snake_case_identifiers become italics
+ s = s.replace(/(^|[^\w\\])_(?=\S)([^_]+?)_(?!\w)/g,
+ (_m, pre: string, x: string) => pre + hold('<em>') + x + hold('</em>'))
+
+ return esc(s).replace(/\u0000(\d+)\u0000/g, (_m, n: string) => held[Number(n)])
+}
+
+/** Inline markdown → plain text, for titles (a page title is text, not html). */
+export function plainText(src: string): string {
+ return src
+ .replace(/!?\[\[([^\]|]+)(?:\|([^\]]*))?\]\]/g, (_m, t: string, a: string) => a ?? t)
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/[*_~`]+/g, '')
+ .replace(/^#+\s*/, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+const splitOnce = (s: string, sep: string): [string, string | undefined] => {
+ const i = s.indexOf(sep)
+ return i < 0 ? [s, undefined] : [s.slice(0, i), s.slice(i + sep.length)]
+}
+
+// ---- one note --------------------------------------------------------------
+
+export interface PendingImage {
+ /** the image block, by reference — the importer rewrites it in place */
+ block: Block
+ /** the address exactly as the note wrote it */
+ ref: string
+ /** the folder the note lived in, for resolving a relative address */
+ dir: string
+}
+
+export interface ParsedNote {
+ title: string
+ blocks: Block[]
+ /** the YAML between the leading `---` fences, verbatim */
+ frontmatter?: string
+ images: PendingImage[]
+ /** images pointing at the web: kept, but not loaded until a reader asks */
+ remoteImages: number
+ /** markdown tables, which this model has no block for yet */
+ tables: number
+}
+
+const mk = (type: string, extra: Partial<Block> = {}): Block => ({ id: uid('b'), type, ...extra })
+
+const IMG_LINE = /^!\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"([^"]*)")?\s*\)$/
+const IMG_EMBED = /^!\[\[([^\]|]+)(?:\|[^\]]*)?\]\]$/
+const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i
+
+/** A line that is nothing but an image. `![[x]]` counts only when it names an
+ * image FILE — otherwise it is an embed of another note, which is a link. */
+function imageOf(line: string): { ref: string; alt: string; caption?: string } | null {
+ const m = IMG_LINE.exec(line.trim())
+ if (m) return { ref: m[2], alt: m[1], ...(m[3] ? { caption: m[3] } : {}) }
+ const e = IMG_EMBED.exec(line.trim())
+ if (e && IMAGE_EXT.test(e[1].trim())) return { ref: e[1].trim(), alt: '' }
+ return null
+}
+
+/**
+ * One markdown file → one page's worth of blocks.
+ *
+ * THE TITLE RULE, which has to be predictable above all else: a leading
+ * `# Heading` becomes the page title AND is removed from the body; otherwise
+ * the file name without its extension is the title. Frontmatter is NOT
+ * consulted for it — wikilinks resolve by FILE NAME, so a title taken from a
+ * `title:` key that disagreed with the file name would leave `[[Note]]`
+ * pointing at a page whose name is nowhere in the sidebar.
+ */
+export function parseNote(text: string, fileTitle: string): ParsedNote {
+ const lines = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').split('\n')
+ const blocks: Block[] = []
+ const images: PendingImage[] = []
+ let remoteImages = 0
+ let tables = 0
+ let frontmatter: string | undefined
+ let i = 0
+
+ if (lines[0]?.trim() === '---') {
+ for (let j = 1; j < lines.length; j++) {
+ if (/^(---|\.\.\.)\s*$/.test(lines[j])) {
+ frontmatter = lines.slice(1, j).join('\n')
+ i = j + 1
+ break
+ }
+ }
+ }
+
+ let title = ''
+ {
+ let j = i
+ while (j < lines.length && !lines[j].trim()) j++
+ const m = /^ {0,3}#\s+(.+?)\s*#*$/.exec(lines[j] ?? '')
+ if (m) { title = plainText(m[1]); i = j + 1 }
+ }
+
+ /** open list levels, innermost last */
+ const stack: Array<{ indent: number; id: string }> = []
+ /** the paragraph a soft line break continues, and the quote a `>` continues */
+ let para: Block | null = null
+ let quote: Block | null = null
+
+ const ownerFor = (indent: number): string | undefined => {
+ while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()
+ return stack[stack.length - 1]?.id || undefined
+ }
+ const add = (b: Block, parent?: string): Block => {
+ if (parent) b.parent = parent
+ blocks.push(b)
+ return b
+ }
+ // NOT model.isRemote(): that answers "would loading this touch the network",
+ // where a relative path counts as remote. The question here is different —
+ // "could a file the user picked satisfy this address" — and a relative path
+ // is the one case where the answer is yes.
+ const imageBlock = (ref: string, alt: string, caption: string | undefined, parent?: string) => {
+ const b = mk('image', { src: ref, ...(alt ? { alt } : {}), ...(caption ? { caption } : {}) })
+ add(b, parent)
+ if (/^(https?:)?\/\//i.test(ref)) remoteImages++
+ else if (!/^data:/i.test(ref)) images.push({ block: b, ref, dir: '' })
+ return b
+ }
+
+ for (; i < lines.length; i++) {
+ const line = lines[i].replace(/\t/g, TAB)
+ const indent = /^ */.exec(line)![0].length
+ const body = line.slice(indent).trimEnd()
+
+ if (!body) { para = null; quote = null; continue }
+
+ // fenced code — taken whole, so nothing inside is interpreted
+ const fence = /^(`{3,}|~{3,})\s*(\S*)/.exec(body)
+ if (fence) {
+ para = null; quote = null
+ const owner = ownerFor(indent)
+ const mark = fence[1][0]
+ const buf: string[] = []
+ let j = i + 1
+ for (; j < lines.length; j++) {
+ const t = lines[j].trim()
+ if (t.length >= 3 && t[0] === mark && t === mark.repeat(t.length)) break
+ buf.push(lines[j].startsWith(' '.repeat(indent)) ? lines[j].slice(indent) : lines[j])
+ }
+ i = j
+ add(mk('code', { html: esc(buf.join('\n')), ...(fence[2] ? { lang: fence[2].toLowerCase() } : {}) }), owner)
+ continue
+ }
+
+ // A TABLE has no block type in this model yet, and turning one into
+ // paragraphs shreds it. Kept verbatim in a code block instead: aligned,
+ // searchable, exportable, and mechanically upgradable the day a table
+ // block ships. Losing the data to make it look tidier is not a trade.
+ if (body.includes('|') && isTableRule(lines[i + 1])) {
+ para = null; quote = null
+ const owner = ownerFor(indent)
+ const buf = [body]
+ let j = i + 1
+ for (; j < lines.length && lines[j].includes('|'); j++) buf.push(lines[j].trim())
+ i = j - 1
+ tables++
+ add(mk('code', { html: esc(buf.join('\n')) }), owner)
+ continue
+ }
+
+ // setext: `===` under a paragraph promotes it. `---` deliberately does NOT
+ // — in a folder of notes a lone rule is a divider far more often than it
+ // is a heading, and silently eating the line above it is unforgivable.
+ if (para && /^=+$/.test(body)) { para.type = 'h1'; para = null; continue }
+
+ if (/^([-*_])\s*(?:\1\s*){2,}$/.test(body)) {
+ para = null; quote = null
+ add(mk('divider'), ownerFor(indent))
+ continue
+ }
+
+ const head = /^(#{1,6})\s+(.*?)\s*#*$/.exec(body)
+ if (head) {
+ para = null; quote = null
+ // h4–h6 land on h3: the model has three heading levels, and dropping a
+ // deep heading to a paragraph would lose the outline entirely
+ add(mk(`h${Math.min(head[1].length, 3)}`, { html: inlineHtml(head[2]) }), ownerFor(indent))
+ continue
+ }
+
+ const q = /^>\s?(.*)$/.exec(body)
+ if (q) {
+ para = null
+ const text = inlineHtml(q[1].replace(/^[>\s]+/, ''))
+ if (quote) quote.html = `${quote.html}<br>${text}`
+ else quote = add(mk('quote', { html: text }), ownerFor(indent))
+ continue
+ }
+ quote = null
+
+ const item = /^([-*+]|\d{1,9}[.)])(?:\s+(.*)|\s*)$/.exec(body)
+ if (item) {
+ para = null
+ const owner = ownerFor(indent)
+ const text = item[2] ?? ''
+ const todo = /^\[([ xX])\]\s*(.*)$/.exec(text)
+ const pic = imageOf(text)
+ const block = todo
+ ? add(mk('todo', { html: inlineHtml(todo[2]), done: todo[1] !== ' ' }), owner)
+ : pic
+ ? imageBlock(pic.ref, pic.alt, pic.caption, owner)
+ : add(mk(/^\d/.test(item[1]) ? 'number' : 'bullet', { html: inlineHtml(text) }), owner)
+ // An IMAGE is not a container and holds no text, so it is neither a
+ // continuation target nor a parent.
+ //
+ // It was both. A continuation line did `${para.html}<br>${text}` against a
+ // block with no html, writing the literal string "undefined" into the
+ // document and hiding the author's line — invisible in the editor, the
+ // reading view, print and the markdown export, but there in the saved
+ // file and findable by search. `- ![[pic.png]]` with an indented caption
+ // is an ordinary Obsidian shape.
+ //
+ // Pushing the image's OWNER (not the image) keeps the caption a SIBLING
+ // of the image, under the same list item. Parenting it to the image would
+ // leave the model saying nested while the renderer, which only opens a
+ // body for a registered container, draws it at root.
+ stack.push({ indent, id: pic ? (owner ?? '') : block.id })
+ para = pic ? null : block
+ continue
+ }
+
+ const pic = imageOf(body)
+ if (pic) {
+ para = null
+ imageBlock(pic.ref, pic.alt, pic.caption, ownerFor(indent))
+ continue
+ }
+
+ // a plain line: a continuation of the block above, or a new paragraph.
+ //
+ // A SOFT LINE BREAK BECOMES <br> rather than a space. Notes are written
+ // with the line breaks the author put there (addresses, verse, one-line
+ // facts), and joining them into a paragraph is not reversible — while
+ // keeping them is, by deleting the break.
+ const text = inlineHtml(body)
+ if (para) para.html = `${para.html}<br>${text}`
+ else para = add(mk('p', { html: text }), ownerFor(indent))
+ }
+
+ return {
+ title: title || fileTitle,
+ blocks,
+ ...(frontmatter !== undefined ? { frontmatter } : {}),
+ images,
+ remoteImages,
+ tables,
+ }
+}
+
+/** `|---|:--:|` — the row that makes the line above it a table header. */
+function isTableRule(line: string | undefined): boolean {
+ if (!line) return false
+ const t = line.trim()
+ return t.includes('-') && t.includes('|') && /^\|?[\s:|-]+$/.test(t)
+}
+
+// ---- a folder of notes -----------------------------------------------------
+
+export interface SourceFile {
+ /** path relative to the import root, `/` separated (webkitRelativePath) */
+ path: string
+ text: string
+}
+
+export interface ImportStats {
+ files: number
+ pages: number
+ blocks: number
+ /** `[[wikilinks]]` that found a page in this import */
+ linked: number
+ /** …and those that named a note that was not in the selection */
+ dangling: number
+ frontmatter: number
+ /** notes that shared a NAME with an earlier one, so links to them resolved to
+ * the first — the reader is told rather than left to find out */
+ duplicateNames: number
+ tables: number
+ remoteImages: number
+}
+
+export interface ImportPlan {
+ pages: Page[]
+ /** local image references, still to be resolved against picked files */
+ images: PendingImage[]
+ stats: ImportStats
+}
+
+const normalizePath = (p: string): string =>
+ p.replace(/\\/g, '/').replace(/^\.?\//, '').replace(/\/+/g, '/').trim()
+
+const dirOf = (p: string): string => p.slice(0, Math.max(0, p.lastIndexOf('/')))
+const fileOf = (p: string): string => p.slice(p.lastIndexOf('/') + 1)
+const stemOf = (p: string): string => fileOf(p).replace(/\.[^.]+$/, '')
+const lastSeg = (p: string): string => p.slice(p.lastIndexOf('/') + 1)
+
+/**
+ * Many notes → the pages of a space, with the folder tree rebuilt.
+ *
+ * Pure: no files are read here and no ids leave this document, so the whole
+ * plan can be asserted in node. The caller does the two things that need a
+ * browser — reading image bytes, and running the sanitizer — and then commits
+ * the pages in ONE step.
+ */
+export function planImport(
+ files: SourceFile[],
+ opts: {
+ rootTitle: string
+ /**
+ * Pages the space ALREADY has, by title — consulted only after the import's
+ * own index misses.
+ *
+ * Order matters and it is this way round on purpose: a vault imported whole
+ * must link to itself, never to a stranger page that happens to share a
+ * title. But someone adding one note to a space they have been keeping for
+ * a year expects `[[Home]]` to mean their Home, and without this it would
+ * arrive as dead text.
+ */
+ resolveExisting?: (target: string) => string | undefined
+ },
+): ImportPlan {
+ const src = files
+ .map((f) => ({ path: normalizePath(f.path), text: f.text }))
+ .filter((f) => f.path)
+ .sort((a, b) => a.path.localeCompare(b.path))
+
+ // A picked FOLDER already has a common first segment, and that folder is the
+ // root of the tree — so only a flat, mixed selection needs a container page
+ // invented for it. Either way the import lands under exactly one new root:
+ // it is undoable in one step and deletable in one gesture.
+ const tops = new Set(src.map((f) => (f.path.includes('/') ? f.path.split('/')[0] : '')))
+ const wrap = src.length > 1 && !(tops.size === 1 && !tops.has(''))
+
+ const pages: Page[] = []
+ const images: PendingImage[] = []
+ const stats: ImportStats = {
+ files: src.length, pages: 0, blocks: 0, linked: 0, dangling: 0,
+ frontmatter: 0, tables: 0, remoteImages: 0, duplicateNames: 0,
+ }
+
+ let rootId: string | undefined
+ if (wrap) {
+ const root: Page = { id: uid('p'), title: opts.rootTitle, icon: 'folder', blocks: [] }
+ pages.push(root)
+ rootId = root.id
+ }
+
+ // A folder note — `Notes/Notes.md` or `Notes/index.md` — IS the folder's
+ // page rather than a child of an empty one. That convention is what Obsidian
+ // and Foam vaults use for a section's overview, and importing it as a
+ // sibling of its own subtree reads as a mistake.
+ const folderNote = new Map<string, string>()
+ for (const f of src) {
+ const dir = dirOf(f.path)
+ if (!dir) continue
+ const stem = stemOf(f.path).toLowerCase()
+ if (stem === 'index' || stem === lastSeg(dir).toLowerCase()) {
+ if (!folderNote.has(dir)) folderNote.set(dir, f.path)
+ }
+ }
+
+ // A folder note falls back to the FOLDER's name, not the file's: measured on
+ // a real vault, `Meetings/index.md` otherwise titles the whole section
+ // "index". Its own `# Heading` still wins, as everywhere else.
+ const parsed = new Map<string, ParsedNote>()
+ for (const f of src) {
+ const dir = dirOf(f.path)
+ const fallback = folderNote.get(dir) === f.path ? lastSeg(dir) : stemOf(f.path)
+ parsed.set(f.path, parseNote(f.text, fallback))
+ }
+
+ // directories first, parents before children, so `parent` always resolves
+ const dirs = new Set<string>()
+ for (const f of src) {
+ for (let d = dirOf(f.path); d; d = dirOf(d)) dirs.add(d)
+ }
+ const dirPage = new Map<string, Page>()
+ for (const dir of [...dirs].sort()) {
+ const note = folderNote.get(dir)
+ const page: Page = note
+ ? { id: uid('p'), title: parsed.get(note)!.title, icon: 'folder', blocks: [] }
+ : { id: uid('p'), title: lastSeg(dir), icon: 'folder', blocks: [] }
+ const parent = dirPage.get(dirOf(dir))?.id ?? rootId
+ if (parent) page.parent = parent
+ dirPage.set(dir, page)
+ pages.push(page)
+ }
+
+ const filePage = new Map<string, Page>()
+ for (const f of src) {
+ const dir = dirOf(f.path)
+ if (folderNote.get(dir) === f.path) { filePage.set(f.path, dirPage.get(dir)!); continue }
+ const page: Page = { id: uid('p'), title: parsed.get(f.path)!.title, blocks: [] }
+ const parent = dirPage.get(dir)?.id ?? rootId
+ if (parent) page.parent = parent
+ filePage.set(f.path, page)
+ pages.push(page)
+ }
+
+ // ---- fill the pages ------------------------------------------------------
+ for (const f of src) {
+ const note = parsed.get(f.path)!
+ const page = filePage.get(f.path)!
+ const dir = dirOf(f.path)
+
+ if (note.frontmatter !== undefined) {
+ stats.frontmatter++
+ page.blocks.push(...frontmatterBlocks(note.frontmatter))
+ }
+ page.blocks.push(...note.blocks)
+ for (const img of note.images) images.push({ ...img, dir })
+ stats.tables += note.tables
+ stats.remoteImages += note.remoteImages
+ }
+
+ // ---- wikilinks, once every page exists ----------------------------------
+ const { index, collisions } = linkIndex(src, parsed, filePage, tops.size === 1 ? [...tops][0] : '')
+ for (const page of pages) {
+ for (const b of page.blocks) {
+ if (!b.html) continue
+ const r = resolveWikilinks(b.html, (target) =>
+ index.get(linkKey(target)) ?? opts.resolveExisting?.(linkKey(target)))
+ b.html = r.html
+ stats.linked += r.linked
+ stats.dangling += r.dangling
+ }
+ }
+
+ // NO PAGE ARRIVES WITH ZERO BLOCKS.
+ //
+ // A folder without a folder note, an empty .md, and the invented root all
+ // produced one — and the importer then navigates to plan.pages[0], which in a
+ // real vault IS a folder page. A zero-block page has no editable host, no
+ // gutter and no `/` menu, so the first thing you saw after importing a vault
+ // was a page you could not put a caret in, permanently: nothing ever adds a
+ // block to a folder page.
+ //
+ // The editor cannot produce this state (mergeBack refuses to remove the last
+ // block) and validate() grades it `error`. DECISIONS.md recorded the
+ // invariant against the editor; the importer landed in the same tree and
+ // broke it, which is exactly the kind of gap parallel work opens.
+ for (const p of pages) if (!p.blocks.length) p.blocks.push(mk('p', { html: '' }))
+
+ for (const p of pages) stats.blocks += p.blocks.length
+ stats.duplicateNames = collisions
+ stats.pages = pages.length
+ return { pages, images, stats }
+}
+
+/**
+ * WHERE FRONTMATTER GOES, and this is a permanent decision because it is in
+ * every file an import writes: verbatim, into a `code` block marked
+ * `frontmatter: true`, folded inside a toggle so it does not shout from the
+ * top of every page.
+ *
+ * NOT parsed into fields. Spaces has no properties model yet, and a properties
+ * model designed here — in an importer, from whatever keys one person's vault
+ * happens to use — would pre-empt the real design and be impossible to change,
+ * because the shape would already be in files on disks. Nothing is interpreted
+ * and nothing is lost: the yaml is still exactly the author's text, it is
+ * searchable, it prints (toggles always print open), it exports back out as a
+ * fenced yaml block, and `frontmatter: true` is the marker that makes adopting
+ * these into real properties a mechanical sweep on the day that ships.
+ */
+function frontmatterBlocks(yaml: string): Block[] {
+ const fold = mk('toggle', { html: 'Frontmatter', open: false })
+ const body = mk('code', { html: esc(yaml), lang: 'yaml', frontmatter: true, parent: fold.id })
+ return [fold, body]
+}
+
+/** Everything a `[[wikilink]]` may name, lowercased. First writer wins, so the
+ * result does not depend on the order a file picker happened to hand us. */
+function linkIndex(
+ src: SourceFile[],
+ parsed: Map<string, ParsedNote>,
+ filePage: Map<string, Page>,
+ root: string,
+): { index: Map<string, string>; collisions: number } {
+ const index = new Map<string, string>()
+ // Two notes can share a NAME in different folders, and a [[wikilink]] names
+ // only the name. First one wins — which is the standard behaviour and the
+ // only thing a bare name CAN mean — but it must be reported: silently, every
+ // link to the second note pointed at the first, including that note's links
+ // to ITSELF, and the import claimed unqualified success. Counted here and
+ // surfaced in the summary, so the reader knows which links to check.
+ const collisions = new Set<string>()
+ const put = (k: string, id: string) => {
+ const key = linkKey(k)
+ if (key && index.has(key) && index.get(key) !== id) collisions.add(key)
+ if (key && !index.has(key)) index.set(key, id)
+ }
+ for (const f of src) {
+ const id = filePage.get(f.path)!.id
+ put(stemOf(f.path), id) // [[Note]]
+ put(f.path.replace(/\.[^.]+$/, ''), id) // [[folder/Note]]
+ if (root && f.path.startsWith(`${root}/`)) {
+ put(f.path.slice(root.length + 1).replace(/\.[^.]+$/, ''), id) // vault-relative
+ }
+ put(parsed.get(f.path)!.title, id) // [[The title]]
+ }
+ return { index, collisions: collisions.size }
+}
+
+/** Wikilink targets ignore case, a `.md` suffix, and a `#heading`/`^block`
+ * anchor — the model has no in-page anchors, so those land on the page. */
+const linkKey = (raw: string): string =>
+ raw.replace(/^\.?\//, '').replace(/[#^].*$/, '').replace(/\.(md|markdown)$/i, '')
+ .trim().toLowerCase()
+
+export interface Resolution { html: string; linked: number; dangling: number }
+
+/**
+ * Turn the parser's `#w/` placeholders into real `#p/<id>` links.
+ *
+ * A target that is not in this import stays as the literal `[[Name]]` the
+ * author wrote: honest, searchable, and still correct markdown if it is
+ * exported again — and it resolves for real if the missing note is imported
+ * later and the author re-links it. A silent unlink would be a lie about what
+ * the file said.
+ */
+export function resolveWikilinks(html: string, lookup: (target: string) => string | undefined): Resolution {
+ let linked = 0
+ let dangling = 0
+ const out = html.replace(
+ /<a href="#w\/([^"]*)">([\s\S]*?)<\/a>/g,
+ (_m, enc: string, text: string) => {
+ let target = enc
+ try { target = decodeURIComponent(enc) } catch { /* keep the raw form */ }
+ const id = lookup(target)
+ if (id) { linked++; return `<a href="#p/${esc(id)}">${text}</a>` }
+ dangling++
+ const shown = esc(target)
+ return text === shown ? `[[${text}]]` : `[[${shown}|${text}]]`
+ },
+ )
+ return { html: out, linked, dangling }
+}
diff --git a/spaces/src/model.ts b/spaces/src/model.ts
index 870496cd..be6a0e02 100644
--- a/spaces/src/model.ts
+++ b/spaces/src/model.ts
@@ -25,15 +25,6 @@ export const FORMAT_VERSION = 1
*/
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.
*
@@ -78,6 +69,27 @@ export interface Block {
h?: number
/** pagelink: the target page id */
page?: string
+ /**
+ * callout: which kind of callout this is — one of blocks.ts CALLOUT_TONES.
+ *
+ * An OPEN string, like `type`, and for the same reason: a tone a future build
+ * adds must survive this one untouched. An unrecognised tone renders with the
+ * neutral treatment and spells ITSELF out as its label, so the reader is told
+ * the truth rather than shown a note that is really a warning.
+ */
+ tone?: string
+ /**
+ * callout: an emoji (or a name from the icon set) REPLACING the tone's own
+ * mark.
+ *
+ * Absent is the normal case and is not a missing value — the mark is DERIVED
+ * from the tone, so every warning in a document looks like every other one,
+ * and a document written today is not frozen to today's glyphs. The override
+ * exists because "🎉 we shipped" is a callout too, and it never changes what
+ * the tone MEANS: the tone is still the tone, in the styling and in the
+ * markdown export.
+ */
+ icon?: string
[extra: string]: unknown
}
@@ -305,6 +317,25 @@ export interface SpaceIndex {
/** Every `#p/<id>` href in a block's html. */
const LINK_RE = /href="#p\/([^"]+)"/g
+/**
+ * The PAGE a `#p/…` target names.
+ *
+ * `#p/<page>` today; `#p/<page>/<block>` is already admissible under
+ * sanitize.ts's allowlist, so it can appear in a file this build did not write.
+ * Keyed on the whole string, a block link produced a backlink on the id
+ * "p1/b2" — which is no page, so the target page listed nothing and the one
+ * feature that makes a wiki worth having quietly failed on exactly the links a
+ * newer build would write.
+ *
+ * `pages` is passed so an author-supplied id CONTAINING a slash still wins:
+ * minted ids never contain one, but nothing stops a hand-written file.
+ */
+function linkTarget(raw: string, pages: Map<string, Page>): string {
+ if (pages.has(raw)) return raw
+ const cut = raw.lastIndexOf('/')
+ return cut > 0 ? raw.slice(0, cut) : raw
+}
+
const pushInto = <T>(m: Map<string, T[]>, k: string, v: T) => {
const list = m.get(k)
if (list) list.push(v)
@@ -325,7 +356,7 @@ export function buildIndex(doc: SpacesDoc): SpaceIndex {
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 })
+ pushInto(backlinks, linkTarget(m[1], page), { pageId: p.id, blockId: b.id })
}
}
if (b.type === 'pagelink' && typeof b.page === 'string') {
diff --git a/spaces/src/preview.ts b/spaces/src/preview.ts
new file mode 100644
index 00000000..a1e13fd3
--- /dev/null
+++ b/spaces/src/preview.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The still render written into every saved space, for readers with no JS.
+//
+// WHAT THIS IS FOR. The shell's runtime ships DEFLATED and is inflated by a
+// loader at boot. With scripting off nothing inflates, nothing boots, and the
+// splash is never removed — so a saved space appeared as the bento boot screen
+// to macOS QuickLook, iOS Files, Bento Tray, and any preview pane that renders
+// HTML without running it. A file whose whole promise is "this is the document"
+// showed a loading animation instead of the document.
+//
+// So every save writes a plain, static render of the home page into the shell,
+// followed IMMEDIATELY by a parser-blocking script that deletes both. A
+// thumbnailer keeps it (it runs no script); a reader never sees it (the remover
+// runs before the first paint). Slides established the whole mechanism —
+// kernel/src/save.ts registerPreview, and the rationale in docs/DECISIONS.md;
+// this is the spaces renderer for it.
+//
+// NOT `<noscript>`: measured on iOS, whose thumbnailer runs no script AND does
+// not render noscript, so the content would be invisible in exactly the place
+// this exists to fix.
+//
+// THE CSS PROBLEM, and why this file carries a style block. The runtime
+// stylesheet is deflated too, so none of the `.sp-*` rules exist in this mode.
+// Slides inlines the handful of rules its render needs; a space is a column of
+// prose and needs a bit more than a handful, so the preview ships its own small
+// scoped sheet. It is a SEPARATE, deliberately plain sheet rather than an
+// extract of the real one: it renders the document honestly at a glance, and it
+// is not trying to be pixel-identical to the editor.
+
+import type { SpacesDoc, Page } from './model'
+import { renderPage } from './render'
+import { homePage } from './model'
+
+/** Above this the preview is trimmed, then dropped to a title card. A preview
+ * is a courtesy; it must never be why a file is large. */
+export const PREVIEW_BUDGET = 64 * 1024
+
+/** Anything that could run, load, or accept input has no business in a still. */
+const BANNED = 'script,iframe,object,embed,video,audio,canvas,form,input,textarea,select,button,link,meta'
+
+/** Attributes the runtime uses to find things. A still has no runtime. */
+const DROP_ATTRS = [
+ 'contenteditable', 'draggable', 'tabindex', 'role', 'href', 'src', 'srcset',
+ 'data-edit', 'data-block-id', 'data-type', 'data-page-title', 'data-ph',
+ 'data-remote-src', 'data-load-remote', 'aria-label', 'aria-expanded', 'title',
+]
+
+const FONT_STACK =
+ '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif'
+
+/**
+ * The preview's own stylesheet.
+ *
+ * Scoped under the host so it cannot touch the live app if it ever survived
+ * (it does not — the remover runs first), and written flat so a conservative
+ * renderer can follow all of it.
+ */
+const SHEET = (doc: SpacesDoc): string => {
+ const ink = flat(doc.theme?.color) ?? '#1E2A3A'
+ const bg = flat(doc.theme?.background) ?? '#FFFFFF'
+ const accent = flat(doc.theme?.accent) ?? '#F7A600'
+ const measure = Number(doc.theme?.measure) || 720
+ return [
+ `.bp{position:fixed;left:0;top:0;width:100%;height:100%;z-index:2147483000;`,
+ `overflow:hidden;background:${bg};color:${ink};font-family:${FONT_STACK};`,
+ `-webkit-font-smoothing:antialiased}`,
+ `.bp-col{max-width:${measure}px;margin:0 auto;padding:56px 28px 0;`,
+ `font-size:16px;line-height:1.62}`,
+ `.bp h1{font-size:33px;line-height:1.2;margin:0 0 18px;letter-spacing:-.02em}`,
+ `.bp h2{font-size:22px;line-height:1.3;margin:26px 0 8px}`,
+ `.bp h3{font-size:18px;margin:20px 0 6px}`,
+ `.bp p{margin:0 0 12px}`,
+ `.bp ul,.bp ol{margin:0 0 12px;padding-inline-start:24px}`,
+ `.bp li{margin:0 0 5px}`,
+ `.bp li.sp-done{color:#5B6472;text-decoration:line-through}`,
+ `.bp blockquote{margin:0 0 14px;padding-inline-start:14px;`,
+ `border-inline-start:3px solid ${accent};color:#5B6472}`,
+ `.bp pre{margin:0 0 14px;padding:11px 13px;border-radius:8px;background:#F5F7FA;`,
+ `font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden}`,
+ `.bp hr{border:0;border-top:1px solid #E3E8EF;margin:20px 0}`,
+ `.bp figure{margin:0 0 14px}`,
+ `.bp img{max-width:100%;height:auto;border-radius:8px;display:block}`,
+ `.bp figcaption{font-size:13px;color:#5B6472;margin-top:5px}`,
+ `.bp aside{margin:0 0 14px;padding:12px 14px;border-radius:10px;`,
+ `border:1px solid #E3E8EF;border-inline-start:3px solid ${accent};background:#F8FAFC}`,
+ `.bp code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.92em}`,
+ `.bp a{color:inherit;text-decoration:none;border-bottom:1px solid ${accent}}`,
+ ].join('')
+}
+
+/** A colour a conservative renderer will certainly accept, or nothing. */
+function flat(v: unknown): string | null {
+ const s = typeof v === 'string' ? v.trim() : ''
+ return /^#[0-9a-f]{3,8}$/i.test(s) || /^rgb/i.test(s) ? s : null
+}
+
+const byteLength = (el: HTMLElement): number => new TextEncoder().encode(el.outerHTML).length
+
+/**
+ * Strip everything a still cannot honour, in place.
+ *
+ * `href`/`src` go too: a preview must not be a link, and it must never fetch —
+ * an <img src="https://…"> here would phone home from a file manager, which is
+ * the very thing the remote-image consent rule exists to prevent, in a context
+ * where nobody could consent.
+ */
+function staticize(root: HTMLElement, keepImages: boolean, doc: SpacesDoc): void {
+ // A to-do's checkbox is an <input>, and a still has no controls — but simply
+ // deleting it leaves a list of oddly indented sentences with no sign they are
+ // tasks, or which are done. Swap in the glyph before the ban runs.
+ for (const box of Array.from(root.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'))) {
+ const mark = document.createElement('span')
+ mark.textContent = box.checked ? '☑ ' : '☐ '
+ mark.setAttribute('style', 'color:#5B6472')
+ box.replaceWith(mark)
+ }
+ for (const el of Array.from(root.querySelectorAll(BANNED))) el.remove()
+
+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {
+ const isImg = el.tagName === 'IMG'
+ for (const attr of Array.from(el.attributes)) {
+ // on* can only arrive through our own code or the sanitizer (which strips
+ // every attribute) — defence in depth, and free.
+ if (attr.name.startsWith('on')) { el.removeAttribute(attr.name); continue }
+ if (!DROP_ATTRS.includes(attr.name)) continue
+ // an embedded image is the one src worth keeping: it is already in the
+ // file, so showing it costs no request
+ if (isImg && attr.name === 'src' && attr.value.startsWith('data:')) continue
+ el.removeAttribute(attr.name)
+ }
+ }
+
+ // an <img> with no src left is a broken-image glyph — drop it
+ for (const img of Array.from(root.querySelectorAll<HTMLImageElement>('img'))) {
+ if (!keepImages || !img.getAttribute('src')) {
+ // Keep the BOX. An empty tinted rectangle where the picture was reads as
+ // layout; removing it collapses the page into floating text.
+ const tint = document.createElement('div')
+ const accent = flat(doc.theme?.accent) ?? '#F7A600'
+ tint.setAttribute('style',
+ `height:120px;border-radius:8px;margin:0 0 14px;` +
+ `background:linear-gradient(135deg,${accent}2E,${accent}12)`)
+ img.replaceWith(tint)
+ }
+ }
+}
+
+/** Last resort: the space's name, on its own background. */
+function titleCard(doc: SpacesDoc): HTMLElement {
+ const col = document.createElement('div')
+ col.className = 'bp-col'
+ const h = document.createElement('h1')
+ h.textContent = doc.title || 'Untitled space'
+ col.appendChild(h)
+ const p = document.createElement('p')
+ const pages = doc.pages?.length ?? 0
+ p.textContent = `${pages} page${pages === 1 ? '' : 's'}`
+ p.setAttribute('style', 'color:#5B6472')
+ col.appendChild(p)
+ return col
+}
+
+function wrap(inner: HTMLElement, doc: SpacesDoc): HTMLElement {
+ const box = document.createElement('div')
+ // z-index above the splash (9999) and the loader's failure card (99999)
+ box.className = 'bp'
+ const style = document.createElement('style')
+ style.textContent = SHEET(doc)
+ box.appendChild(style)
+ box.appendChild(inner)
+ return box
+}
+
+/**
+ * The still for this space: its home page, rendered flat.
+ *
+ * Returns null when there is nothing to show — a pristine shell has an empty
+ * document, and a boot splash is the honest thing to display for a file that
+ * genuinely holds no document yet.
+ */
+export function buildSpacePreview(doc: SpacesDoc): HTMLElement | null {
+ if (!doc?.pages?.length) return null
+ const page: Page | undefined = homePage(doc) ?? doc.pages[0]
+ if (!page) return null
+
+ for (const keepImages of [true, false]) {
+ // the SHARED renderer, so the still cannot disagree with the app about what
+ // the document looks like. forceOpen: a fold that is shut in the editor
+ // still has content worth previewing; printing: no controls.
+ const rendered = renderPage(page, doc, {
+ editable: false,
+ forceOpen: true,
+ printing: true,
+ titleOf: (id) => doc.pages.find((p) => p.id === id)?.title,
+ })
+ const col = document.createElement('div')
+ col.className = 'bp-col'
+ while (rendered.firstChild) col.appendChild(rendered.firstChild)
+ staticize(col, keepImages, doc)
+ const built = wrap(col, doc)
+ if (byteLength(built) <= PREVIEW_BUDGET) return built
+ }
+ return wrap(titleCard(doc), doc)
+}
diff --git a/spaces/src/render.ts b/spaces/src/render.ts
index 5def8052..9d2a0ac1 100644
--- a/spaces/src/render.ts
+++ b/spaces/src/render.ts
@@ -11,7 +11,10 @@
import { type SpacesDoc, type Page, type Block, isRemote } from './model'
import { sanitizeInline, inertBody, esc } from './sanitize'
+import { tokenize } from './highlight'
import { t } from './i18n'
+import { TAG_OF, LIST_OF, SPEC, TONE } from './blocks'
+import { ICONS, type IconName } from './icons'
export interface RenderOpts {
/** editable per-block hosts (the editor); false for reader/print */
@@ -20,6 +23,8 @@ export interface RenderOpts {
titleOf?: (pageId: string) => string | undefined
/** collapsed toggles render OPEN — print always passes this */
forceOpen?: boolean
+ /** rendering to paper: no controls, because paper has no buttons */
+ printing?: boolean
/**
* Has the READER agreed to load this remote url?
*
@@ -31,13 +36,10 @@ export interface RenderOpts {
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' }
+// The tag and list maps come from the block registry (blocks.ts), so a new
+// block type declares its element once instead of being added here, to the /
+// menu, to the autoformat table and to the markdown exporter separately.
-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.
@@ -76,14 +78,32 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):
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') {
+ // A CONTAINER owns the blocks whose parent is its id. Which types those are
+ // is registry data (blocks.ts `container`), not a name test here — the
+ // second container type is what turned `b.type === 'toggle'` from a fact
+ // into a bug waiting for the third one.
+ const container = SPEC.get(b.type)?.container
+ if (container) {
const body = document.createElement('div')
- body.className = 'sp-toggle-body'
- if (!(opts.forceOpen || b.open)) body.hidden = true
+ body.className = `sp-${b.type}-body`
+ if (container === 'fold' && !(opts.forceOpen || b.open)) body.hidden = true
node.appendChild(body)
stack.push([b.id, body])
list = null
+ } else if (kind) {
+ // A LIST ITEM OWNS ITS INDENTED CHILDREN.
+ //
+ // Tab already wrote `parent` (editor.indent), and nothing rendered it:
+ // only registry containers opened a body, so an indented bullet came out
+ // flat and Tab was a key that did nothing you could see. The <li> IS the
+ // host — that is what HTML nesting is — so a child list starts inside it
+ // and `list.under` changing is what makes the grouping open a fresh
+ // <ul>/<ol> at the deeper level.
+ //
+ // Not `container: true` in the registry: a list item does not take a body
+ // div, it takes children directly, and the gutter/inline-host rules that
+ // `container` implies are wrong for it.
+ stack.push([b.id, node])
}
}
return frag
@@ -105,9 +125,12 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
case 'code': {
const pre = document.createElement('pre')
const code = document.createElement('code')
+ // `language-xx` is the convention every markdown pipeline already reads,
+ // and it carries the author's raw tag even when this build cannot
+ // highlight it. esc() because it lands in a class attribute.
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 }
+ paintCode(code, textFromHtml(b.html), b.lang)
pre.appendChild(code)
el.appendChild(pre)
return el
@@ -183,6 +206,38 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
return el
}
+ case 'callout': {
+ const raw = String(b.tone ?? 'note')
+ const known = TONE.has(raw) ? raw : 'note'
+ // Only a KNOWN tone reaches the class name. An unrecognised one keeps the
+ // neutral treatment (and its own word as the label) — and a class built
+ // from an arbitrary string out of a mailed file is a thing not to have.
+ el.className = `sp-b sp-b-callout sp-tone-${known}`
+
+ // The chip is the tone control when there is an editor to change it in,
+ // and a plain label otherwise — reading view, print and a locked space
+ // must not paint a button that does nothing.
+ const chip = document.createElement(opts.editable ? 'button' : 'span')
+ chip.className = 'sp-callout-chip'
+ if (chip instanceof HTMLButtonElement) {
+ chip.type = 'button'
+ chip.title = t('Change the kind of callout')
+ }
+ const mark = document.createElement('span')
+ mark.className = 'sp-callout-mark'
+ calloutMark(mark, b, known)
+ const label = document.createElement('span')
+ label.className = 'sp-callout-label'
+ // NOT aria-hidden and never a ::before: the tone is content the way a
+ // "Warning:" printed on a page is content. A screen reader reading this
+ // page linearly must hear it, and a printout must carry it.
+ label.textContent = toneLabel(raw)
+ chip.append(mark, label)
+ el.appendChild(chip)
+ el.appendChild(inlineHost(b, opts))
+ return el
+ }
+
case 'toggle': {
const twist = document.createElement('button')
twist.className = 'sp-twist'
@@ -201,6 +256,54 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
}
}
+/**
+ * A callout tone's name, in the reader's language.
+ *
+ * Written out as t() calls rather than read from a table in blocks.ts: the i18n
+ * sweep (scripts/build-spaces-i18n.mjs) collects t() calls with a LITERAL
+ * STRING out of the source, so a name held as data would ship English to all
+ * eight locales. A tone with no case here fails scripts/test-spaces-model.ts.
+ *
+ * (The sweep reads comments too, so do not write an example call in one.)
+ *
+ * An UNRECOGNISED tone returns its own word. A file from a future build that
+ * says `success` should say "success", not "Note" — the label is the one place
+ * that can tell the reader the truth about a tone we cannot draw.
+ */
+export function toneLabel(tone: string): string {
+ switch (tone) {
+ case 'note': return t('Note')
+ case 'tip': return t('Tip')
+ case 'important': return t('Important')
+ case 'warning': return t('Warning')
+ case 'caution': return t('Caution')
+ default: return tone
+ }
+}
+
+/**
+ * Fill a callout's mark: the author's override if there is one, else the tone's
+ * own shape.
+ *
+ * The override follows the same rule as a page icon (editor.ts pageIcon) — a
+ * name from the icon set, or any other string as literal TEXT, which is how an
+ * emoji works. textContent, never innerHTML: this string came out of a file
+ * someone sent you.
+ *
+ * `Object.hasOwn`, not `in`: ICONS is an object literal, so `'toString' in
+ * ICONS` is TRUE and the lookup hands back a function, which would then be
+ * stringified into the page as markup.
+ */
+function calloutMark(host: HTMLElement, b: Block, known: string): void {
+ const custom = typeof b.icon === 'string' ? b.icon : ''
+ if (custom) {
+ if (Object.hasOwn(ICONS, custom)) host.innerHTML = ICONS[custom as IconName]
+ else host.textContent = custom
+ return
+ }
+ host.innerHTML = ICONS[(TONE.get(known) ?? TONE.get('note')!).icon]
+}
+
/** 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 {
@@ -224,8 +327,74 @@ const textFromHtml = (html: string | undefined): string => {
return inertBody(html).textContent ?? ''
}
+/**
+ * Paint highlighted code into a `<code>` element — the ONE place colour is
+ * applied, so the editor, the reader and print can never disagree.
+ *
+ * NOTHING IS BUILT AS A STRING. `tokenize` returns ranges into `text`, and
+ * every node here comes from `createTextNode`/`textContent`. Code is text
+ * someone mailed you; the model never gains markup and neither does the DOM.
+ *
+ * IT RECONCILES RATHER THAN REPLACING, and that is the whole answer to
+ * highlighting a live contenteditable. On `input` the browser has ALREADY
+ * applied the keystroke to the DOM, so re-tokenising the same text usually
+ * yields byte-identical nodes: typing inside a string, a comment or an
+ * identifier changes that token's text and nothing else, the existing text node
+ * already holds the new value, and this function performs ZERO mutations. The
+ * caret is not restored because it was never disturbed.
+ *
+ * Only a keystroke that moves a token BOUNDARY — opening a quote, completing a
+ * keyword — restructures anything, and then `changed` is true and the caller
+ * puts the caret back by character offset. Assigning `Text.data` wholesale is
+ * specified to collapse a live range inside it to offset 0, so a restore is
+ * genuinely required there; it is just rare.
+ *
+ * Returns whether the DOM changed.
+ */
+export function paintCode(code: HTMLElement, text: string, lang?: unknown): boolean {
+ let changed = false
+ let node: ChildNode | null = code.firstChild
+
+ for (const tk of tokenize(text, lang)) {
+ const s = text.slice(tk.a, tk.b)
+ if (tk.k) {
+ const cls = `sp-t-${tk.k}`
+ const fit = node?.nodeType === 1 && (node as HTMLElement).className === cls &&
+ node.firstChild?.nodeType === 3 && !node.firstChild.nextSibling
+ if (fit) {
+ if (node!.firstChild!.nodeValue !== s) { (node!.firstChild as Text).data = s; changed = true }
+ } else {
+ const span = document.createElement('span')
+ span.className = cls
+ span.textContent = s
+ code.insertBefore(span, node)
+ changed = true
+ continue // `node` still has to be matched against the NEXT token
+ }
+ } else if (node?.nodeType === 3) {
+ if (node.nodeValue !== s) { (node as Text).data = s; changed = true }
+ } else {
+ code.insertBefore(document.createTextNode(s), node)
+ changed = true
+ continue
+ }
+ node = node!.nextSibling
+ }
+
+ while (node) { const next = node.nextSibling; node.remove(); node = next; changed = true }
+ return changed
+}
+
export function resolveSrc(src: string, doc: SpacesDoc): string {
- if (src.startsWith('asset:')) return doc.assets?.[src.slice(6)] ?? ''
+ // hasOwn, not a bare index: `assets['toString']` returns a FUNCTION, which is
+ // truthy, so the `?? ''` never fired and the stringified function was assigned
+ // to img.src. Same class as the icon lookup — an author-supplied key reaching
+ // a lookup table through the prototype chain.
+ if (src.startsWith('asset:')) {
+ const key = src.slice(6)
+ const table = doc.assets
+ return table && Object.hasOwn(table, key) ? table[key] : ''
+ }
return src
}
@@ -263,7 +432,10 @@ function remoteImagePlaceholder(src: string, b: Block, opts: RenderOpts): HTMLEl
box.appendChild(a)
}
- if (opts.editable !== false || opts.allowRemote) {
+ // `allowRemote` is passed by print too, so this clause was always truthy there
+ // and paper carried a live "Load this image" button. Print asks for it
+ // explicitly instead.
+ if (opts.printing !== true && (opts.editable !== false || opts.allowRemote)) {
const btn = document.createElement('button')
btn.type = 'button'
btn.className = 'sp-btn sp-remote-load'
diff --git a/spaces/src/sanitize.ts b/spaces/src/sanitize.ts
index 35cbadd1..dcf22fa0 100644
--- a/spaces/src/sanitize.ts
+++ b/spaces/src/sanitize.ts
@@ -35,8 +35,15 @@ const ALLOWED = new Set([
*/
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'])
+/**
+ * Tags whose CONTENT should survive when the tag itself is dropped.
+ *
+ * Exported because validate() tells an agent which block-level tags get
+ * unwrapped out of inline html. A second copy of this list would go stale the
+ * first time this one changes, and validate() would then advise an agent to
+ * "fix" markup that is actually fine — or stay silent about markup that is not.
+ */
+export 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.
@@ -158,3 +165,19 @@ export function textOf(html: string | undefined): string {
/** Escape for safe insertion as text. */
export const esc = (s: string): string =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
+
+/**
+ * A `code` block's text, as `Block.html` stores it.
+ *
+ * `&`, `<`, `>` and NOTHING ELSE — exactly what an html serializer emits for a
+ * text node, which is what `code.innerHTML` produced before syntax colouring
+ * made that read unusable (the host now holds `<span>`s). So a code block typed
+ * today serializes byte-identically to one typed before highlighting existed,
+ * and `render.ts`'s `textFromHtml` decodes both.
+ *
+ * `esc()` above escapes `"` as well, correctly, because it writes ATTRIBUTE
+ * values. Doing that here would not round-trip: the parser hands back a bare
+ * quote, so the next save would differ from the last for no reason, forever.
+ */
+export const escText = (s: string): string =>
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
diff --git a/spaces/src/starter.ts b/spaces/src/starter.ts
index d0286c90..7d9a05a7 100644
--- a/spaces/src/starter.ts
+++ b/spaces/src/starter.ts
@@ -8,7 +8,7 @@
// 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'
+import { FORMAT, FORMAT_VERSION, defaultTheme, type SpacesDoc, type Block } from './model.ts'
const b = (type: string, html = '', extra: Partial<Block> = {}): Block =>
({ id: `sd-${(seq++).toString(36)}`, type, html, ...extra })
@@ -29,6 +29,7 @@ export function starterDoc(): SpacesDoc {
// 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 })
+ const callout = b('callout', 'A callout. Click the mark to make it a note, a tip, a warning.', { tone: 'tip' })
return {
format: FORMAT,
@@ -89,7 +90,15 @@ export function starterDoc(): SpacesDoc {
b('todo', '<code>[] </code> makes a checkbox', { done: false }),
b('h2', 'Blocks that are not text'),
b('quote', 'A quote — type <code>&gt; </code>.'),
- b('code', 'const space = oneFile\n// ``` makes a code block', { lang: 'js' }),
+ b('code', 'const space = oneFile\n// type ``` and a SPACE to make a code block', { lang: 'js' }),
+ callout,
+ b('p', 'Press <code>⏎</code> in a callout and the next line goes inside it. Empty line, <code>⌫</code>, and you are out.', { parent: callout.id }),
+ b('code',
+ '// type ```js and a space — the language is yours to pick\n' +
+ 'const space = { file: 1, pages: 5 }\n' +
+ 'console.log(`one file, ${space.pages} pages`)',
+ { lang: 'js' }),
+ b('p', 'Hover a code block to see — and change — its language.'),
toggle,
b('p', 'Anything indented under a toggle folds away with it.', { parent: toggle.id }),
b('divider'),
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index 739291ad..cf8f05c4 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -36,6 +36,15 @@ export class Store {
/** blocks currently selected at block level (Esc from text editing) */
selection: string[] = []
readOnly = false
+ /**
+ * Unsaved changes.
+ *
+ * The header comment above has claimed since 0.1.0 that this policy sets
+ * "the dirty flag", and there was no dirty flag — so the Save button could
+ * not say whether it needed pressing, which in a format whose whole promise
+ * is "the file IS the document" is the one thing it should say.
+ */
+ dirty = false
private undoStack: Entry[] = []
private redoStack: Entry[] = []
@@ -90,6 +99,7 @@ export class Store {
this.endRun()
this.checkpoint()
mutate()
+ this.dirty = true
this.reindex()
this.emit('doc')
if (opts.structure !== false) this.emit('tree')
@@ -124,8 +134,16 @@ export class Store {
/** Model changed without a new undo entry (mid-run). */
touch(): void {
+ // A typing run deliberately does NOT emit 'doc' per keystroke — that is the
+ // whole point of the run. But the FIRST keystroke changes something the
+ // reader can see: the file now differs from the disk. Announce that once,
+ // on the transition only, or the unsaved dot does not appear until the run
+ // closes 600ms later and the button lies for as long as you keep typing.
+ const wasClean = !this.dirty
+ this.dirty = true
this.doc.modified = new Date().toISOString()
this.reindex()
+ if (wasClean) this.emit('doc')
}
private reindex(): void {
@@ -153,6 +171,7 @@ export class Store {
}
private restore(entry: Entry): void {
+ this.dirty = true
const assets = this.doc.assets
this.doc = { ...(JSON.parse(entry.json) as SpacesDoc), ...(assets ? { assets } : {}) }
this.pageId = entry.pageId
@@ -206,6 +225,7 @@ export class Store {
/** Replace the whole document — the AI round-trip and version restore path. */
replaceDoc(next: SpacesDoc): void {
+ this.dirty = true
this.endRun()
this.checkpoint()
this.doc = next
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index ad4269da..8cf9a024 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -47,12 +47,20 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
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 span { color: var(--accent); }
+ display: inline-flex; align-items: center; gap: 7px;
+ font: inherit; font-weight: 700; font-size: 14px; letter-spacing: -0.01em;
+ white-space: nowrap; padding: 4px 7px 4px 4px; user-select: none;
+ background: transparent; border: 1px solid transparent; border-radius: 8px;
+ color: var(--ink); cursor: pointer;
+}
+.sp-mark:hover { background: var(--chrome-2); }
+.sp-mark-svg { display: block; flex: 0 0 auto; }
+.sp-mark-word span { color: #FF9E8A; }
.sp-doctitle {
- flex: 1 1 auto; min-width: 0;
+ /* Sized, not greedy: a title input that eats the slack pushed undo/redo away
+ from the document they belong to and left them floating mid-bar. The
+ spacer is the right group's margin-inline-start:auto. */
+ flex: 0 1 240px; 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;
@@ -83,7 +91,9 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
/* ————— sidebar ————— */
.sp-side {
- flex: 0 0 244px; min-width: 0;
+ /* the reader's width, restored from localStorage — never the document's */
+ flex: 0 0 var(--sp-panew, 244px); min-width: 0;
+ transition: flex-basis .18s ease, padding .18s ease;
border-inline-end: 1px solid var(--line); background: var(--chrome);
overflow: auto; padding: 10px 8px max(16px, env(safe-area-inset-bottom));
}
@@ -154,6 +164,58 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
margin: 8px 0; padding: 2px 0 2px 15px;
border-inline-start: 3px solid var(--line); color: var(--ink-2);
}
+/* ————— callouts —————
+ The tone is carried by the MARK'S SHAPE (circle, bulb, square, triangle,
+ octagon) and by its name spelled out beside it. The tint is decoration: it
+ must be possible to tell a warning from a tip with no colour vision, on a
+ monochrome printout, and at a glance — and amber/red/green happen to be the
+ hues the most readers cannot separate.
+
+ The BODY TEXT stays --ink, never the tone colour. Coloured prose is a
+ readability tax on the sentence that mattered enough to put in a box. */
+.sp-b-callout {
+ /* the neutral fallback: a tone class always lands on top of it, but a
+ stylesheet that only works with one is a stylesheet with a hole in it */
+ --tone-bg: var(--chrome); --tone-line: var(--line); --tone-ink: var(--ink-2);
+ display: block; margin: 10px 0; padding: 9px 14px 10px;
+ border: 1px solid var(--tone-line); border-inline-start-width: 4px;
+ border-radius: var(--radius); background: var(--tone-bg);
+}
+.sp-callout-chip {
+ display: flex; align-items: center; gap: 6px;
+ margin: 0 0 2px; padding: 0; font: inherit; text-align: start;
+ color: var(--tone-ink); background: transparent; border: 0;
+ font-size: 12.5px; font-weight: 700; letter-spacing: .02em;
+ user-select: none;
+}
+button.sp-callout-chip { cursor: pointer; }
+button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset: 3px; }
+.sp-callout-mark {
+ display: inline-flex; align-items: center; justify-content: center;
+ /* an author-supplied glyph is any string a file carried: hold the row height
+ whatever arrives, and never let it push the label off the line */
+ min-width: 17px; max-width: 34px; overflow: hidden; line-height: 1;
+}
+.sp-callout-mark svg { width: 15px; height: 15px; display: block; }
+.sp-callout-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.sp-callout-body { padding-inline-start: 0; }
+.sp-callout-body > .sp-b:first-child { margin-top: 4px; }
+.sp-b-callout .sp-list { padding-inline-start: 20px; }
+
+.sp-tone-note { --tone-bg: #eef3f9; --tone-line: #7d9cbd; --tone-ink: #2b4a68; }
+.sp-tone-tip { --tone-bg: #e9f6ef; --tone-line: #4f9e79; --tone-ink: #1c5a41; }
+.sp-tone-important { --tone-bg: #f2eefb; --tone-line: #8a72cc; --tone-ink: #493081; }
+.sp-tone-warning { --tone-bg: #fdf4e3; --tone-line: #d9a326; --tone-ink: var(--accent-ink); }
+.sp-tone-caution { --tone-bg: #fdeeed; --tone-line: #cd6a63; --tone-ink: #8a2f28; }
+.sp-result-ico.sp-tone-note, .sp-result-ico.sp-tone-tip, .sp-result-ico.sp-tone-important,
+.sp-result-ico.sp-tone-warning, .sp-result-ico.sp-tone-caution { color: var(--tone-ink); }
+
+.sp-tonepop { width: 244px; }
+.sp-toneopt.sp-sel { background: var(--chrome-2); }
+.sp-tonerow { display: block; padding: 8px 9px 4px; border-top: 1px solid var(--line); margin-top: 4px; }
+.sp-tonelabel { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
+.sp-toneicon { width: 100%; }
+
.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; }
@@ -173,6 +235,7 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
"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 { position: relative; }
.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);
@@ -180,6 +243,48 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
.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; }
+/* ————— syntax colours —————
+ Six roles, chosen to survive the two places code is read: a light editor and
+ a printed page. Every one clears 4.5:1 against the code well (#f5f7fa) AND
+ against white, because a browser drops the block's background when printing
+ and keeps the ink — a palette tuned only against the tinted well goes pale on
+ paper. Hue does the work, not lightness, so the block still reads as prose at
+ 13px and stays legible in greyscale.
+
+ Comments reuse --muted and numbers reuse --accent-ink: the suite's palette
+ already had the right two, and a syntax theme that invents a ninth grey is a
+ syntax theme nobody can restyle. The remaining four are new because nothing
+ in the chrome palette means "string". */
+:root {
+ --code-str: #1c6b4b;
+ --code-key: #6b3fa0;
+ --code-lit: #0d6382;
+ --code-prop: #1c4fb5;
+}
+.sp-t-c { color: var(--muted); font-style: italic; }
+.sp-t-s { color: var(--code-str); }
+.sp-t-n { color: var(--accent-ink); }
+.sp-t-k { color: var(--code-key); }
+.sp-t-l { color: var(--code-lit); }
+.sp-t-p { color: var(--code-prop); }
+
+/* The chip FLOATS OVER the top-right of the well, exactly like .sp-imgtools
+ floats over an image — same shadow, same hover-only rule. It can cover the
+ end of a long first line, and the alternative (parking it outside the text
+ column, where the block gutter lives) only has room on a wide window with the
+ sidebar closed. A control that moves depending on the viewport is worse than
+ one that overlaps for as long as your pointer is on the block. */
+.sp-langchip {
+ position: absolute; top: 10px; inset-inline-end: 10px;
+ font-size: 11px; padding: 3px 8px; color: var(--muted);
+ background: rgb(255 255 255 / .94); border-color: var(--line);
+ box-shadow: 0 2px 8px rgb(20 30 45 / .12);
+ opacity: 0; transition: opacity .12s;
+}
+.sp-b-code:hover .sp-langchip, .sp-langchip:focus { opacity: 1; }
+.sp-langpop { width: 190px; }
+.sp-langpop .sp-dditem.sp-sel { background: var(--chrome-2); }
+
.sp-twist {
flex: 0 0 auto; border: 0; background: transparent; color: var(--muted);
cursor: pointer; padding: 3px 0 0; line-height: 1;
@@ -322,11 +427,23 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
/* ————— 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-bar, .sp-side, .sp-banner, .sp-gutter, .sp-scrim, .sp-langchip { 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; }
+ /* A CALLOUT ON PAPER, IN BLACK AND WHITE.
+ The tint is dropped rather than trusted: browsers do not print backgrounds
+ by default, so a callout whose only cue was its fill would print as bare
+ text — and where they DO print, a mid-grey tint under body text costs
+ contrast for nothing. What survives is the box, the heavier start rule, the
+ tone's shape and the tone's name, all of which are pure black on white. */
+ .sp-b-callout {
+ background: none; border-color: #767676;
+ break-inside: avoid; padding: 8px 12px;
+ }
+ .sp-callout-chip { color: #000; }
+ .sp-callout-chip svg { stroke-width: 2.4; }
p, li { orphans: 2; widows: 2; }
}
@@ -420,6 +537,14 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
.sp-b-image figure { position: relative; }
.sp-page.sp-filedrop { outline: 2px dashed var(--blue); outline-offset: 8px; border-radius: var(--radius); }
+/* ————— import ————— */
+.sp-dropzone {
+ display: grid; place-items: center; margin: 4px 4px 10px; padding: 22px 12px;
+ color: var(--muted); font-size: 13px; text-align: center;
+ border: 1.5px dashed var(--line); border-radius: var(--radius); background: var(--chrome);
+}
+.sp-dropzone.sp-drop { border-color: var(--blue); color: var(--blue); }
+
/* ————— page rows: the options button ————— */
.sp-treelink { position: relative; padding-inline-end: 26px; }
.sp-rowmore {
@@ -490,4 +615,159 @@ select, input, textarea, [contenteditable='true'] { -webkit-user-select: auto; u
}
.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; } }
+@media print { .sp-remote { border-color: #999; background: none; } .sp-remote-load { display: none !important; } }
+
+/* ————— narrow topbar: hide, never scroll —————
+ Measured at 375px: the bar wanted 678px, so seven of eleven controls sat off
+ the right edge — Save among them, which made the file unsaveable on a phone.
+ The rule is slides' rule: drop text and fold the less-used controls into ⋯,
+ so every action stays reachable at every width. A horizontally scrolling
+ toolbar hides the same controls, just less honestly. */
+.sp-more { display: none; }
+
+@media (max-width: 720px) {
+ .sp-sec { display: none; }
+ .sp-more { display: inline-flex; }
+ /* Save keeps its icon; the word costs 44px and says nothing the icon doesn't */
+ .sp-bar .sp-primary span.sp-savelabel { display: none; }
+ .sp-bar { gap: 2px; }
+ .sp-doctitle { font-size: 13px; }
+}
+
+/* Hit targets: a 30px button is a miss on a touch screen. */
+@media (pointer: coarse) {
+ .sp-bar .sp-btn { min-width: 40px; min-height: 40px; justify-content: center; }
+ .sp-dditem { padding-block: 11px; }
+}
+
+/* A menu opened from the right end of the bar must open INWARD. Anchoring
+ every dropdown to its start edge put the ⋯ and Save menus half off-screen at
+ 375px — the items were there, just unreadable. */
+.sp-dd-end .sp-ddmenu { inset-inline-start: auto; inset-inline-end: 0; }
+.sp-ddmenu { max-width: calc(100vw - 20px); }
+
+/* ————— find & replace on a small screen —————
+ Measured at a 575px viewport: the bar laid out 644px wide and started at
+ x = -87, so the Find field itself was off the left edge — the one control
+ you must reach to use the feature at all. It is anchored to the end edge and
+ sized by its contents, so it grows off the opposite side rather than
+ wrapping.
+
+ Below the breakpoint it spans the viewport and wraps to two rows: the two
+ fields share the first row, the buttons and the counter take the second. */
+@media (max-width: 720px) {
+ .sp-findbar {
+ inset-inline: 8px; top: 52px;
+ flex-wrap: wrap; gap: 5px;
+ }
+ .sp-findbar .sp-find { flex: 1 1 120px; width: auto; min-width: 0; }
+ .sp-findcount { order: 1; flex: 1 1 100%; text-align: start; }
+}
+
+/* ————— the toolbar, grouped as slides groups it —————
+ LEFT is the document (mark · title · save state · history); RIGHT is what you
+ do with it. Two apps in one suite should not teach two different toolbars. */
+.sp-group { display: flex; align-items: center; gap: 6px; }
+.sp-group-right { margin-inline-start: auto; gap: 4px; }
+.sp-group-history { gap: 2px; }
+
+/* Save is ONE control with two halves, fused — not two buttons that happen to
+ be adjacent. The caret is visibly part of the thing it modifies. */
+.sp-split { display: inline-flex; align-items: stretch; }
+.sp-split > .sp-btn:first-child {
+ border-start-end-radius: 0; border-end-end-radius: 0;
+ padding-inline-end: 10px;
+}
+.sp-split .sp-dd { display: flex; align-items: stretch; }
+.sp-split .sp-caret > .sp-btn {
+ height: 100%; padding: 6px 6px;
+ border-start-start-radius: 0; border-end-start-radius: 0;
+ margin-inline-start: 1px;
+ background: var(--ink); color: #fff;
+}
+.sp-split .sp-caret > .sp-btn:hover { background: var(--ink-2); }
+
+/* The unsaved dot lives ON Save: the place you look to find out whether you
+ need to press it is the button itself. */
+.sp-dirty {
+ width: 7px; height: 7px; border-radius: 50%;
+ background: var(--accent); margin-inline-start: 7px;
+ opacity: 0; transition: opacity .18s;
+}
+.sp-dirty.sp-on { opacity: 1; }
+
+@media (max-width: 720px) {
+ /* the mark stays — it is the route to About — but loses its word */
+ .sp-mark { display: inline-flex; }
+ .sp-mark-word { display: none; }
+}
+
+/* About opens with the suite's mark, as slides does — a dialog that starts on a
+ section heading does not say what you are looking at. */
+.sp-about-head { margin-bottom: 4px; }
+.sp-about-logo {
+ display: inline-flex; align-items: center; gap: 10px;
+ text-decoration: none; color: inherit;
+}
+.sp-about-logo b { display: block; font-size: 15px; letter-spacing: -0.01em; }
+.sp-about-logo span { display: block; font-size: 12px; color: var(--muted); margin-top: 1px; }
+.sp-about-logo:hover b { text-decoration: underline; }
+
+/* ————— the panel edge: resize here, collapse here —————
+ Slides' pattern, and its reasoning: the control that hides a panel belongs on
+ the panel's own edge, where you are already looking, rather than in a toolbar
+ across the room. */
+.sp-resizer {
+ flex: none; width: 5px; position: relative;
+ cursor: col-resize; background: transparent;
+ transition: background .12s ease .08s;
+}
+.sp-resizer:hover,
+body.sp-col-resizing .sp-resizer { background: rgb(91 141 239 / .45); }
+body.sp-col-resizing { cursor: col-resize; user-select: none; }
+.sp-noanim { transition: none !important; }
+
+/* The chevron rides the strip and is ALWAYS visible — same as slides. A
+ hover-only affordance is one nobody finds: the first version of this faded in
+ on hover, so the way to hide the panel was invisible until you happened to
+ pass over a 5px strip. */
+.sp-pane-tab {
+ position: absolute; top: 50%; left: 50%;
+ transform: translate(-50%, -50%);
+ width: 16px; height: 44px; padding: 0;
+ display: flex; align-items: center; justify-content: center;
+ background: #fff; color: #5d6b80;
+ border: 1px solid var(--line); border-radius: 8px;
+ cursor: pointer; z-index: 15;
+ box-shadow: 0 1px 4px rgb(20 30 45 / .12);
+}
+.sp-pane-tab:hover { color: var(--ink); border-color: #b9c3d2; }
+.sp-pane-tab svg { width: 13px; height: 13px; display: block; }
+
+/* Collapsed: the panel takes no width and the strip carries only the chevron,
+ docked flush to the screen edge so there is always a way back. */
+.sp-side.sp-pane-closed {
+ flex-basis: 0; padding-inline: 0; border-inline-end-width: 0; overflow: hidden;
+}
+.sp-side.sp-pane-closed + .sp-resizer { cursor: default; }
+.sp-side.sp-pane-closed + .sp-resizer:hover { background: transparent; }
+.sp-side.sp-pane-closed + .sp-resizer .sp-pane-tab {
+ inset-inline-start: 0; left: auto; transform: translateY(-50%);
+}
+
+/* On a phone the panel is a drawer, not a column: no strip, no resizing. */
+@media (max-width: 820px) {
+ .sp-resizer { display: none; }
+}
+
+/* THE PAGES BUTTON ONLY EXISTS WHERE THE PANEL IS A DRAWER.
+ Above the breakpoint the panel has its own chevron, on its own edge, where
+ you are already looking — so a second control for the same thing sat to the
+ LEFT of the wordmark, pushing the suite's mark out of the corner every app in
+ the suite puts it in. Slides has no topbar panel toggle at all, for the same
+ reason. Below the breakpoint there is no strip to hang a chevron on, so the
+ button is the only way in and it leads the bar. */
+.sp-panel-toggle { display: none; }
+@media (max-width: 820px) {
+ .sp-panel-toggle { display: inline-flex; }
+}