Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
#!/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')
const handDialogs = files.filter((f) => /'sp-overlay|setAttribute\('aria-modal'/.test(read(f)))
ok(handDialogs.length === 0, `no file hand-builds a modal overlay any more — every one is createDialog (found in: ${handDialogs.join(', ') || 'none'})`)
ok(/createPanel\(/.test(editor) && !/private makeResizer\(/.test(editor) && !/sp-pane-tab/.test(css),
'both side panels are the kernel panel; spaces\' own resizer and chevron are gone')
// THE TOP BAR IS SLIDES' BAR. Its numbers are read out of slides' own source,
// so the day slides changes its bar this rig says the two apps have parted,
// rather than asserting a copy of a number that has already moved.
const slidesCss = readFileSync(join(root, 'slides/src/styles.css'), 'utf8')
const slidesEd = readFileSync(join(root, 'slides/src/editor/editor.ts'), 'utf8')
const edBar = /\n\.ed-topbar \{([\s\S]*?)\n\}/.exec(slidesCss)?.[1] ?? ''
const SLIDES_BAR = {
gap: /\bgap:\s*(\d+px)/.exec(edBar)?.[1],
// padding: max(8px, …top…) max(14px, …right…) 8px max(14px, …left…)
padY: /padding:\s*max\((\d+px)/.exec(edBar)?.[1],
padX: [...(/padding:([^;]*);/.exec(edBar)?.[1] ?? '').matchAll(/max\((\d+px)/g)][1]?.[1],
}
ok(!!(SLIDES_BAR.gap && SLIDES_BAR.padY && SLIDES_BAR.padX), `slides' bar values can be read from its stylesheet (${JSON.stringify(SLIDES_BAR)})`)
const spBar = /\n\.sp-bar \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? ''
ok(new RegExp(`\\bgap:\\s*${SLIDES_BAR.gap}`).test(spBar) && new RegExp(`padding:\\s*${SLIDES_BAR.padY} max\\(${SLIDES_BAR.padX}`).test(spBar),
`.sp-bar declares slides' padding and gap (${SLIDES_BAR.padY}/${SLIDES_BAR.padX}, gap ${SLIDES_BAR.gap})`)
// …and slides' fit: the title floor and the phone width are its constants
const edFit = slidesEd.slice(slidesEd.indexOf(' private fitTopbar() {'))
const slidesFloor = /getBoundingClientRect\(\)\.width < (\d+)/.exec(edFit)?.[1]
const slidesPhone = /innerWidth <= (\d+)/.exec(edFit)?.[1]
const topbar = read('topbar.ts')
ok(!!slidesFloor && !!slidesPhone &&
new RegExp(`titleFloor \\?\\? ${slidesFloor}\\b`).test(topbar) && new RegExp(`phoneWidth \\?\\? ${slidesPhone}\\b`).test(topbar) &&
new RegExp(`max-width: ${slidesPhone}px\\) \\{\\n \\.sp-bar, \\.sp-bar\\.sp-bar-compact`).test(css),
`the fit is slides': title floor ${slidesFloor}px, phone ${slidesPhone}px, the same width in the phone stylesheet`)
ok(/createTopbarFit\(bar,/.test(editor) && !/private fitTopbar\(/.test(editor),
'the editor fits its bar through topbar.ts, not a private hand-copy')
// WHAT OPENS FROM THE BAR IS SLIDES' TOO. The menu's numbers are read out of
// slides' stylesheet (`.ed-menu`, `.ed-btn`, `.ed-menu-sep`, `.ed-save-menu`),
// and the browser half holds spaces' COMPUTED values to them — so the day
// slides changes a menu, this rig says the two apps have parted.
const block = (sel: string) => new RegExp(`\\n${sel.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\{([\\s\\S]*?)\\n\\}`).exec(slidesCss)?.[1] ?? ''
const decl = (b: string, prop: string) => new RegExp(`(?:^|[;\\s])${prop}:\\s*([^;]+);`).exec(b)?.[1]?.trim()
const edMenu = block('.ed-menu'), edBtn = block('.ed-btn')
const slidesRoot = /\n:root, :root\[data-theme="light"\] \{([\s\S]*?)\n\}/.exec(slidesCss)?.[1] ?? ''
const SLIDES_MENU = {
offset: /calc\(100% \+ (\d+px)\)/.exec(decl(edMenu, 'top') ?? '')?.[1],
pad: decl(edMenu, 'padding'),
radius: /\n\s*--radius:\s*([^;]+);/.exec(slidesCss)?.[1],
shadow: decl(edMenu, 'box-shadow'),
rowFont: decl(edBtn, 'font-size'),
rowPad: decl(edBtn, 'padding'),
rowGap: decl(edBtn, 'gap'),
rowRadius: decl(edBtn, 'border-radius'),
rowFrame: decl(edBtn, 'border'),
rowInk: /var\((--[a-z0-9-]+)\)/.exec(decl(edBtn, 'color') ?? '')?.[1],
sepMargin: /\.ed-menu-sep \{[^}]*margin:\s*([^;]+);/.exec(slidesCss)?.[1],
saveFont: /\.ed-save-menu \.ed-btn \{ font-size:\s*([^;]+);/.exec(slidesCss)?.[1],
}
SLIDES_MENU.rowInk = SLIDES_MENU.rowInk ? decl(slidesRoot, SLIDES_MENU.rowInk) : undefined
// The keyboard ring (`.ed-btn:focus-visible` outside, `.ed-menu
// .ed-btn:focus-visible` inside)
const ringOut = /\n\.ed-btn:focus-visible[^{]*\{([^}]*)\}/.exec(slidesCss)?.[1] ?? ''
const SLIDES_RING = {
outline: /outline:\s*([^;]+);/.exec(ringOut)?.[1]?.trim(),
outside: /outline-offset:\s*([^;]+);/.exec(ringOut)?.[1]?.trim(),
inside: /\n\.ed-menu \.ed-btn:focus-visible \{[^}]*outline-offset:\s*([^;]+);/.exec(slidesCss)?.[1]?.trim(),
}
// Stacked below slides #573, where slides gains the ring: until it lands, a
// slides checkout without it is held to the kernel's ring, and the check says so.
const hasRing = /\.ed-btn:focus-visible/.test(slidesCss)
const ringRead = Object.values(SLIDES_RING).every(Boolean)
if (!hasRing) Object.assign(SLIDES_RING, { outline: '2px solid var(--accent-ink)', outside: '2px', inside: '-2px' })
ok(ringRead || !hasRing, `slides' keyboard ring is read from its stylesheet where it has it (${hasRing ? 'slides' : 'kernel ruling'}; ${JSON.stringify(SLIDES_RING)})`)
const ringInk = /var\((--[a-z0-9-]+)\)/.exec(SLIDES_RING.outline ?? '')?.[1]
ok(Object.values(SLIDES_MENU).every(Boolean), `slides' menu values can be read from its stylesheet (${JSON.stringify(SLIDES_MENU)})`)
// THE SAVE MENU IS SLIDES' SAVE MENU: the document-level commands, in slides'
// order wherever spaces has the same command. Slides' order is read from its
// buildSaveAsItems; spaces' from doccmds.ts SAVE_ORDER, which the browser half
// then holds the rendered menu to.
const saveFn = slidesEd.slice(slidesEd.indexOf(' private buildSaveAsItems('), slidesEd.indexOf(' private fillPhoneSaveAs('))
const slidesSave = [...saveFn.matchAll(/item\(ICONS\.\w+, t\('([^']+)'\)/g)].map((m) => m[1])
const doccmds = read('doccmds.ts')
const SAVE_ORDER: string[] = JSON.parse(('[' + (/export const SAVE_ORDER = \[([\s\S]*?)\]/.exec(doccmds)?.[1] ?? '') + ']').replace(/'/g, '"').replace(/,\s*\]$/, ']'))
// spaces' command for each of slides' (null: spaces has none)
const EQUIV: Record<string, string | null> = {
'Save a copy…': 'Save a copy…', 'Duplicate as new deck…': 'Duplicate as new space…',
'Export slides as images…': 'Export as Markdown…', 'Encrypt with password…': 'Encrypt with password…',
'Change password…': null, 'Remove password': null,
'Version history…': 'Version history…', 'Copy document JSON': 'Copy document JSON',
'Copy compact JSON (for agents)': null, 'Replace from JSON…': 'Replace from JSON…', 'Start from scratch…': null,
// slides' way in from another format, in the slot spaces gives its own
'Import PowerPoint…': 'Import Markdown…',
// the converter's other direction; spaces has no PowerPoint form to export
'Export for PowerPoint…': null,
}
const unmapped = slidesSave.filter((l) => !(l in EQUIV))
ok(slidesSave.length >= 9 && unmapped.length === 0, `every row of slides' Save menu has an entry in the equivalence table (${slidesSave.length} rows; new: ${unmapped.join(', ') || 'none'})`)
const wantOrder = slidesSave.map((l) => EQUIV[l]).filter((x): x is string => !!x)
const got = wantOrder.map((l) => SAVE_ORDER.indexOf(l))
ok(got.every((i) => i >= 0) && got.every((i, k) => k === 0 || i > got[k - 1]),
`spaces' Save menu holds slides' document commands in slides' order (${wantOrder.join(' · ')} at ${got.join(',')})`)
// THE INSERT GROUP IS SLIDES' INSERT GROUP (DECISIONS 2026-09-26): one
// button per kind, a menu only where the kind has variants, and ONE table of
// families (inserts.ts) that the bar and the `/` menu both read.
const inserts = read('inserts.ts')
ok(/for \(const f of insertFamilies\(\)\)/.test(editor) && /const sections = insertSections\(\)/.test(editor)
&& !/MENU_SPECS/.test(editor) && !/SLASH_ITEMS/.test(editor),
'the bar\'s insert group and the / menu both come from inserts.ts — neither keeps its own list')
ok(/export function unplacedTypes\(\)/.test(inserts) && /MENU_SPECS/.test(inserts),
'inserts.ts can say which listed block types no family places (the browser half holds it to none)')
// The block registry's LISTED types, read from blocks.ts: each spec is a
// `type: '…', label: '…'` entry, and `unlisted: true` before the next one
// keeps it out of every menu.
const blocksSrc = read('blocks.ts')
const specAt = [...blocksSrc.matchAll(/\btype: '(\w+)', label: '/g)]
const LISTED = specAt.filter((m, i) => !/unlisted: true/.test(blocksSrc.slice(m.index, specAt[i + 1]?.index ?? blocksSrc.length))).map((m) => m[1])
ok(LISTED.length >= 15 && LISTED.includes('p') && !LISTED.includes('prop'), `the registry's listed block types can be read from blocks.ts (${LISTED.join(', ')})`)
// Embed sits in Image ▾ beside Link to page (interim, 2026-10-09: a bar
// button of its own tipped the bar out of slides' width at 1440), so it is in
// the Image family's members below, not here.
// The chart of progress sits in View ▾ behind a rule for the same reason
// (interim, 2026-10-10): a Chart button of its own tipped the bar out of
// slides' width at 1440 — measured, it went compact. What the group should
// show on THIS build: a Code menu once maths joins it.
const has = (t: string) => LISTED.includes(t)
const WANT_GROUP = ['Text ▾', 'Image ▾', 'Table', 'View ▾', has('math') ? 'Code ▾' : 'Code', 'Comment']
// slides' numbers for its insert buttons and their group, read from its stylesheet
const SLIDES_INS = {
groupGap: decl(block('.ed-group'), 'gap'),
font: decl(edBtn, 'font-size'), pad: decl(edBtn, 'padding'), gap: decl(edBtn, 'gap'),
radius: decl(edBtn, 'border-radius'),
hover: /var\((--[a-z0-9-]+)\)/.exec(/\n\.ed-btn:hover \{ background:\s*([^;]+);/.exec(slidesCss)?.[1] ?? '')?.[1],
menuMin: decl(edMenu, 'min-width'),
// the insert buttons' icon, from slides' icon factory
icon: /width="(\d+)" height="\1"/.exec(readFileSync(join(root, 'slides/src/icons.ts'), 'utf8'))?.[1],
}
ok(Object.values(SLIDES_INS).every(Boolean), `slides' insert-button values can be read from its source (${JSON.stringify(SLIDES_INS)})`)
// THE READING VIEW PILL IS SLIDES' SLIDESHOW PILL (maintainer, 2026-10-20).
// Reading view left the bar for a floating button, shaped and placed as
// slides' `.ed-present-pill` in `.ed-corner-br`: the numbers are read out of
// slides' stylesheet and the browser half holds the computed pill to them.
const pillB = block('.ed-present-pill'), pillMain = /\n\.ed-present-pill \.ed-pill-main \{([\s\S]*?)\n\}/.exec(slidesCss)?.[1] ?? ''
const cornerB = block('.ed-corner-br')
const SLIDES_PILL = {
radius: decl(pillB, 'border-radius'),
border: decl(pillB, 'border'),
shadow: decl(pillB, 'box-shadow'),
weight: decl(pillMain, 'font-weight'),
padY: decl(pillMain, 'padding-block'),
// inset-inline-end: max(14px, …) / bottom: max(14px, …)
end: /max\((\d+px)/.exec(decl(cornerB, 'inset-inline-end') ?? '')?.[1],
bottom: /max\((\d+px)/.exec(decl(cornerB, 'bottom') ?? '')?.[1],
hover: /var\((--[a-z0-9-]+)\)/.exec(/\n\.ed-present-pill \.ed-btn:hover \{ background:\s*([^;]+);/.exec(slidesCss)?.[1] ?? '')?.[1],
}
ok(Object.values(SLIDES_PILL).every(Boolean), `slides' Slideshow pill values can be read from its stylesheet (${JSON.stringify(SLIDES_PILL)})`)
const readFab = /\.sp-corner > \.sp-readfab \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? ''
ok(/inset-inline-end:/.test(readFab) && !/\b(left|right):/.test(readFab),
'the Reading view pill sits at the bottom-END corner by a logical inset, so RTL mirrors it as slides\' does')
ok(new RegExp(`\\.sp-corner > \\.sp-readfab:hover \\{ background: var\\(${SLIDES_PILL.hover}\\)`).test(css),
`its hover is slides' pill hover, var(${SLIDES_PILL.hover})`)
ok(/\.sp-app\.sp-sealed \.sp-readtoggle,/.test(css) && /classList\.add\('sp-readfab', 'sp-readtoggle'\)/.test(editor),
'a SEALED reading copy hides the pill: it carries .sp-readtoggle, which the sealed rule removes')
ok(!/icon: 'eye'|icon: 'graph'|sp-insp-toggle/.test(editor) && !/sp-insp-toggle/.test(css),
'the bar builds no Reading view, Graph or Properties button any more, and no rule styles one')
// ————— 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
// A cold Chrome on a CI runner took 10.1s to write DevToolsActivePort in the
// last green run, against a 10s wait — it passed by a hair, and slower starts
// failed main three times on 2026-10-07 with a bare ENOENT. So: wait up to
// 45s per attempt, stop early if Chrome exits, relaunch ONCE on a fresh
// profile, and say why (exit code + stderr) instead of throwing on a file.
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
const launch = () => {
const dir = mkdtempSync(join(tmpdir(), 'bento-spaces-chrome-'))
const proc = 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=' + dir, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] })
const state = { exited: null as number | null, stderr: '' }
proc.stderr?.on('data', (d) => { if (state.stderr.length < 4000) state.stderr += String(d) })
proc.on('exit', (code) => { state.exited = code ?? -1 })
return { dir, proc, state }
}
let { dir: profile, proc: child, state } = launch()
try {
let portFile = join(profile, 'DevToolsActivePort')
for (let attempt = 1; ; attempt++) {
const started = Date.now()
while (!existsSync(portFile) && state.exited === null && Date.now() - started < 45_000) await sleep(100)
if (existsSync(portFile)) {
console.log(` (Chrome up in ${((Date.now() - started) / 1000).toFixed(1)}s${attempt > 1 ? ', on the relaunch' : ''})`)
break
}
const why = `${state.exited === null ? 'no DevToolsActivePort after 45s' : `exited with ${state.exited}`}: ${state.stderr.trim().slice(-1500)}`
if (attempt === 2) throw new Error(`Chrome did not start on two attempts (${why})`)
console.log(` (Chrome did not start — ${why.split('\n')[0]} — relaunching once)`)
try { child.kill('SIGKILL') } catch { /* gone */ }
try { rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) } catch { /* temp dir */ }
;({ dir: profile, proc: child, state } = launch())
portFile = join(profile, 'DevToolsActivePort')
}
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)`
// one row's shape: its height, whether a description is drawn, its tooltip,
// its accessible name, and where its accessible description lives
const ROWSHAPE = (rows: string, nameSel: string) => `(() => ${rows}.map(r => { const d = document.getElementById(r.getAttribute('aria-describedby') || ''); const dr = d?.getBoundingClientRect(); return { inside: !!d && r.contains(d), name: r.querySelector(${JSON.stringify(nameSel)})?.textContent, h: Math.round(r.getBoundingClientRect().height), drawn: !!r.querySelector('.bkm-hint'), title: r.title, aria: r.getAttribute('aria-label'), desc: d?.textContent ?? null, hidden: !!dr && dr.width <= 1 && dr.height <= 1 } }))()`
const rowOk = (r: any) => !r.drawn && !!r.title && r.title === r.desc && r.aria === r.name && r.hidden && r.inside
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')
// ⋯ is slides' folded ⋯: absent from a bar that has room
ok(await js<boolean>(`!(${TRIG('More actions')}) || (${TRIG('More actions')}).getBoundingClientRect().width === 0`),
'at 1440 there is no ⋯ — as in slides, it exists only once the bar folds')
const SAVEM = TRIG('Save as… — copy, new space, password')
await tap(SAVEM)
const more = await js<any>(`(() => { const m = ${OPEN}; const t = ${SAVEM}; 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', `Save ▾ 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('Save a copy') && second.startsWith('Duplicate as new space'), `arrow keys walk the Save rows ("${first}" → "${second}")`)
// the ring on a row reached by the keyboard is slides': --accent-ink, INSIDE
const rowRing = await js<any>(`(() => { const e = document.activeElement; const c = getComputedStyle(e); return { style: c.outlineStyle, w: c.outlineWidth, color: c.outlineColor, off: c.outlineOffset, want: getComputedStyle(document.documentElement).getPropertyValue(${JSON.stringify(ringInk)}).trim() } })()`)
const ringW = /(\d+px)/.exec(SLIDES_RING.outline ?? '')?.[1]
const hexOf = (rgb: string) => '#' + (rgb.match(/\d+/g) ?? []).slice(0, 3).map((n) => (+n).toString(16).padStart(2, '0')).join('')
ok(rowRing.style === 'solid' && rowRing.w === ringW && hexOf(rowRing.color) === rowRing.want && rowRing.off === SLIDES_RING.inside,
`a menu row's keyboard ring is slides': ${SLIDES_RING.outline}, offset ${SLIDES_RING.inside} (${JSON.stringify(rowRing)})`)
// SAVE AND SHARE ARE ONE LINE A ROW, as slides' (the maintainer's revisions
// of D2, 2026-09-26): what a row does is its hover tooltip (`title` on the
// row itself) and — for a screen reader — its accessible description via
// aria-describedby on an element that is not drawn, inside the row. The name
// alone is the accessible name.
const one = await js<any>(ROWSHAPE(`[...(${OPEN}).querySelectorAll('.bkm-item')]`, '.bkm-text'))
const bad = one.filter((r: any) => r.h !== 30 || !rowOk(r))
ok(one.length >= 9 && bad.length === 0,
`every Save row is one 30px line whose description is its tooltip and its hidden aria-describedby, the name alone its name (${one.length} rows${bad.length ? '; wrong: ' + JSON.stringify(bad.slice(0, 2)) : ''})`)
// …and it IS slides' Save menu: the rows, in order, and the rule where slides has it
const saveRows = await js<any>(`(() => { const m = ${OPEN}; return [...m.children].map(c => c.classList.contains('bkm-sep') ? '—' : (c.querySelector('.bkm-text')?.textContent ?? '')) })()`)
// in order; a build may carry more exports in the export slot (the tour's
// page-as-slides), so SAVE_ORDER must be an in-order subsequence
const shown = saveRows.filter((x: string) => x !== '—')
let seenAt = -1
const inOrder = SAVE_ORDER.every((l) => { const i = shown.indexOf(l); const okay = i > seenAt; seenAt = i; return okay })
const extra = shown.filter((l: string) => !SAVE_ORDER.includes(l))
ok(inOrder && extra.every((l: string) => /^Export /.test(l)),
`the Save menu renders the document commands in order (${saveRows.join(' · ')})`)
ok(saveRows.indexOf('—') === saveRows.indexOf('Version history…') - 1 && saveRows.indexOf('—') > saveRows.indexOf('Encrypt with password…'),
'a rule sets the timeline and JSON rows apart from the file rows, where slides has its separator')
// …measured against slides' own stylesheet
const mm = await js<any>(`(() => { const m = ${OPEN}, t = ${SAVEM}; const c = getComputedStyle(m); const row = [...m.querySelectorAll('.bkm-item')].find(r => r.textContent.startsWith('Version history')); const rc = getComputedStyle(row); const tx = getComputedStyle(row.querySelector('.bkm-text')); const ico = getComputedStyle(row.querySelector('.bkm-ico')); const sep = getComputedStyle(m.querySelector('.bkm-sep'));
return { offset: Math.round(m.getBoundingClientRect().top - t.getBoundingClientRect().bottom) + 'px', pad: c.padding, radius: c.borderTopLeftRadius, shadow: c.boxShadow, rowFont: tx.fontSize, weight: tx.fontWeight, rowPad: rc.padding, rowGap: rc.columnGap, rowRadius: rc.borderTopLeftRadius, frame: rc.borderTopWidth + ' ' + rc.borderTopStyle, ink: tx.color, icoInk: ico.color, h: Math.round(row.getBoundingClientRect().height), sepMargin: sep.margin } })()`)
const nums = (x: string | undefined) => (x ?? '').match(/[\d.]+/g)?.map(Number).join(',') ?? ''
const hexRgb = (h: string | undefined) => { const x = (h ?? '').replace('#', ''); return `rgb(${parseInt(x.slice(0, 2), 16)}, ${parseInt(x.slice(2, 4), 16)}, ${parseInt(x.slice(4, 6), 16)})` }
const frameW = /(\d+px)/.exec(SLIDES_MENU.rowFrame ?? '')?.[1]
const want = { offset: SLIDES_MENU.offset, pad: SLIDES_MENU.pad, radius: SLIDES_MENU.radius, rowFont: SLIDES_MENU.saveFont, rowPad: SLIDES_MENU.rowPad, rowGap: SLIDES_MENU.rowGap, rowRadius: SLIDES_MENU.rowRadius, sepMargin: SLIDES_MENU.sepMargin }
const off = Object.entries(want).filter(([k, v]) => mm[k] !== v).map(([k, v]) => `${k} ${mm[k]} ≠ ${v}`)
// computed: "rgba(r, g, b, a) x y blur spread"; slides: "x y blur rgb(r g b / a)"
const cs = nums(mm.shadow).split(','), ss = nums(SLIDES_MENU.shadow).split(',')
if (cs.slice(0, 4).join() !== ss.slice(3, 7).join() || cs.slice(4, 7).join() !== ss.slice(0, 3).join()) off.push(`shadow ${mm.shadow} ≠ ${SLIDES_MENU.shadow}`)
if (mm.frame !== `${frameW} solid`) off.push(`frame ${mm.frame} ≠ ${SLIDES_MENU.rowFrame}`)
if (mm.ink !== hexRgb(SLIDES_MENU.rowInk) || mm.icoInk !== mm.ink) off.push(`ink ${mm.ink}/${mm.icoInk} ≠ ${SLIDES_MENU.rowInk}`)
if (mm.weight !== '400' || mm.h !== 30) off.push(`row ${mm.weight} ${mm.h}px, slides' is 400 30px`)
ok(off.length === 0, `the Save menu computes to slides' stylesheet values (.ed-save-menu .ed-btn) — offset, padding, corner, shadow, 30px rows at ${SLIDES_MENU.saveFont}/400 in ${SLIDES_MENU.rowInk}, separators (${off.join('; ') || JSON.stringify(mm)})`)
await key('Escape', 0, 'Escape')
const afterEsc = await js<any>(`({ open: !!(${OPEN}), exp: (${SAVEM}).getAttribute('aria-expanded'), focus: document.activeElement === (${SAVEM}) })`)
ok(!afterEsc.open && afterEsc.exp === 'false' && afterEsc.focus, `Escape closes Save ▾, clears aria-expanded and puts focus back on its trigger (${JSON.stringify(afterEsc)})`)
// …where a bar button's ring is drawn OUTSIDE, on the bar
const barRing = await js<any>(`(() => { const e = document.activeElement; const c = getComputedStyle(e); return { fv: e.matches(':focus-visible'), style: c.outlineStyle, w: c.outlineWidth, off: c.outlineOffset } })()`)
ok(barRing.fv && barRing.style === 'solid' && barRing.w === /(\d+px)/.exec(SLIDES_RING.outline ?? '')?.[1] && barRing.off === SLIDES_RING.outside,
`a bar button's keyboard ring is slides': outside, offset ${SLIDES_RING.outside} (${JSON.stringify(barRing)})`)
// …and every Share action is the same row: one 30px line, its description
// the tooltip and the hidden aria-describedby (slides #573)
await tap(`document.querySelector('.sp-bar .sp-live')`)
const acts = await js<any>(ROWSHAPE(`[...document.querySelectorAll('.sp-pop .sp-paction')]`, '.sp-paction-name'))
const badActs = acts.filter((r: any) => r.h !== 30 || !rowOk(r))
ok(acts.length >= 3 && badActs.length === 0,
`every Share action is one 30px line whose description is its tooltip and its hidden aria-describedby, the name alone its name (${acts.length} actions${badActs.length ? '; wrong: ' + JSON.stringify(badActs.slice(0, 2)) : ''})`)
// …a plain menu row as slides' (#573): nothing at rest — no fill, no frame,
// no filled primary — at the Save rows' size, and adjacent rows touching
const plain = await js<any>(`(() => { const rows = [...document.querySelectorAll('.sp-pop .sp-paction')]; const save = null; const out = rows.map(r => { const c = getComputedStyle(r); return { bg: c.backgroundColor, frame: c.borderTopColor, font: c.fontSize, pad: c.padding } }); const touch = rows.every((r, i) => { const n = rows[i + 1]; return !n || n.previousElementSibling !== r || Math.round(n.getBoundingClientRect().top - r.getBoundingClientRect().bottom) === 0 }); return { out, touch } })()`)
const loud = plain.out.filter((r: any) => r.bg !== 'rgba(0, 0, 0, 0)' || r.frame !== 'rgba(0, 0, 0, 0)' || r.font !== SLIDES_MENU.saveFont || r.pad !== SLIDES_MENU.rowPad)
ok(loud.length === 0 && plain.touch,
`Share's actions are plain rows — no fill or frame at rest, no primary, ${SLIDES_MENU.saveFont} in ${SLIDES_MENU.rowPad}, adjacent rows touching (${loud.length ? JSON.stringify(loud[0]) : 'ok'}; touch ${plain.touch})`)
await key('Escape', 0, 'Escape')
// NO TOP-BAR SURFACE DRAWS A SECOND-LINE DESCRIPTION. Open each of them and
// look for one: a kernel hint, or any described row whose description is
// painted bigger than a pixel.
const drawn: string[] = []
const DRAWN = `(() => { const out = []; const scope = [...document.querySelectorAll('.bkm-open > .bkm-menu, .sp-pop')].filter(e => e.getBoundingClientRect().height > 0); for (const m of scope) { for (const h of m.querySelectorAll('.bkm-hint')) if (h.getBoundingClientRect().height > 1) out.push('hint: ' + h.textContent.slice(0, 30)); for (const r of m.querySelectorAll('[aria-describedby]')) { const d = document.getElementById(r.getAttribute('aria-describedby')); const b = d?.getBoundingClientRect(); if (b && (b.width > 1 || b.height > 1)) out.push('drawn: ' + d.textContent.slice(0, 30)) } } return out })()`
for (const trig of ['Add text — a heading, a list, a quote, a callout or a divider', 'Add an image, a video, audio or a card', 'Save as… — copy, new space, password', 'Language']) {
await tap(TRIG(trig)); drawn.push(...(await js<string[]>(DRAWN)).map((x) => `${trig.split(' ')[0]} ${x}`)); await key('Escape', 0, 'Escape')
}
await tap(`document.querySelector('.sp-bar .sp-live')`); drawn.push(...(await js<string[]>(DRAWN)).map((x) => `Share ${x}`)); await key('Escape', 0, 'Escape')
ok(drawn.length === 0, `no surface opened from the bar draws a second-line description — Text, Image, Save, Language, Share (${drawn.join('; ') || 'none'})`)
await tap(SAVEM)
await tap(`document.querySelector('.sp-group-insert .bkm-trigger')`)
const exclusive = await js<number>(`document.querySelectorAll('.bkm-open').length`)
ok(exclusive === 1, `opening Text ▾ shuts Save ▾ — one menu open at a time (${exclusive} open)`)
await click(900, 700)
ok(!(await js<boolean>(`!!(${OPEN})`)), 'a press outside closes the menu')
// ——— the insert group is slides' insert group ———
const GROUP = `document.querySelector('.sp-bar .sp-group-insert')`
// the group's buttons, in order: a direct button carries its item's key; a
// menu's trigger is named by its family
const gm = await js<any>(`(() => { const g = ${GROUP}; const bs = [...g.querySelectorAll(':scope > button, :scope > .bkm > .bkm-trigger')]
const c = (e) => getComputedStyle(e)
return { gap: c(g).columnGap, btns: bs.map(b => ({ name: (b.getAttribute('aria-label') || '').split(' — ')[0], label: b.querySelector('.sp-btnlabel')?.textContent, menu: b.classList.contains('bkm-trigger'),
font: c(b).fontSize, pad: c(b).padding, gap: c(b).columnGap, radius: c(b).borderTopLeftRadius, h: Math.round(b.getBoundingClientRect().height),
icon: Math.round(b.querySelector('svg')?.getBoundingClientRect().width ?? 0) })) } })()`)
const labels = gm.btns.map((b: any) => b.label)
void labels
ok(JSON.stringify(gm.btns.map((b: any) => b.label + (b.menu ? ' ▾' : ''))) === JSON.stringify(WANT_GROUP),
`the bar's insert group is one button per kind, a menu only where the kind has variants, Comment last (${gm.btns.map((b: any) => b.label + (b.menu ? ' ▾' : '')).join(' · ')})`)
const insOff = gm.btns.flatMap((b: any) => [
b.font !== SLIDES_INS.font && `${b.label} font ${b.font}`, b.pad !== SLIDES_INS.pad && `${b.label} padding ${b.pad}`,
b.gap !== SLIDES_INS.gap && `${b.label} gap ${b.gap}`, b.radius !== SLIDES_INS.radius && `${b.label} radius ${b.radius}`,
b.h !== 30 && `${b.label} ${b.h}px tall`, String(b.icon) !== SLIDES_INS.icon && `${b.label} icon ${b.icon}px`,
]).filter(Boolean)
if (gm.gap !== SLIDES_INS.groupGap) insOff.push(`group gap ${gm.gap}`)
ok(insOff.length === 0, `every insert button is slides' .ed-btn — ${SLIDES_INS.font}, ${SLIDES_INS.pad}, gap ${SLIDES_INS.gap}, radius ${SLIDES_INS.radius}, 30px, a ${SLIDES_INS.icon}px icon — ${SLIDES_INS.groupGap} apart as .ed-group (${insOff.join('; ') || 'all match'})`)
// …and slides' hover: the fill is the same token slides' .ed-btn:hover names
const hp = await at(`${GROUP}.querySelector('button[data-insert="table"]')`)
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: hp!.x, y: hp!.y })
await sleep(150)
const hov = await js<any>(`(() => { const b = ${GROUP}.querySelector('button[data-insert="table"]'); const probe = document.createElement('i'); probe.style.background = 'var(${SLIDES_INS.hover})'; document.body.append(probe); const want = getComputedStyle(probe).backgroundColor; probe.remove(); return { got: getComputedStyle(b).backgroundColor, want } })()`)
ok(hov.got === hov.want && hov.want !== 'rgba(0, 0, 0, 0)', `an insert button's hover fills with slides' ${SLIDES_INS.hover} (${hov.got}; want ${hov.want})`)
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 900, y: 700 })
// Each menu is slides' Shape menu: 30px rows of 13px words, 4px inside, at
// least as wide as .ed-menu, and it fits the window.
const famRows: Record<string, string[]> = {}
const barCaps: string[] = []
const barSeq: string[] = []
const menuOff: string[] = []
for (const b of gm.btns) {
if (b.label === 'Comment') continue
if (!b.menu) { barSeq.push(await js<string>(`${GROUP}.querySelector('button[aria-label^=${JSON.stringify(b.name)}]').dataset.insert`)); continue }
await tap(`[...${GROUP}.querySelectorAll('.bkm-trigger')].find(t => t.getAttribute('aria-label').startsWith(${JSON.stringify(b.name)}))`)
const mm2 = await js<any>(`(() => { const m = ${OPEN}; const r = m.getBoundingClientRect(); const rows = [...m.querySelectorAll('.bkm-item')]; const c = getComputedStyle(m)
return { keys: rows.map(x => x.dataset.insert), names: rows.map(x => x.querySelector('.bkm-text').textContent), pad: c.padding, w: r.width, bottom: r.bottom, vh: innerHeight,
font: [...new Set(rows.map(x => getComputedStyle(x.querySelector('.bkm-text')).fontSize))], h: [...new Set(rows.map(x => Math.round(x.getBoundingClientRect().height)))] } })()`)
famRows[b.label] = mm2.names
barCaps.push(b.label)
barSeq.push(...mm2.keys)
if (mm2.pad !== SLIDES_MENU.pad || mm2.w < parseFloat(SLIDES_INS.menuMin!) || mm2.bottom > mm2.vh || mm2.font.join() !== SLIDES_INS.font || mm2.h.join() !== '30')
menuOff.push(`${b.label}: ${JSON.stringify({ pad: mm2.pad, w: mm2.w, bottom: mm2.bottom, font: mm2.font, h: mm2.h })}`)
await key('Escape', 0, 'Escape')
}
ok(menuOff.length === 0 && barCaps.length === WANT_GROUP.filter((g) => g.endsWith('▾')).length, `Text ▾, Image ▾ and View ▾ are slides' Shape menu: ${SLIDES_MENU.pad} inside, ≥ ${SLIDES_INS.menuMin} wide, 30px rows at ${SLIDES_INS.font}, inside the window (${menuOff.join('; ') || barCaps.join(', ')})`)
ok(JSON.stringify(famRows.Text) === JSON.stringify(['Text', 'Heading 1', 'Heading 2', 'Heading 3', 'Quote', 'Callout', 'Toggle', 'Bulleted list', 'Numbered list', 'To-do', 'Divider']) &&
JSON.stringify(famRows.Image) === JSON.stringify(['Image', 'Video', 'Audio', 'Link card', 'Link to page', ...(has('embed') ? ['Embed a page'] : [])]) &&
JSON.stringify(famRows.View?.slice(0, 4)) === JSON.stringify(['Board', 'List', 'Table view', 'Gallery']) && famRows.View?.at(-1) === 'Canvas',
`the families hold the approved members, in order (Text: ${famRows.Text?.join(', ')} | Image: ${famRows.Image?.join(', ')} | View: ${famRows.View?.join(', ')})`)
// THE / MENU AGREES: same members, same order, same names, the same captions
const pageBlocks = `(() => { const id = document.querySelector('.sp-treelink.sp-here').getAttribute('href').split('/')[1]; return window.bento.getPage(id).blocks })()`
const firstP = await js<string>(`${pageBlocks}.find(b => b.type === 'p' && !b.parent).id`)
const pristine = await js<string>(`JSON.stringify(${pageBlocks}.map(b => b.id))`)
await js(`(() => { const h = document.querySelector('.sp-main [data-edit="${firstP}"]'); h.focus(); const r = document.createRange(); r.selectNodeContents(h); r.collapse(false); const s = getSelection(); s.removeAllRanges(); s.addRange(r) })()`)
await key('Enter', 0, 'Enter', 13)
await key('/', 0, 'Slash', 191)
await sleep(300)
const slash = await js<any>(`(() => { const p = [...document.querySelectorAll('.sp-pop')].find(x => x.getBoundingClientRect().height > 0); if (!p) return null
return { keys: [...p.querySelectorAll('.sp-result')].map(b => b.dataset.insert), names: Object.fromEntries([...p.querySelectorAll('.sp-result')].map(b => [b.dataset.insert, b.querySelector('strong').textContent])),
caps: [...p.querySelectorAll('.sp-results-cap')].map(c => c.textContent) } })()`)
await key('Escape', 0, 'Escape')
for (let i = 0; i < 6 && (await js<string>(`JSON.stringify(${pageBlocks}.map(b => b.id))`)) !== pristine; i++) await js(`window.bento.undo(); 1`)
const sameNames = Object.entries(famRows).every(([, names]) => names.every((n) => Object.values(slash?.names ?? {}).includes(n)))
ok(!!slash && JSON.stringify(slash.keys) === JSON.stringify(barSeq) && JSON.stringify(slash.caps) === JSON.stringify(barCaps) && sameNames,
`the / menu lists the bar's families: the same members in the same order under the same names, captioned where the bar has a menu (bar ${barSeq.join(',')} | / ${slash?.keys?.join(',')} | captions ${slash?.caps?.join(', ')})`)
const slashTypes = new Set((slash?.keys ?? []).map((k: string) => k.split(':')[0]))
const homeless = LISTED.filter((t) => !slashTypes.has(t))
ok(!!slash && homeless.length === 0 && slash.keys.length === new Set(slash.keys).size,
`every block type the registry lists has a place in a family, and no member is listed twice (${slash?.keys?.length} members; no place: ${homeless.join(', ') || 'none'})`)
// EVERY INSERT GOES AFTER THE BLOCK HOLDING THE CARET, AS ONE UNDO STEP,
// and the caret lands in it where it has somewhere to land.
const TEXTUAL = new Set(['p', 'h1', 'h2', 'h3', 'quote', 'callout', 'toggle', 'bullet', 'number', 'todo', 'code'])
const placed: string[] = []
for (const k of barSeq) {
const before = await js<any[]>(`${pageBlocks}.map(b => b.id)`)
await js(`(() => { const h = document.querySelector('.sp-main [data-edit="${firstP}"]'); h.focus(); return 1 })()`)
const direct = await js<boolean>(`!!${GROUP}.querySelector(':scope > button[data-insert="${k}"]')`)
if (direct) await tap(`${GROUP}.querySelector(':scope > button[data-insert="${k}"]')`)
else {
const fam = await js<string>(`(() => { for (const m of ${GROUP}.querySelectorAll('.bkm')) { m.querySelector('.bkm-trigger').click(); const hit = !!m.querySelector('.bkm-item[data-insert="${k}"]'); document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); if (hit) return m.querySelector('.bkm-trigger').getAttribute('aria-label') } return null })()`)
await tap(`[...${GROUP}.querySelectorAll('.bkm-trigger')].find(t => t.getAttribute('aria-label') === ${JSON.stringify(fam)})`)
await tap(`(${OPEN}).querySelector('.bkm-item[data-insert="${k}"]')`)
}
// a page card asks which page first: take the first one offered
if (k === 'pagelink' || k === 'embed') await tap(`[...document.querySelectorAll('[aria-modal="true"] .sp-result')][0]`)
await sleep(150)
const after = await js<any>(`(() => { const bs = ${pageBlocks}; const ae = document.activeElement?.closest?.('[data-block-id]')?.dataset.blockId; return { ids: bs.map(b => b.id), types: bs.map(b => b.type), layout: bs.map(b => b.layout ?? null), kind: bs.map(b => b.kind ?? null), ae } })()`)
const fresh = after.ids.filter((i: string) => !before.includes(i))
const at = after.ids.indexOf(fresh[0])
const type = after.types[at]
const wantType = k.split(':')[0]
const variant = k.split(':')[1]
const variantOk = !variant || (wantType === 'view' ? (variant === 'board' ? after.layout[at] === null : after.layout[at] === variant) : after.kind[at] === variant)
const focusOk = !TEXTUAL.has(type) || after.ae === fresh[0]
// Escape whatever it opened (the link card), then one undo
await key('Escape', 0, 'Escape')
await js(`document.querySelector('.sp-main').focus?.(); 1`)
await tap(`document.querySelector('.sp-bar button[aria-label^="Undo"]')`)
const undone = await js<any[]>(`${pageBlocks}.map(b => b.id)`)
const good = fresh.length === 1 && after.ids[at - 1] === firstP && type === wantType && variantOk && focusOk && JSON.stringify(undone) === JSON.stringify(before)
if (!good) placed.push(`${k}: ${JSON.stringify({ fresh: fresh.length, prev: after.ids[at - 1] === firstP, type, variantOk, focusOk, undone: JSON.stringify(undone) === JSON.stringify(before) })}`)
}
ok(placed.length === 0 && barSeq.length >= 20, `each of the ${barSeq.length} bar inserts lands right after the caret's block, is the member it names, takes the caret where it can, and one undo removes it (${placed.join('; ') || 'all'})`)
// …with no caret on the page, at the end
await js(`(() => { const m = document.querySelector('.sp-main'); m.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); document.activeElement?.blur?.(); return 1 })()`)
await tap(`${GROUP}.querySelector('button[data-insert="table"]')`)
const endIns = await js<any>(`(() => { const bs = ${pageBlocks}; return { lastType: bs.at(-1).type } })()`)
await key('Escape', 0, 'Escape')
await tap(`document.querySelector('.sp-bar button[aria-label^="Undo"]')`)
ok(endIns.lastType === 'table', `with no caret on the page a new block goes at the end (${endIns.lastType})`)
// New pages are on the page list's + ▾, with their shortcuts; + alone is New page
await tap(`document.querySelector('.sp-side .sp-newmenu > .bkm-trigger')`)
const np = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; return [...m.querySelectorAll('.bkm-item')].map(r => r.querySelector('.bkm-text').textContent + ' ' + (r.querySelector('.sp-mkbd')?.textContent ?? '')) })()`)
await key('Escape', 0, 'Escape')
const plusTip = await js<string>(`document.querySelector('.sp-side .sp-newpage').getAttribute('aria-label')`)
// (a build with templates adds Templates… after these three)
ok(JSON.stringify(np?.slice(0, 3)) === JSON.stringify(['New page ⌥⌘N', "Today's journal ⇧⌘J", 'New issue ⇧⌘I']) && (np?.slice(3) ?? []).every((r: string) => /^Templates/.test(r)) && /^New page/.test(plusTip),
`the page list's + ▾ holds the ways a page arrives, with their shortcuts, and + itself is New page (${JSON.stringify(np)}; + "${plusTip}")`)
const pagesInBar = await js<boolean>(`[...document.querySelectorAll('.sp-bar .bkm-item, .sp-bar button')].some(b => /New page|Today's journal|New issue/.test(b.textContent))`)
ok(!pagesInBar, 'no new-page command is left in the top bar')
// 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)`)
// focus is on <body> here (blurred above): Escape must still reach the dialog
await key('Escape', 0, 'Escape')
const aboutGone = await js<boolean>(`!document.querySelector('[aria-modal="true"]')`)
ok(aboutGone, 'Escape closes About with the focus nowhere in it')
if (!aboutGone) throw new Error('About did not close; the steps after this need the page')
// WCAG contrast of an element's text against its composited ground
const CONTRAST = `((el) => { const P = (s) => { const m = s.match(/[\\d.]+/g).map(Number); return { r: m[0], g: m[1], b: m[2], a: m[3] ?? 1 } }
const over = (f, b) => ({ r: f.r * f.a + b.r * (1 - f.a), g: f.g * f.a + b.g * (1 - f.a), b: f.b * f.a + b.b * (1 - f.a), a: 1 })
const L = (c) => { const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }; return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b) }
let bg = { r: 255, g: 255, b: 255, a: 1 }; const chain = []; for (let n = el; n && n.nodeType === 1; n = n.parentElement) chain.push(n)
for (const n of chain.reverse()) { const c = P(getComputedStyle(n).backgroundColor); if (c.a > 0) bg = over(c, bg) }
const fg = over(P(getComputedStyle(el).color), bg); const [x, y] = [L(fg), L(bg)].sort((a, b) => b - a); return +((x + 0.05) / (y + 0.05)).toFixed(2) })`
// About: its links read, and its buttons look like buttons
await tap(`document.querySelector('.sp-mark')`)
const about = await js<any>(`(() => { const d = [...document.querySelectorAll('[aria-modal="true"]')].pop(); const a = d.querySelector('.sp-ab-promo a'); const b = [...d.querySelectorAll('.sp-btn:not(.sp-primary)')][0]; return { link: ${CONTRAST}(a), frame: getComputedStyle(b).borderTopColor } })()`)
ok(about.link >= 4.5, `About's links clear 4.5:1 (${about.link}; 3.23 before)`)
ok(!/rgba\(0, 0, 0, 0\)/.test(about.frame), `a dialog's secondary button has a visible frame (${about.frame})`)
await key('Escape', 0, 'Escape')
// D3: an outcome is a notice the reader sees, not a whisper in the bar —
// Copy document JSON from Save ▾ says whether the clipboard took it
await tap(SAVEM)
await tap(`[...document.querySelectorAll('.bkm-open .bkm-item')].find(b => b.textContent.startsWith('Copy document JSON'))`)
const note = await js<any>(`(() => { const n = document.querySelector('.sp-notice.sp-on'); if (!n) return null; const r = n.getBoundingClientRect(); return { text: n.textContent, role: n.getAttribute('role'), cr: ${CONTRAST}(n), z: +getComputedStyle(n).zIndex, onScreen: r.bottom <= innerHeight && r.top > innerHeight / 2 } })()`)
ok(note && note.role === 'status' && note.cr >= 4.5 && note.z > 1000 && note.onScreen && /JSON copied|clipboard/.test(note.text),
`an outcome ("Document JSON copied" / the clipboard refusing) arrives as a notice: announced, legible, above dialogs, at the foot of the window (${JSON.stringify(note)})`)
// ——— dialogs: the kernel's ———
const MODAL = `[...document.querySelectorAll('[aria-modal="true"]')].find(d => d.getBoundingClientRect().height > 0)`
await tap(SAVEM)
await tap(`[...document.querySelectorAll('.bkm-open .bkm-item')].find(b => b.textContent.startsWith('Import Markdown'))`)
const title = await js<any>(`(() => { const d = ${MODAL}; const h = d && d.querySelector('.bkd-title'); if (!h) return null; const c = getComputedStyle(h); return { text: h.textContent, size: c.fontSize, weight: c.fontWeight, labelled: document.getElementById(d.getAttribute('aria-labelledby') || '') === h } })()`)
ok(title && title.size === '17px' && title.weight === '650' && title.labelled,
`a dialog opens on a real title, 17px/650, wired to aria-labelledby (D4) (${JSON.stringify(title)})`)
let outside = 0
for (let i = 0; i < 20; i++) {
await key('Tab', 0, 'Tab', 9)
if (!(await js<boolean>(`(${MODAL})?.contains(document.activeElement) ?? false`))) outside++
}
ok(outside === 0, `Tab never leaves an open dialog (${outside} of 20 presses landed outside; 23 of 25 did before)`)
const blank = await js<any>(`(() => { const r = (${MODAL}).getBoundingClientRect(); return { x: r.right - 12, y: r.bottom - 8 } })()`)
await click(blank.x, blank.y)
// …and with focus nowhere at all: the old handler hung off the backdrop, so
// Escape worked only while focus was inside the card
await js(`document.activeElement?.blur?.(); 1`)
await key('Escape', 0, 'Escape')
ok(!(await js<boolean>(`!!(${MODAL})`)), 'Escape closes a dialog wherever the focus is (it only worked with focus in the card)')
await js(`document.activeElement?.blur?.(); 1`)
await key('?', 8, 'Slash', 191)
const ring = await js<any>(`(() => { const d = ${MODAL}; const c = getComputedStyle(d); return { outline: c.outlineStyle, focusIn: d.contains(document.activeElement) } })()`)
ok(ring.outline === 'none', `the shortcut sheet does not ring the whole card when it opens (outline ${ring.outline})`)
await key('Escape', 0, 'Escape')
await key('k', await MOD(), 'KeyK', 75)
await send('Input.insertText', { text: 'page' })
await sleep(250)
await key('ArrowDown', 0, 'ArrowDown')
const srch = await js<any>(`({ sel: [...document.querySelectorAll('.sp-result')].findIndex(r => r.getAttribute('aria-selected') === 'true'), focusInInput: document.activeElement?.tagName === 'INPUT' })`)
ok(srch.sel === 1 && srch.focusInInput, `ArrowDown walks the search results while the query keeps focus (${JSON.stringify(srch)})`)
await key('Escape', 0, 'Escape')
// ——— panels: the kernel's ———
await js(`document.activeElement?.blur?.(); 1`)
const side = `document.querySelector('.sp-side').closest('.bkp')`
const w0 = await js<number>(`(${side}).getBoundingClientRect().width`)
await key('[', 0, 'BracketLeft', 219)
await sleep(350) // the width animates (.14s); measure where it lands
const shut = await js<any>(`(() => { const t = (${side}).querySelector('.bkp-toggle').getBoundingClientRect(); return { w: (${side}).getBoundingClientRect().width, chev: Math.round(t.x), exp: (${side}).querySelector('.bkp-toggle').getAttribute('aria-expanded') } })()`)
ok(w0 > 200 && shut.w === 0 && shut.chev === 0 && shut.exp === 'false',
`\`[\` collapses the page list to nothing, its chevron docked at the edge (${w0} → ${shut.w}px, chevron at x=${shut.chev})`)
await key('[', 0, 'BracketLeft', 219)
await sleep(350)
const strip = await js<any>(`(() => { const r = (${side}).querySelector('.bkp-resizer').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + 150 } })()`)
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: strip.x, y: strip.y })
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: strip.x, y: strip.y, button: 'left', clickCount: 1 })
for (let i = 1; i <= 6; i++) { await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: strip.x + i * 10, y: strip.y, button: 'left', buttons: 1 }); await sleep(20) }
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: strip.x + 60, y: strip.y, button: 'left', clickCount: 1 })
await sleep(200)
const dragged = await js<any>(`({ w: Math.round((${side}).getBoundingClientRect().width), stored: localStorage.getItem('bento-sp-pane') })`)
ok(Math.abs(dragged.w - (w0 + 60)) <= 2 && dragged.stored === String(dragged.w),
`dragging the strip widens the page list and remembers it for this reader (${w0} → ${dragged.w}, stored ${dragged.stored})`)
// ——— phone ———
await open(true)
const bar = await js<any>(`(() => { const vis = (e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(e).visibility !== 'hidden' }
const bs = [...document.querySelectorAll('.sp-bar button')].filter(vis).map(b => { const r = b.getBoundingClientRect(); return { l: (b.getAttribute('aria-label') || b.title || '').slice(0, 14), w: Math.round(r.width), h: Math.round(r.height) } })
const save = [...document.querySelectorAll('.sp-bar button')].find(b => (b.getAttribute('aria-label') || '').startsWith('Save')).getBoundingClientRect()
return { small: bs.filter(b => b.w < 44 || b.h < 44), save: { w: Math.round(save.width), h: Math.round(save.height) } } })()`)
ok(bar.small.length === 0, `every phone bar control is a 44px target (D5) (too small: ${JSON.stringify(bar.small)})`)
ok(bar.save.w === bar.save.h, `phone Save is a square icon button, not a slab (${bar.save.w}×${bar.save.h}; 66×40 before)`)
await tap(TRIG('More actions'))
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)})`)
await key('Escape', 0, 'Escape')
// the page list is a DRAWER here: opened from the bar, dimmed behind, shut
// by following a page — and none of that is the reader's desktop preference
await tap(`[...document.querySelectorAll('.sp-bar button')].find(b => (b.getAttribute('aria-label') || '').startsWith('Pages'))`)
const drawer = await js<any>(`(() => { const p = document.querySelector('.sp-side').closest('.bkp'); const r = p.getBoundingClientRect(); const row = document.querySelectorAll('.sp-treelink')[1].getBoundingClientRect(); return { drawer: p.classList.contains('bkp-drawer'), w: r.width, scrim: !!document.querySelector('.sp-scrim'), reach: !!document.elementFromPoint(row.x + 20, row.y + row.height / 2)?.closest('.sp-treelink') } })()`)
ok(drawer.drawer && drawer.w > 200 && drawer.scrim && drawer.reach,
`on a phone the page list opens as a drawer over a scrim, its rows reachable (${JSON.stringify(drawer)})`)
const rows = await js<any>(`(() => { const rs = [...document.querySelectorAll('.sp-treelink')].slice(0, 6); const m = rs[0].querySelector('.sp-rowmore').getBoundingClientRect(); return { minRow: Math.min(...rs.map(r => r.getBoundingClientRect().height)), more: [Math.round(m.width), Math.round(m.height)] } })()`)
ok(rows.minRow >= 44 && rows.more[1] >= 44, `page rows and their ⋯ are 44px targets on a phone (row ${rows.minRow}, ⋯ ${rows.more.join('×')}; 28 and 20×20 before)`)
await tap(`document.querySelectorAll('.sp-treelink')[1]`)
const afterNav = await js<any>(`({ w: document.querySelector('.sp-side').closest('.bkp').getBoundingClientRect().width, scrim: !!document.querySelector('.sp-scrim'), stored: localStorage.getItem('bento-sp-pane-closed') })`)
ok(afterNav.w === 0 && !afterNav.scrim && afterNav.stored === null,
`following a page shuts the drawer and its scrim, and writes nothing to the desktop preference (${JSON.stringify(afterNav)})`)
// ——— a phone drawer is not the desktop preference ———
// The row above could never see this bug: it reads the key while still at
// 390. The write happened on the way OUT — crossing back to column width,
// the panel primitive fires onChange with the drawer's state still in
// force, and the editor used to persist whatever that was as the reader's
// desktop choice (measured: every close path, and no drawer at all, left
// both -closed keys at '1' and both columns shut on the next 1440 load).
// So each case: desktop prefs set at 1440 → a 390 load → open the drawer →
// close it one way → resize the LIVE page to 1440 → reload at 1440.
{
const metrics = 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 })
}
// a reload that KEEPS localStorage (open() clears it — the point here is
// what survives)
const load = async () => {
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"))').catch(() => false)) break }
await js('document.activeElement?.blur?.(); 1')
await sleep(400)
}
// EVERYTHING THIS SECTION CHANGES IS PUT BACK at its end: the reader's
// storage and the viewport. Left behind, the '0' it writes for the
// properties panel opened the inspector on the next open() (which clears
// storage only AFTER the load), and the 1440 reachability walk lost the
// "Show properties" chevron it requires.
const SNAP = `JSON.stringify(Object.fromEntries(Object.keys(localStorage).sort().map(k => [k, localStorage.getItem(k)])))`
const before = await js<string>(SNAP)
const PANES = `(() => { const open = (s) => !document.querySelector(s).closest('.bkp').classList.contains('bkp-collapsed'); return { pages: open('.sp-side'), insp: open('.sp-insp'), pane: localStorage.getItem('bento-sp-pane-closed'), ins: localStorage.getItem('bento-sp-insp-closed') } })()`
const BAR = (label: string) => `[...document.querySelectorAll('.sp-bar button')].find(b => (b.getAttribute('aria-label') || '').startsWith(${JSON.stringify(label)}) && b.getBoundingClientRect().width > 0)`
const toggle = async (panel: 'pages' | 'insp') => {
const label = panel === 'pages' ? 'Pages' : 'Properties'
if (await at(BAR(label))) return tap(BAR(label))
await js('document.activeElement?.blur?.(); 1')
await key(panel === 'pages' ? '[' : ']', 0, panel === 'pages' ? 'BracketLeft' : 'BracketRight', panel === 'pages' ? 219 : 221)
}
const closers: Record<string, (panel: 'pages' | 'insp') => Promise<unknown>> = {
'the dimmed backdrop': async (panel) => {
const x = panel === 'pages' ? 385 : 5
const hit = await js<string>(`document.elementFromPoint(${x}, 600)?.className ?? ''`)
if (!/sp-scrim/.test(hit)) throw new Error(`the tap at x=${x} would land on "${hit}", not the scrim`)
await click(x, 600)
},
'following a page': async () => tap(`[...document.querySelectorAll('.sp-side a.sp-treelink:not(.sp-here)')].find(a => a.getBoundingClientRect().width > 0)`),
'its key': async (panel) => { await js('document.activeElement?.blur?.(); 1'); await key(panel === 'pages' ? '[' : ']', 0, panel === 'pages' ? 'BracketLeft' : 'BracketRight', panel === 'pages' ? 219 : 221) },
'nothing (left open)': async () => {},
}
// No "its bar button" case: with a drawer open the scrim covers the bar
// (measured: elementFromPoint at the Pages button is .sp-scrim, and the
// Properties button is folded into ⋯ at 390), so a tap there IS the
// backdrop case. Escape does not shut a drawer at all.
const cases: [panel: 'pages' | 'insp', how: string, pane: '0' | '1', ins: '0' | '1'][] = [
['pages', 'the dimmed backdrop', '0', '0'],
['pages', 'following a page', '0', '0'],
['pages', 'its key', '0', '0'],
// the drawer left OPEN over a desktop preference of SHUT: the resize
// must restore shut, not write the drawer's open
['pages', 'nothing (left open)', '1', '1'],
['insp', 'the dimmed backdrop', '0', '0'],
['insp', 'its key', '0', '0'],
['insp', 'nothing (left open)', '1', '1'],
]
for (const [panel, how, pane, ins] of cases) {
await metrics(false); await load()
await js(`localStorage.setItem('bento-sp-pane-closed', '${pane}'); localStorage.setItem('bento-sp-insp-closed', '${ins}'); 1`)
await metrics(true); await load()
await toggle(panel)
const opened = await js<any>(PANES)
await closers[how](panel)
const shut = await js<any>(PANES)
const leftOpen = how.startsWith('nothing')
// positive control: the drawer really opened, and really shut (or stayed open)
ok(opened[panel] && shut[panel] === leftOpen && shut.pane === pane && shut.ins === ins,
`390, ${panel === 'pages' ? 'page list' : 'properties'} drawer opened and ${leftOpen ? 'left open' : `shut by ${how}`}; the desktop keys are untouched at phone width (${JSON.stringify({ opened: opened[panel], shut })})`)
await metrics(false); await sleep(400)
const live = await js<any>(PANES)
await load()
const reload = await js<any>(PANES)
const want = { pages: pane === '0', insp: ins === '0', pane, ins }
const same = (s: any) => s.pages === want.pages && s.insp === want.insp && s.pane === pane && s.ins === ins
ok(same(live) && same(reload),
`…then 1440: the desktop keys still read ${pane}/${ins} and both columns are as the reader left them on the desktop, live after the resize and after a reload (${JSON.stringify({ live, reload })})`)
}
// …and the DESKTOP controls still persist: a column change is the
// reader's choice and must survive a reload
await metrics(false); await load()
await js(`localStorage.setItem('bento-sp-pane-closed', '0'); localStorage.setItem('bento-sp-insp-closed', '0'); 1`)
await load()
await js('document.activeElement?.blur?.(); 1')
await key('[', 0, 'BracketLeft', 219)
await tap(`document.querySelector('.sp-insp').closest('.bkp').querySelector('.bkp-toggle')`)
const desk = await js<any>(PANES)
await load()
const deskReload = await js<any>(PANES)
ok(!desk.pages && !desk.insp && desk.pane === '1' && desk.ins === '1' && !deskReload.pages && !deskReload.insp,
`at 1440, \`[\` and the properties chevron shut their columns, write '1', and the reload keeps both shut (${JSON.stringify({ desk, deskReload })})`)
await js('document.activeElement?.blur?.(); 1')
await key('[', 0, 'BracketLeft', 219)
await tap(`document.querySelector('.sp-insp').closest('.bkp').querySelector('.bkp-toggle')`)
await load()
const back = await js<any>(PANES)
ok(back.pages && back.insp && back.pane === '0' && back.ins === '0',
`…and reopening them is remembered the same way (${JSON.stringify(back)})`)
await js(`localStorage.clear(); for (const [k, v] of Object.entries(${before})) localStorage.setItem(k, v); 1`)
await metrics(true); await load()
const after = await js<string>(SNAP)
const restored = await js<any>(`({ w: innerWidth, insp: document.querySelector('.sp-insp').closest('.bkp').classList.contains('bkp-collapsed'), pages: document.querySelector('.sp-side').closest('.bkp').classList.contains('bkp-collapsed') })`)
ok(after === before && restored.w === 390 && restored.insp && restored.pages,
`the drawer-preference rows leave storage and the 390 viewport as they found them, both drawers shut (${after === before ? 'storage identical' : `${before} → ${after}`}; ${JSON.stringify(restored)})`)
}
// ——— the top bar is slides' bar ———
await open(false)
const BAR = `document.querySelector('.sp-bar')`
const geo = await js<any>(`(() => { const c = getComputedStyle(${BAR}); return { gap: c.columnGap, padY: c.paddingTop, padX: c.paddingInlineStart, padE: c.paddingInlineEnd, tier: ${BAR}.className } })()`)
ok(geo.gap === SLIDES_BAR.gap && geo.padY === SLIDES_BAR.padY && geo.padX === SLIDES_BAR.padX && geo.padE === SLIDES_BAR.padX,
`at 1440 the bar's padding and gap are slides' (${geo.padY}/${geo.padX}, gap ${geo.gap}; slides ${SLIDES_BAR.padY}/${SLIDES_BAR.padX}, gap ${SLIDES_BAR.gap}; ${geo.tier})`)
// Language: the globe opens the list slides' globe shows, and choosing one rebuilds the chrome in it
await tap(TRIG('Language'))
const langs = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; const rows = [...m.querySelectorAll('.bkm-item')]; return { n: rows.length, names: rows.map(r => r.textContent.trim()), on: rows.filter(r => r.getAttribute('aria-checked') === 'true').map(r => r.textContent.trim()) } })()`)
ok(langs && langs.n >= 8 && langs.names.includes('English') && langs.names.includes('Deutsch') && langs.on.length === 1 && langs.on[0] === 'English',
`the globe opens the language list, the one in force checked (${JSON.stringify(langs)})`)
await tap(`[...(${OPEN}).querySelectorAll('.bkm-item')].find(b => b.textContent.trim() === 'Deutsch')`)
const de = await js<any>(`({ lang: document.documentElement.lang, insert: document.querySelectorAll('.sp-bar .sp-group-insert .sp-btnlabel')[1]?.textContent, share: !!document.querySelector('.sp-bar .sp-live') })`)
ok(de.lang === 'de' && de.insert === 'Bild' && de.share,
`choosing Deutsch rebuilds the bar in German and keeps the Share control (${JSON.stringify(de)})`)
await tap(`document.querySelector('.sp-bar .sp-lang > button')`)
await tap(`[...(${OPEN}).querySelectorAll('.bkm-item')].find(b => b.textContent.trim() === 'English')`)
// Help: `?` in the bar opens the shortcut sheet
await tap(`document.querySelector('.sp-bar .sp-help')`)
const help = await js<string | null>(`(() => { const d = [...document.querySelectorAll('[aria-modal="true"]')].find(d => d.getBoundingClientRect().height > 0); return d?.querySelector('.bkd-title')?.textContent ?? null })()`)
ok(help === 'Shortcuts & tips', `the bar's ? opens Shortcuts & tips (${help})`)
await key('Escape', 0, 'Escape')
// Every control, at every width, can be reached and pressed: on screen (the
// bar scrolled to it when it scrolls) and topmost at its own centre.
const REACH = `(() => { const bar = ${BAR}; const vis = (e) => { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) return false; for (let n = e; n && n !== bar; n = n.parentElement) { const c = getComputedStyle(n); if (c.display === 'none' || c.visibility === 'hidden') return false } return true }
const ctl = [...bar.querySelectorAll('button, input')].filter(e => !e.closest('.bkm-menu')).filter(vis)
const bad = []
// Scroll ONLY the bar, and only if a person could: overflow:hidden on
// the app root is still scrollable from script, so scrollIntoView would
// 'reach' a control that is clipped for every real reader.
const scrolls = /auto|scroll/.test(getComputedStyle(bar).overflowX)
for (const e of ctl) { let r = e.getBoundingClientRect(); if (scrolls && (r.right > innerWidth || r.left < 0)) { bar.scrollLeft += r.right > innerWidth ? r.right - innerWidth + 2 : r.left - 2; r = e.getBoundingClientRect() } const top = document.elementsFromPoint(r.x + r.width / 2, r.y + r.height / 2)[0]
if (r.left < -0.5 || r.right > innerWidth + 0.5 || r.top < 0 || !top || !(e === top || e.contains(top))) bad.push((e.getAttribute('aria-label') || e.className).slice(0, 18) + '@' + Math.round(r.left) + '..' + Math.round(r.right)) }
bar.scrollLeft = 0
const app = document.querySelector('.sp-app'); if (app.scrollLeft || scrollX) bad.push('page scrolled sideways')
return { n: ctl.length, bad, tier: [...bar.classList].filter(c => /compact|tight|fold/.test(c)).map(c => c.slice(7)).join('+') || 'full', over: bar.scrollWidth - bar.clientWidth, scrolls: getComputedStyle(bar).overflowX } })()`
const reach: string[] = []
for (const w of [1440, 1280, 1024, 900, 800, 700, 600, 480, 390, 360, 320]) {
const phone = w <= 390
await send('Emulation.setDeviceMetricsOverride', { width: w, height: phone ? 844 : 900, deviceScaleFactor: phone ? 2 : 1, mobile: phone })
await send('Emulation.setTouchEmulationEnabled', { enabled: phone, maxTouchPoints: phone ? 5 : 1 })
await sleep(250)
const r = await js<any>(REACH)
reach.push(`${w}:${r.tier}${r.bad.length ? ' UNREACHABLE ' + r.bad.join(',') : ''}`)
if (r.bad.length) ok(false, `at ${w}px every bar control can be reached and pressed (${r.bad.join(', ')})`)
}
ok(!reach.some(s => s.includes('UNREACHABLE')), `every bar control is on screen and topmost at its centre, 320–1440 (${reach.join(' · ')})`)
// The fold engages BEFORE the bar overflows: no width where an unfolded bar
// is wider than itself, and every phone width folded.
const over: string[] = []
let foldAt = 0
for (let w = 1440; w >= 320; w -= 20) {
await send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false })
await send('Emulation.setTouchEmulationEnabled', { enabled: false, maxTouchPoints: 1 })
await sleep(90)
const r = await js<any>(`(() => { const b = ${BAR}; return { fold: b.classList.contains('sp-bar-fold'), over: b.scrollWidth - b.clientWidth } })()`)
if (r.fold && !foldAt) foldAt = w
if (!r.fold && r.over > 1) over.push(`${w}:+${r.over}`)
if (w <= 700 && !r.fold) over.push(`${w}:unfolded`)
}
ok(over.length === 0 && foldAt > 0, `the fold tier engages before the bar overflows (first fold at ${foldAt}px; ${over.join(' ') || 'no overflow unfolded'})`)
// THE INSERT GROUP FOLLOWS THE TIERS AS SLIDES' DOES: its words go at the
// compact tier with every other label, and at the fold the whole group
// moves into ⋯, each family with variants under its caption.
const tierAt = async (w: number) => {
await send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false })
await sleep(150)
return js<any>(`(() => { const b = ${BAR}; const g = b.querySelector('.sp-group-insert'); return { tier: [...b.classList].filter(c => /compact|tight|fold/.test(c)).join(' '),
shown: getComputedStyle(g).display !== 'none', words: [...g.querySelectorAll('.sp-btnlabel')].filter(l => l.getBoundingClientRect().width > 0).length,
icons: [...g.querySelectorAll('svg')].filter(i => i.getBoundingClientRect().width > 0).length } })()`)
}
let compactSeen: any = null, foldSeen: any = null, fullSeen: any = null
for (let w = 1440; w >= 720 && !(compactSeen && foldSeen); w -= 20) {
const r = await tierAt(w)
if (!r.tier) fullSeen ??= { w, ...r }
else if (/compact/.test(r.tier) && !/fold/.test(r.tier)) compactSeen ??= { w, ...r }
else if (/fold/.test(r.tier)) foldSeen ??= { w, ...r }
}
ok(!!fullSeen && fullSeen.words === 6 && !!compactSeen && compactSeen.words === 0 && compactSeen.icons === 6,
`the insert words go with every label at the compact tier, the icons stay (full ${JSON.stringify(fullSeen)}; compact ${JSON.stringify(compactSeen)})`)
ok(!!foldSeen && !foldSeen.shown, `at the fold tier the insert group leaves the bar (${JSON.stringify(foldSeen)})`)
await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true })
await sleep(250)
await tap(TRIG('More actions'))
const foldMenu = await js<any>(`(() => { const m = ${OPEN}; return { caps: [...m.querySelectorAll('.sp-menu-label')].map(c => c.textContent), keys: [...m.querySelectorAll('.bkm-item[data-insert]')].map(r => r.dataset.insert), comment: [...m.querySelectorAll('.bkm-item')].some(r => r.textContent.trim() === 'Comment') } })()`)
await key('Escape', 0, 'Escape')
ok(JSON.stringify(foldMenu.caps.slice(0, 3)) === JSON.stringify(barCaps) && JSON.stringify(foldMenu.keys) === JSON.stringify(barSeq) && foldMenu.comment,
`folded, ⋯ carries the whole insert group — the same members in order under the same captions, and Comment (${foldMenu.caps.join(', ')}; ${foldMenu.keys.length} members)`)
await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false })
await send('Emulation.setTouchEmulationEnabled', { enabled: false, maxTouchPoints: 1 })
await sleep(250)
// …and under browser zoom, where the viewport is wide but the bar is not: the
// phone rule cannot fire, so only MEASURING folds it (150%, 1440 → 720).
await js(`document.documentElement.style.zoom = '1.5'; 1`)
const zover: string[] = []
let zfold = 0
for (let w = 1440; w >= 720; w -= 40) {
await send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false })
await sleep(90)
const r = await js<any>(`(() => { const b = ${BAR}; return { fold: b.classList.contains('sp-bar-fold'), over: b.scrollWidth - b.clientWidth } })()`)
if (r.fold && !zfold) zfold = w
if (!r.fold && r.over > 1) zover.push(`${w}:+${r.over}`)
}
await js(`document.documentElement.style.zoom = ''; 1`)
ok(zover.length === 0 && zfold > 700, `at 150% zoom the measured fold engages before the bar overflows (first fold at ${zfold}px; ${zover.join(' ') || 'no overflow unfolded'})`)
// Below the fold's floor the bar scrolls, and ⋯ still opens a menu you can press
await send('Emulation.setDeviceMetricsOverride', { width: 320, height: 844, deviceScaleFactor: 2, mobile: true })
await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 })
await sleep(250)
const moreAt = await js<any>(`(() => { const bar = ${BAR}; const b = ${TRIG('More actions')}; if (/auto|scroll/.test(getComputedStyle(bar).overflowX)) bar.scrollLeft = bar.scrollWidth; const r = b.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, on: r.right <= innerWidth } })()`)
await click(moreAt.x, moreAt.y)
const se = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; const r = m.getBoundingClientRect(); const rows = [...m.querySelectorAll('.bkm-item')]; const live = rows.find(x => x.getAttribute('aria-disabled') !== 'true'); const f = live.getBoundingClientRect(); const hit = document.elementsFromPoint(f.x + f.width / 2, f.y + f.height / 2)[0]; return { left: Math.round(r.left), right: Math.round(r.right), vw: innerWidth, first: live.contains(hit), lang: rows.some(x => x.textContent.trim() === 'Language'), help: rows.some(x => x.textContent.trim().startsWith('Shortcuts & tips')) } })()`)
ok(se && moreAt.on && se.left >= 0 && se.right <= se.vw && se.first && se.lang && se.help,
`at 320px ⋯ opens on screen, its rows pressable, carrying Language and Shortcuts & tips (${JSON.stringify(se)})`)
await tap(`[...(${OPEN}).querySelectorAll('.bkm-item')].find(b => b.textContent.trim() === 'Language')`)
const sheet2 = await js<any>(`(() => { const m = ${OPEN}; if (!m) return null; const rows = [...m.querySelectorAll('.bkm-item')]; const r = m.getBoundingClientRect(); return { n: rows.length, onScreen: r.top >= 0 && r.bottom <= innerHeight, on: rows.filter(x => x.getAttribute('aria-checked') === 'true').length } })()`)
ok(sheet2 && sheet2.n >= 8 && sheet2.onScreen && sheet2.on === 1, `⋯ → Language opens the same list, on screen (${JSON.stringify(sheet2)})`)
await key('Escape', 0, 'Escape')
// ——— NOTHING WAS DELETED, ONLY MOVED ———
// The commands reachable from the bar BEFORE the Save menu took slides'
// order, captured on the shell built from spaces-topbar (#567) by the same
// walk as below: every bar button, every row of every bar menu, the page's
// own menu and every button in About, at 1440 and at 390. Each must still be
// reachable at the same width — under its own name, or under the name
// slides gives the same command.
const BEFORE_BOTH = ['About this space', 'Insert a block', 'Search all pages', 'Not sharing yet', 'Save',
'Text', 'Heading 1', 'Heading 2', 'Heading 3', 'Bulleted list', 'Numbered list', 'To-do', 'Toggle', 'Callout',
'Quote', 'Code', 'Divider', 'Table', 'Link to page', 'Link to the web', 'Board or list', 'Canvas', 'Image',
'Video or audio', 'Save a copy…', 'Export as Markdown…', 'Export page as a space…',
'New page', "Today's journal", 'New issue', 'Make this page an issue', 'Import Markdown…', 'Graph',
'Print or save as PDF', 'Rename', 'New page inside', 'Comment on this page', 'Archive', 'Column', 'Wide',
'Full width', 'Use this width for every page', 'Delete…', 'Check for updates', 'Set a password…',
'Copy document JSON', 'Export as Markdown', 'Duplicate as a new space…', 'Replace from JSON…', 'Close',
'Undo', 'Redo', 'Reading view', 'Properties', 'Language', 'Keyboard shortcuts']
const BEFORE: Record<number, string[]> = {
// (the ⋯ trigger itself was also there; it is a container, not a
// command — slides has none at this width — and every row it held is
// checked here in its new home)
1440: [...BEFORE_BOTH, 'Other ways to save',
'English', '日本語', '简体中文', '繁體中文', 'Español', 'Français', 'Deutsch', 'Italiano', 'Português'],
390: [...BEFORE_BOTH, 'Pages', 'More'],
}
// renamed to slides' word for the same command
const ALIAS: Record<string, string> = { 'Set a password…': 'Encrypt with password…', 'Export as Markdown': 'Export as Markdown…',
// slides' labels, adopted 2026-09-26 (the walk keeps a name up to its first " (" or " — ")
'About this space': 'About bento/spaces', 'Keyboard shortcuts': 'Shortcuts & tips', 'More': 'More actions',
'Other ways to save': 'Save as…', 'Print or save as PDF': 'Export PDF', 'Duplicate as a new space…': 'Duplicate as new space…',
// the one Insert menu became slides' insert group (2026-09-26): its
// trigger is a container, not a command, and its rows took family names
'Insert a block': 'Text', 'Video or audio': 'Video', 'Link to the web': 'Link card', 'Board or list': 'Board' }
const WALK = `(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const vis = (e) => { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) return false; for (let n = e; n; n = n.parentElement) { const c = getComputedStyle(n); if (c.display === 'none' || c.visibility === 'hidden') return false } return true }
const name = (s) => s.split(' (')[0].split(' — ')[0].trim()
const esc = () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))
const out = {}
const add = (where, label) => { label = name(label); if (label && !out[label]) out[label] = where }
const bar = document.querySelector('.sp-bar')
// the floating Reading view pill, and the panels' own chevrons
const fab = document.querySelector('.sp-readfab')
if (fab && vis(fab)) add('fab', fab.getAttribute('aria-label'))
for (const c of document.querySelectorAll('.bkp-toggle')) if (vis(c)) add('panel', c.getAttribute('aria-label'))
for (const b of bar.querySelectorAll('button')) if (vis(b) && !b.closest('.bkm-menu')) {
add('bar', b.getAttribute('aria-label') || b.title || b.textContent)
// an insert button is also known by its word ("Table" beside "Add a table — …")
const word = b.querySelector('.sp-btnlabel')?.textContent
// (the button is on the bar at every tier above the fold, its word or not)
if (word) add('bar', word)
}
for (const tr of [...bar.querySelectorAll('.bkm > .bkm-trigger')].filter(vis)) {
tr.click(); await sleep(60)
for (const r of tr.parentElement.querySelector(':scope > .bkm-menu').querySelectorAll('.bkm-item')) add('menu', r.querySelector('.bkm-text')?.textContent || '')
esc(); await sleep(60)
}
// the Share popover's actions (a popover of rows, not a kernel menu)
const live = bar.querySelector('.sp-live')
if (live && vis(live)) { live.click(); await sleep(120); for (const r of document.querySelectorAll('.sp-pop .sp-paction-name')) add('share', r.textContent); esc(); await sleep(80) }
const more = document.querySelector('.sp-treelink.sp-here .sp-rowmore')
if (more) { more.click(); await sleep(80); const m = [...document.querySelectorAll('.sp-mn-anchored .bkm-menu')].pop(); if (m) for (const r of m.querySelectorAll('.bkm-item')) add('page menu', r.querySelector('.bkm-text')?.textContent || ''); esc(); await sleep(60) }
// the page list's + ▾ (a drawer on a phone: open it from the bar first)
if (!vis(document.querySelector('.sp-side .sp-newmenu > .bkm-trigger') || document.body)) [...bar.querySelectorAll('button')].find(b => (b.getAttribute('aria-label') || '').startsWith('Pages'))?.click()
await sleep(250)
const nt = document.querySelector('.sp-side .sp-newmenu > .bkm-trigger')
for (const b of document.querySelectorAll('.sp-side-head button')) if (vis(b) && !b.closest('.bkm-menu')) add('page list', b.getAttribute('aria-label'))
if (nt && vis(nt)) { add('page list', nt.getAttribute('aria-label')); nt.click(); await sleep(80); for (const r of nt.parentElement.querySelectorAll(':scope > .bkm-menu .bkm-item')) add('page list menu', r.querySelector('.bkm-text')?.textContent || ''); esc(); await sleep(60) }
document.querySelector('.sp-mark').click(); await sleep(250)
const d = [...document.querySelectorAll('[aria-modal="true"]')].pop()
if (d) for (const b of d.querySelectorAll('button')) add('About', b.textContent)
esc(); await sleep(100)
return out
})()`
for (const w of [1440, 390]) {
await open(w < 700)
const now = await js<Record<string, string>>(WALK)
// Properties left the bar (2026-10-20): where the panel is a column its
// own chevron is the control, as in slides; folded, ⋯ keeps the row
const aliasAt = (c: string) => (w >= 700 && c === 'Properties') ? 'Show properties' : (ALIAS[c] ?? c)
const lost = BEFORE[w].filter((c) => !(aliasAt(c) in now))
// …and the new homes are what reach them (maintainer, 2026-10-20)
if (now['Reading view'] !== 'fab') lost.push(`Reading view (not the floating pill: ${now['Reading view']})`)
if (now['Graph'] !== 'page list') lost.push(`Graph (not on the page list's header: ${now['Graph']})`)
if (w < 700 && now['Properties'] !== 'menu') lost.push(`Properties (not in ⋯: ${now['Properties']})`)
if (w >= 700 && now['Show properties'] !== 'panel') lost.push(`Properties (not the panel chevron: ${now['Show properties']})`)
// …and the new homes are what reach them: the pages from the page list
for (const c of ['New page', "Today's journal", 'New issue']) if (!/^page list/.test(now[c] ?? '')) lost.push(`${c} (not on the page list's + ▾: ${now[c]})`)
for (const c of ['Audio', 'Gallery', 'List', 'Table view', 'Comment']) if (!(c in now)) lost.push(`${c} (new member unreachable)`)
// per-page designs: the page's Design row, and its note under Save ▾
if (!('Design' in now)) lost.push('Design (new member unreachable)')
if (!('Export page as Markdown…' in now)) lost.push('Export page as Markdown… (new member unreachable)')
// the sealed reading copy, from the Share popover
if (now['Save a reading copy…'] !== 'share') lost.push(`Save a reading copy… (not in Share: ${now['Save a reading copy…']})`)
ok(lost.length === 0, `at ${w}px every command reachable before is reachable now (${BEFORE[w].length} checked${lost.length ? '; LOST: ' + lost.join(', ') : ''})`)
}
// ——— THE BAR CARRIES LESS (maintainer, 2026-10-20) ———
// Reading view is a floating pill in slides' Slideshow corner, Properties
// is the panel's chevron, `]` and (folded) ⋯, Graph is on the page list's
// header, Search stays. Each home is pressed with trusted input.
const FAB = `document.querySelector('.sp-readfab')`
const BAR_HAS = `(() => { const names = [...document.querySelectorAll('.sp-bar button')].filter(b => !b.closest('.bkm-menu')).map(b => (b.getAttribute('aria-label') || '').split(' (')[0].split(' — ')[0]); return { reading: names.includes('Reading view'), graph: names.includes('Graph'), props: names.includes('Properties'), search: names.includes('Search all pages') } })()`
const MORE_ROWS = `(() => { const m = ${OPEN}; return m ? [...m.querySelectorAll('.bkm-item .bkm-text')].map(x => x.textContent.trim()) : null })()`
// where the pill sits, how it is drawn, and whether a press lands on it
const FABAT = `(() => { const b = ${FAB}; if (!b) return null; const r = b.getBoundingClientRect(); const main = document.querySelector('.sp-main').getBoundingClientRect(); const top = document.elementsFromPoint(r.x + r.width / 2, r.y + r.height / 2)[0]; const c = getComputedStyle(b);
return { w: Math.round(r.width), h: Math.round(r.height), end: Math.round(main.right - r.right), bottom: Math.round(innerHeight - r.bottom), onScreen: r.left >= 0 && r.right <= innerWidth && r.bottom <= innerHeight, topmost: !!top && (top === b || b.contains(top)),
radius: c.borderTopLeftRadius, border: c.borderTopWidth + ' ' + c.borderTopStyle, shadow: c.boxShadow, weight: c.fontWeight, padY: c.paddingTop, label: b.getAttribute('aria-label'), tip: b.title, pressed: b.getAttribute('aria-pressed'), icon: !!b.querySelector('svg') } })()`
for (const w of [1440, 390]) {
await open(w < 700)
const has = await js<any>(BAR_HAS)
ok(!has.reading && !has.graph && !has.props && has.search,
`at ${w}px the bar no longer carries Reading view, Graph or Properties — and Search stays (${JSON.stringify(has)})`)
// Reading view: the pill, in and back out
const f0 = await js<any>(FABAT)
const pillOff: string[] = []
if (!f0) pillOff.push('no pill')
else {
if (f0.radius !== '999px' || !/999px/.test(SLIDES_PILL.radius ?? '')) pillOff.push(`radius ${f0.radius} ≠ ${SLIDES_PILL.radius}`)
if (f0.border !== `${/(\d+px)/.exec(SLIDES_PILL.border ?? '')?.[1]} solid`) pillOff.push(`border ${f0.border} ≠ ${SLIDES_PILL.border}`)
const cs = nums(f0.shadow).split(','), ss = nums(SLIDES_PILL.shadow).split(',')
if (cs.slice(0, 4).join() !== ss.slice(3, 7).join() || cs.slice(4, 7).join() !== ss.slice(0, 3).join()) pillOff.push(`shadow ${f0.shadow} ≠ ${SLIDES_PILL.shadow}`)
if (f0.weight !== SLIDES_PILL.weight) pillOff.push(`weight ${f0.weight} ≠ ${SLIDES_PILL.weight}`)
if (f0.end !== parseInt(SLIDES_PILL.end ?? '') || f0.bottom !== parseInt(SLIDES_PILL.bottom ?? '')) pillOff.push(`corner ${f0.end}/${f0.bottom} ≠ ${SLIDES_PILL.end}/${SLIDES_PILL.bottom}`)
if (w >= 700 && f0.padY !== SLIDES_PILL.padY) pillOff.push(`padding ${f0.padY} ≠ ${SLIDES_PILL.padY}`)
if (w < 700 && f0.h < 44) pillOff.push(`a ${f0.h}px target on a phone`)
if (!f0.icon || f0.label !== 'Reading view' || f0.tip !== 'Reading view') pillOff.push(`eye/label/tooltip ${f0.icon}/${f0.label}/${f0.tip}`)
}
ok(pillOff.length === 0, `at ${w}px Reading view is slides' Slideshow pill, in its bottom-end corner (${pillOff.join('; ') || `${f0.w}×${f0.h}, ${f0.end}px from the page's end, ${f0.bottom}px up`})`)
ok(!!f0 && f0.onScreen && f0.topmost && f0.pressed === 'false', `at ${w}px the pill is on screen and topmost at its centre (${JSON.stringify({ on: f0?.onScreen, top: f0?.topmost, pressed: f0?.pressed })})`)
await tap(FAB)
await sleep(300)
const f1 = await js<any>(FABAT)
const inRead = await js<boolean>(`!!document.querySelector('.sp-app.sp-reading')`)
ok(inRead && !!f1 && f1.onScreen && f1.topmost && f1.pressed === 'true',
`at ${w}px pressing the pill opens reading view, and the pill stays on screen, pressable and pressed — the way back out (${JSON.stringify({ inRead, on: f1?.onScreen, top: f1?.topmost, pressed: f1?.pressed })})`)
await tap(FAB)
await sleep(300)
ok(!(await js<boolean>(`!!document.querySelector('.sp-app.sp-reading')`)) && (await js<string>(`(${FAB}).getAttribute('aria-pressed')`)) === 'false',
`at ${w}px pressing it again leaves reading view`)
// …Esc leaves it too, as before
await tap(FAB); await sleep(200)
await js(`document.activeElement?.blur?.(); 1`)
await key('Escape', 0, 'Escape'); await sleep(200)
ok(!(await js<boolean>(`!!document.querySelector('.sp-app.sp-reading')`)), `at ${w}px Esc still leaves reading view`)
// …and a sealed copy has no pill (the class the sealed boot sets)
const sealedPill = await js<string>(`(() => { const a = document.querySelector('.sp-app'); a.classList.add('sp-sealed'); const d = getComputedStyle(${FAB}).display; a.classList.remove('sp-sealed'); return d })()`)
ok(sealedPill === 'none', `at ${w}px a sealed reading copy shows no pill (display ${sealedPill})`)
// Graph: on the page list's header, and it opens the graph
if (w < 700) await tap(`[...document.querySelectorAll('.sp-bar button')].find(b => (b.getAttribute('aria-label') || '').startsWith('Pages'))`)
await sleep(250)
const GB = `[...document.querySelectorAll('.sp-side-head button')].find(b => b.getAttribute('aria-label') === 'Graph')`
const gb = await js<any>(`(() => { const b = ${GB}; if (!b) return null; const r = b.getBoundingClientRect(); const top = document.elementsFromPoint(r.x + r.width / 2, r.y + r.height / 2)[0]; return { tip: b.title, w: Math.round(r.width), h: Math.round(r.height), topmost: !!top && (top === b || b.contains(top)), beside: !!b.closest('.sp-side-acts')?.querySelector('.sp-newsplit') } })()`)
ok(!!gb && gb.tip === 'Graph' && gb.topmost && gb.beside && (w >= 700 || gb.h >= 44),
`at ${w}px Graph is an icon button on the page list's header, beside + ▾, with its tooltip${w < 700 ? ', a 44px target in the drawer' : ''} (${JSON.stringify(gb)})`)
await tap(GB)
await sleep(400)
const graph = await js<any>(`(() => { const d = [...document.querySelectorAll('.sp-dlg-graph')].find(d => d.getBoundingClientRect().height > 0); return { title: d?.querySelector('.sp-card-h')?.textContent ?? null, canvas: !!d?.querySelector('canvas'), drawer: document.querySelector('.sp-side').closest('.bkp').getBoundingClientRect().width } })()`)
ok(graph.title === 'Graph' && graph.canvas && (w >= 700 || graph.drawer === 0),
`at ${w}px pressing it opens the graph view${w < 700 ? ', the drawer shut behind it' : ''} (${JSON.stringify(graph)})`)
await key('Escape', 0, 'Escape'); await sleep(250)
await js(`window.bento.graph(); 1`); await sleep(300)
const api = await js<string | null>(`(() => { const d = [...document.querySelectorAll('.sp-dlg-graph')].find(d => d.getBoundingClientRect().height > 0); return d?.querySelector('.sp-card-h')?.textContent ?? null })()`)
ok(api === 'Graph', `at ${w}px bento.graph() still opens it (${api})`)
await key('Escape', 0, 'Escape'); await sleep(250)
// Properties: ⋯ on a phone; `]` and the chevron where the panel is a column
const INSP = `document.querySelector('.sp-insp').closest('.bkp')`
if (w < 700) {
await tap(TRIG('More actions'))
const rows = await js<string[] | null>(MORE_ROWS)
ok(!!rows && rows.includes('Properties') && !rows.includes('Reading view') && !rows.includes('Graph'),
`at ${w}px ⋯ keeps Properties and lists neither Reading view (the pill) nor Graph (the page list) (${rows?.filter((r) => /Properties|Reading|Graph|PDF/.test(r)).join(', ')})`)
await tap(`[...(${OPEN}).querySelectorAll('.bkm-item')].find(b => b.querySelector('.bkm-text')?.textContent.trim() === 'Properties')`)
await sleep(400)
const pw = await js<number>(`(${INSP}).getBoundingClientRect().width`)
ok(pw > 200, `at ${w}px ⋯ → Properties opens the properties drawer (${pw}px)`)
} else {
await js(`document.activeElement?.blur?.(); 1`)
const p0 = await js<number>(`(${INSP}).getBoundingClientRect().width`)
await key(']', 0, 'BracketRight', 221); await sleep(350)
const p1 = await js<number>(`(${INSP}).getBoundingClientRect().width`)
await key(']', 0, 'BracketRight', 221); await sleep(350)
const p2 = await js<number>(`(${INSP}).getBoundingClientRect().width`)
ok(p0 === 0 && p1 > 200 && p2 === 0, `at ${w}px \`]\` opens and shuts the properties panel (${p0} → ${p1} → ${p2}px)`)
const chev = await js<any>(`(() => { const c = (${INSP}).querySelector('.bkp-toggle'); const r = c.getBoundingClientRect(); const top = document.elementsFromPoint(r.x + r.width / 2, r.y + r.height / 2)[0]; return { label: c.getAttribute('aria-label'), right: Math.round(innerWidth - r.right), topmost: !!top && (top === c || c.contains(top)) } })()`)
ok(chev.label === 'Show properties (])' && Math.abs(chev.right) <= 6 && chev.topmost, `at ${w}px the shut panel's chevron is docked at the edge and pressable (${JSON.stringify(chev)})`)
await tap(`(${INSP}).querySelector('.bkp-toggle')`); await sleep(350)
const p3 = await js<number>(`(${INSP}).getBoundingClientRect().width`)
ok(p3 > 200, `at ${w}px pressing that chevron opens the properties panel (${p3}px)`)
}
}
// ——— TAG CHIPS × FOOTNOTE MARKERS: the ORDER in render.ts ———
// inlineHost and table cells set their content with the footnote
// either/or (raw html while editable, `markRefs` <sup><a> markers
// otherwise) and only THEN call `decorateTags`. The reverse order shipped
// in September: the footnote `innerHTML =` replaced the host's children and
// wiped every chip drawn before it. A source check cannot tell those two
// orders apart from a refactor that keeps both calls, so this is measured
// in the rendered DOM: the reading view must carry BOTH a chip and a
// marker; the editor must draw the chip but keep `[^1]` as typed; and what
// a trusted keystroke commits must carry NO chip markup.
console.log('\n tag chips × footnote markers\n')
await open(false)
const TF_PAGE = 'tfpage', TF_P = 'tfpara', TF_T = 'tftable'
const loaded = await js<boolean>(`(() => {
const d = JSON.parse(JSON.stringify(window.bento.doc))
d.pages = [{ id: ${JSON.stringify(TF_PAGE)}, title: 'Tags and footnotes', blocks: [
{ id: ${JSON.stringify(TF_P)}, type: 'p', html: 'See the plan #launch and the note[^1].' },
{ id: ${JSON.stringify(TF_T)}, type: 'table', rows: [['Item', 'Note'], ['Launch', '#launch and[^1]']] },
] }]
d.footnotes = { '1': 'The note.' }
return window.bento.loadDoc(JSON.stringify(d))
})()`)
await sleep(400)
ok(loaded, 'the tags × footnotes fixture loads through window.bento.loadDoc')
const PHOST = `document.querySelector('[data-block-id="${TF_P}"] [data-edit="${TF_P}"]')`
const CHOST = `document.querySelector('[data-block-id="${TF_T}"] td[data-r="1"][data-c="1"]')`
// what a host draws, read from the DOM: chips, footnote markers, whether
// the raw token is still there, and whether the host is editable
const shape = (host: string) => js<any>(`(() => { const h = ${host}; if (!h) return null; return {
chips: [...h.querySelectorAll('a.sp-tag')].map(a => a.dataset.tag + '=' + a.textContent),
markers: [...h.querySelectorAll('sup > a')].map(a => ({ n: a.textContent, chip: a.classList.contains('sp-tag') || !!a.dataset.tag })),
raw: h.textContent.includes('[^1]'), editable: h.isContentEditable } })()`)
// 1 — reading view (editable: false): a chip AND a marker, in both hosts
await tap(`document.querySelector('.sp-readfab')`)
await sleep(300)
ok(await js<boolean>(`!!document.querySelector('.sp-reading')`), 'the reading view is on (the floating eye)')
for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {
const s = await shape(host)
ok(!!s && !s.editable && s.chips.includes('launch=#launch'),
`reading view, ${what}: the #launch tag chip is drawn (${JSON.stringify(s?.chips)})`)
ok(!!s && s.markers.length === 1 && s.markers[0].n === '1' && !s.markers[0].chip && !s.raw,
`reading view, ${what}: the footnote is a sup > a marker "1", not a chip, and no raw [^1] is left (${JSON.stringify(s?.markers)})`)
}
await tap(`document.querySelector('.sp-readfab')`)
await sleep(300)
ok(await js<boolean>(`!document.querySelector('.sp-reading')`), 'the reading view is off again')
// 2, 3 — the editor: chip drawn, token raw, and the commit chip-free
const docBlock = (id: string) => js<any>(`(() => window.bento.doc.pages.find(p => p.id === ${JSON.stringify(TF_PAGE)})?.blocks.find(b => b.id === ${JSON.stringify(id)}))()`)
const chipFree = (h: unknown): h is string => typeof h === 'string' && !/sp-tag|data-tag/.test(h)
for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {
const s = await shape(host)
ok(!!s && s.editable && s.chips.includes('launch=#launch'),
`editing, ${what}: the #launch chip is drawn in the editable host (${JSON.stringify(s?.chips)})`)
ok(!!s && s.markers.length === 0 && s.raw,
`editing, ${what}: the footnote stays its raw [^1] token, no marker (${JSON.stringify(s?.markers)})`)
// focus with a trusted click, park the caret at the host's very end
// (outside every chip), type one trusted character, blur
await tap(host)
await js(`(() => { const h = ${host}; h.focus(); const r = document.createRange(); r.selectNodeContents(h); r.collapse(false); const sel = getSelection(); sel.removeAllRanges(); sel.addRange(r); return 1 })()`)
await key('Z')
await js(`document.activeElement?.blur?.(); 1`)
await sleep(300)
}
const pb = await docBlock(TF_P)
ok(chipFree(pb?.html) && /Z$/.test(pb.html) && pb.html.includes('[^1]') && pb.html.includes('#launch'),
`the paragraph's COMMITTED html took the keystroke, carries no chip markup, and keeps [^1] and #launch as text (${JSON.stringify(pb?.html)})`)
const tb = await docBlock(TF_T)
const cell = tb?.rows?.[1]?.[1]
ok(chipFree(cell) && /Z$/.test(cell) && cell.includes('[^1]') && cell.includes('#launch'),
`the table cell's COMMITTED html took the keystroke, carries no chip markup, and keeps [^1] and #launch as text (${JSON.stringify(cell)})`)
ok(chipFree(tb?.html), `the table's fallback html carries no chip markup either (${JSON.stringify(tb?.html)})`)
// after the blur settle, the editor still draws the chip in both hosts
for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {
const s = await shape(host)
ok(!!s && s.chips.includes('launch=#launch') && s.raw, `after blur, ${what}: the chip is redrawn and the [^1] token is still raw`)
}
// ——— CALENDAR "AGENDA" vs GANTT "TIMELINE" (maintainer, 2026-10-20) ———
// The calendar's second shape was labelled "Timeline", the same word as the
// gantt layout. Its button now reads "Agenda"; the gantt keeps "Timeline";
// and the toggle still STORES `span: 'timeline'`, because that is the
// format every existing file carries. Measured in the rendered head and in
// the committed block, after a trusted click.
console.log('\n calendar agenda vs gantt timeline\n')
await open(false)
const CA_PAGE = 'capage', CA_CAL = 'cacal', CA_GANTT = 'cagantt'
const caLoaded = await js<boolean>(`(() => {
const d = JSON.parse(JSON.stringify(window.bento.doc))
d.pages = [{ id: ${JSON.stringify(CA_PAGE)}, title: 'Calendar and timeline', blocks: [
{ id: ${JSON.stringify(CA_CAL)}, type: 'view', layout: 'calendar', html: 'Cal' },
{ id: ${JSON.stringify(CA_GANTT)}, type: 'view', layout: 'gantt', html: 'Plan' },
] }]
return window.bento.loadDoc(JSON.stringify(d))
})()`)
await sleep(400)
ok(caLoaded, 'the calendar × gantt fixture loads through window.bento.loadDoc')
const viewHead = (id: string) => js<any>(`(() => { const v = document.querySelector('.sp-view[data-block-id="${id}"]'); if (!v) return null;
const s = v.querySelector('[data-view-span]'), l = v.querySelector('[data-view-layout]');
return { span: s ? { text: s.textContent, title: s.title } : null, layout: l?.textContent ?? null } })()`)
const calBlock = () => js<any>(`(() => window.bento.doc.pages.find(p => p.id === ${JSON.stringify(CA_PAGE)})?.blocks.find(b => b.id === ${JSON.stringify(CA_CAL)}))()`)
const g = await viewHead(CA_GANTT)
ok(g?.layout === 'Timeline' && g?.span === null,
`the gantt layout is still labelled "Timeline", with no span button (${JSON.stringify(g)})`)
const m0 = await viewHead(CA_CAL)
ok(m0?.layout === 'Calendar' && m0?.span?.text === 'Month' && m0?.span?.title === 'Show an agenda',
`a fresh calendar reads "Month" and offers "Show an agenda" (${JSON.stringify(m0)})`)
await tap(`document.querySelector('.sp-view[data-block-id="${CA_CAL}"] [data-view-span]')`)
await sleep(300)
const m1 = await viewHead(CA_CAL)
ok(m1?.span?.text === 'Agenda' && m1?.span?.title === 'Show a month at a time',
`after one click the span button reads "Agenda", never "Timeline" (${JSON.stringify(m1)})`)
const cb = await calBlock()
ok(cb?.span === 'timeline',
`…and the block STORES span: 'timeline', the unchanged format value (${JSON.stringify(cb?.span)})`)
await tap(`document.querySelector('.sp-view[data-block-id="${CA_CAL}"] [data-view-span]')`)
await sleep(300)
const cb2 = await calBlock()
ok(cb2 && !('span' in cb2) && (await viewHead(CA_CAL))?.span?.text === 'Month',
`a second click returns to the month grid and removes the key (${JSON.stringify(cb2?.span)})`)
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)