Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: the shared toggle switch primitive (UI primitives, tier 3) (#462)
nyblnetc09b417a61a5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex bbdf6885..3233853a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -349,6 +349,18 @@ jobs:# clips it (hard-won detail 10). Behaviours mutation-caught; themed# through the shared guard.run: node scripts/test-ui-tooltip.ts+ - name: Shared toggle primitive rig+ # kernel/src/ui/toggle.ts — built ahead of a consumer (the three+ # "toggle"-named classes across the apps are a native checkbox, a+ # disclosure block and a button group; no shared switch). The checks pin+ # the contract chosen: a real role="switch" with aria-checked, a click+ # toggles and fires onChange, set() updates state WITHOUT firing+ # onChange, and it is a <button> so the platform gives it keyboard+ # activation. Behaviours mutation-caught; themed through the shared guard+ # (whose alias-indirection fix — a token defined as var(--other) is+ # themed iff --other is — landed here so dash's --chrome-2: var(--hover)+ # resolves).+ run: node scripts/test-ui-toggle.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 a2303264..2f071a5f 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6789,3 +6789,32 @@ while the carried element morphed, then revealed on `→`.live broadcast applies it — forward with the entrance, backward as a hide —and parks it when the nav names another slide, applying it after that slideenters. The speaker view shows `step/max` beside the slide number.+## 2026-09 — UI primitives tier 3: the toggle switch (built ahead of a consumer)++**Decision.** `kernel/src/ui/toggle.ts` + `toggle.css`, guarded by+`scripts/test-ui-toggle.ts`. Kernel half only; same discipline as the others.++**Not a consolidation** — the third of the three tier-3 primitives the+maintainer chose to build ahead of a consumer. The four-way read found no shared+on/off switch: slides' `input.ed-toggle` is a native checkbox, spaces'+`.sp-toggle-body` is a disclosure block's collapsible body, type's `.t-toggles`+is a segmented button group. So this is a new, minimal switch, to be revisited+if no app adopts it.++The one thing it gets right: it is a real `<button role="switch">` with+`aria-checked`, so the platform gives it keyboard activation and a screen reader+announces it as a switch and its state — a switch that is not mouse-only. `set()`+updates state without firing `onChange` (a set is the app's doing, not the+user's). The ON track is `--accent`, which several apps deliberately do NOT+invert, so it is the one colour chain checked for "defines" but not "themes".++**A guard improvement landed with it.** `scripts/lib/ui-theme-guard.ts` now+follows one level of alias indirection: a token defined as `--x: var(--y)` is+themed iff `--y` is themed. dash writes `--chrome-2: var(--hover)` and `--hover`+is themed via `light-dark()`; without this the guard read `--chrome-2` as+un-themed though it inverts at runtime. All five UI rigs re-run green against the+updated guard (adding to the themed set can only relax, never regress).++Pointers: `kernel/src/ui/toggle.{ts,css}`, `scripts/test-ui-toggle.ts` (61+checks; role, click-toggle, aria, set-not-firing-onChange, destroy each+mutation-caught).diff --git a/kernel/src/ui/toggle.css b/kernel/src/ui/toggle.cssnew file mode 100644index 00000000..adf76cf9--- /dev/null+++ b/kernel/src/ui/toggle.css@@ -0,0 +1,60 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors++ THE SHARED TOGGLE (switch) styles. Built ahead of a consumer (see toggle.ts);+ minimal. Same two rules as the other primitives: values through `--bks-*`+ chains onto the host's own tokens, never light-dark(), the shared theming+ guard checks every colour chain resolves per app to a token it defines and+ themes; structure and behaviour shared, only the look is the host's. */++.bks {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ font-size: var(--bks-font-size, 12.5px);+ color: var(--bks-ink, var(--ink-2, var(--ink, #1e2a3a)));+}++/* the track */+.bks-switch {+ flex: none;+ position: relative;+ width: 32px;+ height: 18px;+ padding: 0;+ border: 1px solid var(--bks-border, var(--line, #e3e8ef));+ border-radius: 999px;+ background: var(--bks-off, var(--chrome-2, var(--chrome, #e3e8ef)));+ cursor: pointer;+ transition: background 0.14s ease, border-color 0.14s ease;+}+/* the knob */+.bks-switch::after {+ content: '';+ position: absolute;+ top: 1px;+ inset-inline-start: 1px;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--bks-knob, var(--surface, var(--field, #fff)));+ box-shadow: 0 1px 2px rgb(20 30 45 / 0.3);+ transition: inset-inline-start 0.14s ease;+}+.bks-switch:focus-visible {+ outline: 2px solid var(--bks-focus, var(--accent-ink, currentColor));+ outline-offset: 2px;+}++/* ON: the track takes the accent, the knob slides to the far end. Logical+ offset, so it slides the correct way under RTL. */+.bks-on .bks-switch {+ background: var(--bks-on, var(--accent, #5e7699));+ border-color: var(--bks-on, var(--accent, #5e7699));+}+.bks-on .bks-switch::after {+ inset-inline-start: 15px;+}++.bks-label { min-width: 0; }diff --git a/kernel/src/ui/toggle.ts b/kernel/src/ui/toggle.tsnew file mode 100644index 00000000..7e73666e--- /dev/null+++ b/kernel/src/ui/toggle.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SHARED TOGGLE (on/off switch) primitive — tier 3, BUILT AHEAD OF A+// CONSUMER on the maintainer's call. NOT a consolidation: the four-way read+// found the three "toggle"-named classes are three unrelated things — slides'+// `input.ed-toggle` is a native checkbox, spaces' `.sp-toggle-body` is the+// collapsible body of a disclosure block, type's `.t-toggles` is a segmented+// button group — and no app has a shared on/off switch. So this is a new,+// minimal switch; revisit if no app adopts it. See docs/DECISIONS.md.+//+// Kept to what a switch is, and to the one thing that makes it not+// mouse-only: it is a real <button role="switch"> with `aria-checked`, so the+// platform gives it keyboard operation (Space/Enter activate a button) and a+// screen reader announces it as a switch and its state. Values are the host+// app's through `--bks-*` chains (toggle.css); never light-dark().++export interface ToggleOpts {+ /** Visible label beside the switch, and its accessible name. */+ label: string+ /** Initial state (default off). */+ checked?: boolean+ /** Fired with the new state on every user toggle (not on `set`). */+ onChange?: (checked: boolean) => void+}++export interface Toggle {+ /** The label row: the switch button plus its text. Put it in a panel. */+ readonly root: HTMLElement+ /** The switch button itself (`role="switch"`). */+ readonly control: HTMLElement+ readonly checked: boolean+ /** Set the state programmatically. Updates aria + the visual; does NOT fire+ * onChange — a set is the app's own doing, not the user's. */+ set(checked: boolean): void+ destroy(): void+}++export function createToggle(opts: ToggleOpts): Toggle {+ let checked = !!opts.checked++ const root = document.createElement('label')+ root.className = 'bks'++ const control = document.createElement('button')+ control.type = 'button'+ control.className = 'bks-switch'+ control.setAttribute('role', 'switch')+ control.setAttribute('aria-checked', String(checked))+ control.setAttribute('aria-label', opts.label)++ const text = document.createElement('span')+ text.className = 'bks-label'+ text.textContent = opts.label++ root.append(control, text)++ const render = (): void => {+ control.setAttribute('aria-checked', String(checked))+ root.classList.toggle('bks-on', checked)+ }++ // A <button> activates on click AND on Space/Enter natively, so there is one+ // handler and the keyboard comes free — no second keydown path to double-fire.+ const onClick = (ev: Event): void => {+ ev.preventDefault()+ checked = !checked+ render()+ opts.onChange?.(checked)+ }+ control.addEventListener('click', onClick)+ render()++ return {+ root,+ control,+ get checked() { return checked },+ set(v: boolean): void { checked = !!v; render() },+ destroy(): void { control.removeEventListener('click', onClick); root.remove() },+ }+}diff --git a/scripts/lib/ui-theme-guard.ts b/scripts/lib/ui-theme-guard.tsindex b366e1fd..f98ed0e3 100644--- a/scripts/lib/ui-theme-guard.ts+++ b/scripts/lib/ui-theme-guard.ts@@ -71,6 +71,16 @@ export function tokensOf(cssPath: string): { all: Set<string>; themed: Set<strin}for (const m of src.slice(start.index!, i).matchAll(/(--[a-z0-9-]+)\s*:/g)) themed.add(m[1])}+ // Follow ALIAS indirection: a token defined as `--x: var(--y)` is themed iff+ // --y is themed. dash writes `--chrome-2: var(--hover)`, and --hover is+ // themed via light-dark(); without this, --chrome-2 reads as un-themed though+ // at runtime it inverts. Iterate to a fixpoint for alias chains.+ const aliases: Array<[string, string]> = []+ for (const m of src.matchAll(/(--[a-z0-9-]+)\s*:\s*var\(\s*(--[a-z0-9-]+)/g)) aliases.push([m[1], m[2]])+ for (let changed = true; changed;) {+ changed = false+ for (const [x, y] of aliases) if (themed.has(y) && !themed.has(x)) { themed.add(x); changed = true }+ }return { all, themed }}diff --git a/scripts/test-ui-toggle.ts b/scripts/test-ui-toggle.tsnew file mode 100644index 00000000..7bbe30e6--- /dev/null+++ b/scripts/test-ui-toggle.ts@@ -0,0 +1,109 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The shared kernel TOGGLE (switch) primitive — behaviour rig.+//+// node scripts/test-ui-toggle.ts+//+// Built ahead of a consumer (the three "toggle" classes across the apps are+// three unrelated things, no shared switch — see toggle.ts), so these checks+// pin the contract chosen: a real role="switch" with aria-checked, click+// toggles and fires onChange, set() updates state WITHOUT firing onChange, and+// it is a <button> so the platform gives it keyboard operation. 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[]>()+ text = ''; type = ''+ 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), toggle: (x: string, on?: boolean) => { const v = on ?? !c.has(x); v ? c.add(x) : c.delete(x); return v }, 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 }+ setAttribute(k: string, v: string) { this.attrs.set(k, v) }+ getAttribute(k: string) { return this.attrs.get(k) ?? null }+ append(...xs: El[]) { for (const x of xs) { x.parent = this; this.children.push(x) } }+ remove() { if (this.parent) { this.parent.children = this.parent.children.filter((c) => c !== this); this.parent = null } }+ 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) { for (const fn of [...(this.h.get(t) ?? [])]) fn({ preventDefault() {} }) }+}+;(globalThis as Record<string, unknown>).document = { createElement: (t: string) => new El(t) }++const { createToggle } = await import('../kernel/src/ui/toggle.ts')++let failures = 0, checks = 0+function ok(cond: unknown, msg: string) { checks++; if (!cond) { failures++; console.error(` ✗ ${msg}`) } }+const E = (x: unknown) => x as unknown as El++// ——— role, aria, label ———+{+ const t = createToggle({ label: 'Live sharing' })+ ok(E(t.control).getAttribute('role') === 'switch', 'the control is role=switch')+ ok(E(t.control).getAttribute('aria-checked') === 'false', 'aria-checked starts false')+ ok(E(t.control).getAttribute('aria-label') === 'Live sharing', 'the label is the accessible name')+ ok(E(t.control).tag.toUpperCase() === 'BUTTON', 'the control is a <button> — keyboard-operable by the platform (Space/Enter)')+ const t2 = createToggle({ label: 'On', checked: true })+ ok(E(t2.control).getAttribute('aria-checked') === 'true', 'checked:true starts aria-checked true')+ ok(E(t2.root).classList.contains('bks-on'), 'and carries the bks-on class')+}++// ——— click toggles, flips aria + class, fires onChange with the new state ———+{+ const seen: boolean[] = []+ const t = createToggle({ label: 'X', onChange: (c) => seen.push(c) })+ E(t.control).fire('click')+ ok(t.checked === true, 'a click turns it on')+ ok(E(t.control).getAttribute('aria-checked') === 'true', 'aria-checked follows')+ ok(E(t.root).classList.contains('bks-on'), 'the on-class follows')+ E(t.control).fire('click')+ ok(t.checked === false, 'a second click turns it off')+ ok(seen.join(',') === 'true,false', 'onChange fired with each new state, in order')+}++// ——— set() updates state and visuals but does NOT fire onChange ———+{+ let fired = 0+ const t = createToggle({ label: 'X', onChange: () => { fired++ } })+ t.set(true)+ ok(t.checked === true && E(t.control).getAttribute('aria-checked') === 'true', 'set(true) updates state and aria')+ ok(E(t.root).classList.contains('bks-on'), 'and the visual')+ ok(fired === 0, 'set() does NOT fire onChange (a set is the app’s doing, not the user’s)')+ t.set(false)+ ok(t.checked === false && fired === 0, 'set(false) too')+}++// ——— destroy removes the listener and the root ———+{+ let fired = 0+ const t = createToggle({ label: 'X', onChange: () => { fired++ } })+ t.destroy()+ E(t.control).fire('click')+ ok(fired === 0 && t.checked === false, 'after destroy, a click does nothing')+}++// ——— 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/toggle.css'),+ prefix: 'bks',+ colourProps: new Set(['ink', 'border', 'off', 'knob']),+ // 'on' is the accent track — a brand colour that legitimately does not invert+ // (dash's --accent is one value for both themes), so it is checked for+ // 'defines' only, not 'themes'.+ appStyles,+ })) ok(r.pass, r.msg)+}++console.log(failures ? `\n${failures} FAILED of ${checks}` : `\ntest-ui-toggle: ${checks} checks OK`)+process.exit(failures ? 1 : 0)