Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: finish the writing surface — arrow navigation, a spoken Tab refusal, block controls (#444)

nyblnet1117f9b044bf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 03a6e65a..a1a10909 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -269,6 +269,12 @@ jobs:
# mistakes is made in the source.
run: node scripts/test-spaces-model.ts
+ - name: spaces caret + nesting
+ # Which seat an arrow key lands in, and what Tab resolves to. Caret
+ # MOVEMENT needs a browser; the arithmetic under it does not, and the
+ # arithmetic is where Tab-on-the-first-list-item was silently wrong.
+ run: node scripts/test-spaces-caret.ts
+
- name: Spaces chrome rig
# Every spaces menu is the kernel's createMenu (through
# spaces/src/menus.ts). This drives the BUILT shell with trusted CDP
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 67483b3a..8a963db8 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -6696,6 +6696,49 @@ mapped, 1 correctly absent, run by bento-team-slides.
Claude-Session: https://claude.ai/code/session_01Jcfdy8A69nonyATtm8vRy8
+
+## 2026-09-11 — spaces: Tab REFUSES on a block with nothing above it, visibly
+
+bento/spaces expresses nesting with one field: `Block.parent`, pointing at a
+preceding sibling. Every reader downstream treats that as structural — the
+renderer's indent, the markdown export's list levels, the outline, the graph,
+`mergeBack` re-homing orphans, the CRDT's per-node diff. There is no second
+representation and there never has been.
+
+So "indent the first item" is not a hard case, it is a case with no answer, and
+`editor.ts indent()` fell off the end of its backwards walk and returned. That
+was correct and completely silent: no indent, no feedback, no explanation. A
+control that does nothing and says nothing is worse than a missing one, because
+the reader concludes the app is broken rather than that the gesture does not
+apply. That silence was the bug, and it is what this fixes.
+
+**The considered alternative was an indent LEVEL**, which is what Google Docs
+stores and what would make Tab always "work". Rejected, and the deciding
+argument is permanence rather than taste: the format is additive and forever, so
+a level field would be a SECOND way to express nesting that every future reader
+must reconcile — what a `level: 2` block with a `parent` means, which wins, what
+the markdown export emits for an orphan at level 2, what two replicas do when
+one sets `parent` and the other sets `level`. A silent Tab costs an afternoon;
+a duplicate nesting model costs every version of the reader from here on.
+Notion, Workflowy, Bear and Logseq all refuse the same case, because they all
+nest by parenthood too.
+
+The refusal is now spoken: the status line says the rule, the block nudges, and
+the indent control in the block menu carries the reason as its label before the
+key is pressed. `spaces/src/nesting.ts` holds the argument and the pure
+resolution; `scripts/test-spaces-caret.ts` asserts the first item, the only
+block, the first child of a container and a block absent from the page —
+deliberately, because a Tab test written against the SECOND list item passes
+against the broken code exactly as happily as against the fixed code, which is
+how this shipped in the first place. NO FORMAT CHANGE.
+
+**Also settled here: where block controls live.** Not in the formatting bar —
+that appears on a SELECTION and is inline-only, and "make this a bullet" is
+something you do with a caret and nothing selected. They are a row at the top of
+the block menu (gutter grip, and a bottom sheet on a phone), which is per-block
+by construction and already the home of every other whole-block action. ⌘/ is
+its keyboard route, because the gutter is hover-revealed and ⇥ inside a block is
+indent.
## 2026-09-12 — bento/spaces: procedural covers are a render-time default on two surfaces, and a document theme preset is not a thing this app can honestly offer
**A page with no `cover` draws a generated one — never stored, never on paper,
diff --git a/scripts/test-spaces-caret.ts b/scripts/test-spaces-caret.ts
new file mode 100644
index 00000000..39dc5ee1
--- /dev/null
+++ b/scripts/test-spaces-caret.ts
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The writing surface's two decisions that are pure enough to assert:
+// WHICH SEAT an arrow key lands in, and WHAT Tab resolves to.
+//
+// node scripts/test-spaces-caret.ts
+//
+// Caret MOVEMENT cannot be asserted here — where a line wraps is the browser's
+// answer and there is no browser in this process. What can be asserted, and is
+// the part that was actually wrong, is the arithmetic underneath it:
+//
+// - `onEdgeLine` decides whether ↓ means "the next line of this paragraph" or
+// "the next block". Get it wrong in one direction and a wrapped paragraph
+// traps the caret; wrong in the other and its second line is unreachable.
+// - `indentTarget` decides what Tab does. THE FAILING CASE IS THE FIRST ITEM,
+// and a test written against the second item passes just as happily against
+// the code that shipped with the bug — which is how the bug shipped. Every
+// edge here is a case a happy-path test skips: the only block, the first
+// block, a block whose siblings are all nested elsewhere, a block that is
+// not on the page at all.
+
+import { onEdgeLine, stepSeat, tableStep, nearestByX, mergeLines, type Box } from '../spaces/src/caret.ts'
+import { indentTarget, canOutdent, type Nestable } from '../spaces/src/nesting.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+}
+
+const box = (top: number, bottom: number, left = 0, right = 100): Box => ({ top, bottom, left, right })
+
+// ---- onEdgeLine -------------------------------------------------------------
+// A three-line paragraph: lines at y 0–20, 20–40, 40–60.
+const para = [box(0, 20), box(20, 40), box(40, 60)]
+
+console.log('\nonEdgeLine — within the block before leaving it')
+ok(onEdgeLine(box(2, 18), para, -1), 'caret on line 1: ↑ leaves the block')
+ok(!onEdgeLine(box(2, 18), para, 1), '…and ↓ stays in it')
+ok(!onEdgeLine(box(22, 38), para, -1), 'caret on line 2: ↑ stays in the block')
+ok(!onEdgeLine(box(22, 38), para, 1), '…and so does ↓')
+ok(onEdgeLine(box(42, 58), para, 1), 'caret on line 3: ↓ leaves the block')
+ok(!onEdgeLine(box(42, 58), para, -1), '…and ↑ stays in it')
+
+console.log('\nonEdgeLine — the cases a single-line test never sees')
+const one = [box(0, 20)]
+ok(onEdgeLine(box(2, 18), one, -1) && onEdgeLine(box(2, 18), one, 1),
+ 'a ONE-line block is both edges at once')
+ok(onEdgeLine(box(0, 0), [], -1) && onEdgeLine(box(0, 0), [], 1),
+ 'an EMPTY block has no lines and is crossed in either direction')
+// a caret next to a taller inline is SHORTER than its line box: comparing tops
+// for equality would call this "not on the first line" and trap the caret
+ok(onEdgeLine(box(6, 14), para, -1), 'a short caret on a tall first line still counts as on it')
+// and the reverse: a caret on the last line must not read as being on the first
+ok(!onEdgeLine(box(46, 54), para, -1), '…while one on the last line does not')
+
+// ---- mergeLines -------------------------------------------------------------
+// getClientRects() gives a rect per inline BOX, not per line. The starter
+// space's first paragraph is two visual lines and FIVE rects, because of the
+// <strong> in the middle of the first one — measured in the built shell.
+console.log('\nmergeLines — fragments of one line are one line')
+const frags: Box[] = [
+ { top: 182, bottom: 201, left: 555, right: 983 }, // line 1, before the bold
+ { top: 182, bottom: 201, left: 983, right: 1089 }, // the bold run
+ { top: 182, bottom: 201, left: 983, right: 1089 }, // …reported twice
+ { top: 182, bottom: 201, left: 1089, right: 1261 }, // after it
+ { top: 209, bottom: 228, left: 555, right: 678 }, // line 2
+]
+const merged = mergeLines(frags)
+ok(merged.length === 2, `five rects over two lines merge to two (got ${merged.length})`)
+ok(merged[0].left === 555 && merged[0].right === 1261,
+ 'the first line spans the UNION of its fragments — clamping a goal column into')
+ok(merged[1].top === 209 && merged[1].right === 678, '…and the second line keeps its own extent')
+// a taller inline (a code span, a bigger font) shares the line it sits on
+ok(mergeLines([{ top: 10, bottom: 30, left: 0, right: 50 }, { top: 6, bottom: 34, left: 50, right: 90 }]).length === 1,
+ 'a taller fragment joins the line it overlaps, not a line of its own')
+ok(mergeLines([]).length === 0, 'nothing measures as nothing')
+// and ordering: rects can arrive out of visual order
+ok(mergeLines([{ top: 50, bottom: 70, left: 0, right: 9 }, { top: 10, bottom: 30, left: 0, right: 9 }])[0].top === 10,
+ 'lines come back top-first whatever order the rects arrived in')
+
+// ---- stepSeat ---------------------------------------------------------------
+console.log('\nstepSeat — the ends of the page')
+ok(stepSeat(5, 2, 1) === 3, 'forward from the middle')
+ok(stepSeat(5, 2, -1) === 1, 'back from the middle')
+ok(stepSeat(5, 4, 1) === -1, 'off the LAST seat: nowhere to go')
+ok(stepSeat(5, 0, -1) === -1, 'off the FIRST seat: nowhere to go')
+ok(stepSeat(1, 0, 1) === -1 && stepSeat(1, 0, -1) === -1, 'a page with one seat goes nowhere')
+
+// ---- tableStep --------------------------------------------------------------
+// Cells are row-major in the DOM and column-major on the screen, so a table is
+// stepped by the grid and never by document order.
+console.log('\ntableStep — the grid, not the DOM order')
+const size = { w: 3, h: 3 }
+ok(JSON.stringify(tableStep({ r: 1, c: 2 }, size, -1)) === '{"r":0,"c":2}',
+ '↑ from (1,2) stays in column 2 — document order would give (1,1)')
+ok(JSON.stringify(tableStep({ r: 1, c: 2 }, size, 1)) === '{"r":2,"c":2}', '↓ likewise')
+ok(tableStep({ r: 0, c: 1 }, size, -1) === null, '↑ off the top row leaves the table')
+ok(tableStep({ r: 2, c: 1 }, size, 1) === null, '↓ off the bottom row leaves the table')
+ok(tableStep({ r: 0, c: 0 }, { w: 1, h: 1 }, 1) === null, 'a 1×1 table is all edge')
+
+// ---- nearestByX -------------------------------------------------------------
+console.log('\nnearestByX — entering a table lands under the goal column')
+const cols = [box(0, 20, 0, 50), box(0, 20, 50, 80), box(0, 20, 80, 300)]
+ok(nearestByX(cols, 10) === 0, 'a column the caret is inside wins')
+ok(nearestByX(cols, 65) === 1, '…including a narrow one')
+ok(nearestByX(cols, 200) === 2, '…including a wide one')
+ok(nearestByX(cols, -40) === 0, 'left of everything: the first')
+ok(nearestByX(cols, 999) === 2, 'right of everything: the last')
+ok(nearestByX([], 10) === -1, 'no columns at all: no answer')
+// distance to the BOX, not to its centre. A caret sitting inside a wide first
+// column, near its right edge, belongs to that column — measuring to centres
+// hands it to the narrow one next door, which is the whole reason for the
+// clamp-to-zero above.
+const lopsided = [box(0, 20, 0, 300), box(0, 20, 300, 320)]
+ok(nearestByX(lopsided, 299) === 0, 'a point INSIDE a wide column stays in it')
+ok(nearestByX(lopsided, 305) === 1, '…and a point inside the narrow one stays there')
+
+// ---- indentTarget — THE CASE THE BUG WAS IN ---------------------------------
+console.log('\nindentTarget — Tab, including every case a happy path skips')
+const page = (...rows: Array<[string, string?]>): Nestable[] =>
+ rows.map(([id, parent]) => (parent === undefined ? { id } : { id, parent }))
+
+const list = page(['a'], ['b'], ['c'])
+ok(indentTarget(list, 'b').ok && (indentTarget(list, 'b') as any).parent === 'a',
+ 'the SECOND item nests under the first — the case that always worked')
+const first = indentTarget(list, 'a')
+ok(!first.ok && (first as any).why === 'first',
+ 'the FIRST item refuses, and says WHY — this returned silently before')
+const only = indentTarget(page(['solo']), 'solo')
+ok(!only.ok && (only as any).why === 'first', 'the ONLY block refuses the same way')
+const absent = indentTarget(list, 'nope')
+ok(!absent.ok && (absent as any).why === 'gone', 'a block not on the page is a caller bug, not a refusal')
+
+// nesting is by LEVEL: the preceding block must be a sibling, not any block
+const nested = page(['a'], ['b', 'a'], ['c', 'a'], ['d'])
+ok(indentTarget(nested, 'd').ok && (indentTarget(nested, 'd') as any).parent === 'a',
+ 'a top-level block skips past the nested run above it to the last top-level one')
+ok(indentTarget(nested, 'c').ok && (indentTarget(nested, 'c') as any).parent === 'b',
+ 'a nested block nests under its preceding SIBLING')
+const firstChild = indentTarget(nested, 'b')
+ok(!firstChild.ok && (firstChild as any).why === 'first',
+ 'the first child of a container refuses too — it is first at its level')
+
+// the first block on a page whose every other block is nested elsewhere
+const buried = page(['x', 'ghost'], ['y'])
+ok(indentTarget(buried, 'y').ok === false,
+ 'a block whose only predecessor is at another level has nothing to nest under')
+
+// ---- canOutdent -------------------------------------------------------------
+console.log('\ncanOutdent — by the EFFECTIVE parent')
+const eff = new Map<string, string | undefined>([['a', undefined], ['b', 'a'], ['c', undefined]])
+ok(canOutdent(eff, 'b'), 'a nested block outdents')
+ok(!canOutdent(eff, 'a'), 'a top-level block does not')
+ok(!canOutdent(eff, 'missing'), 'nor does one the map has never heard of')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjs
index 56511e78..20633eb5 100755
--- a/scripts/test-spaces.mjs
+++ b/scripts/test-spaces.mjs
@@ -47,6 +47,7 @@ const RIGS = [
{ name: 'agent', file: 'scripts/test-spaces-agent.ts' },
{ name: 'journal', file: 'scripts/test-spaces-journal.ts', tzs: TZS_JOURNAL },
{ name: 'calc', file: 'scripts/test-spaces-calc.ts', tzs: TZS_CALC },
+ { name: 'caret', file: 'scripts/test-spaces-caret.ts' },
{ name: 'undo', file: 'scripts/test-spaces-undo.ts', bundle: true },
{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },
{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 137de05b..9e708af6 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -486,6 +486,55 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
2026, from the same file. `bento.journal()` opens today's for an agent, and
`bento.journal('2026-08-06')` any day's.
+- **The arrow keys move between blocks, and within one first.** Every block is
+ its own `contenteditable` host, which is what keeps a Selection block-scoped
+ so splitting and merging can never re-mint an id — and the price, until now,
+ was that the browser's own caret movement stopped dead at a block boundary.
+ ↑ and ↓ did nothing at all; ← and → did nothing at the edges. There was no
+ arrow handling in the editor whatsoever.
+
+ ↓ from the first line of a wrapped paragraph means its second line, not the
+ next block, so the question asked is not "which block is this" but "is the
+ caret on the edge VISUAL line of its host" — measured off the caret's own
+ rectangle against the host's line boxes, never counted in characters, because
+ where a line wraps depends on the font, the width, the language and the marks.
+ The goal column is kept across consecutive vertical steps, so down onto a
+ short line and down again comes back out near the original x, and a pointer
+ ends the run. ← at the start of a block goes to the end of the one before and
+ → at the end to the start of the next. It crosses callouts, toggles and canvas
+ cards for free — they render in document order — and a table is stepped by its
+ GRID, because cells are row-major in the DOM and column-major on the screen;
+ entering one from above or below lands in the column the goal column is over,
+ not in the first cell. The table's own ⇥ and ⏎ are untouched.
+
+- **Tab on a block with nothing above it now says so.** A space expresses
+ nesting with one field — `Block.parent`, pointing at a preceding sibling — so
+ the first block at its level has nothing to nest under. `indent()` walked
+ backwards looking for one, found none, and returned in silence: no indent, no
+ feedback, no explanation, which reads as a broken app rather than as a gesture
+ that does not apply. It refuses out loud now, in the status line and with a
+ nudge on the block itself, and the indent control shows the reason before the
+ key is pressed.
+
+ The alternative was to allow it by storing an indent LEVEL, the way Google
+ Docs does. That is a permanent format addition and a SECOND way to express
+ nesting, which the renderer, the markdown export, the outline, the graph and
+ the CRDT would each have to reconcile forever; a silent Tab is worth an
+ afternoon and a duplicate nesting model is worth every future version. Notion,
+ Workflowy, Bear and Logseq all refuse the same case, because they all nest by
+ parenthood too. Nothing about the format changed. ⇧Tab still outdents — and
+ now explains itself when there is nothing to outdent from — and Tab still
+ commits a showing calc answer before it considers indenting at all.
+
+- **Bullets, numbers, to-dos, quotes, headings, indent and outdent have a
+ control.** There were none: the formatting bar is inline-only and appears on a
+ SELECTION, which is the wrong trigger for "make this a bullet" — you want that
+ with a caret and nothing selected. So the block's own format is a row at the
+ top of the block menu, the one the gutter grip opens and the one that is
+ already a bottom sheet on a phone. Indent and outdent existed on no surface at
+ all before this, at any width: ⇥ and ⇧⇥ were their only gesture, and a phone
+ keyboard has neither. ⌘/ opens the menu from the keyboard, since the gutter is
+ hover-revealed and ⇥ inside a block is indent.
- **A page with no cover gets a procedural one — on the home page and on every
gallery card, and nowhere else.** A gradient plus a geometric figure (orbs,
bands, a dot lattice, rings, facets or waves), seeded from the page id, drawn
diff --git a/spaces/src/blockbar.ts b/spaces/src/blockbar.ts
new file mode 100644
index 00000000..f8c899d4
--- /dev/null
+++ b/spaces/src/blockbar.ts
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The block format row — bullet, number, to-do, quote, headings, indent.
+//
+// WHY IT IS NOT IN THE FORMAT BAR, which is where it was first asked for.
+//
+// `formatbar.ts` appears on a SELECTION and everything in it is inline: bold,
+// italic, colour, link. "Make this a bullet" is not a thing you do to selected
+// words — you do it with a caret sitting in a block and nothing selected,
+// which is precisely the state in which that bar does not exist. Putting block
+// controls there would mean the only way to reach them is to select text you
+// did not want to change, and on a phone the bar shares its 40 pixels with
+// iOS's own Copy / Look Up callout, which is why it is a bottom dock there
+// already. There is no room and no trigger.
+//
+// WHERE THEY LIVE INSTEAD: the block menu — the one the gutter grip opens, and
+// the one that is already a bottom SHEET on a phone. It is per-block by
+// construction, so it works with a caret and no selection; the grip is the one
+// gutter control a phone keeps (styles.css hides the add-ghost below 700px and
+// leaves the grip), so it works on touch; and it was already the home of every
+// other whole-block action — move, duplicate, comment, delete. One surface for
+// "things you do to this block" rather than two.
+//
+// WHAT WAS MISSING BEFORE: the menu's only route to a list was "Turn into…",
+// which opens the slash menu — two steps, behind a label that does not say the
+// word "list". The row puts the eight types a writer reaches for on one tap,
+// and adds the two controls that existed on NO surface at all, at any width:
+// indent and outdent. Tab and Shift+Tab were their only gesture, and a phone
+// keyboard has neither.
+//
+// THE KEYBOARD ROUTE IS NOT OPTIONAL. The gutter is hover-revealed, so a
+// keyboard cannot reach the grip by tabbing to it from inside a block (Tab in
+// a block is indent). ⌘/ opens this menu on the focused block — the same key
+// Notion spends on the same question — and it is in the help overlay.
+//
+// The disabled indent button carries the REASON as its title and its
+// aria-label rather than merely greying out; that is the same refusal
+// nesting.ts documents, said before the key is pressed instead of after.
+
+import { t } from './i18n'
+import { ICONS, type IconName } from './icons'
+
+/** What the row needs from the editor around it. */
+export interface BlockBarHost {
+ /** the block's current type, so the active control can be shown as pressed */
+ type: string
+ /** false when this block is the first at its level — see nesting.ts */
+ canIndent: boolean
+ canOutdent: boolean
+ /** why indent is refused, already localized — shown on the disabled control */
+ indentRefusal: string
+ setType(type: string): void
+ indent(deeper: boolean): void
+}
+
+/**
+ * The row, as one element.
+ *
+ * Labels are `t()` calls on LITERALS at this call site. A table of keys fed
+ * through `t(MAP[k])` compiles, runs, reaches no catalog and still reports
+ * 100% packed — so the strings are written out, and they are written out in
+ * the same words the slash menu uses for the same types.
+ */
+export function blockFormatRow(h: BlockBarHost): HTMLElement {
+ const row = document.createElement('div')
+ row.className = 'sp-blockbar'
+ row.setAttribute('role', 'group')
+ row.setAttribute('aria-label', t('Block format'))
+
+ const types: Array<[IconName, string, string]> = [
+ ['text', 'p', t('Text')],
+ ['h1', 'h1', t('Heading 1')],
+ ['h2', 'h2', t('Heading 2')],
+ ['h3', 'h3', t('Heading 3')],
+ ['bullet', 'bullet', t('Bulleted list')],
+ ['number', 'number', t('Numbered list')],
+ ['todo', 'todo', t('To-do')],
+ ['quote', 'quote', t('Quote')],
+ ]
+
+ for (const [icon, type, label] of types) {
+ const b = button(icon, label)
+ const on = h.type === type
+ b.setAttribute('aria-pressed', on ? 'true' : 'false')
+ if (on) b.classList.add('sp-sel')
+ b.addEventListener('click', () => h.setType(type))
+ row.append(b)
+ }
+
+ row.append(el('span', 'sp-blockbar-gap'))
+
+ const out = button('outdent', t('Move back out'))
+ out.addEventListener('click', () => h.indent(false))
+ disable(out, !h.canOutdent, t('This block is not nested'))
+ row.append(out)
+
+ const inn = button('indent', t('Indent'))
+ inn.addEventListener('click', () => h.indent(true))
+ disable(inn, !h.canIndent, h.indentRefusal)
+ row.append(inn)
+
+ return row
+}
+
+function button(icon: IconName, label: string): HTMLButtonElement {
+ const b = document.createElement('button')
+ b.className = 'sp-blockbtn'
+ b.type = 'button'
+ b.innerHTML = ICONS[icon]
+ b.title = label
+ b.setAttribute('aria-label', label)
+ return b
+}
+
+/**
+ * Off, and SAYING WHY.
+ *
+ * `aria-disabled` rather than `disabled`: a disabled button is removed from
+ * the tab order, so the one control whose whole job is to explain itself would
+ * be the one a keyboard could not reach to read the explanation off. It stays
+ * focusable, announces itself as unavailable, and carries the reason.
+ */
+function disable(b: HTMLButtonElement, off: boolean, why: string): void {
+ if (!off) return
+ b.classList.add('sp-off')
+ b.setAttribute('aria-disabled', 'true')
+ b.title = `${b.title} — ${why}`
+ b.setAttribute('aria-label', b.title)
+}
+
+function el(tag: string, cls: string): HTMLElement {
+ const n = document.createElement(tag)
+ n.className = cls
+ return n
+}
diff --git a/spaces/src/caret.ts b/spaces/src/caret.ts
new file mode 100644
index 00000000..3e6b09a3
--- /dev/null
+++ b/spaces/src/caret.ts
@@ -0,0 +1,303 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Caret navigation ACROSS blocks.
+//
+// Every block in a space is its own contenteditable host — that is what keeps
+// Selection block-scoped so a split or a merge can never re-mint an id
+// (editor.ts says why). The price is that the browser's own caret movement
+// stops dead at a block boundary: ↑ and ↓ walk the visual lines INSIDE one
+// host and then do nothing, and ← at the start of a block does nothing either.
+// Until this file there was no arrow handling in the editor at all, so a
+// keyboard could enter a block and could not leave it except by clicking.
+//
+// FOUR THINGS THIS FILE IS CAREFUL ABOUT.
+//
+// (1) WITHIN THE BLOCK FIRST. A wrapped paragraph is several visual lines and
+// ↓ from its first line means "the second line", not "the next block". So
+// the question is never "which block am I in" but "is the caret on the
+// EDGE line of its host" — and that is a geometry question, answered by
+// comparing the caret's own rect against the host's line boxes. Counting
+// characters cannot answer it: where a line wraps depends on the font, the
+// width, the language and the marks.
+//
+// (2) A GOAL COLUMN, because every editor has one. Going down from the middle
+// of a long line onto a short one and down again must come back out near
+// the original x. The column is remembered by the caller across
+// consecutive vertical presses and dropped the moment anything else
+// happens — including a step the BROWSER handles, since inside one host
+// the browser keeps its own goal and ours would fight it.
+//
+// (3) SEATS, NOT BLOCKS. The things a caret can sit in are `[data-edit]`
+// hosts, `[data-cell]` table cells and the page title — three different
+// names for the same idea, and nesting (a callout, a toggle, a canvas
+// card) is already expressed by document order. So the walk is over a flat
+// list of seats in document order, which crosses every container for free.
+// A seat with no box (a shut toggle's children) is not a seat.
+//
+// (4) THE GEOMETRY IS MEASURED, NEVER WRITTEN BACK. `lineBoxes` asks a Range
+// for its client rects; `caretBox` asks the collapsed selection for its
+// own. Both can legitimately answer nothing (an empty host has no text to
+// measure), and every caller has to survive that — which is why the pure
+// predicates below take boxes as data and are testable without a DOM.
+
+/** A rectangle, as much of one as anything here needs. */
+export interface Box { left: number; top: number; right: number; bottom: number }
+
+/** The three things a caret can sit in. Document order is the walk order. */
+export const SEAT_SEL = '[data-edit],[data-cell],[data-page-title]'
+
+/**
+ * Is the caret on the FIRST (dir -1) or LAST (dir +1) visual line of its host?
+ *
+ * Pure, and the one decision that makes ↑/↓ feel native — answer it wrong and
+ * a wrapped paragraph either traps the caret or is skipped over entirely.
+ *
+ * The test is vertical CONTAINMENT of the caret's midpoint in the edge line's
+ * box, not equality of tops: a caret sitting next to a taller inline (a code
+ * span, an image, a bigger font) has a shorter rect than the line it is on, so
+ * `caret.top === line.top` is false on a line the caret is plainly inside.
+ *
+ * With no line boxes at all — an empty block, a block whose only content is a
+ * widget — every direction is an edge, which is the behaviour that lets ↑ and
+ * ↓ cross an empty paragraph rather than stalling on it.
+ */
+export function onEdgeLine(caret: Box, lines: Box[], dir: -1 | 1): boolean {
+ if (!lines.length) return true
+ const mid = (caret.top + caret.bottom) / 2
+ const edge = dir < 0 ? lines[0] : lines[lines.length - 1]
+ // half a pixel of slack: sub-pixel line heights are normal at browser zoom
+ return dir < 0 ? mid < edge.bottom - 0.5 : mid > edge.top + 0.5
+}
+
+/**
+ * The index of the seat a vertical or horizontal step lands in, or -1.
+ *
+ * Document order, deliberately: a callout's children, a toggle's children and
+ * a canvas card's text are all rendered inside their container, so "the next
+ * thing in the document" is already "the next thing on the screen" for every
+ * container this app has. The ONE exception is a table, whose cells are
+ * row-major in the DOM and column-major on the screen — tables are stepped by
+ * `tableStep` below and never by this.
+ */
+export function stepSeat(count: number, from: number, dir: -1 | 1): number {
+ const next = from + dir
+ return next >= 0 && next < count ? next : -1
+}
+
+/**
+ * The cell a vertical step inside a table lands in, or null to leave the table.
+ *
+ * Pure grid arithmetic, so the table's Tab handler (editor.ts `tableKey`) and
+ * this never have to agree about anything but the numbers.
+ */
+export function tableStep(
+ at: { r: number; c: number }, size: { w: number; h: number }, dir: -1 | 1,
+): { r: number; c: number } | null {
+ const r = at.r + dir
+ return r >= 0 && r < size.h ? { r, c: at.c } : null
+}
+
+/**
+ * Which of a row of boxes is nearest a goal column.
+ *
+ * Used when a step ENTERS a table from outside: the seat that happens to be
+ * next in document order is the first cell of the first row, which is the
+ * wrong column whenever the caret was not at the left margin. Distance is to
+ * the box, not to its centre — a wide first column should not win a caret that
+ * is sitting over the narrow third one.
+ */
+export function nearestByX(boxes: Box[], x: number): number {
+ let best = -1
+ let bestD = Infinity
+ boxes.forEach((b, i) => {
+ const d = x < b.left ? b.left - x : x > b.right ? x - b.right : 0
+ if (d < bestD) { bestD = d; best = i }
+ })
+ return best
+}
+
+// ---- the DOM half -----------------------------------------------------------
+
+/** Every seat that is actually on screen, in document order. */
+export function seatsIn(root: ParentNode): HTMLElement[] {
+ return Array.from(root.querySelectorAll<HTMLElement>(SEAT_SEL))
+ // a shut toggle's children, a hidden column: no box, not a seat. `offsetParent`
+ // is null for `display:none` and for nothing else that matters here.
+ .filter((s) => s.offsetParent !== null || s === document.activeElement)
+}
+
+/**
+ * Merge a Range's client rects into ONE BOX PER VISUAL LINE.
+ *
+ * `Range.getClientRects()` returns a rect per inline BOX, not per line: a
+ * sentence containing `<strong>` or a link comes back as three or four rects
+ * that all share the same line. Measured on the starter space's first
+ * paragraph: two visual lines, FIVE rects.
+ *
+ * Both callers are wrong without this merge, in different ways. `onEdgeLine`
+ * reads `lines[0]` as "the first line", which is only the first FRAGMENT of
+ * it. `placeCaretAtX` clamps the goal column into the edge line's box — into
+ * the first fragment's 555–983, so a column at x=1150 would land at 983 and
+ * the rest of the line would be unreachable.
+ *
+ * Pure over rects, so the grouping is testable without a browser.
+ */
+export function mergeLines(rects: readonly Box[]): Box[] {
+ const out: Box[] = []
+ for (const r of rects) {
+ const mid = (r.top + r.bottom) / 2
+ // by the fragment's MIDPOINT inside an existing band, not by equal tops: a
+ // taller inline on the same line has a taller box
+ const g = out.find((o) => mid > o.top && mid < o.bottom)
+ if (g) {
+ g.left = Math.min(g.left, r.left); g.right = Math.max(g.right, r.right)
+ g.top = Math.min(g.top, r.top); g.bottom = Math.max(g.bottom, r.bottom)
+ } else out.push({ left: r.left, right: r.right, top: r.top, bottom: r.bottom })
+ }
+ return out.sort((a, b) => a.top - b.top)
+}
+
+/** The visual lines of a host's contents, one box each, in order. */
+export function lineBoxes(host: HTMLElement): Box[] {
+ const r = document.createRange()
+ r.selectNodeContents(host)
+ return mergeLines(Array.from(r.getClientRects()).filter((b) => b.width > 0 || b.height > 0))
+}
+
+/**
+ * The caret's own rectangle.
+ *
+ * A collapsed Range has zero width and — at a position between two nodes —
+ * sometimes no client rects at all, which is why `getBoundingClientRect` is
+ * the fallback and an all-zero result is discarded rather than believed: a
+ * rectangle at the top-left corner of the window would put the caret above
+ * every block on the page.
+ *
+ * THE LAST FALLBACK IS THE HOST'S OWN BOX, and it is not defensive padding —
+ * it is the EMPTY BLOCK. An empty paragraph has no text to measure, so the
+ * range has no rects and the contents have no line boxes; returning null there
+ * made ↑ and ↓ stop dead on it, which is worse than the bug this file fixes
+ * because an empty paragraph is exactly where a caret waits. Measured in the
+ * built shell: without this, ↓ out of an empty block did nothing at all.
+ */
+export function caretBox(host: HTMLElement): Box | null {
+ const sel = getSelection()
+ if (!sel || !sel.rangeCount) return null
+ const r = sel.getRangeAt(0)
+ if (!host.contains(r.startContainer)) return null
+ const rects = r.getClientRects()
+ const b = rects.length ? rects[rects.length - 1] : r.getBoundingClientRect()
+ if (b && (b.width || b.height || b.top || b.left)) return b
+ // NOTHING. Measured in the built shell at the end of the starter space's
+ // first paragraph: a range collapsed at an ELEMENT boundary (container = the
+ // host, offset = its child count) reports no rects and an all-zero bounding
+ // box. Falling back to a line box here picked the FIRST line, so ↓ at the end
+ // of a two-line paragraph decided it was still on line one and never left
+ // the block — the exact bug this file exists to fix, reintroduced.
+ //
+ // So widen by one unit and read the edge of what that covers: the character
+ // (or node) before the caret gives its right edge, the one after gives its
+ // left. Both are zero-width boxes on the caret's own line.
+ const back = edgeOf(r, -1)
+ if (back) return back
+ const fwd = edgeOf(r, 1)
+ if (fwd) return fwd
+ // an empty block: nothing to measure at all, and the host's box is the line
+ return host.getBoundingClientRect()
+}
+
+/**
+ * Widen a collapsed range by one unit and return the zero-width box at the
+ * caret's side of it — the right edge going back, the left edge going forward.
+ * Null when there is nothing in that direction to measure.
+ */
+function edgeOf(r: Range, dir: -1 | 1): Box | null {
+ const p = r.cloneRange()
+ const node = dir < 0 ? p.startContainer : p.endContainer
+ const off = dir < 0 ? p.startOffset : p.endOffset
+ const limit = node.nodeType === 3 ? (node.textContent ?? '').length : node.childNodes.length
+ if (dir < 0 ? off <= 0 : off >= limit) return null
+ try { if (dir < 0) p.setStart(node, off - 1); else p.setEnd(node, off + 1) } catch { return null }
+ const rects = Array.from(p.getClientRects()).filter((b) => b.width > 0 || b.height > 0)
+ if (!rects.length) return null
+ const b = dir < 0 ? rects[rects.length - 1] : rects[0]
+ const x = dir < 0 ? b.right : b.left
+ return { left: x, right: x, top: b.top, bottom: b.bottom }
+}
+
+/** Is the caret collapsed at the very end of `host`? (the mirror of atStart) */
+export function atEndOf(host: HTMLElement): boolean {
+ const sel = getSelection()
+ if (!sel || !sel.rangeCount) return false
+ const r = sel.getRangeAt(0)
+ if (!r.collapsed) return false
+ const probe = r.cloneRange()
+ probe.selectNodeContents(host)
+ probe.setStart(r.endContainer, r.endOffset)
+ return probe.toString().length === 0
+}
+
+/** Put the caret at the very start of `host`. */
+export function caretToStart(host: HTMLElement): void {
+ const r = document.createRange()
+ r.selectNodeContents(host)
+ r.collapse(true)
+ const sel = getSelection()
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+}
+
+/** Put the caret at the very end of `host`. */
+export function caretToEndOf(host: HTMLElement): void {
+ const r = document.createRange()
+ r.selectNodeContents(host)
+ r.collapse(false)
+ const sel = getSelection()
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+}
+
+/**
+ * Put the caret in `host`, on its first or last visual line, as near column
+ * `x` as that line reaches.
+ *
+ * `caretPositionFromPoint` is the honest instrument here — it asks the engine
+ * that did the layout where a pixel is in the text, so it is right through
+ * bidi text, ligatures, inline images and marks, none of which a character
+ * count survives. It can still answer with a node OUTSIDE the host (the point
+ * grazed a gutter button, a list marker, a checkbox), so the answer is checked
+ * before it is used and the end of the line is the fallback.
+ */
+export function placeCaretAtX(host: HTMLElement, x: number, line: 'first' | 'last'): void {
+ host.focus()
+ const boxes = lineBoxes(host)
+ const box = line === 'first' ? boxes[0] : boxes[boxes.length - 1]
+ if (!box) { caretToEndOf(host); return }
+ const y = (box.top + box.bottom) / 2
+ const cx = Math.min(Math.max(x, box.left + 0.5), Math.max(box.left + 0.5, box.right - 0.5))
+ const hit = caretAt(cx, y)
+ if (hit && host.contains(hit.node)) {
+ const r = document.createRange()
+ try {
+ r.setStart(hit.node, hit.offset)
+ r.collapse(true)
+ const sel = getSelection()
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+ return
+ } catch { /* an offset the node cannot take — fall through */ }
+ }
+ if (line === 'first') caretToStart(host); else caretToEndOf(host)
+}
+
+/** `caretPositionFromPoint`, with the WebKit spelling as the fallback. */
+function caretAt(x: number, y: number): { node: Node; offset: number } | null {
+ const d = document as Document & {
+ caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null
+ caretRangeFromPoint?: (x: number, y: number) => Range | null
+ }
+ const pos = d.caretPositionFromPoint?.(x, y)
+ if (pos) return { node: pos.offsetNode, offset: pos.offset }
+ const range = d.caretRangeFromPoint?.(x, y)
+ return range ? { node: range.startContainer, offset: range.startOffset } : null
+}
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index cf532491..b651c377 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -56,6 +56,12 @@ import '../../kernel/src/ui/dialog.css'
import { createPanel, type Panel } from '../../kernel/src/ui/panel.ts'
import '../../kernel/src/ui/panel.css'
import { PropsPanel } from './props'
+import {
+ SEAT_SEL, seatsIn, lineBoxes, caretBox, onEdgeLine, stepSeat, tableStep, nearestByX,
+ placeCaretAtX, caretToStart, caretToEndOf, atEndOf,
+} from './caret'
+import { indentTarget, canOutdent } from './nesting'
+import { blockFormatRow } from './blockbar'
import {
nameIndex, namesOf, mentionsOf, linkMention, type Mention,
} from './mentions.ts'
@@ -70,6 +76,8 @@ const CTRL = navigator.platform.toLowerCase().includes('mac') ? 'metaKey' : 'ctr
// trigger that no menu mentions.
const AUTOFORMAT = MD_SPECS
+/** The four keys caret.ts answers for. A Set so the keymap's hot path is one lookup. */
+const ARROWS = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'])
/**
* Below this width both side panels are DRAWERS over the page, not columns.
* One number, handed to the kernel panel as `drawerBelow` (D6: the breakpoint
@@ -149,6 +157,15 @@ export class Editor {
private painting = false
/** reading view: the document without the machinery for changing it */
private reading = false
+ /**
+ * The column ↑/↓ are aiming for, in viewport px, or null.
+ *
+ * Held across CONSECUTIVE vertical steps and dropped by anything else — a
+ * horizontal key, a click, and also a vertical step we hand to the browser,
+ * because inside one host the browser keeps its own goal column and two
+ * memories of the same thing is how they start to disagree.
+ */
+ private goalX: number | null = null
/**
* Remote image urls this READER has agreed to load, this session only.
*
@@ -580,6 +597,14 @@ export class Editor {
this.syncHistoryButtons()
this.syncDirty()
document.addEventListener('keydown', (e) => this.onKey(e), true)
+ // A POINTER ENDS THE VERTICAL RUN. Found in the browser, not by reading the
+ // code: the goal column was cleared by every key except ↑ and ↓ and by
+ // nothing else, so after clicking somewhere new the first ↓ still aimed at
+ // the column of the run before it — measured entering a table three times
+ // at three different columns and landing in the first one every time.
+ const dropGoal = () => { this.goalX = null }
+ document.addEventListener('mousedown', dropGoal, true)
+ document.addEventListener('touchstart', dropGoal, { capture: true, passive: 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
@@ -2021,6 +2046,27 @@ export class Editor {
private openBlockMenu(id: string, anchor: HTMLElement): void {
if (this.store.readOnly || this.reading) return
this.menuAt(anchor, t('Block options'), (m) => {
+ // FIRST, above the actions: the block's own format. blockbar.ts records
+ // why these are here and not in the selection toolbar.
+ const page = this.store.page
+ const blk = this.store.block(id)
+ if (page && blk) {
+ extra(m, blockFormatRow({
+ type: String(blk.type ?? 'p'),
+ canIndent: indentTarget(page.blocks, id).ok,
+ canOutdent: canOutdent(effectiveParents(page), id),
+ indentRefusal: t('a block nests under the one above it'),
+ setType: (type) => { m.close(); this.setType(id, type) },
+ // NOT closed first when the gesture is refused: `indent` answers with
+ // the reason, and closing the menu would take the disabled control
+ // away at the moment it is explaining itself.
+ indent: (deeper) => {
+ const allowed = deeper ? indentTarget(page.blocks, id).ok : canOutdent(effectiveParents(page), id)
+ if (allowed) m.close()
+ this.indent(id, deeper)
+ },
+ }))
+ }
for (const a of this.blockActions(id)) {
row(m, { icon: ICONS[a.icon], label: a.label, kbd: a.kbd, off: a.off, run: a.run })
}
@@ -3156,6 +3202,19 @@ export class Editor {
// so without it the save dialog opened every time someone struck text out.
if (mod && e.key.toLowerCase() === 's' && !e.shiftKey) { e.preventDefault(); this.onSave?.(); return }
if (mod && e.key.toLowerCase() === 'p') { e.preventDefault(); this.openPrint(); return }
+ // ⌘/ — the block menu, and THE ONLY KEYBOARD ROUTE TO IT. The menu hangs
+ // off the gutter grip, the gutter is hover-revealed, and Tab inside a
+ // block is indent — so without this key the block format row, and with it
+ // every list, heading and indent control, is reachable by pointer only.
+ if (mod && e.key === '/') {
+ const at = this.focused() ?? this.cellAt(document.activeElement)
+ const grip = at
+ ? this.main.querySelector<HTMLElement>(
+ `[data-block-id="${CSS.escape(at.id)}"] > .sp-gutter > .sp-ghost[draggable]`)
+ : null
+ if (at) { e.preventDefault(); this.openBlockMenu(at.id, grip ?? this.main) }
+ return
+ }
if (mod && e.key.toLowerCase() === 'f') { e.preventDefault(); this.openFind(); return }
if (mod && e.altKey && e.key.toLowerCase() === 'n') { e.preventDefault(); this.newPage(); return }
if (mod && e.shiftKey && e.key.toLowerCase() === 'j') { e.preventDefault(); this.openJournal(); return }
@@ -3200,6 +3259,17 @@ export class Editor {
if (this.tableKey(e, inCell)) return
}
+ // ARROWS COME AFTER `tableKey` AND BEFORE `focused()`. After, because the
+ // table owns ⏎ and ⇥ inside a cell and must get first refusal on every
+ // key; before, because `focused()` looks for `[data-edit]` and a cell is
+ // deliberately not one — so caret navigation would never run in a table at
+ // all if it sat below. It handles the cell case itself.
+ if (ARROWS.has(e.key)) {
+ if (this.caretNav(e, inCell)) return
+ } else if (!mod) {
+ this.goalX = null
+ }
+
const cur = this.focused()
if (!cur) return
const b = s.block(cur.id)
@@ -3330,7 +3400,116 @@ export class Editor {
})
}
- /** Tab sets `parent` to the previous sibling — one field write. */
+ /**
+ * ↑ ↓ ← → across blocks. True when it handled the key.
+ *
+ * The rules, in the order they are asked:
+ *
+ * - A held Shift or ⌥ is a SELECTION or a word jump; both are the browser's
+ * and neither should jump a block. A non-collapsed selection likewise.
+ * - ← and → only do anything at the very edge of the seat; everywhere else
+ * the browser is already right.
+ * - ↑ and ↓ only do anything on the seat's edge VISUAL LINE, which is why
+ * caret.ts measures boxes rather than counting characters: a wrapped
+ * paragraph is several lines and the first ↓ in it means the second line.
+ * - The goal column is remembered across consecutive vertical steps, so
+ * down-through-a-short-line-and-out comes back near the original x.
+ */
+ private caretNav(e: KeyboardEvent, inCell: ReturnType<Editor['cellAt']>): boolean {
+ if (e.shiftKey || e.altKey || (e as any)[CTRL]) { this.goalX = null; return false }
+ const active = document.activeElement as HTMLElement | null
+ const host = active?.closest<HTMLElement>(SEAT_SEL) ?? null
+ if (!host || !this.main.contains(host)) return false
+ const sel = getSelection()
+ if (!sel || !sel.rangeCount || !sel.isCollapsed) { this.goalX = null; return false }
+
+ const seats = seatsIn(this.main)
+ const i = seats.indexOf(host)
+ if (i < 0) return false
+ const dir: -1 | 1 = e.key === 'ArrowUp' || e.key === 'ArrowLeft' ? -1 : 1
+ const vertical = e.key === 'ArrowUp' || e.key === 'ArrowDown'
+
+ if (!vertical) {
+ this.goalX = null
+ // at the edge, ← leaves for the END of the seat before and → for the
+ // START of the seat after — which is exactly what the caret would have
+ // done had the page been one editable rather than many
+ if (dir < 0 ? !atStart(host) : !atEndOf(host)) return false
+ const j = stepSeat(seats.length, i, dir)
+ if (j < 0) return false
+ e.preventDefault()
+ const next = seats[j]
+ next.focus()
+ if (dir < 0) caretToEndOf(next); else caretToStart(next)
+ return true
+ }
+
+ const caret = caretBox(host)
+ if (!caret) return false
+ if (!onEdgeLine(caret, lineBoxes(host), dir)) { this.goalX = null; return false }
+ const x = this.goalX ?? caret.left
+
+ // INSIDE A TABLE the grid is the truth, not document order: cells are
+ // row-major in the DOM, so the seat before (1,2) is (1,1) and stepping to
+ // it would walk sideways along the row the reader was trying to leave.
+ if (inCell) {
+ const b = this.store.block(inCell.id)
+ const shape = b ? tableOf(b) : null
+ const to = shape ? tableStep(inCell, shape, dir) : null
+ if (to) {
+ e.preventDefault()
+ this.goalX = x
+ const td = this.main.querySelector<HTMLElement>(
+ `[data-cell="${CSS.escape(inCell.id)}"][data-r="${to.r}"][data-c="${to.c}"]`)
+ if (td) { placeCaretAtX(td, x, dir < 0 ? 'last' : 'first'); return true }
+ }
+ // off the top or the bottom of the grid: out of the table altogether,
+ // past every one of its other cells
+ const out = this.outOfTable(seats, i, dir, inCell.id)
+ if (out < 0) return false
+ e.preventDefault()
+ this.goalX = x
+ placeCaretAtX(seats[out], x, dir < 0 ? 'last' : 'first')
+ return true
+ }
+
+ let j = stepSeat(seats.length, i, dir)
+ if (j < 0) return false
+ // ENTERING a table from outside lands on whichever cell of the entry row
+ // the goal column is over, not on the first one in the DOM
+ const cellId = seats[j].dataset.cell
+ if (cellId !== undefined) {
+ const row = seats.filter((sea) => sea.dataset.cell === cellId
+ && sea.dataset.r === seats[j].dataset.r)
+ const pick = nearestByX(row.map((sea) => sea.getBoundingClientRect()), x)
+ if (pick >= 0) j = seats.indexOf(row[pick])
+ }
+ e.preventDefault()
+ this.goalX = x
+ placeCaretAtX(seats[j], x, dir < 0 ? 'last' : 'first')
+ return true
+ }
+
+ /** The first seat after (dir 1) or before (dir -1) every cell of one table. */
+ private outOfTable(seats: HTMLElement[], from: number, dir: -1 | 1, tableId: string): number {
+ for (let j = from + dir; j >= 0 && j < seats.length; j += dir) {
+ if (seats[j].dataset.cell !== tableId) return j
+ }
+ return -1
+ }
+
+ /**
+ * Tab sets `parent` to the previous sibling — one field write.
+ *
+ * AND WHEN THERE IS NO PREVIOUS SIBLING IT SAYS SO. This loop used to fall
+ * off its own end and return, so Tab on the first item of a list — the most
+ * common list gesture there is — did nothing, showed nothing and explained
+ * nothing. nesting.ts holds the argument for refusing rather than inventing
+ * an indent level; what belongs here is that a refusal has to be VISIBLE, in
+ * the status line the app already has (a second transient-message mechanism
+ * in one app is one too many — collabui.ts) and as a nudge on the block, so
+ * the answer arrives where the reader is looking.
+ */
private indent(id: string, deeper: boolean): void {
const s = this.store
const page = s.page
@@ -3338,6 +3517,20 @@ export class Editor {
const i = page.blocks.findIndex((x) => x.id === id)
const b = page.blocks[i]
if (!b) return
+ if (deeper) {
+ const aim = indentTarget(page.blocks, id)
+ if (!aim.ok) {
+ if (aim.why === 'first') {
+ this.status(t('A block nests under the one above it — this one has nothing above it'))
+ this.nudge(id)
+ }
+ return
+ }
+ } else if (!canOutdent(effectiveParents(page), id)) {
+ this.status(t('This block is not nested'))
+ this.nudge(id)
+ return
+ }
s.commit(() => {
if (!deeper) {
// by the EFFECTIVE parent (model.ts), not by whatever `parent` names:
@@ -3361,6 +3554,25 @@ export class Editor {
this.focusBlock(id)
}
+ /**
+ * A refused gesture, shown where the reader is looking.
+ *
+ * The status line carries the WORDS and this carries the pointer: the block
+ * you aimed at is the one that twitches, so a message in the topbar is not
+ * left to be connected to a keystroke by guesswork. Purely a class the
+ * stylesheet animates — nothing here touches the model, so a refusal can
+ * never end up in the file or in an undo step.
+ */
+ private nudge(id: string): void {
+ const node = this.main.querySelector<HTMLElement>(`[data-block-id="${CSS.escape(id)}"]`)
+ if (!node) return
+ node.classList.remove('sp-nudge')
+ // reflow between the two writes, or the class never leaves and re-arrives
+ void node.offsetWidth
+ node.classList.add('sp-nudge')
+ setTimeout(() => node.classList.remove('sp-nudge'), 400)
+ }
+
setType(id: string, type: string, variant?: (b: Block) => void): void {
this.store.commit(() => {
const b = this.store.block(id)
@@ -3471,6 +3683,7 @@ export class Editor {
[t('Writing'), [
['↵', t('A new block')],
[`Tab / ${M('shift')}Tab`, t('Indent, or move back out')],
+ [M('mod', '/'), t('Block options — type, list, indent')],
['/', t('The block menu, on an empty line')],
['[[', t('Link to another page')],
[`${M('mod', 'Z')} / ${M('shift', 'mod', 'Z')}`, t('Undo, redo')],
@@ -3485,6 +3698,8 @@ export class Editor {
[M('mod', 'K'), t('Link the selected words')],
]],
[t('Getting around'), [
+ ['↑ ↓', t('Between blocks, and between the lines of one')],
+ ['← →', t('Off the edge of a block, into the next')],
[M('mod', 'K'), t('Search all pages, with nothing selected')],
[M('mod', 'F'), t('Find and replace')],
[M('alt', 'mod', 'N'), t('New page')],
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index b3e7a15f..81ecc9ef 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -636,6 +636,15 @@ export const de: Catalog = {
"Date": "Datum",
"Person": "Person",
"Labels": "Labels",
+ "Indent": "Einrücken",
+ "Move back out": "Wieder heraus",
+ "Block format": "Blockformat",
+ "Block options — type, list, indent": "Block-Optionen — Typ, Liste, Einrückung",
+ "This block is not nested": "Dieser Block ist nicht verschachtelt",
+ "a block nests under the one above it": "ein Block wird unter dem darüberliegenden verschachtelt",
+ "A block nests under the one above it — this one has nothing above it": "Ein Block wird unter dem darüberliegenden verschachtelt — über diesem steht nichts",
+ "Between blocks, and between the lines of one": "Zwischen Blöcken, und zwischen den Zeilen eines Blocks",
+ "Off the edge of a block, into the next": "Über den Rand eines Blocks in den nächsten",
"Footnotes": "Fußnoten",
"Back to the text": "Zurück zum Text",
"Write the note": "Notiz schreiben",
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index a447f9b9..8f3641f3 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -636,6 +636,15 @@ export const es: Catalog = {
"Date": "Fecha",
"Person": "Persona",
"Labels": "Etiquetas",
+ "Indent": "Sangrar",
+ "Move back out": "Volver a salir",
+ "Block format": "Formato del bloque",
+ "Block options — type, list, indent": "Opciones del bloque — tipo, lista, sangría",
+ "This block is not nested": "Este bloque no está anidado",
+ "a block nests under the one above it": "un bloque se anida bajo el que tiene encima",
+ "A block nests under the one above it — this one has nothing above it": "Un bloque se anida bajo el que tiene encima — este no tiene ninguno encima",
+ "Between blocks, and between the lines of one": "Entre bloques, y entre las líneas de uno",
+ "Off the edge of a block, into the next": "Desde el borde de un bloque al siguiente",
"Footnotes": "Notas al pie",
"Back to the text": "Volver al texto",
"Write the note": "Escribe la nota",
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index e16504d2..67907532 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -636,6 +636,15 @@ export const fr: Catalog = {
"Date": "Date",
"Person": "Personne",
"Labels": "Étiquettes",
+ "Indent": "Indenter",
+ "Move back out": "Revenir en arrière",
+ "Block format": "Format du bloc",
+ "Block options — type, list, indent": "Options du bloc — type, liste, indentation",
+ "This block is not nested": "Ce bloc n’est pas imbriqué",
+ "a block nests under the one above it": "un bloc s’imbrique sous celui qui le précède",
+ "A block nests under the one above it — this one has nothing above it": "Un bloc s’imbrique sous celui qui le précède — celui-ci n’a rien au-dessus",
+ "Between blocks, and between the lines of one": "Entre les blocs, et entre les lignes d’un bloc",
+ "Off the edge of a block, into the next": "Du bord d’un bloc vers le suivant",
"Footnotes": "Notes de bas de page",
"Back to the text": "Revenir au texte",
"Write the note": "Rédigez la note",
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index c07841db..fc4fd6ab 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -636,6 +636,15 @@ export const it: Catalog = {
"Date": "Data",
"Person": "Persona",
"Labels": "Etichette",
+ "Indent": "Rientra",
+ "Move back out": "Torna indietro",
+ "Block format": "Formato del blocco",
+ "Block options — type, list, indent": "Opzioni del blocco — tipo, elenco, rientro",
+ "This block is not nested": "Questo blocco non è annidato",
+ "a block nests under the one above it": "un blocco si annida sotto quello che lo precede",
+ "A block nests under the one above it — this one has nothing above it": "Un blocco si annida sotto quello che lo precede — sopra questo non c’è nulla",
+ "Between blocks, and between the lines of one": "Tra i blocchi, e tra le righe di uno",
+ "Off the edge of a block, into the next": "Dal bordo di un blocco al successivo",
"Footnotes": "Note a piè di pagina",
"Back to the text": "Torna al testo",
"Write the note": "Scrivi la nota",
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index 37ffc5bc..fca77d04 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -636,6 +636,15 @@ export const ja: Catalog = {
"Date": "日付",
"Person": "担当者",
"Labels": "ラベル",
+ "Indent": "字下げ",
+ "Move back out": "戻す",
+ "Block format": "ブロックの書式",
+ "Block options — type, list, indent": "ブロックのオプション — 種類、リスト、字下げ",
+ "This block is not nested": "このブロックは入れ子になっていません",
+ "a block nests under the one above it": "ブロックは一つ上のブロックの中に入ります",
+ "A block nests under the one above it — this one has nothing above it": "ブロックは一つ上のブロックの中に入ります — このブロックより上には何もありません",
+ "Between blocks, and between the lines of one": "ブロック間、および一つのブロック内の行間",
+ "Off the edge of a block, into the next": "ブロックの端を越えて次のブロックへ",
"Footnotes": "脚注",
"Back to the text": "本文に戻る",
"Write the note": "脚注を入力",
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index b294e2c1..127a4d0a 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -12,6 +12,7 @@
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 block nests under the one above it — this one has nothing above it": ["ブロックは一つ上のブロックの中に入ります — このブロックより上には何もありません","块会嵌套在它上面的那个块里 — 这个块上面没有别的块","區塊會巢狀於它上面的那個區塊 — 這個區塊上面沒有別的區塊","Un bloque se anida bajo el que tiene encima — este no tiene ninguno encima","Un bloc s’imbrique sous celui qui le précède — celui-ci n’a rien au-dessus","Ein Block wird unter dem darüberliegenden verschachtelt — über diesem steht nichts","Un blocco si annida sotto quello che lo precede — sopra questo non c’è nulla","Um bloco aninha-se sob o que está acima — este não tem nada acima"],
"A card for an address you type": ["入力したアドレスのカード","为你输入的网址生成的卡片","為你輸入的網址產生的卡片","Una tarjeta para una dirección que escribas","Une carte pour une adresse que vous saisissez","Eine Karte für eine Adresse, die du eingibst","Una scheda per un indirizzo che digiti","Um cartão para um endereço que escreves"],
"A card that opens a page": ["ページを開くカード","打开某个页面的卡片","開啟某個頁面的卡片","Una tarjeta que abre una página","Une carte qui ouvre une page","Eine Karte, die eine Seite öffnet","Una scheda che apre una pagina","Um cartão que abre uma página"],
"A filter here is newer than this build and was not applied.": ["このビューには、このバージョンより新しいフィルターがあり、適用されていません。","此视图中有比当前版本更新的筛选条件,未被应用。","此檢視中有比目前版本更新的篩選條件,未被套用。","Un filtro de esta vista es más reciente que esta versión y no se ha aplicado.","Un filtre de cette vue est plus récent que cette version et n’a pas été appliqué.","Ein Filter dieser Ansicht ist neuer als diese Version und wurde nicht angewendet.","Un filtro di questa vista è più recente di questa versione e non è stato applicato.","Um filtro desta vista é mais recente do que esta versão e não foi aplicado."],
@@ -72,8 +73,11 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Back": ["戻る","返回","返回","Atrás","Retour","Zurück","Indietro","Voltar"],
"Back to the text": ["本文に戻る","返回正文","回到內文","Volver al texto","Revenir au texte","Zurück zum Text","Torna al testo","Voltar ao texto"],
"Background": ["背景","背景","背景","Fondo","Arrière-plan","Hintergrund","Sfondo","Plano de fundo"],
+ "Between blocks, and between the lines of one": ["ブロック間、および一つのブロック内の行間","在块之间移动,也在一个块的各行之间移动","在區塊之間移動,也在一個區塊的各行之間移動","Entre bloques, y entre las líneas de uno","Entre les blocs, et entre les lignes d’un bloc","Zwischen Blöcken, und zwischen den Zeilen eines Blocks","Tra i blocchi, e tra le righe di uno","Entre blocos, e entre as linhas de um"],
"Block": ["ブロック","块","區塊","Bloque","Bloc","Block","Blocco","Bloco"],
+ "Block format": ["ブロックの書式","块格式","區塊格式","Formato del bloque","Format du bloc","Blockformat","Formato del blocco","Formato do bloco"],
"Block options": ["ブロックのオプション","块选项","區塊選項","Opciones del bloque","Options du bloc","Block-Optionen","Opzioni del blocco","Opções do bloco"],
+ "Block options — type, list, indent": ["ブロックのオプション — 種類、リスト、字下げ","块选项 — 类型、列表、缩进","區塊選項 — 類型、清單、縮排","Opciones del bloque — tipo, lista, sangría","Options du bloc — type, liste, indentation","Block-Optionen — Typ, Liste, Einrückung","Opzioni del blocco — tipo, elenco, rientro","Opções do bloco — tipo, lista, avanço"],
"Blocks": ["ブロック","块","區塊","Bloques","Blocs","Blöcke","Blocchi","Blocos"],
"Blue": ["青","蓝色","藍色","Azul","Bleu","Blau","Blu","Azul"],
"Board": ["ボード","看板","看板","Tablero","Tableau","Board","Bacheca","Quadro"],
@@ -234,6 +238,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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."],
"Include the pages nested under it": ["その下にあるページも含める","包含其下级页面","包含其下層頁面","Incluir las páginas anidadas debajo","Inclure les pages imbriquées en dessous","Die darunter verschachtelten Seiten einschließen","Includi le pagine annidate sotto di essa","Incluir as páginas aninhadas por baixo"],
+ "Indent": ["字下げ","缩进","縮排","Sangrar","Indenter","Einrücken","Rientra","Avançar"],
"Indent, or move back out": ["字下げ、または戻す","缩进,或退回一级","縮排,或退回一層","Sangrar, o volver a salir","Indenter, ou revenir en arrière","Einrücken, oder wieder heraus","Rientra, o torna indietro","Avançar, ou recuar de novo"],
"Inline code — ⌘E": ["インラインコード — ⌘E","行内代码 — ⌘E","行內程式碼 — ⌘E","Código en línea — ⌘E","Code en ligne — ⌘E","Inline-Code — ⌘E","Codice in linea — ⌘E","Código em linha — ⌘E"],
"Interface language": ["表示言語","界面语言","介面語言","Idioma de la interfaz","Langue de l’interface","Sprache der Oberfläche","Lingua dell’interfaccia","Idioma da interface"],
@@ -286,6 +291,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Match my system": ["システムに合わせる","跟随系统","跟隨系統","Según el sistema","Comme le système","Systemeinstellung folgen","Come il sistema","Acompanhar o sistema"],
"Mints brand-new keys. Every previously sent copy stops syncing for good; share fresh copies afterwards.": ["まったく新しい鍵を発行します。これまでに送ったコピーは永久に同期しなくなります。以後は新しいコピーを共有してください。","铸造全新密钥。之前发送的所有副本将永久停止同步;此后请分享新副本。","鑄造全新金鑰。之前傳送的所有副本將永久停止同步;此後請分享新副本。","Genera claves totalmente nuevas. Todas las copias enviadas dejan de sincronizarse para siempre; comparte copias nuevas después.","Génère des clés toutes neuves. Chaque copie déjà envoyée cesse définitivement de se synchroniser ; partagez ensuite de nouvelles copies.","Erzeugt brandneue Schlüssel. Jede bereits gesendete Kopie synchronisiert endgültig nicht mehr; teile danach frische Kopien.","Genera chiavi nuove di zecca. Ogni copia già inviata smette per sempre di sincronizzarsi; condividi poi copie nuove.","Gera chaves novas em folha. Toda cópia enviada antes para de sincronizar de vez; compartilhe cópias novas depois."],
"More actions": ["その他の操作","更多操作","更多操作","Más acciones","Plus d’actions","Weitere Aktionen","Altre azioni","Mais ações"],
+ "Move back out": ["戻す","退回一级","退回一層","Volver a salir","Revenir en arrière","Wieder heraus","Torna indietro","Recuar de novo"],
"Move down": ["下へ移動","下移","下移","Bajar","Descendre","Nach unten","Sposta giù","Mover para baixo"],
"Move up": ["上へ移動","上移","上移","Subir","Monter","Nach oben","Sposta su","Mover para cima"],
"Muted": ["ミュート","静音","靜音","Silenciado","Muet","Stumm","Muto","Sem som"],
@@ -324,6 +330,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Number": ["数値","数字","數字","Número","Nombre","Zahl","Numero","Número"],
"Numbered list": ["番号付きリスト","编号列表","編號清單","Lista numerada","Liste numérotée","Nummerierte Liste","Elenco numerato","Lista numerada"],
"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"],
+ "Off the edge of a block, into the next": ["ブロックの端を越えて次のブロックへ","越过块的边缘,进入下一个块","越過區塊的邊緣,進入下一個區塊","Desde el borde de un bloque al siguiente","Du bord d’un bloc vers le suivant","Über den Rand eines Blocks in den nächsten","Dal bordo di un blocco al successivo","Da borda de um bloco para o seguinte"],
"Offline mode is on — nothing leaves this computer.": ["オフラインモードがオンです — このコンピュータから何も送信されません。","离线模式已开启 — 任何数据都不会离开这台电脑。","離線模式已開啟 — 任何資料都不會離開這台電腦。","El modo sin conexión está activo: nada sale de este equipo.","Le mode hors ligne est activé — rien ne quitte cet ordinateur.","Der Offline-Modus ist aktiv — nichts verlässt diesen Computer.","La modalità offline è attiva: nulla lascia questo computer.","O modo offline está ativado — nada sai deste computador."],
"On this screen only — it is not saved in the file": ["この画面でのみ有効です。ファイルには保存されません","仅在此屏幕上生效,不会保存到文件中","僅在此螢幕上生效,不會儲存到檔案中","Solo en esta pantalla: no se guarda en el archivo","Sur cet écran seulement — ce n’est pas enregistré dans le fichier","Nur auf diesem Bildschirm — es wird nicht in der Datei gespeichert","Solo su questo schermo: non viene salvato nel file","Apenas neste ecrã — não é guardado no ficheiro"],
"One emoji": ["絵文字ひとつ","一个表情符号","一個表情符號","Un emoji","Un emoji","Ein Emoji","Un'emoji","Um emoji"],
@@ -495,6 +502,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"The workspace": ["ワークスペース","工作区","工作區","El espacio de trabajo","L’espace de travail","Der Arbeitsbereich","Lo spazio di lavoro","A área de trabalho"],
"These windows are on this computer. Start a session to work with someone elsewhere.": ["これらのウィンドウはこのパソコン内のものです。別の場所にいる人と作業するにはセッションを開始してください。","这些窗口都在本机。若要与其他地方的人协作,请开始一个会话。","這些視窗都在本機。若要與其他地方的人協作,請開始一個工作階段。","Estas ventanas están en este ordenador. Inicia una sesión para trabajar con alguien en otro sitio.","Ces fenêtres sont sur cet ordinateur. Démarrez une session pour travailler avec quelqu’un ailleurs.","Diese Fenster sind auf diesem Computer. Starte eine Sitzung, um mit jemand anderem zu arbeiten.","Queste finestre sono su questo computer. Avvia una sessione per lavorare con qualcuno altrove.","Estas janelas estão neste computador. Inicia uma sessão para trabalhar com alguém noutro lugar."],
"This block has no settings of its own — its content is all of it.": ["このブロックに固有の設定はありません — 中身がすべてです。","这个块没有自己的设置 — 内容就是它的全部。","這個區塊沒有自己的設定 — 內容就是它的全部。","Este bloque no tiene ajustes propios: su contenido es todo lo que hay.","Ce bloc n’a pas de réglages à lui — son contenu, c’est tout.","Dieser Block hat keine eigenen Einstellungen — sein Inhalt ist alles.","Questo blocco non ha impostazioni proprie: il suo contenuto è tutto.","Este bloco não tem definições próprias — o conteúdo é tudo o que há."],
+ "This block is not nested": ["このブロックは入れ子になっていません","这个块没有嵌套","這個區塊沒有巢狀","Este bloque no está anidado","Ce bloc n’est pas imbriqué","Dieser Block ist nicht verschachtelt","Questo blocco non è annidato","Este bloco não está aninhado"],
"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 clip is {size} and travels inside the file, making it that much bigger for everyone you send it to. Embed it anyway?": ["このクリップは {size} あり、ファイルの中に一緒に入ります。その分、送る相手全員にとってファイルが大きくなります。それでも埋め込みますか?","这个片段有 {size},会嵌在文件内部,你发给谁,文件对谁就大出这么多。仍要嵌入吗?","這個片段有 {size},而且會跟著檔案一起走,你傳給的每個人拿到的檔案都會大這麼多。仍要嵌入嗎?","Este clip pesa {size} y viaja dentro del archivo, que crecerá otro tanto para todos a quienes se lo envíes. ¿Incrustarlo de todos modos?","Ce clip 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 ?","Dieser Clip 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 clip è di {size} e viaggia dentro il file, rendendolo altrettanto più grande per chiunque la riceva. Incorporarla comunque?","Este clipe tem {size} e viaja dentro do ficheiro, tornando-o maior para todas as pessoas a quem o enviar. Incorporar mesmo assim?"],
"This copy goes offline; the others carry on": ["このコピーはオフラインになります。ほかの人はそのまま続けられます","此副本将离线;其他人继续协作","此副本將離線;其他人繼續協作","Esta copia se desconecta; las demás siguen","Cette copie passe hors ligne ; les autres continuent","Diese Kopie geht offline; die anderen machen weiter","Questa copia va offline; le altre continuano","Esta cópia fica offline; as outras continuam"],
@@ -593,6 +601,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Your name": ["あなたの名前","你的名字","你的名字","Tu nombre","Votre nom","Dein Name","Il tuo nome","Seu nome"],
"Your name (shown on comments):": ["あなたの名前(コメントに表示):","您的名字(显示在评论中):","您的名字(顯示於註解):","Tu nombre (visible en los comentarios):","Votre nom (affiché sur les commentaires) :","Ihr Name (bei Kommentaren sichtbar):","Il tuo nome (visibile nei commenti):","Seu nome (exibido nos comentários):"],
"Your name (shown on new comments):": ["あなたの名前(新しいコメントに表示):","您的名字(显示在新评论中):","您的名字(顯示於新註解):","Tu nombre (visible en los nuevos comentarios):","Votre nom (affiché sur les nouveaux commentaires) :","Ihr Name (bei neuen Kommentaren sichtbar):","Il tuo nome (visibile nei nuovi commenti):","Seu nome (exibido em novos comentários):"],
+ "a block nests under the one above it": ["ブロックは一つ上のブロックの中に入ります","块会嵌套在它上面的那个块里","區塊會巢狀於它上面的那個區塊","un bloque se anida bajo el que tiene encima","un bloc s’imbrique sous celui qui le précède","ein Block wird unter dem darüberliegenden verschachtelt","un blocco si annida sotto quello che lo precede","um bloco aninha-se sob o que está acima"],
"also called “{name}”": ["別名「{name}」","又名“{name}”","又名「{name}」","también llamada «{name}»","aussi appelée « {name} »","auch „{name}“ genannt","detta anche «{name}»","também chamada “{name}”"],
"archived": ["アーカイブ済み","已归档","已封存","archivada","archivée","archiviert","archiviata","arquivada"],
"bento/spaces is MIT-licensed and carries no third-party runtime — the full notices travel in this file’s source.": ["bento/spaces は MIT ライセンスで、サードパーティのランタイムは含みません。完全な表示はこのファイルのソースに入っています。","bento/spaces 采用 MIT 许可,且不含任何第三方运行时——完整声明就在这个文件的源码里。","bento/spaces 採用 MIT 授權,且不含任何第三方執行環境——完整聲明就在這個檔案的原始碼裡。","bento/spaces tiene licencia MIT y no incluye ningún runtime de terceros: los avisos completos viajan en el código fuente de este archivo.","bento/spaces est sous licence MIT et n’embarque aucun runtime tiers — les mentions complètes voyagent dans le source de ce fichier.","bento/spaces steht unter MIT-Lizenz und enthält keine Fremd-Runtime — die vollständigen Hinweise reisen im Quelltext dieser Datei mit.","bento/spaces è rilasciato con licenza MIT e non include alcun runtime di terze parti: le note complete viaggiano nel sorgente di questo file.","O bento/spaces tem licença MIT e não inclui qualquer runtime de terceiros — os avisos completos viajam no código-fonte deste ficheiro."],
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index 72b177c8..0fdaeed3 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -636,6 +636,15 @@ export const pt: Catalog = {
"Date": "Data",
"Person": "Pessoa",
"Labels": "Etiquetas",
+ "Indent": "Avançar",
+ "Move back out": "Recuar de novo",
+ "Block format": "Formato do bloco",
+ "Block options — type, list, indent": "Opções do bloco — tipo, lista, avanço",
+ "This block is not nested": "Este bloco não está aninhado",
+ "a block nests under the one above it": "um bloco aninha-se sob o que está acima",
+ "A block nests under the one above it — this one has nothing above it": "Um bloco aninha-se sob o que está acima — este não tem nada acima",
+ "Between blocks, and between the lines of one": "Entre blocos, e entre as linhas de um",
+ "Off the edge of a block, into the next": "Da borda de um bloco para o seguinte",
"Footnotes": "Notas de rodapé",
"Back to the text": "Voltar ao texto",
"Write the note": "Escreva a nota",
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index 9fcab6ef..d8ea8d27 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -636,6 +636,15 @@ export const zh_Hans: Catalog = {
"Date": "日期",
"Person": "人员",
"Labels": "标签",
+ "Indent": "缩进",
+ "Move back out": "退回一级",
+ "Block format": "块格式",
+ "Block options — type, list, indent": "块选项 — 类型、列表、缩进",
+ "This block is not nested": "这个块没有嵌套",
+ "a block nests under the one above it": "块会嵌套在它上面的那个块里",
+ "A block nests under the one above it — this one has nothing above it": "块会嵌套在它上面的那个块里 — 这个块上面没有别的块",
+ "Between blocks, and between the lines of one": "在块之间移动,也在一个块的各行之间移动",
+ "Off the edge of a block, into the next": "越过块的边缘,进入下一个块",
"Footnotes": "脚注",
"Back to the text": "返回正文",
"Write the note": "撰写脚注",
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index 08989884..f41f28bb 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -636,6 +636,15 @@ export const zh_Hant: Catalog = {
"Date": "日期",
"Person": "人員",
"Labels": "標籤",
+ "Indent": "縮排",
+ "Move back out": "退回一層",
+ "Block format": "區塊格式",
+ "Block options — type, list, indent": "區塊選項 — 類型、清單、縮排",
+ "This block is not nested": "這個區塊沒有巢狀",
+ "a block nests under the one above it": "區塊會巢狀於它上面的那個區塊",
+ "A block nests under the one above it — this one has nothing above it": "區塊會巢狀於它上面的那個區塊 — 這個區塊上面沒有別的區塊",
+ "Between blocks, and between the lines of one": "在區塊之間移動,也在一個區塊的各行之間移動",
+ "Off the edge of a block, into the next": "越過區塊的邊緣,進入下一個區塊",
"Footnotes": "註腳",
"Back to the text": "回到內文",
"Write the note": "撰寫註腳",
diff --git a/spaces/src/icons.ts b/spaces/src/icons.ts
index b0f10b0f..d5130254 100644
--- a/spaces/src/icons.ts
+++ b/spaces/src/icons.ts
@@ -97,6 +97,10 @@ export const ICONS = {
toggle: svg('<polyline points="9 6 15 12 9 18"/><line x1="19" y1="12" x2="21" y2="12"/>'),
quote: svg('<path d="M6 17h3l2-4V7H5v6h3zM16 17h3l2-4V7h-6v6h3z"/>'),
code: svg('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>'),
+ // The two controls that existed on no surface at all before the block
+ // format row: lines, with an arrow saying which way the nesting goes.
+ indent: svg('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><polyline points="3 8 6 12 3 16"/>'),
+ outdent: svg('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><polyline points="6 8 3 12 6 16"/>'),
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"/>'),
diff --git a/spaces/src/nesting.ts b/spaces/src/nesting.ts
new file mode 100644
index 00000000..dedc5f06
--- /dev/null
+++ b/spaces/src/nesting.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// What Tab MEANS, and why it sometimes says no.
+//
+// THE DECISION, so nobody has to re-derive it from the silence.
+//
+// A space expresses nesting with ONE field: `Block.parent`, pointing at a
+// block that precedes it. That is structural — the nested block is a child of
+// a real block, and everything downstream reads it as one: the renderer's
+// indent, the markdown export's list levels, the outline, the graph, `sync`'s
+// per-node diff, "merge back" re-homing orphans. There is no second
+// representation and never has been.
+//
+// So "indent the first item of a list" is not a hard case, it is a case with
+// no answer: there is nothing preceding it at the same level to be its parent.
+// `editor.ts indent()` walked backwards looking for one, found nothing, and
+// returned — correct, and completely silent, which is the bug the maintainer
+// hit. A control that does nothing and says nothing is worse than a control
+// that is missing, because the reader concludes the app is broken rather than
+// that the gesture does not apply.
+//
+// TWO WAYS OUT, and only one of them is free.
+//
+// (a) ALLOW IT, by storing an indent LEVEL — what Google Docs does. This is a
+// format addition, and the format here is additive and PERMANENT: every
+// version from now on opens what this one wrote. It would also be a
+// SECOND way to express nesting, so every reader in the paragraph above
+// has to reconcile two systems and answer questions that currently cannot
+// be asked — what a `level: 2` block with a `parent` means, which wins,
+// what the markdown export emits for an orphan at level 2, what two
+// replicas do when one sets `parent` and the other sets `level`. The cost
+// is not writing the field; it is that it can never be taken back.
+//
+// (b) REFUSE, VISIBLY — what Notion, Workflowy, Bear and Logseq all do,
+// because they all nest by parenthood too. The gesture keeps one meaning,
+// the format does not grow, and the fix for the actual complaint is that
+// the refusal now SAYS SO: the editor puts the rule in the status line
+// ("A block nests under the one above it…") and nudges the block, and the
+// indent control in the block menu is disabled with the same reason as
+// its title, so the answer is visible before the key is pressed as well
+// as after.
+//
+// (b) is what this ships. The deciding argument is the permanence in (a): a
+// silent Tab is a bug worth an afternoon, and a duplicate nesting model is a
+// bug worth every future version of the reader.
+//
+// Shift+Tab is unaffected and still outdents by the EFFECTIVE parent.
+//
+// These functions are pure so the refusal is testable — the failing case is
+// the first item, and a happy-path test that indents the SECOND item passes
+// against the broken code as readily as against this one.
+
+/** The only two fields nesting is about. */
+export interface Nestable { id: string; parent?: string }
+
+export type IndentResult =
+ /** Tab applies: `parent` is the block that becomes the owner. */
+ | { ok: true; parent: string }
+ /** Tab does not apply, and this is what to tell the reader. */
+ | { ok: false; why: 'first' | 'gone' }
+
+/**
+ * What Tab resolves to for `id` — the nearest PRECEDING block at the same
+ * level, which becomes its parent.
+ *
+ * `why: 'first'` means there is no such block: `id` is the first at its level,
+ * so there is nothing to nest under. `why: 'gone'` means `id` is not in the
+ * page at all, which is a caller bug rather than a refusal a reader should see.
+ */
+export function indentTarget(blocks: readonly Nestable[], id: string): IndentResult {
+ const i = blocks.findIndex((b) => b.id === id)
+ if (i < 0) return { ok: false, why: 'gone' }
+ const me = blocks[i]
+ for (let j = i - 1; j >= 0; j--) {
+ if (blocks[j].parent === me.parent) return { ok: true, parent: blocks[j].id }
+ }
+ return { ok: false, why: 'first' }
+}
+
+/**
+ * Can `id` be outdented?
+ *
+ * By the EFFECTIVE parent map (model.ts `effectiveParents`), never by whatever
+ * `parent` names: on a merged document `parent` can point at a block that is
+ * absent or that sits later, and the renderer does not nest by those either.
+ * Passed in rather than computed so this stays pure and so the editor computes
+ * the map once.
+ */
+export function canOutdent(effective: ReadonlyMap<string, string | undefined>, id: string): boolean {
+ return effective.get(id) !== undefined
+}
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index 4705f6f2..5a8a23f9 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -2682,6 +2682,52 @@ body.sp-canvas-dragging { user-select: none; cursor: grabbing; }
.sp-cv-grip, .sp-canvas-btn { display: none !important; }
}
+/* ————— the block format row —————
+ Lives at the top of the block menu, which is a bottom SHEET on a phone, so
+ this is the same markup at both widths and the touch targets are sized for
+ the smaller of them (44px is the floor a thumb needs; the row wraps rather
+ than scrolls, because a scroll container inside a popover clips the other
+ axis too). blockbar.ts records why these controls are not in the selection
+ toolbar. */
+.sp-blockbar {
+ display: flex; flex-wrap: wrap; gap: 2px; align-items: center;
+ padding: 2px 2px 6px; margin-bottom: 4px; border-bottom: 1px solid var(--line);
+}
+.sp-blockbar-gap { flex: 1 1 auto; min-width: 4px; }
+.sp-blockbtn {
+ display: inline-flex; align-items: center; justify-content: center;
+ /* 28, not 30: eight type buttons plus their gaps have to fit one row of a
+ 260px popover (8×28 + 7×2 = 238 ≤ 248 of usable width), so the row breaks
+ between the types and the two nesting controls rather than orphaning the
+ quote button on a line of its own. Measured in the built shell. */
+ width: 28px; height: 28px; padding: 0; border: 0; border-radius: 7px;
+ background: none; color: var(--ink-2); cursor: pointer;
+}
+.sp-blockbtn svg { width: 17px; height: 17px; }
+.sp-blockbtn:hover { background: var(--chrome-2); color: var(--ink); }
+.sp-blockbtn.sp-sel { background: var(--chrome-2); color: var(--accent); }
+/* aria-disabled, NOT disabled: the control has to stay focusable so a keyboard
+ can reach the label that explains why it is off (blockbar.ts). So the opacity
+ is the only thing that changes — clicks still land, and land on the code that
+ says why. */
+.sp-blockbtn.sp-off { opacity: .38; }
+@media (pointer: coarse) {
+ .sp-blockbar { gap: 4px; padding-bottom: 8px; }
+ .sp-blockbtn { width: 44px; height: 44px; }
+ .sp-blockbtn svg { width: 20px; height: 20px; }
+}
+
+/* A refused gesture, at the block it was aimed at. The words are in the status
+ line; this is the pointer. Motion only — no layout, so it cannot reflow the
+ prose under the caret. */
+@media (prefers-reduced-motion: no-preference) {
+ .sp-nudge { animation: sp-nudge .34s ease; }
+ @keyframes sp-nudge {
+ 0%, 100% { transform: none }
+ 25% { transform: translateX(3px) }
+ 60% { transform: translateX(-2px) }
+ }
+}
/* ---------------------------------------------------------------------------
FOOTNOTES (src/footnotes.ts)