Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: the shared modal dialog primitive (UI primitives, tier 3) (#459)
nyblnet162555b79100
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e8cf2dd4..e86ff881 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -329,6 +329,16 @@ jobs:# plus the theming guard (every colour chain reaches a token each of the# four apps defines and themes). Each is mutation-caught.run: node scripts/test-ui-panel.ts+ - name: Shared dialog primitive rig+ # kernel/src/ui/dialog.ts is the tier-3 consolidation: the modal all+ # four apps build their About dialog on. The checks guard behaviour that+ # lived in one app or none — focus captured on open and restored to the+ # opener on close, a capture-phase document Escape that does not fall+ # through to the editor behind it, backdrop dismissal that a click on the+ # card does not trigger, and a real focus trap (Tab wraps in the card) —+ # plus listener cleanup and the shared theming guard. Each is+ # mutation-caught; none is visible to a developer with a mouse.+ run: node scripts/test-ui-dialog.ts- name: Shared menu primitive rig# kernel/src/ui/menu.ts replaces four hand-rolled dropdowns, and what# differed between them was all INVISIBLE: three of the four appsdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 38495f31..92366154 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6678,3 +6678,45 @@ the whole primitive in node with no build machinery and no CSS-import stub.Pointers: `kernel/src/ui/menu.ts` (the four-app comparison, function byfunction), `kernel/src/ui/menu.css` (details 9 and 10, written down once),`scripts/test-ui-menu.ts` (what each check guards, and which app's gap it is).++## 2026-09 — UI primitives tier 3: the modal dialog (and three built ahead of a consumer)++**Decision.** Tier 3 of the UI primitives is `kernel/src/ui/dialog.ts` ++`dialog.css`, guarded by `scripts/test-ui-dialog.ts`. Kernel half only; same+discipline as the menu and the panel (values through `--bkd-*` chains onto the+host's own tokens, never `light-dark()`, the shared theming guard).++**The dialog is a real consolidation.** All four apps build their About dialog+(and smaller confirms) on a per-app overlay — slides `.ed-about-overlay`, spaces+`.sp-overlay`, dash `.dx-about`, type `.t-overlay`, each with its own open/close+in an `about.ts`. As the tier's brief predicted, this is where "slides is the+basis" gives the LEAST: slides' dialog machinery is one class and a blur, while+spaces captures and restores focus and closes on a capture-phase document+Escape, and type cleans up a named handler. The primitive takes spaces'/type's+behaviour and adds what no app had — a focus trap, backdrop dismissal, and+`role="dialog"`/`aria-modal`/`aria-labelledby` — so the modal works for the+keyboard, not only the mouse. The overlay is `position: fixed` at a z above the+topbar's ceiling, so it escapes every ancestor stacking context (detail 9) and+clip (detail 10).++**The other three of tier 3 are built ahead of a consumer, on the maintainer's+call ("build all four, they would come into play soon"), NOT as consolidations.**+The four-way read found nothing to consolidate for them, and that read stands as+the record:+- **tooltip** — no app has a CSS tooltip; all four use the native `title`+ attribute. A custom one is a new abstraction, built forward-looking.+- **toggle** — the three toggle-named classes are three concepts (a native+ checkbox, a disclosure block body, a segmented button group); no shared switch+ exists. Built as a labelled `role="switch"`, forward-looking.+- **chip** — 21 classes across four apps are homonyms (a removable filter chip,+ static badges, clickable pickers); the only behavioural one is dash-only. Built+ minimal — a label with an optional removable ✕ and count — shaped against+ dash's filter chip, forward-looking.++Each of the three ships as its own PR and should be revisited if no app adopts+it. This entry is their record as design decisions rather than consolidations.++Pointers: `kernel/src/ui/dialog.{ts,css}`, `scripts/test-ui-dialog.ts` (66+checks; focus restore, capture-phase Escape, backdrop guard, focus trap and+listener cleanup each mutation-caught), `working/team/notes/kernel.md` (the+tier-3 four-way read and its correction).diff --git a/kernel/src/ui/dialog.css b/kernel/src/ui/dialog.cssnew file mode 100644index 00000000..2edc878e--- /dev/null+++ b/kernel/src/ui/dialog.css@@ -0,0 +1,81 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors++ THE SHARED MODAL DIALOG styles. See dialog.ts for why this exists and what+ each app contributed. Sibling of menu.css and panel.css; the two rules from+ those hold here too and are not restated in full:++ 1. VALUES ARE THE HOST APP'S — every colour through a `--bkd-*` chain onto+ the app's own token; never light-dark(); the shared theming guard+ (scripts/lib/ui-theme-guard.ts) checks every colour chain resolves, per+ app, to a token that app defines and themes.+ 2. Structure and behaviour are shared; only the look is the host's. */++.bkd-overlay {+ /* A fixed scrim over the whole viewport. `position: fixed` at a z ABOVE the+ topbar's ceiling is what lets the dialog escape every ancestor stacking+ context (hard-won detail 9) and every ancestor clip (detail 10): a modal+ rendered inside a panel or a bar would be trapped by it. */+ position: fixed;+ inset: 0;+ z-index: var(--bkd-z, 1000);+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ background: var(--bkd-scrim, rgb(20 30 45 / 0.44));+ /* the scrim is the one deliberately theme-independent surface here: a dim+ over the page reads the same in light and dark, so it is a literal, not a+ token chain — and it is excluded from the guard's colour set for that. */+ overflow: auto;+}++.bkd-card {+ display: flex;+ flex-direction: column;+ max-width: min(560px, 100%);+ max-height: calc(100vh - 48px);+ /* the card scrolls its own overflow; a long changelog does not push the+ actions row off the bottom of the viewport. */+ overflow: auto;+ padding: 20px 22px;+ background: var(--bkd-bg, var(--surface, var(--chrome, #fff)));+ color: var(--bkd-ink, var(--ink, #1e2a3a));+ border: 1px solid var(--bkd-border, var(--line, #e3e8ef));+ border-radius: var(--bkd-radius, var(--radius-lg, var(--radius, 12px)));+ box-shadow: var(--bkd-shadow, 0 18px 60px rgb(20 30 45 / 0.30));+}+.bkd-card:focus { outline: none; } /* the card takes focus as a fallback; no ring on the box itself */++.bkd-title {+ margin: 0 0 12px;+ font-size: 17px;+ font-weight: 650;+ color: var(--bkd-ink, var(--ink, #1e2a3a));+}++.bkd-body {+ min-height: 0;+ color: var(--bkd-body-ink, var(--ink-2, var(--ink, #1e2a3a)));+}++/* the actions row: pinned at the foot, buttons trailing — dash's actions()+ pattern, made the shared shape. */+.bkd-actions {+ display: flex;+ gap: 8px;+ justify-content: flex-end;+ margin-top: 18px;+}++@media (max-width: 700px) {+ /* on a phone the card is a bottom sheet — full width, docked low, the reach+ the thumb has. spaces already does this for its own popovers (.sp-sheet). */+ .bkd-overlay { padding: 0; align-items: flex-end; }+ .bkd-card {+ max-width: 100%;+ width: 100%;+ border-radius: var(--bkd-radius, 12px) var(--bkd-radius, 12px) 0 0;+ max-height: 88vh;+ }+}diff --git a/kernel/src/ui/dialog.ts b/kernel/src/ui/dialog.tsnew file mode 100644index 00000000..5650faba--- /dev/null+++ b/kernel/src/ui/dialog.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SHARED MODAL DIALOG primitive — tier 3, and the one of that tier's four+// that is a real consolidation. All four apps build their About dialog (and+// their smaller confirms) on a per-app overlay: slides `.ed-about-overlay`,+// spaces `.sp-overlay`, dash `.dx-about`, type `.t-overlay`, each with its own+// open/close in an about.ts. This is the substrate they share.+//+// WHERE "SLIDES IS THE BASIS" GIVES THE LEAST — and the brief said so up front.+// slides' dialog machinery is one class (`.ed-dialog-actions`); it blurs the+// active element and removes an overlay. The fuller behaviour is in spaces' and+// type's about.ts, and this primitive takes it from there:+//+// spaces captures document.activeElement on open and RESTORES it on close,+// and closes on a CAPTURE-PHASE, document-level Escape (its own+// comment: "a dialog whose Escape must win over the editor's").+// type a named keydown handler removed on close, stopPropagation on Escape.+// dash an actions() row builder — the [Cancel] [Confirm] pattern.+// slides blur-the-opener, so a keystroke does not fall through to the canvas.+//+// What NO app had, and the primitive adds because a modal without it is a modal+// only for the mouse: a real focus TRAP (Tab cycles within the card), backdrop+// dismissal, `role="dialog"` + `aria-modal` + `aria-labelledby`, and — detail 9+// and 10 — a `position: fixed` scrim at a z above the topbar's ceiling so the+// dialog escapes every ancestor stacking context and clip.+//+// Values are the host app's, through `--bkd-*` fallback chains onto whatever the+// app already defines (dialog.css); never light-dark(); the shared theming+// guard (scripts/lib/ui-theme-guard.ts) checks it. Kernel half only.++export interface DialogOpts {+ /** Accessible title. Rendered as the card's heading and wired to+ * `aria-labelledby`; omit to supply your own labelled content and pass+ * `label` instead. */+ title?: string+ /** aria-label when there is no visible title. */+ label?: string+ /** The dialog body — the app's content. */+ content: HTMLElement+ /** Optional actions row (buttons). Rendered pinned at the card's foot. */+ actions?: HTMLElement[]+ /** Called after the dialog closes, however it closed. */+ onClose?: () => void+ /** Backdrop click closes (default true). A confirint dialog may want false so+ * a stray click cannot dismiss an unanswered question. */+ dismissOnBackdrop?: boolean+}++export interface Dialog {+ /** The full-viewport overlay (scrim). Appended to the body on open. */+ readonly root: HTMLElement+ /** The dialog card. */+ readonly card: HTMLElement+ readonly isOpen: boolean+ open(): void+ close(): void+}++const FOCUSABLE =+ 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'++let seq = 0++export function createDialog(opts: DialogOpts): Dialog {+ const id = `bkd-title-${++seq}`+ const root = document.createElement('div')+ root.className = 'bkd-overlay'++ const card = document.createElement('div')+ card.className = 'bkd-card'+ card.setAttribute('role', 'dialog')+ card.setAttribute('aria-modal', 'true')+ card.tabIndex = -1+ if (opts.title) card.setAttribute('aria-labelledby', id)+ else if (opts.label) card.setAttribute('aria-label', opts.label)++ if (opts.title) {+ const h = document.createElement('h2')+ h.className = 'bkd-title'+ h.id = id+ h.textContent = opts.title+ card.appendChild(h)+ }+ opts.content.classList.add('bkd-body')+ card.appendChild(opts.content)+ if (opts.actions?.length) {+ const bar = document.createElement('div')+ bar.className = 'bkd-actions'+ for (const b of opts.actions) bar.appendChild(b)+ card.appendChild(bar)+ }+ root.appendChild(card)++ let open = false+ let returnFocus: HTMLElement | null = null++ const focusables = (): HTMLElement[] =>+ [...card.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => el.offsetParent !== null || el === card)++ // Capture-phase, on the document, so the dialog's Escape wins over an editor+ // that also listens for it (spaces' hard-won rule), and so Tab can be trapped+ // before anything else acts on it.+ function onKey(e: KeyboardEvent): void {+ if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); api.close(); return }+ if (e.key !== 'Tab') return+ // The focus TRAP no app had: Tab off either end of the card wraps to the+ // other end, so focus can never leave an open modal.+ const f = focusables()+ if (!f.length) { e.preventDefault(); card.focus(); return }+ const first = f[0], last = f[f.length - 1]+ const active = document.activeElement as HTMLElement | null+ if (e.shiftKey && (active === first || active === card)) { e.preventDefault(); last.focus() }+ else if (!e.shiftKey && active === last) { e.preventDefault(); first.focus() }+ }++ const onBackdrop = (e: MouseEvent): void => {+ if (e.target === root && (opts.dismissOnBackdrop ?? true)) api.close()+ }++ const api: Dialog = {+ root,+ card,+ get isOpen() { return open },+ open(): void {+ if (open) return+ open = true+ returnFocus = document.activeElement as HTMLElement | null+ document.body.appendChild(root)+ document.addEventListener('keydown', onKey, true)+ root.addEventListener('mousedown', onBackdrop)+ // Move focus into the card: the first focusable, else the card itself, so+ // the very next keystroke is the dialog's, not the surface behind it.+ ;(focusables()[0] ?? card).focus()+ },+ close(): void {+ if (!open) return+ open = false+ document.removeEventListener('keydown', onKey, true)+ root.removeEventListener('mousedown', onBackdrop)+ root.remove()+ // Restore focus to whatever opened the dialog — a keyboard user is put+ // back where they were, not dropped on document.body.+ try { returnFocus?.focus() } catch { /* opener is gone */ }+ returnFocus = null+ opts.onClose?.()+ },+ }+ return api+}diff --git a/scripts/test-ui-dialog.ts b/scripts/test-ui-dialog.tsnew file mode 100644index 00000000..94ca2bfb--- /dev/null+++ b/scripts/test-ui-dialog.ts@@ -0,0 +1,189 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The shared kernel MODAL DIALOG primitive — behaviour rig.+//+// node scripts/test-ui-dialog.ts+//+// kernel/src/ui/dialog.ts is the real consolidation of tier 3: all four apps+// build their About dialog on a per-app overlay. Every check guards behaviour+// that was in one app and not the others, or in none:+// - focus captured on open and RESTORED to the opener on close (spaces);+// - Escape closes and does NOT fall through — the dialog's handler is+// capture-phase on the document (spaces' hard-won rule);+// - the backdrop dismisses, a click on the card does not, and a confirm+// dialog can refuse backdrop dismissal;+// - a real focus TRAP (Tab wraps within the card) — no app had one;+// - role=dialog / aria-modal / aria-labelledby;+// - close removes the overlay AND both its listeners (no leak).+// Self-contained DOM, like scripts/test-sync-vouch.ts and test-ui-panel.ts.++import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'+import { checkThemedChains } from './lib/ui-theme-guard.ts'+const rroot = join(dirname(fileURLToPath(import.meta.url)), '..')++type Handler = (e: unknown) => void+class El {+ tag: string+ children: El[] = []+ parent: El | null = null+ private attrs = new Map<string, string>()+ private classes = new Set<string>()+ private bub = new Map<string, Handler[]>()+ tabIndex = -1+ text = ''+ offsetParent: unknown = {}+ constructor(tag: string) { this.tag = tag }+ get classList() { const c = this.classes; return { add: (x: string) => c.add(x), remove: (x: string) => c.delete(x), contains: (x: string) => c.has(x) } }+ set className(v: string) { this.classes = new Set(v.split(/\s+/).filter(Boolean)) }+ get className() { return [...this.classes].join(' ') }+ set textContent(v: string) { this.text = v }+ setAttribute(k: string, v: string) { this.attrs.set(k, v) }+ getAttribute(k: string) { return this.attrs.get(k) ?? null }+ set id(v: string) { this.attrs.set('id', v) }+ get id() { return this.attrs.get('id') ?? '' }+ appendChild(x: El) { x.parent = this; this.children.push(x); return x }+ append(...xs: El[]) { for (const x of xs) this.appendChild(x) }+ remove() { if (this.parent) { this.parent.children = this.parent.children.filter((c) => c !== this); this.parent = null } }+ contains(x: El | null) { for (let n = x; n; n = n.parent) if (n === this) return true; return false }+ addEventListener(t: string, fn: Handler) { this.bub.set(t, [...(this.bub.get(t) ?? []), fn]) }+ removeEventListener(t: string, fn: Handler) { this.bub.set(t, (this.bub.get(t) ?? []).filter((f) => f !== fn)) }+ listenerCount(t: string) { return (this.bub.get(t) ?? []).length }+ fire(t: string, target: El) { for (const fn of [...(this.bub.get(t) ?? [])]) fn({ target, preventDefault() {}, stopPropagation() {} }) }+ focus() { doc.activeElement = this }+ private descend(out: El[]) { for (const c of this.children) { out.push(c); c.descend(out) } }+ querySelectorAll(_sel: string): El[] {+ const all: El[] = []; this.descend(all)+ return all.filter((e) => ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'].includes(e.tag.toUpperCase()) || e.tabIndex >= 0)+ }+}+class Doc {+ body = new El('body')+ activeElement: El | null = null+ private cap = new Map<string, Handler[]>()+ private bub = new Map<string, Handler[]>()+ createElement(t: string) { return new El(t) }+ addEventListener(t: string, fn: Handler, capture?: boolean) { const m = capture ? this.cap : this.bub; m.set(t, [...(m.get(t) ?? []), fn]) }+ removeEventListener(t: string, fn: Handler, capture?: boolean) { const m = capture ? this.cap : this.bub; m.set(t, (m.get(t) ?? []).filter((f) => f !== fn)) }+ capCount(t: string) { return (this.cap.get(t) ?? []).length }+ fireKey(key: string, shiftKey = false) {+ let stopped = false+ const ev = { key, shiftKey, preventDefault() {}, stopPropagation() { stopped = true } }+ for (const fn of [...(this.cap.get('keydown') ?? [])]) { fn(ev); if (stopped) return }+ for (const fn of [...(this.bub.get('keydown') ?? [])]) fn(ev)+ }+}+const doc = new Doc()+;(globalThis as Record<string, unknown>).document = doc++const { createDialog } = await import('../kernel/src/ui/dialog.ts')++let failures = 0, checks = 0+function ok(cond: unknown, msg: string) { checks++; if (!cond) { failures++; console.error(` ✗ ${msg}`) } }+function eq(msg: string, got: unknown, want: unknown) { checks++; if (got !== want) { failures++; console.error(` ✗ ${msg}\n got ${got} want ${want}`) } }+const E = (x: unknown) => x as unknown as El+const content = () => new El('div') as unknown as HTMLElement+const btn = (label: string) => { const b = new El('button'); b.textContent = label; return b as unknown as HTMLElement }++// ——— aria + structure ———+{+ const d = createDialog({ title: 'About', content: content(), actions: [btn('OK'), btn('Cancel')] })+ eq('card is role=dialog', E(d.card).getAttribute('role'), 'dialog')+ eq('card is aria-modal', E(d.card).getAttribute('aria-modal'), 'true')+ ok(E(d.card).getAttribute('aria-labelledby'), 'a titled dialog is aria-labelledby')+ ok(E(d.card).querySelectorAll('button').length >= 2, 'the actions row is rendered')+ const d2 = createDialog({ label: 'Rename', content: content() })+ eq('an untitled dialog uses aria-label', E(d2.card).getAttribute('aria-label'), 'Rename')+}++// ——— open mounts + focuses in; close unmounts + restores ———+{+ const opener = new El('button'); doc.activeElement = opener+ const first = btn('First')+ const c = content(); E(c).appendChild(E(first))+ const d = createDialog({ title: 'T', content: c })+ d.open()+ ok(doc.body.contains(E(d.root)), 'open mounts the overlay')+ eq('focus moves to the first focusable', doc.activeElement, E(first))+ ok(d.isOpen, 'isOpen true')+ d.close()+ ok(!doc.body.contains(E(d.root)), 'close unmounts the overlay')+ eq('focus is restored to the opener', doc.activeElement, opener)+}++// ——— Escape closes, capture-phase, no fall-through ———+{+ let bubbleSaw = false+ const probe = () => { bubbleSaw = true }+ doc.addEventListener('keydown', probe) // an "editor" listener on the bubble phase+ const d = createDialog({ title: 'T', content: content() })+ d.open()+ doc.fireKey('Escape')+ ok(!d.isOpen, 'Escape closes the dialog')+ ok(!bubbleSaw, 'the capture-phase Escape does NOT reach a bubble listener behind it')+ doc.removeEventListener('keydown', probe)+}++// ——— backdrop dismisses; the card does not; and it can be refused ———+{+ const d = createDialog({ title: 'T', content: content() })+ d.open()+ E(d.card).fire('mousedown', E(d.card)) // wrong target: a click inside the card+ // the dialog listens on root; fire on root with target=card+ E(d.root).fire('mousedown', E(d.card))+ ok(d.isOpen, 'a mousedown on the card does not dismiss')+ E(d.root).fire('mousedown', E(d.root)) // target is the scrim itself+ ok(!d.isOpen, 'a mousedown on the backdrop dismisses')++ const d2 = createDialog({ title: 'Confirm', content: content(), dismissOnBackdrop: false })+ d2.open()+ E(d2.root).fire('mousedown', E(d2.root))+ ok(d2.isOpen, 'a dialog with dismissOnBackdrop:false ignores the backdrop')+ d2.close()+}++// ——— the focus trap: Tab wraps within the card ———+{+ const a = btn('A'), b = btn('B'), c = btn('C')+ const body = content(); E(body).append(E(a), E(b), E(c))+ const d = createDialog({ title: 'T', content: body })+ d.open()+ E(c).focus() // last+ doc.fireKey('Tab')+ eq('Tab off the last focusable wraps to the first', doc.activeElement, E(a))+ E(a).focus() // first+ doc.fireKey('Tab', true) // shift+Tab+ eq('Shift+Tab off the first wraps to the last', doc.activeElement, E(c))+ d.close()+}++// ——— close cleans up: overlay gone, document listener removed, onClose fired ———+{+ const before = doc.capCount('keydown')+ let closed = 0+ const d = createDialog({ title: 'T', content: content(), onClose: () => { closed++ } })+ d.open()+ eq('open adds one capture-phase keydown listener', doc.capCount('keydown') - before, 1)+ d.close()+ eq('close removes it (no leak)', doc.capCount('keydown'), before)+ eq('onClose fired once', closed, 1)+ d.close()+ eq('a second close is a no-op', closed, 1)+}++// ——— THEMING GUARD (shared helper) ———+{+ const appStyles = Object.fromEntries(+ ['slides', 'spaces', 'dash', 'type'].map((a) => [a, join(rroot, `${a}/src/styles.css`)]),+ )+ for (const r of checkThemedChains({+ cssPath: join(rroot, 'kernel/src/ui/dialog.css'),+ prefix: 'bkd',+ colourProps: new Set(['bg', 'ink', 'body-ink', 'border']),+ appStyles,+ })) ok(r.pass, r.msg)+}++console.log(failures ? `\n${failures} FAILED of ${checks}` : `\ntest-ui-dialog: ${checks} checks OK`)+process.exit(failures ? 1 : 0)