Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: the shared menu primitive (UI primitives, tier 1 of 4) (#432)
nyblnet7ae7d3ee6bf6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e977494d..e8cf2dd4 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 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 apps+ # publish no aria-expanded at all, five of slides' eight dropdowns never+ # dismissed on an outside press, no app closed a menu on Escape or let+ # an arrow key move through one, and two apps added a document listener+ # per dropdown and removed none. Each of those is a check here, because+ # every one of them is a regression a sighted developer with a mouse+ # would never notice.+ run: node scripts/test-ui-menu.ts- name: First-page preview rig# Every save writes a static render of page one for file-managerdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 2a0a374f..38495f31 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6578,3 +6578,103 @@ Pointers: `kernel/src/ui/panel.ts`, `kernel/src/ui/panel.css`,`scripts/test-ui-panel.ts` (62 checks; the drag/RTL/collapse/persistence/drawerbehaviours are each mutation-caught, and the theming guard is reproduced fromtier 1 — to be factored into one shared helper when both primitives have landed).+## 2026-09-09 — Shared UI primitives live in the kernel; the menu is the first, and values stay the app's++**Decision.** The seven UI primitives every Bento app implements independently+move into `kernel/src/ui/`, one at a time, each as its own serialized kernel PR.+The menu/dropdown is first: `kernel/src/ui/menu.ts` + `menu.css`, guarded by+`scripts/test-ui-menu.ts`. **This lands the shared definition only — each app's+migration is that app zone's own change**, per the kernel zone's rule that a+kernel PR never carries the app half.++**Why, and it is not bytes.** Each Bento app is one self-contained file, so+shared code is bundled into each anyway; measured, the primitive adds 604+compressed bytes to the slides shell while slides still carries its own menu+code as well. A general primitive can easily cost more than the specific thing+one app needed. The return is elsewhere.++Comparing CSS selector NAMES across the apps finds nothing — two apps+implementing the identical dropdown as `.ed-menu` and `.dv-menu` register as+zero overlap, which is why an earlier count of 11 shared selectors out of 2,156+concluded, wrongly, that there was nothing to share. Compared by CONCEPT, seven+primitives are implemented four times over. The dropdown is one design copied+four times, and the tell is the offset from the trigger: slides `calc(100% ++4px)`, spaces `+5px`, dash `+6px`, type `+6px`. Nobody designed 4, 5, 6, 6.++**The real cost is that hard-won knowledge has nowhere to live.** CLAUDE.md's+hard-won details 9 and 10 — a flex item's `z-index` is a CEILING that caps every+descendant, and `overflow-y: auto` also clips HORIZONTALLY — cost slides real+debugging. Slides, spaces AND dash each record both traps in their own source,+because each hit the same wall independently. Type records only one. Three teams+paid for the same two lessons, and the only home either lesson had was a comment+in one app's CSS. `menu.css` is now that home.++**What differed between the four was invisible, and that is what the primitive+fixes.** Of slides' eight dropdowns, five had no outside-press dismissal at all,+one hand-rolled it inline and two called a helper; none closed on Escape. Three+of the four apps publish no `aria-expanded` anywhere. No app had arrow-key+navigation. slides and spaces each add document listeners per dropdown and+remove none. So the primitive takes dash's single delegated listener pair and+mutual exclusion, spaces' ARIA and disabled/selected row semantics, slides'+split-button and phone-fold structure — and adds the arrow-key navigation and+focus-return that no app had.++**"Slides is the basis" is true of the CSS and false of the behaviour.** It was+the maintainer's default and it holds for structure; where slides has the least,+the fuller implementation wins on its merits and this entry says which.++**Token VALUES are deliberately NOT settled here**, and neither is the theming+MECHANISM. dash has `--line-strong`, `--shadow-pop`, `--radius-lg` and `--hover`+that the other three lack, and a `--radius` of 7px against their 10px. Separately+— and more importantly for a shared sheet — the four theme by three different+mechanisms: slides and type via `:root[data-theme="dark"]`, spaces via that AND a+`prefers-color-scheme` media query, dash via `light-dark()`, which resolves off+`color-scheme`. All four DO have a dark theme; what differs is who decides.++**A shared stylesheet therefore cannot express themed values with+`light-dark()`.** slides sets `:root { color-scheme: only light }` deliberately+(`slides/src/styles.css:96`) because without it a dark-mode phone renders native+form controls dark under the app's dark ink — "blank" dropdowns — and Chrome on+Android may force-darken the page. Under `only light`, every `light-dark()`+value pins to its light half forever, so a shared sheet built on it would+silently cost slides the dark theme it already has.++`menu.css` sidesteps all of it: every value reads through a `--bkm-*` property+whose fallback chain **consumes whatever themed token the host app already+defines, by whichever mechanism that app themes it**. That is why one sheet+survives four theming mechanisms without picking one, why adoption is+appearance-neutral, and why tier 1 did not have to wait for the mechanism+ruling. Only two values had to be picked, because a shared rule cannot hold+four: the trigger offset (6px) and the stacking level (60), each the majority+and each overridable per app.++**The literal at the end of a themed chain is a latent dark-mode bug**, and this+is the one defect tier 1 actually shipped and then caught. A chain ends in a+light-only literal so the rule is never invalid; an app defining none of the+tokens above it silently gets that literal in DARK mode. `type` has no+`--surface` — its chrome surface token is `--field` — so `--bkm-bg` fell through+to `#fff`, which would have painted a white menu under light ink. Fixed by+extending the chain, and guarded by `scripts/test-ui-menu.ts`, which now asserts+statically that every colour chain reaches a token each of the four apps both+DEFINES and THEMES. A comment naming the gap was not enough; it named this one+and the fallback was still wrong.++**A boundary for tier 4, found here and not settled here.** Menus are chrome,+and chrome should follow the theme — every app already themes the token this+sheet consumes. The DOCUMENT must not, which `kernel/src/theme.ts:17-18` states+outright. `type` draws that line explicitly and correctly, with `--paper` for+the page and `--field` commented "form-control surface — CHROME, not paper".+The shared token set should make that distinction explicit rather than inherit+whichever app's habit arrives first.++**The kernel ships CSS now, which it never did before.** Verified end to end+rather than assumed: an app's `import '../../kernel/src/ui/menu.css'` is folded+by Vite into the single stylesheet that `scripts/postbuild-compress.mjs`+deflates into the `#bento-rt-css` payload, and the rules inflate intact out of+the built shell. No build change was needed. `menu.ts` deliberately does NOT+import its own stylesheet: keeping them separate is what lets the rig exercise+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 by+function), `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).diff --git a/kernel/src/ui/menu.css b/kernel/src/ui/menu.cssnew file mode 100644index 00000000..dcef4a2e--- /dev/null+++ b/kernel/src/ui/menu.css@@ -0,0 +1,307 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors++ THE SHARED MENU PRIMITIVE'S STYLES. See menu.ts for why this exists and what+ each of the four apps contributed.++ THIS IS THE FIRST CSS THE KERNEL HAS EVER SHIPPED. It reaches a build the way+ every other kernel module does — an app imports it, and Vite folds it into the+ one stylesheet that `scripts/postbuild-compress.mjs` then deflates into the+ `#bento-rt-css` payload. Nothing in the build needed changing for that, but it+ is worth stating plainly, because that script matches exactly ONE+ `<style rel="stylesheet">` and has been fooled before by a `<style>` that was+ really a JS string literal.++ ————— VALUES ARE THE HOST APP'S, STRUCTURE AND BEHAVIOUR ARE SHARED —————++ The four apps disagree about tokens: dash has `--line-strong`,+ `--shadow-pop`, `--radius-lg` and `--hover`, which the other three lack, and+ a `--radius` of 7px against their 10px. Resolving that is a maintainer's+ ruling and it is tier 4 of this project, so this file does not pre-empt it.++ They ALSO disagree about the theming MECHANISM, which matters more here and+ is the reason this sheet imposes none:++ slides :root[data-theme="dark"] + :root { color-scheme: only light }+ type :root[data-theme="dark"]+ spaces [data-theme="dark"] AND a prefers-color-scheme media query+ dash light-dark() + a media query — i.e. color-scheme, i.e. the OS++ All four DO have a dark theme; `--ink: #e7eaf0` sits in three of the dark+ blocks (slides:39, spaces:165, type:75). What differs is who decides.++ A SHARED SHEET MUST NOT USE `light-dark()`. It resolves off `color-scheme`,+ and slides sets `:root { color-scheme: only light }` deliberately+ (styles.css:96) — without it, dark-mode phones render native form controls+ dark while the app's ink stays dark ("blank" dropdowns), and Chrome on+ Android may force-darken the page. Under `only light` every `light-dark()`+ value pins to its LIGHT half forever, so a shared sheet built on it would+ silently cost slides the dark theme it already has.++ The fallback chains below sidestep the whole question: they CONSUME whatever+ themed token the host app already defines, by whichever mechanism that app+ themes it. That is why this one sheet survives four different theming+ mechanisms without picking one, and it is why tier 1 does not have to wait+ for the tier 4 ruling.++ A NOTE FOR TIER 4, found here and not settled here. Menus are CHROME, and+ chrome SHOULD follow the theme — every app already themes the token this+ sheet consumes for it. The document must not. type draws that line+ explicitly and correctly: `--paper` is the page, `--field` is "form-control+ surface — CHROME, not paper", and only the second is a menu's business. The+ shared token set should make that boundary explicit rather than inherit+ whichever app's habit arrives first. kernel/src/theme.ts:17-18 already says+ a theme is a viewer preference and the document does not invert; the token+ names are where an app either honours that or quietly does not.++ Instead every value reads through a `--bkm-*` property whose fallback chain+ lands on whatever the host already defines. An app that defines+ `--line-strong` (dash) gets its stronger edge; an app that does not (the+ other three) falls through to `--line`. Adopting this primitive therefore+ changes no app's appearance, which is what makes tier 1 safe to land before+ the token question is settled. An app that wants something else sets+ `--bkm-*` on its own root — type will need `--bkm-bg: var(--field)`, because+ it paints menus on `--field` where the other three use `--surface`.++ Two values could not be deferred, because a shared rule has to pick one:++ the offset from the trigger 4px / 5px / 6px / 6px → 6px+ the stacking level 50 / 60 / 60 / 60 → 60++ Both are the majority of the four, and both stay overridable. slides moves+ 2px and spaces 1px on adoption; that difference was never designed. */++.bkm {+ /* The wrapper is the positioning context. It must be `relative` and it must+ not establish anything else — see the z-index note below. */+ position: relative;+ display: inline-flex;+ align-items: center;+}++.bkm-menu {+ display: none;+ position: absolute;+ top: calc(100% + var(--bkm-gap, 6px));+ inset-inline-start: 0;+ flex-direction: column;+ min-width: var(--bkm-min-width, 200px);+ padding: 5px;+ /* `--field` is in the chain because type has no `--surface` — its chrome+ surface token is `--field`, themed #ffffff → #12151a and commented "form-+ control surface — CHROME, not paper". Without it this fell through to the+ literal below, which is LIGHT-ONLY, so a type menu in dark mode would have+ painted white under light ink. A hardcoded literal at the end of a themed+ chain is a dark-mode bug waiting for the first app that misses the token,+ which is why `scripts/test-ui-menu.ts` now asserts every chain here+ resolves to a token each app actually defines, rather than trusting this+ comment to be remembered. */+ background: var(--bkm-bg, var(--surface, var(--field, #fff)));+ border: 1px solid var(--bkm-border, var(--line-strong, var(--line, #e3e8ef)));+ border-radius: var(--bkm-radius, var(--radius-lg, var(--radius, 10px)));+ box-shadow: var(--bkm-shadow, var(--shadow-pop, 0 12px 32px rgb(20 30 45 / 0.16)));++ /* ————— HARD-WON DETAIL 9, and the reason this primitive exists —————++ `z-index` on the BAR that contains a menu is a CEILING, not just an order.+ A topbar is a flex item of the app root, and a flex item honours `z-index`+ even at `position: static` — so the value opens a stacking context that+ caps every descendant. In slides the bar sat at 20 and this menu asked for+ 50; it was clamped to 20, and the phone panel drawers at 40 painted+ straight over it. The menu rendered in full and every click landed on the+ panel behind it. Raising THIS number can never fix that — only the+ ceiling moves.++ Diagnose it with `document.elementsFromPoint()`, which is how it was found:+ the menu sat fourth in the stack under its own coordinates.++ slides, spaces and dash each hit this independently and each wrote it down+ in their own source. Type hit it and did not. This comment is the first+ place that knowledge lives once rather than three times. */+ z-index: var(--bkm-z, 60);+}++.bkm.bkm-open > .bkm-menu {+ display: flex;+}++/* DIRECT child, not any descendant. Phone chrome demotes whole dropdown widgets+ into a ⋯ menu, so a descendant selector opens their popups too — slides' ⋯+ came up with the entire language list already unrolled inside it. Every+ `.bkm-menu` is appended straight onto its own `.bkm`, so `>` is exact. */++/* A menu hanging off a control near the inline-end edge grows AWAY from the+ screen if it is start-anchored. Three of the four apps discovered this and+ each wrote a bespoke selector for it — `.ed-topbar.ed-bar-fold .ed-menu`,+ `.sp-dd:last-child .sp-ddmenu`, `.dx-data-dd > .dx-menu`. It is an option+ here instead. */+.bkm.bkm-end > .bkm-menu {+ inset-inline-start: auto;+ inset-inline-end: 0;+}++/* Never wider than the screen. dash's save menu is 260px and hangs off a button+ in the right half of the bar; on a phone a start-anchored panel that wide+ simply walks off the edge. */+.bkm-menu {+ max-width: calc(100vw - 16px);+}++/* ————— rows ————— */++.bkm-item {+ display: flex;+ align-items: center;+ gap: 9px;+ width: 100%;+ font: inherit;+ font-size: var(--bkm-font-size, 13px);+ color: var(--bkm-ink, var(--ink-2, var(--ink, #1e2a3a)));+ text-align: start;+ background: transparent;+ border: 0;+ border-radius: var(--bkm-item-radius, 7px);+ padding: 7px 9px;+ cursor: pointer;+}++.bkm-item:hover {+ background: var(--bkm-hover, var(--hover, var(--chrome-2, rgb(0 0 0 / 0.05))));+}++/* The keyboard has to leave as clear a trail as the mouse does. No app's menu+ had arrow-key navigation at all, so none of them needed this; all four+ inherit both at once. `:focus-visible` rather than `:focus` so a pointer user+ never sees a ring they did not ask for. */+.bkm-item:focus-visible {+ outline: 2px solid var(--bkm-focus, var(--accent-ink, currentColor));+ outline-offset: -2px;+ background: var(--bkm-hover, var(--hover, var(--chrome-2, rgb(0 0 0 / 0.05))));+}++/* Present but not runnable — folded undo/redo on a phone. DISABLED, not hidden,+ so the menu does not change shape as you edit. 0.35 is dash's figure for a+ dead control and it is the one with a reason attached. */+.bkm-item.bkm-off {+ opacity: 0.35;+ cursor: default;+ pointer-events: none;+}++.bkm-item.bkm-selected .bkm-text {+ font-weight: 700;+}++.bkm-ico {+ display: inline-flex;+ color: var(--bkm-ico, var(--muted, #6b7789));+ flex: none;+}++.bkm-ico svg {+ display: block;+}++.bkm-body {+ display: block;+ min-width: 0;+}++/* A row that TEACHES rather than naming a command needs to WRAP. dash cut+ "Typed columns — for volume, joins and charts" mid-phrase inside a 220px+ menu, because the row inherited a one-line ellipsis meant for "Rename". A+ truncated explanation of a central concept explains nothing and reads as a+ bug. */+.bkm-hint {+ display: block;+ font-size: var(--bkm-hint-size, 12px);+ line-height: 1.35;+ color: var(--muted, #6b7789);+ white-space: normal;+}++.bkm-text {+ display: block;+}++.bkm-sep {+ height: 1px;+ background: var(--bkm-border, var(--line, #e3e8ef));+ margin: 4px 6px;+}++/* ————— HARD-WON DETAIL 10: a scrolling menu is a CLIPPING BOX —————++ A menu that can outgrow the screen needs a `max-height`, and `overflow-y:+ auto` cannot be had on its own: set either axis to a non-`visible` value and+ the browser computes the OTHER to `auto` too. So the moment a menu scrolls,+ it clips horizontally as well.++ slides paid for this. Phone chrome demotes whole dropdown widgets (Share,+ Language) into the ⋯ menu, and the share popover is 250px anchored to its+ parent's end — inside a 200px menu it hung 55px off the left and 69px below,+ both silently cut, and the properties panel underneath showed THROUGH the+ gap, so the popover looked interleaved with the panel behind it.++ A floating child can never escape a scroll container. So it stops floating:+ a menu nested inside a scrolling menu renders as a SECTION of the list,+ scrolling with it and taking its width. Nothing can be clipped because+ nothing overhangs.++ dash has two menus built this way today with nothing floating inside them+ yet. Nothing stopped the next person putting something there; now this rule+ does, for every app at once. */+.bkm-menu.bkm-scroll {+ max-height: var(--bkm-max-height, calc(100dvh - 96px));+ overflow-y: auto;+ -webkit-overflow-scrolling: touch;+}++.bkm-menu.bkm-scroll .bkm-menu {+ position: static;+ min-width: 0;+ max-width: none;+ max-height: none;+ overflow: visible;+ box-shadow: none;+ background: transparent;+ border: 0;+ border-radius: 0;+ border-block: 1px solid var(--bkm-border, var(--line, #e3e8ef));+ margin-block: 3px;+ padding-inline: 6px;+}++/* ————— a bar that scrolls —————++ Below the fold's floor a topbar scrolls itself: fully folded slides' bar+ still needs ~356px and an iPhone SE is 320px, so the excess was simply cut+ off and ⋯ could not be reached at all. A scroll container clips BOTH axes+ (see above), so a menu hanging off a button in that bar would now be cut off+ by the bar itself. `fixed` takes it out of that clip. It costs nothing extra+ to anchor, because a bar this narrow pins its menus to the end of the screen+ rather than to their trigger anyway.++ The one thing this cannot read from CSS is where the bar ENDS, because that+ moves with the safe-area insets — the app publishes it as `--bkm-bar-bottom`+ (slides already computes exactly this as `--ed-bar-bottom`). */+.bkm-fixed.bkm-open > .bkm-menu {+ position: fixed;+ top: calc(var(--bkm-bar-bottom, 56px) + var(--bkm-gap, 6px));+ inset-inline-end: max(6px, env(safe-area-inset-right), var(--tray-safe-right, 0px));+ inset-inline-start: auto;+}++/* Touch targets. A menu row on a phone is a 44px target like everything else. */+@media (max-width: 700px) {+ .bkm-item {+ padding-block: 11px;+ }+}++@media (prefers-reduced-motion: no-preference) {+ /* Deliberately no open/close animation. Three of the four apps have none, the+ fourth animates only its phone sheet, and a menu that fades is a menu whose+ first click can land before it is there. Kept as an explicit note so the+ absence reads as a decision rather than an oversight. */+}diff --git a/kernel/src/ui/menu.ts b/kernel/src/ui/menu.tsnew file mode 100644index 00000000..7b866d5b--- /dev/null+++ b/kernel/src/ui/menu.ts@@ -0,0 +1,342 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SHARED MENU / DROPDOWN PRIMITIVE — the first of the kernel UI primitives.+//+// WHY THIS EXISTS. Four apps had four dropdowns, and they are one design copied+// four times. The tell is the offset from the trigger: slides `calc(100% + 4px)`,+// spaces `+5px`, dash `+6px`, type `+6px`. Nobody designed 4, 5, 6, 6 — that is+// copy-paste-and-tweak, and it is history rather than intent.+//+// The cost was never bytes. Each app is one self-contained file, so shared code+// is bundled into each anyway and this primitive may well make the shells+// slightly BIGGER. What four copies actually cost is that no piece of hard-won+// knowledge about menus has anywhere to live. CLAUDE.md's hard-won details 9 and+// 10 — a flex item's z-index is a CEILING that caps every descendant, and+// `overflow-y: auto` also clips HORIZONTALLY — were paid for by slides, and+// reached spaces and dash only because each of them independently hit the same+// wall. Type records only one of the two. Three teams bought the same two+// lessons. A shared primitive is the only place that knowledge can live once.+//+// WHAT EACH APP CONTRIBUTED, because "slides is the basis" is true of the CSS+// and false of the behaviour, and the difference is the whole point:+//+// slides the richest STRUCTURE — the split button, and the phone treatment+// where a folded bar scrolls and its menus go `position: fixed`+// against `--ed-bar-bottom` to escape the scroller's clip. Also the+// WEAKEST behaviour of the four: of its eight dropdowns, five have no+// outside-press dismissal at all, one hand-rolls it inline, two call a+// helper — and not one of them closes on Escape or carries a single+// `aria-haspopup` or `aria-expanded`.+// dash the best BEHAVIOUR — one delegated listener pair for every menu in+// the app rather than a fresh pair per instance, mutual exclusion+// (opening one shuts the others), Escape, and dismiss-on-choose.+// spaces the only real ACCESSIBILITY — `aria-haspopup`, `aria-expanded`,+// `role=menu`/`menuitem`, `aria-current` for a selected row and+// `aria-disabled` for a row that exists but cannot run right now.+// Also the only viewport-aware placement (`place()`), and the phone+// bottom-sheet.+// type the thinnest, and the one that shows what copying costs: it hides+// with the `hidden` attribute rather than a state class (a fifth+// mechanism), hardcodes its radius and shadow instead of using+// tokens, and paints on `--field` where the other three use+// `--surface`.+//+// So this primitive takes dash's delegation, spaces' semantics, and slides'+// structure — and adds the one thing NO app has: arrow-key navigation. A menu+// you can open with the keyboard and then not move through is a menu a keyboard+// user is not actually inside.+//+// WHAT THIS DELIBERATELY DOES NOT DECIDE. The four apps disagree on token+// VALUES — dash has diverged forward with `--line-strong`, `--shadow-pop`,+// `--radius-lg` and a `light-dark()` dark mode, against the other three's+// `--line`, a literal shadow and `--radius`. Which way that resolves is the+// maintainer's ruling and it is tier 4 of this project, not this file's to make.+// So every value here reads through a `--bkm-*` custom property whose fallback+// chain lands on whatever the host app already defines (see menu.css). An app+// adopting this primitive keeps the look it has today; only the structure and+// the behaviour are shared. The two places that could not be deferred are the+// trigger offset and the stacking level, where a single value had to be picked:+// 6px and 60, each the majority of the four, each overridable per app.++/** A row in a menu. `off` is a command that exists but cannot run right now;+ * `selected` is the choice a view is currently on. They are different things —+ * spaces learned that when they arrived as two separate 5th parameters on two+ * branches — and a row may be neither. */+export interface MenuItemOpts {+ /** Inline SVG (or any markup) for the row's leading icon. */+ icon?: string+ /** Secondary line under the label. */+ hint?: string+ /** Present but not runnable: dimmed, unfocusable, announced `aria-disabled`. */+ off?: boolean+ /** The option currently in force: announced `aria-current`. */+ selected?: boolean+ /** Skip the default "choosing a row closes the menu". */+ keepOpen?: boolean+}++export interface MenuOpts {+ /** Extra classes for the wrapper, e.g. an app's own `ed-split`. */+ className?: string+ /** Extra classes for the popup itself, e.g. an app's `ed-share-pop`. */+ menuClass?: string+ /** Anchor the popup to the end of the trigger rather than the start. Used by+ * a menu that hangs off a control near the inline-end edge, where a+ * start-anchored popup grows off the screen. */+ alignEnd?: boolean+ /** Rebuild the rows every time it opens. A row's label can be a function of+ * state — "Hide comments" becomes "Show comments" — and rendering it once at+ * mount leaves it permanently wrong after the first use. */+ fill?: (menu: HTMLElement, close: () => void) => void+}++export interface Menu {+ /** The positioned wrapper. Put this in the bar. */+ readonly root: HTMLElement+ /** The button that opens it. */+ readonly trigger: HTMLButtonElement+ /** The popup. Append rows here, or let `fill` do it. */+ readonly menu: HTMLElement+ readonly isOpen: boolean+ open(): void+ close(): void+ toggle(): void+ /** Build a row. Appends to the popup unless `into` says otherwise. */+ item(label: string, onClick: () => void, opts?: MenuItemOpts): HTMLButtonElement+ /** A hairline between groups of rows. */+ separator(): HTMLElement+ /** Drop the wrapper and forget this menu. Safe to call twice. */+ destroy(): void+}++const OPEN = 'bkm-open'++/** Every live menu, so one document listener can serve all of them.+ *+ * This is dash's model and it is the correct one. slides and spaces both add a+ * `document.addEventListener` (two, in spaces' case) per dropdown and remove+ * neither, so a long-lived editor accumulates a listener for every menu it has+ * ever built — including menus whose elements are long gone. Here the document+ * listeners are installed once, on the first menu, and removed again when the+ * last one is destroyed. */+const live = new Set<MenuState>()++interface MenuState {+ root: HTMLElement+ trigger: HTMLButtonElement+ menu: HTMLElement+ close(): void+}++let wired = false++function onDocPointerDown(ev: Event): void {+ const target = ev.target as Node | null+ for (const m of live) {+ if (!m.root.classList.contains(OPEN)) continue+ if (target && m.root.contains(target)) continue+ m.close()+ }+}++function onDocKeyDown(ev: KeyboardEvent): void {+ const open = [...live].find((m) => m.root.classList.contains(OPEN))+ if (!open) return+ if (ev.key === 'Escape') {+ ev.stopPropagation()+ open.close()+ // Focus goes back to the trigger, not to nowhere. Escaping a menu into+ // `document.body` is how a keyboard user loses their place entirely.+ open.trigger.focus()+ return+ }+ if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp' || ev.key === 'Home' || ev.key === 'End') {+ const rows = focusableRows(open.menu)+ if (!rows.length) return+ ev.preventDefault()+ const at = rows.indexOf(document.activeElement as HTMLElement)+ let next: number+ if (ev.key === 'Home') next = 0+ else if (ev.key === 'End') next = rows.length - 1+ else if (ev.key === 'ArrowDown') next = at < 0 ? 0 : (at + 1) % rows.length+ else next = at < 0 ? rows.length - 1 : (at - 1 + rows.length) % rows.length+ rows[next].focus()+ }+}++/** Rows a keyboard may land on: not the disabled ones, and not a nested menu's+ * rows. A demoted widget's popup renders INSIDE the ⋯ list on a phone (see+ * menu.css), so a bare descendant query would walk into it. */+function focusableRows(menu: HTMLElement): HTMLElement[] {+ return [...menu.querySelectorAll<HTMLElement>('.bkm-item')].filter(+ (b) => b.getAttribute('aria-disabled') !== 'true' && b.closest('.bkm-menu') === menu,+ )+}++function wire(): void {+ if (wired) return+ wired = true+ document.addEventListener('pointerdown', onDocPointerDown)+ document.addEventListener('keydown', onDocKeyDown)+}++function unwire(): void {+ if (!wired || live.size) return+ wired = false+ document.removeEventListener('pointerdown', onDocPointerDown)+ document.removeEventListener('keydown', onDocKeyDown)+}++/**+ * Build a dropdown menu.+ *+ * `label` may be empty for an icon-only trigger, but `tip` never is: an+ * icon-only control leans on its `title` for its name, and that name is also+ * what `aria-label` publishes.+ */+export function createMenu(label: string, tip: string, opts: MenuOpts = {}): Menu {+ const root = document.createElement('div')+ root.className = 'bkm' + (opts.className ? ' ' + opts.className : '')++ const trigger = document.createElement('button')+ trigger.type = 'button'+ trigger.className = 'bkm-trigger'+ trigger.title = tip+ trigger.setAttribute('aria-label', tip)+ trigger.setAttribute('aria-haspopup', 'menu')+ trigger.setAttribute('aria-expanded', 'false')+ if (label) {+ // The word is a SPAN, not a bare text node, so a narrow bar can drop the+ // label and keep the icon. Both slides and spaces arrived at this+ // independently; it is the only way to collapse a labelled control without+ // also losing it.+ const span = document.createElement('span')+ span.className = 'bkm-label'+ span.textContent = label+ trigger.appendChild(span)+ }++ const menu = document.createElement('div')+ menu.className = 'bkm-menu' + (opts.menuClass ? ' ' + opts.menuClass : '')+ menu.setAttribute('role', 'menu')+ if (opts.alignEnd) root.classList.add('bkm-end')++ let dead = false++ const state: MenuState = {+ root,+ trigger,+ menu,+ close(): void {+ root.classList.remove(OPEN)+ trigger.setAttribute('aria-expanded', 'false')+ },+ }++ const open = (): void => {+ if (dead) return+ // Mutual exclusion: opening one menu shuts every other. Without it a bar+ // ends up with two popups overlapping each other, which dash fixed and the+ // other three did not.+ for (const m of live) if (m !== state) m.close()+ if (opts.fill) {+ menu.replaceChildren()+ opts.fill(menu, state.close)+ }+ root.classList.add(OPEN)+ trigger.setAttribute('aria-expanded', 'true')+ }++ const api: Menu = {+ root,+ trigger,+ menu,+ get isOpen(): boolean {+ return root.classList.contains(OPEN)+ },+ open,+ close: state.close,+ toggle(): void {+ if (root.classList.contains(OPEN)) state.close()+ else open()+ },+ item(text: string, onClick: () => void, io: MenuItemOpts = {}): HTMLButtonElement {+ const b = document.createElement('button')+ b.type = 'button'+ b.className =+ 'bkm-item' + (io.off ? ' bkm-off' : '') + (io.selected ? ' bkm-selected' : '')+ b.setAttribute('role', 'menuitem')+ if (io.off) b.setAttribute('aria-disabled', 'true')+ if (io.selected) b.setAttribute('aria-current', 'true')+ if (io.icon) {+ const ico = document.createElement('span')+ ico.className = 'bkm-ico'+ ico.innerHTML = io.icon+ b.appendChild(ico)+ }+ const body = document.createElement('span')+ body.className = 'bkm-body'+ const strong = document.createElement('span')+ strong.className = 'bkm-text'+ strong.textContent = text+ body.appendChild(strong)+ if (io.hint) {+ const hint = document.createElement('span')+ hint.className = 'bkm-hint'+ hint.textContent = io.hint+ body.appendChild(hint)+ }+ b.appendChild(body)+ b.addEventListener('click', (ev) => {+ ev.stopPropagation()+ if (io.off) return+ if (!io.keepOpen) state.close()+ onClick()+ })+ menu.appendChild(b)+ return b+ },+ separator(): HTMLElement {+ const sep = document.createElement('div')+ sep.className = 'bkm-sep'+ // A hairline is decoration; a screen reader walking the menu should not+ // stop on it.+ sep.setAttribute('role', 'separator')+ menu.appendChild(sep)+ return sep+ },+ destroy(): void {+ if (dead) return+ dead = true+ live.delete(state)+ root.remove()+ unwire()+ },+ }++ trigger.addEventListener('click', (ev) => {+ ev.stopPropagation()+ api.toggle()+ })+ // ArrowDown on a CLOSED trigger opens it and lands on the first row — the+ // standard menu-button gesture, and the one that makes the arrow handling+ // above reachable without a mouse.+ trigger.addEventListener('keydown', (ev) => {+ if (ev.key !== 'ArrowDown' || root.classList.contains(OPEN)) return+ ev.preventDefault()+ open()+ focusableRows(menu)[0]?.focus()+ })++ root.append(trigger, menu)+ live.add(state)+ wire()+ return api+}++/** Close every open menu. For an app that needs to shut the bar on its own+ * events — starting a presentation, entering a modal. */+export function closeAllMenus(): void {+ for (const m of live) m.close()+}diff --git a/scripts/test-ui-menu.ts b/scripts/test-ui-menu.tsnew file mode 100644index 00000000..d2f009ca--- /dev/null+++ b/scripts/test-ui-menu.ts@@ -0,0 +1,347 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The shared kernel MENU primitive — behaviour rig.+//+// node scripts/test-ui-menu.ts (Node ≥ 23.6 strips types natively)+//+// WHAT THIS PROVES. `kernel/src/ui/menu.ts` replaces four hand-rolled dropdowns+// with one, and the case for doing that was never bytes — it was that the+// INVISIBLE behaviour differed in every app and no app had all of it. Every+// check below guards a gap that is real in the tree today:+//+// 1. ARIA. Three of the four apps publish nothing. `aria-haspopup` appears+// once in spaces and nowhere else; `aria-expanded` is absent from slides+// and dash entirely. A menu that does not say it is a menu, or whether it+// is open, is a menu a screen reader cannot describe.+// 2. OUTSIDE-PRESS DISMISSAL. slides builds eight dropdowns; two call its+// `closeOnOutsidePress` helper, one hand-rolls the same listener inline,+// and five have no dismissal at all — they stay open until you click the+// trigger again.+// 3. ESCAPE. slides has no Escape handling on any dropdown. The 74 `Escape`+// matches in its source are dialogs and overlays.+// 4. FOCUS RETURN. Escaping a menu into `document.body` loses a keyboard+// user's place. Focus goes back to the trigger.+// 5. ARROW-KEY NAVIGATION. NO app has it. A menu you can open with the+// keyboard and then not move through is a menu you are not inside.+// 6. MUTUAL EXCLUSION. Only dash shuts the other menus when one opens; the+// others will happily overlap two popups.+// 7. THE LISTENER LEAK. slides and spaces both add document listeners PER+// DROPDOWN and remove none — spaces adds two. A long-lived editor+// accumulates a listener for every menu it has ever built, including ones+// whose elements are long gone. This rig asserts the count directly,+// because it is the kind of regression that is invisible until a profile.+// 8. ROWS REBUILT ON OPEN. A row's label can be a function of state — "Hide+// comments" becomes "Show comments" — and rendering it once at mount+// leaves it permanently wrong after the first use. Type hit this and+// wrote `refreshMenuLabels` for it.+// 9. A NESTED MENU IS NOT PART OF THE OUTER ONE. Phone chrome demotes whole+// dropdown widgets into a ⋯ list, so a bare descendant query walks into+// the nested popup — which is how slides' ⋯ once came up with the entire+// language list already unrolled inside it.++import { installDom, fireDoc } from './lib/dash-dom.ts'++const { doc } = installDom()+const bar = doc.createElement('div')+doc.body.appendChild(bar)++const { createMenu, closeAllMenus } = await import('../kernel/src/ui/menu.ts')++let failures = 0+let checks = 0+function ok(what: string, cond: unknown): void {+ checks+++ if (cond) return+ failures+++ console.error(` FAIL ${what}`)+}+function eq(what: string, got: unknown, want: unknown): void {+ checks+++ if (got === want) return+ failures+++ console.error(` FAIL ${what}\n got ${String(got)}\n want ${String(want)}`)+}++const click = (el: unknown): void =>+ (el as { dispatchEvent(e: unknown): void }).dispatchEvent({+ type: 'click', preventDefault() {}, stopPropagation() {},+ })+const key = (k: string): void =>+ fireDoc(doc, 'keydown', { key: k, preventDefault() {}, stopPropagation() {} })+const triggerKey = (el: unknown, k: string): void =>+ (el as { dispatchEvent(e: unknown): void }).dispatchEvent({+ type: 'keydown', key: k, preventDefault() {}, stopPropagation() {},+ })+const pressOutside = (): void => fireDoc(doc, 'pointerdown', { target: doc.body })+// deno-lint-ignore no-explicit-any+const A = (el: unknown, k: string): string | null => (el as any).getAttribute(k)++// ————— 1. structure and ARIA —————+{+ const m = createMenu('Insert', 'Insert an element')+ bar.appendChild(m.root as never)+ eq('trigger announces a menu', A(m.trigger, 'aria-haspopup'), 'menu')+ eq('trigger starts collapsed', A(m.trigger, 'aria-expanded'), 'false')+ eq('trigger carries its name', A(m.trigger, 'aria-label'), 'Insert an element')+ eq('popup is a menu', A(m.menu, 'role'), 'menu')++ const row = m.item('Picture', () => {})+ eq('a row is a menuitem', A(row, 'role'), 'menuitem')++ const off = m.item('Redo', () => {}, { off: true })+ eq('an unrunnable row says so', A(off, 'aria-disabled'), 'true')+ const sel = m.item('Board', () => {}, { selected: true })+ eq('the current choice says so', A(sel, 'aria-current'), 'true')+ ok('a separator is not an item', A(m.separator(), 'role') === 'separator')++ click(m.trigger)+ ok('clicking the trigger opens it', m.isOpen)+ eq('open is published', A(m.trigger, 'aria-expanded'), 'true')+ click(m.trigger)+ ok('clicking again closes it', !m.isOpen)+ eq('closed is published', A(m.trigger, 'aria-expanded'), 'false')+ m.destroy()+}++// ————— 2. outside press dismisses; inside press does not —————+{+ const m = createMenu('File', 'File')+ bar.appendChild(m.root as never)+ const row = m.item('Save', () => {})+ m.open()+ fireDoc(doc, 'pointerdown', { target: row })+ ok('a press INSIDE the menu leaves it open', m.isOpen)+ pressOutside()+ ok('a press outside dismisses it', !m.isOpen)+ m.destroy()+}++// ————— 3/4. Escape closes, and focus goes back to the trigger —————+{+ const m = createMenu('View', 'View')+ bar.appendChild(m.root as never)+ const row = m.item('Zoom', () => {})+ m.open()+ ;(row as unknown as { focus(): void }).focus()+ key('Escape')+ ok('Escape closes the menu', !m.isOpen)+ eq('focus returns to the trigger', doc.activeElement, m.trigger)+ m.destroy()+}++// ————— 5. arrow-key navigation, which no app has —————+{+ const m = createMenu('Go', 'Go')+ bar.appendChild(m.root as never)+ const a = m.item('First', () => {})+ const dead = m.item('Unavailable', () => {}, { off: true })+ const c = m.item('Last', () => {})++ triggerKey(m.trigger, 'ArrowDown')+ ok('ArrowDown on a closed trigger opens it', m.isOpen)+ eq('…and lands on the first row', doc.activeElement, a)++ key('ArrowDown')+ eq('ArrowDown skips the disabled row', doc.activeElement, c)+ key('ArrowDown')+ eq('ArrowDown wraps to the top', doc.activeElement, a)+ key('ArrowUp')+ eq('ArrowUp wraps to the bottom', doc.activeElement, c)+ key('Home')+ eq('Home goes to the first row', doc.activeElement, a)+ key('End')+ eq('End goes to the last row', doc.activeElement, c)+ ok('the disabled row was never focused', doc.activeElement !== dead)+ m.destroy()+}++// ————— 6. mutual exclusion —————+{+ const one = createMenu('One', 'One')+ const two = createMenu('Two', 'Two')+ bar.append(one.root as never, two.root as never)+ one.open()+ two.open()+ ok('opening the second closes the first', !one.isOpen)+ ok('the second is open', two.isOpen)+ closeAllMenus()+ ok('closeAllMenus shuts everything', !two.isOpen)+ one.destroy()+ two.destroy()+}++// ————— 7. THE LISTENER LEAK —————+{+ const before = {+ down: doc.docListeners.get('pointerdown')?.length ?? 0,+ key: doc.docListeners.get('keydown')?.length ?? 0,+ }+ const menus = Array.from({ length: 8 }, (_, i) => createMenu(`M${i}`, `M${i}`))+ for (const m of menus) bar.appendChild(m.root as never)+ eq('eight menus install ONE pointerdown listener',+ (doc.docListeners.get('pointerdown')?.length ?? 0) - before.down, 1)+ eq('eight menus install ONE keydown listener',+ (doc.docListeners.get('keydown')?.length ?? 0) - before.key, 1)++ for (const m of menus) m.destroy()+ eq('destroying them all removes the pointerdown listener',+ doc.docListeners.get('pointerdown')?.length ?? 0, before.down)+ eq('destroying them all removes the keydown listener',+ doc.docListeners.get('keydown')?.length ?? 0, before.key)++ // destroy() twice must not double-remove somebody else's listener+ menus[0].destroy()+ eq('a second destroy is a no-op', doc.docListeners.get('keydown')?.length ?? 0, before.key)+}++// ————— 8. rows are rebuilt every time it opens —————+{+ let hidden = false+ const m = createMenu('More', 'More', {+ fill: (menu, close) => {+ const b = doc.createElement('button')+ b.className = 'bkm-item'+ b.textContent = hidden ? 'Show comments' : 'Hide comments'+ b.addEventListener('click', () => { hidden = !hidden; close() })+ menu.appendChild(b as never)+ },+ })+ bar.appendChild(m.root as never)+ m.open()+ eq('first open reads the state', m.menu.textContent, 'Hide comments')+ click(m.menu.querySelector('.bkm-item'))+ ok('choosing the row closed the menu', !m.isOpen)+ m.open()+ eq('second open re-reads the state', m.menu.textContent, 'Show comments')+ m.destroy()+}++// ————— choosing a row closes, unless it asks not to —————+{+ const m = createMenu('Act', 'Act')+ bar.appendChild(m.root as never)+ let ran = 0+ const once = m.item('Run', () => { ran++ })+ const sticky = m.item('Toggle', () => { ran++ }, { keepOpen: true })+ const dead = m.item('Nope', () => { ran++ }, { off: true })++ m.open()+ click(once)+ eq('the row ran', ran, 1)+ ok('choosing a row closes the menu', !m.isOpen)++ m.open()+ click(sticky)+ eq('a keepOpen row ran', ran, 2)+ ok('a keepOpen row leaves the menu up', m.isOpen)++ click(dead)+ eq('a disabled row does NOT run', ran, 2)+ m.destroy()+}++// ————— 9. a nested menu's rows are not the outer menu's —————+{+ const outer = createMenu('⋯', 'More')+ bar.appendChild(outer.root as never)+ const mine = outer.item('Mine', () => {})+ const inner = createMenu('Language', 'Language')+ outer.menu.appendChild(inner.root as never)+ inner.item('Deutsch', () => {})+ inner.item('Français', () => {})++ outer.open()+ triggerKey(outer.trigger, 'ArrowDown')+ key('End')+ eq('End stops at the outer menu\'s own last row', doc.activeElement, mine)+ outer.destroy()+ inner.destroy()+}++// ————— 10. EVERY THEMED FALLBACK CHAIN REACHES A TOKEN THE APP ACTUALLY THEMES+//+// menu.css styles CHROME, and chrome follows the theme. Each colour reads+// through a chain like `var(--bkm-bg, var(--surface, var(--field, #fff)))`, and+// the literal at the end is LIGHT-ONLY — it exists so the rule is never+// invalid, not because any app should reach it. An app that defines none of the+// tokens in a chain silently gets that light literal in DARK mode: a white menu+// under light ink, which is the mirror of the dark-on-dark bug slides fixed with+// `color-scheme: only light`.+//+// This was not hypothetical. `type` has no `--surface` at all — its chrome+// surface token is `--field` — so the first version of the chain fell through+// to `#fff` for the one app whose gap the comment had already noted and whose+// fallback had not been fixed. A comment is not a guard. This is.+//+// The four apps theme by three different MECHANISMS (slides and type via+// `[data-theme="dark"]`, spaces via both that and a media query, dash via+// `light-dark()`), so "is this token themed" has to accept all three.+{+ const { readFileSync } = await import('node:fs')+ const APPS = ['slides', 'spaces', 'dash', 'type']+ const css = readFileSync(new URL('../kernel/src/ui/menu.css', import.meta.url), 'utf8')++ /** Every `--token` a chain falls through, in order, ignoring our own. */+ const chains: Array<{ prop: string; tokens: string[] }> = []+ for (const line of css.split('\n')) {+ const decl = /^\s*(background|color|border|box-shadow|outline)?[^:]*:\s*var\(--bkm-([a-z-]+),(.*)$/.exec(line)+ if (!decl) continue+ // `--[a-z-]+` stopped at the digit in `--chrome-2` and reported a token+ // nobody defines. Digits are part of a custom-property name.+ const tokens = [...decl[3].matchAll(/var\(\s*(--[a-z0-9-]+)/g)].map((m) => m[1])+ if (tokens.length) chains.push({ prop: decl[2], tokens })+ }+ ok('found the themed chains to check', chains.length >= 4)++ /** Tokens an app defines at all, and the subset it actually themes. */+ function tokensOf(app: string): { all: Set<string>; themed: Set<string> } {+ const src = readFileSync(new URL(`../${app}/src/styles.css`, import.meta.url), 'utf8')+ const all = new Set<string>()+ const themed = new Set<string>()+ for (const m of src.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)) {+ all.add(m[1])+ // dash themes by resolving against color-scheme, in the value itself+ if (m[2].includes('light-dark(')) themed.add(m[1])+ }+ // …the other three theme by re-declaring inside a dark block. Brace-count+ // from each one so a nested rule inside a media query is still counted.+ for (const start of [...src.matchAll(/\[data-theme=["']dark["']\][^{]*\{|@media[^{]*prefers-color-scheme:\s*dark[^{]*\{/g)]) {+ let depth = 0+ let i = start.index! + start[0].length - 1+ for (; i < src.length; i++) {+ if (src[i] === '{') depth+++ else if (src[i] === '}') { depth--; if (!depth) break }+ }+ for (const m of src.slice(start.index!, i).matchAll(/(--[a-z0-9-]+)\s*:/g)) themed.add(m[1])+ }+ return { all, themed }+ }++ // Only the colour-bearing chains must be THEMED. A radius or a font size is+ // the same in both themes by design, so requiring it here would be noise.+ const COLOUR = new Set(['bg', 'border', 'ink', 'hover', 'ico', 'focus'])++ // `shadow` is deliberately exempt from BOTH checks. Only dash has a shadow+ // token (`--shadow-pop`); spaces has none at all, and slides and type write+ // their menu shadow as a literal today. So the literal here IS the intended+ // value for three of four apps rather than a gap — and unlike a background or+ // an ink, a translucent shadow that does not follow the theme is not a+ // legibility failure. If tier 4 mints a shared shadow token, move `shadow`+ // into COLOUR above and this becomes a real check.+ const EXEMPT = new Set(['shadow'])++ for (const app of APPS) {+ const { all, themed } = tokensOf(app)+ for (const { prop, tokens } of chains) {+ if (EXEMPT.has(prop)) continue+ const defined = tokens.find((t) => all.has(t))+ ok(`${app}: --bkm-${prop} reaches a token ${app} defines (${tokens.join(' → ')})`, defined)+ if (!defined || !COLOUR.has(prop)) continue+ ok(`${app}: --bkm-${prop} lands on ${defined}, which ${app} themes`, themed.has(defined))+ }+ }+}++console.log(failures ? `\ntest-ui-menu: ${failures} FAILED of ${checks}` : `test-ui-menu: ${checks} checks OK`)+process.exit(failures ? 1 : 0)