Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: the shared tooltip primitive (UI primitives, tier 3) (#461)
nyblnetad43bb380e05
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e86ff881..4c6fec1d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -339,6 +339,16 @@ jobs:# 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 tooltip primitive rig+ # kernel/src/ui/tooltip.ts — built ahead of a consumer (no app has a+ # hover tooltip; all four use native title=), so the checks pin the+ # contract chosen, not a behaviour found: shows after a delay on+ # hover/focus, hides on leave/blur/Escape, wires aria-describedby, does+ # not flash on a pointer passing through, and — the one that matters —+ # renders in document.body as a fixed element so no scroll container+ # clips it (hard-won detail 10). Behaviours mutation-caught; themed+ # through the shared guard.+ run: node scripts/test-ui-tooltip.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 92366154..b2b5c4df 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6720,3 +6720,30 @@ Pointers: `kernel/src/ui/dialog.{ts,css}`, `scripts/test-ui-dialog.ts` (66checks; focus restore, capture-phase Escape, backdrop guard, focus trap andlistener cleanup each mutation-caught), `working/team/notes/kernel.md` (thetier-3 four-way read and its correction).++## 2026-09 — UI primitives tier 3: the tooltip (built ahead of a consumer)++**Decision.** `kernel/src/ui/tooltip.ts` + `tooltip.css`, guarded by+`scripts/test-ui-tooltip.ts`. Kernel half only; same discipline as the other+primitives (`--bkt-*` chains onto host tokens, never `light-dark()`, the shared+theming guard).++**This is NOT a consolidation** — recorded here as one of the three tier-3+primitives the maintainer chose to build ahead of a consumer ("build all four,+they would come into play soon"). The four-way read found no app has a hover+tooltip: all four use the native `title` attribute (99/132/135/65 uses), and the+`*-tip` classes that exist are a help overlay, a tone indicator and a drop+marker. So this is a new, deliberately minimal abstraction, to be revisited if+no app adopts it.++**The one thing it gets right on purpose:** it is never clipped. A tooltip is+the primitive most likely to be born inside a scroll container (a panel, a+menu), and hard-won detail 10 says an ancestor with `overflow:auto` clips both+axes. So the tip is a single `document.body`-level, `position: fixed` element,+positioned from the anchor's rect — it has no scrolling ancestor to be trapped+by, by construction. Shown after a delay (no flash on a pointer passing+through), hidden on leave/blur/Escape, wired with `aria-describedby`.++Pointers: `kernel/src/ui/tooltip.{ts,css}`, `scripts/test-ui-tooltip.ts` (34+checks; delay, the body/fixed placement, the flash-guard, aria wiring and Escape+each mutation-caught).diff --git a/kernel/src/ui/tooltip.css b/kernel/src/ui/tooltip.cssnew file mode 100644index 00000000..6aa307f3--- /dev/null+++ b/kernel/src/ui/tooltip.css@@ -0,0 +1,31 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors++ THE SHARED TOOLTIP styles. Built ahead of a consumer (see tooltip.ts); minimal+ by intent. Same two rules as the other primitives:+ 1. Values through `--bkt-*` chains onto the host's own tokens; never+ light-dark(); the shared theming guard checks it.+ 2. Structure and behaviour shared; only the look is the host's.++ The tip is a single body-level, position:fixed element — it has no scrolling+ ancestor to clip it (hard-won detail 10), which is the whole reason a tooltip+ is rendered here rather than next to its anchor in the tree. */++.bkt {+ position: fixed;+ z-index: var(--bkt-z, 1100); /* above dialogs' scrim too: a tip in a dialog must show */+ transform: translateX(-50%); /* centre on the anchor's mid-x (set as `left`) */+ max-width: var(--bkt-max, 240px);+ padding: 5px 8px;+ font-size: var(--bkt-font-size, 12px);+ line-height: 1.35;+ color: var(--bkt-ink, var(--surface, var(--chrome, #fff)));+ /* the tooltip is the INVERSE of the surface — dark bubble on a light app,+ light on a dark one — which is what --ink gives on both, the same pairing+ the primary button uses. */+ background: var(--bkt-bg, var(--ink, #1e2a3a));+ border-radius: var(--bkt-radius, 6px);+ box-shadow: var(--bkt-shadow, 0 4px 14px rgb(20 30 45 / 0.24));+ pointer-events: none; /* the tip never eats a click; it is not interactive */+ white-space: normal;+}diff --git a/kernel/src/ui/tooltip.ts b/kernel/src/ui/tooltip.tsnew file mode 100644index 00000000..779a7f0e--- /dev/null+++ b/kernel/src/ui/tooltip.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SHARED TOOLTIP primitive — tier 3, BUILT AHEAD OF A CONSUMER on the+// maintainer's call ("build all four, they would come into play soon"). It is+// NOT a consolidation: the four-way read found no app has a hover tooltip at+// all — all four use the native `title` attribute (99/132/135/65 uses), and the+// `*-tip` classes that exist are a help overlay, a tone indicator and a drop+// marker, not tooltips. So this is a new, deliberately minimal abstraction; a+// real consumer will tell us what it needs, and this should be revisited if+// none adopts it. See docs/DECISIONS.md.+//+// Kept to exactly what a tooltip is: anchored to an element, shown on hover or+// focus after a short delay, hidden on leave / blur / Escape, and wired to the+// anchor with `aria-describedby` so it is not mouse-only.+//+// THE ONE THING THAT MATTERS MOST, per the brief: it must never be clipped by an+// ancestor. A tooltip is the primitive most likely to be born inside a scroll+// container (a panel, a menu), and hard-won detail 10 says an ancestor with+// `overflow:auto` clips BOTH axes. So the tip is rendered in `document.body` as+// a single `position: fixed` element, positioned from the anchor's rect — it has+// no scrolling ancestor to be trapped by, by construction. Values are the host+// app's via `--bkt-*` chains (tooltip.css); never light-dark().++export interface TooltipOpts {+ /** ms of hover/focus before it shows (default 400 — long enough not to flash+ * on a pointer passing through, short enough to feel responsive). */+ delay?: number+ /** which side of the anchor to prefer (default 'top'). */+ placement?: 'top' | 'bottom'+}++/** The one body-level tip element, reused across every anchor — a tooltip is+ * singular on screen, so there is never a reason for more than one. */+let tip: HTMLElement | null = null+let tipSeq = 0+let hideTimer: ReturnType<typeof setTimeout> | null = null+let showTimer: ReturnType<typeof setTimeout> | null = null++function ensureTip(): HTMLElement {+ if (tip) return tip+ tip = document.createElement('div')+ tip.className = 'bkt'+ tip.setAttribute('role', 'tooltip')+ tip.id = `bkt-${++tipSeq}`+ tip.hidden = true+ document.body.appendChild(tip)+ return tip+}++function place(anchor: HTMLElement, placement: 'top' | 'bottom'): void {+ const t = ensureTip()+ const r = anchor.getBoundingClientRect()+ // fixed, viewport coordinates — no scrolling ancestor to clip it (detail 10).+ t.style.position = 'fixed'+ t.style.left = `${Math.round(r.left + r.width / 2)}px`+ // translateX(-50%) centres it on the anchor (tooltip.css); top/bottom flips+ // which edge it hangs from.+ if (placement === 'bottom') { t.style.top = `${Math.round(r.bottom + 6)}px`; t.style.bottom = 'auto' }+ else { t.style.top = 'auto'; t.style.bottom = `${Math.round(window.innerHeight - r.top + 6)}px` }+}++function hideNow(): void {+ if (showTimer) { clearTimeout(showTimer); showTimer = null }+ if (tip) tip.hidden = true+}++/**+ * Attach a tooltip to `anchor`. Returns a detach() that removes every listener+ * and the `aria-describedby` wiring — call it when the anchor goes away.+ */+export function attachTooltip(anchor: HTMLElement, text: string, opts: TooltipOpts = {}): () => void {+ const delay = opts.delay ?? 400+ const placement = opts.placement ?? 'top'++ const show = (): void => {+ if (hideTimer) { clearTimeout(hideTimer); hideTimer = null }+ if (showTimer) clearTimeout(showTimer)+ showTimer = setTimeout(() => {+ const t = ensureTip()+ t.textContent = text+ place(anchor, placement)+ t.hidden = false+ anchor.setAttribute('aria-describedby', t.id)+ }, delay)+ }+ const hide = (): void => {+ if (showTimer) { clearTimeout(showTimer); showTimer = null }+ anchor.removeAttribute('aria-describedby')+ // a tiny grace so moving the pointer onto nothing does not flicker; the+ // primitive stays simple — no hovering the tip itself (it is not interactive)+ hideTimer = setTimeout(hideNow, 60)+ }+ const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape') hide() }++ anchor.addEventListener('mouseenter', show)+ anchor.addEventListener('mouseleave', hide)+ anchor.addEventListener('focus', show)+ anchor.addEventListener('blur', hide)+ anchor.addEventListener('keydown', onKey)++ return () => {+ anchor.removeEventListener('mouseenter', show)+ anchor.removeEventListener('mouseleave', hide)+ anchor.removeEventListener('focus', show)+ anchor.removeEventListener('blur', hide)+ anchor.removeEventListener('keydown', onKey)+ anchor.removeAttribute('aria-describedby')+ hideNow()+ }+}diff --git a/scripts/test-ui-tooltip.ts b/scripts/test-ui-tooltip.tsnew file mode 100644index 00000000..b2eef26c--- /dev/null+++ b/scripts/test-ui-tooltip.ts@@ -0,0 +1,147 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The shared kernel TOOLTIP primitive — behaviour rig.+//+// node scripts/test-ui-tooltip.ts+//+// Built ahead of a consumer (no app has a hover tooltip; see tooltip.ts), so+// these checks pin the contract we chose rather than a behaviour we found:+// shows after a delay on hover/focus, hides on leave/blur/Escape, wires+// aria-describedby, does not flash on a pointer passing through, and — the one+// that matters most — renders in document.body as a fixed element so no scroll+// container clips it. Self-contained DOM, like the other primitive rigs.++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 cls = new Set<string>()+ private h = new Map<string, Handler[]>()+ hidden = false; text = ''; id = ''+ style: Record<string, string> = {}+ rect = { left: 100, top: 200, right: 180, bottom: 224, width: 80, height: 24 }+ constructor(tag: string) { this.tag = tag }+ get classList() { const c = this.cls; return { add: (x: string) => c.add(x), remove: (x: string) => c.delete(x), contains: (x: string) => c.has(x) } }+ set className(v: string) { this.cls = new Set(v.split(/\s+/).filter(Boolean)) }+ set textContent(v: string) { this.text = v }+ get textContent() { return this.text }+ setAttribute(k: string, v: string) { this.attrs.set(k, v) }+ getAttribute(k: string) { return this.attrs.get(k) ?? null }+ removeAttribute(k: string) { this.attrs.delete(k) }+ appendChild(x: El) { x.parent = this; this.children.push(x); return x }+ getBoundingClientRect() { return this.rect }+ addEventListener(t: string, fn: Handler) { this.h.set(t, [...(this.h.get(t) ?? []), fn]) }+ removeEventListener(t: string, fn: Handler) { this.h.set(t, (this.h.get(t) ?? []).filter((f) => f !== fn)) }+ fire(t: string, ev: Record<string, unknown> = {}) { for (const fn of [...(this.h.get(t) ?? [])]) fn({ preventDefault() {}, ...ev }) }+ querySelectorAll(sel: string): El[] { const out: El[] = []; const cls = sel.replace('.', ''); const walk = (n: El) => { for (const c of n.children) { if (c.cls.has(cls)) out.push(c); walk(c) } }; walk(this); return out }+}+const doc = { body: new El('body'), createElement: (t: string) => new El(t) }+;(globalThis as Record<string, unknown>).document = doc+;(globalThis as Record<string, unknown>).window = { innerHeight: 800 }++const { attachTooltip } = await import('../kernel/src/ui/tooltip.ts')++let failures = 0, checks = 0+function ok(cond: unknown, msg: string) { checks++; if (!cond) { failures++; console.error(` ✗ ${msg}`) } }+const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))+const anchor = () => new El('button')+const theTip = () => doc.body.querySelectorAll('.bkt')[0]++// ——— shows after the delay, wired to the anchor ———+{+ const a = anchor()+ attachTooltip(a as unknown as HTMLElement, 'Save the deck', { delay: 15 })+ a.fire('mouseenter')+ ok(!theTip() || theTip().hidden, 'nothing shows before the delay')+ await wait(30)+ const tip = theTip()+ ok(tip && !tip.hidden, 'the tip shows after the delay')+ ok(tip.text === 'Save the deck', 'with the anchor’s text')+ ok(a.getAttribute('aria-describedby') === tip.id, 'the anchor is aria-describedby the tip')+ a.fire('mouseleave')+ ok(a.getAttribute('aria-describedby') === null, 'leaving clears aria-describedby immediately')+ await wait(80)+ ok(theTip().hidden, 'and the tip hides')+}++// ——— detail-10: the tip lives in the body, position fixed — no clip ———+{+ const scroller = new El('div') // a would-be scroll container+ const a = anchor(); scroller.appendChild(a)+ attachTooltip(a as unknown as HTMLElement, 'Tip', { delay: 5 })+ a.fire('mouseenter'); await wait(15)+ const tip = theTip()+ ok(tip.parent === doc.body, 'the tip is a child of document.body, NOT of the anchor’s container (so no ancestor clips it)')+ ok(tip.style.position === 'fixed', 'it is position:fixed')+ ok(tip.style.left && (tip.style.top !== 'auto' || tip.style.bottom), 'it is positioned from the anchor rect')+ a.fire('mouseleave'); await wait(80)+}++// ——— no flash: leaving before the delay never shows it ———+{+ const a = anchor()+ attachTooltip(a as unknown as HTMLElement, 'Nope', { delay: 40 })+ a.fire('mouseenter')+ await wait(10)+ a.fire('mouseleave') // before the 40ms delay+ // check at +35 (t≈45): PAST the 40ms show delay, but BEFORE the 60ms hide+ // grace — so a tip that (wrongly) showed would still be visible here. This+ // window is what makes the check catch a missing flash-guard, rather than the+ // grace timer hiding it for the wrong reason.+ await wait(35)+ ok(theTip().hidden, 'a pointer passing through (leave before delay) never shows the tip')+}++// ——— focus/blur, and Escape ———+{+ const a = anchor()+ attachTooltip(a as unknown as HTMLElement, 'Focused', { delay: 5 })+ a.fire('focus'); await wait(15)+ ok(!theTip().hidden, 'focus shows the tip (keyboard, not just hover)')+ a.fire('keydown', { key: 'Escape' }); await wait(80)+ ok(theTip().hidden, 'Escape hides it')+ ok(a.getAttribute('aria-describedby') === null, 'and clears aria')+}++// ——— singleton: many anchors, one tip element ———+{+ const a = anchor(), b = anchor()+ attachTooltip(a as unknown as HTMLElement, 'A', { delay: 5 })+ attachTooltip(b as unknown as HTMLElement, 'B', { delay: 5 })+ a.fire('mouseenter'); await wait(15); a.fire('mouseleave'); await wait(80)+ b.fire('mouseenter'); await wait(15)+ ok(doc.body.querySelectorAll('.bkt').length === 1, 'there is exactly one tip element for all anchors')+ ok(theTip().text === 'B', 'and it carries the current anchor’s text')+ b.fire('mouseleave'); await wait(80)+}++// ——— detach removes the listeners and aria ———+{+ const a = anchor()+ const detach = attachTooltip(a as unknown as HTMLElement, 'Gone', { delay: 5 })+ detach()+ a.fire('mouseenter'); await wait(20)+ ok(theTip().hidden, 'after detach, hovering the anchor does nothing')+ ok(a.getAttribute('aria-describedby') === null, 'and no aria wiring remains')+}++// ——— THEMING GUARD (shared helper) ———+{+ const appStyles = Object.fromEntries(+ ['slides', 'spaces', 'dash', 'type'].map((x) => [x, join(rroot, `${x}/src/styles.css`)]),+ )+ for (const r of checkThemedChains({+ cssPath: join(rroot, 'kernel/src/ui/tooltip.css'),+ prefix: 'bkt',+ colourProps: new Set(['ink', 'bg']),+ appStyles,+ })) ok(r.pass, r.msg)+}++console.log(failures ? `\n${failures} FAILED of ${checks}` : `\ntest-ui-tooltip: ${checks} checks OK`)+process.exit(failures ? 1 : 0)