Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: every menu is the kernel menu — arrow keys, Escape, no leaked listeners (chrome PR 1 of 3) (#563)

nyblnet4746a5a49e75
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fea378f4..00128c00 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -256,6 +256,17 @@ jobs:
# mistakes is made in the source.
run: node scripts/test-spaces-model.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
+ # input and asserts what spaces used to get wrong invisibly: arrow keys
+ # in every menu, Escape with focus return, one menu open at a time, no
+ # listener left on the document by a menu closed with Escape (one used
+ # to close the NEXT overlay on its first click), no global shortcut
+ # under a modal, and phone menus that end inside the screen with 44px
+ # rows. Needs the shell built above; a skip in CI is a failure.
+ run: node scripts/test-spaces-chrome.ts
+
- name: spaces rig manifest
# Bookkeeping, not a ninth run of the eight steps above. scripts/
# test-spaces.mjs is the local entry point for the spaces suite (two of
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index d781a0c9..dd966c33 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -8125,6 +8125,87 @@ size limit must be enforced DURING decompression, never after; the declared
size in a container header is an attacker input, and the primitive, not the
caller's preflight, must hold the ceiling.
+## 2026-09-26 — Spaces adopts the kernel menu; an anchored menu is the primitive mounted over its anchor
+
+**Every menu in bento/spaces is `createMenu` (kernel/src/ui/menu.ts), through
+one adapter, `spaces/src/menus.ts`.** That covers the topbar dropdowns (Insert,
+⋯, the save caret) and the nine anchored popovers that were menus: the block and
+page ⋯ menus, a view's group, sort, filter and source, a select field's options,
+a code block's language, a callout's tone, and "Add a property". Spaces' own
+`dropdown()`, `menuItem()`, `trapAndClose()` and every per-popover `mousedown`
+away-listener are deleted. `scripts/test-spaces-chrome.ts` asserts that the
+adapter is the only spaces file importing the kernel menu, and drives the
+built shell with trusted CDP input.
+
+**Why adopt the primitive, and not fix spaces' copies.** Measured on the built
+shell before the change:
+- No menu had arrow keys.
+- A popover closed by Escape left its away-listener on the document. That
+ listener closed the next overlay on its first mousedown, even a press inside
+ it. Escape a block menu, press ⌘K, click in the search card, and the search
+ closed.
+- The phone ⋯ menu was 950px tall in an 844px viewport, and its last three rows
+ were unreachable.
+- At 1440×900 the Insert menu ran 10px off the bottom of the window.
+
+The kernel's rig already proves Escape with focus return, arrows, `aria-expanded`,
+outside-press, mutual exclusion and a single delegated listener pair. Adopting
+the primitive gets all of it. Fixing four copies would have left four copies.
+
+**The anchored mode is composition, not a fork.** The kernel positions a menu
+under its own trigger in CSS. `anchoredMenu()` mounts the menu's wrapper
+`position: fixed` exactly over the anchor with the trigger hidden. It places the
+popup against the viewport with the rules the old `place()` used: flip above
+when there is more room, cap the height to the room available, clamp to the
+edges. Below the drawer breakpoint the popup is a bottom sheet. The primitive
+has no close callback, so the adapter observes the wrapper's `bkm-open` class.
+That is the one signal every close path shares: a row, Escape, an outside
+press, another menu opening. The observer tears the menu down, calls `onClose`
+exactly once, and returns focus to the anchor if focus was inside the menu.
+
+**What stays a popover, and why.** These keep spaces' `.sp-pop` and are not
+menus:
+- the `/` block filter, a combobox whose input keeps focus;
+- the icon grid;
+- a free-text field value;
+- the share panel;
+- a comment thread.
+
+They go through one helper, `float()`. It registers its Escape handler, its
+away-listener and its resize reflow in a teardown list that `closeOverlay()`
+always runs, so no path leaves a listener behind. A panel of controls announces
+`role="dialog"`, not `role="menu"`. The share panel and the thread said "menu"
+while holding a textarea.
+
+**A modal owns the keyboard.** The editor's keymap returns before reading any
+global shortcut while an `[aria-modal="true"]` element exists. Before this, `[`
+toggled the page list behind About (and persisted that choice), and `?` stacked
+a second modal.
+
+**The rulings applied here** (maintainer, 2026-09-25):
+- **D2:** a visible second line only where a row has a consequence (Save-as,
+ the page menu's archive, width and delete, "Make this page an issue");
+ command lists are one line.
+- **D5:** 44px menu rows under a coarse pointer.
+- **D7:** ⋯, not ⋮.
+- **D8:** shortcuts right-aligned in the UI face, in ⌃⌥⇧⌘ order, from one
+ helper (`keys()`); hidden where the pointer is coarse.
+
+The chrome scale uses the names of the shared token sheet. That sheet is not
+merged, so spaces does not depend on it; adopting it later deletes spaces'
+unthemed `:root` scale block.
+
+**Gaps the kernel menu has, written down for the kernel rather than forked
+here:**
+- an anchored mode with viewport-aware placement;
+- a close callback;
+- a right-aligned shortcut slot on a row;
+- `role` and `aria-checked` options for `menuitemcheckbox` and
+ `menuitemradio` rows (the adapter sets them after `item()` returns).
+
+**Cost:** +2,041 B of shell (282,586 → 284,627, both built with `ZOPFLI=0`).
+The kernel sheet carries rules spaces never needed (the scrolling bar, nested
+menus). The kernel file's own header predicted a slightly bigger shell.
## 2026-10-05 — An embed keeps the source document, never its capabilities (type)
**An embedded document's `collab` block — that document's sharing keys — does
diff --git a/scripts/test-spaces-chrome.ts b/scripts/test-spaces-chrome.ts
new file mode 100644
index 00000000..42d76e69
--- /dev/null
+++ b/scripts/test-spaces-chrome.ts
@@ -0,0 +1,277 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/spaces CHROME — the menus behave like the kernel's menus, because they
+// are the kernel's menus.
+//
+// node scripts/test-spaces-chrome.ts (after `npm run build:single` in spaces/)
+//
+// WHY THIS EXISTS. Spaces grew its own dropdown and nine anchored popovers,
+// each with its own dismissal. What they did NOT do was invisible in a
+// screenshot and measured on the built shell:
+//
+// · no menu had arrow keys;
+// · every popover's `mousedown` away-listener removed itself only when it
+// fired, so one closed by Escape stayed on the document and closed the NEXT
+// overlay on its first press — Escape a block menu, ⌘K, click inside the
+// search card, and the search closed;
+// · the global shortcuts ran BEFORE the "an overlay is open" test, and the
+// modal dialogs never set it: `[` collapsed the page list behind About,
+// `?` stacked a second modal on top of it;
+// · on a phone the ⋯ menu was 950px tall in an 844px screen, and its last
+// three rows — the only ways to save a copy or export there — could not
+// be reached; at 1440×900 the Insert menu's last row was cut off.
+//
+// Every menu is now `createMenu` (kernel/src/ui/menu.ts) through
+// spaces/src/menus.ts. The kernel's own rig proves the primitive; THIS rig
+// proves spaces actually uses it — with TRUSTED input (CDP), on the built
+// shell, counting the document's listeners with DOMDebugger rather than
+// trusting a comment that says they are removed.
+//
+// The source half always runs. The browser half needs Chrome and the built
+// shell; it self-skips outside CI and FAILS inside it.
+
+import { existsSync, readFileSync, mkdtempSync, rmSync, readdirSync } from 'node:fs'
+import { spawn, spawnSync } from 'node:child_process'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+let checks = 0
+let failures = 0
+const ok = (cond: unknown, msg: string): void => {
+ checks++
+ if (cond) console.log(` ok ${msg}`)
+ else { failures++; console.log(` FAIL ${msg}`) }
+}
+
+// ————— source half —————————————————————————————————————————————————————————
+console.log('\nthe source\n')
+const SRC = join(root, 'spaces/src')
+const files = readdirSync(SRC).filter((f) => f.endsWith('.ts'))
+const read = (f: string) => readFileSync(join(SRC, f), 'utf8')
+const editor = read('editor.ts')
+const css = readFileSync(join(SRC, 'styles.css'), 'utf8')
+
+const menuImports = files.filter((f) => /from '\.\.\/\.\.\/kernel\/src\/ui\/menu\.ts'/.test(read(f)))
+ok(menuImports.length === 1 && menuImports[0] === 'menus.ts',
+ `the kernel menu is imported in ONE place, the adapter (found in: ${menuImports.join(', ') || 'none'})`)
+ok(/import \{[^}]*\bbarMenu\b[^}]*\banchoredMenu\b[^}]*\} from '\.\/menus\.ts'/.test(editor),
+ 'the editor builds its menus through the adapter (barMenu, anchoredMenu)')
+ok(!/private dropdown\(/.test(editor) && !/private menuItem\(/.test(editor),
+ 'spaces\' own dropdown() and menuItem() are gone')
+ok(!/sp-ddmenu|\.sp-dd\b|sp-dd-end/.test(css + editor),
+ 'no .sp-dd / .sp-ddmenu machinery survives in the stylesheet or the editor')
+const aways = [...editor.matchAll(/addEventListener\('(mousedown|pointerdown)', away/g)]
+ok(aways.length === 1, `exactly ONE away-listener is installed in the editor, in float() (found ${aways.length})`)
+const floatBody = editor.slice(editor.indexOf(' private float('), editor.indexOf('\n }\n', editor.indexOf(' private float(')))
+ok(/overlayOff\.push\([\s\S]*removeEventListener\('pointerdown', away, true\)/.test(floatBody),
+ 'float() registers the away-listener\'s REMOVAL with closeOverlay, so it goes however the popover closes')
+const handMenus = files.filter((f) => f !== 'menus.ts').filter((f) => /setAttribute\('role', 'menu'\)/.test(read(f)))
+ok(handMenus.length === 0, `no file hand-builds a role=menu popup any more (found in: ${handMenus.join(', ') || 'none'})`)
+const onKey = editor.slice(editor.indexOf(' private onKey(e: KeyboardEvent): void {'))
+const guardAt = onKey.indexOf(`if (document.querySelector('[aria-modal="true"]')) return`)
+const firstShortcut = onKey.indexOf("e.key.toLowerCase() === 'k'")
+ok(guardAt > 0 && guardAt < firstShortcut,
+ 'the editor\'s keymap stands down under a modal BEFORE any global shortcut is read')
+
+// ————— browser half ————————————————————————————————————————————————————————
+console.log('\nthe built shell, driven with trusted input\n')
+const CHROME = [process.env.BENTO_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']
+ .find((p) => p && existsSync(p)) ?? (spawnSync('which', ['google-chrome']).status === 0 ? 'google-chrome' : undefined)
+const SHELL = join(root, 'spaces/dist-single/Bento_Spaces.bento.html')
+
+if (!CHROME || !existsSync(SHELL)) {
+ if (process.env.CI) ok(false, `the browser half RAN (Chrome: ${CHROME ?? 'none'}, shell: ${existsSync(SHELL)}) — in CI a skip is a failure`)
+ else console.log(` skip needs Chrome (BENTO_CHROME) and the built shell (${SHELL})`)
+} else {
+ await browser(CHROME, readFileSync(SHELL, 'utf8'))
+}
+
+async function browser(chrome: string, html: string): Promise<void> {
+ const server = createServer((_q, r) => { r.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); r.end(html) })
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ const port = (server.address() as { port: number }).port
+ const profile = mkdtempSync(join(tmpdir(), 'bento-spaces-chrome-'))
+ const child = spawn(chrome, ['--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run', '--no-default-browser-check',
+ '--disable-background-networking', '--disable-component-update', '--disable-sync', '--hide-scrollbars',
+ '--remote-debugging-port=0', '--user-data-dir=' + profile, 'about:blank'], { stdio: 'ignore' })
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
+ try {
+ const portFile = join(profile, 'DevToolsActivePort')
+ for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100)
+ const cdp = readFileSync(portFile, 'utf8').split('\n')[0].trim()
+ const t = await (await fetch(`http://127.0.0.1:${cdp}/json/new?about:blank`, { method: 'PUT' })).json() as { webSocketDebuggerUrl: string }
+ const ws = new WebSocket(t.webSocketDebuggerUrl)
+ await new Promise<void>((res, rej) => { ws.addEventListener('open', () => res()); ws.addEventListener('error', () => rej(new Error('cdp socket'))) })
+ let id = 0
+ const pending = new Map<number, (m: any) => void>()
+ ws.addEventListener('message', (e) => {
+ const m = JSON.parse(String(e.data))
+ // a native confirm()/alert() would freeze every later step; dismiss it
+ if (m.method === 'Page.javascriptDialogOpening') ws.send(JSON.stringify({ id: 1e6 + (++id), method: 'Page.handleJavaScriptDialog', params: { accept: false } }))
+ if (m.id && pending.has(m.id)) { pending.get(m.id)!(m); pending.delete(m.id) }
+ })
+ const send = (method: string, params: Record<string, unknown> = {}): Promise<any> =>
+ new Promise((res) => { const i = ++id; pending.set(i, res); ws.send(JSON.stringify({ id: i, method, params })) })
+ const js = async <T = any>(expression: string): Promise<T> => {
+ const m = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })
+ if (m.result?.exceptionDetails) throw new Error(m.result.exceptionDetails.exception?.description ?? 'eval failed')
+ return m.result?.result?.value as T
+ }
+ const click = async (x: number, y: number) => {
+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
+ await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
+ await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
+ await sleep(250)
+ }
+ const key = async (k: string, modifiers = 0, code = k, vk = 0) => {
+ const text = k.length === 1 && !(modifiers & 6) ? k : undefined
+ await send('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', key: k, code, modifiers, text, windowsVirtualKeyCode: vk })
+ await send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, modifiers })
+ await sleep(150)
+ }
+ const at = async (expr: string): Promise<{ x: number; y: number } | null> =>
+ js(`(() => { const e = ${expr}; if (!e) return null; e.scrollIntoView?.({ block: 'nearest' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 } })()`)
+ const tap = async (expr: string) => { const p = await at(expr); if (!p) throw new Error('not found: ' + expr); await click(p.x, p.y) }
+ const docListeners = async (): Promise<Record<string, number>> => {
+ const o = await send('Runtime.evaluate', { expression: 'document' })
+ const l = await send('DOMDebugger.getEventListeners', { objectId: o.result.result.objectId })
+ const c: Record<string, number> = {}
+ for (const x of l.result.listeners) c[x.type] = (c[x.type] ?? 0) + 1
+ return c
+ }
+ const open = async (phone: boolean) => {
+ await send('Emulation.setDeviceMetricsOverride', phone
+ ? { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }
+ : { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false })
+ await send('Emulation.setTouchEmulationEnabled', { enabled: phone, maxTouchPoints: phone ? 5 : 1 })
+ await send('Page.navigate', { url: `http://127.0.0.1:${port}/s.html` })
+ for (let i = 0; i < 100; i++) { await sleep(100); if (await js('!!(window.bento && window.bento.doc && document.querySelector(".sp-bar"))')) break }
+ await js('try { localStorage.clear() } catch {}; document.activeElement?.blur?.(); 1')
+ await sleep(400)
+ }
+ // The editor's ⌘ is metaKey on a Mac and ctrlKey everywhere else
+ // (spaces/src/editor.ts CTRL, read from navigator.platform). Press the one
+ // THE PAGE reads — a hard-coded Meta passes on a Mac and never reaches the
+ // shortcut on CI's Linux runner, which is how ⌘K "failed" there.
+ const MOD = async (): Promise<number> =>
+ (await js<boolean>(`navigator.platform.toLowerCase().includes('mac')`)) ? 4 : 2
+ await send('Page.enable')
+ await send('Runtime.enable')
+ await send('Emulation.setFocusEmulationEnabled', { enabled: true })
+
+ const TRIG = (label: string) => `[...document.querySelectorAll('.sp-bar button')].find(b => b.getAttribute('aria-label') === ${JSON.stringify(label)})`
+ const OPEN = `[...document.querySelectorAll('.bkm-open > .bkm-menu')].find(m => m.getBoundingClientRect().height > 0)`
+ const FOCUSED = `(document.activeElement?.textContent || '').trim().slice(0, 30)`
+
+ // ——— desktop ———
+ await open(false)
+ const baseline = await docListeners()
+ ok(await js(`document.visibilityState === 'visible' && document.querySelector('meta[name=generator]')?.content === 'bento-spaces'`),
+ 'the page under test is the spaces shell, visible')
+
+ await tap(TRIG('More'))
+ const more = await js<any>(`(() => { const m = ${OPEN}; const t = ${TRIG('More')}; if (!m) return null; const r = m.getBoundingClientRect(); return { exp: t.getAttribute('aria-expanded'), role: m.getAttribute('role'), bottom: r.bottom, vh: innerHeight } })()`)
+ ok(more && more.exp === 'true' && more.role === 'menu', `⋯ opens as a menu and says so (aria-expanded ${more?.exp}, role ${more?.role})`)
+ await key('ArrowDown', 0, 'ArrowDown')
+ const first = await js<string>(FOCUSED)
+ await key('ArrowDown', 0, 'ArrowDown')
+ const second = await js<string>(FOCUSED)
+ ok(first.startsWith('New page') && second.startsWith("Today's journal"), `arrow keys walk the ⋯ rows ("${first}" → "${second}")`)
+ await key('Escape', 0, 'Escape')
+ const afterEsc = await js<any>(`({ open: !!(${OPEN}), exp: (${TRIG('More')}).getAttribute('aria-expanded'), focus: document.activeElement === (${TRIG('More')}) })`)
+ ok(!afterEsc.open && afterEsc.exp === 'false' && afterEsc.focus, `Escape closes ⋯, clears aria-expanded and puts focus back on its trigger (${JSON.stringify(afterEsc)})`)
+
+ await tap(TRIG('More'))
+ await tap(`[...document.querySelectorAll('.sp-bar button')].find(b => (b.getAttribute('aria-label') || '').startsWith('Insert'))`)
+ const exclusive = await js<number>(`document.querySelectorAll('.bkm-open').length`)
+ ok(exclusive === 1, `opening Insert shuts ⋯ — one menu open at a time (${exclusive} open)`)
+ const ins = await js<any>(`(() => { const r = (${OPEN}).getBoundingClientRect(); return { bottom: Math.round(r.bottom), vh: innerHeight } })()`)
+ ok(ins.bottom <= ins.vh, `the Insert menu fits a 1440×900 window (bottom ${ins.bottom} ≤ ${ins.vh}; it ran to 910 before)`)
+ await click(900, 700)
+ ok(!(await js<boolean>(`!!(${OPEN})`)), 'a press outside closes the menu')
+
+ // the leak, stated as the user met it
+ const grip = `(() => { const n = document.querySelectorAll('.sp-main [data-block-id]')[2]; return [...n.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Block options') })()`
+ for (let i = 0; i < 5; i++) {
+ const g = await at(`document.querySelectorAll('.sp-main [data-block-id]')[2]`)
+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: g!.x - 200, y: g!.y })
+ await sleep(120)
+ await tap(grip)
+ if (i === 0) {
+ const bm = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; const r = m.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, vh: innerHeight, label: m.getAttribute('aria-label') } })()`)
+ ok(bm && bm.label === 'Block options' && bm.top >= 0 && bm.bottom <= bm.vh, `the block menu is a kernel menu, placed inside the window (${JSON.stringify(bm)})`)
+ await key('ArrowDown', 0, 'ArrowDown')
+ ok((await js<string>(FOCUSED)).startsWith('Turn into'), 'ArrowDown lands on the block menu\'s first row')
+ }
+ await key('Escape', 0, 'Escape')
+ }
+ const afterMenus = await docListeners()
+ const same = JSON.stringify(Object.entries(afterMenus).sort()) === JSON.stringify(Object.entries(baseline).sort())
+ ok(same, `five block menus closed by Escape leave the document's listeners exactly as they were (${JSON.stringify(baseline)} → ${JSON.stringify(afterMenus)})`)
+ await js(`document.activeElement?.blur?.(); 1`)
+ await key('k', await MOD(), 'KeyK', 75)
+ const card = await at(`[...document.querySelectorAll('[role=dialog]')].find(d => d.getBoundingClientRect().height > 0)`)
+ ok(!!card, '⌘K opens the search dialog')
+ if (card) {
+ const c = await js<any>(`(() => { const d = [...document.querySelectorAll('[role=dialog]')].find(d => d.getBoundingClientRect().height > 0); const r = d.getBoundingClientRect(); return { x: r.right - 30, y: r.top + 14 } })()`)
+ await click(c.x, c.y)
+ ok(await js<boolean>(`!![...document.querySelectorAll('[role=dialog]')].find(d => d.getBoundingClientRect().height > 0)`),
+ 'a click INSIDE the search dialog, after an Escaped menu, leaves it open (it closed it before)')
+ await key('Escape', 0, 'Escape')
+ }
+
+ // page ⋯ — an anchored menu
+ const row = `document.querySelector('.sp-treelink.sp-here')`
+ const rp = await at(row)
+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: rp!.x, y: rp!.y })
+ await sleep(150)
+ await tap(`document.querySelector('.sp-treelink.sp-here .sp-rowmore')`)
+ await key('ArrowDown', 0, 'ArrowDown')
+ ok((await js<string>(FOCUSED)).startsWith('Rename'), 'the page ⋯ menu takes the arrow keys')
+ await key('Escape', 0, 'Escape')
+ ok(await js<boolean>(`!(${OPEN}) && document.activeElement === document.querySelector('.sp-treelink.sp-here .sp-rowmore')`),
+ 'Escape closes the page menu and returns focus to the ⋯ that opened it')
+
+ // a modal owns the keyboard
+ await tap(`document.querySelector('.sp-mark')`)
+ const side0 = await js<string>(`document.querySelector('.sp-side').className`)
+ await js(`document.activeElement?.blur?.(); 1`)
+ await key('[', 0, 'BracketLeft', 219)
+ await key('?', 8, 'Slash', 191)
+ const underModal = await js<any>(`({ side: document.querySelector('.sp-side').className, modals: document.querySelectorAll('[aria-modal="true"]').length })`)
+ ok(underModal.side === side0 && underModal.modals === 1,
+ `under About, \`[\` and \`?\` do nothing behind it (page list ${underModal.side === side0 ? 'unchanged' : 'TOGGLED'}, ${underModal.modals} modal open)`)
+ await key('Escape', 0, 'Escape')
+
+ // ——— phone ———
+ await open(true)
+ await tap(TRIG('More'))
+ const ph = await js<any>(`(() => { const m = ${OPEN}; const r = m.getBoundingClientRect(); const rows = [...m.querySelectorAll('.bkm-item')]; return { bottom: r.bottom, vh: innerHeight, n: rows.length, minH: Math.min(...rows.map(x => x.getBoundingClientRect().height)), scrolls: m.scrollHeight > m.clientHeight } })()`)
+ ok(ph.bottom <= ph.vh, `the phone ⋯ menu ends inside the screen (bottom ${Math.round(ph.bottom)} ≤ ${ph.vh}; 1003 before)`)
+ ok(ph.minH >= 44, `every phone menu row is a 44px target (smallest ${ph.minH.toFixed(1)}px)`)
+ const last = await js<any>(`(() => { const m = ${OPEN}; const rows = [...m.querySelectorAll('.bkm-item')]; const l = rows[rows.length - 1]; l.scrollIntoView({ block: 'nearest' }); const r = l.getBoundingClientRect(); const hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2); return { text: l.textContent.trim().slice(0, 24), reach: l.contains(hit) } })()`)
+ ok(last.reach, `the last ⋯ row ("${last.text}") can be scrolled to and pressed`)
+ await key('Escape', 0, 'Escape')
+ const g2 = `(() => { const n = document.querySelectorAll('.sp-main [data-block-id]')[2]; return [...n.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Block options') })()`
+ await tap(g2)
+ const sheet = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; const r = m.getBoundingClientRect(); return { bottom: r.bottom, vh: innerHeight, w: r.width, vw: innerWidth, minH: Math.min(...[...m.querySelectorAll('.bkm-item')].map(x => x.getBoundingClientRect().height)) } })()`)
+ ok(sheet && sheet.vh - sheet.bottom <= 12 && sheet.w >= sheet.vw - 20 && sheet.minH >= 44,
+ `on a phone the block menu is a bottom sheet of 44px rows (${JSON.stringify(sheet)})`)
+ ws.close()
+ } finally {
+ try { child.kill('SIGKILL') } catch { /* gone */ }
+ server.close()
+ // Chrome may still be writing its profile as it dies; a failed cleanup of
+ // a temp dir is not a failed check
+ await new Promise<void>((r) => { child.once('exit', () => r()); setTimeout(r, 2000) })
+ try { rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } catch { /* temp dir */ }
+ }
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.ts
index 2ce5a087..8d747873 100644
--- a/scripts/test-spaces-model.ts
+++ b/scripts/test-spaces-model.ts
@@ -439,10 +439,11 @@ for (const [label, input, err] of [
ok(!/\.sp-pop \{[^}]*max-height: 44vh/.test(css), 'the popover is not capped at a fraction of the window')
ok(/pop\.style\.maxHeight = /.test(ed), '…place() gives it the room the anchor actually leaves')
- // Both popover builders must route through the helper, or the one that does
- // not will size itself once and stay that size while the window moves.
- const viaHelper = (ed.match(/else this\.placed\(pop, anchor\)/g) ?? []).length
- ok(viaHelper === 2, 'both popover call sites place through the same helper')
+ // Every popover that is not a menu routes through ONE helper, float(), or
+ // the one that does not will size itself once and stay that size while the
+ // window moves. (Menus are the kernel's, placed by spaces/src/menus.ts.)
+ const viaHelper = (ed.match(/this\.float\(pop, /g) ?? []).length
+ ok(viaHelper >= 4, `every non-menu popover places through the same helper, float() (${viaHelper} call sites)`)
ok(/addEventListener\('resize', reflow\)/.test(ed), '…which re-places on resize')
ok(/removeEventListener\('resize', reflow\)/.test(ed), '…and takes the listener back off when it closes')
@@ -839,7 +840,7 @@ for (const [label, input, err] of [
ok(/const menuActions: BarAction\[\]/.test(ed), '…the ⋯-only actions as another')
ok(/barActions\.map\(/.test(ed), '…the inline row is built from the bar list')
ok(/for \(const a of menuActions\)/.test(ed), '…⋯ always carries the menu-only actions')
- ok(/isFolded\(\)\) \{\s*\n\s*for \(const a of barActions\)/.test(ed),
+ ok(/const folded = this\.isFolded\(\)/.test(ed) && /if \(folded\) \{\s*\n\s*for \(const a of barActions\)/.test(ed),
'…and picks up the bar list ONLY once folded, or ⋯ duplicates the visible row')
// WHICH TIER a rule lives in is the thing worth pinning — but the tiers are
@@ -910,7 +911,7 @@ for (const [label, input, err] of [
const edCode = ed.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
ok(!/matchMedia\('\(max-width: 600px\)'\)/.test(edCode),
'no phone breakpoint is duplicated in the editor CODE')
- ok(/if \(this\.isFolded\(\)\)/.test(ed) && /t\('Undo \(⌘Z\)'\)/.test(ed) && /t\('Redo \(⇧⌘Z\)'\)/.test(ed),
+ ok(/if \(folded\) \{[\s\S]{0,400}?label: t\('Undo'\)[\s\S]{0,300}?label: t\('Redo'\)/.test(ed),
'…and the ⋯ menu picks up undo/redo exactly when the bar has folded them away')
// the bar must never become a scroller — that hides the same controls, just
@@ -919,11 +920,9 @@ for (const [label, input, err] of [
ok(!/overflow-x:\s*(auto|scroll)/.test(barRule), 'the topbar does not scroll horizontally')
// a menu opened from the right end must open inward
- ok(/\.sp-dd-end \.sp-ddmenu \{ inset-inline-start: auto; inset-inline-end: 0/.test(css),
- 'right-end dropdowns open inward')
- ok(/more\.classList\.add\('sp-more', 'sp-dd-end'\)/.test(ed) &&
- /saveMore\.classList\.add\('sp-caret', 'sp-dd-end'\)/.test(ed),
- '…and both right-end menus say so')
+ // (the kernel menu's `alignEnd` is what opens it inward — kernel/src/ui/menu.css .bkm-end)
+ ok(/tip: t\('More'\), end: true/.test(ed) && /tip: t\('Other ways to save'\), end: true/.test(ed),
+ 'both right-end menus open inward (the kernel menu\'s alignEnd)')
}
// ---- one declaration per block type ---------------------------------------
diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjs
index efbe7993..7267c86a 100755
--- a/scripts/test-spaces.mjs
+++ b/scripts/test-spaces.mjs
@@ -56,6 +56,8 @@ const RIGS = [
// built spaces shell and Playwright/Chrome (the CI browser job provides both).
{ name: 'save-revisions', file: 'scripts/test-spaces-save-revisions.ts' },
{ name: 'save-browser', file: 'scripts/test-spaces-save-browser.mjs' },
+ // drives the BUILT shell in Chrome; self-skips outside CI without one
+ { name: 'chrome', file: 'scripts/test-spaces-chrome.ts' },
]
// A rig that exists but is not listed here would never run locally, and the
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 7e69880e..8bf46d18 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -532,6 +532,37 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
recovery banner in the first place. Reading copies and view-only copies
don't offer to restore at all.
+- **Every menu is the suite's menu now, and it behaves like one.** Insert, ⋯,
+ the save caret, the block and page ⋯ menus, a board's group, sort, filter and
+ source menus, a field's options, a code block's language and a callout's tone
+ are all built on the kernel's shared menu. You can walk every one of them with
+ the arrow keys and close it with Escape, and focus goes back to the button
+ that opened it. Opening one menu closes any other. Four things this fixes,
+ each measured in the built file:
+ - A menu closed with Escape left its click-away listener behind, and that
+ listener closed the NEXT thing you opened on your first click inside it:
+ Escape a block menu, press ⌘K, click in the search box, and the search
+ vanished.
+ - On a phone the ⋯ menu was 950px tall on an 844px screen. Its last three
+ rows, which are the only ways to save a copy or export on a phone, could
+ not be reached. It now ends inside the screen and scrolls.
+ - The Insert menu's last row ran off the bottom of a 1440×900 window. Insert
+ is one line per row now, with the Markdown shortcut (`#`, `1.`, `>`) on the
+ right. The descriptions stay on the `/` menu, where you learn them.
+ - With About or the shortcut sheet open, `[` collapsed the page list behind
+ it and `?` opened a second sheet on top. Nothing reaches the page under an
+ open dialog now.
+
+ On a phone, every anchored menu is a sheet at the bottom of the screen,
+ including the page ⋯ menu, which used to be a small popup over the drawer.
+ Rows are 44px tall under a finger. Shortcuts are right-aligned and written
+ in one order, ⌃⌥⇧⌘ (⌥⌘N, not ⌘⌥N). They are hidden where there is no
+ keyboard. Only menus whose rows have consequences keep a second line saying
+ what each row does (save a copy, archive, delete, page width). The overflow
+ button is ⋯, not ⋮, as in slides. A search, import or export dialog now
+ closes with Escape wherever the focus is, not only while it is inside the
+ card. The graph view puts focus in its card, not on the dimmed page behind it.
+
## [0.1.0] — 2026-08-03
First release.
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index 150ec76d..39b3d050 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -45,6 +45,7 @@ import { offlineEnabled } from '../../kernel/src/net.ts'
import { startSharing } from '../../kernel/src/sync/online.ts'
import * as shareModule from './share.ts'
import { ICONS, type IconName } from './icons'
+import { barMenu, anchoredMenu, row, caption, extra, keys, type Menu } from './menus.ts'
import { PropsPanel } from './props'
import {
internAsset, prepareImage, humanBytes, IMAGE_EMBED_BUDGET, MEDIA_EMBED_BUDGET, blobToDataUri,
@@ -58,6 +59,13 @@ const CTRL = navigator.platform.toLowerCase().includes('mac') ? 'metaKey' : 'ctr
const AUTOFORMAT = MD_SPECS
const SLASH_ITEMS = MENU_SPECS
+/**
+ * A block's markdown trigger, when its hint IS one ("#", "1.", "```") — the
+ * shortcut an Insert row prints right-aligned. A hint that is a description
+ * ("Collapsible section") is not a key, and a command list does not repeat it.
+ */
+const mdTrigger = (hint: string): string | undefined =>
+ /^[^\p{L}\s]{1,4}\s*$/u.test(hint) ? hint.trim() : undefined
/** What counts as a note when a folder is dropped on the app. */
const NOTE_EXT = /\.(md|markdown|mdown|mkd)$/i
/** …and what counts as another SPACE: a saved shell, or the bare document JSON
@@ -108,8 +116,16 @@ export class Editor {
private sidebar!: HTMLElement
private statusEl!: HTMLElement
private overlay: HTMLElement | null = null
- /** undo whatever the open popover attached to the window */
- private overlayReflow: (() => void) | null = null
+ /**
+ * Undo EVERYTHING the open overlay attached — its away-listener, its Escape
+ * handler, its resize reflow, a graph's animation frame. A list, not one
+ * slot: the single slot held the resize reflow, so the away-listener could
+ * never be put in it, and every popover closed by anything but a click away
+ * left its listener on the document to close the NEXT overlay on its first
+ * mousedown (measured: Escape a block menu, ⌘K, click inside the search
+ * card — the search closed).
+ */
+ private overlayOff: Array<() => void> = []
/** set while the editor is writing the DOM, so input handlers stand down */
private painting = false
/** reading view: the document without the machinery for changing it */
@@ -278,10 +294,16 @@ export class Editor {
this.statusEl = el('span', 'sp-status')
// insert — the block menu, reachable without knowing "/" exists
- const insert = this.dropdown('plus', t('Insert'), t('Insert a block — text, headings, lists, code, images'), (menu, close) => {
+ // A COMMAND LIST, so one line a row (D2): the name says what it is. The
+ // markdown trigger that makes the same block is its shortcut, shown where
+ // shortcuts go (D8); a hint that is a description rather than a key is not
+ // repeated here — it is still on the / menu, which is the place you learn.
+ const insert = barMenu({
+ icon: ICONS.plus, label: t('Insert'), tip: t('Insert a block — text, headings, lists, code, images'),
+ scroll: true,
+ fill: (m) => {
for (const item of SLASH_ITEMS) {
- menu.append(this.menuItem(item.icon, t(item.label), t(item.hint), () => {
- close()
+ row(m, { icon: ICONS[item.icon], label: t(item.label), kbd: mdTrigger(item.hint), run: () => {
const page = this.store.page
if (!page) return
const fresh = newBlock(item.type === 'pagelink' ? 'p' : item.type)
@@ -301,9 +323,9 @@ export class Editor {
// which is also the only route the / menu needs.
else if (item.type === 'media') void this.pickMedia(fresh.id)
else this.focusBlock(fresh.id)
- }))
+ } })
}
- })
+ } }).root
this.undoB = iconBtn('undo', t('Undo (⌘Z)'), () => { this.store.undo(); this.repaint() })
this.redoB = iconBtn('redo', t('Redo (⇧⌘Z)'), () => { this.store.redo(); this.repaint() })
@@ -325,10 +347,15 @@ export class Editor {
// right edge. Below the breakpoint the inline copies hide and ⋯ picks them
// up, one list feeding both, because a phone menu maintained by hand as a
// copy of the desktop row drifts the first time either one changes.
+ // `kbd` is a shortcut, printed right-aligned (D8). `hint` is a visible
+ // second line, and a row gets one only when it has a CONSEQUENCE worth
+ // reading before you press it (D2) — "Make this page an issue" adds four
+ // fields to it; "Graph" just opens a view, and its name says so.
type BarAction = {
icon: IconName
label: string
- hint: string
+ kbd?: string
+ hint?: string
run: () => void
keep?: (b: HTMLButtonElement) => void
}
@@ -337,7 +364,7 @@ export class Editor {
// room. Reading view is a MODE — you leave and re-enter it while working,
// and a mode you cannot see the state of is a mode you lose track of.
const barActions: BarAction[] = [
- { icon: 'eye', label: t('Reading view'), hint: t('The pages without the editing tools'),
+ { icon: 'eye', label: t('Reading view'),
run: () => this.toggleReading(),
keep: (b) => { this.readB = b } },
]
@@ -347,80 +374,74 @@ export class Editor {
// live in ⋯ at every width — findable, out of the road, and each with the
// keyboard shortcut printed beside it.
const menuActions: BarAction[] = [
- { icon: 'page', label: t('New page'), hint: '⌘⌥N', run: () => this.newPage() },
- { icon: 'book', label: t("Today's journal"), hint: '⌘⇧J', run: () => this.openJournal() },
- { icon: 'board', label: t('New issue'), hint: '⌘⇧I', run: () => this.newIssue() },
+ { icon: 'page', label: t('New page'), kbd: keys('alt', 'mod', 'N'), run: () => this.newPage() },
+ { icon: 'book', label: t("Today's journal"), kbd: keys('shift', 'mod', 'J'), run: () => this.openJournal() },
+ { icon: 'board', label: t('New issue'), kbd: keys('shift', 'mod', 'I'), run: () => this.newIssue() },
{ icon: 'tag', label: t('Make this page an issue'), hint: t('Adds status, priority, assignee, estimate'),
run: () => this.makeIssue() },
- { icon: 'markdown', label: t('Import Markdown…'), hint: t('A folder of notes, or another space'),
- run: () => this.openImport() },
- { icon: 'graph', label: t('Graph'), hint: t('Every page, and what links to what'),
- run: () => this.openGraph() },
- { icon: 'print', label: t('Print or save as PDF'), hint: '⌘P', run: () => this.openPrint() },
- { icon: 'info', label: t('About this space'), hint: t('Version, language, password, exports'),
- run: () => this.openAbout() },
+ { icon: 'markdown', label: t('Import Markdown…'), run: () => this.openImport() },
+ { icon: 'graph', label: t('Graph'), run: () => this.openGraph() },
+ { icon: 'print', label: t('Print or save as PDF'), kbd: keys('mod', 'P'), run: () => this.openPrint() },
+ { icon: 'info', label: t('About this space'), run: () => this.openAbout() },
// A help screen only reachable by pressing the key it documents is a
// help screen for people who did not need it.
- { icon: 'help', label: t('Keyboard shortcuts'), hint: '?', run: () => this.openHelp() },
+ { icon: 'help', label: t('Keyboard shortcuts'), kbd: '?', run: () => this.openHelp() },
]
const inlineSecondary = barActions.map((a) => {
- const b = iconBtn(a.icon, a.hint && a.hint.length < 12 ? `${a.label} (${a.hint})` : a.label, a.run)
+ const b = iconBtn(a.icon, a.kbd ? `${a.label} (${a.kbd})` : a.label, a.run)
b.classList.add('sp-sec')
a.keep?.(b)
return b
})
- const more = this.dropdown('more', '', t('More'), (menu, close) => {
- // On a PHONE the ⋯ menu also carries the history pair and the other ways
- // to save. Measured at 390px with a coarse pointer: eleven bar controls
- // wanted 467px of a 390px viewport, and Save — the one action that must
- // never be off-screen — ended at x = 426. Undo/redo (84px), the wordmark
- // (35px) and the save caret (48px) are what a phone gives up so that the
- // document title beside them is still wide enough to read. Nothing is
- // lost: they are all one tap away, here.
- // THE PROPERTIES PANEL, ONCE THE BAR HAS FOLDED. Its inline button is a
- // 40px control, and measured at 375px it took the document title from
- // 70px to 26px — a title nobody can read, to reach a panel that is one
- // more row in a menu that is already open. So below the fold it comes
- // here, the way undo/redo and the other ways to save already do.
- if (this.isFolded()) {
- menu.append(this.menuItem('panelRight', t('Properties'),
- t('This block’s settings, and the page’s'), () => {
- close(); this.toggleInsp()
- }))
- }
- if (this.isFolded()) {
- menu.append(this.menuItem('undo', t('Undo (⌘Z)'), '', () => {
- close(); this.store.undo(); this.repaint()
- }, { off: !this.store.canUndo }))
- menu.append(this.menuItem('redo', t('Redo (⇧⌘Z)'), '', () => {
- close(); this.store.redo(); this.repaint()
- }, { off: !this.store.canRedo }))
- }
- for (const a of menuActions) {
- menu.append(this.menuItem(a.icon, a.label, a.hint, () => { close(); a.run() }))
- }
- // …and only THEN what the bar itself has had to give up. Listing these
- // unconditionally is what made ⋯ a duplicate of the visible row.
- if (this.isFolded()) {
- for (const a of barActions) {
- menu.append(this.menuItem(a.icon, a.label, a.hint, () => { close(); a.run() }))
+ // The ways to write this document somewhere else — a CONSEQUENCE menu, so
+ // every row says what it leaves behind (D2). One list for the caret and
+ // for the folded ⋯, so the two can never offer different things.
+ const saveRows = (m: Menu) => {
+ row(m, { icon: ICONS.copy, label: t('Save a copy…'), hint: t('A second file — the original is left alone'),
+ run: () => { void this.saveAs('copy') } })
+ row(m, { icon: ICONS.markdown, label: t('Export as Markdown…'), hint: t('Every page, as one .md file'),
+ run: () => this.exportMarkdown() })
+ row(m, { icon: ICONS.page, label: t('Export page as a space…'), hint: t('One page and what is under it, as its own file'),
+ run: () => this.openExportSpace() })
+ }
+
+ const more = barMenu({
+ icon: ICONS.more, label: '', tip: t('More'), end: true, scroll: true, className: 'sp-more',
+ fill: (m) => {
+ // On a PHONE the ⋯ menu also carries the history pair and the other
+ // ways to save. Measured at 390px with a coarse pointer: eleven bar
+ // controls wanted 467px of a 390px viewport, and Save — the one action
+ // that must never be off-screen — ended at x = 426. Undo/redo, the
+ // wordmark and the save caret are what a phone gives up so that the
+ // document title beside them is still wide enough to read.
+ //
+ // The list SCROLLS (`scroll`). Folded, it was sixteen rows — 950px in
+ // an 844px phone viewport — and the last three, the ONLY ways to save
+ // a copy or export on a phone, sat below the screen with nothing to
+ // scroll them into view.
+ const folded = this.isFolded()
+ if (folded) {
+ // THE PROPERTIES PANEL, ONCE THE BAR HAS FOLDED: its 40px button took
+ // the document title from 70px to 26px at 375px.
+ row(m, { icon: ICONS.panelRight, label: t('Properties'), kbd: ']', run: () => this.toggleInsp() })
+ row(m, { icon: ICONS.undo, label: t('Undo'), kbd: keys('mod', 'Z'), off: !this.store.canUndo,
+ run: () => { this.store.undo(); this.repaint() } })
+ row(m, { icon: ICONS.redo, label: t('Redo'), kbd: keys('shift', 'mod', 'Z'), off: !this.store.canRedo,
+ run: () => { this.store.redo(); this.repaint() } })
+ m.separator()
}
- }
- if (this.isFolded()) {
- menu.append(this.menuItem('copy', t('Save a copy…'), t('A second file — the original is left alone'), () => {
- close(); void this.saveAs('copy')
- }))
- menu.append(this.menuItem('markdown', t('Export as Markdown…'), t('Every page, as one .md file'), () => {
- close(); this.exportMarkdown()
- }))
- menu.append(this.menuItem('page', t('Export page as a space…'), t('One page and what is under it, as its own file'), () => {
- close(); this.openExportSpace()
- }))
- }
- })
- more.classList.add('sp-more', 'sp-dd-end')
+ for (const a of menuActions) row(m, { icon: ICONS[a.icon], label: a.label, kbd: a.kbd, hint: a.hint, run: a.run })
+ // …and only THEN what the bar itself has had to give up. Listing these
+ // unconditionally is what made ⋯ a duplicate of the visible row.
+ if (folded) {
+ for (const a of barActions) row(m, { icon: ICONS[a.icon], label: a.label, kbd: a.kbd, run: a.run })
+ m.separator()
+ saveRows(m)
+ }
+ },
+ }).root
// The live control sits BEFORE ⋯ and is replaced in place once the session
// exists (connectSync). A placeholder rather than a conditional build, so
@@ -442,18 +463,10 @@ export class Editor {
? t('Unsaved changes — ⌘S rewrites this file')
: t('Unsaved changes — ⌘S downloads an updated copy')
saveB.append(this.dirtyDot)
- const saveMore = this.dropdown('chevronDown', '', t('Other ways to save'), (menu, close) => {
- menu.append(this.menuItem('copy', t('Save a copy…'), t('A second file — the original is left alone'), () => {
- close(); void this.saveAs('copy')
- }))
- menu.append(this.menuItem('markdown', t('Export as Markdown…'), t('Every page, as one .md file'), () => {
- close(); this.exportMarkdown()
- }))
- menu.append(this.menuItem('page', t('Export page as a space…'), t('One page and what is under it, as its own file'), () => {
- close(); this.openExportSpace()
- }))
- })
- saveMore.classList.add('sp-caret', 'sp-dd-end')
+ const saveMore = barMenu({
+ icon: ICONS.chevronDown, label: '', tip: t('Other ways to save'), end: true, className: 'sp-caret',
+ fill: saveRows,
+ }).root
// LEFT = the document (mark · title · save state · history), RIGHT = doing
// things with it. Same grouping as slides, so the two apps do not teach two
@@ -592,70 +605,6 @@ export class Editor {
if (this.redoB) this.redoB.disabled = !this.store.canRedo
}
- /** A topbar dropdown: button + menu, closed by choosing, Esc, or clicking away. */
- private dropdown(
- icon: IconName, label: string, tip: string,
- fill: (menu: HTMLElement, close: () => void) => void,
- ): HTMLElement {
- const wrap = el('div', 'sp-dd')
- const b = document.createElement('button')
- b.className = 'sp-btn'
- b.type = 'button'
- b.innerHTML = ICONS[icon]
- // The word is a SPAN, not a bare text node, so a narrow bar can drop it and
- // keep the icon — slides' rule, and the only way to collapse a labelled
- // control without also losing it.
- if (label) b.append(el('span', 'sp-btnlabel', label))
- b.title = tip
- b.setAttribute('aria-label', tip)
- b.setAttribute('aria-haspopup', 'menu')
- const menu = el('div', 'sp-ddmenu')
- menu.setAttribute('role', 'menu')
- const close = () => { wrap.classList.remove('sp-open'); b.setAttribute('aria-expanded', 'false') }
- b.addEventListener('click', (e) => {
- e.stopPropagation()
- const open = !wrap.classList.contains('sp-open')
- for (const other of document.querySelectorAll('.sp-dd.sp-open')) other.classList.remove('sp-open')
- wrap.classList.toggle('sp-open', open)
- b.setAttribute('aria-expanded', String(open))
- if (open) { menu.innerHTML = ''; fill(menu, close) }
- })
- document.addEventListener('click', close)
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close() })
- wrap.append(b, menu)
- return wrap
- }
-
- /**
- * One row in a dropdown menu.
- *
- * `state` carries BOTH meanings the menus need, because they arrived from
- * two directions and mean different things: `off` is a command that exists
- * but cannot run right now (folded undo/redo on a phone — disabled, not
- * hidden, so the menu does not change shape as you edit), and `selected` is
- * the choice a view is currently on (layout, group-by, sort). A row can be
- * neither; nothing yet is both. They were separate 5th parameters on two
- * branches, which is exactly the collision an options object avoids.
- */
- private menuItem(
- icon: IconName,
- label: string,
- hint: string,
- onClick: () => void,
- state: { off?: boolean; selected?: boolean } = {},
- ): HTMLElement {
- const b = document.createElement('button')
- b.className = 'sp-dditem' + (state.off ? ' sp-off' : '') + (state.selected ? ' sp-sel' : '')
- b.type = 'button'
- if (state.off) b.setAttribute('aria-disabled', 'true')
- if (state.selected) b.setAttribute('aria-current', 'true')
- b.setAttribute('role', 'menuitem')
- b.innerHTML = `<span class="sp-result-ico">${ICONS[icon]}</span>` +
- `<span class="sp-result-txt"><strong>${escapeHtml(label)}</strong>` +
- (hint ? `<span>${escapeHtml(hint)}</span>` : '') + `</span>`
- b.addEventListener('click', (e) => { e.stopPropagation(); onClick() })
- return b
- }
/** Open/close the page drawer on narrow screens, with a scrim to tap away. */
/**
@@ -874,7 +823,7 @@ export class Editor {
// Re-fitting starts by UNFOLDING, which would slam shut a menu somebody is
// reading — and the ⋯ menu's contents depend on the tier, so rebuilding it
// mid-read would change it under them. The next resize runs this again.
- if (this.overlay) return
+ if (this.overlay || bar.querySelector('.bkm-open')) return
// scrollWidth counts content sticking out of the padding box even with
// overflow visible, so this IS the clipped-controls condition. 1px of
// slack absorbs subpixel rounding at fractional zoom.
@@ -1364,7 +1313,7 @@ export class Editor {
* 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 }> {
+ private blockActions(id: string): Array<{ icon: IconName; label: string; kbd?: string; run: () => void; off?: boolean }> {
const s = this.store
const page = s.page
const blocks = page?.blocks ?? []
@@ -1381,21 +1330,21 @@ export class Editor {
// the touch sheet too, so without an entry here a card could be made on a
// phone and never changed.
...(blocks[at]?.type === 'link'
- ? [{ icon: 'globe' as const, label: t('Edit this link card'), hint: '',
+ ? [{ icon: 'globe' as const, label: t('Edit this link card'),
run: () => this.openLinkCard(id) }]
: []),
- { icon: 'text', label: t('Turn into…'), hint: t('Change this block’s type'),
+ { icon: 'text', label: t('Turn into…'),
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,
+ { icon: 'plus', label: t('Add below'), kbd: '↵', run: () => this.insertAfter(id) },
+ { icon: 'up', label: t('Move up'), 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,
+ { icon: 'down', label: t('Move down'), 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: 'copy', label: t('Duplicate'), run: () => this.duplicateBlock(id) },
// The gutter holds two controls and a phone fits one, so commenting
// lives in the menu BOTH of them open — which is also the touch sheet.
- { icon: 'comment', label: t('Comment'), hint: '', run: () => this.comments.openNew(id) },
- { icon: 'trash', label: t('Delete'), hint: '⌫', run: () => this.deleteBlock(id) },
+ { icon: 'comment', label: t('Comment'), run: () => this.comments.openNew(id) },
+ { icon: 'trash', label: t('Delete'), kbd: '⌫', run: () => this.deleteBlock(id) },
]
}
@@ -1522,27 +1471,26 @@ export class Editor {
private fieldPicker(
f: FieldSpec, cur: unknown, anchor: HTMLElement, write: (v: unknown) => void,
): void {
- this.closeOverlay()
-
- const pop = el('div', this.isDrawer() ? 'sp-pop sp-sheet' : 'sp-pop')
- pop.setAttribute('role', 'menu')
- this.trapAndClose(pop)
-
if (f.vt === 'select' && f.options?.length) {
const now = String(cur ?? '')
- for (const o of f.options) {
- const item = document.createElement('button')
- item.className = 'sp-dditem' + (o.id === now ? ' sp-sel' : '')
- item.type = 'button'
- const dot = el('span', 'sp-prop-dot')
- if (o.color) dot.style.background = o.color
- const name = document.createElement('span')
- name.textContent = o.label
- item.append(dot, name)
- item.addEventListener('click', () => { this.closeOverlay(); write(o.id) })
- pop.append(item)
- }
- } else {
+ const options = f.options
+ this.menuAt(anchor, f.label, (m) => {
+ for (const o of options) {
+ const b = row(m, { label: o.label, selected: o.id === now, run: () => write(o.id) })
+ // the option's colour is the author's data: a style PROPERTY, never
+ // markup handed to the row's icon slot
+ const ico = el('span', 'bkm-ico')
+ const dot = el('span', 'sp-prop-dot')
+ if (o.color) dot.style.background = o.color
+ ico.append(dot)
+ b.prepend(ico)
+ }
+ })
+ return
+ }
+ this.closeOverlay()
+ const pop = el('div', 'sp-pop')
+ {
// free text, a number or a date: one field, committed on Enter
const input = document.createElement('input')
input.className = 'sp-find'
@@ -1557,18 +1505,11 @@ export class Editor {
write(f.vt === 'number' ? (raw === '' ? '' : Number(raw)) : raw)
}
})
+ input.setAttribute('aria-label', f.label)
pop.append(input)
afterPaint(() => input.focus())
}
-
- this.overlay = pop
- document.body.append(pop)
- if (this.isDrawer()) pop.classList.add('sp-sheet-in')
- else this.placed(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)
+ this.float(pop, anchor, { role: 'dialog', label: f.label, onEscape: () => anchor.focus?.() })
}
/**
@@ -1777,18 +1718,16 @@ export class Editor {
*/
private popover(anchor: HTMLElement, build: (pop: HTMLElement) => void): void {
this.closeOverlay()
- const pop = el('div', this.isDrawer() ? 'sp-pop sp-sheet' : 'sp-pop')
- pop.setAttribute('role', 'menu')
- this.trapAndClose(pop)
+ const pop = el('div', 'sp-pop')
+ // A panel of CONTROLS — the share panel, a comment thread — not a list of
+ // commands. It announced itself as role=menu and held a textarea; a screen
+ // reader then promised menu items and found a form. Menus go through
+ // menuAt() and the kernel primitive.
+ pop.tabIndex = -1
build(pop)
- this.overlay = pop
- document.body.append(pop)
- if (this.isDrawer()) pop.classList.add('sp-sheet-in')
- else this.placed(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)
+ this.float(pop, anchor, { role: 'dialog', onEscape: () => anchor.focus?.() })
+ // the keyboard lands inside, unless the popover already put it somewhere
+ afterPaint(() => { if (!pop.contains(document.activeElement)) pop.focus() })
}
/**
@@ -1829,28 +1768,24 @@ export class Editor {
const s = this.store
const b = s.block(blockId)
if (!b) return
- this.popover(anchor, (pop) => {
- const set = (src: { has?: string; under?: string } | undefined) => {
- this.editView(blockId, 'source', src)
- this.closeOverlay()
- }
- pop.append(el('div', 'sp-pop-title', t('Which pages')))
- pop.append(this.menuItem('board', t('Issues'), t('Every page with a status'), () => set(undefined)))
+ const set = (src: { has?: string; under?: string } | undefined) => this.editView(blockId, 'source', src)
+ this.menuAt(anchor, t('Which pages'), (m) => {
+ caption(m, t('Which pages'))
+ row(m, { icon: ICONS.board, label: t('Issues'), hint: t('Every page with a status'), run: () => set(undefined) })
// A property somebody invented is the interesting case, so it comes
// first among the fields and lists every one the vocabulary has.
for (const f of fieldsOf(s.doc)) {
- pop.append(this.menuItem('tag', f.label, t('Pages that have this property'),
- () => set({ has: f.key })))
+ row(m, { icon: ICONS.tag, label: f.label, hint: t('Pages that have this property'), run: () => set({ has: f.key }) })
}
// Nesting is how a space is already organised, so the current page and
// its ancestors are the ones worth offering rather than every page.
const here = s.page
if (here) {
- pop.append(el('div', 'sp-pop-title', t('Nested under')))
- pop.append(this.menuItem('page', here.title || t('Untitled'),
- t('Pages nested under this one'), () => set({ under: here.id })))
+ caption(m, t('Nested under'))
+ row(m, { icon: ICONS.page, label: here.title || t('Untitled'), hint: t('Pages nested under this one'),
+ run: () => set({ under: here.id }) })
}
})
}
@@ -1884,16 +1819,14 @@ export class Editor {
if (!b || s.readOnly || this.reading) return
const now = String((b as { groupBy?: unknown }).groupBy ?? 'status')
const groupable = fieldsOf(s.doc).filter((f) => f.options?.length)
- this.popover(anchor, (pop) => {
+ this.menuAt(anchor, t('Group'), (m) => {
for (const f of groupable) {
- pop.append(this.menuItem('board', f.label, '', () => {
- this.closeOverlay()
+ row(m, { icon: ICONS.board, label: f.label, selected: f.key === now,
// `status` is the default the renderer assumes, so choosing it clears
// the key instead of writing what absence already means
- this.editView(blockId, 'groupBy', f.key === 'status' ? undefined : f.key)
- }, { selected: f.key === now }))
+ run: () => this.editView(blockId, 'groupBy', f.key === 'status' ? undefined : f.key) })
}
- if (!groupable.length) pop.append(el('div', 'sp-fgroup', t('No field here has options to group by')))
+ if (!groupable.length) extra(m, el('div', 'sp-fgroup', t('No field here has options to group by')))
})
}
@@ -1911,12 +1844,10 @@ export class Editor {
if (!b || s.readOnly || this.reading) return
const cur = (Array.isArray((b as { sort?: unknown }).sort)
? ((b as { sort?: ViewSort[] }).sort ?? [])[0] : undefined) as ViewSort | undefined
- this.popover(anchor, (pop) => {
- pop.append(this.menuItem('grip', t('Manual order'), '', () => {
- this.closeOverlay()
- this.editView(blockId, 'sort', undefined)
- }, { selected: !cur }))
- pop.append(el('div', 'sp-fgroup', t('Sort')))
+ this.menuAt(anchor, t('Sort'), (m) => {
+ row(m, { icon: ICONS.grip, label: t('Manual order'), selected: !cur,
+ run: () => this.editView(blockId, 'sort', undefined) })
+ caption(m, t('Sort'))
for (const f of fieldsOf(s.doc)) {
const mine = cur?.key === f.key
// clicking the field you are already sorted by REVERSES it — the second
@@ -1925,10 +1856,8 @@ export class Editor {
// finds
const dir: 'asc' | 'desc' = mine && cur?.dir !== 'desc' ? 'desc' : 'asc'
const hint = mine ? (cur?.dir === 'desc' ? t('Ascending') : t('Descending')) : ''
- pop.append(this.menuItem('arrowDown', f.label, hint, () => {
- this.closeOverlay()
- this.editView(blockId, 'sort', [dir === 'asc' ? { key: f.key } : { key: f.key, dir }])
- }, { selected: mine }))
+ row(m, { icon: ICONS.arrowDown, label: f.label, hint: hint || undefined, selected: mine,
+ run: () => this.editView(blockId, 'sort', [dir === 'asc' ? { key: f.key } : { key: f.key, dir }]) })
}
})
}
@@ -1960,38 +1889,35 @@ export class Editor {
const b = s.block(blockId)
if (!b || s.readOnly || this.reading) return
const cur = ((b as { filter?: ViewFilter }).filter ?? {}) as ViewFilter
- this.popover(anchor, (pop) => {
- for (const f of fieldsOf(s.doc)) {
- if (!f.options?.length) continue
- pop.append(el('div', 'sp-fgroup', f.label))
- for (const o of f.options) {
- const on = (cur.is?.[f.key] ?? []).includes(o.id)
- const item = document.createElement('button')
- item.className = 'sp-dditem' + (on ? ' sp-sel' : '')
- item.type = 'button'
- item.setAttribute('aria-pressed', String(on))
- const dot = el('span', 'sp-prop-dot')
- if (o.color) dot.style.background = o.color
- const name = document.createElement('span')
- name.textContent = o.label
- item.append(dot, name)
- // the popover STAYS OPEN: picking three labels is one thought, and
- // reopening a menu between each is the thing that makes filters
- // unusable. Each toggle is still its own undo step.
- item.addEventListener('click', () => {
- const next = !item.classList.contains('sp-sel')
- item.classList.toggle('sp-sel', next)
- item.setAttribute('aria-pressed', String(next))
- this.toggleViewValue(blockId, f.key, o.id)
- })
- pop.append(item)
+ this.menuAt(anchor, t('Filter'), (m) => {
+ for (const f of fieldsOf(s.doc)) {
+ if (!f.options?.length) continue
+ caption(m, f.label)
+ for (const o of f.options) {
+ const on = (cur.is?.[f.key] ?? []).includes(o.id)
+ // the menu STAYS OPEN (keepOpen): picking three labels is one
+ // thought, and reopening a menu between each is the thing that makes
+ // filters unusable. Each toggle is still its own undo step.
+ const item: HTMLButtonElement = row(m, { label: o.label, keepOpen: true, run: () => {
+ const next = item.getAttribute('aria-checked') !== 'true'
+ item.setAttribute('aria-checked', String(next))
+ item.classList.toggle('bkm-selected', next)
+ this.toggleViewValue(blockId, f.key, o.id)
+ } })
+ item.setAttribute('role', 'menuitemcheckbox')
+ item.setAttribute('aria-checked', String(on))
+ item.classList.toggle('bkm-selected', on)
+ const ico = el('span', 'bkm-ico')
+ const dot = el('span', 'sp-prop-dot')
+ if (o.color) dot.style.background = o.color
+ ico.append(dot)
+ item.prepend(ico)
+ }
}
- }
- pop.append(this.menuItem('trash', t('Clear filter'), '', () => {
- this.closeOverlay()
+ m.separator()
// unknown keys survive: this clears what this build put there
- this.editViewFilter(blockId, (f) => { delete f.is; delete f.open })
- }))
+ row(m, { icon: ICONS.trash, label: t('Clear filter'),
+ run: () => this.editViewFilter(blockId, (f) => { delete f.is; delete f.open }) })
})
}
@@ -2039,24 +1965,11 @@ export class Editor {
/** 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)
+ this.menuAt(anchor, t('Block options'), (m) => {
+ 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 })
+ }
+ })
}
/** Move `id` to sit BEFORE `target` — the inverse of moveBlock's "after". */
@@ -2923,45 +2836,25 @@ export class Editor {
private openLangPicker(blockId: string, anchor: HTMLElement): void {
const s = this.store
if (s.readOnly || this.reading) return
- this.closeOverlay()
- const pop = el('div', 'sp-pop sp-langpop')
- pop.setAttribute('role', 'menu')
- this.trapAndClose(pop, () => this.focusBlock(blockId))
// An UNKNOWN tag matches NO row. `rust` renders plain, but it is not the
// same thing as plain: ticking "Plain text" for it would say the tag is
// already gone, and the next click would quietly delete it.
const raw = String(s.block(blockId)?.lang ?? '').trim()
const cur = normLang(raw)
const unknown = !!raw && !cur
- for (const { id, label } of CODE_LANGS) {
- const b = document.createElement('button')
- b.className = 'sp-dditem' + (!unknown && id === cur ? ' sp-sel' : '')
- b.type = 'button'
- b.setAttribute('role', 'menuitem')
- b.append(Object.assign(document.createElement('strong'), {
- textContent: label || t('Plain text'),
- }))
- b.addEventListener('click', () => {
- this.closeOverlay()
- s.commit(() => {
- const blk = s.block(blockId)
- if (!blk) return
- if (id) blk.lang = id
- else delete blk.lang
- })
- this.paintPage()
- })
- pop.append(b)
- }
- document.body.append(pop)
- this.overlay = pop
- place(pop, anchor)
- setTimeout(() => {
- const away = (ev: MouseEvent) => {
- if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
+ this.menuAt(anchor, t('Language'), (m) => {
+ for (const { id, label } of CODE_LANGS) {
+ row(m, { label: label || t('Plain text'), selected: !unknown && id === cur, run: () => {
+ s.commit(() => {
+ const blk = s.block(blockId)
+ if (!blk) return
+ if (id) blk.lang = id
+ else delete blk.lang
+ })
+ this.paintPage()
+ } })
}
- document.addEventListener('mousedown', away)
- }, 0)
+ })
}
private collab: import('./collabui.ts').CollabUi | null = null
@@ -3073,6 +2966,15 @@ export class Editor {
const s = this.store
const mod = (e as any)[CTRL] as boolean
+ // A MODAL OWNS THE KEYBOARD — all of it, shortcuts included. The shortcut
+ // branch below used to run BEFORE the overlay test, and About, the key
+ // sheet and every dialog built in about.ts never set `this.overlay` at
+ // all: measured with About open, `[` collapsed the page list behind the
+ // scrim (and saved that to the reader's preferences), `?` stacked the
+ // shortcut sheet on top of About, and ⌘Z would have undone the page
+ // underneath. The dialog's own handler still runs; this one stands down.
+ if (document.querySelector('[aria-modal="true"]')) return
+
// ⌘K IS TWO COMMANDS, decided by whether anything is selected — the same
// split Notion and Confluence make, and the reason it is not a second
// shortcut: on a selection it is "link these words", and with nothing
@@ -3117,7 +3019,7 @@ export class Editor {
this.paintPage(); this.paintTree()
return
}
- if (e.key === 'Escape' && this.reading && !this.overlay) { e.preventDefault(); this.toggleReading(false); return }
+ if (e.key === 'Escape' && this.reading && !this.overlay && !document.querySelector('.bkm-open')) { e.preventDefault(); this.toggleReading(false); return }
if (this.overlay) return // the overlay owns the keyboard while it is open
// A TABLE CELL IS NOT A BLOCK HOST, so the block keymap below does not
@@ -3316,6 +3218,7 @@ export class Editor {
const back = el('div', 'sp-overlay')
const card = el('div', 'sp-card')
card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
card.setAttribute('aria-label', title)
const close = () => this.closeOverlay()
build(card, close)
@@ -3323,8 +3226,15 @@ export class Editor {
back.addEventListener('mousedown', (e) => { if (e.target === back) close() })
document.body.append(back)
this.overlay = back
- const onEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); close() } }
- back.addEventListener('keydown', onEsc)
+ // On the DOCUMENT, capture-phase: hung off the backdrop, Escape worked only
+ // while focus was inside the card, and one click on the card's blank space
+ // left a dialog you could not dismiss from the keyboard.
+ const onEsc = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape' || this.overlay !== back) return
+ e.preventDefault(); e.stopPropagation(); close()
+ }
+ document.addEventListener('keydown', onEsc, true)
+ this.overlayOff.push(() => document.removeEventListener('keydown', onEsc, true))
card.querySelector<HTMLElement>('input,button,[tabindex]')?.focus()
}
@@ -3347,7 +3257,7 @@ export class Editor {
*
* The DRAWING lives in graph.ts; what is here is only what an overlay is in
* this editor — one at a time, and it owns the keyboard while it is open
- * (`this.overlay`). Teardown rides on `overlayReflow`, which is the hook
+ * (`this.overlay`). Teardown rides on `overlayOff`, which is the list
* `closeOverlay` already calls before it removes the node: the graph has
* observers and an animation frame to give back, and there is no second
* teardown path to forget about.
@@ -3364,7 +3274,6 @@ export class Editor {
})
const close = () => {
this.closeOverlay()
- document.removeEventListener('keydown', onKey, true)
returnFocus?.focus?.()
}
const onKey = (e: KeyboardEvent) => {
@@ -3372,10 +3281,14 @@ export class Editor {
}
document.addEventListener('keydown', onKey, true)
this.overlay = view.el
- this.overlayReflow = () => view.destroy()
+ // the key handler leaves with the graph however it closes — closed by
+ // another overlay opening, it used to stay on the document
+ this.overlayOff.push(() => view.destroy(), () => document.removeEventListener('keydown', onKey, true))
document.body.append(view.el)
- view.el.tabIndex = -1
- view.el.focus()
+ // focus goes INTO the card, not onto the scrim behind it
+ const card = view.el.querySelector<HTMLElement>('[role=dialog]') ?? view.el
+ card.tabIndex = -1
+ card.focus()
}
openHelp(): void {
@@ -3462,20 +3375,78 @@ export class Editor {
}
/**
- * Place a popover AND keep it placed.
+ * A MENU anchored to something that is not its trigger — a grip, a row's ⋯,
+ * a board chip. The kernel's menu (menus.ts anchoredMenu), so it has the
+ * primitive's Escape, arrow keys, outside-press and one shared listener pair;
+ * a bottom sheet below the drawer breakpoint, where a thumb reaches it.
*
- * place() sizes a popover to the room the window has right now, so its answer
- * stops being true the moment the window changes. Stale in the small-to-large
- * direction merely misplaces a box; stale the other way CLIPS it, which is
- * the bug this change exists to remove — the 44vh it replaces at least
- * tracked the viewport. Both popover call sites go through here so neither
- * can forget.
+ * It is the editor's ONE overlay while it is open, exactly as a popover was:
+ * `this.overlay` gates the block keymap and the topbar refit.
*/
- private placed(pop: HTMLElement, anchor: HTMLElement): void {
- place(pop, anchor)
- const reflow = () => place(pop, anchor)
- addEventListener('resize', reflow)
- this.overlayReflow = () => removeEventListener('resize', reflow)
+ private menuAt(
+ anchor: HTMLElement | DOMRect, label: string, fill: (m: Menu) => void,
+ o: { onClose?: () => void; role?: 'menu' | 'dialog' } = {},
+ ): Menu {
+ this.closeOverlay()
+ const m: Menu = anchoredMenu(anchor, fill, {
+ label, sheet: this.isDrawer(), role: o.role,
+ onClose: () => {
+ if (this.overlay === m.root) { this.overlay = null; this.overlayOff = [] }
+ o.onClose?.()
+ },
+ })
+ this.overlay = m.root
+ this.overlayOff.push(() => m.close())
+ return m
+ }
+
+ /**
+ * A popover that is NOT a menu — a form, a thread, a picker grid, the /
+ * filter. Anchored (or a sheet on a phone), dismissed by Escape or a press
+ * outside, and EVERY listener it adds is registered for closeOverlay to take
+ * back, however it closes. Before this, nine popovers each hand-rolled a
+ * `mousedown` away-listener that only removed itself when it fired.
+ */
+ private float(
+ pop: HTMLElement, anchor: HTMLElement | DOMRect | null,
+ o: { sheet?: boolean; role?: string; label?: string; onEscape?: () => void } = {},
+ ): void {
+ const sheet = o.sheet ?? this.isDrawer()
+ pop.classList.toggle('sp-sheet', sheet)
+ if (o.role) pop.setAttribute('role', o.role)
+ if (o.label) pop.setAttribute('aria-label', o.label)
+ document.body.append(pop)
+ this.overlay = pop
+ if (sheet) {
+ pop.classList.add('sp-sheet-in')
+ } else if (anchor) {
+ // place() answers for the window as it is NOW; keep it true on resize,
+ // or a shrinking window clips the popover it sized for a bigger one
+ place(pop, anchor)
+ const reflow = () => place(pop, anchor)
+ addEventListener('resize', reflow)
+ this.overlayOff.push(() => removeEventListener('resize', reflow))
+ }
+ // Capture-phase so it wins over the page's own Escape; stopped here so the
+ // editor's keymap does not also act on it.
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape' || this.overlay !== pop) return
+ e.preventDefault()
+ e.stopPropagation()
+ this.closeOverlay()
+ o.onEscape?.()
+ }
+ // armed a turn late, so the press that OPENED the popover does not close it
+ const away = (ev: Event) => {
+ if (this.overlay === pop && !pop.contains(ev.target as Node)) this.closeOverlay()
+ }
+ const t = setTimeout(() => document.addEventListener('pointerdown', away, true), 0)
+ document.addEventListener('keydown', onKey, true)
+ this.overlayOff.push(() => {
+ clearTimeout(t)
+ document.removeEventListener('pointerdown', away, true)
+ document.removeEventListener('keydown', onKey, true)
+ })
}
/**
@@ -3501,7 +3472,7 @@ export class Editor {
const page = s.index.page.get(pageId)
if (!page) return
- this.popover(anchor, (pop) => {
+ this.menuAt(anchor, t('Add a property'), (m) => {
const has = new Set(page.blocks
.filter((b) => b.type === 'prop')
.map((b) => String((b as { key?: unknown }).key ?? '')))
@@ -3513,20 +3484,18 @@ export class Editor {
if (!p) return
p.blocks.splice(headerLength(p), 0, propBlock(f, f.def ?? '', newBlock('prop').id))
})
- this.closeOverlay()
+ m.close()
this.repaint()
this.status(t('Added {name}', { name: f.label }))
}
const spare = fieldsOf(s.doc).filter((f) => !has.has(f.key))
if (spare.length) {
- pop.append(el('div', 'sp-pop-title', t('Add a property')))
- for (const f of spare) {
- pop.append(this.menuItem('tag', f.label, fieldTypeLabel(f.vt), () => put(f)))
- }
+ caption(m, t('Add a property'))
+ for (const f of spare) row(m, { icon: ICONS.tag, label: f.label, hint: fieldTypeLabel(f.vt), run: () => put(f) })
}
- pop.append(el('div', 'sp-pop-title', t('New property')))
+ caption(m, t('New property'))
const form = el('div', 'sp-newprop')
const name = document.createElement('input')
name.type = 'text'
@@ -3551,44 +3520,19 @@ export class Editor {
add.addEventListener('click', submit)
name.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); submit() } })
form.append(name, type, add)
- pop.append(form)
+ extra(m, form)
afterPaint(() => name.focus())
})
}
private closeOverlay(): void {
- this.overlayReflow?.()
- this.overlayReflow = null
+ const off = this.overlayOff
+ this.overlayOff = []
+ for (const fn of off) fn()
this.overlay?.remove()
this.overlay = null
}
- /**
- * Make a popover dismissible and reachable from the keyboard.
- *
- * The tone and language pickers set `this.overlay` and installed only a
- * mousedown-away listener — and `onKey` early-returns while an overlay is
- * open, so Escape did nothing and Tab walked off into the page behind. That
- * is a keyboard trap: a menu you can open without a mouse and cannot close
- * without one. The slash menu got this right by focusing its own input; these
- * two have no input, so the popover itself takes focus.
- */
- private trapAndClose(pop: HTMLElement, returnTo?: () => void): void {
- pop.tabIndex = -1
- pop.addEventListener('keydown', (e) => {
- if (e.key !== 'Escape') return
- e.preventDefault()
- e.stopPropagation()
- this.closeOverlay()
- returnTo?.()
- })
- // focus AFTER the browser has laid the popover out, or the focus is lost to
- // the element the click came from
- afterPaint(() => pop.focus())
- }
-
- /** Anchor a popover to a rect, kept inside the viewport. */
-
/** ⌘K — search every page, including collapsed toggles and archived pages. */
openSearch(): void {
const s = this.store
@@ -3695,18 +3639,12 @@ export class Editor {
})
paint()
- document.body.append(pop)
- this.overlay = pop
- place(pop, anchor ?? caretRect())
+ // a COMBOBOX, not a menu: the filter keeps the focus and the arrows move
+ // the highlight, so it stays a popover. Anchored to the caret even on a
+ // phone — a sheet at the bottom edge would sit under the soft keyboard.
+ find.setAttribute('aria-label', t('Filter blocks…'))
+ this.float(pop, anchor ?? caretRect(), { sheet: false, onEscape: () => this.focusBlock(blockId) })
find.focus()
-
- // clicking anywhere else dismisses, but not the first click that opened it
- setTimeout(() => {
- const away = (ev: MouseEvent) => {
- if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
- }
- document.addEventListener('mousedown', away)
- }, 0)
}
private insertPageCard(blockId: string): void {
@@ -3925,15 +3863,10 @@ export class Editor {
})
pop.append(b)
}
- document.body.append(pop)
- this.overlay = pop
- place(pop, anchor)
- setTimeout(() => {
- const away = (ev: MouseEvent) => {
- if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
- }
- document.addEventListener('mousedown', away)
- }, 0)
+ // a GRID of choices, not a list — a popover, which Escape closes and which
+ // the keyboard lands in
+ this.float(pop, anchor, { sheet: false, role: 'dialog', label: t('Icon'), onEscape: () => anchor.focus?.() })
+ afterPaint(() => pop.querySelector<HTMLElement>('button')?.focus())
}
/**
@@ -3948,63 +3881,45 @@ export class Editor {
const s = this.store
const b = s.block(blockId)
if (!b || s.readOnly || this.reading) return
- this.closeOverlay()
- const pop = el('div', 'sp-pop sp-tonepop')
- pop.setAttribute('role', 'menu')
- this.trapAndClose(pop, () => this.focusBlock(blockId))
-
const current = String(b.tone ?? 'note')
- for (const tone of CALLOUT_TONES) {
- const btn = document.createElement('button')
- btn.className = 'sp-dditem sp-toneopt' + (tone.tone === current ? ' sp-sel' : '')
- btn.type = 'button'
- btn.setAttribute('role', 'menuitemradio')
- btn.setAttribute('aria-checked', String(tone.tone === current))
- btn.innerHTML =
- `<span class="sp-result-ico sp-tone-${tone.tone}">${ICONS[tone.icon]}</span>` +
- `<span class="sp-result-txt"><strong>${escapeHtml(toneLabel(tone.tone))}</strong></span>`
- btn.addEventListener('click', () => {
- this.closeOverlay()
- s.commit(() => { const bb = s.block(blockId); if (bb) bb.tone = tone.tone })
+ this.menuAt(anchor, t('Callout'), (m) => {
+ for (const tone of CALLOUT_TONES) {
+ const btn = row(m, { icon: ICONS[tone.icon], label: toneLabel(tone.tone), selected: tone.tone === current,
+ run: () => {
+ s.commit(() => { const bb = s.block(blockId); if (bb) bb.tone = tone.tone })
+ this.paintPage()
+ } })
+ btn.setAttribute('role', 'menuitemradio')
+ btn.setAttribute('aria-checked', String(tone.tone === current))
+ btn.querySelector('.bkm-ico')?.classList.add('sp-result-ico', `sp-tone-${tone.tone}`)
+ }
+
+ const iconRow = el('label', 'sp-tonerow')
+ const icon = document.createElement('input')
+ icon.className = 'sp-find sp-toneicon'
+ icon.value = typeof b.icon === 'string' ? b.icon : ''
+ icon.maxLength = 16
+ icon.placeholder = t('Leave it empty to use the tone mark')
+ icon.setAttribute('aria-label', t('Callout icon'))
+ // `change`, not `input`: one commit when the field is done with, rather
+ // than one undo entry per keystroke of a pasted emoji
+ icon.addEventListener('change', () => {
+ const v = icon.value.trim()
+ s.commit(() => {
+ const bb = s.block(blockId)
+ if (!bb) return
+ if (v) bb.icon = v
+ else delete bb.icon
+ })
this.paintPage()
})
- pop.append(btn)
- }
-
- const row = el('label', 'sp-tonerow')
- const icon = document.createElement('input')
- icon.className = 'sp-find sp-toneicon'
- icon.value = typeof b.icon === 'string' ? b.icon : ''
- icon.maxLength = 16
- icon.placeholder = t('Leave it empty to use the tone mark')
- icon.setAttribute('aria-label', t('Callout icon'))
- // `change`, not `input`: one commit when the field is done with, rather
- // than one undo entry per keystroke of a pasted emoji
- icon.addEventListener('change', () => {
- const v = icon.value.trim()
- s.commit(() => {
- const bb = s.block(blockId)
- if (!bb) return
- if (v) bb.icon = v
- else delete bb.icon
+ icon.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); icon.blur(); m.close() }
})
- this.paintPage()
- })
- icon.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.preventDefault(); icon.blur(); this.closeOverlay() }
+ iconRow.append(el('span', 'sp-tonelabel', t('Icon')), icon)
+ m.separator()
+ extra(m, iconRow)
})
- row.append(el('span', 'sp-tonelabel', t('Icon')), icon)
- pop.append(row)
-
- document.body.append(pop)
- this.overlay = pop
- place(pop, anchor)
- setTimeout(() => {
- const away = (ev: MouseEvent) => {
- if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
- }
- document.addEventListener('mousedown', away)
- }, 0)
}
/** Rename, archive, or delete one page. */
@@ -4012,108 +3927,93 @@ export class Editor {
const s = this.store
const page = s.index.page.get(pageId)
if (!page) return
- this.closeOverlay()
- const pop = el('div', 'sp-pop')
- pop.setAttribute('role', 'menu')
-
- pop.append(this.menuItem('edit', t('Rename'), '', () => {
- this.closeOverlay()
- s.goToPage(pageId)
- afterPaint(() => {
- const h = this.main.querySelector<HTMLElement>('[data-page-title]')
- if (h) { h.focus(); selectAll(h) }
- })
- }))
-
- pop.append(this.menuItem('plus', t('New page inside'), '', () => {
- this.closeOverlay()
- this.newPage(pageId)
- }))
-
- // A thread about the PAGE — the second and last anchor. It is offered
- // where the page's own actions are, and only for the page in view,
- // because a thread is written into the page you are looking at.
- if (pageId === s.pageId && !s.readOnly) {
- pop.append(this.menuItem('comment', t('Comment on this page'), '', () => {
- this.closeOverlay()
- this.comments.openNew()
- }))
- }
-
- pop.append(this.menuItem(page.archived ? 'unarchive' : 'archive',
- page.archived ? t('Restore to the page list') : t('Archive'),
- page.archived ? '' : t('Out of the sidebar, still searchable and linkable'), () => {
- this.closeOverlay()
- s.commit(() => {
- const p = s.index.page.get(pageId)
- if (!p) return
- if (p.archived) delete p.archived
- else p.archived = true
+ // A CONSEQUENCE menu (D2): the rows that change or remove something say
+ // what, on the row. The ones that only go somewhere are a name.
+ this.menuAt(anchor, t('Page options'), (m) => {
+ row(m, { icon: ICONS.edit, label: t('Rename'), run: () => {
+ s.goToPage(pageId)
+ afterPaint(() => {
+ const h = this.main.querySelector<HTMLElement>('[data-page-title]')
+ if (h) { h.focus(); selectAll(h) }
})
- }))
+ } })
- // HOW WIDE THIS PAGE IS. The renderer already varied it — a page carrying a
- // board jumped to 1500px — but it decided for you silently. Measured at a
- // 1600px viewport: the default column is 720px with 631px of the page left
- // empty beside it, and nothing on the starter pages even reaches the limit
- // (0 of 15 blocks wrap). The line length was never the problem; having no
- // say was.
- pop.append(el('div', 'sp-menu-label', t('Width')))
- const current: 'normal' | 'wide' | 'full' =
- page.width === 'wide' ? 'wide' : page.width === 'full' ? 'full' : 'normal'
- const setWidth = (v: 'normal' | 'wide' | 'full') => {
- this.closeOverlay()
- s.commit(() => {
- const pg = s.index.page.get(pageId)
- if (!pg) return
- // THE DEFAULT IS AN ABSENT KEY, never a stored 'normal'. A page somebody
- // set to wide and back is then byte-identical to one never touched, and
- // a file written before this control existed stays that way.
- if (v === 'normal') delete pg.width
- else pg.width = v
- }, { scope: 'doc' })
- this.paintPage()
- }
- pop.append(this.menuItem('widthNarrow', t('Column'), t('Comfortable for reading'),
- () => setWidth('normal'), { selected: current === 'normal' }))
- pop.append(this.menuItem('widthWide', t('Wide'), t('Room for a board or a table'),
- () => setWidth('wide'), { selected: current === 'wide' }))
- pop.append(this.menuItem('widthFull', t('Full width'), t('Fills the window'),
- () => setWidth('full'), { selected: current === 'full' }))
-
- // AND THE SAME CHOICE, FOR EVERY PAGE. Setting a width page by page answers
- // "this page needs the room"; it does not answer "I have a wide screen",
- // which is one fact about one person and was costing a visit to every page
- // in the space. This one is a VIEWER preference — localStorage, never the
- // file — so it follows the reader rather than the document, and somebody
- // opening the same space on a laptop is unaffected.
- const pref = readerWidth()
- const applyAll = (v: 'wide' | 'full' | undefined) => {
- this.closeOverlay()
- setReaderWidth(v)
- this.paintPage()
- this.status(v ? t('Every page opens wide on this screen from now on')
- : t('Pages open at their normal width again'))
- }
- pop.append(this.menuItem(pref ? 'widthNarrow' : 'widthWide',
- pref ? t('Stop widening every page') : t('Use this width for every page'),
- pref ? t('Only pages that ask for it') : t('On this screen only — it is not saved in the file'),
- () => applyAll(pref ? undefined : (current === 'full' ? 'full' : 'wide'))))
+ row(m, { icon: ICONS.plus, label: t('New page inside'), run: () => this.newPage(pageId) })
- pop.append(this.menuItem('trash', t('Delete…'), t('Links to it become dead'), () => {
- this.closeOverlay()
- this.deletePage(pageId)
- }))
+ // A thread about the PAGE — the second and last anchor. It is offered
+ // where the page's own actions are, and only for the page in view,
+ // because a thread is written into the page you are looking at.
+ if (pageId === s.pageId && !s.readOnly) {
+ row(m, { icon: ICONS.comment, label: t('Comment on this page'), run: () => this.comments.openNew() })
+ }
- document.body.append(pop)
- this.overlay = pop
- place(pop, anchor)
- setTimeout(() => {
- const away = (ev: MouseEvent) => {
- if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }
+ row(m, {
+ icon: page.archived ? ICONS.unarchive : ICONS.archive,
+ label: page.archived ? t('Restore to the page list') : t('Archive'),
+ hint: page.archived ? undefined : t('Out of the sidebar, still searchable and linkable'),
+ run: () => {
+ s.commit(() => {
+ const p = s.index.page.get(pageId)
+ if (!p) return
+ if (p.archived) delete p.archived
+ else p.archived = true
+ })
+ },
+ })
+
+ // HOW WIDE THIS PAGE IS. The renderer already varied it — a page carrying
+ // a board jumped to 1500px — but it decided for you silently. Measured at
+ // a 1600px viewport: the default column is 720px with 631px of the page
+ // left empty beside it, and nothing on the starter pages even reaches the
+ // limit (0 of 15 blocks wrap). The line length was never the problem;
+ // having no say was.
+ caption(m, t('Width'))
+ const current: 'normal' | 'wide' | 'full' =
+ page.width === 'wide' ? 'wide' : page.width === 'full' ? 'full' : 'normal'
+ const setWidth = (v: 'normal' | 'wide' | 'full') => {
+ s.commit(() => {
+ const pg = s.index.page.get(pageId)
+ if (!pg) return
+ // THE DEFAULT IS AN ABSENT KEY, never a stored 'normal'. A page
+ // somebody set to wide and back is then byte-identical to one never
+ // touched, and a file written before this control existed stays so.
+ if (v === 'normal') delete pg.width
+ else pg.width = v
+ }, { scope: 'doc' })
+ this.paintPage()
}
- document.addEventListener('mousedown', away)
- }, 0)
+ row(m, { icon: ICONS.widthNarrow, label: t('Column'), hint: t('Comfortable for reading'),
+ selected: current === 'normal', run: () => setWidth('normal') })
+ row(m, { icon: ICONS.widthWide, label: t('Wide'), hint: t('Room for a board or a table'),
+ selected: current === 'wide', run: () => setWidth('wide') })
+ row(m, { icon: ICONS.widthFull, label: t('Full width'), hint: t('Fills the window'),
+ selected: current === 'full', run: () => setWidth('full') })
+
+ // AND THE SAME CHOICE, FOR EVERY PAGE. Setting a width page by page
+ // answers "this page needs the room"; it does not answer "I have a wide
+ // screen", which is one fact about one person and was costing a visit to
+ // every page in the space. This one is a VIEWER preference —
+ // localStorage, never the file — so it follows the reader rather than
+ // the document, and somebody opening the same space on a laptop is
+ // unaffected.
+ const pref = readerWidth()
+ const applyAll = (v: 'wide' | 'full' | undefined) => {
+ setReaderWidth(v)
+ this.paintPage()
+ this.status(v ? t('Every page opens wide on this screen from now on')
+ : t('Pages open at their normal width again'))
+ }
+ row(m, {
+ icon: pref ? ICONS.widthNarrow : ICONS.widthWide,
+ label: pref ? t('Stop widening every page') : t('Use this width for every page'),
+ hint: pref ? t('Only pages that ask for it') : t('On this screen only — it is not saved in the file'),
+ run: () => applyAll(pref ? undefined : (current === 'full' ? 'full' : 'wide')),
+ })
+
+ m.separator()
+ row(m, { icon: ICONS.trash, label: t('Delete…'), hint: t('Links to it become dead'),
+ run: () => this.deletePage(pageId) })
+ })
}
/**
diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.ts
index 19fbd301..7361d33a 100644
--- a/spaces/src/i18n/de.ts
+++ b/spaces/src/i18n/de.ts
@@ -491,6 +491,7 @@ export const de: Catalog = {
"Type / for blocks, [[ to link a page": "Tippe / für Blöcke, [[ für einen Seitenlink",
"Underline": "Unterstrichen",
"Underline — ⌘U": "Unterstrichen — ⌘U",
+ "Undo": "Rückgängig",
"Undo (⌘Z)": "Rückgängig (⌘Z)",
"Unlock": "Entsperren",
"Unlocked, but the document inside could not be read.": "Entsperrt, aber das Dokument darin konnte nicht gelesen werden.",
diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.ts
index 88abbb1d..d53df9bb 100644
--- a/spaces/src/i18n/es.ts
+++ b/spaces/src/i18n/es.ts
@@ -491,6 +491,7 @@ export const es: Catalog = {
"Type / for blocks, [[ to link a page": "Escribe / para bloques, [[ para enlazar una página",
"Underline": "Subrayado",
"Underline — ⌘U": "Subrayado — ⌘U",
+ "Undo": "Deshacer",
"Undo (⌘Z)": "Deshacer (⌘Z)",
"Unlock": "Desbloquear",
"Unlocked, but the document inside could not be read.": "Desbloqueado, pero no se pudo leer el documento de dentro.",
diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.ts
index 4712f8c1..1af37120 100644
--- a/spaces/src/i18n/fr.ts
+++ b/spaces/src/i18n/fr.ts
@@ -491,6 +491,7 @@ export const fr: Catalog = {
"Type / for blocks, [[ to link a page": "Tapez / pour les blocs, [[ pour lier une page",
"Underline": "Souligné",
"Underline — ⌘U": "Souligné — ⌘U",
+ "Undo": "Annuler",
"Undo (⌘Z)": "Annuler (⌘Z)",
"Unlock": "Déverrouiller",
"Unlocked, but the document inside could not be read.": "Déverrouillé, mais le document à l’intérieur n’a pas pu être lu.",
diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.ts
index 360fa076..b6a13267 100644
--- a/spaces/src/i18n/it.ts
+++ b/spaces/src/i18n/it.ts
@@ -491,6 +491,7 @@ export const it: Catalog = {
"Type / for blocks, [[ to link a page": "Digita / per i blocchi, [[ per collegare una pagina",
"Underline": "Sottolineato",
"Underline — ⌘U": "Sottolineato — ⌘U",
+ "Undo": "Annulla",
"Undo (⌘Z)": "Annulla (⌘Z)",
"Unlock": "Sblocca",
"Unlocked, but the document inside could not be read.": "Sbloccato, ma non è stato possibile leggere il documento all’interno.",
diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.ts
index d2955f0c..e2bb6399 100644
--- a/spaces/src/i18n/ja.ts
+++ b/spaces/src/i18n/ja.ts
@@ -491,6 +491,7 @@ export const ja: Catalog = {
"Type / for blocks, [[ to link a page": "/ でブロック、[[ でページにリンク",
"Underline": "下線",
"Underline — ⌘U": "下線 — ⌘U",
+ "Undo": "元に戻す",
"Undo (⌘Z)": "元に戻す (⌘Z)",
"Unlock": "ロック解除",
"Unlocked, but the document inside could not be read.": "ロックは解除しましたが、中のドキュメントを読み取れませんでした。",
diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.ts
index 94c48b26..339d2688 100644
--- a/spaces/src/i18n/packed.ts
+++ b/spaces/src/i18n/packed.ts
@@ -16,7 +16,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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."],
"A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": ["「.md」ファイルのフォルダーがページになります。フォルダー階層も [[ウィキリンク]] もそのままです。","一个装满 .md 文件的文件夹会变成页面,文件夹层级和 [[wiki 链接]] 都保留下来。","一個裝滿 .md 檔案的資料夾會變成頁面,資料夾層級和 [[wiki 連結]] 都會保留。","Una carpeta de archivos .md se convierte en páginas, con el árbol de carpetas y los [[wikilinks]] intactos.","Un dossier de fichiers .md devient des pages, avec l’arborescence et les [[wikilinks]] intacts.","Ein Ordner voller .md-Dateien wird zu Seiten — samt Ordnerbaum und den [[Wikilinks]] dazwischen.","Una cartella di file .md diventa pagine, con l’albero delle cartelle e i [[wikilink]] intatti.","Uma pasta de ficheiros .md transforma-se em páginas, com a árvore de pastas e os [[wikilinks]] intactos."],
- "A folder of notes, or another space": ["ノートのフォルダー、または別のスペース","一个笔记文件夹,或另一个空间","一個筆記資料夾,或另一個空間","Una carpeta de notas u otro espacio","Un dossier de notes, ou un autre espace","Ein Ordner mit Notizen oder ein anderer Space","Una cartella di note o un altro spazio","Uma pasta de notas, ou outro espaço"],
"A link with nothing in it yet": ["まだ何も入っていないリンク","还没有内容的链接","還沒有內容的連結","Un enlace todavía sin nada","Un lien encore vide","Ein Link, in dem noch nichts steht","Un collegamento ancora vuoto","Um link ainda sem nada"],
"A list of every page, in order": ["すべてのページを順番に並べた一覧","按顺序列出的所有页面","依順序列出每一個頁面","Una lista de todas las páginas, en orden","La liste de toutes les pages, dans l’ordre","Eine Liste aller Seiten, der Reihe nach","Un elenco di tutte le pagine, in ordine","Uma lista de todas as páginas, por ordem"],
"A live viewer: follows every edit as it happens but can never change this space — the relay enforces it.": ["ライブビューア:編集をリアルタイムで追いますが、この Space を変更することはできません — リレーが強制します。","实时查看副本:实时跟随每次编辑,但永远无法修改此 Space — 由中继强制执行。","即時檢視副本:即時跟隨每次編輯,但永遠無法修改此 Space — 由中繼強制執行。","Un visor en vivo: sigue cada edición al instante pero nunca puede modificar este Space — el relé lo garantiza.","Un visualiseur en direct : suit chaque modification mais ne peut jamais changer cet espace — le relais l’applique.","Ein Live-Viewer: folgt jeder Änderung, kann diesen Space aber nie verändern — vom Relay erzwungen.","Un visualizzatore live: segue ogni modifica ma non può mai cambiare questo Space — imposto dal relay.","Um visualizador ao vivo: acompanha cada edição conforme acontece, mas nunca pode alterar este Space — o retransmissor garante isso."],
@@ -89,7 +88,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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 the name used for your new comments and replies": ["新しいコメントと返信に使う名前を変更","更改新评论和回复所用的名字","變更新註解與回覆所用的名字","Cambiar el nombre para tus nuevos comentarios y respuestas","Changer le nom utilisé pour vos nouveaux commentaires et réponses","Namen für neue Kommentare und Antworten ändern","Cambia il nome usato per i tuoi nuovi commenti e risposte","Altere o nome usado nos seus novos comentários e respostas"],
"Change the shape of this canvas": ["このキャンバスの形を変更","更改此画布的形状","變更此畫布的形狀","Cambiar la forma de este lienzo","Changer la forme de ce canevas","Form dieser Leinwand ändern","Cambia la forma di questa tela","Alterar o formato desta tela"],
- "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"],
"Change {field}": ["{field}を変更","更改{field}","變更{field}","Cambiar {field}","Modifier {field}","{field} ändern","Cambia {field}","Alterar {field}"],
"Check for updates": ["更新を確認","检查更新","檢查更新","Buscar actualizaciones","Rechercher des mises à jour","Nach Updates suchen","Cerca aggiornamenti","Verificar atualizações"],
@@ -174,7 +172,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Enter the password to open it.": ["開くにはパスワードを入力してください。","输入密码以打开。","請輸入密碼以開啟。","Introduce la contraseña para abrirlo.","Saisissez le mot de passe pour l’ouvrir.","Gib das Passwort ein, um ihn zu öffnen.","Inserisci la password per aprirlo.","Introduza a palavra-passe para o abrir."],
"Every page opens wide on this screen from now on": ["この画面では今後すべてのページを広く表示します","在此屏幕上,之后所有页面都会以加宽方式打开","在此螢幕上,之後所有頁面都會以加寬方式開啟","A partir de ahora todas las páginas se abren anchas en esta pantalla","Désormais toutes les pages s’ouvrent en large sur cet écran","Auf diesem Bildschirm öffnen ab jetzt alle Seiten breit","Da ora tutte le pagine si aprono larghe su questo schermo","A partir de agora todas as páginas abrem largas neste ecrã"],
"Every page with a status": ["ステータスを持つすべてのページ","所有带状态的页面","所有帶狀態的頁面","Todas las páginas con estado","Toutes les pages ayant un statut","Jede Seite mit einem Status","Ogni pagina con uno stato","Todas as páginas com estado"],
- "Every page, and what links to what": ["すべてのページと、そのつながり","所有页面,以及它们之间的链接","所有頁面,以及它們之間的連結","Todas las páginas, y qué enlaza con qué","Toutes les pages, et ce qui pointe vers quoi","Alle Seiten, und was worauf verweist","Tutte le pagine, e cosa collega a cosa","Todas as páginas, e o que liga ao quê"],
"Every page, as one .md file": ["すべてのページを 1 つの .md ファイルに","所有页面合并为一个 .md 文件","所有頁面合併為一個 .md 檔","Todas las páginas, en un solo archivo .md","Toutes les pages, en un seul fichier .md","Jede Seite, in einer .md-Datei","Tutte le pagine, in un unico file .md","Todas as páginas num único ficheiro .md"],
"Everything in this space is replaced by what you paste. ⌘Z undoes it, but only while this window stays open.": ["このスペースの内容はすべて貼り付けた内容に置き換わります。⌘Z で元に戻せますが、それはこのウィンドウを開いている間だけです。","这个空间里的所有内容都会被你粘贴的内容替换。⌘Z 可以撤销,但仅限于这个窗口保持打开时。","這個空間裡的所有內容都會被你貼上的內容取代。⌘Z 可以復原,但僅限於這個視窗保持開啟時。","Todo lo que hay en este espacio se sustituye por lo que pegues. ⌘Z lo deshace, pero solo mientras esta ventana siga abierta.","Tout ce que contient cet espace est remplacé par ce que vous collez. ⌘Z annule l’opération, mais seulement tant que cette fenêtre reste ouverte.","Alles in diesem Space wird durch das ersetzt, was Sie einfügen. ⌘Z macht das rückgängig, aber nur solange dieses Fenster geöffnet bleibt.","Tutto ciò che si trova in questo spazio viene sostituito da quello che incolli. ⌘Z annulla l’operazione, ma solo finché questa finestra resta aperta.","Tudo o que está neste espaço é substituído pelo que colar. ⌘Z desfaz, mas só enquanto esta janela continuar aberta."],
"Export": ["書き出す","导出","匯出","Exportar","Exporter","Exportieren","Esporta","Exportar"],
@@ -363,6 +360,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Reading view — press Esc or the eye to edit": ["閲覧ビュー — Esc か目のアイコンで編集に戻ります","阅读视图 — 按 Esc 或点击眼睛图标即可编辑","閱讀檢視 — 按 Esc 或眼睛圖示即可編輯","Vista de lectura — pulsa Esc o el ojo para editar","Vue lecture — appuyez sur Esc ou sur l’œil pour modifier","Leseansicht — Esc oder das Auge zum Bearbeiten","Vista di lettura — premi Esc o l’occhio per modificare","Vista de leitura — prima Esc ou o olho para editar"],
"Reading {n} file(s)…": ["{n} 個のファイルを読み込み中…","正在读取 {n} 个文件…","正在讀取 {n} 個檔案…","Leyendo {n} archivo(s)…","Lecture de {n} fichier(s)…","Lese {n} Datei(en)…","Lettura di {n} file…","A ler {n} ficheiro(s)…"],
"Red": ["赤","红色","紅色","Rojo","Rouge","Rot","Rosso","Vermelho"],
+ "Redo": ["やり直す","重做","重做","Rehacer","Rétablir","Wiederholen","Ripristina","Refazer"],
"Redo (⇧⌘Z)": ["やり直す (⇧⌘Z)","重做 (⇧⌘Z)","重做 (⇧⌘Z)","Rehacer (⇧⌘Z)","Rétablir (⇧⌘Z)","Wiederholen (⇧⌘Z)","Ripeti (⇧⌘Z)","Refazer (⇧⌘Z)"],
"Reload into new version": ["再読込して新バージョンへ","重新加载进入新版本","重新載入進入新版本","Recargar en la nueva versión","Recharger dans la nouvelle version","Neu laden in die neue Version","Ricarica nella nuova versione","Recarregar na nova versão"],
"Remove": ["削除","移除","移除","Quitar","Retirer","Entfernen","Rimuovi","Remover"],
@@ -466,14 +464,12 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": ["ライブセッションがこの変更を保存できませんでした。自分のコピーには保存されますが、共同編集者には表示されません。","实时会话无法保存该更改。它已保存在你的副本中,但协作者不会看到。","即時工作階段無法儲存此變更。它已儲存在你的副本中,但協作者不會看到。","La sesión en vivo no pudo guardar ese cambio. Se guarda en tu copia, pero los colaboradores no lo verán.","La session en direct n’a pas pu enregistrer cette modification. Elle est enregistrée dans votre copie, mais les collaborateurs ne la verront pas.","Die Live-Sitzung konnte diese Änderung nicht speichern. Sie ist in deiner Kopie gespeichert, aber Mitarbeitende sehen sie nicht.","La sessione dal vivo non è riuscita a salvare questa modifica. È salvata nella tua copia, ma i collaboratori non la vedranno.","A sessão ao vivo não conseguiu armazenar essa alteração. Ela fica salva na sua cópia, mas os colaboradores não a verão."],
"The next save writes this space as plain, readable JSON — anybody who opens the file can read every page.": ["次の保存で、このスペースはそのまま読める JSON として書き出されます。ファイルを開いた人は誰でも全ページを読めます。","下一次保存会把这个空间写成可直接阅读的 JSON——任何打开这个文件的人都能读到每一页。","下一次儲存會把這個空間寫成可直接閱讀的 JSON——任何開啟這個檔案的人都能讀到每一頁。","El próximo guardado escribe este espacio como JSON legible: cualquiera que abra el archivo podrá leer todas las páginas.","Le prochain enregistrement écrira cet espace en JSON lisible : quiconque ouvre le fichier pourra lire toutes les pages.","Beim nächsten Speichern wird dieser Space als lesbares JSON geschrieben — wer die Datei öffnet, kann jede Seite lesen.","Il prossimo salvataggio scrive questo spazio come JSON leggibile: chiunque apra il file potrà leggere ogni pagina.","A próxima gravação escreve este espaço como JSON legível — quem abrir o ficheiro consegue ler todas as páginas."],
"The page becomes a new file of its own: a whole space, with a new document id and none of this one’s sharing keys.": ["そのページが独立した新しいファイルになります。ひとつの完全なスペースで、新しいドキュメント ID を持ち、このスペースの共有キーは一切引き継ぎません。","该页面会成为一个独立的新文件:一个完整的空间,拥有新的文档 ID,且不带本空间的任何共享密钥。","該頁面會成為獨立的新檔案:一個完整的空間,擁有新的文件 ID,且不帶本空間的任何共用金鑰。","La página se convierte en un archivo propio: un espacio completo, con un nuevo id de documento y sin ninguna de las claves de uso compartido de este.","La page devient un fichier à part entière : un espace complet, avec un nouvel identifiant de document et aucune des clés de partage de celui-ci.","Die Seite wird zu einer eigenen Datei: ein vollständiger Space mit einer neuen Dokument-ID und ohne die Freigabeschlüssel dieses Space.","La pagina diventa un file a sé: uno spazio completo, con un nuovo id di documento e senza nessuna delle chiavi di condivisione di questo.","A página passa a ser um ficheiro próprio: um espaço completo, com um novo id de documento e sem nenhuma das chaves de partilha deste."],
- "The pages without the editing tools": ["編集ツールのないページ表示","不带编辑工具的页面","不含編輯工具的頁面","Las páginas sin las herramientas de edición","Les pages sans les outils d'édition","Die Seiten ohne die Bearbeitungswerkzeuge","Le pagine senza gli strumenti di modifica","As páginas sem as ferramentas de edição"],
"The rest name notes that were not in the selection, and are left as text.": ["残りは選択に含まれていないノートを指しており、テキストのまま残ります。","其余指向不在所选范围内的笔记,保留为文字。","其餘指向不在所選範圍內的筆記,保留為文字。","El resto nombra notas que no estaban en la selección y se dejan como texto.","Les autres désignent des notes absentes de la sélection et restent en texte.","Der Rest nennt Notizen, die nicht in der Auswahl waren, und bleibt als Text stehen.","Gli altri nominano note che non erano nella selezione e restano come testo.","Os restantes nomeiam notas que não estavam na seleção e ficam como texto."],
"The theme follows whoever opens the file. It is never written into the document.": ["テーマはファイルを開いた人に従います。ドキュメントには書き込まれません。","主题跟随打开文件的人,绝不会写入文档。","主題取決於開啟檔案的人,永遠不會寫入文件中。","El tema sigue a quien abre el archivo. Nunca se escribe en el documento.","Le thème suit la personne qui ouvre le fichier. Il n’est jamais écrit dans le document.","Das Design richtet sich danach, wer die Datei öffnet. Es wird nie ins Dokument geschrieben.","Il tema segue chi apre il file. Non viene mai scritto nel documento.","O tema segue quem abre o ficheiro. Nunca é escrito no documento."],
"The whole space": ["スペース全体","整个空间","整個空間","Todo el espacio","Tout l’espace","Der ganze Space","L’intero spazio","Todo o espaço"],
"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’s settings, and the page’s": ["このブロックの設定と、ページの設定","这个块的设置,还有页面的设置","這個區塊的設定,還有頁面的設定","Los ajustes de este bloque, y los de la página","Les réglages de ce bloc, et ceux de la page","Die Einstellungen dieses Blocks — und die der Seite","Le impostazioni di questo blocco, e quelle della pagina","As definições deste bloco, e as da página"],
"This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルに書き戻せないため、保存のたびに新しいコピーができます。パソコンの Chrome と Edge なら直接上書き保存できます。","此浏览器无法写回原文件,因此每次保存都会生成新副本。电脑上的 Chrome 和 Edge 可以就地保存。","此瀏覽器無法寫回檔案,因此每次儲存都會產生新的副本。電腦版的 Chrome 和 Edge 可以就地儲存。","Este navegador no puede reescribir el archivo, así que cada guardado crea una copia nueva. Chrome y Edge en un ordenador sí pueden guardar en el sitio.","Ce navigateur ne peut pas réécrire le fichier : chaque enregistrement crée donc une nouvelle copie. Chrome et Edge sur ordinateur enregistrent sur place.","Dieser Browser kann nicht in die Datei zurückschreiben, deshalb entsteht bei jedem Speichern eine neue Kopie. Chrome und Edge auf dem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare sul posto.","Este navegador não consegue escrever de volta no ficheiro, por isso cada vez que guarda cria uma nova cópia. O Chrome e o Edge num computador conseguem guardar no local."],
"This 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"],
@@ -515,6 +511,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"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"],
"Underline": ["下線","下划线","底線","Subrayado","Souligné","Unterstrichen","Sottolineato","Sublinhado"],
"Underline — ⌘U": ["下線 — ⌘U","下划线 — ⌘U","底線 — ⌘U","Subrayado — ⌘U","Souligné — ⌘U","Unterstrichen — ⌘U","Sottolineato — ⌘U","Sublinhado — ⌘U"],
+ "Undo": ["元に戻す","撤销","還原","Deshacer","Annuler","Rückgängig","Annulla","Desfazer"],
"Undo (⌘Z)": ["元に戻す (⌘Z)","撤销 (⌘Z)","還原 (⌘Z)","Deshacer (⌘Z)","Annuler (⌘Z)","Rückgängig (⌘Z)","Annulla (⌘Z)","Desfazer (⌘Z)"],
"Undo, redo": ["取り消し・やり直し","撤销、重做","復原、重做","Deshacer, rehacer","Annuler, rétablir","Rückgängig, wiederherstellen","Annulla, ripeti","Anular, refazer"],
"Unlock": ["ロック解除","解锁","解鎖","Desbloquear","Déverrouiller","Entsperren","Sblocca","Desbloquear"],
@@ -533,7 +530,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Verifies and builds the new version with this document inside, then asks where to save it — pick the file you have open to update it.": ["このドキュメントを含む新バージョンを検証・生成し、保存先を尋ねます — 開いているファイルを選べば更新されます。","验证并生成包含此文档的新版本,然后询问保存位置 — 选择当前打开的文件即可更新。","驗證並建立包含此文件的新版本,然後詢問儲存位置 — 選擇目前開啟的檔案即可更新。","Verifica y construye la nueva versión con este documento dentro, y pregunta dónde guardarla — elige el archivo que tienes abierto para actualizarlo.","Vérifie et construit la nouvelle version avec ce document, puis demande où l'enregistrer — choisissez le fichier ouvert pour le mettre à jour.","Verifiziert und erstellt die neue Version mit diesem Dokument und fragt nach dem Speicherort — wählen Sie die geöffnete Datei, um sie zu aktualisieren.","Verifica e costruisce la nuova versione con questo documento, poi chiede dove salvarla — scegli il file aperto per aggiornarlo.","Verifica e monta a nova versão com este documento dentro e depois pergunta onde salvá-la — escolha o arquivo que você tem aberto para atualizá-lo."],
"Verifying…": ["検証中…","验证中…","驗證中…","Verificando…","Vérification…","Verifiziere…","Verifica…","Verificando…"],
"Version {v} is available.": ["バージョン {v} が利用可能です。","版本 {v} 可用。","版本 {v} 可用。","Versión {v} disponible.","La version {v} est disponible.","Version {v} ist verfügbar.","È disponibile la versione {v}.","A versão {v} está disponível."],
- "Version, language, password, exports": ["バージョン・言語・パスワード・書き出し","版本、语言、密码、导出","版本、語言、密碼、匯出","Versión, idioma, contraseña, exportaciones","Version, langue, mot de passe, exports","Version, Sprache, Passwort, Export","Versione, lingua, password, esportazioni","Versão, idioma, senha, exportações"],
"Versions are kept in this browser only — never in the file, never online. Restoring is undoable.": ["バージョンはこのブラウザーにのみ保存されます。ファイルにもオンラインにも残りません。復元は取り消せます。","版本仅保存在此浏览器中,不会写入文件,也不会上传。恢复操作可以撤销。","版本僅保存在此瀏覽器中,不會寫入檔案,也不會上傳。還原操作可以復原。","Las versiones se guardan solo en este navegador: nunca en el archivo ni en línea. Restaurar se puede deshacer.","Les versions sont conservées uniquement dans ce navigateur — jamais dans le fichier, jamais en ligne. La restauration est annulable.","Versionen liegen nur in diesem Browser — nie in der Datei, nie online. Das Wiederherstellen lässt sich rückgängig machen.","Le versioni restano solo in questo browser: mai nel file, mai online. Il ripristino si può annullare.","As versões ficam apenas neste navegador — nunca no ficheiro, nunca online. Restaurar pode ser desfeito."],
"Video": ["動画","视频","影片","Vídeo","Vidéo","Video","Video","Vídeo"],
"Video from {host}": ["{host} の動画","来自 {host} 的视频","來自 {host} 的影片","Vídeo de {host}","Vidéo provenant de {host}","Video von {host}","Video da {host}","Vídeo de {host}"],
diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.ts
index 13845acf..e91b3eab 100644
--- a/spaces/src/i18n/pt.ts
+++ b/spaces/src/i18n/pt.ts
@@ -491,6 +491,7 @@ export const pt: Catalog = {
"Type / for blocks, [[ to link a page": "Escreva / para blocos, [[ para ligar uma página",
"Underline": "Sublinhado",
"Underline — ⌘U": "Sublinhado — ⌘U",
+ "Undo": "Desfazer",
"Undo (⌘Z)": "Desfazer (⌘Z)",
"Unlock": "Desbloquear",
"Unlocked, but the document inside could not be read.": "Desbloqueado, mas não foi possível ler o documento lá dentro.",
diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.ts
index 58a05195..cd72a1ce 100644
--- a/spaces/src/i18n/zh-Hans.ts
+++ b/spaces/src/i18n/zh-Hans.ts
@@ -491,6 +491,7 @@ export const zh_Hans: Catalog = {
"Type / for blocks, [[ to link a page": "输入 / 插入块,[[ 链接页面",
"Underline": "下划线",
"Underline — ⌘U": "下划线 — ⌘U",
+ "Undo": "撤销",
"Undo (⌘Z)": "撤销 (⌘Z)",
"Unlock": "解锁",
"Unlocked, but the document inside could not be read.": "已解锁,但无法读取其中的文档。",
diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.ts
index 8aa746d0..ea784695 100644
--- a/spaces/src/i18n/zh-Hant.ts
+++ b/spaces/src/i18n/zh-Hant.ts
@@ -491,6 +491,7 @@ export const zh_Hant: Catalog = {
"Type / for blocks, [[ to link a page": "輸入 / 插入區塊,輸入 [[ 連結頁面",
"Underline": "底線",
"Underline — ⌘U": "底線 — ⌘U",
+ "Undo": "還原",
"Undo (⌘Z)": "還原 (⌘Z)",
"Unlock": "解鎖",
"Unlocked, but the document inside could not be read.": "已解鎖,但無法讀取裡面的文件。",
diff --git a/spaces/src/icons.ts b/spaces/src/icons.ts
index 077e0846..de0bcf12 100644
--- a/spaces/src/icons.ts
+++ b/spaces/src/icons.ts
@@ -55,7 +55,8 @@ export const ICONS = {
widthWide: svg('<rect x="5" y="4" width="14" height="16" rx="1.5"/><line x1="2" y1="9" x2="2" y2="15"/><line x1="22" y1="9" x2="22" y2="15"/>'),
widthFull: svg('<rect x="2" y="4" width="20" height="16" rx="1.5"/>'),
people: svg('<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>'),
- 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"/>'),
+ // ⋯, horizontal: the suite's overflow glyph (D7), the one slides folds into
+ more: svg('<circle cx="5" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="19" cy="12" r="1.6" fill="currentColor" stroke="none"/>'),
unarchive: svg('<rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><polyline points="9 15 12 12 15 15"/><line x1="12" y1="12" x2="12" y2="18"/>'),
replace: svg('<path d="M14 4h5v5"/><path d="M19 4 5 18"/><path d="M9 4H5v4"/><path d="m15 15 4 4-4 4"/>'),
arrowUp: svg('<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>'),
diff --git a/spaces/src/menus.ts b/spaces/src/menus.ts
new file mode 100644
index 00000000..397108e8
--- /dev/null
+++ b/spaces/src/menus.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// SPACES' MENUS, ON THE KERNEL'S MENU. Every dropdown and every anchored menu
+// in this app is a `createMenu` from kernel/src/ui/menu.ts; this file is only
+// the adapter that fits the primitive to the two ways spaces opens a menu.
+//
+// WHY. Spaces had its own dropdown (`dropdown()`, two document listeners per
+// menu, never removed) and nine anchored popovers, each installing its own
+// `mousedown` away-listener. That listener was removed only when IT fired, so a
+// popover closed by Escape left one behind, and the next mousedown anywhere —
+// including inside the NEXT overlay — closed whatever was open. Measured on the
+// built shell: Escape a block menu, open search with ⌘K, click inside the
+// search card, and the search closes. None of the menus had arrow keys. The
+// kernel primitive has one delegated listener pair for every menu, Escape with
+// focus return, arrow/Home/End, aria-expanded, and mutual exclusion, and its
+// rig (scripts/test-ui-menu.ts) proves all of it. Adopting it is how spaces
+// gets those, rather than growing a second copy of each.
+//
+// TWO SHAPES:
+//
+// barMenu a trigger in the topbar with its popup under it — the
+// primitive exactly as it comes.
+// anchoredMenu a menu opened FROM something that is not its trigger: a row's
+// ⋯, a block's grip, a board chip. The kernel's menu is
+// positioned by CSS under its own trigger, so this mounts the
+// menu's wrapper `position: fixed` over the anchor, with the
+// trigger hidden, and places the popup against the viewport
+// (flip above when the room is there, clamp to the edges, cap the
+// height to the room it has). Below the drawer breakpoint it is a
+// bottom sheet instead, where a thumb can reach it.
+//
+// WHAT THE KERNEL DOES NOT HAVE, and is written down for it rather than forked
+// here (working/team/notes/spaces.md): an anchored mode with viewport-aware
+// placement, a close callback, and a right-aligned shortcut slot on a row. The
+// first two are the MutationObserver below; the third is the <kbd> appended to
+// the row the kernel returns. Each is composition over the kernel's API, not a
+// copy of it.
+
+import { createMenu, type Menu } from '../../kernel/src/ui/menu.ts'
+import '../../kernel/src/ui/menu.css'
+
+export type { Menu }
+
+export interface Row {
+ /** inline SVG for the leading icon */
+ icon?: string
+ label: string
+ /**
+ * A visible second line — only where the row has a CONSEQUENCE worth saying
+ * before you press it ("Links to it become dead"). A command list is single
+ * line (D2): the name is the description.
+ */
+ hint?: string
+ /** a keyboard shortcut, shown right-aligned in the row (D8) */
+ kbd?: string
+ off?: boolean
+ selected?: boolean
+ keepOpen?: boolean
+ run: () => void
+}
+
+/** One row. Composition over the kernel's `item()`: the shortcut slot is ours. */
+export function row(m: Menu, r: Row): HTMLButtonElement {
+ const b = m.item(r.label, r.run, {
+ icon: r.icon, hint: r.hint, off: r.off, selected: r.selected, keepOpen: r.keepOpen,
+ })
+ if (r.kbd) {
+ const k = document.createElement('kbd')
+ k.className = 'sp-mkbd'
+ k.textContent = r.kbd
+ b.append(k)
+ }
+ return b
+}
+
+/** A caption over a group of rows. Not a row: arrow keys never land on it. */
+export function caption(m: Menu, text: string): HTMLElement {
+ const c = document.createElement('div')
+ c.className = 'sp-menu-label'
+ c.setAttribute('role', 'presentation')
+ c.textContent = text
+ m.menu.append(c)
+ return c
+}
+
+/** Anything that is not a row — a form, a note — appended as-is. */
+export function extra(m: Menu, node: HTMLElement): HTMLElement {
+ m.menu.append(node)
+ return node
+}
+
+/**
+ * Shortcut notation, in ONE place: modifiers in Apple's ⌃⌥⇧⌘ order (D8).
+ * The help sheet and the menus used to disagree with each other — ⇧⌘S beside
+ * ⌘⇧J in the same list — because each was typed by hand.
+ */
+export function keys(...parts: Array<'ctrl' | 'alt' | 'shift' | 'mod' | string>): string {
+ const ORDER = ['ctrl', 'alt', 'shift', 'mod']
+ const GLYPH: Record<string, string> = { ctrl: '⌃', alt: '⌥', shift: '⇧', mod: '⌘' }
+ const mods = parts.filter((p) => ORDER.includes(p)).sort((a, b) => ORDER.indexOf(a) - ORDER.indexOf(b))
+ const rest = parts.filter((p) => !ORDER.includes(p))
+ return mods.map((m) => GLYPH[m]).join('') + rest.join('')
+}
+
+export interface BarMenuOpts {
+ icon: string
+ label: string
+ tip: string
+ fill: (m: Menu) => void
+ /** hangs off the inline-end of the bar: grow inward */
+ end?: boolean
+ /** a long list: scroll inside the viewport rather than run off it */
+ scroll?: boolean
+ className?: string
+}
+
+/** A topbar dropdown. The kernel primitive, with spaces' button face. */
+export function barMenu(o: BarMenuOpts): Menu {
+ let m: Menu | null = null
+ m = createMenu(o.label, o.tip, {
+ className: 'sp-mn' + (o.className ? ' ' + o.className : ''),
+ menuClass: 'sp-mn-pop' + (o.scroll ? ' bkm-scroll' : ''),
+ alignEnd: o.end,
+ fill: () => { if (m) o.fill(m) },
+ })
+ m.trigger.classList.add('sp-btn')
+ m.trigger.insertAdjacentHTML('afterbegin', o.icon)
+ // the word collapses with the bar's compact tier, like every labelled button
+ m.trigger.querySelector('.bkm-label')?.classList.add('sp-btnlabel')
+ return m
+}
+
+export interface AnchoredOpts {
+ /** the menu's accessible name */
+ label: string
+ /** a bottom sheet instead of an anchored popup (phone) */
+ sheet?: boolean
+ /** extra class on the popup */
+ className?: string
+ /** runs once, however the menu closed: a row, Escape, a click away, close() */
+ onClose?: () => void
+ /** where focus goes when the menu closes with focus inside it */
+ returnFocus?: HTMLElement | null
+ /** role of the popup: `menu` unless it holds a form, which is a `dialog` */
+ role?: 'menu' | 'dialog' | 'listbox'
+}
+
+const GAP = 6
+const EDGE = 8
+
+/**
+ * Put the popup against the viewport. The same rules place() in editor.ts
+ * followed: take the side with more room, give the popup that room, then clamp
+ * it inside the edges. Coordinates are the wrapper's, which sits exactly over
+ * the anchor.
+ */
+function placeMenu(root: HTMLElement, pop: HTMLElement, r: DOMRect): void {
+ root.style.left = `${r.left}px`
+ root.style.top = `${r.top}px`
+ root.style.width = `${r.width}px`
+ root.style.height = `${r.height}px`
+ const below = innerHeight - r.bottom - GAP - EDGE
+ const above = r.top - GAP - EDGE
+ const useBelow = below >= above || below >= 320
+ pop.style.maxHeight = `${Math.max(160, useBelow ? below : above)}px`
+ pop.style.top = useBelow ? `calc(100% + ${GAP}px)` : 'auto'
+ pop.style.bottom = useBelow ? 'auto' : `calc(100% + ${GAP}px)`
+ // measured after the cap; clamp on the inline axis. Physical left/right, so
+ // the logical inset the kernel sets is cleared first.
+ pop.style.insetInlineStart = 'auto'
+ pop.style.insetInlineEnd = 'auto'
+ const w = pop.offsetWidth
+ const rtl = getComputedStyle(root).direction === 'rtl'
+ let left = rtl ? r.right - w : r.left
+ if (left + w > innerWidth - EDGE) left = innerWidth - w - EDGE
+ if (left < EDGE) left = EDGE
+ pop.style.left = `${left - r.left}px`
+ pop.style.right = 'auto'
+}
+
+/**
+ * A menu opened from an element that is not its trigger. Returns the open
+ * menu; `onClose` fires exactly once, whichever way it closes.
+ */
+export function anchoredMenu(
+ anchor: HTMLElement | DOMRect,
+ fill: (m: Menu) => void,
+ o: AnchoredOpts,
+): Menu {
+ const m = createMenu('', o.label, {
+ className: 'sp-mn-anchored',
+ menuClass: 'sp-mn-pop bkm-scroll' + (o.sheet ? ' sp-mn-sheet' : '') + (o.className ? ' ' + o.className : ''),
+ })
+ m.trigger.hidden = true
+ m.trigger.tabIndex = -1
+ if (o.role && o.role !== 'menu') m.menu.setAttribute('role', o.role)
+ m.menu.setAttribute('aria-label', o.label)
+ // populate BEFORE opening: an anchored menu is built once for the one open
+ fill(m)
+ document.body.append(m.root)
+ m.open()
+
+ const rect = () => (anchor instanceof HTMLElement ? anchor.getBoundingClientRect() : anchor)
+ const place = () => { if (!o.sheet) placeMenu(m.root, m.menu, rect()) }
+ place()
+ addEventListener('resize', place)
+
+ // THE CLOSE CALLBACK THE PRIMITIVE DOES NOT HAVE. The kernel closes a menu
+ // by taking `bkm-open` off its wrapper — on Escape, on a press outside, when
+ // another menu opens, on a row. Watching that one class is the only way to
+ // hear all four, so this is where the menu is torn down and focus returned.
+ let done = false
+ const finish = () => {
+ if (done) return
+ done = true
+ mo.disconnect()
+ removeEventListener('resize', place)
+ const hadFocus = m.root.contains(document.activeElement)
+ m.destroy()
+ o.onClose?.()
+ if (hadFocus) {
+ const back = o.returnFocus ?? (anchor instanceof HTMLElement ? anchor : null)
+ try { back?.focus?.() } catch { /* the anchor went with a repaint */ }
+ }
+ }
+ const mo = new MutationObserver(() => { if (!m.isOpen) finish() })
+ mo.observe(m.root, { attributes: true, attributeFilter: ['class'] })
+ return m
+}
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index ce524af5..eed2417d 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -1123,20 +1123,84 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
p, li { orphans: 2; widows: 2; }
}
-/* ————— topbar dropdowns ————— */
-.sp-dd { position: relative; }
-.sp-ddmenu {
- display: none; position: absolute; top: calc(100% + 5px); inset-inline-start: 0;
- min-width: 250px; flex-direction: column; z-index: 60;
- background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
- box-shadow: 0 12px 34px rgb(var(--shade) / .2); padding: 5px;
-}
-.sp-dd.sp-open .sp-ddmenu { display: flex; }
-.sp-dd:last-child .sp-ddmenu { inset-inline-start: auto; inset-inline-end: 0; }
+/* ————— the chrome scale, named as the suite's shared sheet names it —————
+ The values the D1–D8 rulings settled (2026-09-25), under the names the
+ kernel's tier-4 token sheet gives them, so adopting that sheet later is a
+ deletion here and a rename nowhere. Its own block, and UNTHEMED: these are
+ sizes, and the one colour in them (the shadow) reads `--shade`, which the
+ dark blocks already flip. */
+:root {
+ --radius-sm: 6px; /* inputs, menu rows */
+ --radius-lg: 14px; /* dialogs and sheets */
+ --shadow-pop: 0 12px 32px rgb(var(--shade) / .16); /* menus, popovers */
+ --ctl-h: 30px;
+ --tap: 44px; /* D5: a coarse pointer's target */
+ --fs-hint: 12px;
+ --z-pop: 60;
+}
+
+/* ————— menus: the kernel's (kernel/src/ui/menu.css) —————
+ Every dropdown and anchored menu is `createMenu`; see menus.ts for why. The
+ primitive reads its look through `--bkm-*` chains, and these are this app's
+ answers. Structure and behaviour are the kernel's and are not restated here.
+ Menus keep `--radius` (10px): `--radius-lg` is the DIALOG corner, and the
+ kernel's chain would otherwise hand a menu 14px. */
+.sp-app, .sp-mn-anchored {
+ --bkm-radius: var(--radius);
+ --bkm-item-radius: var(--radius-sm);
+ --bkm-shadow: var(--shadow-pop);
+ --bkm-ink: var(--ink);
+ --bkm-font-size: 13.5px;
+ --bkm-min-width: 240px;
+ --bkm-z: var(--z-pop);
+}
+.sp-mn-pop { font-family: inherit; }
+.sp-mn-pop .bkm-text { font-weight: 600; }
+.sp-mn-pop .bkm-hint { font-size: var(--fs-hint); }
+.sp-mn-pop .bkm-item { min-height: var(--ctl-h); }
+/* Selectors that override the kernel sheet carry `.bkm`/`.bkm-menu`: the
+ bundle places that sheet AFTER this file, so equal specificity loses.
+ A row that TEACHES may wrap, but no menu here is wider than a phone column. */
+.bkm-menu.sp-mn-pop { max-width: min(320px, calc(100vw - 16px)); }
+.sp-mn-pop .bkm-body { flex: 1 1 auto; }
+.sp-mn-pop .bkm-selected { background: var(--chrome-2); }
+/* a SHORTCUT sits at the row's end, in the interface face, right-aligned, in
+ ⌃⌥⇧⌘ order (D8) — never a second line under the name, where it read as a
+ description of the command */
+.sp-mkbd {
+ margin-inline-start: auto; padding-inline-start: 14px; flex: none;
+ font: inherit; font-size: var(--fs-hint); color: var(--muted);
+ letter-spacing: .02em; white-space: nowrap;
+}
+/* the trigger is a bar button like any other */
+.sp-mn > .bkm-trigger { display: inline-flex; align-items: center; gap: 6px; }
+/* the menu hanging off the save caret is the save split's; reset the wrapper */
+.sp-split .sp-mn { display: flex; align-items: stretch; }
+/* the anchored menu's wrapper sits exactly over its anchor (menus.ts places it)
+ and must take no clicks of its own */
+.bkm.sp-mn-anchored { position: fixed; pointer-events: none; z-index: var(--z-pop); }
+.bkm.sp-mn-anchored > .bkm-menu { pointer-events: auto; }
+/* …and on a phone it is a SHEET at the bottom edge, where a thumb reaches it and
+ nothing can be placed off-screen */
+.bkm.sp-mn-anchored > .bkm-menu.sp-mn-sheet {
+ position: fixed; top: auto; left: 8px; right: 8px;
+ bottom: max(8px, env(safe-area-inset-bottom));
+ max-width: none; min-width: 0; max-height: 62vh;
+ border-radius: var(--radius-lg); padding: 8px;
+ box-shadow: 0 -8px 40px rgb(var(--shade) / .28);
+}
+/* rows that are not commands — the "Width" caption, a filter's field name */
+.sp-mn-pop .sp-menu-label:first-child { border-top: 0; margin-top: 0; }
+/* a form inside a menu (a new property, a callout's own icon) */
+.sp-mn-pop .sp-newprop, .sp-mn-pop .sp-tonerow { padding: 4px 6px 6px; }
+
+/* ————— rows outside the kernel menu —————
+ The design picker's rows (designpanel.ts) are built by hand and keep this
+ class; they are drawn to match a kernel row exactly. */
.sp-dditem {
- display: flex; align-items: center; gap: 10px; width: 100%;
- text-align: start; font: inherit; color: var(--ink);
- background: transparent; border: 0; border-radius: 7px;
+ display: flex; align-items: center; gap: 9px; width: 100%;
+ text-align: start; font: inherit; font-size: 13.5px; color: var(--ink);
+ background: transparent; border: 0; border-radius: var(--radius-sm);
padding: 7px 9px; cursor: pointer;
}
.sp-dditem:hover { background: var(--chrome-2); }
@@ -1461,13 +1525,12 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
@media (pointer: coarse) {
.sp-bar .sp-btn { min-width: 40px; min-height: 40px; justify-content: center; }
.sp-dditem { padding-block: 11px; }
+ /* D5: a menu row is a 44px target under a finger, like every other one */
+ .sp-mn-pop .bkm-item { min-height: var(--tap); }
+ /* …and a shortcut is noise where there is no keyboard to press it on */
+ .sp-mkbd { display: none; }
}
-/* A menu opened from the right end of the bar must open INWARD. Anchoring
- every dropdown to its start edge put the ⋯ and Save menus half off-screen at
- 375px — the items were there, just unreadable. */
-.sp-dd-end .sp-ddmenu { inset-inline-start: auto; inset-inline-end: 0; }
-.sp-ddmenu { max-width: calc(100vw - 20px); }
/* ————— find & replace on a small screen —————
Measured at a 575px viewport: the bar laid out 644px wide and started at
@@ -1501,7 +1564,6 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset
border-start-end-radius: 0; border-end-end-radius: 0;
padding-inline-end: 10px;
}
-.sp-split .sp-dd { display: flex; align-items: stretch; }
.sp-split .sp-caret > .sp-btn {
height: 100%; padding: 6px 6px;
border-start-start-radius: 0; border-end-start-radius: 0;