Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: the shared side-panel + resizer primitive (UI primitives, tier 2) (#456)
nyblnetefd3d898d353
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 90dd1864..e977494d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -319,6 +319,17 @@ jobs:# bugs found in review ride along.run: node scripts/test-codediff.ts+ - name: Shared panel primitive rig+ # kernel/src/ui/panel.ts is the second UI primitive (after the menu):+ # the resizable, collapsible side panel three apps hand-rolled and a+ # fourth stubbed. Every check guards a piece of invisible behaviour each+ # app learned alone — the no-animation-during-drag class, the RTL widen+ # direction, a collapsed panel refusing to drag, per-viewer persistence+ # clamped on restore, the drawer that boots shut below a phone width —+ # 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: First-page preview rig# Every save writes a static render of page one for file-manager# thumbnails. Two decisions in that path fail silently: an encrypteddiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex fd177faa..2a0a374f 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6543,3 +6543,38 @@ derived rooms and trust-on-first-use pinning, `doc.broadcast`, the hostingURL, the hosted client, and the relay integration check that tested them.The contributor's relay verb logic, follow UI and off-by-default rule are thesurviving core; the PR stays theirs.++## 2026-09 — Shared UI primitives, tier 2: the side panel + resizer++**Decision.** The resizable, collapsible side panel moves into the kernel as+`kernel/src/ui/panel.ts` + `panel.css`, guarded by `scripts/test-ui-panel.ts`.+Kernel definition only — each app's migration is that zone's own change, as with+the menu (tier 1). Same rules: structure and behaviour are shared; token VALUES+read through `--bkp-*` fallback chains onto whatever the host app already+defines, so adoption is appearance-neutral and no theme mechanism is imposed+(never `light-dark()`, for the reason in the tier-1 entry). The persistence key+is INJECTED — the kernel does not hardcode an app's localStorage namespace.++**Why, measured by concept.** Three apps implement the same resizable panel and+a fourth stubs it: slides (`.ed-sidebar`/`.ed-props`, two resizers, RTL widen,+`bento-ed-panels`, phone drawers), spaces (`.sp-insp`, `bento-sp-*`), dash+(explicitly "ported from slides", one panel, `]` collapse, `bento-dash-panels`),+and type, whose `.t-props` is a FIXED-WIDTH aside with no resizer, collapse or+persistence — its CSS even says it copied the row metrics "at a fixed width, as+slides and dash both do" and none of the machinery. So "slides is the basis"+again gives the fourth app the LEAST; type would gain drag/collapse/persistence+from adopting this, not lose anything.++**The value is knowledge, not bytes**, as with the menu. Each app learned the+same non-obvious things alone: a panel needs a no-animation class DURING a drag+or its width transition chases the cursor; the collapse chevron docks flush to+the screen edge when shut; widening flips direction under RTL because the drag+delta is physical while the panel is docked logically; a panel boots SHUT below+a phone width; and (hard-won detail 10) a panel is `overflow:auto`, so anything+floating inside it is clipped on both axes and must escape rather than overflow.+`panel.ts`/`panel.css` are the one home for each.++Pointers: `kernel/src/ui/panel.ts`, `kernel/src/ui/panel.css`,+`scripts/test-ui-panel.ts` (62 checks; the drag/RTL/collapse/persistence/drawer+behaviours are each mutation-caught, and the theming guard is reproduced from+tier 1 — to be factored into one shared helper when both primitives have landed).diff --git a/kernel/src/ui/panel.css b/kernel/src/ui/panel.cssnew file mode 100644index 00000000..8ba791ee--- /dev/null+++ b/kernel/src/ui/panel.css@@ -0,0 +1,122 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors++ THE SHARED SIDE-PANEL + RESIZER STYLES. See panel.ts for why this exists and+ what each of the four apps contributed. Sibling of menu.css (tier 1); the+ same two rules hold here and are not restated in full:++ 1. VALUES ARE THE HOST APP'S. Every colour and metric reads through a+ `--bkp-*` property whose fallback chain lands on whatever token the host+ already defines, so adoption changes no app's appearance and this sheet+ commits to no theme mechanism. NEVER `light-dark()` — it resolves off+ `color-scheme`, and slides sets `color-scheme: only light`, which would+ pin every light-dark() value to its light half (menu.css explains at+ length). The tier-1 theming guard — every colour chain must reach a token+ each app both DEFINES and THEMES — is reproduced against this file in+ scripts/test-ui-panel.ts.++ 2. Structure and behaviour are shared; only the look is the host's. */++.bkp {+ /* The panel is a flex column of the app's layout: the content, and the+ resizer strip on its inner edge. Width is the one thing that animates, and+ only when NOT dragging (see .bkp-noanim). */+ position: relative;+ display: flex;+ flex: none;+ width: var(--bkp-w, 236px);+ min-height: 0;+ background: var(--bkp-bg, var(--surface, var(--chrome, #fff)));+ transition: width 0.14s ease;+}+.bkp-start { border-inline-end: 1px solid var(--bkp-border, var(--line, #e3e8ef)); }+.bkp-end { border-inline-start: 1px solid var(--bkp-border, var(--line, #e3e8ef)); }++/* The resizer sits between the content and the canvas. On a 'start' panel it+ comes after the content in the DOM; on an 'end' panel, before — the source+ order does that, so the strip is always on the inner edge either way. */+.bkp-content {+ flex: 1 1 auto;+ min-width: 0;+ /* A panel scrolls its own content. hard-won detail 10: overflow on one axis+ computes the other to `auto` too, so anything that floats inside a panel+ (a menu, a popover) is clipped on BOTH axes — such a child must escape the+ panel the way menu.css's phone rule does, not rely on overflowing it. */+ overflow: auto;+}++.bkp-resizer {+ position: relative;+ flex: none;+ width: 5px;+ cursor: col-resize;+ background: transparent;+ /* the strip itself is invisible until hovered; the chevron is always there */+}+.bkp-resizer:hover { background: var(--bkp-resizer-hover, var(--line, #e3e8ef)); }+body.bkp-resizing { cursor: col-resize; user-select: none; }++/* WHILE DRAGGING, kill the width transition, or the panel animates a frame+ behind the cursor. The class is added for the drag only. */+.bkp-noanim { transition: none !important; }++/* The collapse chevron lives ON the resizer, centred, and docks flush to the+ screen edge when the panel is shut so it is still reachable. */+.bkp-toggle {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ width: 16px;+ height: 44px;+ padding: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ border: 1px solid var(--bkp-border, var(--line, #e3e8ef));+ border-radius: 8px;+ background: var(--bkp-bg, var(--surface, var(--chrome, #fff)));+ /* --muted, not a literal: the chevron colour must clear the contrast floor on+ both the light and dark surface, which a fixed grey does not. */+ color: var(--bkp-toggle-ink, var(--muted, #6b7789));+ font-size: 11px;+ line-height: 1;+ cursor: pointer;+}+.bkp-toggle::before { content: ''; width: 0; height: 0; border-block: 4px solid transparent; }+/* the arrow points toward the edge the panel would collapse into, and flips+ when collapsed to point back — direction is logical, so it mirrors under RTL */+.bkp-start .bkp-toggle::before { border-inline-start: 5px solid currentColor; }+.bkp-end .bkp-toggle::before { border-inline-end: 5px solid currentColor; }+.bkp-start.bkp-collapsed .bkp-toggle::before { border-inline: 0; border-inline-end: 5px solid currentColor; }+.bkp-end.bkp-collapsed .bkp-toggle::before { border-inline: 0; border-inline-start: 5px solid currentColor; }++/* ————— collapsed: the content is gone, the strip and its chevron remain —————+ The panel shrinks to the strip width; the chevron docks flush against the+ screen edge so it is still a target. */+.bkp-collapsed {+ width: var(--bkp-collapsed-w, 16px);+}+.bkp-collapsed > .bkp-content { display: none; }+.bkp-collapsed > .bkp-resizer { cursor: default; }+.bkp-collapsed > .bkp-resizer:hover { background: transparent; }++/* ————— drawer: below the phone width the panel overlays the canvas —————+ Set in JS (matchMedia against the configurable drawerBelow), not a fixed+ media query, so the breakpoint is the app's to choose. Open, it floats over+ the canvas; collapsed, it is off-screen entirely (the chevron aside). */+.bkp-drawer {+ position: absolute;+ top: 0;+ bottom: 0;+ z-index: var(--bkp-drawer-z, 40);+ box-shadow: var(--bkp-drawer-shadow, 0 0 40px rgb(20 30 45 / 0.28));+}+.bkp-drawer.bkp-start { inset-inline-start: 0; }+.bkp-drawer.bkp-end { inset-inline-end: 0; }+/* a collapsed drawer leaves only its chevron on the edge */+.bkp-drawer.bkp-collapsed {+ box-shadow: none;+ background: transparent;+ border: 0;+}diff --git a/kernel/src/ui/panel.ts b/kernel/src/ui/panel.tsnew file mode 100644index 00000000..1a8fd9b4--- /dev/null+++ b/kernel/src/ui/panel.ts@@ -0,0 +1,225 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SHARED SIDE-PANEL + RESIZER PRIMITIVE — tier 2 of the kernel UI+// primitives, after the menu (tier 1).+//+// WHY THIS EXISTS. Measured by concept, the resizable side panel is one design+// implemented three times and stubbed a fourth:+//+// slides .ed-sidebar + .ed-props, two .ed-resizer strips, drag-to-size with+// a per-side clamp, RTL-aware widening, .ed-noanim during the drag,+// .ed-collapsed, double-click reset, bento-ed-panels persistence,+// overlay DRAWERS below 700px, a chevron that docks flush when shut.+// spaces .sp-sidebar + .sp-insp, .sp-resizer + .sp-insp-rz, --sp-panew,+// .sp-noanim, .sp-pane-closed, keys bento-sp-width / -pane / -insp.+// dash one props panel, EXPLICITLY ported from slides (its panels.ts says+// "slides is the reference"): 5px resizer + docking chevron, `]` to+// collapse, boots shut below a width, bento-dash-panels* keys.+// type .t-props is a FIXED-WIDTH aside — overflow:auto, no resizer, no+// collapse, no persistence. It copied the row metrics ("at a fixed+// width, as slides and dash both do") and none of the machinery.+//+// So "slides is the basis" is again true of three and empty for the fourth —+// type would GAIN drag, collapse and persistence from adopting this, not lose+// anything to it.+//+// THE COST, as with the menu, is not bytes but knowledge with nowhere to live.+// Each app learned the same non-obvious things by itself: a panel must carry a+// no-animation class DURING a drag (or its width transition fights the cursor);+// the chevron docks flush to the screen edge when the panel is collapsed;+// widening flips direction under RTL because the drag delta is physical while+// the panel is docked logically; a panel boots SHUT below a phone width so the+// canvas is what you see; and — hard-won detail 10 — a panel is `overflow:auto`,+// so anything that floats inside it (a menu, a popover) is clipped on BOTH axes+// and must escape the way the menu primitive's phone rule does.+//+// VALUES ARE THE HOST APP'S, exactly as the menu primitive does it: every+// colour and metric reads through a `--bkp-*` custom property whose fallback+// chain lands on whatever token the host already defines, so adoption is+// appearance-neutral and this file commits to no theme mechanism (never+// light-dark(); see panel.css). The PERSISTENCE KEY is injected — the kernel+// must not hardcode an app's localStorage namespace, the same way the broadcast+// session takes an injected projection rather than learning an app's shape.++export interface PanelOpts {+ /** The panel body the app fills. The primitive owns the frame and the+ * resizer; the content is the app's. */+ content: HTMLElement+ /** Which screen edge the panel docks to. LOGICAL: 'start' is the left in LTR+ * and the right in RTL — the resizer and the drag direction follow. */+ side: 'start' | 'end'+ /** Width bounds and the default (also the double-click reset target). */+ defaultWidth: number+ minWidth: number+ maxWidth: number+ /** localStorage namespace for this panel's {width, collapsed}. Absent = the+ * panel does not persist (type's today). Two panels need two keys. */+ storageKey?: string+ /** Initial collapsed state, unless persistence overrides it. */+ collapsed?: boolean+ /** At or below this viewport width the panel is an overlay DRAWER rather than+ * a column, and boots shut. Default 700 (every app's phone width). */+ drawerBelow?: number+ /** Accessible name for the panel region. */+ label?: string+}++export interface Panel {+ /** The panel column (content + resizer). Put it in the app's layout. */+ readonly root: HTMLElement+ /** The draggable strip, carrying the collapse chevron. */+ readonly resizer: HTMLElement+ readonly content: HTMLElement+ readonly width: number+ readonly collapsed: boolean+ setWidth(px: number): void+ /** Reset to defaultWidth (what a double-click on the resizer does). */+ resetWidth(): void+ collapse(): void+ expand(): void+ toggle(): void+ /** Fires after any width or collapse change — the app refits its canvas here.+ * Returns an unsubscribe. */+ onChange(fn: () => void): () => void+ destroy(): void+}++const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v))++function lsGet(key: string): string | null {+ try { return localStorage.getItem(key) } catch { return null }+}+function lsSet(key: string, val: string): void {+ try { localStorage.setItem(key, val) } catch { /* private window / quota / blocked */ }+}++/** Is the document right-to-left? The drag delta is physical (clientX), so a+ * 'start' panel in RTL is docked on the RIGHT and widens the opposite way. */+function isRtl(): boolean {+ try { return getComputedStyle(document.documentElement).direction === 'rtl' } catch { return false }+}++export function createPanel(opts: PanelOpts): Panel {+ const drawerBelow = opts.drawerBelow ?? 700+ const root = document.createElement('div')+ root.className = 'bkp bkp-' + opts.side+ if (opts.label) root.setAttribute('aria-label', opts.label)+ root.setAttribute('role', 'region')++ const resizer = document.createElement('div')+ resizer.className = 'bkp-resizer'+ resizer.title = '' // the app may set a localized title; the primitive stays language-free+ const chevron = document.createElement('button')+ chevron.type = 'button'+ chevron.className = 'bkp-toggle'+ chevron.setAttribute('aria-expanded', 'true')+ resizer.appendChild(chevron)++ opts.content.classList.add('bkp-content')++ // The resizer sits on the panel's INNER edge: after the content for a 'start'+ // panel, before it for an 'end' panel, so the strip is always between the+ // panel and the canvas.+ if (opts.side === 'start') root.append(opts.content, resizer)+ else root.append(resizer, opts.content)++ let width = opts.defaultWidth+ let collapsed = !!opts.collapsed+ // A drawer boots shut: on a phone the canvas is what you want first.+ const mql = typeof matchMedia === 'function' ? matchMedia(`(max-width: ${drawerBelow}px)`) : null+ if (mql?.matches) collapsed = true++ // Persistence overrides the initial width/collapsed, when a key is given.+ if (opts.storageKey) {+ const raw = lsGet(opts.storageKey)+ if (raw) {+ try {+ const saved = JSON.parse(raw) as { width?: number; collapsed?: boolean }+ if (typeof saved.width === 'number') width = clamp(saved.width, opts.minWidth, opts.maxWidth)+ if (typeof saved.collapsed === 'boolean' && !mql?.matches) collapsed = saved.collapsed+ } catch { /* corrupt entry — ignore, use defaults */ }+ }+ }++ const listeners = new Set<() => void>()+ const fire = (): void => listeners.forEach((fn) => fn())++ function persist(): void {+ if (opts.storageKey) lsSet(opts.storageKey, JSON.stringify({ width, collapsed }))+ }++ function render(): void {+ root.style.setProperty('--bkp-w', `${width}px`)+ root.classList.toggle('bkp-collapsed', collapsed)+ root.classList.toggle('bkp-drawer', !!mql?.matches)+ chevron.setAttribute('aria-expanded', String(!collapsed))+ }++ const api: Panel = {+ root,+ resizer,+ content: opts.content,+ get width() { return width },+ get collapsed() { return collapsed },+ setWidth(px: number): void {+ width = clamp(px, opts.minWidth, opts.maxWidth)+ render(); persist(); fire()+ },+ resetWidth(): void {+ width = opts.defaultWidth+ render(); persist(); fire()+ },+ collapse(): void { if (!collapsed) { collapsed = true; render(); persist(); fire() } },+ expand(): void { if (collapsed) { collapsed = false; render(); persist(); fire() } },+ toggle(): void { collapsed = !collapsed; render(); persist(); fire() },+ onChange(fn: () => void): () => void { listeners.add(fn); return () => listeners.delete(fn) },+ destroy(): void {+ mql?.removeEventListener?.('change', onMql)+ root.remove()+ listeners.clear()+ },+ }++ // The chevron toggles; its click must not also start a drag.+ chevron.addEventListener('click', (ev) => { ev.stopPropagation(); api.toggle() })++ // Drag-to-size. A collapsed panel does not resize; the chevron is not a drag.+ resizer.addEventListener('mousedown', (down) => {+ if (down.target === chevron || collapsed) return+ down.preventDefault()+ const startX = down.clientX+ const startW = width+ // Physical delta → logical widen: a 'start' panel widens with a rightward+ // drag in LTR and a leftward drag in RTL; an 'end' panel is the mirror.+ const widensRight = (opts.side === 'start') !== isRtl()+ // No width transition WHILE dragging, or the panel chases the cursor a+ // frame behind. Every app learned this; here it is one class.+ root.classList.add('bkp-noanim')+ document.body.classList.add('bkp-resizing')+ const move = (ev: MouseEvent): void => {+ const dx = ev.clientX - startX+ api.setWidth(startW + (widensRight ? dx : -dx))+ }+ const up = (): void => {+ window.removeEventListener('mousemove', move)+ window.removeEventListener('mouseup', up)+ root.classList.remove('bkp-noanim')+ document.body.classList.remove('bkp-resizing')+ }+ window.addEventListener('mousemove', move)+ window.addEventListener('mouseup', up)+ })+ resizer.addEventListener('dblclick', (ev) => { if (ev.target !== chevron) api.resetWidth() })++ // Crossing the drawer breakpoint re-lays-out and, entering drawer width,+ // boots the panel shut so the canvas is what shows.+ function onMql(): void {+ if (mql?.matches) collapsed = true+ render(); fire()+ }+ mql?.addEventListener?.('change', onMql)++ render()+ return api+}diff --git a/scripts/test-ui-panel.ts b/scripts/test-ui-panel.tsnew file mode 100644index 00000000..9fabf620--- /dev/null+++ b/scripts/test-ui-panel.ts@@ -0,0 +1,269 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The shared kernel PANEL + RESIZER primitive — behaviour rig.+//+// node scripts/test-ui-panel.ts+//+// kernel/src/ui/panel.ts replaces three hand-rolled resizable side panels (and+// stubs a fourth). What differed between the apps was, again, INVISIBLE — the+// no-animation-during-drag class, the boot-shut-below-a-width rule, the RTL+// widening direction, double-click reset, per-viewer persistence. Every check+// below guards one of those, plus the theming guarantee the menu primitive+// introduced. Self-contained DOM (no build), like scripts/test-sync-vouch.ts.++import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'+const root = join(dirname(fileURLToPath(import.meta.url)), '..')++// ——— a DOM just big enough for panel.ts ———+type Handler = (e: unknown) => void+class El {+ tag: string+ children: El[] = []+ parent: El | null = null+ attrs = new Map<string, string>()+ styleMap = new Map<string, string>()+ private classes = new Set<string>()+ private handlers = new Map<string, Handler[]>()+ title = ''+ 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) },+ 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),+ }+ }+ get className() { return [...this.classes].join(' ') }+ set className(v: string) { this.classes = new Set(v.split(/\s+/).filter(Boolean)) }+ get style() { const m = this.styleMap; return { setProperty: (k: string, v: string) => m.set(k, v), getPropertyValue: (k: string) => m.get(k) ?? '' } }+ 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) } }+ appendChild(x: El) { x.parent = this; this.children.push(x); return x }+ remove() { if (this.parent) this.parent.children = this.parent.children.filter((c) => c !== this) }+ addEventListener(t: string, fn: Handler) { const a = this.handlers.get(t) ?? []; a.push(fn); this.handlers.set(t, a) }+ removeEventListener(t: string, fn: Handler) { this.handlers.set(t, (this.handlers.get(t) ?? []).filter((f) => f !== fn)) }+ fire(t: string, ev: Record<string, unknown> = {}) {+ for (const fn of this.handlers.get(t) ?? []) fn({ target: this, preventDefault() {}, stopPropagation() {}, ...ev })+ }+}+const win = new El('window')+;(globalThis as Record<string, unknown>).window = win+const docEl = new El('html')+const body = new El('body')+;(globalThis as Record<string, unknown>).document = {+ createElement: (t: string) => new El(t),+ documentElement: docEl,+ body,+}+let RTL = false+;(globalThis as Record<string, unknown>).getComputedStyle = () => ({ direction: RTL ? 'rtl' : 'ltr' })+const store = new Map<string, string>()+;(globalThis as Record<string, unknown>).localStorage = {+ getItem: (k: string) => store.get(k) ?? null,+ setItem: (k: string, v: string) => { store.set(k, v) },+ removeItem: (k: string) => { store.delete(k) },+}+let MQ = false+const mqlListeners: Handler[] = []+;(globalThis as Record<string, unknown>).matchMedia = () => ({+ get matches() { return MQ },+ addEventListener: (_t: string, fn: Handler) => { mqlListeners.push(fn) },+ removeEventListener: () => {},+})+const setMedia = (on: boolean) => { MQ = on; for (const fn of [...mqlListeners]) fn({}) }++const { createPanel } = await import('../kernel/src/ui/panel.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 mkContent = () => new El('div') as unknown as HTMLElement+const cssVar = (p: { root: { style: { getPropertyValue(k: string): string } } }) => p.root.style.getPropertyValue('--bkp-w')+type P = ReturnType<typeof createPanel>+const R = (p: P) => p.root as unknown as El+const RZ = (p: P) => p.resizer as unknown as El+const chevronOf = (p: P) => (p.resizer as unknown as El).children[0]++// ——— defaults & clamp ———+{+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 236, minWidth: 190, maxWidth: 520 })+ eq('boots at the default width', cssVar(p), '236px')+ ok(!p.collapsed, 'boots expanded')+ p.setWidth(1000); eq('setWidth clamps to max', p.width, 520)+ p.setWidth(10); eq('setWidth clamps to min', p.width, 190)+ p.resetWidth(); eq('resetWidth returns to default', p.width, 236)+ p.destroy()+}++// ——— drag, and the no-anim class during it ———+{+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ RZ(p).fire('mousedown', { clientX: 500 })+ ok(R(p).classList.contains('bkp-noanim'), 'the panel gets .bkp-noanim while dragging')+ win.fire('mousemove', { clientX: 560 }) // +60, start panel LTR widens right+ eq('a rightward drag widens a start panel in LTR', p.width, 260)+ win.fire('mouseup', {})+ ok(!R(p).classList.contains('bkp-noanim'), 'and loses .bkp-noanim after')+ p.destroy()+}++// ——— RTL flips the widen direction ———+{+ RTL = true+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ RZ(p).fire('mousedown', { clientX: 500 })+ win.fire('mousemove', { clientX: 560 }) // +60 physical, but RTL start panel is docked right+ eq('a rightward drag NARROWS a start panel under RTL', p.width, 140)+ win.fire('mouseup', {})+ p.destroy()+ RTL = false+}++// ——— an end panel is the mirror ———+{+ const p = createPanel({ content: mkContent(), side: 'end', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ RZ(p).fire('mousedown', { clientX: 500 })+ win.fire('mousemove', { clientX: 560 }) // +60, end panel LTR widens LEFTward → narrows on rightward+ eq('a rightward drag narrows an end panel in LTR', p.width, 140)+ win.fire('mouseup', {})+ p.destroy()+}++// ——— collapse: chevron toggles, aria flips, a collapsed panel does not drag ———+{+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ chevronOf(p).fire('click')+ ok(p.collapsed && R(p).classList.contains('bkp-collapsed'), 'the chevron collapses the panel')+ eq('aria-expanded flips', chevronOf(p).getAttribute('aria-expanded'), 'false')+ const w = p.width+ RZ(p).fire('mousedown', { clientX: 500 }); win.fire('mousemove', { clientX: 600 }); win.fire('mouseup', {})+ eq('a collapsed panel does not resize on drag', p.width, w)+ chevronOf(p).fire('click')+ ok(!p.collapsed, 'the chevron expands it again')+ p.destroy()+}++// ——— double-click resets ———+{+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 236, minWidth: 100, maxWidth: 400 })+ p.setWidth(300)+ RZ(p).fire('dblclick')+ eq('double-click resets to default', p.width, 236)+ p.destroy()+}++// ——— persistence: saved and restored, clamped; absent key writes nothing ———+{+ store.clear()+ const a = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 190, maxWidth: 520, storageKey: 'k-props' })+ a.setWidth(300); a.collapse()+ ok(store.has('k-props'), 'a panel with a key persists')+ a.destroy()+ const b = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 190, maxWidth: 520, storageKey: 'k-props' })+ eq('a new panel restores the saved width', b.width, 300)+ ok(b.collapsed, 'and the saved collapsed state')+ b.destroy()+ // a corrupt/oversized saved width is clamped on restore+ store.set('k-props', JSON.stringify({ width: 99999, collapsed: false }))+ const c = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 190, maxWidth: 520, storageKey: 'k-props' })+ eq('a saved width past max is clamped on restore', c.width, 520)+ c.destroy()+ // no key → nothing written+ const before = store.size+ const d = createPanel({ content: mkContent(), side: 'start', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ d.setWidth(250); d.collapse()+ eq('a panel with no key writes nothing', store.size, before)+ d.destroy()+}++// ——— drawer: boots shut below the width, and crossing in collapses ———+{+ MQ = true+ const p = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 100, maxWidth: 400 })+ ok(p.collapsed, 'a panel that boots below the drawer width boots SHUT')+ ok(R(p).classList.contains('bkp-drawer'), 'and carries .bkp-drawer')+ p.destroy()+ MQ = false+ const q = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 100, maxWidth: 400 })+ ok(!q.collapsed, 'above the width it boots open')+ setMedia(true)+ ok(q.collapsed && R(q).classList.contains('bkp-drawer'), 'crossing into drawer width collapses it and marks it a drawer')+ q.destroy()+}++// ——— drawer boot-shut does NOT overwrite a saved OPEN state until crossed ———+{+ store.clear(); MQ = false+ const a = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 100, maxWidth: 400, storageKey: 'k-d' })+ ok(!a.collapsed, 'wide: open')+ a.destroy()+ MQ = true+ const b = createPanel({ content: mkContent(), side: 'end', defaultWidth: 236, minWidth: 100, maxWidth: 400, storageKey: 'k-d' })+ ok(b.collapsed, 'below the drawer width the panel boots shut even though the saved state was open')+ b.destroy()+ MQ = false+}++// ——— onChange fires; destroy cleans up ———+{+ const p = createPanel({ content: mkContent(), side: 'start', defaultWidth: 200, minWidth: 100, maxWidth: 400 })+ let n = 0+ const off = p.onChange(() => { n++ })+ p.setWidth(250); p.toggle(); p.resetWidth()+ eq('onChange fires on width and collapse changes', n, 3)+ off(); p.setWidth(260)+ eq('unsubscribe stops it', n, 3)+ p.destroy()+ ok(R(p).parent === null || !R(p).parent, 'destroy removes the root')+}++// ——— THEMING GUARD (reproduced from tier 1's test-ui-menu): every colour+// chain in panel.css must reach a token each of the four apps both DEFINES and+// THEMES. When both primitives land, factor this into one shared helper. ———+{+ const css = readFileSync(join(root, 'kernel/src/ui/panel.css'), 'utf8')+ const chains: Array<{ prop: string; tokens: string[] }> = []+ for (const line of css.split('\n')) {+ const m = /(background|color|border[a-z-]*|box-shadow)\s*:\s*var\(--bkp-([a-z-]+),(.*)$/.exec(line)+ if (!m) continue+ const tokens = [...m[3].matchAll(/var\(\s*(--[a-z0-9-]+)/g)].map((x) => x[1])+ if (tokens.length) chains.push({ prop: m[2], tokens })+ }+ ok(chains.length >= 3, 'found the themed chains to check')++ function tokensOf(app: string) {+ const src = readFileSync(join(root, `${app}/src/styles.css`), '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]); if (m[2].includes('light-dark(')) themed.add(m[1])+ }+ for (const start of [...src.matchAll(/\[data-theme=["']dark["']\][^{]*\{|@media[^{]*prefers-color-scheme:\s*dark[^{]*\{/g)]) {+ let depth = 0, 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 }+ }+ // shadow is exempt (a translucent overlay shadow need not follow the theme,+ // and only some apps have a shadow token) — matches tier 1's exemption.+ const COLOUR = new Set(['bg', 'border', 'toggle-ink', 'resizer-hover'])+ for (const app of ['slides', 'spaces', 'dash', 'type']) {+ const { all, themed } = tokensOf(app)+ for (const { prop, tokens } of chains) {+ const defined = tokens.find((t) => all.has(t))+ ok(defined, `${app}: --bkp-${prop} reaches a token ${app} defines (${tokens.join(' → ')})`)+ if (!defined || !COLOUR.has(prop)) continue+ ok(themed.has(defined), `${app}: --bkp-${prop} lands on ${defined}, which ${app} themes`)+ }+ }+}++console.log(failures ? `\n${failures} FAILED of ${checks}` : `\ntest-ui-panel: ${checks} checks OK`)+process.exit(failures ? 1 : 0)