Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: agent coverage, undo depth, and block actions on every device (#240)

nyblnet20a2d23c3586
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c32db79c..b1361d6e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -117,6 +117,33 @@ jobs:
# build rather than shipping a half-translated interface.
run: node scripts/build-spaces-i18n.mjs --check
+ - name: Spaces undo rig
+ # Every checkpoint used to stringify the WHOLE document: measured on a
+ # 200-page, 2.5 MB handbook, fifty edits left an undo depth of NINE,
+ # because nine snapshots exhaust the 24 MB budget. A typing run now
+ # records only its PAGE. That is fast and deep — and it is only correct
+ # while the mutation touched nothing else, so `doc` stays the default
+ # and this rig covers the cases where a wrong scope silently loses
+ # work: mixed scopes, interleaved undo/redo, and two pages edited in
+ # turn. (Bundled: store.ts imports './model' extensionless.)
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-spaces-undo.ts --bundle --platform=node --format=esm \
+ --outfile="$RUNNER_TEMP/test-spaces-undo.mjs"
+ node "$RUNNER_TEMP/test-spaces-undo.mjs"
+
+ - name: Spaces agent-surface rig
+ # agent.ts is ~900 lines and shipped with no coverage at all: two of the
+ # five defects an adversarial review found in round 2 lived here,
+ # including a walk over author-supplied parent links that never
+ # returned. What this pins is what makes the surface trustworthy —
+ # validate() SILENT on documents that are correct but unusual (a false
+ # positive teaches an agent to ignore warnings), every write verb
+ # refusing what it cannot honour, no verb producing a document the app
+ # itself could not produce, and every walk terminating. The termination
+ # probes run in child processes with timeouts, because a hang cannot be
+ # reported by the process it hangs.
+ run: node scripts/test-spaces-agent.ts
+
- 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
diff --git a/scripts/test-spaces-agent.ts b/scripts/test-spaces-agent.ts
new file mode 100644
index 00000000..c5021cd0
--- /dev/null
+++ b/scripts/test-spaces-agent.ts
@@ -0,0 +1,254 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The bento/spaces agent surface: validate() and the seven patch verbs.
+//
+// node scripts/test-spaces-agent.ts
+//
+// WHY THIS EXISTS. `spaces/src/agent.ts` is ~900 lines and shipped with ZERO
+// automated coverage — the slides validator has its own rig, and the spaces
+// model rig never imported this file. Two of the five defects an adversarial
+// review found in round 2 were in here, including a page-cycle walk that hung
+// the tab forever, and both were found by a person reading code rather than by
+// anything that runs.
+//
+// WHAT IS WORTH ASSERTING, and what is not:
+//
+// · validate() is only useful if it is TRUSTED, and trust is destroyed by
+// false positives, not by misses. An agent that gets warnings for good
+// documents learns to ignore warnings — so "silent on documents that are
+// unusual but CORRECT" matters more here than any single check firing.
+//
+// · The patch verbs are an API other code will be built on. Each one must
+// refuse a read-only document, refuse input it cannot honour, and — the
+// thing that actually bites — never produce a document THIS BUILD COULD NOT
+// HAVE PRODUCED ITSELF: no unsanitized html, no duplicate ids, no parent
+// cycles, no block parented across pages.
+//
+// · Termination. A walk over author-supplied parent links must end. The
+// review found one that did not, and `parseDoc` preserves the cycle that
+// triggers it, so it arrives from any hand-edited or mailed file.
+//
+// These run in node against the real modules. agent.ts is DOM-free by
+// construction (it plans mutations; the editor applies them), which is what
+// makes this rig possible at all — and is worth preserving.
+
+import { parseDoc, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
+import { starterDoc } from '../spaces/src/starter.ts'
+import {
+ validateDoc, outlineDoc, statsDoc,
+ planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock,
+ planUpdatePage, planRemovePage,
+} from '../spaces/src/agent.ts'
+
+let checks = 0
+let failures = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+/** A document, through the real loader, so ids and defaults are real. */
+function load(pages: unknown[], extra: Record<string, unknown> = {}): SpacesDoc {
+ const r = parseDoc(JSON.stringify({
+ format: FORMAT, version: 1, docId: 'test', title: 'Test', home: (pages[0] as { id: string })?.id,
+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', measure: 720 },
+ pages, ...extra,
+ }))
+ if (!r.ok) throw new Error('fixture did not parse')
+ return r.doc
+}
+
+const p = (id: string, blocks: unknown[], extra: Record<string, unknown> = {}) =>
+ ({ id, title: id, blocks, ...extra })
+const b = (id: string, type = 'p', extra: Record<string, unknown> = {}) =>
+ ({ id, type, html: `text ${id}`, ...extra })
+
+/** Apply a plan the way main.ts's run() does, so the test exercises the real path. */
+function apply<T extends object>(plan: ReturnType<typeof planInsertBlocks> | any): any {
+ if (!plan.ok) return plan
+ const { apply: fn, ...rest } = plan
+ fn()
+ return rest
+}
+
+console.log('bento/spaces agent surface\n')
+
+// ---- validate() is SILENT on documents that are correct --------------------
+// The failure mode that makes a validator worthless is the false positive.
+{
+ const starter = starterDoc()
+ const v = validateDoc(starter as unknown as SpacesDoc)
+ ok(v.findings.length === 0,
+ `the shipped starter space is clean (${v.findings.length} finding(s): ${v.findings.map((f) => f.code).join(', ')})`)
+
+ // unusual, but perfectly legal documents
+ const odd: Array<[string, SpacesDoc]> = [
+ ['a page holding only an image', load([p('p1', [b('b1', 'image', { src: 'asset:k', alt: 'a photo', w: 10, h: 10 })])], { assets: { k: 'data:image/gif;base64,R0lGODlhAQABAAAAACw=' } })],
+ ['a single empty paragraph', load([p('p1', [{ id: 'b1', type: 'p', html: '' }])])],
+ ['a deeply nested toggle', load([p('p1', [
+ b('t1', 'toggle', { open: true }), b('t2', 'toggle', { open: true, parent: 't1' }), b('b3', 'p', { parent: 't2' }),
+ ])])],
+ ['an unknown block type from a newer build', load([p('p1', [b('b1', 'somethingnew')])])],
+ ['a page with no children and no links', load([p('p1', [b('b1')]), p('p2', [b('b2')])])],
+ ]
+ for (const [label, doc] of odd) {
+ const r = validateDoc(doc)
+ const errs = r.findings.filter((f) => f.severity === 'error')
+ ok(errs.length === 0, `${label}: no ERRORS (${errs.map((f) => f.code).join(', ') || 'none'})`)
+ }
+
+ // …and a 500-page space is not itself a problem
+ const many = load(Array.from({ length: 500 }, (_, i) => p(`p${i}`, [b(`b${i}`)])))
+ const big = validateDoc(many)
+ ok(big.findings.filter((f) => f.severity === 'error').length === 0,
+ 'a 500-page space raises no errors')
+}
+
+// ---- …and specific on documents that are broken ---------------------------
+{
+ const broken = load([
+ p('p1', [
+ { id: 'dup', type: 'p', html: 'see <a href="#p/ghost">a dead link</a>' },
+ { id: 'dup', type: 'p', html: 'a duplicate id' },
+ { id: 'b3', type: 'wat', html: 'unknown type' },
+ { id: 'b4', type: 'image', src: 'https://example.com/x.png' },
+ { id: 'b5', type: 'p', html: '<p>block markup inside inline html</p>' },
+ ]),
+ ], { home: 'nope' })
+ const codes = new Set(validateDoc(broken).findings.map((f) => f.code))
+ for (const want of ['broken-link', 'unknown-block-type', 'no-such-home', 'block-markup']) {
+ ok(codes.has(want), `a broken document reports ${want} (got: ${[...codes].join(', ')})`)
+ }
+ ok(validateDoc(broken).findings.every((f) => !!f.fix && !!f.message),
+ 'every finding says what is wrong AND how to fix it')
+
+ // a LEGAL block anchor is not a broken link — the review found this reported
+ // as severity ERROR with a fix that would have destroyed a working link
+ const anchored = load([p('p1', [{ id: 'b1', type: 'p', html: 'see <a href="#p/p2/b9">that block</a>' }]), p('p2', [b('b9')])])
+ ok(!validateDoc(anchored).findings.some((f) => f.code === 'broken-link'),
+ 'a #p/<page>/<block> anchor is not reported as broken')
+}
+
+// ---- every write verb refuses what it cannot honour ------------------------
+{
+ const doc = load([p('p1', [b('b1'), b('b2')]), p('p2', [b('b3')])])
+
+ const refusals: Array<[string, { ok: boolean }]> = [
+ ['insertBlocks into a page that does not exist', planInsertBlocks(doc, 'nope', null, [{ type: 'p' }]) as never],
+ ['updateBlock on a block that does not exist', planUpdateBlock(doc, 'nope', { html: 'x' }) as never],
+ ['updateBlock deleting `type`', planUpdateBlock(doc, 'b1', { type: undefined, __delete: ['type'] }) as never],
+ ['moveBlock to a page that does not exist', planMoveBlock(doc, 'b1', { pageId: 'nope' }) as never],
+ ['updatePage making a page its own parent', planUpdatePage(doc, 'p1', { parent: 'p1' }) as never],
+ ['removePage that does not exist', planRemovePage(doc, 'nope') as never],
+ ]
+ for (const [label, plan] of refusals) ok(plan.ok === false, `refuses: ${label}`)
+
+ // a refusal must SAY why — an agent cannot act on a bare null
+ const bad = planUpdatePage(doc, 'p1', { parent: 'p1' }) as { ok: false; err?: string; detail?: string }
+ ok(bad.ok === false && !!bad.err, 'a refusal carries a machine-readable code')
+}
+
+// ---- the verbs cannot produce a document this build could not produce ------
+{
+ // 1. html goes through the sanitizer on the way IN
+ const doc = load([p('p1', [b('b1')])])
+ apply(planInsertBlocks(doc, 'p1', null, [{ type: 'p', html: '<img src=x onerror="alert(1)"><p>block</p>hi' }]))
+ const added = doc.pages[0].blocks[doc.pages[0].blocks.length - 1]
+ ok(!/onerror|<img|<p>/i.test(added.html ?? ''),
+ `inserted html is sanitized (${(added.html ?? '').slice(0, 40)})`)
+
+ // 2. ids are unique, and minted rather than taken from the caller
+ const doc2 = load([p('p1', [b('b1')])])
+ apply(planInsertBlocks(doc2, 'p1', null, [{ id: 'b1', type: 'p', html: 'tries to reuse an id' }]))
+ const ids = doc2.pages.flatMap((pg) => pg.blocks.map((x) => x.id))
+ ok(new Set(ids).size === ids.length, 'an insert cannot reuse an existing block id')
+
+ // 3. a type change runs the registry's init, so the block is complete
+ const doc3 = load([p('p1', [b('b1')])])
+ apply(planUpdateBlock(doc3, 'b1', { type: 'todo' }))
+ ok(doc3.pages[0].blocks[0].done === false, 'retyping to `todo` initialises `done`')
+ apply(planUpdateBlock(doc3, 'b1', { type: 'callout' }))
+ ok(typeof doc3.pages[0].blocks[0].tone === 'string', 'retyping to `callout` initialises `tone`')
+
+ // 4. a removed container takes its children with it, or they resurrect
+ const doc4 = load([p('p1', [b('t1', 'toggle', { open: true }), b('c1', 'p', { parent: 't1' }), b('after')])])
+ apply(planRemoveBlocks(doc4, ['t1']))
+ const left = doc4.pages[0].blocks.map((x) => x.id)
+ ok(!left.includes('c1'), `removing a container removes its children (left: ${left.join(', ')})`)
+ ok(left.includes('after'), '…and nothing else')
+}
+
+// ---- walks over author-supplied links must TERMINATE -----------------------
+// parseDoc keeps a cycle (it only drops parents naming no page), so this
+// arrives from any hand-edited or mailed file — and the sequence is the
+// RECOMMENDED one: validate() reports the cycle, an agent re-homes a page to
+// fix it, and that call used to hang the tab with every unsaved edit in it.
+{
+ const cyclic = load([
+ p('A', [b('a1')], { parent: 'B' }),
+ p('B', [b('b1')], { parent: 'A' }),
+ p('C', [b('c1')]),
+ ])
+ ok(cyclic.pages.find((x) => x.id === 'A')?.parent === 'B', 'a page cycle survives loading (so it must be handled)')
+
+ // IN A CHILD PROCESS, with a hard timeout.
+ //
+ // Measuring elapsed time AFTER the call cannot report a call that never
+ // returns: the first version of this hung the whole rig, so CI would have
+ // timed out with nothing to read instead of naming the defect. A non-
+ // terminating walk is exactly the failure being guarded, so the guard has to
+ // survive it.
+ const { execFileSync } = await import('node:child_process')
+ const probe = (expr: string, label: string) => {
+ const src =
+ `import { parseDoc, FORMAT } from '${new URL('../spaces/src/model.ts', import.meta.url).pathname}';` +
+ `import * as A from '${new URL('../spaces/src/agent.ts', import.meta.url).pathname}';` +
+ `const r = parseDoc(JSON.stringify({format:FORMAT,version:1,docId:'c',title:'c',home:'A',pages:[` +
+ `{id:'A',title:'A',parent:'B',blocks:[{id:'a1',type:'p',html:'a'}]},` +
+ `{id:'B',title:'B',parent:'A',blocks:[{id:'b1',type:'p',html:'b'}]},` +
+ `{id:'C',title:'C',blocks:[{id:'c1',type:'p',html:'c'}]}]}));` +
+ `${expr};`
+ try {
+ execFileSync(process.execPath, ['--input-type=module', '-e', src], { timeout: 8000, stdio: 'pipe' })
+ return true
+ } catch {
+ return false
+ }
+ }
+ ok(probe(`A.planUpdatePage(r.doc, 'C', { parent: 'A' })`, ''), 'updatePage terminates on a page cycle')
+ ok(probe(`A.validateDoc(r.doc)`, ''), 'validate terminates on a page cycle')
+ ok(probe(`A.outlineDoc(r.doc)`, ''), 'outline terminates on a page cycle')
+ ok(probe(`A.statsDoc(r.doc)`, ''), 'stats terminates on a page cycle')
+}
+
+// ---- outline() and stats() describe the document they were given -----------
+{
+ const doc = load([
+ p('p1', [b('b1', 'h1'), b('b2'), b('b3')]),
+ p('p2', [b('b4')], { parent: 'p1' }),
+ p('p3', [b('b5')], { archived: true }),
+ ])
+ const o = outlineDoc(doc)
+ ok(o.pages === 3 && o.blocks === 5, `outline counts the space (${o.pages} pages, ${o.blocks} blocks)`)
+ // FLAT and in pre-order, with `depth` and `parent` — the same convention the
+ // document itself uses for pages and blocks, so an agent that can read one
+ // can read the other. (Nested children would be a second shape to learn.)
+ const tree = o.tree as Array<{ id: string; depth: number; parent?: string }>
+ ok(tree.length === 3, `outline's tree holds every page (${tree.length})`)
+ ok(tree.every((n) => typeof n.depth === 'number'), 'every node carries its depth')
+ const child = tree.find((x) => x.id === 'p2')
+ ok(child?.depth === 1 && child?.parent === 'p1', 'a child page reports depth 1 and names its parent')
+ ok(tree.findIndex((x) => x.id === 'p1') < tree.findIndex((x) => x.id === 'p2'),
+ 'and a child always follows its parent, so one forward pass rebuilds the tree')
+
+ const s = statsDoc(doc)
+ ok(s.pages === 3 && s.blocks === 5, `stats counts pages and blocks (${s.pages}/${s.blocks})`)
+ ok(s.archived === 1, 'stats counts archived pages separately')
+ ok(s.bytes.document > 0, 'stats reports a document size, so "why is this file large" is answerable')
+ ok(typeof s.todos.total === 'number', 'stats reports to-do progress')
+}
+
+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 718c8c03..222d9764 100644
--- a/scripts/test-spaces-model.ts
+++ b/scripts/test-spaces-model.ts
@@ -1065,5 +1065,43 @@ for (const [label, input, err] of [
'the preview is size-budgeted, with a title card as the fallback')
}
+// ---- a block can be moved, duplicated and deleted, on every device --------
+// Four actions existed NOWHERE: move up, move down, duplicate, delete.
+// Deletion was Backspace-into-the-previous-block; reordering was drag-only —
+// and the drag gutter was display:none on touch, so on a phone a block could
+// not be reordered or removed at all.
+{
+ const fsb = await import('node:fs')
+ const rdb = (f: string) => fsb.readFileSync(new URL(`../spaces/src/${f}`, import.meta.url), 'utf8')
+ const ed = rdb('editor.ts'), css = rdb('styles.css')
+
+ ok(/private blockActions\(/.test(ed), 'the block actions are declared as ONE list')
+ for (const label of ['Turn into', 'Add below', 'Move up', 'Move down', 'Duplicate', 'Delete']) {
+ ok(new RegExp(`t\\('${label}`).test(ed), `…including ${label}`)
+ }
+ ok(/openBlockMenu\(/.test(ed) && /this\.blockActions\(id\)/.test(ed),
+ 'and the menu is built from that list rather than a second copy')
+
+ // the gutter must SURVIVE the drawer breakpoint, or none of it is reachable
+ const narrow = css.slice(css.indexOf('@media (max-width: 820px)'))
+ ok(!/\.sp-gutter \{ display: none/.test(narrow), 'the gutter is not hidden on touch')
+ ok(/\.sp-gutter \{ opacity: 1/.test(narrow), '…it is shown rather than hovered')
+ ok(/sp-sheet/.test(css) && /isDrawer\(\)/.test(ed),
+ 'and the menu becomes a bottom sheet where a 5px anchor would be unusable')
+
+ // a disabled action is shown, not removed — a menu that changes shape is one
+ // you have to re-read every time
+ ok(/sp-off/.test(css) && /a\.off/.test(ed), 'unavailable actions are disabled, not hidden')
+
+ // THE SUBTREE RULES. Each of these silently loses or orphans work.
+ ok(/never drop a block inside its own subtree/.test(ed), 'a block cannot be moved into itself')
+ ok(/AFTER the target's whole SUBTREE/.test(ed),
+ 'a move lands after the target\'s whole subtree, not between a container and its children')
+ ok(/if \(c\.parent && remap\.has\(c\.parent\)\) c\.parent = remap\.get\(c\.parent\)/.test(ed),
+ 'a duplicate rewrites its copies\' parent links, so the copy owns the copies')
+ ok(/if \(!page\.blocks\.length\) page\.blocks\.push\(newBlock\('p'\)\)/.test(ed),
+ 'deleting the last block leaves something to type into')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-spaces-undo.ts b/scripts/test-spaces-undo.ts
new file mode 100644
index 00000000..163e0d52
--- /dev/null
+++ b/scripts/test-spaces-undo.ts
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Undo: depth on a real document, and correctness across mixed scopes.
+//
+// esbuild scripts/test-spaces-undo.ts --bundle --platform=node --format=esm …
+//
+// (Bundled rather than run directly because store.ts imports './model' without
+// an extension, which node's ESM resolver cannot follow. Same pattern as the
+// autosave and validate rigs.)
+//
+// WHY. Every checkpoint used to stringify the WHOLE document. Measured on a
+// 200-page, 2.5 MB handbook: fifty edits left an undo depth of NINE, because
+// nine snapshots of 2.5 MB exhaust a 24 MB budget. A writer who notices a
+// mistake ten edits back cannot reach it, and nothing tells them why.
+//
+// So a typing run — one block, one page, and by far the most common edit —
+// records only that PAGE. The budget then holds hundreds of entries instead of
+// nine.
+//
+// WHAT MAKES THAT DANGEROUS, and what this rig is really for: a page entry
+// restores one page and leaves the rest of the document alone. That is only
+// correct if the mutation touched nothing else. Scope is therefore opted into,
+// `doc` is the default, and the cases below are the ones where a wrong scope
+// would silently lose work — mixed scopes, interleaved undo/redo, and edits
+// spanning two pages.
+
+import { Store } from '../spaces/src/store.ts'
+import { parseDoc, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'
+
+let checks = 0
+let failures = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+function load(pages: unknown[]): SpacesDoc {
+ const r = parseDoc(JSON.stringify({
+ format: FORMAT, version: 1, docId: 'u', title: 'U', home: (pages[0] as { id: string }).id,
+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', measure: 720 },
+ pages,
+ }))
+ if (!r.ok) throw new Error('fixture did not parse')
+ return r.doc
+}
+const page = (id: string, text: string) =>
+ ({ id, title: id, blocks: [{ id: `${id}b`, type: 'p', html: text }] })
+const textOf = (s: Store, pid: string) =>
+ String(s.doc.pages.find((p) => p.id === pid)?.blocks[0]?.html ?? '')
+
+console.log('bento/spaces undo\n')
+
+// ---- depth on a document people actually have ------------------------------
+{
+ const pages = Array.from({ length: 200 }, (_, i) => ({
+ id: `p${i}`, title: `Page ${i}`,
+ blocks: Array.from({ length: 40 }, (_, j) => ({
+ id: `p${i}b${j}`, type: 'p',
+ html: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod '
+ + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, '
+ + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
+ })),
+ }))
+ const doc = load(pages)
+ const mb = JSON.stringify(doc).length / 1024 / 1024
+ const s = new Store(doc)
+ for (let n = 0; n < 150; n++) {
+ s.runEdit('p0b0', () => { s.doc.pages[0].blocks[0].html = `typed ${n}` })
+ s.endRun()
+ }
+ let depth = 0
+ while (s.canUndo) { s.undo(); depth++ }
+ ok(depth >= 150, `${mb.toFixed(1)} MB document keeps 150 typing runs undoable (got ${depth})`)
+ ok(s.doc.pages.length === 200 && s.doc.pages[199].blocks.length === 40,
+ 'and undoing 150 times leaves every other page untouched')
+}
+
+// ---- a page entry restores ONE page ----------------------------------------
+{
+ const s = new Store(load([page('a', 'A0'), page('b', 'B0')]))
+ s.goToPage('a')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A1' })
+ s.endRun()
+ s.goToPage('b')
+ s.runEdit('bb', () => { s.doc.pages[1].blocks[0].html = 'B1' })
+ s.endRun()
+
+ s.undo()
+ ok(textOf(s, 'b') === 'B0' && textOf(s, 'a') === 'A1',
+ 'undo takes back the last page edit and leaves the earlier one')
+ s.undo()
+ ok(textOf(s, 'a') === 'A0' && textOf(s, 'b') === 'B0', 'and then the one before it')
+}
+
+// ---- page and doc entries interleave in the right order --------------------
+// The order matters most when they mix: a doc entry restores the whole
+// document, so a page entry taken AFTER it must not be applied on top of a
+// document that no longer contains that page.
+{
+ const s = new Store(load([page('a', 'A0')]))
+ s.goToPage('a')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A1' }) // page
+ s.endRun()
+ s.commit(() => { s.doc.pages.push(page('c', 'C0') as never) }) // doc
+ s.goToPage('c')
+ s.runEdit('cb', () => { s.doc.pages[1].blocks[0].html = 'C1' }) // page
+ s.endRun()
+
+ ok(s.doc.pages.length === 2 && textOf(s, 'c') === 'C1', 'set-up: two pages, both edited')
+ s.undo()
+ ok(textOf(s, 'c') === 'C0', 'undo 1 takes back the page edit on the new page')
+ s.undo()
+ ok(s.doc.pages.length === 1, 'undo 2 takes back the page creation')
+ ok(textOf(s, 'a') === 'A1', '…without disturbing the earlier page edit')
+ s.undo()
+ ok(textOf(s, 'a') === 'A0', 'undo 3 takes back that too')
+ ok(!s.canUndo, 'and the history is exhausted, not looping')
+}
+
+// ---- redo returns exactly what undo took -----------------------------------
+{
+ const s = new Store(load([page('a', 'A0')]))
+ s.goToPage('a')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A1' })
+ s.endRun()
+ s.commit(() => { s.doc.pages.push(page('z', 'Z0') as never) })
+
+ s.undo(); s.undo()
+ ok(textOf(s, 'a') === 'A0' && s.doc.pages.length === 1, 'undone to the start')
+ s.redo()
+ ok(textOf(s, 'a') === 'A1', 'redo restores the page edit')
+ s.redo()
+ ok(s.doc.pages.length === 2, 'redo restores the structural change')
+ ok(!s.canRedo, 'and there is nothing left to redo')
+}
+
+// ---- a new edit clears the redo branch -------------------------------------
+{
+ const s = new Store(load([page('a', 'A0')]))
+ s.goToPage('a')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A1' })
+ s.endRun()
+ s.undo()
+ ok(s.canRedo, 'after undo there is something to redo')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A2' })
+ s.endRun()
+ ok(!s.canRedo, 'a new edit drops the redo branch rather than leaving a stale future')
+}
+
+// ---- undo restores the VIEW too --------------------------------------------
+{
+ const s = new Store(load([page('a', 'A0'), page('b', 'B0')]))
+ s.goToPage('a')
+ s.runEdit('ab', () => { s.doc.pages[0].blocks[0].html = 'A1' })
+ s.endRun()
+ s.goToPage('b')
+ s.undo()
+ ok(s.pageId === 'a', 'undo returns you to the page the change was made on')
+}
+
+// ---- a read-only space records nothing -------------------------------------
+{
+ const s = new Store(load([page('a', 'A0')]))
+ s.readOnly = true
+ s.commit(() => { s.doc.pages[0].blocks[0].html = 'nope' })
+ ok(!s.canUndo && textOf(s, 'a') === 'A0', 'a read-only space neither changes nor records')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 7c19cbfc..d0c8f2b5 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -656,7 +656,7 @@ export class Editor {
grip.innerHTML = ICONS.grip
grip.title = t('Drag to move, click for block options')
grip.setAttribute('aria-label', t('Block options'))
- grip.addEventListener('click', () => this.openSlash(blockId, grip))
+ grip.addEventListener('click', () => this.openBlockMenu(blockId, grip))
grip.addEventListener('dragstart', (e) => {
e.dataTransfer?.setData('text/bento-block', blockId)
node.classList.add('sp-dragging')
@@ -691,6 +691,144 @@ export class Editor {
}
/** Move a block (and anything nested under it) to sit after another. */
+ /**
+ * What you can do to a block, declared ONCE.
+ *
+ * Four of these existed NOWHERE, on any device: move up, move down,
+ * duplicate, delete. Deletion was Backspace-into-the-previous-block and
+ * reordering was drag-only — and the drag gutter is hidden on touch, so on a
+ * phone a block could not be reordered or removed at all.
+ *
+ * One list, so the desktop menu and the touch sheet cannot drift — the same
+ * reasoning as the topbar's secondary actions.
+ */
+ private blockActions(id: string): Array<{ icon: IconName; label: string; hint: string; run: () => void; off?: boolean }> {
+ const s = this.store
+ const page = s.page
+ const blocks = page?.blocks ?? []
+ const at = blocks.findIndex((b) => b.id === id)
+ // a block moves past its SIBLINGS; a child cannot jump out of its parent by
+ // stepping, which would silently re-home it
+ const owner = blocks[at]?.parent
+ const sibs = blocks.filter((b) => b.parent === owner)
+ const si = sibs.findIndex((b) => b.id === id)
+
+ return [
+ { icon: 'text', label: t('Turn into…'), hint: t('Change this block’s type'),
+ run: () => this.openSlash(id) },
+ { icon: 'plus', label: t('Add below'), hint: '⏎', run: () => this.insertAfter(id) },
+ { icon: 'up', label: t('Move up'), hint: '', off: si <= 0,
+ run: () => { if (si > 0) this.moveBefore(id, sibs[si - 1].id) } },
+ { icon: 'down', label: t('Move down'), hint: '', off: si < 0 || si >= sibs.length - 1,
+ run: () => { if (si >= 0 && si < sibs.length - 1) this.moveBlock(id, sibs[si + 1].id) } },
+ { icon: 'copy', label: t('Duplicate'), hint: '', run: () => this.duplicateBlock(id) },
+ { icon: 'trash', label: t('Delete'), hint: '⌫', run: () => this.deleteBlock(id) },
+ ]
+ }
+
+ /** The block actions, as a menu. Anchored on a wide screen, a sheet on a phone. */
+ private openBlockMenu(id: string, anchor: HTMLElement): void {
+ if (this.store.readOnly || this.reading) return
+ this.closeOverlay()
+ const sheet = this.isDrawer()
+ const pop = el('div', sheet ? 'sp-pop sp-sheet' : 'sp-pop')
+ pop.setAttribute('role', 'menu')
+ this.trapAndClose(pop, () => this.focusBlock(id))
+ for (const a of this.blockActions(id)) {
+ const item = this.menuItem(a.icon, a.label, a.hint, () => { this.closeOverlay(); a.run() })
+ if (a.off) { item.setAttribute('aria-disabled', 'true'); item.classList.add('sp-off') }
+ pop.append(item)
+ }
+ this.overlay = pop
+ document.body.append(pop)
+ if (sheet) pop.classList.add('sp-sheet-in')
+ else place(pop, anchor)
+ const away = (ev: MouseEvent) => {
+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
+ }
+ setTimeout(() => document.addEventListener('mousedown', away), 0)
+ }
+
+ /** Move `id` to sit BEFORE `target` — the inverse of moveBlock's "after". */
+ private moveBefore(id: string, target: string): void {
+ const page = this.store.page
+ if (!page) return
+ const before = page.blocks.findIndex((b) => b.id === target)
+ // the block that precedes the target is what `after` needs; at the top of a
+ // sibling run there is none, so splice to the front instead
+ const prev = page.blocks.slice(0, before).reverse().find((b) => b.parent === page.blocks[before]?.parent)
+ if (prev) this.moveBlock(id, prev.id)
+ else this.moveToFront(id)
+ }
+
+ private duplicateBlock(id: string): void {
+ const s = this.store
+ const page = s.page
+ if (!page) return
+ const at = page.blocks.findIndex((b) => b.id === id)
+ if (at < 0) return
+ // the SUBTREE, with fresh ids and the parent links rewritten to match, or a
+ // duplicated toggle's copy would adopt the original's children
+ const remap = new Map<string, string>()
+ const group: Block[] = []
+ const take = (owner: string) => {
+ for (const b of page.blocks) {
+ if (b.parent !== owner) continue
+ group.push(b)
+ take(b.id)
+ }
+ }
+ group.push(page.blocks[at])
+ take(id)
+ const copies = group.map((b) => {
+ const fresh = { ...JSON.parse(JSON.stringify(b)), id: newBlock(b.type).id } as Block
+ remap.set(b.id, fresh.id)
+ return fresh
+ })
+ for (const c of copies) if (c.parent && remap.has(c.parent)) c.parent = remap.get(c.parent)
+ s.commit(() => { page.blocks.splice(at + group.length, 0, ...copies) })
+ this.paintPage()
+ this.focusBlock(copies[0].id)
+ }
+
+ private deleteBlock(id: string): void {
+ const s = this.store
+ const page = s.page
+ if (!page) return
+ const at = page.blocks.findIndex((b) => b.id === id)
+ if (at < 0) return
+ // children go with their owner, or they re-home at the top of the page and
+ // reappear in a document the author believed they had emptied
+ const doomed = new Set([id])
+ let grew = true
+ while (grew) {
+ grew = false
+ for (const b of page.blocks) {
+ if (b.parent && doomed.has(b.parent) && !doomed.has(b.id)) { doomed.add(b.id); grew = true }
+ }
+ }
+ const before = page.blocks[at - 1]?.id
+ s.commit(() => {
+ page.blocks = page.blocks.filter((b) => !doomed.has(b.id))
+ // a page is never left with nothing to type into
+ if (!page.blocks.length) page.blocks.push(newBlock('p'))
+ })
+ this.paintPage()
+ this.focusBlock(before ?? page.blocks[0]?.id)
+ }
+
+ private moveToFront(id: string): void {
+ const page = this.store.page
+ if (!page) return
+ const at = page.blocks.findIndex((b) => b.id === id)
+ if (at <= 0) return
+ this.store.commit(() => {
+ const [b] = page.blocks.splice(at, 1)
+ page.blocks.unshift(b)
+ })
+ this.paintPage()
+ }
+
private moveBlock(moved: string, after: string): void {
const s = this.store
const page = s.page
@@ -707,7 +845,23 @@ export class Editor {
s.commit(() => {
const group = [moved, ...kids].map((id) => page.blocks.find((b) => b.id === id)!).filter(Boolean)
for (const b of group) page.blocks.splice(page.blocks.indexOf(b), 1)
- const at = page.blocks.findIndex((b) => b.id === after) + 1
+ // AFTER the target's whole SUBTREE, not merely after the target.
+ // Landing immediately after a container put the block between that
+ // container and its children — the array stayed pre-order but the child
+ // no longer followed its parent contiguously, so the renderer's forward
+ // pass popped the open container and drew the child at root. Measured:
+ // moving the first block down past a toggle un-nested the toggle's body.
+ const tgt = page.blocks.findIndex((b) => b.id === after)
+ let at = tgt + 1
+ if (tgt >= 0) {
+ const under = new Set([after])
+ while (at < page.blocks.length) {
+ const p = page.blocks[at].parent
+ if (!p || !under.has(p)) break
+ under.add(page.blocks[at].id)
+ at++
+ }
+ }
page.blocks.splice(at, 0, ...group)
})
this.paintPage()
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index 50255490..38b6d8cc 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -216,4 +216,11 @@ export const de: Catalog = {
"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.",
+ "Turn into…": "Umwandeln in…",
+ "Change this block’s type": "Den Typ dieses Blocks ändern",
+ "Add below": "Darunter einfügen",
+ "Move up": "Nach oben",
+ "Move down": "Nach unten",
+ "Duplicate": "Duplizieren",
+ "Delete": "Löschen",
}
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index e664411d..d005ec19 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -216,4 +216,11 @@ export const es: Catalog = {
"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.",
+ "Turn into…": "Convertir en…",
+ "Change this block’s type": "Cambiar el tipo de este bloque",
+ "Add below": "Añadir debajo",
+ "Move up": "Subir",
+ "Move down": "Bajar",
+ "Duplicate": "Duplicar",
+ "Delete": "Eliminar",
}
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index 084c881a..81cde408 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -216,4 +216,11 @@ export const fr: Catalog = {
"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.",
+ "Turn into…": "Convertir en…",
+ "Change this block’s type": "Changer le type de ce bloc",
+ "Add below": "Ajouter en dessous",
+ "Move up": "Monter",
+ "Move down": "Descendre",
+ "Duplicate": "Dupliquer",
+ "Delete": "Supprimer",
}
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index fee3309e..4eb7de14 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -216,4 +216,11 @@ export const it: Catalog = {
"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.",
+ "Turn into…": "Converti in…",
+ "Change this block’s type": "Cambia il tipo di questo blocco",
+ "Add below": "Aggiungi sotto",
+ "Move up": "Sposta su",
+ "Move down": "Sposta giù",
+ "Duplicate": "Duplica",
+ "Delete": "Elimina",
}
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index db1eaf82..8a8e7820 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -216,4 +216,11 @@ export const ja: Catalog = {
"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} 件のノート名が重複しているため、その名前のリンクはすべて最初のノートに向いています。",
+ "Turn into…": "種類を変更…",
+ "Change this block’s type": "このブロックの種類を変更します",
+ "Add below": "下に追加",
+ "Move up": "上へ移動",
+ "Move down": "下へ移動",
+ "Duplicate": "複製",
+ "Delete": "削除",
}
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index 49216894..8d1d08e6 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -22,6 +22,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
+ "Add below": ["下に追加","在下方添加","在下方新增","Añadir debajo","Ajouter en dessous","Darunter einfügen","Aggiungi sotto","Adicionar 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"],
@@ -30,6 +31,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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 block’s type": ["このブロックの種類を変更します","更改此块的类型","變更此區塊的類型","Cambiar el tipo de este bloque","Changer le type de ce bloc","Den Typ dieses Blocks ändern","Cambia il tipo di questo blocco","Alterar o tipo deste bloco"],
"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."],
@@ -47,6 +49,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Could not reach the update channel.": ["更新チャンネルに接続できませんでした。","无法连接更新通道。","無法連線到更新來源。","No se pudo contactar con el canal de actualizaciones.","Impossible de joindre le canal de mise à jour.","Der Update-Kanal war nicht erreichbar.","Impossibile raggiungere il canale degli aggiornamenti.","Não foi possível contactar o canal de atualizações."],
"Could not verify an update, so nothing was changed.": ["更新を検証できなかったため、何も変更していません。","无法验证更新,因此未做任何改动。","無法驗證更新,因此未變更任何內容。","No se pudo verificar la actualización, así que no se cambió nada.","Impossible de vérifier une mise à jour, rien n’a été modifié.","Ein Update ließ sich nicht verifizieren, daher wurde nichts geändert.","Impossibile verificare l’aggiornamento, quindi non è stato modificato nulla.","Não foi possível verificar a atualização, por isso nada foi alterado."],
"Create “{name}”": ["「{name}」を作成","创建“{name}”","建立「{name}」","Crear «{name}»","Créer « {name} »","„{name}“ erstellen","Crea «{name}»","Criar “{name}”"],
+ "Delete": ["削除","删除","刪除","Eliminar","Supprimer","Löschen","Elimina","Eliminar"],
"Delete “{name}”?": ["「{name}」を削除しますか?","要删除“{name}”吗?","要刪除「{name}」嗎?","¿Eliminar «{name}»?","Supprimer « {name} » ?","„{name}“ löschen?","Eliminare «{name}»?","Eliminar “{name}”?"],
"Delete…": ["削除…","删除…","刪除…","Eliminar…","Supprimer…","Löschen…","Elimina…","Eliminar…"],
"Discard": ["破棄","放弃","捨棄","Descartar","Ignorer","Verwerfen","Ignora","Descartar"],
@@ -54,6 +57,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
+ "Duplicate": ["複製","创建副本","建立副本","Duplicar","Dupliquer","Duplizieren","Duplica","Duplicar"],
"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"],
@@ -93,6 +97,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
+ "Move down": ["下へ移動","下移","下移","Bajar","Descendre","Nach unten","Sposta giù","Mover para baixo"],
+ "Move up": ["上へ移動","上移","上移","Subir","Monter","Nach oben","Sposta su","Mover para cima"],
"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"],
@@ -175,6 +181,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
+ "Turn into…": ["種類を変更…","转换为…","轉換為…","Convertir en…","Convertir en…","Umwandeln in…","Converti in…","Converter em…"],
"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"],
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index 9598a3ca..f4d29398 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -216,4 +216,11 @@ export const pt: Catalog = {
"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.",
+ "Turn into…": "Converter em…",
+ "Change this block’s type": "Alterar o tipo deste bloco",
+ "Add below": "Adicionar abaixo",
+ "Move up": "Mover para cima",
+ "Move down": "Mover para baixo",
+ "Duplicate": "Duplicar",
+ "Delete": "Eliminar",
}
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index c5fa0165..a8eb9bdc 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -216,4 +216,11 @@ export const zh_Hans: Catalog = {
"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} 个笔记名称重复,因此指向该名称的链接都指向了第一个。",
+ "Turn into…": "转换为…",
+ "Change this block’s type": "更改此块的类型",
+ "Add below": "在下方添加",
+ "Move up": "上移",
+ "Move down": "下移",
+ "Duplicate": "创建副本",
+ "Delete": "删除",
}
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index 5366ee16..283ff1fe 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -216,4 +216,11 @@ export const zh_Hant: Catalog = {
"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} 個筆記名稱重複,因此指向該名稱的連結都指向了第一個。",
+ "Turn into…": "轉換為…",
+ "Change this block’s type": "變更此區塊的類型",
+ "Add below": "在下方新增",
+ "Move up": "上移",
+ "Move down": "下移",
+ "Duplicate": "建立副本",
+ "Delete": "刪除",
}
diff --git a/spaces/src/icons.ts b/spaces/src/icons.ts
index efa46776..bd1930aa 100644
--- a/spaces/src/icons.ts
+++ b/spaces/src/icons.ts
@@ -37,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"/>'),
+ up: svg('<path d="m18 15-6-6-6 6"/>'),
+ down: svg('<path d="m6 9 6 6 6-6"/>'),
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"/>'),
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index cf8f05c4..1b4ed810 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -11,6 +11,8 @@
// closes on idle, on the caret leaving the block, on any structural change, on
// save, and on replaceDoc. One run = one undo entry = later, one text batch.
+type Scope = 'doc' | 'page'
+
import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'
type Listener = () => void
@@ -22,11 +24,26 @@ const RUN_IDLE_MS = 600
* snapshots retain tens of MB. Assets are excluded from snapshots entirely. */
const UNDO_BUDGET = 24 * 1024 * 1024
-interface Entry {
- json: string
- /** page in view when the entry was taken, so undo restores the view too */
- pageId: string
-}
+/**
+ * One undoable step.
+ *
+ * A `page` entry holds ONE page's JSON; a `doc` entry holds the whole document
+ * minus its assets. The distinction is the difference between an undo history
+ * that survives a real document and one that does not: measured on a 200-page,
+ * 2.5 MB handbook, whole-document entries gave a depth of NINE — fifty edits,
+ * and you can take back the last nine — because every checkpoint stringified
+ * 2.5 MB against a 24 MB budget. The same budget holds hundreds of page
+ * entries, and a page entry costs ~12 KB rather than 2.5 MB to take.
+ *
+ * DOC IS THE DEFAULT, and page scope is opted into. A page entry restores one
+ * page by id and leaves the rest of the document alone, so it is only correct
+ * when the mutation touched nothing else — the caller knows that and the store
+ * cannot cheaply check it. Defaulting the other way would corrupt undo for any
+ * caller that forgot.
+ */
+type Entry =
+ | { kind: 'doc'; json: string; viewId: string }
+ | { kind: 'page'; pageId: string; json: string; viewId: string }
export class Store {
doc: SpacesDoc
@@ -94,10 +111,10 @@ export class Store {
* A structural change: one undoable step. Closes any open typing run first,
* so the run's text and the structural edit never merge into one entry.
*/
- commit(mutate: () => void, opts: { structure?: boolean } = {}): void {
+ commit(mutate: () => void, opts: { structure?: boolean; scope?: Scope } = {}): void {
if (this.readOnly) return
this.endRun()
- this.checkpoint()
+ this.checkpoint(opts.scope ?? 'doc')
mutate()
this.dirty = true
this.reindex()
@@ -113,7 +130,9 @@ export class Store {
if (this.readOnly) return
if (this.runBlock !== blockId) {
this.endRun()
- this.checkpoint()
+ // A typing run is one block in the page in view, by definition — the
+ // cheapest and by far the most common checkpoint there is.
+ this.checkpoint('page')
this.runBlock = blockId
}
mutate()
@@ -159,9 +178,20 @@ export class Store {
return JSON.stringify(rest)
}
- checkpoint(): void {
+ /** An entry for the state as it is NOW, at the requested scope. */
+ private entry(scope: Scope): Entry {
+ if (scope === 'page') {
+ const page = this.index.page.get(this.pageId)
+ // no page in view is not a page-scoped edit — fall back rather than
+ // record an entry that restores nothing
+ if (page) return { kind: 'page', pageId: page.id, json: JSON.stringify(page), viewId: this.pageId }
+ }
+ return { kind: 'doc', json: this.snapshot(), viewId: this.pageId }
+ }
+
+ checkpoint(scope: Scope = 'doc'): void {
if (this.readOnly) return
- this.undoStack.push({ json: this.snapshot(), pageId: this.pageId })
+ this.undoStack.push(this.entry(scope))
this.redoStack.length = 0
let bytes = 0
for (let i = this.undoStack.length - 1; i >= 0; i--) {
@@ -172,9 +202,18 @@ 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
+ if (entry.kind === 'page') {
+ const at = this.doc.pages.findIndex((p) => p.id === entry.pageId)
+ // The page can be gone if a later doc-level step removed it. Undo runs in
+ // order, so the step that removed it is undone FIRST and the page is back
+ // by the time this entry is reached — but a hand-built history could
+ // reach here, and dropping the entry is better than throwing.
+ if (at >= 0) this.doc.pages[at] = JSON.parse(entry.json) as Page
+ } else {
+ const assets = this.doc.assets
+ this.doc = { ...(JSON.parse(entry.json) as SpacesDoc), ...(assets ? { assets } : {}) }
+ }
+ this.pageId = entry.viewId
this.reindex()
this.emit('doc')
this.emit('tree')
@@ -186,7 +225,9 @@ export class Store {
this.endRun()
const entry = this.undoStack.pop()
if (!entry) return
- this.redoStack.push({ json: this.snapshot(), pageId: this.pageId })
+ // the inverse entry is taken at the SAME scope, or redo would restore a
+ // whole document over a one-page change
+ this.redoStack.push(this.entry(entry.kind))
this.restore(entry)
}
@@ -195,7 +236,7 @@ export class Store {
this.endRun()
const entry = this.redoStack.pop()
if (!entry) return
- this.undoStack.push({ json: this.snapshot(), pageId: this.pageId })
+ this.undoStack.push(this.entry(entry.kind))
this.restore(entry)
}
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index 8cf9a024..2ef7c083 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -421,7 +421,13 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
[dir='rtl'] .sp-side.sp-open { inset: 0 0 0 auto; }
.sp-scrim { position: fixed; inset: 0; background: rgb(20 30 45 / .3); z-index: 45; }
.sp-main { padding: 26px 18px 45vh; }
- .sp-gutter { display: none; } /* no hover on touch; long-press later */
+ /* THE GUTTER STAYS ON TOUCH. It used to be display:none here, on the
+ reasoning that there is no hover — but hover was how you reached the only
+ controls a block has, so hiding it meant a block could not be reordered or
+ deleted on a phone AT ALL. It is shown rather than hovered, and sized for
+ a thumb. */
+ .sp-gutter { opacity: 1; position: static; display: flex; justify-content: flex-end; margin-bottom: 2px; }
+ .sp-gutter .sp-ghost { width: 40px; height: 34px; }
.sp-title { font-size: 27px; }
}
@@ -771,3 +777,21 @@ body.sp-col-resizing { cursor: col-resize; user-select: none; }
@media (max-width: 820px) {
.sp-panel-toggle { display: inline-flex; }
}
+
+/* A disabled action is shown, not hidden: "move up" missing from the top block
+ is a menu that changes shape, and a menu that changes shape is one you have
+ to re-read every time. */
+.sp-dditem.sp-off { opacity: .38; pointer-events: none; }
+
+/* On a phone a popover anchored to a 5px gutter button is unusable, so the
+ block menu is a sheet at the bottom edge — within reach of a thumb, and it
+ cannot be positioned off-screen. */
+.sp-pop.sp-sheet {
+ position: fixed; inset-inline: 8px; bottom: max(8px, env(safe-area-inset-bottom));
+ top: auto; width: auto; max-height: 62vh; border-radius: 14px;
+ padding: 8px; box-shadow: 0 -8px 40px rgb(20 30 45 / .28);
+ transform: translateY(8px); opacity: 0;
+ transition: transform .16s ease, opacity .16s ease;
+}
+.sp-pop.sp-sheet.sp-sheet-in { transform: none; opacity: 1; }
+.sp-pop.sp-sheet .sp-dditem { padding-block: 13px; }