strata-react 1.0.29 → 1.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/components/compare-grid.d.ts +4 -1
- package/dist/components/compare-parts.d.ts +2 -1
- package/dist/components/compare-regions.d.ts +37 -0
- package/dist/components/compare-video.d.ts +19 -1
- package/dist/components/compare.d.ts +4 -1
- package/dist/components/media.d.ts +6 -1
- package/dist/components/viewport.d.ts +19 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +426 -24
- package/dist/index.js.map +1 -1
- package/dist/lib/viewport.d.ts +26 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_Fragment","AriaPopover","AriaMenu","AriaDialog","AriaInput","AriaToolbar","sizes","_Fragment","AriaToggleButton","AriaSwitch","AriaDialog","_Fragment","AriaPopover","Dialog","AriaCheckbox","_Fragment","_Fragment","idle","tones","_Fragment","_Fragment","AriaNumberField","AriaInput","AriaSlider","_Fragment","_Fragment","defaultFormat","format","Table","AriaTable","AriaColumn","AriaRow","AriaCell","AriaButton","clamp","clamp","clamp","_Fragment","AriaButton","_Fragment","Disclosure","_Fragment","AriaButton","AriaCheckbox","useWidth","_Fragment","_Fragment","AriaTabs","_Fragment","AriaDialog","_Fragment","MODE_LABEL","_Fragment","AriaSlider","_Fragment","db","AriaSlider","_Fragment","Separator","labelOf"],"sources":["../src/lib/in-view.ts","../src/lib/chords.ts","../src/components/hotkeys.tsx","../src/components/commands.tsx","../src/components/toolbar.tsx","../src/components/toggle.tsx","../src/components/switch.tsx","../src/components/dialog.tsx","../src/components/popover.tsx","../src/components/checkbox.tsx","../src/components/async-button.tsx","../src/components/status.tsx","../src/components/metric.tsx","../src/components/meter.tsx","../src/components/composition.tsx","../src/components/link-card.tsx","../src/components/data-view.tsx","../src/lib/number-input.ts","../src/components/value-controls.tsx","../src/components/alert.tsx","../src/lib/client-work.ts","../src/components/job-status.tsx","../src/components/thumbnail.tsx","../src/components/selection.tsx","../src/components/disclosure.tsx","../src/components/data-table.tsx","../src/components/media.tsx","../src/components/media-player.tsx","../src/lib/timeline.ts","../src/components/timeline.tsx","../src/components/sortable-list.tsx","../src/components/file-intake.tsx","../src/lib/file-intake.ts","../src/components/inspector.tsx","../src/components/selectable-grid.tsx","../src/components/virtual-list.tsx","../src/components/infinite-list.tsx","../src/components/line-chart.tsx","../src/components/page-header.tsx","../src/components/undo.tsx","../src/components/done.tsx","../src/components/app-shell.tsx","../src/components/tabs.tsx","../src/components/active-list.tsx","../src/query/infinite.ts","../src/query/job.ts","../src/components/fullscreen-frame.tsx","../src/lib/viewport.ts","../src/components/compare-parts.tsx","../src/lib/image-diff.ts","../src/components/difference.tsx","../src/components/viewport.tsx","../src/components/compare.tsx","../src/components/pair-vote.tsx","../src/lib/loudness.ts","../src/components/compare-audio.tsx","../src/components/compare-video.tsx","../src/lib/text-diff.ts","../src/components/compare-text.tsx","../src/components/compare-grid.tsx","../src/components/workspace.tsx","../src/components/history.tsx","../src/components/save.tsx"],"sourcesContent":["import * as React from \"react\";\n\n// One IntersectionObserver hook for everything that waits until it is near the screen: the\n// sentinel at the end of an InfiniteList and an image in a Thumbnail. Both watch from the nearest\n// `[data-strata-scroll]` region (a VirtualList's) or else the viewport, with a root\n// margin so the work starts before the element is reached. They differ in two ways, which are\n// options rather than two hooks:\n//\n// - `once`: an image, once asked for, stays asked for; scrolling it away again must not unload it.\n// A sentinel reports in and out of view every time.\n// - `unsupported`: where there is no IntersectionObserver (an old browser, a test without the\n// fake), an image loads at once, because a photo that never loads is worse than one loaded\n// early. A sentinel reports out of view, because InfiniteList's Show more button is the path\n// that always works.\n\n/** Options for {@link useInView}. */\nexport type InViewOptions = {\n /** Watch only while this is true. Default true. */\n active?: boolean;\n /** How far outside the scroll region still counts as in view (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Stay in view after the first time, and stop watching. */\n once?: boolean;\n /** What to report where `IntersectionObserver` does not exist. Default false. */\n unsupported?: boolean;\n};\n\n/**\n * Whether an element is within `rootMargin` of its scroll region (the nearest\n * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the\n * element as it mounts and unmounts.\n */\nexport function useInView({ active = true, rootMargin = \"0px\", once = false, unsupported = false }: InViewOptions = {}) {\n const [inView, setInView] = React.useState(false);\n const [el, setEl] = React.useState<Element | null>(null);\n const seen = once && inView;\n React.useEffect(() => {\n if (seen) return;\n if (!active || !el) {\n setInView(false);\n return;\n }\n if (typeof IntersectionObserver === \"undefined\") {\n setInView(unsupported);\n return;\n }\n const root = el.parentElement?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? null;\n const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), { root, rootMargin });\n observer.observe(el);\n return () => observer.disconnect();\n }, [active, el, rootMargin, seen, unsupported]);\n return { ref: setEl, inView };\n}\n","// Chords: a shortcut written once (\"Mod+Shift+Z\") and shown per platform (⌘⇧Z on macOS, Ctrl+Shift+Z\n// elsewhere). `Mod` is the platform's command key: Meta on macOS, Ctrl everywhere else. The other\n// modifiers are Ctrl, Meta, Alt and Shift. The key is a `KeyboardEvent.key` value, compared without\n// case (\"z\" and \"Z\" are the same key; Shift is part of the chord when written).\n//\n// Matching is exact on the modifiers: \"Mod+Z\" is not \"Mod+Shift+Z\", so Undo and Redo cannot both\n// fire. Shift is ignored for a symbol key (\"?\" is typed with Shift on most layouts), and Alt is\n// matched on the physical key for letters, since Alt+Z types \"Ω\" on a Mac.\n\n/** `\"mac\"` or `\"other\"`: which modifier glyphs to draw and what `Mod` means. */\nexport type Platform = \"mac\" | \"other\";\n\n/** The platform this page runs on, read from the browser (`mac` for macOS and iOS). Server and test default: `other`. */\nexport function detectPlatform(): Platform {\n if (typeof navigator === \"undefined\") return \"other\";\n const nav = navigator as Navigator & { userAgentData?: { platform?: string } };\n const text = nav.userAgentData?.platform ?? nav.platform ?? \"\";\n return /mac|iphone|ipad|ipod/i.test(text) ? \"mac\" : \"other\";\n}\n\ntype Parsed = { ctrl: boolean; meta: boolean; alt: boolean; shift: boolean; key: string };\n\n/** Splits \"Mod+Shift+Z\" into modifiers and key for a platform. A bare \"+\" key is written \"Mod++\". */\nexport function parseChord(chord: string, platform: Platform = detectPlatform()): Parsed {\n const parts = chord.endsWith(\"++\") ? [...chord.slice(0, -2).split(\"+\").filter(Boolean), \"+\"] : chord.split(\"+\");\n const key = parts.pop() ?? \"\";\n const mods = new Set(parts.map((p) => p.toLowerCase()));\n const mod = mods.has(\"mod\");\n return {\n ctrl: mods.has(\"ctrl\") || (mod && platform !== \"mac\"),\n meta: mods.has(\"meta\") || (mod && platform === \"mac\"),\n alt: mods.has(\"alt\"),\n shift: mods.has(\"shift\"),\n key,\n };\n}\n\nconst symbol = (key: string) => key.length === 1 && key.toUpperCase() === key.toLowerCase();\n\n/** Whether a key event is this chord. Exact on Ctrl, Meta and Alt; Shift is exact for letters and named keys. */\nexport function matchesChord(e: Pick<KeyboardEvent, \"key\" | \"code\" | \"ctrlKey\" | \"metaKey\" | \"altKey\" | \"shiftKey\">, chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n if (e.ctrlKey !== c.ctrl || e.metaKey !== c.meta || e.altKey !== c.alt) return false;\n if (!symbol(c.key) && e.shiftKey !== c.shift) return false;\n if (symbol(c.key) && c.shift && !e.shiftKey) return false;\n if (e.key.toLowerCase() === c.key.toLowerCase()) return true;\n return c.alt && /^[a-z]$/i.test(c.key) && e.code === `Key${c.key.toUpperCase()}`;\n}\n\nconst NAMES: Record<string, { mac: string; other: string }> = {\n ArrowUp: { mac: \"↑\", other: \"↑\" },\n ArrowDown: { mac: \"↓\", other: \"↓\" },\n ArrowLeft: { mac: \"←\", other: \"←\" },\n ArrowRight: { mac: \"→\", other: \"→\" },\n Escape: { mac: \"⎋\", other: \"Esc\" },\n Enter: { mac: \"↩\", other: \"Enter\" },\n Backspace: { mac: \"⌫\", other: \"Backspace\" },\n Delete: { mac: \"⌦\", other: \"Delete\" },\n \" \": { mac: \"Space\", other: \"Space\" },\n Tab: { mac: \"⇥\", other: \"Tab\" },\n Home: { mac: \"↖\", other: \"Home\" },\n End: { mac: \"↘\", other: \"End\" },\n};\n\n/** A chord as a person reads it on this platform: \"⌘⇧Z\" on macOS, \"Ctrl+Shift+Z\" elsewhere. */\nexport function formatChord(chord: string, platform: Platform = detectPlatform()): string {\n const c = parseChord(chord, platform);\n const key = NAMES[c.key]?.[platform] ?? (c.key.length === 1 ? c.key.toUpperCase() : c.key);\n if (platform === \"mac\") return `${c.ctrl ? \"⌃\" : \"\"}${c.alt ? \"⌥\" : \"\"}${c.shift ? \"⇧\" : \"\"}${c.meta ? \"⌘\" : \"\"}${key}`;\n return [c.ctrl && \"Ctrl\", c.meta && \"Meta\", c.alt && \"Alt\", c.shift && \"Shift\", key].filter(Boolean).join(\"+\");\n}\n\n// Chords the browser or the OS uses for itself. An app takes one over only on purpose (`claim` on\n// the command): silently stealing Ctrl+S from a person who wanted the browser's own is a choice.\nconst RESERVED = [\n \"Mod+S\", \"Mod+P\", \"Mod+F\", \"Mod+G\", \"Mod+O\", \"Mod+N\", \"Mod+T\", \"Mod+W\", \"Mod+R\", \"Mod+L\", \"Mod+D\", \"Mod+Q\", \"Mod+H\",\n \"Mod+J\", \"Mod+U\", \"Mod+Shift+T\", \"Mod+Shift+N\", \"Mod+Shift+W\", \"Alt+ArrowLeft\", \"Alt+ArrowRight\", \"F5\", \"F11\", \"F12\",\n];\n\n/** Whether the browser uses this chord for itself, so a command may take it only with `claim`. */\nexport function isReservedChord(chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n return RESERVED.some((r) => {\n const p = parseChord(r, platform);\n return p.ctrl === c.ctrl && p.meta === c.meta && p.alt === c.alt && p.shift === c.shift && p.key.toLowerCase() === c.key.toLowerCase();\n });\n}\n","import { KeyText } from \"./key-glyphs\";\nimport * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Single-key shortcuts for Operate screens that clear a queue (accept, reject, next). A person\n// doing the same answer a hundred times a day wants one key, no pointer and no motion\n// (ux-research `ux-character.md`: 100+ a day gets nothing but an instant change). Three rules\n// keep single keys from hurting anyone:\n// 1. They never fire while the person is typing: not in an input, textarea, select or\n// contenteditable (WCAG 2.1.4 Character Key Shortcuts), and not mid-composition (IME).\n// 2. They never take a chord: with Ctrl, Meta or Alt held the browser and the OS keep the key.\n// Shift is part of the key itself, so \"?\" works and \"A\" is not \"a\".\n// 3. Holding a key does not repeat an answer; only shortcuts marked `repeat` (moving) repeat.\n// The same list drives the handler and the legend, so a shortcut cannot exist without being\n// shown, and the legend cannot advertise a key that does nothing.\n\n/** One shortcut: the keys that run it (as `KeyboardEvent.key`), what it does in the product's words, and the action. */\nexport type Shortcut = {\n /** `KeyboardEvent.key` values, e.g. `[\"j\", \"ArrowDown\"]`. The first is the one the legend leads with. */\n keys: string[];\n /** What it does, in the product's words: \"Accept booking\", not \"Action 1\". */\n label: string;\n run: () => void;\n /** Fire again while the key is held. On for moving through a list, off (the default) for answers. */\n repeat?: boolean;\n /** Ignore the key for now, and show it muted in the legend (nothing is active, say). */\n disabled?: boolean;\n};\n\nconst TEXT_INPUTS_EXEMPT = new Set([\"checkbox\", \"radio\", \"button\", \"submit\", \"reset\", \"range\", \"color\", \"file\"]);\n\n/** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */\nexport function isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n if (target.isContentEditable || target.closest(\"[contenteditable=''],[contenteditable='true']\")) return true;\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;\n if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);\n return false;\n}\n\nfunction toShortcuts(input: Shortcut[] | Record<string, () => void>): Shortcut[] {\n return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({ keys: [key], label: key, run }));\n}\n\n/**\n * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta\n * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.\n */\nexport function useHotkeys(shortcuts: Shortcut[] | Record<string, () => void>, { enabled = true }: { enabled?: boolean } = {}) {\n // The listener is bound once; it reads the latest list, so handlers can close over fresh state.\n const latest = React.useRef<Shortcut[]>([]);\n latest.current = toShortcuts(shortcuts);\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;\n if (isTypingTarget(e.target)) return;\n const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));\n if (!hit || (e.repeat && !hit.repeat)) return;\n e.preventDefault();\n hit.run();\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled]);\n}\n\nconst KEY_NAMES: Record<string, string> = {\n ArrowDown: \"↓\",\n ArrowUp: \"↑\",\n ArrowLeft: \"←\",\n ArrowRight: \"→\",\n Escape: \"Esc\",\n Enter: \"Enter\",\n Backspace: \"Backspace\",\n Delete: \"Delete\",\n \" \": \"Space\",\n};\n\n// The legend is quiet, caption-sized and muted: it is there to be found, not read every time.\n// It hides on coarse pointers (phones, tablets without a keyboard), where the keys do not exist.\n// Each key is a <kbd>; alternatives are read as \"j or down arrow\".\n/** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */\nexport function KeysLegend({\n shortcuts,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n shortcuts: Pick<Shortcut, \"keys\" | \"label\" | \"disabled\">[];\n /** Names the legend for screen readers. */\n label?: string;\n className?: string;\n}) {\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shortcuts.map((s) => (\n <div key={s.keys.join(\" \")} className={cn(\"flex items-center gap-1.5\", s.disabled && \"opacity-50\")}>\n <dt className=\"flex items-center gap-1\">\n {s.keys.map((k, i) => (\n <React.Fragment key={k}>\n {i > 0 && <span className=\"sr-only\"> or </span>}\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n <KeyText>{KEY_NAMES[k] ?? k}</KeyText>\n </kbd>\n </React.Fragment>\n ))}\n </dt>\n <dd>{s.label}</dd>\n </div>\n ))}\n </dl>\n );\n}\n","import { KeyText } from \"./key-glyphs\";\nimport * as React from \"react\";\nimport {\n Autocomplete,\n Dialog as AriaDialog,\n Header,\n Heading,\n Keyboard,\n Menu as AriaMenu,\n MenuItem,\n MenuSection,\n MenuTrigger,\n Modal,\n ModalOverlay,\n Popover as AriaPopover,\n SearchField,\n Input as AriaInput,\n Separator,\n SubmenuTrigger,\n Text,\n useFilter,\n} from \"react-aria-components\";\nimport { Check, ChevronRight, Search, Trash2 } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { formatChord, detectPlatform, isReservedChord, matchesChord, type Platform } from \"../lib/chords\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// One command, declared once, used everywhere a person can reach it: a dropdown or menu-bar menu,\n// a context menu, the command menu, the key handler and the legend. Each of those reads the same\n// object, so the label, the enabled state and the shortcut text cannot disagree (components.md\n// §3.16 and §3.11; strata-react issue #71). This is the single-key `Shortcut` idea of `useHotkeys`\n// carried to menus and chords: `useHotkeys` is unchanged for a queue worked with single keys.\n//\n// - A label is a string or a function, so Undo can say \"Undo move clip\" and follow the history.\n// - `keys` are chords written once (\"Mod+Z\"), shown per platform (⌘Z or Ctrl+Z). They never fire\n// while the person is typing (a field's own Ctrl+Z is the field's) unless the command says\n// `inFields`, never during IME composition, and a chord the browser uses (Ctrl+S, Ctrl+P, ...)\n// is taken only with `claim: true`, an explicit choice.\n// - `disabled` is `true` or a sentence saying why (\"Nothing to undo\"); a disabled command's chord\n// does nothing, and every menu shows the item as unavailable, with the reason.\n// - Menus use React Aria's menu: roles, arrows, Home and End, typeahead, Escape back to the\n// trigger, submenus. A destructive item carries an icon as well as its colour, since colour\n// alone is not a signal (components.md §3.4). A group whose commands all have `checked` is a\n// group of checkable items.\n// Motion: shortcuts and the command menu are used 100+ times a day, so they appear at once.\n\n/** A command: what it is called, how it is run, and everything the menus need to draw it. */\nexport type Command = {\n /** Stable key for the command. */\n id: string;\n /** The verb phrase, sentence case, in the product's words (\"Split clip\"); a function when it follows state (\"Undo move clip\"). */\n label: string | (() => string);\n run: () => void;\n /** Chords that run it, written once (\"Mod+Z\", \"Delete\", \"Shift+?\"); the first is the one shown. */\n keys?: string[];\n /** Cannot run now. A sentence says why (\"Nothing to undo\") and is shown in menus. */\n disabled?: boolean | string;\n /** Cannot be undone or removes something: drawn with an icon and the danger colour. */\n destructive?: boolean;\n /** Makes a menu item checkable: whether it is on now. `run` toggles it. */\n checked?: boolean;\n icon?: IconComponent;\n /** Fire again while the key is held (for moving). Default false. */\n repeat?: boolean;\n /** Run from inside a text field too. Default false: a field keeps its own keys. */\n inFields?: boolean;\n /** Take over a chord the browser uses (Ctrl+S, Ctrl+P). Required for those; otherwise the command is not bound. */\n claim?: boolean;\n};\n\n/** What goes in a menu: a command, a separator, a titled group, or a submenu. */\nexport type MenuEntry = Command | \"separator\" | { group: string; items: Command[] } | { submenu: string; items: MenuEntry[] };\n\n/** The text of a command's label, whether it is a string or a function. */\nexport const labelOf = (c: Command) => (typeof c.label === \"function\" ? c.label() : c.label);\nconst isDisabled = (c: Command) => Boolean(c.disabled);\nconst reasonOf = (c: Command) => (typeof c.disabled === \"string\" ? c.disabled : undefined);\nconst isCommand = (e: MenuEntry): e is Command => typeof e === \"object\" && \"run\" in e;\n\n/** Options for `useCommands`. */\nexport type CommandsOptions = {\n enabled?: boolean;\n /** Which platform's `Mod` to use; read from the browser when left out. */\n platform?: Platform;\n};\n\n/**\n * Binds every command's chords on the window. Never while typing (unless the command says\n * `inFields`), never during IME composition, not on a held key (unless `repeat`), not for a disabled\n * command, and not for a chord the browser uses unless the command `claim`s it. A command's chord\n * that clashes with another's is a mistake: the first in the list wins, and a dev warning names both.\n */\nexport function useCommands(commands: readonly Command[], { enabled = true, platform }: CommandsOptions = {}) {\n const latest = React.useRef<readonly Command[]>([]);\n latest.current = commands;\n const where = platform ?? detectPlatform();\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing) return;\n for (const c of latest.current) {\n const chord = c.keys?.find((k) => matchesChord(e, k, where));\n if (!chord) continue;\n if (isReservedChord(chord, where) && !c.claim) continue;\n if (isTypingTarget(e.target) && !c.inFields) continue;\n if (isDisabled(c) || (e.repeat && !c.repeat)) return;\n e.preventDefault();\n c.run();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled, where]);\n\n if (import.meta.env?.DEV) warnOnClashes(commands, where);\n}\n\nfunction warnOnClashes(commands: readonly Command[], platform: Platform) {\n const seen = new Map<string, string>();\n for (const c of commands) {\n for (const k of c.keys ?? []) {\n const shown = formatChord(k, platform);\n const other = seen.get(shown);\n if (other && other !== c.id) console.warn(`strata-react: \"${shown}\" is bound to both \"${other}\" and \"${c.id}\"; the first wins.`);\n else seen.set(shown, c.id);\n }\n if (c.keys?.some((k) => isReservedChord(k, platform)) && !c.claim) {\n console.warn(`strata-react: \"${c.id}\" uses a chord the browser keeps for itself; add \\`claim: true\\` to take it over.`);\n }\n }\n}\n\n/** The shortcut a command shows in menus and legends (\"⌘Z\", \"Ctrl+Z\"), or undefined. */\nexport function commandShortcut(c: Command, platform: Platform = detectPlatform()): string | undefined {\n return c.keys?.[0] ? formatChord(c.keys[0], platform) : undefined;\n}\n\n/** A quiet legend built from the same commands the key handler runs: only commands with keys, disabled ones muted. */\nexport function CommandLegend({\n commands,\n platform,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n commands: readonly Command[];\n platform?: Platform;\n label?: string;\n className?: string;\n}) {\n const where = platform ?? detectPlatform();\n const shown = commands.filter((c) => c.keys?.length);\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shown.map((c) => (\n <div key={c.id} className={cn(\"flex items-center gap-1.5\", isDisabled(c) && \"opacity-50\")}>\n <dt>\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n <KeyText>{commandShortcut(c, where) ?? \"\"}</KeyText>\n </kbd>\n </dt>\n <dd>{labelOf(c)}</dd>\n </div>\n ))}\n </dl>\n );\n}\n\nconst itemClass = cn(\n \"flex min-h-(--control-h-sm) cursor-pointer items-center gap-2 rounded-control px-2 type-body-sm outline-none\",\n \"focus:bg-muted disabled:cursor-not-allowed disabled:text-muted-foreground disabled:opacity-70\",\n \"open:bg-muted\",\n);\n\nfunction Item({ command, platform }: { command: Command; platform: Platform }) {\n const Icon = command.icon ?? (command.destructive ? Trash2 : undefined);\n const shortcut = commandShortcut(command, platform);\n const reason = reasonOf(command);\n return (\n <MenuItem\n id={command.id}\n textValue={labelOf(command)}\n isDisabled={isDisabled(command)}\n onAction={command.run}\n className={cn(itemClass, command.destructive && !isDisabled(command) && \"text-danger\", \"flex-wrap\")}\n >\n {({ isSelected, selectionMode }) => (\n <>\n {selectionMode !== \"none\" ? (\n <span aria-hidden className=\"grid size-4 shrink-0 place-items-center\">{isSelected && <Check className=\"size-4\" />}</span>\n ) : (\n Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />\n )}\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{labelOf(command)}</Text>\n {shortcut && <Keyboard className=\"ml-6 shrink-0 font-mono type-caption text-muted-foreground\"><KeyText>{shortcut}</KeyText></Keyboard>}\n {reason && <Text slot=\"description\" className=\"w-full pl-6 type-caption text-muted-foreground\">{reason}</Text>}\n </>\n )}\n </MenuItem>\n );\n}\n\nfunction Entries({ entries, platform }: { entries: readonly MenuEntry[]; platform: Platform }) {\n return (\n <>\n {entries.map((entry, i) => {\n if (entry === \"separator\") return <Separator key={`sep-${i}`} className=\"my-1 h-px border-0 bg-border\" />;\n if (isCommand(entry)) return <Item key={entry.id} command={entry} platform={platform} />;\n if (\"group\" in entry) {\n const checkable = entry.items.length > 0 && entry.items.every((c) => c.checked !== undefined);\n return (\n <MenuSection\n key={`group-${entry.group}`}\n selectionMode={checkable ? \"multiple\" : undefined}\n selectedKeys={checkable ? entry.items.filter((c) => c.checked).map((c) => c.id) : undefined}\n >\n <Header className=\"px-2 pt-1 type-caption text-muted-foreground\">{entry.group}</Header>\n {entry.items.map((c) => <Item key={c.id} command={c} platform={platform} />)}\n </MenuSection>\n );\n }\n return (\n <SubmenuTrigger key={`sub-${entry.submenu}`}>\n <MenuItem textValue={entry.submenu} className={itemClass}>\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{entry.submenu}</Text>\n <ChevronRight aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n </MenuItem>\n <AriaPopover offset={0} crossOffset={-4} className={cn(\"layer-overlay min-w-48 p-1\", overlaySurface)}>\n <AriaMenu aria-label={entry.submenu} className=\"outline-none\">\n <Entries entries={entry.items} platform={platform} />\n </AriaMenu>\n </AriaPopover>\n </SubmenuTrigger>\n );\n })}\n </>\n );\n}\n\nconst surface = cn(\"layer-overlay min-w-48 p-1\", overlaySurface);\n\n/** Props for `Menu`. */\nexport type MenuProps = {\n /** Names the menu: \"File\", \"Edit\". Required. */\n label: string;\n /** The control that opens it. */\n trigger: React.ReactElement;\n items: readonly MenuEntry[];\n /** Controlled open state, for a story or a test that needs it shown. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n platform?: Platform;\n className?: string;\n};\n\n/** A dropdown menu of commands: the menu roles and keyboard model, shortcuts shown per platform, unavailable items with their reason, separators, groups, checkable groups and submenus. */\nexport function Menu({ label, trigger, items, open, onOpenChange, platform, className }: MenuProps) {\n const where = platform ?? detectPlatform();\n return (\n <MenuTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement=\"bottom start\" offset={4} className={cn(surface, className)}>\n <AriaMenu aria-label={label} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </MenuTrigger>\n );\n}\n\n/** Props for `ContextMenu`. */\nexport type ContextMenuProps = {\n /** Names the menu: \"Clip actions\". Required. */\n label: string;\n items: readonly MenuEntry[];\n /** The object it belongs to. It becomes the thing the menu opens on: right-click, the context-menu key and Shift+F10. */\n children: React.ReactElement<React.HTMLAttributes<HTMLElement>>;\n platform?: Platform;\n disabled?: boolean;\n};\n\n/**\n * A context menu for an object: opens on right-click at the pointer, and from the keyboard (the\n * context-menu key or Shift+F10) beside the focused object, with the same items and shortcuts as\n * every other menu. The child gets the handlers, so it should be focusable (a row, a clip).\n */\nexport function ContextMenu({ label, items, children, platform, disabled }: ContextMenuProps) {\n const where = platform ?? detectPlatform();\n const [at, setAt] = React.useState<{ x: number; y: number } | null>(null);\n const anchor = React.useRef<HTMLSpanElement>(null);\n const open = (x: number, y: number) => setAt({ x, y });\n const child = React.Children.only(children);\n return (\n <>\n {React.cloneElement(child, {\n onContextMenu: (e: React.MouseEvent<HTMLElement>) => {\n child.props.onContextMenu?.(e);\n if (disabled || e.defaultPrevented) return;\n e.preventDefault();\n open(e.clientX, e.clientY);\n },\n onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {\n child.props.onKeyDown?.(e);\n if (disabled || e.defaultPrevented) return;\n if (e.key === \"ContextMenu\" || (e.key === \"F10\" && e.shiftKey)) {\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n open(r.left + 8, r.bottom);\n }\n },\n })}\n {at && (\n <span ref={anchor} aria-hidden style={{ position: \"fixed\", left: at.x, top: at.y, width: 0, height: 0 }} />\n )}\n <AriaPopover triggerRef={anchor} isOpen={at !== null} onOpenChange={(o) => !o && setAt(null)} placement=\"bottom start\" offset={0} className={surface}>\n <AriaMenu aria-label={label} autoFocus=\"first\" onAction={() => setAt(null)} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </>\n );\n}\n\n/** Props for `CommandMenu`. */\nexport type CommandMenuProps = {\n /** The commands to search, usually the same list given to `useCommands`. Entries may be grouped. */\n commands: readonly MenuEntry[];\n /** Controlled open state; otherwise it opens on `shortcut`. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** The chord that opens it. Default `Mod+K`. `null` for none. */\n shortcut?: string | null;\n /** The search field's name and placeholder. Default \"Search commands\". */\n label?: string;\n platform?: Platform;\n};\n\nfunction flatten(entries: readonly MenuEntry[]): Command[] {\n return entries.flatMap((e) => (e === \"separator\" ? [] : isCommand(e) ? [e] : flatten(e.items)));\n}\n\n/** A searchable list of every command, opened by a chord (default Mod+K). Choosing one closes it and runs it; an unavailable command is shown with its reason and does nothing. */\nexport function CommandMenu({ commands, open, onOpenChange, shortcut = \"Mod+K\", label = \"Search commands\", platform }: CommandMenuProps) {\n const where = platform ?? detectPlatform();\n const [own, setOwn] = React.useState(false);\n const isOpen = open ?? own;\n const set = (next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n };\n React.useEffect(() => {\n if (!shortcut) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || !matchesChord(e, shortcut, where)) return;\n e.preventDefault();\n // A held key repeats keydown; toggling on each would flicker the dialog open and shut.\n if (e.repeat) return;\n set(!isOpen);\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n });\n const { contains } = useFilter({ sensitivity: \"base\" });\n const all = flatten(commands);\n return (\n <ModalOverlay isOpen={isOpen} onOpenChange={set} isDismissable className=\"layer-overlay fixed inset-0 grid justify-items-center overflow-hidden scrim p-4 pt-24\">\n <Modal className={cn(\"flex max-h-full w-full max-w-lg flex-col self-start outline-none\", overlaySurface)}>\n <AriaDialog aria-label={label} className=\"flex min-h-0 flex-col outline-none\">\n <Autocomplete filter={contains}>\n <SearchField aria-label={label} autoFocus className=\"flex items-center gap-2 border-b border-border px-3\">\n <Search aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <AriaInput placeholder={label} className=\"h-(--control-h) min-w-0 flex-1 bg-transparent type-body outline-none placeholder:text-muted-foreground\" />\n </SearchField>\n <AriaMenu\n aria-label=\"Commands\"\n className=\"min-h-0 overflow-y-auto overscroll-contain p-1 outline-none\"\n renderEmptyState={() => <p className=\"px-3 py-4 type-body-sm text-muted-foreground\">No command matches.</p>}\n onAction={() => set(false)}\n >\n {all.map((c) => <Item key={c.id} command={c} platform={where} />)}\n </AriaMenu>\n </Autocomplete>\n </AriaDialog>\n <Heading slot=\"title\" className=\"sr-only\">{label}</Heading>\n </Modal>\n </ModalOverlay>\n );\n}\n","import * as React from \"react\";\nimport { Toolbar as AriaToolbar, Separator } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// A toolbar groups controls that act on what is shown (a preview's grid and quality, a timeline's\n// snap, a table's density). React Aria gives it the WAI-ARIA toolbar keyboard model: one tab stop,\n// arrow keys (and Home and End) move inside it, Tab leaves it. It needs a `label`, as an unnamed\n// toolbar is announced as nothing. Groups inside it are separated by a hairline (`ToolbarSeparator`)\n// rather than by space alone, so a row of eight small controls reads as three groups. It lays out\n// as one wrapping row: when it runs out of width, controls wrap to the next line instead of being\n// hidden behind an overflow menu, which keeps every control reachable with no extra state\n// (an overflow menu is the later step, once the Menu exists).\n\n/** Props for `Toolbar`. */\nexport type ToolbarProps = {\n /** Names the toolbar for screen readers: \"Preview options\". Required. */\n label: string;\n orientation?: \"horizontal\" | \"vertical\";\n children: React.ReactNode;\n className?: string;\n};\n\n/** A group of controls with one tab stop and arrow-key movement (the WAI-ARIA toolbar pattern). Needs a `label`. */\nexport function Toolbar({ label, orientation = \"horizontal\", children, className }: ToolbarProps) {\n // React Aria's toolbar moves with the arrow keys; Home and End (to the first and last control) are\n // added here, as the WAI-ARIA toolbar pattern lists them. The capture phase runs before React\n // Aria's own handler, and a typing target (a number field inside the toolbar) keeps its Home and End.\n const jump = (e: React.KeyboardEvent<HTMLElement>) => {\n // Only events from inside the toolbar's own DOM: a Popover opened from a control here renders in\n // a portal, and its events still reach this handler through React's tree.\n if ((e.key !== \"Home\" && e.key !== \"End\") || isTypingTarget(e.target) || !e.currentTarget.contains(e.target as Node)) return;\n const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"button, input, select, textarea, a[href], [tabindex]\")].filter(\n (el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\" && el.tabIndex >= -1 && el.getAttribute(\"role\") !== \"separator\",\n );\n const target = e.key === \"Home\" ? items[0] : items[items.length - 1];\n if (!target) return;\n e.preventDefault();\n e.stopPropagation();\n target.focus();\n };\n return (\n <div className=\"contents\" onKeyDownCapture={jump}>\n <AriaToolbar\n aria-label={label}\n orientation={orientation}\n className={cn(\"flex flex-wrap items-center gap-1\", orientation === \"vertical\" && \"flex-col items-stretch\", className)}\n >\n {children}\n </AriaToolbar>\n </div>\n );\n}\n\n/** A hairline between groups of controls inside a `Toolbar`. */\nexport function ToolbarSeparator({ className }: { className?: string }) {\n return <Separator className={cn(\"mx-1 h-5 w-px self-center border-0 bg-border\", className)} />;\n}\n","import * as React from \"react\";\nimport { ToggleButton as AriaToggleButton, ToggleButtonGroup } from \"react-aria-components\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// On/off and one-of-a-few controls for what acts on the view: grid, snap, quality, view mode,\n// density. `Toggle` is one pressed-or-not button (`aria-pressed`); `ToggleGroup` is a single-choice\n// set of them for 2 to 7 short options that switch a view (components.md §3.3; for 2 to 5 options\n// that each need a sentence use `ChoiceGroup`).\n//\n// The chosen state must be seen without colour and must not look like the view's one filled\n// primary button (patterns.md §2, the one-filled-button rule): chosen is an ink border on a\n// neutral tint, with the label unchanged in weight (no layout shift), never `bg-primary`. An\n// icon-only toggle cannot be written without its name: `label` is required, becomes the accessible\n// name and is shown as a tooltip, as for `IconButton`. Toggles are used tens of times a day, so\n// they get the press and colour transitions and nothing more (character.md §3).\n\nconst base =\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control border type-label transition-state press [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 \" +\n \"border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground \" +\n \"selected:border-foreground selected:bg-muted selected:text-foreground \" +\n \"disabled:pointer-events-none disabled:opacity-50\";\n\nconst sizes = { default: \"h-(--control-h)\", sm: \"h-(--control-h-sm)\" } as const;\ntype Size = keyof typeof sizes;\n\n/** Props for `Toggle`. */\nexport type ToggleProps = {\n /** The name, always. Shown as the text unless `icon` is given with `iconOnly`, then it is the accessible name and the tooltip. */\n label: string;\n icon?: IconComponent;\n /** Show only the icon; `label` stays the name and tooltip. */\n iconOnly?: boolean;\n pressed?: boolean;\n defaultPressed?: boolean;\n onChange?: (pressed: boolean) => void;\n disabled?: boolean;\n size?: Size;\n className?: string;\n};\n\nfunction Face({ label, icon: Icon, iconOnly, pad }: { label: string; icon?: IconComponent; iconOnly?: boolean; pad: string }) {\n return (\n <>\n {Icon && <Icon aria-hidden />}\n {!iconOnly && <span className={pad}>{label}</span>}\n </>\n );\n}\n\n/** A button that is pressed or not (`aria-pressed`). Chosen reads as an ink border on a tint, never as the filled primary. */\nexport function Toggle({ label, icon, iconOnly = false, pressed, defaultPressed, onChange, disabled, size = \"default\", className }: ToggleProps) {\n const button = (\n <AriaToggleButton\n isSelected={pressed}\n defaultSelected={defaultPressed}\n onChange={onChange}\n isDisabled={disabled}\n aria-label={icon && iconOnly ? label : undefined}\n className={cn(base, sizes[size], icon && iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\", className)}\n >\n <Face label={label} icon={icon} iconOnly={iconOnly && Boolean(icon)} pad=\"\" />\n </AriaToggleButton>\n );\n return icon && iconOnly ? <Tooltip label={label}>{button}</Tooltip> : button;\n}\n\n/** One option of a `ToggleGroup`. */\nexport type ToggleOption = { value: string; label: string; icon?: IconComponent; iconOnly?: boolean };\n\n/** Props for `ToggleGroup`. */\nexport type ToggleGroupProps = {\n /** Names the group for screen readers: \"Preview quality\". Required. */\n label: string;\n options: readonly ToggleOption[];\n value: string;\n onChange: (value: string) => void;\n size?: Size;\n className?: string;\n};\n\n/** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */\nexport function ToggleGroup({ label, options, value, onChange, size = \"default\", className }: ToggleGroupProps) {\n return (\n <ToggleButtonGroup\n aria-label={label}\n selectionMode=\"single\"\n disallowEmptySelection\n selectedKeys={[value]}\n onSelectionChange={(keys) => {\n const next = [...keys][0];\n if (next !== undefined) onChange(String(next));\n }}\n className={cn(\"inline-flex gap-0.5 rounded-surface border border-border bg-background p-0.5\", className)}\n >\n {options.map((o) => {\n const iconOnly = Boolean(o.icon && o.iconOnly);\n const item = (\n <AriaToggleButton\n id={o.value}\n aria-label={iconOnly ? o.label : undefined}\n className={cn(\n base,\n // Inside the group the segments are 4px, the outer 6px less its 2px padding; the group's own\n // hairline replaces each segment's, and the chosen one keeps the ink border.\n \"border-transparent bg-transparent selected:border-foreground\",\n sizes[size],\n iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\",\n )}\n >\n <Face label={o.label} icon={o.icon} iconOnly={iconOnly} pad=\"\" />\n </AriaToggleButton>\n );\n return iconOnly ? <Tooltip key={o.value} label={o.label}>{item}</Tooltip> : React.cloneElement(item, { key: o.value });\n })}\n </ToggleButtonGroup>\n );\n}\n","import * as React from \"react\";\nimport { Switch as AriaSwitch } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A switch is for a setting that applies the moment it is flipped (show the grid, enable the\n// heatmap), never for one that needs a Save: that is a Checkbox in a form (components.md §3.3).\n// The label and the control are one target. \"On\" is shown by position and by a tick in the thumb\n// as well as by colour, so it survives a colour-blind reading. `role=\"switch\"` and its on state\n// come from React Aria. `detail` is the description, not part of the name: React Aria puts all the\n// text inside the switch into its label, so the label span names the control (`aria-labelledby`)\n// and the detail is pointed at by `aria-describedby`, as `Checkbox` and `Field` do (issue #152).\n// Used many times a day, so only a short colour and position transition.\n\n/** Props for `Switch`. */\nexport type SwitchProps = {\n /** What it turns on, as the visible label: \"Show elevation profile\". Required. */\n label: string;\n /** A muted second line under the label. */\n detail?: string;\n on?: boolean;\n defaultOn?: boolean;\n onChange?: (on: boolean) => void;\n disabled?: boolean;\n className?: string;\n};\n\n/** An on/off setting that applies at once, its label and control one target. */\nexport function Switch({ label, detail, on, defaultOn, onChange, disabled, className }: SwitchProps) {\n const id = React.useId();\n return (\n <AriaSwitch\n isSelected={on}\n defaultSelected={defaultOn}\n onChange={onChange}\n isDisabled={disabled}\n aria-labelledby={`${id}-label`}\n aria-describedby={detail ? `${id}-detail` : undefined}\n className={cn(\"group inline-flex min-h-6 cursor-pointer items-start gap-3 disabled:cursor-not-allowed disabled:opacity-50\", className)}\n >\n <span\n aria-hidden\n className={cn(\n \"mt-0.5 flex h-5 w-9 shrink-0 items-center rounded-pill border border-input bg-muted p-0.5 transition-state\",\n \"group-selected:border-primary group-selected:bg-primary\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n )}\n >\n <span className=\"grid size-3.5 place-items-center rounded-pill bg-background text-primary group-selected:translate-x-4\">\n <span className=\"hidden size-1.5 rounded-pill bg-primary group-selected:block\" />\n </span>\n </span>\n <span className=\"grid\">\n <span id={`${id}-label`} className=\"type-body\">{label}</span>\n {detail && <span id={`${id}-detail`} className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n </AriaSwitch>\n );\n}\n","import * as React from \"react\";\nimport {\n Dialog as AriaDialog,\n DialogTrigger,\n Heading,\n Modal,\n ModalOverlay,\n} from \"react-aria-components\";\nimport { X } from \"lucide-react\";\nimport { Button, IconButton } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Dialog is for a task that needs its own space; \"a modal is never the first idea for a form that\n// fits on the page\" (components.md §3.11). AlertDialog is the only confirm in the library, for what\n// cannot be undone: a reversible removal uses `UndoBar` instead (patterns.md §7).\n//\n// What the types and the component settle, so an app cannot get them wrong:\n// - A title is required (visible, or `hideTitle` for a screen-reader-only one): an unnamed dialog is\n// announced as \"dialog\" and nothing else. An AlertDialog's `confirm` is required and is the verb,\n// \"Delete 3 firings\", never \"OK\".\n// - React Aria moves focus in on open and back to the trigger on close, makes the page behind inert\n// and stops it scrolling. Content scrolls inside the dialog when tall (`overscroll-contain`), and\n// everything is portalled onto `layer-overlay`, above panes, sticky headers and the undo bar.\n// - A dialog can be made not closable while work runs (`closable={false}`: no close control, no\n// Escape, no outside press), so an export cannot lose its Close button halfway, as strata-vid's did.\n// - An AlertDialog ignores outside presses, focuses its safe choice (Cancel) first, and stays open\n// with the reason when an async confirm fails, since closing would hide that it did not happen.\n// - The same surface is a Sheet with `placement=\"end\"`: a side panel for a long form or a detail.\n\ntype Common = {\n /** What it is for: \"Export video\", \"Delete 3 firings?\". Required. */\n title: string;\n /** Shown under the title when it is not enough alone. */\n description?: React.ReactNode;\n /** The control that opens it. Leave out and drive it with `open` and `onOpenChange`. */\n trigger?: React.ReactElement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n};\n\n/** Props for `Dialog`. */\nexport type DialogProps = Common & {\n /** The body. It scrolls inside the dialog when it is taller than the window. */\n children?: React.ReactNode;\n /** The buttons along the bottom, built with `DialogActions`'s `close` render prop when one should close it. One filled button at most. */\n actions?: React.ReactNode | ((close: () => void) => React.ReactNode);\n /** Keep the title for screen readers only, when the body already says it. */\n hideTitle?: boolean;\n /** `false` while work cannot be interrupted: no close control, Escape or outside press. Default true. */\n closable?: boolean;\n /** `center` is a dialog; `end` is a sheet down the right edge. Default `center`. */\n placement?: \"center\" | \"end\";\n size?: \"sm\" | \"md\" | \"lg\";\n};\n\nconst sizes = { sm: \"max-w-sm\", md: \"max-w-lg\", lg: \"max-w-3xl\" } as const;\n\n// A dialog with a `trigger` is React Aria's DialogTrigger around it. One driven only by `open` has\n// nothing pressable to put in a trigger, and React Aria warns \"A PressResponder was rendered without a\n// pressable child\" for an empty one on every mount (issue #116), so it gets the controlled\n// ModalOverlay alone: it still traps focus and, on close, returns it to whatever had it before.\nfunction Overlay({ trigger, open, onOpenChange, children }: { trigger?: React.ReactElement; open?: boolean; onOpenChange?: (open: boolean) => void; children: React.ReactElement<React.ComponentProps<typeof ModalOverlay>> }) {\n if (trigger) {\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n {children}\n </DialogTrigger>\n );\n }\n return <Driven open={open} onOpenChange={onOpenChange}>{children}</Driven>;\n}\n\n// Without a trigger, React Aria has no element to hand focus back to, so the one that had it when\n// the dialog opened is kept (read while rendering, before the dialog moves focus in) and given it\n// back on close, unless the app has already put focus somewhere on purpose.\nfunction Driven({ open, onOpenChange, children }: { open?: boolean; onOpenChange?: (open: boolean) => void; children: React.ReactElement<React.ComponentProps<typeof ModalOverlay>> }) {\n const opener = React.useRef<Element | null>(null);\n const wasOpen = React.useRef(false);\n if (open && !wasOpen.current) opener.current = typeof document === \"undefined\" ? null : document.activeElement;\n wasOpen.current = Boolean(open);\n React.useEffect(() => {\n if (!open) return;\n return () => {\n const back = opener.current;\n opener.current = null;\n requestAnimationFrame(() => {\n const idle = !document.activeElement || document.activeElement === document.body;\n if (idle && back instanceof HTMLElement && back.isConnected) back.focus();\n });\n };\n }, [open]);\n return React.cloneElement(children, { isOpen: open, onOpenChange });\n}\n\nconst overlayClass = \"layer-overlay fixed inset-0 grid overflow-hidden scrim\";\n\n/** A modal dialog with a required title; focus goes in and returns, Escape and a close control dismiss it. `placement=\"end\"` makes it a sheet. */\nexport function Dialog({\n title, description, trigger, open, onOpenChange, className, children, actions,\n hideTitle, closable = true, placement = \"center\", size = \"md\",\n}: DialogProps) {\n const descriptionId = React.useId();\n return (\n <Overlay trigger={trigger} open={open} onOpenChange={onOpenChange}>\n <ModalOverlay isDismissable={closable} isKeyboardDismissDisabled={!closable} className={cn(overlayClass, placement === \"end\" ? \"justify-items-end\" : \"place-items-center p-4\")}>\n <Modal\n className={cn(\n \"flex max-h-full min-h-0 w-full flex-col outline-none\",\n overlaySurface,\n placement === \"end\" ? \"h-full max-w-md rounded-r-none\" : sizes[size],\n className,\n )}\n >\n <AriaDialog aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className={cn(\"type-heading\", hideTitle && \"sr-only\")}>\n {title}\n </Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {closable && <IconButton icon={X} label=\"Close\" onPress={close} className=\"-mr-2 -mt-2 shrink-0\" />}\n </div>\n {children != null && <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\">{children}</div>}\n {actions != null && (\n <div className=\"flex flex-wrap justify-end gap-2\">{typeof actions === \"function\" ? actions(close) : actions}</div>\n )}\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </Overlay>\n );\n}\n\n/** Props for `AlertDialog`. */\nexport type AlertDialogProps = Common & {\n /** The verb, repeating the action: \"Delete 3 firings\". Required; \"OK\" and \"Confirm\" are what this prevents. */\n confirm: string;\n /** Runs on confirm. When it returns a promise the dialog waits, shows the button busy, and stays open with the reason if it rejects. */\n onConfirm: () => void | Promise<unknown>;\n /** The safe choice, which has initial focus. Default \"Cancel\". */\n cancel?: string;\n /** `destructive` fills the confirm button with the destructive role. Default `destructive`. */\n tone?: \"destructive\" | \"default\";\n};\n\n/**\n * A confirm for what cannot be undone. Names the object and the consequence in `title`, repeats the\n * verb on the confirm button, focuses Cancel first and ignores outside presses.\n */\nexport function AlertDialog({\n title, description, trigger, open, onOpenChange, className, confirm, onConfirm, cancel = \"Cancel\", tone = \"destructive\",\n}: AlertDialogProps) {\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string>();\n const [inner, setInner] = React.useState(false);\n const descriptionId = React.useId();\n const isOpen = open ?? inner;\n const change = (next: boolean) => {\n if (busy) return;\n setError(undefined);\n setInner(next);\n onOpenChange?.(next);\n };\n const run = async () => {\n try {\n const result = onConfirm();\n if (result && typeof (result as Promise<unknown>).then === \"function\") {\n setBusy(true);\n await result;\n }\n setBusy(false);\n change(false);\n } catch (thrown) {\n setBusy(false);\n setError(describeActionError(thrown) ?? \"That did not go through. Nothing was confirmed; try again.\");\n }\n };\n return (\n <Overlay trigger={trigger} open={isOpen} onOpenChange={change}>\n <ModalOverlay isDismissable={false} isKeyboardDismissDisabled={busy} className={cn(overlayClass, \"place-items-center p-4\")}>\n <Modal className={cn(\"flex max-h-full w-full max-w-sm flex-col outline-none\", overlaySurface, className)}>\n <AriaDialog role=\"alertdialog\" aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n {/* The message scrolls inside the dialog on a short window or with large text; the buttons stay in view. */}\n <div className=\"grid min-h-0 gap-3 overflow-y-auto overscroll-contain\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className=\"type-heading\">{title}</Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-control bg-danger-subtle px-3 py-2 type-body-sm text-danger\">\n {error}\n </p>\n )}\n </div>\n <div className=\"flex flex-wrap justify-end gap-2\">\n <Button autoFocus disabled={busy} onPress={close}>{cancel}</Button>\n <Button variant={tone === \"destructive\" ? \"destructive\" : \"default\"} disabled={busy} aria-busy={busy || undefined} onPress={run}>\n {busy ? `${confirm}…` : confirm}\n </Button>\n </div>\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </Overlay>\n );\n}\n\n","import * as React from \"react\";\nimport { Dialog, DialogTrigger, Popover as AriaPopover } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A popover holds a small form or a choice anchored to the control that opened it (a colour, a\n// sort, a few filters) where a dialog would take the whole screen. Unlike a tooltip it may hold\n// anything interactive. React Aria keeps it inside the viewport (flips and shifts at the edges),\n// closes it on Escape and on a press outside, and returns focus to the trigger. It is a labelled\n// `dialog`, so `label` is required: an unnamed floating region is the same defect as an unnamed\n// icon button. It is portalled to the body on `layer-overlay`, so panes and sticky headers cannot\n// clip or cover it.\n\n/** Props for `Popover`. */\nexport type PopoverProps = {\n /** What the popover is, as a screen reader names it: \"Line colour\", \"Filters\". Required. */\n label: string;\n /** The control that opens it (a `Button`); it gets `aria-expanded` and focus back on close. */\n trigger: React.ReactElement;\n children: React.ReactNode;\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n /** Where along the trigger it lines up. Default `start`. */\n align?: \"start\" | \"center\" | \"end\";\n /** Controlled open state. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** Width of the surface. Default `md` (18rem). */\n size?: \"sm\" | \"md\" | \"lg\";\n className?: string;\n};\n\nconst widths = { sm: \"w-52\", md: \"w-72\", lg: \"w-96\" } as const;\n\n/** A floating panel anchored to its trigger, for a small form or choice. Requires a `label`; closes on Escape and outside press, and returns focus. */\nexport function Popover({ label, trigger, children, side = \"bottom\", align = \"start\", open, onOpenChange, size = \"md\", className }: PopoverProps) {\n const placement = (align === \"center\" ? side : `${side} ${align}`) as React.ComponentProps<typeof AriaPopover>[\"placement\"];\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement={placement} offset={6} className={cn(\"layer-overlay p-3\", widths[size], overlaySurface, className)}>\n <Dialog aria-label={label} className=\"outline-none\">\n {children}\n </Dialog>\n </AriaPopover>\n </DialogTrigger>\n );\n}\n","import * as React from \"react\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check, Minus } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A checkbox cannot be written without a name: `label` is required, as `IconButton`'s is. Shown,\n// it sits beside the box inside one <label>, so the label and the control are a single target\n// with no dead zone between them (Vercel's interface guidelines; ux-design audit.md). Hidden\n// (`hideLabel`, for a table cell where the row already says what it is), it becomes the\n// accessible name through aria-label, never through visually hidden text: a hidden span inside a\n// label joined to a neighbour did not form a name with its space in dom-testing-library (strata-\n// react issue #11), and an aria-label leaves no room for that.\n//\n// It is React Aria's Checkbox (a visually hidden native input inside the label), so keyboard,\n// forms, `aria-checked=\"mixed\"` and press handling are the library's, and the 18px box is drawn\n// from our tokens (it is no longer the platform's `accent-primary` control: that one could not show\n// a tick and a dash in the theme's own roles). `checked=\"mixed\"` is the indeterminate state a\n// select-all needs. It used to be native; the visual baselines changed for it (CHANGELOG).\n//\n// `onCheckedChange` also says whether Shift was held, which is how a list of checkboxes extends a\n// range (strata-react issue #32). A change event carries no modifier keys, so the label notes Shift\n// on the press that leads to it: a mouse press anywhere on the target, or Space on the box.\n\n/** A checkbox with its label as one target. `label` is required; `checked=\"mixed\"` is indeterminate. */\nexport type CheckboxProps = Omit<React.ComponentProps<\"input\">, \"type\" | \"checked\" | \"onChange\" | \"aria-label\" | \"children\" | \"style\"> & {\n /** Names the checkbox. Shown beside it unless `hideLabel`. */\n label: string;\n /** Keep the label as the accessible name only, for a cell or toolbar where the context shows what it is. */\n hideLabel?: boolean;\n /** A muted second line under a shown label. */\n detail?: string;\n checked: boolean | \"mixed\";\n /** Called with the new state, and whether Shift was held (a range click or Shift+Space). */\n onCheckedChange: (checked: boolean, gesture: CheckboxGesture) => void;\n};\n\n/** How a checkbox was changed: `shiftKey` is true for Shift+click and Shift+Space, which extend a range in a list. */\nexport type CheckboxGesture = { shiftKey: boolean };\n\n/** A checkbox and its label as one target. `label` is required; `hideLabel` keeps it as the accessible name only. */\nexport function Checkbox({ label, hideLabel = false, detail, checked, onCheckedChange, className, disabled, required, ...props }: CheckboxProps) {\n const shift = useShiftNote();\n const id = React.useId();\n // Shift is noted in the capture phase on a wrapper, because React Aria's press handling stops the\n // events it uses before they bubble. `contents` keeps the wrapper out of layout.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={checked === true}\n isIndeterminate={checked === \"mixed\"}\n isDisabled={disabled}\n isRequired={required}\n onChange={(selected) => onCheckedChange(selected, shift.take())}\n aria-label={hideLabel ? label : undefined}\n aria-labelledby={hideLabel ? undefined : `${id}-label`}\n aria-describedby={!hideLabel && detail ? `${id}-detail` : undefined}\n {...(props as object)}\n className={cn(\n \"group inline-flex min-h-6 min-w-6 items-start gap-3\",\n hideLabel && \"items-center justify-center\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\",\n className,\n )}\n >\n {({ isSelected, isIndeterminate }) => (\n <>\n <CheckboxBox selected={isSelected} indeterminate={isIndeterminate} hideLabel={hideLabel} />\n {!hideLabel && (\n <span className=\"grid\">\n <span id={`${id}-label`} className=\"type-body\">{label}</span>\n {detail && <span id={`${id}-detail`} className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n )}\n </>\n )}\n </AriaCheckbox>\n </span>\n );\n}\n\n/** Notes Shift on the press that leads to a checkbox's change event, which has no modifier keys of its own. */\nexport function useShiftNote() {\n const held = React.useRef(false);\n return React.useMemo(\n () => ({\n handlers: {\n onMouseDown: (e: React.MouseEvent) => void (held.current = e.shiftKey),\n onKeyDown: (e: React.KeyboardEvent) => void (held.current = e.shiftKey),\n },\n take: (): CheckboxGesture => {\n const shiftKey = held.current;\n held.current = false;\n return { shiftKey };\n },\n }),\n [],\n );\n}\n\n// The drawn box, shared by `Checkbox` and the table's selection checkbox.\nfunction CheckboxBox({ selected, indeterminate, hideLabel }: { selected: boolean; indeterminate: boolean; hideLabel: boolean }) {\n return (\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 shrink-0 place-items-center rounded-control border border-input bg-background transition-state\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n (selected || indeterminate) && \"border-primary bg-primary text-primary-foreground\",\n !hideLabel && \"mt-0.5\",\n )}\n >\n {indeterminate ? <Minus className=\"size-3.5\" strokeWidth={3} /> : selected ? <Check className=\"size-3.5\" strokeWidth={3} /> : null}\n </span>\n );\n}\n\n/**\n * The checkbox of a React Aria `Table` row or header (`slot=\"selection\"`): its checked, mixed and\n * disabled state come from the table, so it takes only a name. A `Checkbox` is controlled and would\n * fight the table's own selection state. Not exported from the package: `DataTable` uses it.\n * @internal\n */\nexport function TableSelectionCheckbox({ label, className, disabled }: { label: string; className?: string; disabled?: boolean }) {\n // The table names a row's checkbox from its own label and the row header's text; ours is named\n // by the caller's `rowLabel` alone (\"Select Tom Ellery\"), so it labels itself.\n const id = React.useId();\n return (\n <AriaCheckbox\n slot=\"selection\"\n isDisabled={disabled}\n id={id}\n aria-labelledby={id}\n aria-label={label}\n className={({ isDisabled }) =>\n cn(\"group inline-flex min-h-6 min-w-6 items-center justify-center\", isDisabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\", className)\n }\n >\n {({ isSelected, isIndeterminate }) => <CheckboxBox selected={isSelected} indeterminate={isIndeterminate} hideLabel />}\n </AriaCheckbox>\n );\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button, type ButtonProps } from \"./button\";\nimport { describeActionError, fieldErrorsOf } from \"../lib/errors\";\n\n// One object through its states: \"Book firing\" becomes \"Booking…\" becomes \"Booked\", in the same\n// button, rather than the button being swapped for a spinner. The labels are stacked in one grid\n// cell so the button is always as wide as its longest label and nothing around it shifts. The\n// button stays enabled until the request starts (so a person can always try), and the outcome is\n// announced politely for screen readers. When the action fails, the announcement carries what\n// went wrong in the product's words before the retry label (\"Kiln 2 is already booked. Try\n// again\"), because \"Try again\" alone does not say whether trying again can help.\n//\n// The button carries `data-phase` (and Button's `data-variant`), so a test reads which phase it is\n// in without matching four stacked labels in its text (strata-react issue #48); `asyncButtonPhase`\n// in strata-react/testing reads it.\n//\n// `useAsyncAction` also owns a form's field messages (strata-react issues #42 and #46). `validate`\n// runs before the action, and messages it returns stop the run and land on `fieldErrors`, keyed by\n// field; a server's per-field messages (an HttpError's `fieldErrors`, from a 422) land there too.\n// A screen passes `fieldErrors.link` to `Field error=` and keeps no `problem` state of its own.\n// Failing validation leaves the button idle, not \"Try again\": nothing was tried. `onInvalid` runs\n// once the messages are on screen, to move focus to the first field named.\n\nexport type Phase = \"idle\" | \"pending\" | \"done\" | \"error\";\n\nexport type AsyncLabels = {\n idle: string;\n /** Ends in an ellipsis: \"Saving…\", \"Booking…\". */\n pending: string;\n /** The same verb, finished: \"Saved\", \"Booked\". */\n done: string;\n error?: string;\n};\n\n/** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */\nexport function AsyncButton({\n phase,\n labels,\n error,\n disabled,\n ...props\n}: Omit<ButtonProps, \"children\"> & {\n phase: Phase;\n labels: AsyncLabels;\n /** What went wrong, in the product's words (`useAsyncAction`'s `error`). Announced with the error label when `phase` is `error`. */\n error?: string;\n}) {\n const errorLabel = labels.error ?? \"Try again\";\n const current = { idle: labels.idle, pending: labels.pending, done: labels.done, error: errorLabel }[phase];\n const Icon = { idle: null, pending: LoaderCircle, done: Check, error: CircleAlert }[phase];\n const announcement = phase === \"done\" ? labels.done : phase === \"error\" ? (error ? `${error} ${errorLabel}` : errorLabel) : \"\";\n\n return (\n <>\n <Button {...props} data-phase={phase} disabled={disabled || phase === \"pending\"} aria-disabled={phase === \"pending\" || undefined}>\n {Icon && <Icon aria-hidden className={phase === \"pending\" ? \"motion-safe:animate-spin\" : undefined} />}\n <span className=\"grid\">\n {[labels.idle, labels.pending, labels.done, errorLabel].map((l) => (\n <span key={l} aria-hidden={l !== current} className={l === current ? \"[grid-area:1/1]\" : \"invisible [grid-area:1/1]\"}>\n {l}\n </span>\n ))}\n </span>\n </Button>\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </>\n );\n}\n\n/** Messages for a form's fields, keyed by field name. */\nexport type FieldErrors = Readonly<Record<string, string>>;\n\n/** Options for `useAsyncAction`. */\nexport type AsyncActionOptions<A extends unknown[] = unknown[]> = {\n /** How long `done` shows before returning to `idle`. Default 2000ms. */\n settleMs?: number;\n /** Called with whatever the action threw, once the `error` render has committed: for logging, or to move focus to the retry button or an error message. */\n onError?: (error: unknown) => void;\n /** Turns what was thrown into `error`'s sentence, in the product's words. Default `describeActionError`: HTTP status sentences for `fetchJson`'s `HttpError`, else the Error's message. */\n describeError?: (error: unknown) => string | undefined;\n /** Checks the arguments before the action runs. A message for any field stops the run and is put on `fieldErrors`; the button stays idle. */\n validate?: (...args: A) => Record<string, string | undefined> | undefined;\n /** Called once validation's messages are on screen: to move focus to the first field named. */\n onInvalid?: (fieldErrors: FieldErrors) => void;\n};\n\n/** What `useAsyncAction` returns: the phase for `AsyncButton`, a stable `run`, and what went wrong while `phase` is `error`. */\nexport type AsyncAction<A extends unknown[]> = {\n phase: Phase;\n run: (...args: A) => Promise<void>;\n /** What went wrong, from `describeError`, while `phase` is `error`; otherwise undefined. Pass it to `AsyncButton`'s `error`. */\n error: string | undefined;\n /** What the action threw, while `phase` is `error`: to read more than the sentence (an HttpError's `status` or `body`). */\n thrown: unknown;\n /** Messages per field, from `validate` or from the server (an HttpError's `fieldErrors`). Pass each to its `Field`'s `error`. Cleared by the next run. */\n fieldErrors: FieldErrors;\n /** Clears one field's message (as the person edits it), or all of them. */\n clearFieldError: (field?: string) => void;\n};\n\n// The action and its options are read through a ref so `run` keeps one identity for the\n// component's life: a caller can pass an inline arrow without re-rendering every child that takes\n// `run`, and without the try/catch and error state each caller used to write to reach the phase.\n\n/** Runs an async action and reports its phase, its error and any field messages. `done` returns to `idle` after `settleMs`; `run` never changes identity. */\nexport function useAsyncAction<A extends unknown[]>(\n action: (...args: A) => Promise<unknown>,\n { settleMs = 2000, onError, describeError = describeActionError, validate, onInvalid }: AsyncActionOptions<A> = {},\n): AsyncAction<A> {\n const [state, setState] = React.useState<ActionState>(idle);\n const timer = React.useRef<number | undefined>(undefined);\n const unreported = React.useRef<{ thrown: unknown } | { invalid: FieldErrors } | undefined>(undefined);\n const latest = React.useRef({ action, onError, settleMs, describeError, validate, onInvalid });\n React.useLayoutEffect(() => {\n latest.current = { action, onError, settleMs, describeError, validate, onInvalid };\n });\n React.useEffect(() => () => window.clearTimeout(timer.current), []);\n const run = React.useCallback(async (...args: A) => {\n window.clearTimeout(timer.current);\n const invalid = messages(latest.current.validate?.(...args));\n if (invalid) {\n unreported.current = { invalid };\n setState({ ...idle, fieldErrors: invalid });\n return;\n }\n setState({ ...idle, phase: \"pending\" });\n try {\n await latest.current.action(...args);\n setState({ ...idle, phase: \"done\" });\n timer.current = window.setTimeout(() => setState(idle), latest.current.settleMs);\n } catch (thrown) {\n unreported.current = { thrown };\n setState({ phase: \"error\", error: latest.current.describeError(thrown), thrown, fieldErrors: fieldErrorsOf(thrown) });\n }\n }, []);\n // onError and onInvalid run after their render commits, not inside run: there the button is\n // still disabled from `pending` and a message rendered on `error` does not exist yet, so a\n // callback that moves focus to either would find nothing to focus.\n React.useEffect(() => {\n const note = unreported.current;\n if (!note) return;\n if (\"thrown\" in note && state.phase === \"error\") latest.current.onError?.(note.thrown);\n else if (\"invalid\" in note) latest.current.onInvalid?.(note.invalid);\n else return;\n unreported.current = undefined;\n }, [state]);\n const clearFieldError = React.useCallback(\n (field?: string) =>\n setState((s) => {\n if (field === undefined) return Object.keys(s.fieldErrors).length ? { ...s, fieldErrors: {} } : s;\n if (!(field in s.fieldErrors)) return s;\n const { [field]: _gone, ...rest } = s.fieldErrors;\n return { ...s, fieldErrors: rest };\n }),\n [],\n );\n return { phase: state.phase, run, error: state.error, thrown: state.thrown, fieldErrors: state.fieldErrors, clearFieldError };\n}\n\ntype ActionState = { phase: Phase; error: string | undefined; thrown: unknown; fieldErrors: FieldErrors };\nconst idle: ActionState = { phase: \"idle\", error: undefined, thrown: undefined, fieldErrors: {} };\n\n/** The messages `validate` returned, without the empty ones; undefined when there are none. */\nfunction messages(found: Record<string, string | undefined> | undefined): FieldErrors | undefined {\n if (!found) return undefined;\n const kept = Object.fromEntries(Object.entries(found).filter((e): e is [string, string] => Boolean(e[1])));\n return Object.keys(kept).length ? kept : undefined;\n}\n","import type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\n\n// Status is a word first. `children` is required and must be a string, so a status can never be a\n// bare coloured dot. The tint and ink come from the fixed status roles, which are kept apart from\n// the brand accent: pale tint, dark ink of the same hue, never a saturated chip with white text.\n// No pulsing variant exists; nothing on a status mark moves unless the data behind it is live.\n\nexport type Tone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\nconst tones: Record<Tone, string> = {\n neutral: \"bg-muted text-muted-foreground\",\n info: \"bg-info-subtle text-info\",\n success: \"bg-success-subtle text-success\",\n warning: \"bg-warning-subtle text-warning\",\n danger: \"bg-danger-subtle text-danger\",\n};\n\n/** A status as a word on a pale tint of its tone, with an optional icon. Never colour alone. */\nexport function Status({\n tone,\n icon: Icon,\n children,\n className,\n}: {\n tone: Tone;\n icon?: IconComponent;\n children: string;\n className?: string;\n}) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 whitespace-nowrap rounded-pill py-0.5 pr-2.5 pl-2 type-caption font-medium\",\n tones[tone],\n className,\n )}\n >\n {Icon && <Icon aria-hidden className=\"size-3.5 shrink-0\" />}\n {children}\n </span>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Headline figures as one container split by hairlines, label over value: what real product screens\n// do, instead of four cards each with an icon in a tinted circle. There is deliberately no `icon`,\n// `sparkline` or `trend` prop. A change is written in words with its window (\"4 more than last\n// Thursday\"), because a green \"+12.5%\" pill says neither what changed nor since when, and the trend\n// gets its own chart.\n\n/** Headline figures as one description list split by hairlines. Holds `Metric`s. */\nexport function MetricStrip({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <dl\n aria-label={label}\n className={cn(\n \"grid grid-cols-1 border-y border-border sm:auto-cols-fr sm:grid-flow-col sm:divide-x sm:divide-border\",\n className,\n )}\n >\n {children}\n </dl>\n );\n}\n\nexport type MetricProps = {\n label: string;\n /** Already formatted. Ink colour, 28px, tabular figures: never the brand colour, never 48px. */\n value: string;\n unit?: string;\n /** One sentence: the change in words with its window, or what the figure means right now. */\n note?: React.ReactNode;\n};\n\n/** One figure: label over value, an optional muted unit and a note that states any change in words with its window. */\nexport function Metric({ label, value, unit, note }: MetricProps) {\n return (\n <div className=\"grid content-start gap-0.5 border-border py-3 not-first:border-t sm:px-5 sm:not-first:border-t-0 sm:first:pl-0\">\n <dt className=\"type-label text-muted-foreground\">{label}</dt>\n <dd className=\"type-figure text-foreground\">\n {value}\n {unit && <span className=\"type-body text-muted-foreground\">{\" \" + unit}</span>}\n </dd>\n {note && <dd className=\"type-body-sm text-muted-foreground\">{note}</dd>}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Status } from \"./status\";\n\n// A usage bar: how full one thing is (a disk, a quota, a kiln's shelves), for status dashboards\n// that otherwise hand-roll a div with a width (strata-react issue #25, from jburnhams/homepage).\n// The rules it encodes, from ux-research ui-library/components.md §3.8 and patterns.md §5:\n// - It is a `meter`, not a `progressbar`: a progress bar is a task moving to done, a meter is a\n// level that can go up or down. Its accessible name is what is measured (\"Disk /\") and its\n// value text says the reading in words (\"72% used\"), so a screen reader hears \"Disk /, meter,\n// 72% used\" rather than a bare 72.\n// - The figure is always printed beside the bar. A bar alone is read to ±10% at best.\n// - Thresholds are what the person compares against, so they are drawn on the track as notches,\n// like LineChart's `band`. Each threshold must name its state (\"Filling up\", \"Nearly full\"):\n// when the reading crosses one, the fill takes the status ink and the word is shown as a\n// `Status`, so colour is never the only cue. Thresholds are shares of `max` (0.8 is 80%),\n// because a dashboard of disks of different sizes shares one set of them.\n// - `worseWhen=\"lower\"` turns the thresholds round for levels where empty is the problem (a\n// battery, credit left): a threshold then applies at or below its share.\n// - Below every threshold the fill is one chart hue (`--chart-1` unless `colour` says otherwise),\n// the same default as LineChart, never the brand accent and never a status colour, since\n// \"fine\" needs no colour of its own.\n// - `hideLabel` is for a meter in a table row, where the row already says what it measures; the\n// label stays as the meter's accessible name.\n// - No animation on the fill: a dashboard re-renders readings, and a bar that slides on each one\n// draws the eye to nothing.\n\n/** A level on a `Meter` at which the reading changes state, with the word for that state. */\nexport type MeterThreshold = {\n /** A share of `max`, from 0 to 1: 0.8 is 80%. */\n at: number;\n tone: \"warning\" | \"danger\";\n /** What the state is called, in the product's words: \"Filling up\", \"Nearly full\". */\n label: string;\n};\n\nexport type MeterProps = {\n /** What is measured, such as \"Disk /\". The meter's accessible name. */\n label: string;\n value: number;\n /** The full scale, in the same units as `value`. Defaults to 1, so a share can be passed as is. */\n max?: number;\n /** The reading in words, shown beside the bar and used as `aria-valuetext`. Defaults to \"72% used\". */\n valueText?: string;\n /** A second line of fact, such as \"36 of 50 GB\". */\n detail?: React.ReactNode;\n thresholds?: MeterThreshold[];\n /** \"lower\" when an emptier reading is the worse one (a battery, credit left). */\n worseWhen?: \"higher\" | \"lower\";\n /** Keeps the label as the accessible name only, for a meter in a table row that names it. */\n hideLabel?: boolean;\n /** CSS colour for the fill below every threshold. Defaults to the first chart token. */\n colour?: string;\n className?: string;\n};\n\n/** The threshold a share has crossed, if any: the most severe one reached in the worse direction. */\nexport function crossedThreshold(\n share: number,\n thresholds: readonly MeterThreshold[] = [],\n worseWhen: \"higher\" | \"lower\" = \"higher\",\n): MeterThreshold | undefined {\n const reached = thresholds.filter((t) => (worseWhen === \"higher\" ? share >= t.at : share <= t.at));\n // The one furthest in the worse direction wins, so danger beats warning when both are reached.\n return reached.sort((a, b) => (worseWhen === \"higher\" ? b.at - a.at : a.at - b.at))[0];\n}\n\nconst fills = { warning: \"var(--warning)\", danger: \"var(--danger)\" } as const;\n\n/** How full one thing is: a labelled `meter` with its reading in words, threshold notches, and a status word once a threshold is crossed. */\nexport function Meter({\n label,\n value,\n max = 1,\n valueText,\n detail,\n thresholds,\n worseWhen = \"higher\",\n hideLabel = false,\n colour = \"var(--chart-1)\",\n className,\n}: MeterProps) {\n const labelId = React.useId();\n const statusId = React.useId();\n const detailId = React.useId();\n const share = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;\n const crossed = crossedThreshold(share, thresholds, worseWhen);\n // `share`, not `percent`: a disk with a little on it reads \"<1% used\", never \"0% used\".\n const text = valueText ?? `${format.share(share)} used`;\n const hasNote = Boolean(crossed || detail);\n // Two ids rather than one wrapper, so the description reads \"Nearly full, 431 GB of 466 GB\"\n // with a break between the parts instead of running them together.\n const describedBy = [crossed && statusId, detail && detailId].filter(Boolean).join(\" \") || undefined;\n\n const bar = (\n <div\n role=\"meter\"\n aria-labelledby={hideLabel ? undefined : labelId}\n aria-label={hideLabel ? label : undefined}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-valuenow={Math.min(max, Math.max(0, value))}\n aria-valuetext={text}\n aria-describedby={describedBy}\n className=\"relative h-2 min-w-16 flex-1 overflow-hidden rounded-pill bg-muted\"\n >\n <div\n className=\"absolute inset-y-0 left-0\"\n style={{ width: `${share * 100}%`, background: crossed ? fills[crossed.tone] : colour }}\n />\n {/* Notches in the ground colour: the levels the reading is judged against. */}\n {thresholds?.map((t) => (\n <div\n key={t.at}\n className=\"absolute inset-y-0 w-0.5 -translate-x-1/2 bg-background\"\n style={{ left: `${Math.min(1, Math.max(0, t.at)) * 100}%` }}\n />\n ))}\n </div>\n );\n\n // The visible figure is the meter's value text, so it is hidden from the accessibility tree\n // rather than read twice.\n const figure = (\n <span aria-hidden className=\"shrink-0 type-body-sm tabular-nums text-foreground\">\n {text}\n </span>\n );\n\n const note = hasNote && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n {crossed && (\n <span id={statusId} className=\"contents\">\n <Status tone={crossed.tone}>{crossed.label}</Status>\n </span>\n )}\n {detail && (\n <span id={detailId} className=\"type-body-sm text-muted-foreground tabular-nums\">\n {detail}\n </span>\n )}\n </div>\n );\n\n if (hideLabel) {\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-3\">\n {bar}\n {figure}\n </div>\n {note}\n </div>\n );\n }\n\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-baseline justify-between gap-3\">\n <span id={labelId} className=\"min-w-0 truncate type-label text-foreground\">\n {label}\n </span>\n {figure}\n </div>\n <div className=\"flex\">{bar}</div>\n {note}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// What a whole is made of (memory: used, cached, buffers, free; a kiln load: bisque, glaze, empty\n// shelves), as one stacked bar over a table. strata-react issue #25 asked for it after\n// jburnhams/homepage hand-rolled one. The rules, from ux-research ui-library/components.md §3.8\n// and patterns.md §5:\n// - Colour is never the only cue. The bar shows proportion at a glance; the table under it says\n// every part's name, amount and share in words, with a swatch that ties the row to its\n// segment. The bar is hidden from screen readers because the table already carries all of it.\n// - The parts stay in the order given, in the bar and the table, so the order is the caller's\n// meaning (used before cached before free), not sorted by size.\n// - Categorical colours come from `--chart-1…5` in order, which palette.mjs checks are told apart\n// by colour-blind readers. A sixth part has no token to take, so it must bring its own colour;\n// more than five parts usually means the small ones belong in an \"Other\" part.\n// - Segments are split by a 2px gap in the ground colour, so two neighbours of similar lightness\n// still read as two.\n// - When the parts do not fill the whole (`total` is larger than their sum), the remainder is the\n// empty track, and it must be named (`restLabel`, such as \"Free\"), so the table can say what the\n// gap is. Neither the remainder nor a part is ever left unlabelled.\n// - Values are formatted by the caller (`formatValue`), as LineChart's `formatY` is, so units stay\n// the product's; shares go through `format.share` unless `formatShare` says otherwise.\n// - A part that is there is never shown as nothing (strata-react issue #43: 2.4 GB of a 512 GB\n// disk read \"0%\"). Its share prints \"<1%\" (`format.share`), and its segment keeps a 4px sliver\n// however small it is; the table carries the exact figure.\n\n/** One part of a `CompositionBar`'s whole. */\nexport type CompositionPart = {\n /** Stable key for the part. */\n key: string;\n label: string;\n value: number;\n /** CSS colour for the segment and swatch. Defaults to the chart token for its position. */\n colour?: string;\n};\n\nexport type CompositionBarProps = {\n /** What the whole is, such as \"Memory\". Shown above the bar and names the table. */\n label: string;\n parts: CompositionPart[];\n formatValue: (value: number) => string;\n /** Formats a part's share of the whole (0 to 1). Defaults to `format.share` (\"<1%\" for a part that rounds to 0). */\n formatShare?: (share: number) => string;\n /** Header of the parts column, for screen readers and over the table. Defaults to \"Part\". */\n partHeader?: string;\n /** Header of the amounts column. Defaults to \"Amount\". */\n valueHeader?: string;\n /** Header of the shares column. Defaults to \"Share\". */\n shareHeader?: string;\n className?: string;\n} & (\n | {\n /** The size of the whole, when the parts do not fill it. The remainder is the empty track. */\n total: number;\n /** What the remainder is called (\"Free\", \"Empty shelves\"). Required with `total`. */\n restLabel: string;\n }\n | { total?: undefined; restLabel?: undefined }\n);\n\nconst MAX_TOKENS = 5;\n\n/** A part's colour: its own, or the chart token for its position. Throws past the fifth token. */\nfunction colourFor(part: CompositionPart, index: number) {\n if (part.colour) return part.colour;\n if (index >= MAX_TOKENS) {\n throw new Error(\n `CompositionBar: part \"${part.label}\" is number ${index + 1}, and there are only ${MAX_TOKENS} chart colours. ` +\n `Combine the smallest parts into one \"Other\" part, or give this part a colour.`,\n );\n }\n return `var(--chart-${index + 1})`;\n}\n\n/** What a whole is made of: a stacked bar for proportion and a table that names every part, its amount and its share, so colour is never the only cue. */\nexport function CompositionBar({\n label,\n parts,\n formatValue,\n formatShare = format.share,\n partHeader = \"Part\",\n valueHeader = \"Amount\",\n shareHeader = \"Share\",\n className,\n ...whole\n}: CompositionBarProps) {\n const captionId = React.useId();\n const sum = parts.reduce((n, p) => n + Math.max(0, p.value), 0);\n const total = Math.max(whole.total ?? sum, sum);\n const rest = whole.total !== undefined ? total - sum : 0;\n const shareOf = (value: number) => (total > 0 ? Math.max(0, value) / total : 0);\n const rows = parts.map((p, i) => ({ ...p, colour: colourFor(p, i), share: shareOf(p.value) }));\n\n return (\n <figure className={cn(\"grid min-w-0 gap-3\", className)}>\n <figcaption id={captionId} className=\"type-label text-foreground\">\n {label}\n </figcaption>\n <div aria-hidden className=\"flex h-3 gap-0.5 overflow-hidden rounded-pill bg-muted\">\n {rows\n .filter((r) => r.value > 0)\n .map((r) => (\n // Grow by share from a zero basis, so the gaps come out of every segment fairly and the\n // parts fill the track exactly. Shares, not raw values: flex-grow factors that sum to\n // less than 1 fill only that fraction of the track (found in review).\n <div key={r.key} className=\"h-full min-w-1\" style={{ flex: `${r.share} 1 0`, background: r.colour }} />\n ))}\n {rest > 0 && <div className=\"h-full min-w-0\" style={{ flex: `${shareOf(rest)} 1 0` }} />}\n </div>\n <table aria-labelledby={captionId} className=\"w-full border-collapse type-body-sm\">\n <thead className=\"sr-only\">\n <tr>\n <th scope=\"col\">{partHeader}</th>\n <th scope=\"col\">{valueHeader}</th>\n <th scope=\"col\">{shareHeader}</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => (\n <tr key={r.key} className=\"border-t border-border first:border-t-0\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n <span aria-hidden className=\"size-3 shrink-0 rounded-control\" style={{ background: r.colour }} />\n {r.label}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(r.value)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(r.share)}\n </td>\n </tr>\n ))}\n {whole.total !== undefined && (\n <tr className=\"border-t border-border\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n {/* The empty track's colour with a hairline, so the swatch reads as \"nothing here\". */}\n <span aria-hidden className=\"size-3 shrink-0 rounded-control border border-border bg-muted\" />\n {whole.restLabel}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(rest)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(shareOf(rest))}\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </figure>\n );\n}\n","import * as React from \"react\";\nimport { Link, type To } from \"react-router\";\nimport { ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A card that is a way to somewhere: an app on a homepage, a project in a list of projects.\n// strata-react issue #25 asked for it after jburnhams/homepage built `AppCard` by hand. A card is\n// right here because each destination *is* a separate object a person picks (ux-research\n// ui-library/patterns.md §3); a section of a screen is not, and gets space and hairlines instead.\n// - The whole card is the target, but it is one link with a short name. The link sits on the\n// title and its `::after` covers the card, so a pointer can press anywhere while a screen reader\n// hears \"Kiln log, link\" and then the description and status marks as its description, instead\n// of a link named with every word on the card. There is one tab stop per card.\n// - Because the whole card is one link, nothing else on it can be interactive (a button or a\n// second link inside a link is invalid and unreachable). `marks` is for `Status` words only.\n// - Status marks are words (`Status`), never a coloured dot in a corner.\n// - `to` is a route in this app (React Router's `Link`); `href` leaves it (a plain anchor) and is\n// marked with an arrow, so a person knows before pressing that they will leave.\n// - Hover and focus change the border and draw the ring around the card, not the title. There is\n// no lift, scale or shadow: elevation is for what floats above the page, and a card on a\n// homepage is pressed many times a day (ux-research ux-character.md, character by frequency).\n\n/** A destination card's props: `to` for a route in this app, or `href` for anywhere else, never both. */\nexport type LinkCardProps = (\n | {\n /** A route in this app, followed with React Router. */\n to: To;\n href?: undefined;\n }\n | {\n /** Somewhere outside this app; the card shows an arrow. */\n href: string;\n to?: undefined;\n }\n) & {\n /** The destination's name, and the link's accessible name. */\n title: string;\n /** One sentence on what is there. Read as the link's description. */\n description?: string;\n /** `Status` words about the destination (\"Running\", \"Updated today\"). Nothing interactive. */\n marks?: React.ReactNode;\n /** The title's element. h3 under a section heading; h2 when the cards are the page's sections. */\n as?: \"h2\" | \"h3\" | \"h4\";\n className?: string;\n};\n\n/** A destination as a card that is one link: its title is the link's name, the description and status marks are its description, and the whole card is the target. */\nexport function LinkCard({ title, description, marks, as: Heading = \"h3\", className, ...destination }: LinkCardProps) {\n const descriptionId = React.useId();\n const marksId = React.useId();\n const describedBy = [description && descriptionId, marks && marksId].filter(Boolean).join(\" \") || undefined;\n const linkClass =\n \"rounded-control outline-none after:absolute after:inset-0 after:rounded-surface\";\n\n return (\n <div\n className={cn(\n \"relative grid content-start gap-1.5 rounded-surface border border-border bg-background p-4 transition-state\",\n \"hover:border-muted-foreground has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring\",\n className,\n )}\n >\n <Heading className=\"flex items-start justify-between gap-3 type-heading text-foreground\">\n {destination.href !== undefined ? (\n <>\n <a href={destination.href} aria-describedby={describedBy} className={linkClass}>\n {title}\n </a>\n <ArrowUpRight aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n </>\n ) : (\n <Link to={destination.to} aria-describedby={describedBy} className={linkClass}>\n {title}\n </Link>\n )}\n </Heading>\n {description && (\n <p id={descriptionId} className=\"type-body-sm text-pretty text-muted-foreground\">\n {description}\n </p>\n )}\n {marks && (\n <div id={marksId} className=\"mt-1.5 flex flex-wrap gap-2\">\n {marks}\n </div>\n )}\n </div>\n );\n}\n\n/** A labelled list of `LinkCard`s in a grid: one column on a phone, up to three on a wide screen. */\nexport function LinkCardList({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <ul aria-label={label} className={cn(\"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3\", className)}>\n {React.Children.toArray(children).map((child, i) => (\n <li key={React.isValidElement(child) && child.key != null ? child.key : i} className=\"grid\">\n {child}\n </li>\n ))}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, History, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// Every view of remote data goes through DataView, and DataView will not type-check without a\n// skeleton and an empty state. Generated UI renders the happy path; this makes the other three\n// states part of the component's signature rather than a review comment.\n//\n// A failed refresh is not a failed read (strata-react issue #26). Once data has arrived, a later\n// refetch that fails (a poll while the server restarts, a Try again on a flaky link) leaves the\n// data on screen with `stale` set: a polite notice above it says what happened, when the data\n// shown was read, and offers Try again. Swapping a whole dashboard for an error panel throws away\n// readings the person was using, and a silent failure lets them act on old numbers as if live, so\n// the data stays and its age is said in words. Only a read that never produced data is an error.\n//\n// The failed read's look is replaceable (strata-react issue #50): an app with a second look (the\n// Tubes viewer, with its own tokens and pill buttons) passes `error`, a render function given the\n// message and the retry, and keeps the state machine (loading, error, ready, stale, empty) rather\n// than copying DataView to change one panel. Whatever it draws sits inside a `role=\"alert\"` box,\n// so the failure is still announced; the default is `LoadError`, exported for reuse.\n\n/** Data still shown after a refresh failed: why the refresh failed, when the data was read, and the Try again. */\nexport type Stale = {\n /** Why the refresh failed, for a person: the sentence an error panel would have shown. */\n message: string;\n /** When the data on screen was read. */\n readAt: Date;\n /** Fetch again. */\n retry: () => void;\n /** A fetch is on its way (a Try again or the next poll). */\n retrying?: boolean;\n};\n\n/** The state of one remote read, for `DataView`: loading, failed with no data, or ready (and `stale` when a later refresh failed). */\nexport type Load<T> =\n | { status: \"loading\" }\n | { status: \"error\"; message: string; retry: () => void }\n | { status: \"ready\"; data: T; stale?: Stale };\n\n/** What a failed read hands to an `error` renderer: the sentence for a person, and the Try again. */\nexport type LoadFailure = { message: string; retry: () => void };\n\n/** The default failed-read panel: the reason on the danger tint, with Try again. Its parent carries `role=\"alert\"`. */\nexport function LoadError({ message, retry, className }: LoadFailure & { className?: string }) {\n return (\n <div className={cn(\"flex flex-wrap items-start gap-3 rounded-surface bg-danger-subtle p-4 text-danger\", className)}>\n <CircleAlert aria-hidden className=\"mt-0.5 size-5 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultError = (failure: LoadFailure) => <LoadError {...failure} />;\n\n/** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */\nexport function DataView<T>({\n state,\n isEmpty,\n skeleton,\n empty,\n children,\n staleNotice = (stale) => <StaleNotice stale={stale} />,\n error = defaultError,\n className,\n}: {\n state: Load<T>;\n /** When the loaded data counts as empty. For arrays, `(rows) => rows.length === 0`. */\n isEmpty: (data: T) => boolean;\n /** Mirrors the final layout, so nothing jumps when data arrives. Not a centred spinner. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it. An `EmptyState`, not an illustration. */\n empty: React.ReactNode;\n children: (data: T) => React.ReactNode;\n /** Shown above the data when a refresh failed. Defaults to a `StaleNotice`; pass one with the product's words for what is old (\"Readings from 13:50\"). */\n staleNotice?: (stale: Stale) => React.ReactNode;\n /** Draws a read that failed with no data, given the message and the retry. Defaults to `LoadError`. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-w-0\", className)} aria-busy={state.status === \"loading\" || undefined}>\n {state.status === \"loading\" && skeleton}\n {state.status === \"error\" && <div role=\"alert\">{error({ message: state.message, retry: state.retry })}</div>}\n {state.status === \"ready\" && (\n <>\n {state.stale && staleNotice(state.stale)}\n {isEmpty(state.data) ? empty : children(state.data)}\n </>\n )}\n </div>\n );\n}\n\n/** When `readAt` was, for a person: the clock time today, else the weekday and time. */\nfunction readTime(readAt: Date, now = new Date()) {\n return readAt.toDateString() === now.toDateString() ? format.clock.format(readAt) : format.shortDay.format(readAt);\n}\n\n/** The notice over data whose refresh failed: what happened, how old the data shown is, and Try again. A polite status, not an alert: nothing was lost. */\nexport function StaleNotice({\n stale,\n shown,\n className,\n}: {\n stale: Stale;\n /** What is old, in the product's words, given when it was read (\"13:50\", or \"Sat 13:50\" before today). Defaults to \"Showing data from 13:50.\" */\n shown?: (when: string) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div role=\"status\" className={cn(\"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\", className)}>\n <History aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">\n {stale.message} {shown ? shown(readTime(stale.readAt)) : `Showing data from ${readTime(stale.readAt)}.`}\n </p>\n <Button size=\"sm\" onClick={stale.retry} disabled={stale.retrying}>\n <RotateCcw aria-hidden />\n {stale.retrying ? \"Trying again…\" : \"Try again\"}\n </Button>\n </div>\n );\n}\n\n// An empty state teaches the next action. No illustration slot exists, on purpose.\n/** An empty state that teaches the next action: a title, a sentence and an action. No illustration slot, on purpose. */\nexport function EmptyState({ title, children, action }: { title: string; children?: React.ReactNode; action?: React.ReactNode }) {\n return (\n <div className=\"grid justify-items-start gap-2 border-y border-border py-6\">\n <p className=\"type-heading\">{title}</p>\n {children && <p className=\"max-w-prose type-body text-muted-foreground\">{children}</p>}\n {action && <div className=\"mt-2\">{action}</div>}\n </div>\n );\n}\n\n/** A placeholder block for a loading layout. Size it with layout classes so it mirrors the final content. */\nexport function Skeleton({ className }: { className?: string }) {\n return <div aria-hidden className={cn(\"rounded-control bg-muted motion-safe:animate-pulse\", className)} />;\n}\n","// Colour rules for `ColorField` (issue #73): reading a typed hex, and the WCAG contrast ratio\n// against what the colour is drawn on, which a user-chosen colour (content, not theme) is checked\n// with. Number parsing and stepping are React Aria's.\n\n/** Reads `#rgb`, `#rrggbb` (with or without the #) as lower-case `#rrggbb`, or null. */\nexport function parseHex(text: string): string | null {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());\n if (!m) return null;\n const h = m[1].toLowerCase();\n return \"#\" + (h.length === 3 ? [...h].map((c) => c + c).join(\"\") : h);\n}\n\nfunction luminance(hex: string): number {\n const v = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));\n return 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];\n}\n\n/** WCAG contrast ratio between two `#rrggbb` colours, 1 to 21. */\nexport function contrastRatio(a: string, b: string): number {\n const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);\n return (hi + 0.05) / (lo + 0.05);\n}\n","import * as React from \"react\";\nimport {\n I18nProvider,\n Input as AriaInput,\n NumberField as AriaNumberField,\n Slider as AriaSlider,\n SliderOutput,\n SliderThumb,\n SliderTrack,\n} from \"react-aria-components\";\nimport { useFieldControl } from \"./field\";\nimport { NBSP, format } from \"../lib/format\";\nimport { contrastRatio, parseHex } from \"../lib/number-input\";\nimport { cn } from \"../lib/utils\";\nimport { controlHeight, type ControlSize } from \"../lib/control\";\n\n// Controls for setting a number or a colour precisely (strata-react issue #73, from moving\n// strata-vid onto Strata: opacity, rotation, volume, bitrate, a line colour). The native ones fail\n// in the same few ways, and each rule below answers one:\n//\n// - `parseFloat(e.target.value)` turns an empty field into NaN. Here a value that is not known is\n// `null`, stays `null`, and prints `format.missing`; a typed value outside the limits is NOT\n// clamped and NOT passed on: React Aria's field runs with `commitBehavior=\"validate\"` (it keeps\n// what was typed instead of snapping 600 to 500), and the control tells the surrounding `Field`\n// what is wrong (\"Enter a value from 0% to 500%.\"), the same place a server's 422 appears. The\n// callback only ever receives a number inside the limits, or null.\n// - The unit lives inside the control, muted. A slider's spoken value carries it (\"40%\", \"90°\")\n// when `Intl` knows the unit (percent, degree, millisecond, megabit-per-second and the like):\n// React Aria builds `aria-valuetext` from an `Intl.NumberFormat`, so \"px\" or \"steps\" are in the\n// printed value and the label but cannot be in the spoken one.\n// - Digits are the locale's: what is printed and what is read back go through `Intl` (React Aria's\n// `NumberParser`), so 12,5 works in a de-DE app, and the message is in the same digits.\n// - Behaviour is React Aria's: arrows step, PageUp/PageDown take ten steps, Home/End jump to the\n// limits, a field commits on Enter and blur. Nothing animates when a value changes: these are\n// dragged and stepped dozens of times a minute (character.md, the frequency budget).\n// - A colour a person picks for their own content (a route's line) is content, not theme, so it is\n// the one place a raw colour value is right; `against` checks it against what it is drawn on.\n// The colour field's text box is ours: React Aria's colour field puts the old colour back when\n// the text is not a colour, where this one says so under the control; the swatch opens the\n// platform picker.\n\nconst box =\n \"flex w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring\";\n\n/** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */\nfunction withUnit(text: string, unit?: string) {\n if (!unit) return text;\n return unit === \"%\" || unit === \"°\" ? text + unit : text + NBSP + unit;\n}\n\n// Units `Intl` can speak, by the symbol an app prints. Anything else is printed but not spoken.\nconst intlUnits: Record<string, string> = {\n \"%\": \"percent\",\n \"°\": \"degree\",\n ms: \"millisecond\",\n s: \"second\",\n kB: \"kilobyte\",\n MB: \"megabyte\",\n GB: \"gigabyte\",\n kbps: \"kilobit-per-second\",\n Mbps: \"megabit-per-second\",\n};\n\nfunction decimalsOf(n: number): number {\n const s = String(n);\n if (s.includes(\"e-\")) return Number(s.split(\"e-\")[1]) + (s.split(\"e-\")[0].split(\".\")[1]?.length ?? 0);\n return s.split(\".\")[1]?.length ?? 0;\n}\n\nfunction useNumberText(locale: string, places: number) {\n return React.useMemo(() => {\n const f = new Intl.NumberFormat(locale, { maximumFractionDigits: places, minimumFractionDigits: 0 });\n return (n: number) => f.format(n);\n }, [locale, places]);\n}\n\nfunction formatOptionsFor(places: number, unit?: string): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = { maximumFractionDigits: places, minimumFractionDigits: 0 };\n const known = unit ? intlUnits[unit] : undefined;\n return known ? { ...base, style: \"unit\", unit: known, unitDisplay: \"narrow\" } : base;\n}\n\n/** Props shared by the number field and the slider. */\nexport type RangeProps = {\n min?: number;\n max?: number;\n /** The size of one arrow-key step. Default 1. */\n step?: number;\n /** The unit shown with the value: \"%\", \"°\", \"Mbps\", \"px\". Spoken too when `Intl` has it (%, °, ms, s, kB, MB, GB, kbps, Mbps). */\n unit?: string;\n /** The locale for digits and the decimal mark. Default the app's `format` locale. */\n locale?: string;\n};\n\n/** Props for `NumberField`. */\nexport type NumberFieldProps = RangeProps & {\n /** The current value; `null` when it is not known (shown as an en dash, not 0). */\n value: number | null;\n /** Receives a number inside the limits, or `null` when the field is cleared. Never NaN, never out of range. */\n onChange: (value: number | null) => void;\n /** Decimal places to show and keep. Default the places in `step` (and `min`). */\n places?: number;\n /** An empty field is an error (\"Enter a value.\") rather than `null`. */\n required?: boolean;\n disabled?: boolean;\n /** Names the control when it is used without a `Field`. */\n \"aria-label\"?: string;\n id?: string;\n name?: string;\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `IconButton` beside it. Default --control-h. */\n size?: ControlSize;\n className?: string;\n};\n\nfunction describeRange(min: number | undefined, max: number | undefined, show: (n: number) => string, unit?: string) {\n const a = min === undefined ? \"\" : withUnit(show(min), unit);\n const b = max === undefined ? \"\" : withUnit(show(max), unit);\n if (min !== undefined && max !== undefined) return `Enter a value from ${a} to ${b}.`;\n if (min !== undefined) return `Enter ${a} or more.`;\n if (max !== undefined) return `Enter ${b} or less.`;\n return \"Enter a number.\";\n}\n\n/** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */\nexport function NumberField({\n value,\n onChange,\n min,\n max,\n step = 1,\n places,\n unit,\n locale = format.locale,\n required = false,\n disabled,\n id: idProp,\n name,\n size = \"default\",\n className,\n \"aria-label\": ariaLabel,\n}: NumberFieldProps) {\n const { field, report } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), min === undefined ? 0 : decimalsOf(min));\n const show = useNumberText(locale, digits);\n const [own, setOwn] = React.useState(false); // invalid, when there is no Field to say so\n const unitId = React.useId();\n // What the field shows. It follows `value`, but also holds an entry we refused, so the person sees\n // (and can correct) what they typed instead of the field snapping back to the old value.\n const [local, setLocal] = React.useState<number>(value ?? Number.NaN);\n const [seen, setSeen] = React.useState(value);\n if (seen !== value) {\n setSeen(value);\n setLocal(value ?? Number.NaN);\n }\n\n const fail = (message: string) => {\n setOwn(true);\n report(message);\n };\n const ok = () => {\n setOwn(false);\n report(undefined);\n };\n\n const handle = (n: number) => {\n setLocal(n);\n if (Number.isNaN(n)) {\n if (required) return fail(\"Enter a value.\");\n ok();\n if (value !== null) onChange(null);\n return;\n }\n if ((min !== undefined && n < min) || (max !== undefined && n > max)) return fail(describeRange(min, max, show, unit));\n ok();\n if (n !== value) onChange(n);\n };\n\n const invalid = field?.invalid || own;\n return (\n <I18nProvider locale={locale}>\n <AriaNumberField\n value={local}\n onChange={handle}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={{ maximumFractionDigits: digits, minimumFractionDigits: 0 }}\n commitBehavior=\"validate\"\n isDisabled={disabled}\n isInvalid={invalid || undefined}\n name={name}\n aria-label={ariaLabel ?? field?.label}\n className={cn(box, controlHeight[size], className)}\n >\n <AriaInput\n id={idProp ?? field?.id}\n placeholder={format.missing}\n aria-describedby={[field?.describedBy, unit ? unitId : undefined].filter(Boolean).join(\" \") || undefined}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n {unit && (\n <span id={unitId} className=\"ml-2 shrink-0 type-body-sm text-muted-foreground\">\n <span aria-hidden>{unit}</span>\n <span className=\"sr-only\">{intlUnits[unit] ? intlUnits[unit].replace(/-/g, \" \") : unit}</span>\n </span>\n )}\n </AriaNumberField>\n </I18nProvider>\n );\n}\n\n/** Props for `Slider`. */\nexport type SliderProps = RangeProps & {\n value: number;\n onChange: (value: number) => void;\n /** Both limits are required: a slider with no ends is not a slider. */\n min: number;\n max: number;\n /** Replace the printed value with a `NumberField` beside the track, so an exact value can be typed. */\n editable?: boolean;\n /** Hide the printed value (when something else beside it already shows it). */\n hideValue?: boolean;\n /** Decimal places in the printed and spoken value. Default the places in `step`. */\n places?: number;\n disabled?: boolean;\n /** Names the slider when it is used without a `Field`. */\n \"aria-label\"?: string;\n className?: string;\n};\n\n/** A slider on React Aria with its current value always printed beside the track (and spoken with the unit when `Intl` knows it); `editable` adds a number field to type an exact value. */\nexport function Slider({\n value,\n onChange,\n min,\n max,\n step = 1,\n unit,\n locale = format.locale,\n editable = false,\n hideValue = false,\n places,\n disabled,\n className,\n \"aria-label\": ariaLabel,\n}: SliderProps) {\n const { field } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), decimalsOf(min));\n const show = useNumberText(locale, digits);\n const name = ariaLabel ?? field?.label ?? \"Value\";\n const text = withUnit(show(value), unit);\n return (\n <I18nProvider locale={locale}>\n <AriaSlider\n value={value}\n onChange={(v) => onChange(v as number)}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={formatOptionsFor(digits, unit)}\n isDisabled={disabled}\n aria-label={name}\n aria-describedby={field?.describedBy}\n className={cn(\"flex min-w-0 items-center gap-3\", className)}\n >\n <SliderTrack className=\"relative flex h-(--control-h) min-w-0 flex-1 cursor-pointer items-center disabled:cursor-not-allowed disabled:opacity-50\">\n {({ state }) => (\n <>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${state.getThumbPercent(0) * 100}%` }} />\n <SliderThumb className=\"top-1/2 size-5 rounded-pill border-2 border-primary bg-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\" />\n </>\n )}\n </SliderTrack>\n {editable ? (\n <NumberField className=\"w-28 shrink-0\" aria-label={`${name}, exact value`} value={value} onChange={(v) => v !== null && onChange(v)} min={min} max={max} step={step} unit={unit} locale={locale} places={digits} required disabled={disabled} />\n ) : (\n !hideValue && (\n <SliderOutput aria-hidden className=\"w-16 shrink-0 text-right type-body-sm tabular-nums text-foreground\">\n {text}\n </SliderOutput>\n )\n )}\n </AriaSlider>\n </I18nProvider>\n );\n}\n\n/** Props for `ColorField`. */\nexport type ColorFieldProps = {\n /** `#rrggbb`, or `null` when no colour is set. */\n value: string | null;\n /** Receives a valid `#rrggbb` (lower case) or `null` when cleared; never a half-typed value. */\n onChange: (value: string | null) => void;\n /** A short list the app suggests, as `#rrggbb`. Pressing one chooses it. */\n suggestions?: readonly string[];\n /** The colour this will be drawn on, `#rrggbb`: a note appears when the contrast would be low. */\n against?: string;\n /** What it is drawn on, in words: \"the map\". Completes the note. */\n againstLabel?: string;\n /** The lowest contrast ratio accepted before the note shows. Default 3, the WCAG minimum for graphics. */\n minContrast?: number;\n disabled?: boolean;\n \"aria-label\"?: string;\n id?: string;\n className?: string;\n};\n\n/** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */\nexport function ColorField({ value, onChange, suggestions, against, againstLabel = \"the background\", minContrast = 3, disabled, id: idProp, className, \"aria-label\": ariaLabel }: ColorFieldProps) {\n const { field, report } = useFieldControl();\n // Named for the `aria-label` or, failing that, the surrounding Field's label, so two colour fields in one panel never share a name (issue #116).\n const label = ariaLabel ?? field?.label;\n const pickerName = label ? `${label}, picker` : \"Colour picker\";\n const [draft, setDraft] = React.useState<string | null>(null);\n const [own, setOwn] = React.useState(false);\n const text = draft ?? value ?? \"\";\n const ratio = value && against ? contrastRatio(value, against) : null;\n\n const commitText = (t: string): boolean => {\n if (t.trim() === \"\") {\n setOwn(false);\n report(undefined);\n if (value !== null) onChange(null);\n return true;\n }\n const hex = parseHex(t);\n if (!hex) {\n setOwn(true);\n report(\"Enter a colour like #1a7f64.\");\n return false;\n }\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n return true;\n };\n\n const pick = (hex: string) => {\n setDraft(null);\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n };\n\n const invalid = field?.invalid || own;\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div className={cn(box, controlHeight.default, \"gap-2 px-2\")} aria-invalid={invalid || undefined}>\n <span className=\"relative size-6 shrink-0 overflow-hidden rounded-control border border-input\">\n {/* The swatch is the chosen colour itself: user content, not a theme role. */}\n <span aria-hidden className={cn(\"absolute inset-0\", value === null && \"bg-muted\")} style={value ? { background: value } : undefined} />\n <input\n type=\"color\"\n aria-label={pickerName}\n value={value ?? \"#000000\"}\n disabled={disabled}\n onChange={(e) => pick(e.target.value)}\n className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n />\n </span>\n <input\n id={idProp ?? field?.id}\n type=\"text\"\n autoComplete=\"off\"\n spellCheck={false}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-describedby={field?.describedBy}\n aria-invalid={invalid || undefined}\n placeholder={format.missing}\n value={text}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n if (draft !== null && commitText(draft)) setDraft(null);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && draft !== null && commitText(draft)) setDraft(null);\n if (e.key === \"Escape\" && draft !== null) {\n setDraft(null);\n setOwn(false);\n report(undefined);\n }\n }}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n </div>\n {suggestions && suggestions.length > 0 && (\n <div role=\"group\" aria-label=\"Suggested colours\" className=\"flex flex-wrap gap-1.5\">\n {suggestions.map((hex) => (\n <button\n key={hex}\n type=\"button\"\n disabled={disabled}\n aria-label={hex}\n aria-pressed={value === hex}\n onClick={() => pick(hex)}\n className=\"size-6 cursor-pointer rounded-control border border-input transition-state aria-pressed:outline-2 aria-pressed:outline-offset-2 aria-pressed:outline-foreground disabled:cursor-not-allowed disabled:opacity-50\"\n style={{ background: hex }}\n />\n ))}\n </div>\n )}\n {ratio !== null && ratio < minContrast && (\n <p className=\"type-body-sm text-warning\">\n Hard to see on {againstLabel}: contrast {format.decimal(ratio)}:1, aim for {format.decimal(minContrast)}:1 or more.\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, Info, TriangleAlert } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { Tone } from \"./status\";\n\n// An alert is one inline sentence about a problem or a fact, where it applies: a failed export\n// under the export, a stale reading above the chart. It is how an error a person must act on is\n// shown, with its recovery as `action`; a toast is not (components.md §3.13, patterns.md §7).\n//\n// Drawn as a pale tint of its tone with its icon and, for `title`, a heavier first line: never a\n// coloured stripe down one side of a rounded box (the tell in ux-slop-taxonomy), and never colour\n// alone, since the icon and the words carry the tone. `role=\"alert\"` interrupts a screen reader,\n// so it is on only when the alert appears in response to something the person just did\n// (`announce`); a banner that is simply there on load is a plain region the reader finds in order.\n\n/** Props for `Alert`. */\nexport type AlertProps = {\n tone: Exclude<Tone, \"neutral\">;\n /** A short first line, when the sentence needs one: \"Export failed\". */\n title?: string;\n /** The sentence, in the product's words: what happened and what to do. */\n children: React.ReactNode;\n /** One recovery, a `Button` (\"Try again\"). */\n action?: React.ReactNode;\n /** It appeared because of something the person just did (a failed submit): announce it at once (`role=\"alert\"`). */\n announce?: boolean;\n className?: string;\n};\n\nconst tones: Record<Exclude<Tone, \"neutral\">, { box: string; icon: IconComponent }> = {\n info: { box: \"bg-info-subtle text-info\", icon: Info },\n success: { box: \"bg-success-subtle text-success\", icon: CircleCheck },\n warning: { box: \"bg-warning-subtle text-warning\", icon: TriangleAlert },\n danger: { box: \"bg-danger-subtle text-danger\", icon: CircleAlert },\n};\n\n/** An inline sentence about a problem or a fact, in a tone with an icon, with one optional action. `announce` makes it `role=\"alert\"` for a result of the person's own action. */\nexport function Alert({ tone, title, children, action, announce = false, className }: AlertProps) {\n const { box, icon: Icon } = tones[tone];\n return (\n <div role={announce ? \"alert\" : \"region\"} aria-label={announce ? undefined : title ?? \"Notice\"} className={cn(\"flex items-start gap-3 rounded-surface px-3 py-2.5\", box, className)}>\n <Icon aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <div className=\"grid min-w-0 flex-1 gap-0.5\">\n {title && <p className=\"type-label\">{title}</p>}\n <div className=\"type-body-sm\">{children}</div>\n </div>\n {action && <div className=\"shrink-0 self-center\">{action}</div>}\n </div>\n );\n}\n","import * as React from \"react\";\n\n// Work the browser does for a while (an export, an upload, a render) has the same shape as a\n// server job: it runs, reports how far it is, and ends finished, failed or cancelled (issue #72).\n// `useClientWork` holds that shape so a screen hands it straight to `JobStatus` and a toast,\n// instead of each screen keeping its own booleans. Cancelling aborts the `signal` the work was\n// given (pass it to `fetch`, or check it between steps) and ends as `cancelled`, never as a\n// failure: an abort is the person's decision, and its error is not reported. Starting again while\n// running is ignored, so a double click does not run the work twice. A stale run (cancelled, then\n// restarted) cannot write over the newer one.\n\n/** What the work is given: a signal that aborts on cancel, and a way to report progress. */\nexport type WorkContext = {\n signal: AbortSignal;\n /** Report items done, and the total when it is known. */\n progress: (current: number, total?: number) => void;\n};\n\n/** Where client work is. */\nexport type WorkPhase = \"idle\" | \"running\" | \"finished\" | \"failed\" | \"cancelled\";\n\n/** The state `useClientWork` returns. */\nexport type ClientWork<T> = {\n phase: WorkPhase;\n current?: number;\n total?: number;\n result?: T;\n error?: unknown;\n /** Runs the work. Ignored while it is already running. */\n start: () => Promise<void>;\n /** Aborts the work's signal; the phase becomes `cancelled`. */\n cancel: () => void;\n /** Back to `idle`, forgetting the result. */\n dismiss: () => void;\n};\n\ntype State<T> = { phase: WorkPhase; current?: number; total?: number; result?: T; error?: unknown };\n\n/** Runs browser-side work with progress, cancel and a clear end state, ready for `JobStatus`. */\nexport function useClientWork<T>(run: (ctx: WorkContext) => Promise<T>): ClientWork<T> {\n const [state, setState] = React.useState<State<T>>({ phase: \"idle\" });\n const controller = React.useRef<AbortController | null>(null);\n const runRef = React.useRef(run);\n runRef.current = run;\n\n const start = React.useCallback(async () => {\n if (controller.current) return;\n const mine = new AbortController();\n controller.current = mine;\n const live = () => controller.current === mine;\n setState({ phase: \"running\" });\n try {\n const result = await runRef.current({\n signal: mine.signal,\n progress: (current, total) => live() && setState((s) => ({ ...s, current, total: total ?? s.total })),\n });\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"finished\", result });\n } catch (error) {\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"failed\", error });\n } finally {\n if (live()) controller.current = null;\n }\n }, []);\n\n const cancel = React.useCallback(() => {\n const c = controller.current;\n if (!c) return;\n c.abort();\n controller.current = null;\n setState({ phase: \"cancelled\" });\n }, []);\n\n const dismiss = React.useCallback(() => {\n if (!controller.current) setState({ phase: \"idle\" });\n }, []);\n\n // Unmounting aborts the run and forgets it, so a remount (Strict Mode's setup, cleanup, setup) can\n // start again and the aborted run can no longer write state.\n React.useEffect(\n () => () => {\n controller.current?.abort();\n controller.current = null;\n },\n [],\n );\n\n return { ...state, start, cancel, dismiss };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle, TriangleAlert, Ban } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Status, type Tone } from \"./status\";\n\n// A job the server runs for a while (syncing sources one after another, an import, a re-index),\n// as the screen that started it shows it (strata-react issue #45, from the Tubes Library screen,\n// which built each part by hand). Three things are true of every such job, and the props make\n// each one impossible to leave out:\n//\n// - Its state is a word, as `Status` is: `words` names running, finished and failed in the\n// product's terms (\"Syncing\", \"Finished\", \"Finished with failures\"), all three required, so a\n// screen cannot forget the end it did not test. Beside the word, `summary` is the app's own\n// sentence (\"Syncing 2 of 3: Night Sky. 42 new videos so far.\").\n// - How far it has got is a bar only when the total is known (`current` of `total`), a\n// `progressbar`, not a `meter`: this is a task moving to done. Without a total there is no bar,\n// because a bar that guesses is worse than the sentence.\n// - When it ends, each item that failed is named with its reason (`failures`), because \"3\n// failed\" alone sends the person hunting. A job that failed as a whole (`failed`, the summary\n// saying why) names no item.\n//\n// It is announced, politely, only when something a person waits for happens: the item changes\n// (`current`) or the job ends. A poll every two seconds that rewrites \"42 new videos so far\" in\n// a live region would talk over everything else, so the visible sentence is not the live region;\n// a separate one carries the word and the sentence at those moments.\n//\n// Work the browser does (an export, an upload, a render; issue #72) uses the same component, so one\n// idea of \"a job\" covers both: `onCancel` shows a Cancel button while it runs (work the person can\n// stop is stoppable), `cancelled` is a fourth ending in neutral (\"Cancelled\": not a failure, nothing\n// to retry), and `onDismiss` shows Dismiss once it has ended so the result does not linger. With no\n// `total` there is no bar, only the turning mark and the sentence, which is the indeterminate case. The spinner turns only\n// while running, the one case where a status mark's data is live. Polling and re-reading what\n// the job changed is `useJob`'s.\n\n/** An item a job could not do, and why, in the product's words. */\nexport type JobFailure = { key: string; label: string; reason: string };\n\n/** A job's three states as words, all required: \"Syncing\", \"Finished\", \"Finished with failures\". */\nexport type JobWords = { running: string; finished: string; failed: string; /** Shown when `cancelled`. Default \"Cancelled\". */ cancelled?: string };\n\n/** The job status's props. */\nexport type JobStatusProps = {\n /** What the job is (\"Library sync\"): names the section and the progress bar. */\n label: string;\n /** The job is still going. */\n running: boolean;\n words: JobWords;\n /** The app's sentence for where the job is or how it went: \"Syncing 2 of 3: Night Sky.\" */\n summary: string;\n /** Items done or being done, with `total`, for the bar. */\n current?: number;\n /** Items in all, when known. No bar without it. */\n total?: number;\n /** Each item that failed, with its reason. Any failure makes a finished job `failed`'s word. */\n failures?: JobFailure[];\n /** The job failed as a whole, for a reason that names no item (the summary says it). */\n failed?: boolean;\n /** Names the list of failures for screen readers. Default \"Failures\". */\n failuresLabel?: string;\n /** The person stopped it. A neutral ending, not a failure. */\n cancelled?: boolean;\n /** Stops the job. Shows a Cancel button while it runs. */\n onCancel?: () => void;\n /** Label of the cancel button. Default \"Cancel\". */\n cancelLabel?: string;\n /** Clears the result. Shows a Dismiss button once the job has ended. */\n onDismiss?: () => void;\n className?: string;\n};\n\nconst Spinner: IconComponent = ({ className, ...props }) => (\n <LoaderCircle {...props} className={cn(className, \"motion-safe:animate-spin\")} />\n);\n\n/** A long-running server job: its state as a required word beside the app's sentence, a progress bar when the total is known, each failure named with its reason, and a polite announcement only when the item changes or the job ends. */\nexport function JobStatus({\n label,\n running,\n words,\n summary,\n current,\n total,\n failures = [],\n failed = false,\n failuresLabel = \"Failures\",\n cancelled = false,\n onCancel,\n cancelLabel = \"Cancel\",\n onDismiss,\n className,\n}: JobStatusProps) {\n const ended: { tone: Tone; icon: IconComponent; word: string } = cancelled\n ? { tone: \"neutral\", icon: Ban, word: words.cancelled ?? \"Cancelled\" }\n : failed\n ? { tone: \"danger\", icon: CircleAlert, word: words.failed }\n : failures.length\n ? { tone: \"warning\", icon: TriangleAlert, word: words.failed }\n : { tone: \"success\", icon: Check, word: words.finished };\n const { tone, icon, word } = running ? { tone: \"info\" as const, icon: Spinner, word: words.running } : ended;\n\n // What is announced changes only with the item or the end, not with every poll's sentence.\n const moment = running ? `running:${current ?? \"\"}` : `ended:${word}`;\n const [said, setSaid] = React.useState({ moment, text: \"\" });\n if (said.moment !== moment) setSaid({ moment, text: `${word}. ${summary}` });\n\n const bar = running && total !== undefined && total > 0 && current !== undefined;\n const done = Math.min(total ?? 0, Math.max(0, current ?? 0));\n\n return (\n <section aria-label={label} className={cn(\"grid min-w-0 gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <Status tone={tone} icon={icon}>\n {word}\n </Status>\n <p className=\"min-w-0 flex-1 type-body-sm text-foreground\">{summary}</p>\n {running && onCancel && (\n <Button size=\"sm\" onPress={onCancel}>\n {cancelLabel}\n </Button>\n )}\n {!running && onDismiss && (\n <Button size=\"sm\" variant=\"ghost\" onPress={onDismiss}>\n Dismiss\n </Button>\n )}\n </div>\n {bar && (\n <div\n role=\"progressbar\"\n aria-label={label}\n aria-valuemin={0}\n aria-valuemax={total}\n aria-valuenow={done}\n aria-valuetext={`${format.integer(done)} of ${format.integer(total)}`}\n className=\"relative h-2 overflow-hidden rounded-pill bg-muted\"\n >\n <div className=\"absolute inset-y-0 left-0\" style={{ width: `${(done / total) * 100}%`, background: \"var(--chart-1)\" }} />\n </div>\n )}\n {!running && failures.length > 0 && (\n <ul aria-label={failuresLabel} className=\"grid gap-1 border-l-2 border-warning pl-3 type-body-sm\">\n {failures.map((f) => (\n <li key={f.key}>\n <span className=\"type-label\">{f.label}</span>\n <span className=\"text-muted-foreground\">: {f.reason}</span>\n </li>\n ))}\n </ul>\n )}\n <p role=\"status\" className=\"sr-only\">\n {said.text}\n </p>\n </section>\n );\n}\n","import * as React from \"react\";\nimport { ImageOff } from \"lucide-react\";\nimport { Skeleton } from \"./data-view\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A photo or crop from an API, in a list, a table cell or a grid (strata-react issue #33, from\n// the Bright Horizons review app, where some crops 404 because the file is missing on disk). A\n// plain <img> gets three things wrong there, and each is a state generated UI leaves out:\n//\n// - it has no size until it loads, so the rows below jump as each one arrives. The box here has\n// its aspect ratio before anything is fetched, and the image is cropped (`cover`) or fitted\n// (`contain`) into it, so nothing moves.\n// - while it loads it is a blank, and on a slow connection a blank reads as \"no photo\". Here it\n// is a `Skeleton`, the same placeholder DataView's loading layouts are made of.\n// - when it fails it is the browser's broken-image icon and the alt text crammed into the box.\n// Here it says what happened in the product's words: `missing` is required (\"Photo not\n// found\"), for the same reason DataView requires `empty`. A record with no photo at all\n// (`src={null}`) shows the same words without a request.\n//\n// `alt` is required too; pass \"\" only when the name beside the thumbnail already says everything\n// it shows. The missing state is an `img` named \"<alt>: <missing>\", so a screen reader hears\n// which photo is gone. Thumbnails come in dozens, so the request waits until the box is near the\n// screen (`useInView`, the hook InfiniteList's sentinel uses, with the same scroll region and a\n// root margin), and once asked for it is not unloaded. `eager` is for the first few on screen.\n// There is no fade-in: a list of thumbnails is seen many times a day (ux-character.md, character\n// by frequency), so the photo simply replaces its skeleton.\n//\n// Two more uses from the Tubes viewer (strata-react issue #51), which drew plain <img>s and lost\n// all of the above:\n//\n// - `children` are drawn above the image in the same positioned box: a video's running time in\n// one corner, \"Saved\" in another. They keep their place while the image loads, fails or is\n// missing, because the box, not the image, holds them. Position them yourself (`absolute\n// bottom-1 right-1`); they are not part of the image's name.\n// - `fallback` replaces the icon and words with the product's own drawing, such as a channel's\n// first letter on a disc for an avatar with no picture. The missing state is still one `img`,\n// named `alt` (with `missing` after it, when given, as \"Night Sky: No picture\"), so a person\n// using a screen reader hears whose picture it is either way. A round avatar is `aspect={1}`\n// with `className=\"rounded-pill\"`.\n\n/** A width-over-height ratio: a number (`1.5`) or a fraction (`\"4/3\"`). */\nexport type AspectRatio = number | `${number}/${number}`;\n\n/** The thumbnail's props. Either `missing` (the words shown when there is no image) or a `fallback` drawing is required. */\nexport type ThumbnailProps = {\n /** The image URL. `null` when the record has no photo: the `missing` words show without a request. */\n src: string | null;\n /** What the photo shows (\"Celadon bowl, front\"). `\"\"` only when the text beside it already says it. */\n alt: string;\n /** Width over height. The box has this shape before the image loads. Default `1`. */\n aspect?: AspectRatio;\n /** `cover` crops to fill the box (default); `contain` fits the whole image in it. */\n fit?: \"cover\" | \"contain\";\n srcSet?: string;\n sizes?: string;\n /** Load at once rather than when near the screen: for the first few above the fold. */\n eager?: boolean;\n /** How far outside the scroll region the request starts (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Layout at the call site: a width (`w-24`, `w-full`), or `rounded-pill` for an avatar. The height follows from `aspect`. */\n className?: string;\n /** Overlays drawn above the image in the same box (a running time, a \"Saved\" badge), in place whether the image has loaded, failed or is missing. */\n children?: React.ReactNode;\n} & (\n | {\n /** What to show when there is no photo or it cannot be loaded, in the product's words: \"Photo not found\". */\n missing: string;\n /** Drawn instead of the icon and `missing` words when there is no image: a letter on a disc for an avatar. */\n fallback?: React.ReactNode;\n }\n | {\n /** Added to the missing state's name after `alt` (\"Night Sky: No picture\"), when given. */\n missing?: string;\n /** Drawn when there is no image or it cannot be loaded: a letter on a disc for an avatar. */\n fallback: React.ReactNode;\n }\n);\n\ntype Phase = \"loading\" | \"loaded\" | \"missing\";\n\nconst ratio = (aspect: AspectRatio) => (typeof aspect === \"number\" ? String(aspect) : aspect.replace(\"/\", \" / \"));\n\n/** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */\nexport function Thumbnail({\n src,\n alt,\n missing,\n aspect = 1,\n fit = \"cover\",\n srcSet,\n sizes,\n eager = false,\n rootMargin = \"200px\",\n className,\n fallback,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (`src` and `srcSet`, since the browser may\n // have loaded a candidate from either), so a new request starts loading again without an effect\n // to reset it, and a late event from the old image cannot mark the new one.\n const request = src ? `${src} ${srcSet ?? \"\"}` : null;\n const [result, setResult] = React.useState<{ request: string; ok: boolean } | null>(null);\n const phase: Phase = !request ? \"missing\" : result?.request === request ? (result.ok ? \"loaded\" : \"missing\") : \"loading\";\n const near = useInView({ active: !eager && !!src, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView;\n\n return (\n <div\n ref={near.ref}\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n aria-busy={phase === \"loading\" || undefined}\n >\n {phase === \"loading\" && <Skeleton className=\"absolute inset-0\" />}\n {src && request && phase !== \"missing\" && requested && (\n <img\n key={request}\n src={src}\n srcSet={srcSet}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={() => setResult({ request, ok: true })}\n onError={() => setResult({ request, ok: false })}\n className={cn(\"absolute inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\", phase === \"loading\" && \"opacity-0\")}\n />\n )}\n {phase === \"missing\" && (\n <div\n role=\"img\"\n aria-label={[alt, missing].filter(Boolean).join(\": \")}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined && \"content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground\",\n )}\n >\n {fallback === undefined ? (\n <>\n <ImageOff aria-hidden className=\"size-4 shrink-0\" />\n <span className=\"type-caption text-balance\">{missing}</span>\n </>\n ) : (\n <div aria-hidden className=\"grid size-full min-h-0 min-w-0\">\n {fallback}\n </div>\n )}\n </div>\n )}\n {children}\n </div>\n );\n}\n\n/** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */\nexport function ThumbnailSkeleton({ aspect = 1, className }: { aspect?: AspectRatio; className?: string }) {\n return (\n <div aria-hidden className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)} style={{ aspectRatio: ratio(aspect) }}>\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\nimport { X } from \"lucide-react\";\nimport { format as defaultFormat, type Format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\n\n// Select many, then act: the state (`useSelection`), and the bar that says how many are chosen and\n// holds what can be done to them (`BulkBar`). `DataTable`'s `selection` prop draws the checkboxes.\n//\n// The selection is pruned to the rows that exist. After a bulk removal, a refetch or a new filter,\n// a key whose row is gone is not counted and not acted on: the bar never says \"3 selected\" over\n// two visible rows, and an action never reaches a row the person cannot see. (Gmail and Linear\n// both drop a selection a filter hides; acting on hidden rows is how a bulk delete surprises.)\n//\n// Shift extends a range from the last row clicked, on every surface (`useSelectRows`), and\n// `initial` chooses a row when it first appears rather than only on mount, so a selection seeded\n// from data still applies once the data arrives (both from strata-react issue #32, a review screen\n// of face crops with the likely matches pre-chosen).\n//\n// The count is the bar's live region, and only the count: it is always mounted, so a screen reader\n// hears \"2 bookings selected\" on each change, and the buttons are outside it, so their names are\n// not read again with every tick. The actions are a labelled group. Per the research, at most one\n// of them is filled (`variant=\"default\"`), named with its verb and count (\"Withdraw 3\"), and a\n// reversible bulk removal goes through `useUndoable` like a single one, not through a confirm.\n\n/** Which rows start chosen: their keys, or a test on each row. Either applies to a row the first time it appears. */\nexport type InitialSelection<T> = Iterable<string> | ((row: T) => boolean);\n\ntype SelectionState = { keys: readonly string[]; seen: ReadonlySet<string>; raw: ReadonlySet<string> };\n\n// Bring the state up to the rows now shown: drop keys whose row has gone, and choose the rows seen\n// for the first time that `initial` names. A row seen before keeps the person's choice, even if it\n// left and came back (it returns unchosen, as it was forgotten when it left).\nfunction reconcile<T>(prev: SelectionState, rows: readonly T[], keys: readonly string[], initial: (row: T, key: string) => boolean): SelectionState {\n const present = new Set(keys);\n const raw = new Set([...prev.raw].filter((k) => present.has(k)));\n const seen = new Set(prev.seen);\n rows.forEach((row, i) => {\n const key = keys[i];\n if (seen.has(key)) return;\n seen.add(key);\n if (initial(row, key)) raw.add(key);\n });\n return { keys, seen, raw };\n}\n\nconst sameKeys = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((k, i) => k === b[i]);\n\n/**\n * Chosen row keys, pruned to the rows that exist, and the calls that change them. Spread into\n * `DataTable`'s or `SelectableGrid`'s `selection` with a `rowLabel`. `initial` (keys, or a test on\n * the row) chooses each row the first time it appears, so a selection seeded from data that loads\n * later, or a next page, still starts right.\n */\nexport function useSelection<T>(rows: readonly T[], rowKey: (row: T) => string, initial: InitialSelection<T> = []) {\n // `initial` is read when a row first appears, so a new function each render is fine.\n const initialRef = React.useRef(initial);\n initialRef.current = initial;\n // Keys are read into a set once per `initial` value, not once per row: a single-use iterable (a\n // generator, `set.values()`) would otherwise be used up by the first row, and an array rebuilt\n // for every row. The set is kept for rows that arrive later.\n const initialKeys = React.useRef<{ source: InitialSelection<T>; keys: ReadonlySet<string> } | undefined>(undefined);\n const test = (row: T, key: string) => {\n const init = initialRef.current;\n if (typeof init === \"function\") return init(row);\n if (initialKeys.current?.source !== init) initialKeys.current = { source: init, keys: new Set(init) };\n return initialKeys.current.keys.has(key);\n };\n const keys = rows.map(rowKey);\n const [state, setState] = React.useState<SelectionState>(() =>\n reconcile({ keys: [], seen: new Set(), raw: new Set() }, rows, keys, test),\n );\n // Adjusted while rendering (React's pattern for state derived from props), not in an effect, so\n // the first paint of new rows already shows them chosen. Compared by key, not by array identity,\n // so `rows={data ?? []}` does not loop.\n let current = state;\n if (!sameKeys(state.keys, keys)) {\n current = reconcile(state, rows, keys, test);\n setState(current);\n }\n const selected = current.raw;\n // rowKey is usually an inline arrow, so it is left out of the dependencies: the rows change.\n const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);\n // A key with no row is never kept, so an action never reaches a row the person cannot see.\n const onChange = React.useCallback(\n (next: Set<string>) =>\n setState((s) => {\n const present = new Set(s.keys);\n return { ...s, raw: new Set([...next].filter((k) => present.has(k))) };\n }),\n [],\n );\n const clear = React.useCallback(() => setState((s) => ({ ...s, raw: new Set() })), []);\n return { selected, selectedRows, count: selected.size, onChange, clear };\n}\n\n/** The part of a selection the surfaces drawing it (`DataTable`, `SelectableGrid`) need. */\ntype SelectionLike<T> = {\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n isSelectable?: (row: T) => boolean;\n};\n\n/**\n * Selecting rows of a surface in the order it shows them: one row, a range with Shift, and all\n * shown. Shared by `DataTable` and `SelectableGrid`, so a range and select-all behave the same on\n * both. `rows` are in display order (after sorting) and include rows a virtualised surface has not\n * rendered.\n *\n * A range runs from the last row clicked (the anchor) to this one, over the selectable rows\n * between, and sets them all to this row's new state, as Gmail and Finder do: Shift-clicking an\n * unchosen row chooses the run, Shift-clicking a chosen one clears it. Every click moves the\n * anchor. An anchor that has left the rows (filtered, removed) makes the next Shift-click a plain\n * one.\n * @internal\n */\nexport function useSelectRows<T>(rows: readonly T[], rowKey: (row: T) => string, selection?: SelectionLike<T>) {\n const anchor = React.useRef<string | undefined>(undefined);\n const keys = selection ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [];\n const chosen = selection ? keys.filter((k) => selection.selected.has(k)).length : 0;\n const allChecked: boolean | \"mixed\" = chosen === 0 ? false : chosen === keys.length ? true : \"mixed\";\n\n const toggle = (key: string, on: boolean, { shiftKey }: { shiftKey: boolean }) => {\n if (!selection) return;\n const next = new Set(selection.selected);\n const from = shiftKey && anchor.current !== undefined ? keys.indexOf(anchor.current) : -1;\n const to = keys.indexOf(key);\n if (from >= 0 && to >= 0) {\n const [a, b] = from < to ? [from, to] : [to, from];\n for (const k of keys.slice(a, b + 1)) {\n if (on) next.add(k);\n else next.delete(k);\n }\n } else if (on) next.add(key);\n else next.delete(key);\n anchor.current = key;\n selection.onChange(next);\n };\n\n // A full or mixed box clears what is shown; an empty one selects every selectable row shown.\n // Keys outside `rows` (filtered away) are left as they are.\n const toggleAll = () => {\n if (!selection) return;\n const next = new Set(selection.selected);\n if (allChecked === false) keys.forEach((k) => next.add(k));\n else keys.forEach((k) => next.delete(k));\n selection.onChange(next);\n };\n\n // A range React Aria makes itself (Shift on a row press) moves the anchor too, so the next\n // Shift-click on a checkbox runs from where the last press was, whichever path it came by.\n const setAnchor = (key: string | null) => {\n if (key !== null) anchor.current = key;\n };\n\n return { toggle, setAnchor, all: { checked: allChecked, toggle: toggleAll, disabled: keys.length === 0 } };\n}\n\n/** The bar for a selection: a polite live count (\"2 bookings selected\"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */\nexport function BulkBar({\n count,\n noun,\n onClear,\n children,\n format = defaultFormat,\n className,\n}: {\n count: number;\n /** What is chosen, singular, or singular and plural: `\"booking\"`, `[\"person\", \"people\"]`. */\n noun: string | [one: string, many: string];\n onClear: () => void;\n /** The actions. At most one filled button, named with its verb and count; while the bar is up it is the view's only filled button, so the screen's own primary goes to `outline`. */\n children: React.ReactNode;\n /** The product's formatters, for the count's figures and plural. Default en-GB. */\n format?: Format;\n className?: string;\n}) {\n const [one, many] = typeof noun === \"string\" ? [noun, `${noun}s`] : noun;\n const label = `${format.count(count, one, many)} selected`;\n return (\n <div\n className={cn(\n count > 0 && \"flex flex-wrap items-center gap-x-4 gap-y-2 rounded-surface bg-surface-sunken py-1.5 pr-1.5 pl-3\",\n className,\n )}\n >\n <p aria-live=\"polite\" className={count > 0 ? \"type-label tabular-nums\" : \"sr-only\"}>\n {count > 0 ? label : `No ${many} selected`}\n </p>\n {count > 0 && (\n <div role=\"group\" aria-label={`Actions for the selected ${many}`} className=\"flex flex-1 flex-wrap items-center gap-2\">\n {children}\n <Button size=\"sm\" variant=\"ghost\" className=\"ml-auto\" onClick={onClear}>\n <X aria-hidden />\n Clear selection\n </Button>\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ChevronRight } from \"lucide-react\";\nimport { useSearchParams } from \"react-router\";\nimport { cn } from \"../lib/utils\";\n\n// Show more of one thing in place: a batch's faces under its row in a history list, a firing's\n// pieces under its line in the log. Strata issue #34, from an app that wrote its own <details>.\n//\n// Not <details>. A closed <details> still mounts its content, so every row's detail component\n// runs, and a list of forty batches makes forty requests on load for bodies nobody opened. Here\n// the body is mounted only while it is open: a `useLoad` inside it runs on the first open, and on\n// a later open the query cache answers at once. Closed, nothing of the body is in the DOM.\n//\n// The trigger is a native button (Enter and Space, focus outline from the base layer) with\n// `aria-expanded`, and `aria-controls` naming the body while it exists (the WAI-ARIA disclosure\n// pattern). Focus stays on the button through open and close, so a keyboard user walks a list of\n// rows with Tab and opens each in place. The summary is the button's name, so it holds text and\n// marks (a Status, a count), never controls; actions for the row go in `actions`, beside it.\n//\n// No height animation: people open rows in a list many times a session, and character by\n// frequency (ux-research ux-character.md) gives frequent actions no motion. The chevron turns\n// with the state, which is the only signal besides the body itself.\n//\n// Many disclosures over one list share their state through `useExpanded`, which can keep it in\n// the URL (`?open=f-0412`), so an opened row survives a reload and can be linked. `DataTable`'s\n// `expansion` prop draws the same thing as a detail row under a table row.\n\n/** Open and closed disclosure state: controlled with `open` and `onOpenChange`, or uncontrolled from `defaultOpen`. */\nexport type DisclosureOpenProps =\n | { open: boolean; onOpenChange: (open: boolean) => void; defaultOpen?: never }\n | { open?: never; onOpenChange?: (open: boolean) => void; defaultOpen?: boolean };\n\nexport type DisclosureProps = DisclosureOpenProps & {\n /** The always-visible line, and the button's accessible name: text and marks, no controls. */\n summary: React.ReactNode;\n /** Mounted only while open, so a request inside runs when the person opens it. */\n children: React.ReactNode;\n /** Controls for the row (a `RowAction`), beside the summary and outside its button. */\n actions?: React.ReactNode;\n className?: string;\n};\n\n/** Shows more of one thing in place: a button with `aria-expanded` around `summary`, and a body mounted only while open (so a request inside it runs on first open). Controlled with `open`/`onOpenChange` or `useExpanded`, or uncontrolled with `defaultOpen`. */\nexport function Disclosure({ summary, children, actions, open, defaultOpen = false, onOpenChange, className }: DisclosureProps) {\n const [own, setOwn] = React.useState(defaultOpen);\n const isOpen = open ?? own;\n const bodyId = React.useId();\n const toggle = () => {\n if (open === undefined) setOwn(!isOpen);\n onOpenChange?.(!isOpen);\n };\n return (\n <div className={cn(\"min-w-0\", className)}>\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n aria-expanded={isOpen}\n aria-controls={isOpen ? bodyId : undefined}\n onClick={toggle}\n className=\"-mx-1 flex min-h-(--control-h-sm) min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-control px-1 text-left hover:bg-muted\"\n >\n <Chevron open={isOpen} />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </button>\n {actions && <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>}\n </div>\n {isOpen && (\n <div id={bodyId} className=\"pt-2 pb-3 pl-6\">\n {children}\n </div>\n )}\n </div>\n );\n}\n\n/** The disclosure chevron: points right when closed, down when open. Shared with `DataTable`'s row toggle. */\nexport function Chevron({ open, className }: { open: boolean; className?: string }) {\n return <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", open && \"rotate-90\", className)} />;\n}\n\n/** Which of many disclosures are open, by key: spread into `DataTable`'s `expansion`, or read with `isOpen`/`setOpen` for a list of `Disclosure`s. */\nexport type Expanded = {\n /** Keys of the open items. */\n expanded: ReadonlySet<string>;\n /** Replaces the open set. `DataTable` calls this. */\n onChange: (next: Set<string>) => void;\n isOpen: (key: string) => boolean;\n setOpen: (key: string, open: boolean) => void;\n collapseAll: () => void;\n};\n\nexport type ExpandedOptions = {\n /** Keep the open keys in this URL search parameter (`?open=a&open=b`), so an opened row can be linked and survives a reload. Needs a React Router context. */\n param?: string;\n /** Keys open at first. Ignored with `param`: there the URL says what is open, so a link that opens a row carries it. */\n initial?: Iterable<string>;\n /** Opening one closes the others (an accordion). Default false: people compare two rows. */\n single?: boolean;\n};\n\n/** Shared open state for the disclosures of one list or table, optionally kept in the URL (`param`). */\nexport function useExpanded(options: ExpandedOptions = {}): Expanded {\n // One of two hooks, chosen by whether `param` is given; a screen does not switch between the two\n // while mounted (as with DataTable's `sortParam`), so the hook order is stable.\n return options.param ? useUrlExpanded(options.param, options) : useLocalExpanded(options);\n}\n\nfunction api(expanded: ReadonlySet<string>, set: (next: Set<string>) => void, single?: boolean): Expanded {\n return {\n expanded,\n // With `single`, a change that opens a key keeps only that key, so `DataTable` (which calls\n // onChange with the whole set) gets the accordion too, not only `setOpen`.\n onChange: (next) => {\n const opened = single ? [...next].filter((k) => !expanded.has(k)) : [];\n set(opened.length ? new Set([opened[opened.length - 1]]) : next);\n },\n isOpen: (key) => expanded.has(key),\n setOpen: (key, open) => {\n const next = single ? new Set<string>() : new Set(expanded);\n if (open) next.add(key);\n else next.delete(key);\n set(next);\n },\n collapseAll: () => set(new Set()),\n };\n}\n\nfunction useLocalExpanded({ initial = [], single }: ExpandedOptions): Expanded {\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set(initial));\n return React.useMemo(() => api(expanded, setExpanded, single), [expanded, single]);\n}\n\nfunction useUrlExpanded(param: string, { single }: ExpandedOptions): Expanded {\n const [params, setParams] = useSearchParams();\n const fromUrl = params.getAll(param);\n const joined = fromUrl.join(\"\\u0000\");\n // `fromUrl` is a new array each render; its joined form is the dependency.\n const expanded = React.useMemo<ReadonlySet<string>>(() => new Set(fromUrl), [joined]);\n const set = React.useCallback(\n (next: Set<string>) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.delete(param);\n for (const k of next) out.append(param, k);\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return React.useMemo(() => api(expanded, set, single), [expanded, set, single]);\n}\n","import * as React from \"react\";\nimport { ArrowDown, ArrowUp, ArrowUpDown } from \"lucide-react\";\nimport {\n createSortedRowModel,\n flexRender,\n rowSortingFeature,\n tableFeatures,\n useTable,\n type ColumnDef,\n type SortingState,\n} from \"@tanstack/react-table\";\nimport {\n Button as AriaButton,\n Cell as AriaCell,\n Column as AriaColumn,\n Row as AriaRow,\n Table as AriaTable,\n TableBody,\n TableHeader,\n TableLayout,\n Virtualizer,\n type Selection,\n} from \"react-aria-components\";\nimport { useSearchParams } from \"react-router\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { TableSelectionCheckbox, useShiftNote } from \"./checkbox\";\nimport { useSelectRows } from \"./selection\";\nimport { Chevron } from \"./disclosure\";\n\n// The table real product screens use: 12px muted sentence-case headers, row rules (no zebra),\n// numbers right-aligned in tabular figures, one status mark and at most one action per row.\n//\n// The split (Jonathan, 2026-11-12): React Aria's Table draws it and owns what a person does with it\n// (focus and arrow-key navigation, a header that sorts, selection, row and cell semantics for screen\n// readers), and TanStack Table owns the data model (here the sort: `useTable` with the row-sorting\n// feature, so the data model can grow pagination, filtering or grouping without touching the markup).\n// From `virtualizeFrom` rows React Aria's Virtualizer with `TableLayout` draws only the visible rows\n// and keeps the header in place (a table with no detail rows uses a fixed 41px row; one with them\n// measures its rows). The column API stays small on purpose (key, header, cell, numeric, sort), so a\n// screen reads as a list of decisions about columns, not as table plumbing. `sortParam` keeps the\n// sort in the URL (?sort=when.desc) so a sorted view can be linked and survives a reload.\n//\n// A table is a `grid`, its rows `row`s and its cells `gridcell`s (the first column is the row\n// header, which React Aria requires): that is the role the keyboard model belongs to. A sortable\n// header is the column header itself, pressed or Enter: `aria-sort` is \"none\" until it is sorted.\n//\n// Selection is opt-in (`selection`), because checkboxes belong only where a bulk action exists\n// (one of 23 real product screens had them; a checkbox on every row is a generated-UI tell). When\n// it is on, the first column is a checkbox per row (React Aria's selection checkbox), named from the\n// row (`rowLabel` is required), disabled where `isSelectable` says no; the header's \"Select all shown\"\n// covers the selectable rows in `rows` (all of them, not only the rendered ones of a virtualised\n// table) and is mixed when some are chosen, and then clears them. Only the checkbox or Space\n// chooses a row: a click on a cell does nothing to the selection. Shift-click on a checkbox (or\n// Shift+Space) chooses or clears the run from the last row clicked, in the sorted order shown\n// (`useSelectRows`, shared with `SelectableGrid`; React Aria extends a range on a row press, but a\n// checkbox always toggles one row). Selected rows take the sunken fill, not a ring, so a selection\n// never reads as focus. The table only draws the selection; the state is the caller's, usually\n// `useSelection`, and the actions live in a `BulkBar`.\n//\n// Expansion is opt-in too (`expansion`): a row opens a detail row under it, for what belongs to\n// the row but would crowd the table (a firing's pieces, a batch's faces). It follows `Disclosure`:\n// the toggle is a button with `aria-expanded`, named for what it shows (`rowLabel`, \"Pieces in\n// firing 412\"), and the detail is mounted only while open, so a `useLoad` inside it runs on the\n// first open and not for every row on load. The detail is one more row of the grid, spanning the\n// data columns and starting under the first of them, with no rule between it and its row; it can\n// be focused but never chosen. The toggle does not carry `aria-controls`: a grid cell has no DOM id\n// to point at. State is the caller's, usually `useExpanded` (which can keep it in the URL).\n//\n// Missing values (strata-react issue #47, from the Tubes Library table): a column that gives\n// `value` gets a typed sort (numbers, then text in the locale's order with numbers in it read as\n// numbers, then dates) and a placeholder for a row whose value is `null` or `undefined`: an en\n// dash in the muted ink, named \"No value\" for a screen reader, or the column's `missing` word\n// where the word carries meaning (\"Never\"). Missing rows sort after every real value in both\n// directions, because \"not known\" is not \"smallest\"; a column's own `sort` still decides the\n// order among the rows that have a value. Without `value` a column works as before.\n\n/** What a column's `value` may be: a number, text or a date, or `null`/`undefined` when the row has none. */\nexport type CellValue = number | string | Date | null | undefined;\n\nexport type Column<T> = {\n key: string;\n header: string;\n /** Right-aligns and sets tabular figures. Use for every quantity. */\n numeric?: boolean;\n /** Orders two rows. With `value`, it orders only rows that have one (missing ones go last); `false` turns off `value`'s default sort. */\n sort?: ((a: T, b: T) => number) | false;\n /** What the cell shows when the row's `value` is missing, where the word carries meaning (\"Never\"). Default an en dash. */\n missing?: string;\n /** Cells that may hold long text get truncated rather than stretching the table. */\n truncate?: boolean;\n /** Keep the header for screen readers only, as for a column of row actions. `header` still names it. */\n hideHeader?: boolean;\n className?: string;\n} & (\n | {\n cell: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value?: (row: T) => CellValue;\n }\n | {\n /** How a row with a value is drawn. Default: numbers through `format.decimal`, dates through `format.date`, text as it is. */\n cell?: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value: (row: T) => CellValue;\n }\n);\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" });\nconst kind = (v: number | string | Date) => (typeof v === \"number\" ? 0 : typeof v === \"string\" ? 1 : 2);\n\n/** Orders two present values: numbers, then text (locale order, numbers in text read as numbers), then dates. */\nfunction compareValues(a: number | string | Date, b: number | string | Date) {\n if (kind(a) !== kind(b)) return kind(a) - kind(b);\n if (typeof a === \"string\") return collator.compare(a, b as string);\n return Number(a) - Number(b);\n}\n\n/** A cell with no value: the column's word, or an en dash named \"No value\" for a screen reader. */\nfunction Missing({ word }: { word?: string }) {\n return word ? (\n <span className=\"text-muted-foreground\">{word}</span>\n ) : (\n <span className=\"text-muted-foreground\">\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">No value</span>\n </span>\n );\n}\n\nfunction drawValue(v: number | string | Date) {\n return typeof v === \"number\" ? format.decimal(v) : v instanceof Date ? format.date(v) : v;\n}\n\n/** Row selection for a `DataTable`: the chosen row keys, how to change them, and how to name each row's checkbox. */\nexport type RowSelection<T> = {\n /** Keys (from `rowKey`) of the chosen rows. */\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row in its checkbox (\"Select <rowLabel>\"). Required: an unnamed checkbox is a column of \"checkbox, not checked\". */\n rowLabel: (row: T) => string;\n /** Rows that cannot be chosen get a disabled checkbox and are left out of select-all. Default: every row. */\n isSelectable?: (row: T) => boolean;\n};\n\n/** Row expansion for a `DataTable`: the open row keys, how to change them, how to name each toggle, and the detail to show. */\nexport type RowExpansion<T> = {\n /** Keys (from `rowKey`) of the open rows. */\n expanded: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row's toggle by what it shows: \"Pieces in firing 412\". Its state is `aria-expanded`, so the name stays the same open or closed. */\n rowLabel: (row: T) => string;\n /** The row's detail, mounted only while it is open. Return an element whose component makes any request, so the request runs on open. */\n detail: (row: T) => React.ReactNode;\n /** Rows with nothing to show get no toggle. Default: every row. */\n isExpandable?: (row: T) => boolean;\n};\n\nexport type Sort = { key: string; dir: \"ascending\" | \"descending\" };\n\nexport type DataTableProps<T> = {\n /** Names the table for screen readers and labels the scroll region. */\n caption: string;\n columns: Column<T>[];\n rows: T[];\n rowKey: (row: T) => string;\n initialSort?: Sort;\n /** Keep the sort in this URL search parameter. Needs a React Router context. */\n sortParam?: string;\n /** Row count from which only the visible rows render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n /** Adds a checkbox column and \"Select all shown\". Use only where a `BulkBar` acts on the selection. */\n selection?: RowSelection<T>;\n /** Adds a toggle per row that opens a detail row under it. Spread `useExpanded()` in with a `rowLabel` and `detail`. */\n expansion?: RowExpansion<T>;\n className?: string;\n};\n\ntype SortState = [Sort | undefined, (next: Sort) => void];\n\nfunction useLocalSort(initial?: Sort): SortState {\n const [sort, setSort] = React.useState(initial);\n return [sort, setSort];\n}\n\n/** Reads a sort from its URL form (`pieces.desc`). */\nexport function parseSort(value: string | null): Sort | undefined {\n if (!value) return undefined;\n const [key, dir] = value.split(\".\");\n if (!key) return undefined;\n return { key, dir: dir === \"desc\" ? \"descending\" : \"ascending\" };\n}\n\n/** Writes a sort in its URL form (`pieces.desc`). */\nexport function serialiseSort(sort: Sort) {\n return `${sort.key}.${sort.dir === \"descending\" ? \"desc\" : \"asc\"}`;\n}\n\nfunction useUrlSort(param: string, initial?: Sort): SortState {\n const [params, setParams] = useSearchParams();\n const sort = parseSort(params.get(param)) ?? initial;\n const set = React.useCallback(\n (next: Sort) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.set(param, serialiseSort(next));\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return [sort, set];\n}\n\n/** A table on React Aria's Table with TanStack Table's data model: muted headers, row rules, right-aligned tabular numbers, sortable headers with `aria-sort`, virtualised from `virtualizeFrom` rows, sort optionally kept in the URL (`sortParam`). */\nexport function DataTable<T>(props: DataTableProps<T>) {\n // Two thin wrappers so each calls its hooks unconditionally.\n return props.sortParam ? <UrlSortedTable {...props} sortParam={props.sortParam} /> : <LocalSortedTable {...props} />;\n}\n\nfunction LocalSortedTable<T>(props: DataTableProps<T>) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useLocalSort(props.initialSort)} />;\n}\n\nfunction UrlSortedTable<T>(props: DataTableProps<T> & { sortParam: string }) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useUrlSort(props.sortParam, props.initialSort)} />;\n}\n\n// The one TanStack feature in use for now: sorting, on the client. TanStack Table 9 is tree-shaken by feature, so\n// nothing else (pagination, filtering, TanStack's own selection or expansion) is bundled.\nconst features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel() });\n// TanStack Table 9 requires object or array rows. Every row a DataTable draws is a record, but the\n// public `T` stays unconstrained so an app's row types need no change: the cast is in the two wrappers.\ntype Rec = Record<string, any>; // TanStack's own RowData\n\nfunction Table<T extends Rec>({\n caption,\n columns,\n rows,\n rowKey,\n sortState: [sort, setSort],\n virtualizeFrom = 100,\n maxHeight = 480,\n selection,\n expansion,\n className,\n}: DataTableProps<T> & { sortState: SortState }) {\n const defs = React.useMemo<ColumnDef<typeof features, T, unknown>[]>(\n () =>\n columns.map((c): ColumnDef<typeof features, T, unknown> => {\n const { value, sort } = c;\n if (!value) {\n return {\n id: c.key,\n // TanStack only sorts columns with an accessor; the row itself is enough, since the\n // column's own comparator does the work.\n accessorFn: (row) => row,\n header: c.header,\n cell: (info) => c.cell?.(info.row.original),\n enableSorting: Boolean(sort),\n sortFn: sort ? (a, b) => sort(a.original, b.original) : undefined,\n };\n }\n // The accessor is the value, with null as undefined, so TanStack's `sortUndefined: \"last\"`\n // keeps missing rows at the end whichever way the column is sorted (it applies before the\n // direction is). The comparator then sees only rows that have a value.\n return {\n id: c.key,\n accessorFn: (row) => value(row) ?? undefined,\n header: c.header,\n cell: (info) => {\n const v = value(info.row.original);\n if (v == null) return <Missing word={c.missing} />;\n return c.cell ? c.cell(info.row.original) : drawValue(v);\n },\n enableSorting: sort !== false,\n sortUndefined: \"last\",\n sortFn: sort\n ? (a, b) => sort(a.original, b.original)\n : (a, b) => compareValues(a.getValue<number | string | Date>(c.key), b.getValue<number | string | Date>(c.key)),\n };\n }),\n [columns],\n );\n\n const sortable = (c: Column<T>) => (c.value ? c.sort !== false : Boolean(c.sort));\n const sorting: SortingState = sort && columns.some((c) => c.key === sort.key && sortable(c))\n ? [{ id: sort.key, desc: sort.dir === \"descending\" }]\n : [];\n\n const table = useTable({\n features,\n data: rows,\n columns: defs,\n state: { sorting },\n getRowId: (row) => rowKey(row),\n // No pagination here, and expansion is the caller's state, not TanStack's: nothing to reset. Left on, TanStack resets the page\n // index whenever `rows` is a new array; a screen that filters its rows on every render (the\n // kiln room after Withdraw) then re-renders forever and the tab freezes. Found by the\n // example app's visual suite, which jsdom did not show.\n autoResetAll: false,\n });\n\n const modelRows = table.getRowModel().rows;\n const canExpand = (row: T) => expansion?.isExpandable?.(row) ?? true;\n const virtual = modelRows.length >= virtualizeFrom;\n const lead = (selection ? 1 : 0) + (expansion ? 1 : 0);\n\n // Selection is React Aria's: its checkboxes (`slot=\"selection\"`), its Space and Shift-range\n // keys, its select-all. We translate to and from our `RowSelection`, which holds keys of rows\n // only (an open detail row is a row of the grid too, and is never chosen).\n const shownKeys = React.useMemo(() => new Set(modelRows.map((r) => r.id)), [modelRows]);\n const selectableKeys = modelRows.filter((r) => selection?.isSelectable?.(r.original) ?? true).map((r) => r.id);\n const detailKey = (id: string) => `${id}\\u0000detail`;\n const disabledKeys = React.useMemo(() => {\n const keys: string[] = [];\n for (const r of modelRows) {\n if (selection && !(selection.isSelectable?.(r.original) ?? true)) keys.push(r.id);\n if (expansion && canExpand(r.original)) keys.push(detailKey(r.id));\n }\n return keys;\n // canExpand reads `expansion`.\n }, [modelRows, selection, expansion]);\n // Shift-click on a checkbox extends a range from the last one clicked (issue #32). React Aria\n // extends on a row press and Shift+Space, but a checkbox always toggles one row, so the range is\n // still ours: Shift is noted on the press, and a change of exactly one row is a click.\n const shift = useShiftNote();\n // The row last pressed (React Aria marks each row with `data-key`), to anchor a range it extended itself.\n const pressed = React.useRef<string | null>(null);\n const notePress = (e: React.SyntheticEvent) => void (pressed.current = (e.target as HTMLElement).closest(\"[data-key]\")?.getAttribute(\"data-key\") ?? null);\n const sortedRows = React.useMemo(() => modelRows.map((r) => r.original), [modelRows]);\n const select = useSelectRows(sortedRows, rowKey, selection);\n const changeSelection = (next: Selection) => {\n if (!selection) return;\n if (next !== \"all\") {\n const nextShown = new Set([...next].map(String).filter((k) => shownKeys.has(k)));\n const added = [...nextShown].filter((k) => !selection.selected.has(k));\n const removed = [...selection.selected].filter((k) => shownKeys.has(k) && !nextShown.has(k));\n if (added.length + removed.length === 1) {\n select.toggle(added[0] ?? removed[0], added.length === 1, shift.take());\n return;\n }\n select.setAnchor(pressed.current);\n }\n // What the table does not show (filtered away) is left as it is, as `useSelection` prunes it.\n const outside = [...selection.selected].filter((k) => !shownKeys.has(k));\n // React Aria's select-all chooses everything when only some are chosen; a mixed box clears\n // what is shown here (Gmail's rule, kept from before), so \"all\" over a part-chosen set clears.\n const chosen = selectableKeys.filter((k) => selection.selected.has(k)).length;\n const picked =\n next === \"all\" ? (chosen > 0 && chosen < selectableKeys.length ? [] : selectableKeys) : [...next].map(String).filter((k) => shownKeys.has(k));\n selection.onChange(new Set([...outside, ...picked]));\n };\n\n const grid = (\n <AriaTable\n aria-label={caption}\n selectionMode={selection ? \"multiple\" : \"none\"}\n selectionBehavior=\"toggle\"\n selectedKeys={selection ? new Set([...selection.selected].filter((k) => shownKeys.has(k))) : undefined}\n onSelectionChange={changeSelection}\n disabledKeys={disabledKeys}\n sortDescriptor={sort && columns.some((c) => c.key === sort.key && sortable(c)) ? { column: sort.key, direction: sort.dir } : undefined}\n onSortChange={(d) => setSort({ key: String(d.column), dir: d.direction })}\n className={cn(\"w-full border-collapse type-body-sm outline-none\", virtual && \"overflow-auto\")}\n style={virtual ? { maxHeight } : undefined}\n >\n <TableHeader className={cn(virtual && \"bg-background\")}>\n {selection && (\n <AriaColumn id={SELECT} textValue=\"Select all shown\" width={32} className=\"w-8 py-2 pr-2 text-left align-bottom outline-offset-[-2px]\">\n <TableSelectionCheckbox label=\"Select all shown\" className=\"-my-1\" disabled={selectableKeys.length === 0} />\n </AriaColumn>\n )}\n {expansion && (\n <AriaColumn id={EXPAND} textValue=\"Details\" width={40} className=\"w-10 py-2 pr-2 outline-offset-[-2px]\">\n <span className=\"sr-only\">Details</span>\n </AriaColumn>\n )}\n {columns.map((c, i) => (\n <AriaColumn\n key={c.key}\n id={c.key}\n textValue={c.header}\n // React Aria requires a row header; the first data column is the row's name.\n isRowHeader={i === 0}\n allowsSorting={sortable(c)}\n // Widths apply only to a virtualised table (a plain one sizes its columns to their\n // content): numbers take less than text. `last:pr-0` would match every cell of a\n // virtualised table, where each sits alone in a wrapper, so the last column is named.\n width={c.numeric ? \"0.6fr\" : \"1fr\"}\n className={cn(\n \"py-2 text-left align-bottom type-caption font-normal text-muted-foreground outline-offset-[-2px]\",\n i < columns.length - 1 && \"pr-4\",\n c.numeric && \"text-right\",\n )}\n >\n {({ allowsSorting, sortDirection }) => {\n const Icon = sortDirection === \"ascending\" ? ArrowUp : sortDirection === \"descending\" ? ArrowDown : ArrowUpDown;\n const label = c.hideHeader ? <span className=\"sr-only\">{c.header}</span> : c.header;\n return allowsSorting ? (\n <span\n className={cn(\n \"-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-control px-1 transition-state hover:text-foreground\",\n c.numeric && \"flex-row-reverse\",\n sortDirection && \"text-foreground\",\n )}\n >\n {label}\n <Icon aria-hidden className={cn(\"size-3.5\", !sortDirection && \"opacity-50\")} />\n </span>\n ) : (\n label\n );\n }}\n </AriaColumn>\n ))}\n </TableHeader>\n <TableBody>\n {modelRows.flatMap((row) => {\n const open = (expansion?.expanded.has(row.id) ?? false) && canExpand(row.original);\n const cells = new Map(row.getAllCells().map((cell) => [cell.column.id, cell]));\n const items = [\n <AriaRow\n key={row.id}\n id={row.id}\n textValue={selection?.rowLabel(row.original) ?? expansion?.rowLabel(row.original) ?? row.id}\n // A row's own press does nothing: only its checkbox, or Space, chooses it, so a click on\n // a cell never changes the selection (React Aria's \"toggle\" would otherwise make every row a switch).\n onAction={selection ? noop : undefined}\n className={cn(\"border-t border-border outline-offset-[-2px] selected:bg-surface-sunken\", open && \"selected:bg-surface-sunken\")}\n >\n {selection && (\n <AriaCell className=\"w-8 py-2.5 pr-2 align-middle\">\n <TableSelectionCheckbox label={`Select ${selection.rowLabel(row.original)}`} className=\"-my-0.5\" />\n </AriaCell>\n )}\n {expansion && (\n <AriaCell className=\"w-10 py-2.5 pr-2 align-middle\">\n {canExpand(row.original) && (\n <AriaButton\n aria-expanded={open}\n aria-label={expansion.rowLabel(row.original)}\n onPress={() => {\n const next = new Set(expansion.expanded);\n if (open) next.delete(row.id);\n else next.add(row.id);\n expansion.onChange(next);\n }}\n className=\"-my-1.5 grid size-(--control-h-sm) cursor-pointer place-items-center rounded-control hover:bg-muted\"\n >\n <Chevron open={open} />\n </AriaButton>\n )}\n </AriaCell>\n )}\n {columns.map((c, i) => {\n const cell = cells.get(c.key)!;\n return (\n <AriaCell\n key={c.key}\n className={cn(\n \"py-2.5 align-middle\",\n i < columns.length - 1 && \"pr-4\",\n c.numeric && \"text-right tabular-nums\",\n c.truncate && \"max-w-48 truncate\",\n c.className,\n )}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </AriaCell>\n );\n })}\n </AriaRow>,\n ];\n if (open && expansion)\n items.push(\n <AriaRow key={detailKey(row.id)} id={detailKey(row.id)} textValue={expansion.rowLabel(row.original)} className=\"outline-offset-[-2px]\">\n {lead > 0 && <AriaCell colSpan={lead} />}\n <AriaCell colSpan={columns.length} className=\"pt-0.5 pb-4 align-top\">\n {expansion.detail(row.original)}\n </AriaCell>\n </AriaRow>,\n );\n return items;\n })}\n </TableBody>\n </AriaTable>\n );\n\n return (\n <div\n className={cn(\"relative min-w-0\", !virtual && \"overflow-x-auto\", className)}\n onMouseDownCapture={(e) => {\n shift.handlers.onMouseDown(e);\n notePress(e);\n }}\n onKeyDownCapture={(e) => {\n shift.handlers.onKeyDown(e);\n notePress(e);\n }}\n >\n {virtual ? (\n <Virtualizer layout={TableLayout} layoutOptions={expansion ? { estimatedRowHeight: 41, headingHeight: 36 } : { rowHeight: 41, headingHeight: 36 }}>\n {grid}\n </Virtualizer>\n ) : (\n grid\n )}\n </div>\n );\n}\n\nconst SELECT = \"\\u0000select\";\nconst EXPAND = \"\\u0000expand\";\nconst noop = () => {};\n\n/** The loading placeholder for a `DataTable`, shaped like its rows. */\nexport function TableSkeleton({ rows = 4, columns = 5 }: { rows?: number; columns?: number }) {\n return (\n <div aria-hidden className=\"grid gap-0\">\n <div className=\"flex gap-4 py-2\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-3 flex-1 rounded-control bg-muted\" />\n ))}\n </div>\n {Array.from({ length: rows }, (_, r) => (\n <div key={r} className=\"flex gap-4 border-t border-border py-3.5\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-4 flex-1 rounded-control bg-muted motion-safe:animate-pulse\" />\n ))}\n </div>\n ))}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Pause, Play, SkipBack, SkipForward, Square, StepBack, StepForward, Volume2, VolumeX } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\nimport { NativeSelect } from \"./field\";\nimport type { Shortcut } from \"./hotkeys\";\nimport { Toolbar } from \"./toolbar\";\nimport { Slider } from \"./value-controls\";\nimport { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport { useSliderState } from \"react-stately\";\n\n// The controls around anything that plays (strata issue #78): transport, a time readout, a seek\n// bar, volume with mute, a playback rate, and a stage that holds a picture at its aspect ratio.\n// Video and audio editors, media viewers, lesson players and replays of recorded data (a kiln\n// firing played back) share them. Nothing here is tied to `<video>`: the app owns its player (HTML\n// media, Web Audio, a canvas compositor, a data replay) and passes the state in and takes the\n// requests out, so a replay with no media element at all uses the same controls.\n//\n// Transport is used hundreds of times a session, so it changes instantly with no motion and is\n// driven from the one shortcut list (`transportShortcuts`, for `useHotkeys` and `KeysLegend`), not\n// from key handlers of its own (ux-character.md, by frequency; components.md §3.16). Each control is\n// a named `IconButton`, and the play button's NAME follows the state (\"Play\" / \"Pause\"). It is not\n// also `aria-pressed`: a button whose name flips and whose pressed state flips reads as a toggle of\n// a toggle in a screen reader. (The issue asked for both; one is the WAI-ARIA way, so the name.)\n// The group is React Aria's toolbar through `Toolbar` (one tab stop, arrows between controls).\n//\n// The seek bar is React Aria's slider hooks (`useSlider`, `useSliderThumb`, `useSliderState`): the\n// pointer, the thumb, the hidden range input and its label come from them. Two things are ours on top,\n// each checked in the hooks' source. The value text: `useSliderState` formats through an object with\n// `format`, `formatRange` and `resolvedOptions`, so it is given one that says \"1:23\" instead of an\n// `Intl.NumberFormat` (which would read seconds as a bare number). The keys: the state has one\n// `step`, and a seek bar needs a fine one so a drag lands on any moment, so arrows (`step` seconds),\n// Page keys (`bigStep`) and Home and End are handled in a capture handler on the input and the hooks'\n// own arrow handling is stopped. Volume has neither limit, and stays React Aria's component.\n//\n// Readouts are `tabular-nums` and are padded to the width of the longest value they will show\n// (`duration`), so they do not change width as the time runs.\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);\n\nexport type Precision = \"seconds\" | \"ms\" | \"frames\";\n\ntype TimeProps = { precision?: Precision; fps?: number };\n\nconst timecode = (t: number, { precision, fps }: TimeProps) => format.timecode(t, { precision, fps });\n\n/** The current and total time, in `tabular-nums`, as `<time>` elements. */\nexport function TimeReadout({ time, duration, precision = \"seconds\", fps = 30, className }: { time: number; duration: number | null } & TimeProps & { className?: string }) {\n const total = duration === null ? null : timecode(duration, { precision, fps });\n return (\n <span className={cn(\"inline-flex items-baseline gap-1 type-body-sm tabular-nums\", className)}>\n <time dateTime={`PT${Math.floor(time)}S`} aria-label={`Position ${timecode(time, { precision, fps })}`} className=\"text-foreground\" style={total ? { minWidth: `${total.length}ch` } : undefined}>\n {timecode(time, { precision, fps })}\n </time>\n <span aria-hidden className=\"text-muted-foreground\">\n /\n </span>\n <time dateTime={duration === null ? undefined : `PT${Math.floor(duration)}S`} aria-label={`Length ${total ?? format.missing}`} className=\"text-muted-foreground\">\n {total ?? format.missing}\n </time>\n </span>\n );\n}\n\nexport type SeekBarProps = TimeProps & {\n time: number;\n /** Seconds; null, NaN or 0 while it is not known (a stream before its metadata): the bar is drawn disabled, with no thumb. */\n duration: number | null;\n /** The viewer asked for this time (drag, click or key). */\n onSeek: (time: number) => void;\n /** Named points on the bar (chapters, markers). Pressing one seeks to it. */\n marks?: readonly { time: number; label: string }[];\n /** How far has loaded or been recorded, drawn behind the played part. */\n buffered?: number;\n /** Arrow key step in seconds. Default 5. */\n step?: number;\n /** Page Up and Page Down step in seconds. Default 30. */\n bigStep?: number;\n label?: string;\n disabled?: boolean;\n className?: string;\n};\n\n/** A seek bar: dragged, clicked and moved by keys (arrows `step`, Page keys `bigStep`, Home and End), with its time as the accessible value. */\nexport function SeekBar({ time, duration: known, onSeek, marks = [], buffered, step = 5, bigStep = 30, label = \"Seek\", precision = \"seconds\", fps = 30, disabled: off, className }: SeekBarProps) {\n const duration = known && Number.isFinite(known) && known > 0 ? known : 0;\n const disabled = off || duration === 0;\n const track = React.useRef<HTMLDivElement>(null);\n const input = React.useRef<HTMLInputElement>(null);\n const frac = duration > 0 ? clamp(time / duration, 0, 1) : 0;\n const seekTo = (t: number) => onSeek(clamp(t, 0, duration));\n // React Aria's state with a formatter that says \"1:23\" (it only needs `format`, `formatRange` and\n // `resolvedOptions`, which is all `useSliderState` calls) and a fine step, so a drag lands on any\n // moment and not on every 5 s.\n const timeText = React.useMemo(() => {\n const say = (t: number) => timecode(t, { precision, fps });\n return { format: say, formatRange: (a: number, b: number) => `${say(a)} to ${say(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) } as unknown as Intl.NumberFormat;\n }, [precision, fps]);\n const fine = precision === \"frames\" ? 1 / fps : precision === \"ms\" ? 0.001 : 0.01;\n const state = useSliderState({ minValue: 0, maxValue: Math.max(duration, fine), step: fine, value: [clamp(time, 0, duration)], onChange: ([t]) => seekTo(t), numberFormatter: timeText, isDisabled: disabled });\n const { groupProps, trackProps } = useSlider({ \"aria-label\": label, isDisabled: disabled }, state, track);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: track, inputRef: input, \"aria-label\": label, isDisabled: disabled }, state);\n const { focusProps, isFocusVisible } = useFocusRing();\n // The keys are ours, because the hooks step by `state.step` and this one has to be fine for the\n // drag: arrows move `step` seconds, Page keys `bigStep`, Home and End the ends. Captured so the\n // hook's own arrow handling (one fine step) does not also run.\n const keys: Record<string, number> = { ArrowLeft: -step, ArrowDown: -step, ArrowRight: step, ArrowUp: step, PageDown: -bigStep, PageUp: bigStep };\n const onKeyDownCapture = (e: React.KeyboardEvent) => {\n if (disabled) return;\n if (e.key in keys) seekTo(time + keys[e.key]);\n else if (e.key === \"Home\") seekTo(0);\n else if (e.key === \"End\") seekTo(duration);\n else return;\n e.preventDefault();\n e.stopPropagation();\n };\n return (\n <div {...groupProps} className={cn(\"relative flex h-(--control-h) min-w-0 flex-1 items-center\", disabled && \"cursor-not-allowed opacity-50\", className)}>\n <div {...trackProps} ref={track} className={cn(\"relative flex h-full w-full cursor-pointer touch-none items-center\", disabled && \"cursor-not-allowed\")}>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n {buffered !== undefined && duration > 0 && <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-neutral-4\" style={{ width: `${clamp(buffered / duration, 0, 1) * 100}%` }} />}\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${frac * 100}%` }} />\n {duration > 0 &&\n marks.map((m) => (\n <button\n key={`${m.time}-${m.label}`}\n type=\"button\"\n tabIndex={-1}\n disabled={disabled}\n title={`${m.label}, ${timecode(m.time, { precision, fps })}`}\n aria-label={`${m.label}, ${timecode(m.time, { precision, fps })}`}\n onPointerDown={(e) => e.stopPropagation()}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={() => seekTo(m.time)}\n className=\"absolute top-1/2 h-3 w-1 -translate-y-1/2 cursor-pointer rounded-pill bg-foreground\"\n style={{ left: `${(m.time / duration) * 100}%` }}\n />\n ))}\n <div {...thumbProps} className={cn(\"absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-pill border-2 border-primary bg-background\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")} style={{ left: `${frac * 100}%` }}>\n <VisuallyHidden>\n <input ref={input} {...mergeProps(inputProps, focusProps)} aria-labelledby={undefined} onKeyDownCapture={onKeyDownCapture} />\n </VisuallyHidden>\n </div>\n </div>\n </div>\n );\n}\n\nexport type TransportProps = {\n playing: boolean;\n onPlayPause: () => void;\n onStop?: () => void;\n onToStart?: () => void;\n onToEnd?: () => void;\n onStepBack?: () => void;\n onStepForward?: () => void;\n /** What a step is called in the buttons' names: \"frame\" (default) or \"second\". */\n stepUnit?: string;\n /** Anything else on the row: the time readout, a seek bar, volume. */\n children?: React.ReactNode;\n className?: string;\n};\n\n/** The transport buttons for a player the app owns. Every control is a named icon button; the play button's name is \"Play\" or \"Pause\" from `playing`. Only the buttons whose handler is passed are drawn. */\nexport function Transport({ playing, onPlayPause, onStop, onToStart, onToEnd, onStepBack, onStepForward, stepUnit = \"frame\", children, className }: TransportProps) {\n return (\n <Toolbar label=\"Playback\" className={cn(\"gap-2\", className)}>\n {onToStart && <IconButton icon={SkipBack} label=\"Go to start\" hint=\"Home\" onClick={onToStart} />}\n {onStepBack && <IconButton icon={StepBack} label={`Back one ${stepUnit}`} hint=\"←\" onClick={onStepBack} />}\n <IconButton icon={playing ? Pause : Play} label={playing ? \"Pause\" : \"Play\"} hint=\"Space\" variant=\"outline\" onClick={onPlayPause} />\n {onStop && <IconButton icon={Square} label=\"Stop\" onClick={onStop} />}\n {onStepForward && <IconButton icon={StepForward} label={`Forward one ${stepUnit}`} hint=\"→\" onClick={onStepForward} />}\n {onToEnd && <IconButton icon={SkipForward} label=\"Go to end\" hint=\"End\" onClick={onToEnd} />}\n {children}\n </Toolbar>\n );\n}\n\nexport type VolumeControlProps = {\n /** 0 to 100. */\n volume: number;\n onVolumeChange: (volume: number) => void;\n /** Allow over 100 (a boost), up to this. Default 100. */\n max?: number;\n disabled?: boolean;\n className?: string;\n};\n\n/** A mute button and a volume slider with its value in percent. Muting sets the volume to 0 and remembers the level; unmuting puts it back. Moving the slider from 0 unmutes. */\nexport function VolumeControl({ volume, onVolumeChange, max = 100, disabled, className }: VolumeControlProps) {\n const last = React.useRef(volume > 0 ? volume : 100);\n if (volume > 0) last.current = volume;\n const muted = volume === 0;\n return (\n <div className={cn(\"flex items-center gap-2\", className)}>\n <IconButton icon={muted ? VolumeX : Volume2} label={muted ? \"Unmute\" : \"Mute\"} hint=\"M\" disabled={disabled} onClick={() => onVolumeChange(muted ? last.current : 0)} />\n <Slider aria-label=\"Volume\" value={volume} onChange={onVolumeChange} min={0} max={max} unit=\"%\" disabled={disabled} className=\"w-40\" />\n </div>\n );\n}\n\n/** A choice of playback speed (\"0.5×\", \"1×\", \"1.5×\") on a native select, named \"Playback speed\". */\nexport function RateChoice({ rate, onRateChange, rates = [0.5, 1, 1.25, 1.5, 2], className }: { rate: number; onRateChange: (rate: number) => void; rates?: readonly number[]; className?: string }) {\n return (\n <NativeSelect aria-label=\"Playback speed\" value={String(rate)} onChange={(e) => onRateChange(Number(e.target.value))} className={cn(\"w-auto\", className)}>\n {rates.map((r) => (\n <option key={r} value={String(r)}>\n {`${r}×`}\n </option>\n ))}\n </NativeSelect>\n );\n}\n\n/**\n * The shortcuts a player takes, as one list for `useHotkeys` and `KeysLegend`: Space and K play\n * or pause, J and L go back or forward `jump` seconds, the arrows by `frame` seconds, Home and End\n * to the ends, M mutes. Pass the player's actions; the labels are the legend's words.\n */\nexport function transportShortcuts({ toggle, seek, time, duration, frame = 1 / 30, jump = 1, toggleMute }: { toggle: () => void; seek: (time: number) => void; time: number; duration: number; frame?: number; jump?: number; toggleMute?: () => void }): Shortcut[] {\n const to = (t: number) => () => seek(clamp(t, 0, duration));\n return [\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: toggle },\n { keys: [\"j\"], label: `Back ${jump} s`, run: to(time - jump), repeat: true },\n { keys: [\"l\"], label: `Forward ${jump} s`, run: to(time + jump), repeat: true },\n { keys: [\"ArrowLeft\"], label: \"Back one frame\", run: to(time - frame), repeat: true },\n { keys: [\"ArrowRight\"], label: \"Forward one frame\", run: to(time + frame), repeat: true },\n { keys: [\"Home\"], label: \"Go to start\", run: to(0) },\n { keys: [\"End\"], label: \"Go to end\", run: to(duration) },\n ...(toggleMute ? [{ keys: [\"m\"], label: \"Mute\", run: toggleMute }] : []),\n ];\n}\n\n/** A frame that fits content of an aspect ratio into the pane, letterboxed on the sunken surface role (light and dark both), with room for the app's overlays. */\nexport function MediaStage({ aspect, children, label, className }: { aspect: number | `${number}/${number}`; children: React.ReactNode; label: string; className?: string }) {\n const outer = React.useRef<HTMLDivElement>(null);\n const [box, setBox] = React.useState<{ w: number; h: number } | null>(null);\n const ratio = typeof aspect === \"number\" ? aspect : (() => { const [w, h] = aspect.split(\"/\").map(Number); return w / h; })();\n React.useEffect(() => {\n const el = outer.current;\n if (!el) return;\n const read = () => setBox({ w: el.clientWidth, h: el.clientHeight });\n read();\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n // Contain-fit by arithmetic: CSS aspect-ratio with max-width breaks the ratio when the width is clamped.\n const fit = box && box.w > 0 && box.h > 0 ? (box.w / box.h > ratio ? { w: box.h * ratio, h: box.h } : { w: box.w, h: box.w / ratio }) : null;\n return (\n <div ref={outer} role=\"group\" aria-label={label} className={cn(\"grid min-h-0 min-w-0 place-items-center overflow-hidden bg-surface-sunken\", className)}>\n <div className=\"relative overflow-hidden bg-background\" style={fit ? { width: fit.w, height: fit.h } : { width: \"100%\", aspectRatio: String(ratio) }}>\n {children}\n </div>\n </div>\n );\n}\n\n/** Guides over a stage: action-safe and title-safe frames (90% and 80%), a centre cross and a rule-of-thirds grid. Drawn as two strokes (light over dark) so they read on any picture. */\nexport function StageGuides({ safe, thirds, centre, className }: { safe?: boolean; thirds?: boolean; centre?: boolean; className?: string }) {\n const lines: [number, number, number, number][] = [];\n if (thirds) lines.push([100 / 3, 0, 100 / 3, 100], [200 / 3, 0, 200 / 3, 100], [0, 100 / 3, 100, 100 / 3], [0, 200 / 3, 100, 200 / 3]);\n if (centre) lines.push([50, 46, 50, 54], [46, 50, 54, 50]);\n const rects = safe ? [5, 10] : [];\n const draw = (cls: string, w: number) => (\n <g className={cls} strokeWidth={w} fill=\"none\" vectorEffect=\"non-scaling-stroke\">\n {lines.map((l, i) => <line key={i} x1={l[0]} y1={l[1]} x2={l[2]} y2={l[3]} vectorEffect=\"non-scaling-stroke\" />)}\n {rects.map((m) => <rect key={m} x={m} y={m} width={100 - 2 * m} height={100 - 2 * m} vectorEffect=\"non-scaling-stroke\" />)}\n </g>\n );\n return (\n <svg aria-hidden viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className={cn(\"pointer-events-none absolute inset-0 size-full\", className)}>\n {draw(\"stroke-foreground\", 3)}\n {draw(\"stroke-background\", 1)}\n </svg>\n );\n}\n","import * as React from \"react\";\nimport { SkipBack, SkipForward } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\nimport { Alert } from \"./alert\";\nimport { Button, IconButton } from \"./button\";\nimport { useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { RateChoice, SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\n\n// Playing a file without writing the glue (strata-react issue #134, from strata-listory, whose two\n// players stayed `<audio controls>` because the parts of #78 take state in and requests out, and\n// every app that plays a file would write the same event handling). Two pieces, one on the other:\n//\n// - `useMediaElement(ref)` owns the element's state. It listens to the events a player needs\n// (`timeupdate`, `durationchange`, `progress`, `play`, `pause`, `ended`, `volumechange`,\n// `ratechange`, `waiting`, `error`, and the ones that say loading has started or finished) and\n// hands back plain values that spread straight into `Transport`, `SeekBar`, `TimeReadout`,\n// `VolumeControl` and `RateChoice`, and the requests (`play`, `pause`, `toggle`, `seek`,\n// `setVolume`, `setRate`, `retry`). It catches the rejection of `play()` (autoplay refused) into\n// `error` instead of an unhandled promise, applies a seek made before the metadata has loaded\n// once it has, and gives `duration` as `null` until it is known (a stream says `NaN` or `Infinity`),\n// so `SeekBar` draws a disabled bar with an en dash and no thumb stuck at 0. It only listens, so it\n// reads an element drawn with the browser's own controls just as well.\n// - `MediaPlayer` is the 90% case: the element, the hook, the parts and the keys. `controls` is\n// `\"auto\"` (the browser's own bar on a touch device, `(pointer: coarse)`, Strata's on a desktop),\n// `\"native\"` or `\"strata\"`. Native stays an option because the browser's bar brings what a custom\n// one will not (lock-screen and headset controls, AirPlay and Cast, picture in picture, caption\n// menus); `session` sets `navigator.mediaSession` for the same reason. The stack table's rule,\n// \"native elements stay where the platform does it better\", applies to playback of a file.\n// - A sequence (chapters, a playlist) is `sources`: ending moves to the next and keeps playing by\n// changing the element's `src`, never remounting it, because a browser allows playback to continue\n// only on an element the person has already started. When every source gives its `duration` the\n// seek bar spans the whole sequence, with a mark at each source's title; otherwise it spans the\n// current one.\n//\n// Checked: React Aria has no media element hook (its `VisuallyHidden`, `useSlider` and toolbar are\n// what the parts are built on), so the hook is ours. Volume is 0 to 100 and 0 is muted, the way\n// `VolumeControl` has it; unmuting restores the element's own level.\n\n/** Why a player is not playing, for the app to word. */\nexport type MediaProblem = { kind: \"load\"; message: string } | { kind: \"blocked\"; message: string };\n\n/** What `useMediaElement` returns: the element's state as values, and the requests a player makes of it. */\nexport type MediaElementState = {\n playing: boolean;\n /** Seconds. */\n time: number;\n /** Seconds, or null until the element knows it (a stream reports NaN or Infinity). */\n duration: number | null;\n /** Seconds buffered from the start of the range holding `time`. */\n buffered: number;\n /** 0 to 100; 0 while muted. */\n volume: number;\n muted: boolean;\n rate: number;\n ended: boolean;\n /** Waiting for data (the first load, or a seek into what is not buffered yet). */\n loading: boolean;\n error: MediaProblem | null;\n play: () => Promise<void>;\n pause: () => void;\n toggle: () => void;\n /** Seeks; before the metadata has loaded, remembers the time and applies it when it has. */\n seek: (time: number) => void;\n /** 0 to 100. 0 mutes; more unmutes at that level. */\n setVolume: (volume: number) => void;\n setRate: (rate: number) => void;\n /** Loads again, and plays if it was playing. For the error state's \"Try again\". */\n retry: () => void;\n};\n\ntype Snapshot = Omit<MediaElementState, \"play\" | \"pause\" | \"toggle\" | \"seek\" | \"setVolume\" | \"setRate\" | \"retry\">;\n\nconst idle: Snapshot = { playing: false, time: 0, duration: null, buffered: 0, volume: 100, muted: false, rate: 1, ended: false, loading: false, error: null };\n\nconst LOAD_MESSAGES: Record<number, string> = {\n 2: \"The connection dropped while it was loading.\",\n 3: \"The file could not be decoded.\",\n 4: \"This format is not supported or the file is not there.\",\n};\n\nfunction bufferedAhead(el: HTMLMediaElement) {\n const ranges = el.buffered;\n for (let i = 0; i < ranges.length; i++) if (el.currentTime >= ranges.start(i) && el.currentTime <= ranges.end(i)) return ranges.end(i);\n return 0;\n}\n\n// Subscribes while an element is mounted, and again if the ref later holds another one (a player that\n// changes `kind` replaces its DOM node, and the old node's listeners are gone with it).\nfunction useElementListeners(ref: React.RefObject<HTMLMediaElement | null>, bind: (el: HTMLMediaElement) => () => void) {\n const bound = React.useRef<{ el: HTMLMediaElement; unbind: () => void } | null>(null);\n const latest = React.useRef(bind);\n latest.current = bind;\n // No dependency list on purpose: a ref changing does not render, but whatever replaced the node did.\n React.useEffect(() => {\n const el = ref.current;\n if (bound.current?.el === el) return;\n bound.current?.unbind();\n bound.current = el ? { el, unbind: latest.current(el) } : null;\n });\n React.useEffect(\n () => () => {\n bound.current?.unbind();\n bound.current = null;\n },\n [],\n );\n}\n\nconst EVENTS = [\n \"loadstart\", \"loadedmetadata\", \"durationchange\", \"timeupdate\", \"progress\", \"play\", \"playing\", \"pause\", \"ended\",\n \"volumechange\", \"ratechange\", \"seeking\", \"seeked\", \"waiting\", \"canplay\", \"emptied\", \"error\",\n] as const;\n\n/** Follows an `<audio>` or `<video>` and returns its state and the requests a player makes. Works with the browser's own controls too. */\nexport function useMediaElement(ref: React.RefObject<HTMLMediaElement | null>): MediaElementState {\n const [snapshot, setSnapshot] = React.useState<Snapshot>(idle);\n const blocked = React.useRef<MediaProblem | null>(null);\n const pendingSeek = React.useRef<number | null>(null);\n\n const read = React.useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const finite = Number.isFinite(el.duration) && el.duration > 0;\n let error: MediaProblem | null = blocked.current;\n // Code 1 is the load being abandoned on purpose (a new src), not a failure.\n if (el.error && el.error.code !== 1) error = { kind: \"load\", message: LOAD_MESSAGES[el.error.code] ?? \"It could not be played.\" };\n const next: Snapshot = {\n playing: !el.paused && !el.ended,\n time: Number.isFinite(el.currentTime) ? el.currentTime : 0,\n duration: finite ? el.duration : null,\n buffered: bufferedAhead(el),\n volume: el.muted ? 0 : Math.round(el.volume * 100),\n muted: el.muted,\n rate: el.playbackRate,\n ended: el.ended,\n loading: !error && el.networkState === 2 && el.readyState < 3 && !el.paused,\n error,\n };\n setSnapshot((previous) => (Object.keys(next) as (keyof Snapshot)[]).every((k) => Object.is(previous[k], next[k]) || (k === \"error\" && previous.error?.message === next.error?.message && previous.error?.kind === next.error?.kind)) ? previous : next);\n }, [ref]);\n\n useElementListeners(ref, (el) => {\n const on = (e: Event) => {\n if (e.type === \"play\" || e.type === \"playing\") blocked.current = null;\n if (e.type === \"loadedmetadata\" && pendingSeek.current !== null) {\n el.currentTime = pendingSeek.current;\n pendingSeek.current = null;\n }\n if (e.type === \"emptied\" || e.type === \"loadstart\") blocked.current = null;\n read();\n };\n for (const type of EVENTS) el.addEventListener(type, on);\n read();\n return () => {\n for (const type of EVENTS) el.removeEventListener(type, on);\n };\n });\n\n return React.useMemo<MediaElementState>(() => {\n const play = async () => {\n const el = ref.current;\n if (!el) return;\n try {\n await el.play();\n } catch (e) {\n // A load error also rejects play(); it is reported through the element's own error.\n if (e instanceof DOMException && e.name === \"NotAllowedError\") {\n blocked.current = { kind: \"blocked\", message: \"The browser blocked playback until you press Play.\" };\n read();\n } else if (!(e instanceof DOMException && e.name === \"AbortError\")) read();\n }\n };\n return {\n ...snapshot,\n play,\n pause: () => ref.current?.pause(),\n toggle: () => {\n const el = ref.current;\n if (!el) return;\n if (el.paused || el.ended) void play();\n else el.pause();\n },\n seek: (time) => {\n const el = ref.current;\n if (!el) return;\n if (el.readyState < 1) pendingSeek.current = Math.max(0, time);\n else el.currentTime = Math.max(0, Number.isFinite(el.duration) ? Math.min(time, el.duration) : time);\n read();\n },\n setVolume: (volume) => {\n const el = ref.current;\n if (!el) return;\n const v = Math.min(Math.max(volume, 0), 100);\n el.muted = v === 0;\n if (v > 0) el.volume = v / 100;\n },\n setRate: (rate) => {\n const el = ref.current;\n if (!el) return;\n // The default too: loading another source resets `playbackRate` to `defaultPlaybackRate`, which would drop the chosen speed at every chapter.\n el.defaultPlaybackRate = rate;\n el.playbackRate = rate;\n },\n retry: () => {\n const el = ref.current;\n if (!el) return;\n const resume = !el.paused;\n const at = el.currentTime;\n blocked.current = null;\n el.load();\n if (at > 0) pendingSeek.current = at;\n read();\n if (resume) void play();\n },\n };\n }, [snapshot, ref, read]);\n}\n\n/** One file in a sequence. */\nexport type MediaSource = {\n src: string;\n /** Names the source on the seek bar's marks and in \"Chapter 2 of 5\". */\n title: string;\n /** Seconds. When every source gives it, the seek bar spans the whole sequence. */\n duration?: number;\n};\n\n/** Lock-screen and headset metadata (`navigator.mediaSession`). */\nexport type MediaSession = { title: string; artist?: string; album?: string; artwork?: string };\n\nexport type MediaPlayerProps = {\n /** Names the player and its element. */\n label: string;\n kind?: \"audio\" | \"video\";\n /** One file. */\n src?: string;\n /** Or a sequence; ending moves to the next and keeps playing. */\n sources?: readonly MediaSource[];\n /** The current source, when the app holds it (a chapter list beside the player). */\n index?: number;\n onIndexChange?: (index: number) => void;\n /** Move to the next source when one ends. Default true. */\n autoAdvance?: boolean;\n /** `\"auto\"`: the browser's controls on a touch device, Strata's on a desktop. Default. */\n controls?: \"auto\" | \"native\" | \"strata\";\n autoPlay?: boolean;\n poster?: string;\n session?: MediaSession;\n /** The playback speeds offered. Default 0.5 to 2; for speech use {@link SPEECH_RATES}. */\n rates?: readonly number[];\n /** Keys on the page (Space or K, J and L for 10 s, M). Default true; turn off when the screen binds its own. With several players on a page the keys go to the one last played, focused or pressed. */\n shortcuts?: boolean;\n /** The last source has ended. */\n onEnded?: () => void;\n /** Called as the element plays, with the time in the whole sequence. */\n onTimeChange?: (time: number) => void;\n className?: string;\n};\n\n// Which player the page's keys belong to. A page with one player binds them for it, as ever. With\n// several, binding Space once per player played and paused every one of them at once, so the keys go\n// to the player last used (played, focused or pressed) and the others leave them alone (issue #147,\n// from strata-models' blind A/B of two voices). A tiny store outside React so the players on a page\n// can see each other without a provider the app would have to add.\nconst keyPlayers = (() => {\n const ids = new Set<string>();\n let active: string | null = null;\n let warned = false;\n const listeners = new Set<() => void>();\n let snapshot = { count: 0, active: null as string | null };\n const emit = () => {\n snapshot = { count: ids.size, active };\n listeners.forEach((l) => l());\n };\n return {\n subscribe: (l: () => void) => {\n listeners.add(l);\n return () => void listeners.delete(l);\n },\n get: () => snapshot,\n add(id: string) {\n ids.add(id);\n if (ids.size === 2 && !warned && typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\") {\n warned = true;\n console.warn(\"strata-react: several MediaPlayers are on this page, so Space, K, J, L and M go to the one last played or focused. Pass shortcuts={false} to one you bind your own keys for.\");\n }\n emit();\n },\n remove(id: string) {\n ids.delete(id);\n if (active === id) active = null;\n emit();\n },\n use(id: string) {\n // A player with shortcuts off is not registered and must not take the keys from the others.\n if (active === id || !ids.has(id)) return;\n active = id;\n emit();\n },\n };\n})();\n\n/** Playback speeds an audiobook or lecture listener expects. */\nexport const SPEECH_RATES: readonly number[] = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3];\n\nconst JUMP = 10;\n\nfunction useCoarsePointer() {\n const [coarse, setCoarse] = React.useState(false);\n React.useEffect(() => {\n if (typeof matchMedia !== \"function\") return;\n const query = matchMedia(\"(pointer: coarse)\");\n const read = () => setCoarse(query.matches);\n read();\n query.addEventListener?.(\"change\", read);\n return () => query.removeEventListener?.(\"change\", read);\n }, []);\n return coarse;\n}\n\n/**\n * Plays a file or a sequence: the element, its state, and Strata's controls (or the browser's own on\n * a touch device), with the failure to load shown and retried. For an editor or a replay, use the\n * parts and `useMediaElement` directly.\n */\nexport function MediaPlayer({\n label,\n kind = \"audio\",\n src,\n sources,\n index: controlledIndex,\n onIndexChange,\n autoAdvance = true,\n controls = \"auto\",\n autoPlay,\n poster,\n session,\n rates,\n shortcuts = true,\n onEnded,\n onTimeChange,\n className,\n}: MediaPlayerProps) {\n const list = React.useMemo<readonly MediaSource[]>(() => sources ?? (src ? [{ src, title: label }] : []), [sources, src, label]);\n const [ownIndex, setOwnIndex] = React.useState(0);\n const index = Math.min(controlledIndex ?? ownIndex, Math.max(list.length - 1, 0));\n const current = list[index];\n const ref = React.useRef<HTMLMediaElement>(null);\n const media = useMediaElement(ref);\n const coarse = useCoarsePointer();\n const native = controls === \"native\" || (controls === \"auto\" && coarse);\n\n const go = React.useCallback(\n (to: number) => {\n if (controlledIndex === undefined) setOwnIndex(to);\n onIndexChange?.(to);\n },\n [controlledIndex, onIndexChange],\n );\n // Changing src on the same element: whether to carry on playing, and where to start, are applied once the new file is loaded.\n const resume = React.useRef(false);\n const startAt = React.useRef<number | null>(null);\n const keep = React.useRef({ index, playing: media.playing, go, onEnded, autoAdvance, last: list.length - 1 });\n keep.current = { index, playing: media.playing, go, onEnded, autoAdvance, last: list.length - 1 };\n\n const wasSrc = React.useRef(current?.src);\n React.useEffect(() => {\n if (wasSrc.current === current?.src) return;\n wasSrc.current = current?.src;\n const el = ref.current;\n if (!el) return;\n if (startAt.current !== null) {\n media.seek(startAt.current);\n startAt.current = null;\n }\n if (resume.current) {\n resume.current = false;\n void media.play();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [current?.src]);\n\n const onEnd = React.useCallback(() => {\n const k = keep.current;\n if (k.autoAdvance && k.index < k.last) {\n resume.current = true;\n k.go(k.index + 1);\n } else k.onEnded?.();\n }, []);\n useElementListeners(ref, (el) => {\n el.addEventListener(\"ended\", onEnd);\n return () => el.removeEventListener(\"ended\", onEnd);\n });\n\n // The sequence as one timeline, when every source says how long it is.\n const offsets = React.useMemo(() => {\n if (list.length < 2 || !list.every((s) => s.duration && s.duration > 0)) return null;\n let at = 0;\n return list.map((s) => {\n const start = at;\n at += s.duration!;\n return start;\n });\n }, [list]);\n const total = offsets ? offsets[offsets.length - 1] + list[list.length - 1].duration! : null;\n const time = (offsets ? offsets[index] : 0) + media.time;\n const duration = total ?? media.duration;\n\n const seek = (t: number) => {\n if (!offsets) return media.seek(t);\n let to = offsets.length - 1;\n while (to > 0 && offsets[to] > t) to--;\n if (to === index) return media.seek(t - offsets[to]);\n resume.current = media.playing;\n startAt.current = t - offsets[to];\n go(to);\n };\n const step = (by: number) => {\n const to = index + by;\n if (to < 0 || to > list.length - 1) return;\n resume.current = media.playing;\n go(to);\n };\n\n React.useEffect(() => {\n if (onTimeChange) onTimeChange(time);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [time]);\n\n const keys = React.useMemo<Shortcut[]>(\n () => [\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: media.toggle },\n { keys: [\"j\"], label: `Back ${JUMP} s`, run: () => seek(time - JUMP), repeat: true },\n { keys: [\"l\"], label: `Forward ${JUMP} s`, run: () => seek(time + JUMP), repeat: true },\n { keys: [\"m\"], label: \"Mute\", run: () => media.setVolume(media.muted ? 100 : 0) },\n ],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [media, time, offsets, index],\n );\n // Several players on a page: the keys follow the last used (see keyPlayers); alone, they are this one's.\n const id = React.useId();\n React.useEffect(() => {\n if (!shortcuts || native) return;\n keyPlayers.add(id);\n return () => keyPlayers.remove(id);\n }, [id, shortcuts, native]);\n const page = React.useSyncExternalStore(keyPlayers.subscribe, keyPlayers.get, keyPlayers.get);\n React.useEffect(() => {\n if (media.playing && shortcuts && !native) keyPlayers.use(id);\n }, [media.playing, id, shortcuts, native]);\n useHotkeys(keys, { enabled: shortcuts && !native && (page.count <= 1 || page.active === id) });\n\n // Lock-screen and headset controls.\n React.useEffect(() => {\n if (!session || typeof navigator === \"undefined\" || !(\"mediaSession\" in navigator) || typeof MediaMetadata === \"undefined\") return;\n const s = navigator.mediaSession;\n s.metadata = new MediaMetadata({ title: current?.title ?? session.title, artist: session.artist, album: session.album ?? (list.length > 1 ? session.title : undefined), artwork: session.artwork ? [{ src: session.artwork }] : [] });\n return () => {\n s.metadata = null;\n };\n }, [session, current?.title, list.length]);\n React.useEffect(() => {\n if (!session || typeof navigator === \"undefined\" || !(\"mediaSession\" in navigator)) return;\n const s = navigator.mediaSession;\n const set = (action: MediaSessionAction, handler: MediaSessionActionHandler | null) => {\n try {\n s.setActionHandler(action, handler);\n } catch {\n // An action this browser does not offer.\n }\n };\n set(\"play\", () => void media.play());\n set(\"pause\", media.pause);\n set(\"seekbackward\", () => seek(time - JUMP));\n set(\"seekforward\", () => seek(time + JUMP));\n set(\"previoustrack\", index > 0 ? () => step(-1) : null);\n set(\"nexttrack\", index < list.length - 1 ? () => step(1) : null);\n return () => {\n for (const a of [\"play\", \"pause\", \"seekbackward\", \"seekforward\", \"previoustrack\", \"nexttrack\"] as const) set(a, null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session, media, time, index, list.length]);\n\n const common = { ref: ref as React.Ref<never>, src: current?.src, controls: native, autoPlay, preload: \"metadata\" as const, \"aria-label\": `${label}, ${kind}` };\n const element = kind === \"video\" ? <video {...common} poster={poster} playsInline className=\"w-full rounded-surface bg-surface-sunken\" /> : <audio {...common} className={native ? \"w-full\" : \"hidden\"} />;\n const what = kind === \"video\" ? \"this video\" : \"this recording\";\n\n return (\n <div role=\"group\" aria-label={label} onFocusCapture={() => keyPlayers.use(id)} onPointerDownCapture={() => keyPlayers.use(id)} className={cn(\"grid w-full gap-2\", className)}>\n {element}\n {media.error?.kind === \"load\" && (\n <Alert\n tone=\"danger\"\n announce\n title={`Could not load ${what}`}\n action={\n <Button size=\"sm\" variant=\"outline\" onClick={media.retry}>\n Try again\n </Button>\n }\n >\n {media.error.message}\n </Alert>\n )}\n {media.error?.kind === \"blocked\" && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {media.error.message}\n </p>\n )}\n {!native && (\n <div className=\"grid gap-2\">\n <div className=\"flex min-w-0 items-center gap-3\">\n <SeekBar\n time={time}\n duration={duration}\n onSeek={seek}\n buffered={offsets ? undefined : media.buffered}\n marks={offsets ? list.map((s, i) => ({ time: offsets[i], label: s.title })).slice(1) : []}\n step={JUMP}\n bigStep={60}\n label={`Seek in ${label}`}\n />\n <TimeReadout time={time} duration={duration} />\n </div>\n <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2\">\n <Transport playing={media.playing} onPlayPause={media.toggle}>\n {list.length > 1 && <IconButton icon={SkipBack} label=\"Previous chapter\" disabled={index === 0} onClick={() => step(-1)} />}\n {list.length > 1 && <IconButton icon={SkipForward} label=\"Next chapter\" disabled={index === list.length - 1} onClick={() => step(1)} />}\n </Transport>\n {list.length > 1 && (\n <span className=\"type-body-sm text-muted-foreground\">\n {current?.title} ({index + 1} of {list.length})\n </span>\n )}\n <span className=\"ml-auto flex items-center gap-3\">\n <RateChoice rate={media.rate} onRateChange={media.setRate} rates={rates} />\n <VolumeControl volume={media.volume} onVolumeChange={media.setVolume} />\n </span>\n </div>\n </div>\n )}\n </div>\n );\n}\n","// The arithmetic of a time axis, kept apart from drawing so it can be tested without a layout\n// (strata issue #77). Times are numbers in one unit the app picks (seconds for media, minutes or\n// hours for a schedule); `pxPerUnit` is the zoom.\n\n/** Steps a person would write on a scale, in seconds: 1, 2, 5 and 10 × 10ⁿ below a minute, then 15 s, 30 s, minutes, quarter hours, hours, days. ux-research components.md §3.8: ticks land on values people would write. */\nconst STEPS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 14400, 21600, 43200, 86400];\n\n/** The smallest step whose ticks are at least `minGapPx` apart at this zoom, so labels thin out instead of colliding. */\nexport function tickStep(pxPerUnit: number, minGapPx = 80): number {\n return STEPS.find((s) => s * pxPerUnit >= minGapPx) ?? STEPS[STEPS.length - 1];\n}\n\n/** Tick times from `from` to `to` inclusive, on multiples of `step`. */\nexport function ticksBetween(from: number, to: number, step: number): number[] {\n const out: number[] = [];\n const first = Math.ceil(from / step - 1e-9);\n for (let i = first; i * step <= to + 1e-9; i++) out.push(Math.round(i * step * 1e6) / 1e6 || 0);\n return out;\n}\n\n/** A tick's label: m:ss, h:mm:ss, with tenths or hundredths when the step is under a second. */\nexport function tickLabel(time: number, step: number): string {\n const decimals = step < 0.1 ? 2 : step < 1 ? 1 : 0;\n const whole = Math.floor(time + 1e-9);\n const h = Math.floor(whole / 3600);\n const m = Math.floor((whole % 3600) / 60);\n const s = whole % 60;\n const two = (n: number) => String(n).padStart(2, \"0\");\n const base = h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`;\n return decimals ? `${base}.${String(Math.round((time - whole) * 10 ** decimals)).padStart(decimals, \"0\")}` : base;\n}\n\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/** The point to snap `time` to: the nearest of `points` within `thresholdPx` at this zoom, or `null`. */\nexport function snapTo(time: number, points: readonly number[], pxPerUnit: number, thresholdPx = 8): { time: number; point: number } | null {\n let best: number | null = null;\n for (const p of points) if (Math.abs(p - time) * pxPerUnit <= thresholdPx && (best === null || Math.abs(p - time) < Math.abs(best - time))) best = p;\n return best === null ? null : { time: best, point: best };\n}\n\n/** Round away float noise from adding steps (0.1 + 0.2). */\nexport const tidy = (n: number) => Math.round(n * 1e6) / 1e6;\n","import * as React from \"react\";\nimport { VisuallyHidden, mergeProps, useDrop, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport type { DropItem } from \"react-aria-components\";\nimport { useSliderState } from \"react-stately\";\nimport { Ban, Maximize2, ZoomIn, ZoomOut } from \"lucide-react\";\nimport { clamp, snapTo, tickLabel, tickStep, ticksBetween, tidy } from \"../lib/timeline\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\n\n// A time axis with lanes of items (strata issue #77, from a video editor's timeline; the research's\n// own example is a kiln schedule). Video and audio editors, rotas, resource bookings, Gantt-style\n// plans and deployment timelines are the same picture: a ruler, lanes, items with a start and a\n// length, a current-time line, markers.\n//\n// The component draws and the app decides. Every change (move, trim, change lane, set the current\n// time, select) is reported through a callback and applied by the app, so the app's own rules\n// (overlap, snapping to its grid, undo) stay in one place and the timeline never holds a second copy\n// of the data. A change the app refuses (`validate` returns a reason) is shown while it is being\n// made, with an icon and the reason in words, and is not reported.\n//\n// Keyboard first (the issue found nothing but Delete working). One tab stop for the items, with the\n// focus moving inside it: Left and Right go to the previous and next item in the lane, Up and Down\n// to the nearest in the lane above or below, Home and End to the lane's first and last. Enter or\n// Space selects (with Ctrl or Shift, adds to the selection). On the focused item: Ctrl+Left/Right\n// nudge it by `step` (Shift: ten steps), Ctrl+Up/Down move it a lane, Alt+Left/Right trim the end,\n// Alt+Shift+Left/Right trim the start, Delete asks the app to remove the selection. The current time\n// is React Aria's slider hooks, with the ruler as its track and the marker as its thumb (a press or\n// drag on the ruler moves it; arrows `step`, Shift ten steps, Page keys ten, Home and End the limits\n// are a capture handler on its input, because the hooks have one step and a drag needs a fine one; the\n// value is spoken through `formatTime`, which `Intl.NumberFormat` options cannot do).\n// `+`, `-` and `0` zoom in, out and to fit when `onZoomChange` is given. Every change is announced\n// politely in words: \"run-02.mp4 moved to 0:14, Track 1\".\n//\n// Items are named for a screen reader as \"run-02.mp4, 0:12 to 0:47, Track 1\" and lanes are labelled\n// groups. The ruler's labels are chosen from a ladder of steps a person would write on a scale\n// (1, 2, 5, 10 s, 15 s, 30 s, minutes…) wide enough apart that they never collide, and the end\n// labels stay inside the axis (components.md §3.8). Nothing animates on zoom, scroll or move: these\n// are the most repeated actions on the screen (ux-character.md, by frequency).\n//\n// Performance: items outside the visible window, plus a margin, are not rendered, so thousands of\n// items cost what is on screen. Widths come from the props (`zoom` is pixels per unit) and one\n// ResizeObserver reading the viewport, not from measuring items.\n//\n// Drops from outside (issue #121, strata-vid's library list). Each lane is a React Aria `useDrop`\n// target, so the pointer path, the keyboard path (React Aria's virtual drag: the lane takes focus\n// and Enter drops) and the screen-reader announcements are its. Checked in `useDrop.d.ts` and\n// `DragManager`: while a drag is over a lane the types are known but the items are not, so the\n// preview is `dropLength` long and the app learns what was dropped only in `onDrop`. A pointer\n// drop lands with its left edge at the pointer, snapped like a move; a virtual drop reports the\n// lane's centre, not a time (and in a different coordinate space from a pointer's), so it is told\n// apart by the lane being the focused element and lands at the current time (`position`, else the\n// start). `validateDrop` is `validate` for a drop: the refusal shows beside the preview while it is\n// over a lane and is announced for the keyboard.\n//\n// Pointer moves are our own pointer events with a 3px threshold between click and drag. React\n// Aria's `useMove` (in `react-aria`, a transitive dependency of `react-aria-components`) would do\n// the pointer and arrow-key deltas, but using it means listing `react-aria` as a direct\n// dependency, which is Jonathan's call (CLAUDE.md), so it is not done here; it is offered in the\n// PR. Native HTML drag and drop (#76's `SortableList`) is for lists and cannot give a live,\n// snapped, zoom-aware position along time, which is why this is not built on it.\n\nexport type TimelineItem = {\n id: string;\n /** The lane's id. */\n lane: string;\n start: number;\n length: number;\n /** The item's name, in the item and for a screen reader. */\n label: string;\n /** What kind of thing it is (video, audio, booking). Shown as a word and a colour stripe, never colour alone. Its colour is `kindColours[kind]`, else the chart palette in order of appearance. */\n kind?: string;\n};\n\nexport type TimelineLane = {\n id: string;\n label: string;\n /** The app's controls for the lane (mute, lock, delete). Drawn in the lane's header, at the left. */\n header?: React.ReactNode;\n};\n\nexport type TimelineMarker = { id: string; time: number; label: string };\n\n/** What a move or trim would produce. */\nexport type TimelineChange = { start: number; length: number; lane: string };\n\n/** Where something dragged in from outside landed. */\nexport type TimelineDrop = TimelineChange & { items: DropItem[] };\n\nexport type TimelineProps = {\n /** Names the timeline for a screen reader (\"Firing schedule\"). */\n label: string;\n lanes: readonly TimelineLane[];\n items: readonly TimelineItem[];\n /** The axis runs from this time. Default 0. */\n from?: number;\n /** ... to this time. */\n to: number;\n /** Pixels per unit of time. Controlled with `onZoomChange`. */\n zoom: number;\n onZoomChange?: (zoom: number) => void;\n /** The current time, drawn as a rule across the lanes and set by the slider on the ruler. */\n position?: number;\n onPositionChange?: (time: number) => void;\n /** Keep the current time in view as it advances. */\n follow?: boolean;\n markers?: readonly TimelineMarker[];\n selectedIds?: ReadonlySet<string>;\n /** The selection changed: `ids` is the whole new selection. */\n onSelect?: (ids: string[]) => void;\n /** The item was moved, trimmed or put in another lane. Not called for a change `validate` refused. */\n onItemChange?: (id: string, next: TimelineChange) => void;\n /** The person asked to remove the selection (Delete). The app does it, undoably. */\n onDelete?: (ids: string[]) => void;\n /** A reason a change cannot be made, in the product's words, or `null`. Called while dragging, so keep it cheap. */\n validate?: (id: string, next: TimelineChange) => string | null;\n /** Extra times items snap to, besides the edges of other items, markers and the current time. */\n snapPoints?: readonly number[];\n /** Turn snapping off. Default on. */\n snap?: boolean;\n /** One keyboard step, in time units. Default 1. */\n step?: number;\n /** Smallest an item may be, in time units. Default `step`. */\n minLength?: number;\n /** The colour of each kind's stripe, chosen by the app: a CSS colour, normally a role or a subject colour of its theme (`var(--info)`, `var(--kind-gpx)`). Without an entry a kind takes the chart palette in order of appearance, which moves when the set of kinds changes. */\n kindColours?: Readonly<Record<string, string>>;\n /** How many control heights tall each lane is. Default 1; 2 or 3 for items that draw thumbnails or a waveform. */\n laneRows?: number;\n /** Drag types a lane accepts from outside the timeline (`\"text/plain\"`, an app type). Without it nothing can be dropped. */\n dropTypes?: readonly string[];\n /** Length of an item dropped from outside, for the preview and for `validateDrop`. Default five steps. */\n dropLength?: number;\n /** Something was dropped on a lane at a time (snapped like a move). The app makes the item. Not called for a drop `validateDrop` refused. */\n onDrop?: (drop: TimelineDrop) => void;\n /** A reason a drop cannot be made, in the product's words, or `null`. Called while a drag is over a lane, so keep it cheap. */\n validateDrop?: (next: TimelineChange) => string | null;\n /** Draws an item's content (a strip of thumbnails, a waveform). Default: the label and kind. */\n renderItem?: (item: TimelineItem, state: { selected: boolean; width: number }) => React.ReactNode;\n /** A time as words (\"0:14\", \"13:30\"). Default `m:ss`, with tenths on the ruler when zoomed far in. Also labels the ruler when given, so a schedule in hours reads as clock times. */\n formatTime?: (time: number) => string;\n /** Shown instead of the lanes' area when there are no lanes. */\n empty?: React.ReactNode;\n className?: string;\n};\n\nconst EDGE_PX = 8;\nconst DRAG_THRESHOLD = 3;\n\nconst defaultFormat = (t: number) => tickLabel(t, 1);\n\ntype Drag = { id: string; mode: \"move\" | \"start\" | \"end\"; originX: number; origin: TimelineItem; next: TimelineChange; reason: string | null; guide: number | null; moved: boolean };\n\n/** Zoom state for a timeline: `zoomIn`, `zoomOut`, and `fit` to a viewport width. Pass `zoom` and `setZoom` as the timeline's `zoom` and `onZoomChange`. */\nexport function useTimelineZoom({ initial = 20, min = 0.5, max = 400 }: { initial?: number; min?: number; max?: number } = {}) {\n const [zoom, set] = React.useState(initial);\n const setZoom = React.useCallback((z: number) => set(clamp(z, min, max)), [min, max]);\n return {\n zoom,\n setZoom,\n zoomIn: () => setZoom(zoom * 1.5),\n zoomOut: () => setZoom(zoom / 1.5),\n /** Zoom so `duration` fills `viewportWidth` pixels. */\n fit: (viewportWidth: number, duration: number) => setZoom(viewportWidth / Math.max(duration, 1e-6)),\n };\n}\n\n/** Zoom in, zoom out and fit, as named icon buttons for a timeline's toolbar. */\nexport function TimelineZoomControls({ zoom }: { zoom: Pick<ReturnType<typeof useTimelineZoom>, \"zoomIn\" | \"zoomOut\"> & { fit: () => void } }) {\n return (\n <div className=\"flex items-center gap-1\">\n <IconButton icon={ZoomOut} label=\"Zoom out\" hint=\"-\" onClick={zoom.zoomOut} />\n <IconButton icon={ZoomIn} label=\"Zoom in\" hint=\"+\" onClick={zoom.zoomIn} />\n <IconButton icon={Maximize2} label=\"Fit to view\" hint=\"0\" onClick={zoom.fit} />\n </div>\n );\n}\n\n/** A rule that refuses an item overlapping another in its lane, for `validate`: names the item in the way. */\nexport function noOverlap(items: readonly TimelineItem[]): (id: string, next: TimelineChange) => string | null {\n return (id, next) => {\n const me = items.find((i) => i.id === id);\n const other = items.find((i) => i.id !== id && i.lane === next.lane && i.start < next.start + next.length - 1e-9 && next.start < i.start + i.length - 1e-9);\n return other ? `${me?.label ?? \"This\"} would overlap ${other.label}.` : null;\n };\n}\n\n/** Items placed on a zoomable time axis in lanes, with a current-time rule and markers. Reports every move, trim, selection and time change; the app applies them. Keyboard-complete, and only the items near the view are rendered. */\nexport function Timeline({\n label,\n lanes,\n items,\n from = 0,\n to,\n zoom,\n onZoomChange,\n position,\n onPositionChange,\n follow,\n markers = [],\n selectedIds,\n onSelect,\n onItemChange,\n onDelete,\n validate,\n snapPoints = [],\n snap = true,\n step = 1,\n minLength,\n renderItem,\n kindColours,\n laneRows = 1,\n dropTypes,\n dropLength,\n onDrop,\n validateDrop,\n formatTime = defaultFormat,\n empty,\n className,\n}: TimelineProps) {\n const min = minLength ?? step;\n const scroller = React.useRef<HTMLDivElement>(null);\n const laneRefs = React.useRef(new Map<string, HTMLElement>());\n const [view, setView] = React.useState({ left: 0, width: 640 });\n const [drag, setDrag] = React.useState<Drag | null>(null);\n const dragRef = React.useRef<Drag | null>(null);\n const [focusId, setFocusId] = React.useState<string | null>(null);\n const [said, setSaid] = React.useState(\"\");\n const [hover, setHover] = React.useState<{ next: TimelineChange; reason: string | null; guide: number | null } | null>(null);\n const refocus = React.useRef<string | null>(null);\n const selected = selectedIds ?? new Set<string>();\n const laneIndex = React.useMemo(() => new Map(lanes.map((l, i) => [l.id, i])), [lanes]);\n const laneLabel = (id: string) => lanes.find((l) => l.id === id)?.label ?? id;\n const width = Math.max((to - from) * zoom, 1);\n const x = (t: number) => (t - from) * zoom;\n\n // The viewport: its width, and where it is scrolled. Items outside it (plus a margin of one\n // viewport on each side) are not rendered.\n React.useEffect(() => {\n const el = scroller.current;\n if (!el) return;\n const read = () => setView({ left: el.scrollLeft, width: el.clientWidth || 640 });\n read();\n const ro = new ResizeObserver(read);\n ro.observe(el);\n el.addEventListener(\"scroll\", read, { passive: true });\n return () => {\n ro.disconnect();\n el.removeEventListener(\"scroll\", read);\n };\n }, []);\n\n // Follow the current time: scroll only when it leaves the view, so a person who scrolled away to\n // look is not dragged back while it is still on screen.\n React.useEffect(() => {\n const el = scroller.current;\n if (!follow || position === undefined || !el) return;\n const px = x(position);\n if (px < el.scrollLeft || px > el.scrollLeft + el.clientWidth - 24) el.scrollLeft = Math.max(px - el.clientWidth * 0.25, 0);\n }, [follow, position, zoom]); // eslint-disable-line react-hooks/exhaustive-deps\n\n React.useEffect(() => {\n const id = refocus.current;\n if (!id) return;\n refocus.current = null;\n const el = scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`);\n if (el && document.activeElement !== el && (!document.activeElement || document.activeElement === document.body || !scroller.current?.contains(document.activeElement))) el.focus();\n }, [items]);\n\n const sorted = React.useMemo(() => {\n const byLane = new Map<string, TimelineItem[]>();\n for (const l of lanes) byLane.set(l.id, []);\n for (const i of items) byLane.get(i.lane)?.push(i);\n for (const list of byLane.values()) list.sort((a, b) => a.start - b.start);\n return byLane;\n }, [lanes, items]);\n\n const snapTimes = React.useMemo(() => {\n const pts = [...snapPoints, ...markers.map((m) => m.time)];\n if (position !== undefined) pts.push(position);\n return pts;\n }, [snapPoints, markers, position]);\n\n /** Apply a change: validate, report, and say it. Returns the refusal, if any. */\n const commit = (item: TimelineItem, next: TimelineChange): string | null => {\n const reason = validate?.(item.id, next) ?? null;\n if (reason) {\n setSaid(reason);\n return reason;\n }\n // A change of lane remounts the item's element in the new lane; put focus back on it once the app has applied the change.\n refocus.current = item.id;\n onItemChange?.(item.id, next);\n const where = next.lane !== item.lane ? `, ${laneLabel(next.lane)}` : \"\";\n setSaid(\n next.start !== item.start && next.length === item.length\n ? `${item.label} moved to ${formatTime(next.start)}${where}.`\n : next.lane !== item.lane\n ? `${item.label} moved to ${laneLabel(next.lane)}.`\n : `${item.label} now ${formatTime(next.start)} to ${formatTime(next.start + next.length)}.`,\n );\n return null;\n };\n\n const select = (id: string, add: boolean) => {\n const next = add ? (selected.has(id) ? [...selected].filter((s) => s !== id) : [...selected, id]) : [id];\n onSelect?.(next);\n };\n\n // --- keyboard on an item -------------------------------------------------------------------\n const focusItem = (id: string) => {\n setFocusId(id);\n requestAnimationFrame(() => scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`)?.focus());\n // jsdom has no layout and runs rAF late; focus now too when the element is already mounted.\n scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`)?.focus();\n const item = items.find((i) => i.id === id);\n if (item && scroller.current) {\n const el = scroller.current;\n if (x(item.start) < el.scrollLeft) el.scrollLeft = x(item.start) - 16;\n else if (x(item.start + item.length) > el.scrollLeft + el.clientWidth) el.scrollLeft = x(item.start + item.length) - el.clientWidth + 16;\n }\n };\n\n const onItemKeyDown = (e: React.KeyboardEvent, item: TimelineItem) => {\n const k = e.key;\n const big = e.shiftKey ? 10 : 1;\n const lane = sorted.get(item.lane) ?? [];\n const idx = lane.findIndex((i) => i.id === item.id);\n const handled = () => {\n e.preventDefault();\n e.stopPropagation();\n };\n if (e.ctrlKey || e.metaKey) {\n if (k === \"ArrowLeft\" || k === \"ArrowRight\") {\n handled();\n const dir = k === \"ArrowLeft\" ? -1 : 1;\n commit(item, { start: clamp(tidy(item.start + dir * step * big), from, to - item.length), length: item.length, lane: item.lane });\n } else if (k === \"ArrowUp\" || k === \"ArrowDown\") {\n handled();\n const target = lanes[(laneIndex.get(item.lane) ?? 0) + (k === \"ArrowUp\" ? -1 : 1)];\n if (target) commit(item, { start: item.start, length: item.length, lane: target.id });\n return;\n }\n // Ctrl or Cmd with Enter or Space adds to the selection; the switch below handles it.\n if (k !== \"Enter\" && k !== \" \") return;\n }\n if (e.altKey && (k === \"ArrowLeft\" || k === \"ArrowRight\")) {\n handled();\n const dir = k === \"ArrowLeft\" ? -1 : 1;\n if (e.shiftKey) {\n // Trim the start: Right shortens from the start, Left extends it.\n const start = clamp(tidy(item.start + dir * step), from, item.start + item.length - min);\n commit(item, { start, length: tidy(item.start + item.length - start), lane: item.lane });\n } else {\n commit(item, { start: item.start, length: clamp(tidy(item.length + dir * step), min, to - item.start), lane: item.lane });\n }\n return;\n }\n switch (k) {\n case \"ArrowLeft\":\n handled();\n if (lane[idx - 1]) focusItem(lane[idx - 1].id);\n break;\n case \"ArrowRight\":\n handled();\n if (lane[idx + 1]) focusItem(lane[idx + 1].id);\n break;\n case \"ArrowUp\":\n case \"ArrowDown\": {\n handled();\n const neighbour = lanes[(laneIndex.get(item.lane) ?? 0) + (k === \"ArrowUp\" ? -1 : 1)];\n const candidates = neighbour ? (sorted.get(neighbour.id) ?? []) : [];\n const nearest = candidates.reduce<TimelineItem | null>((best, c) => (!best || Math.abs(c.start - item.start) < Math.abs(best.start - item.start) ? c : best), null);\n if (nearest) focusItem(nearest.id);\n break;\n }\n case \"Home\":\n handled();\n if (lane[0]) focusItem(lane[0].id);\n break;\n case \"End\":\n handled();\n if (lane.length) focusItem(lane[lane.length - 1].id);\n break;\n case \"Enter\":\n case \" \":\n handled();\n select(item.id, e.shiftKey || e.ctrlKey || e.metaKey);\n break;\n case \"Delete\":\n case \"Backspace\":\n if (selected.size && onDelete) {\n handled();\n onDelete([...selected]);\n }\n break;\n }\n };\n\n /** Snaps an item of `length` starting at `start` to whichever of its ends is nearer an edge. */\n const snapMove = (start: number, length: number, exclude?: string) => {\n const edges = [...snapTimes, ...items.filter((i) => i.id !== exclude).flatMap((i) => [i.start, i.start + i.length])];\n const a = snap ? snapTo(start, edges, zoom) : null;\n const b = snap ? snapTo(start + length, edges, zoom) : null;\n if (a && (!b || Math.abs(a.time - start) <= Math.abs(b.time - (start + length)))) return { start: a.time, guide: a.point as number | null };\n if (b) return { start: b.time - length, guide: b.point as number | null };\n return { start, guide: null as number | null };\n };\n\n // --- drops from outside ----------------------------------------------------------------------\n const dropLen = dropLength ?? step * 5;\n const dropAt = (lane: string, px: number | null) => {\n const at = px === null ? (position ?? from) : from + px / zoom;\n const snapped = snapMove(at, dropLen);\n const next: TimelineChange = { start: clamp(tidy(snapped.start), from, Math.max(to - dropLen, from)), length: dropLen, lane };\n return { next, guide: snapped.guide, reason: validateDrop?.(next) ?? null };\n };\n const onLaneHover = (lane: string, px: number | null) => {\n const h = dropAt(lane, px);\n setHover(h);\n // A pointer sees the preview; the keyboard is told, as nothing else says where the drop would land.\n if (px === null) setSaid(h.reason ?? `Drop here: ${laneLabel(lane)} at ${formatTime(h.next.start)}.`);\n };\n const onLaneDrop = (lane: string, px: number | null, dropped: DropItem[]) => {\n setHover(null);\n const h = dropAt(lane, px);\n if (h.reason) {\n setSaid(h.reason);\n return;\n }\n onDrop?.({ ...h.next, items: dropped });\n setSaid(`Added at ${formatTime(h.next.start)}, ${laneLabel(lane)}.`);\n };\n const dropsOn = Boolean(dropTypes?.length && onDrop);\n\n // --- pointer: move and trim ----------------------------------------------------------------\n const begin = (e: React.PointerEvent, item: TimelineItem, mode: Drag[\"mode\"]) => {\n if (e.button !== 0) return;\n e.stopPropagation();\n (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);\n const d: Drag = { id: item.id, mode, originX: e.clientX, origin: item, next: { start: item.start, length: item.length, lane: item.lane }, reason: null, guide: null, moved: false };\n dragRef.current = d;\n setDrag(d);\n };\n\n const laneAt = (clientY: number, fallback: string) => {\n for (const [id, el] of laneRefs.current) {\n const r = el.getBoundingClientRect();\n if (clientY >= r.top && clientY < r.bottom) return id;\n }\n return fallback;\n };\n\n const onPointerMove = (e: React.PointerEvent) => {\n const d = dragRef.current;\n if (!d) return;\n const dx = e.clientX - d.originX;\n if (!d.moved && Math.abs(dx) < DRAG_THRESHOLD && d.mode !== \"move\") return;\n const dt = dx / zoom;\n const o = d.origin;\n let next: TimelineChange = { start: o.start, length: o.length, lane: o.lane };\n let guide: number | null = null;\n const edges = [...snapTimes, ...items.filter((i) => i.id !== o.id).flatMap((i) => [i.start, i.start + i.length])];\n const snapped = (t: number) => {\n const s = snap ? snapTo(t, edges, zoom) : null;\n if (s) guide = s.point;\n return s ? s.time : t;\n };\n if (d.mode === \"move\") {\n const m = snapMove(o.start + dt, o.length, o.id);\n const start = m.start;\n guide = m.guide;\n next = { start: clamp(tidy(start), from, to - o.length), length: o.length, lane: laneAt(e.clientY, o.lane) };\n } else if (d.mode === \"end\") {\n next = { start: o.start, length: clamp(tidy(snapped(o.start + o.length + dt) - o.start), min, to - o.start), lane: o.lane };\n } else {\n const start = clamp(tidy(snapped(o.start + dt)), from, o.start + o.length - min);\n next = { start, length: tidy(o.start + o.length - start), lane: o.lane };\n }\n const moved = d.moved || Math.abs(dx) >= DRAG_THRESHOLD || next.lane !== o.lane;\n const updated: Drag = { ...d, next, guide, moved, reason: moved ? (validate?.(o.id, next) ?? null) : null };\n dragRef.current = updated;\n setDrag(updated);\n };\n\n const onPointerUp = (e: React.PointerEvent) => {\n const d = dragRef.current;\n dragRef.current = null;\n setDrag(null);\n if (!d) return;\n (e.currentTarget as HTMLElement).releasePointerCapture?.(e.pointerId);\n if (!d.moved) {\n if (d.mode === \"move\") select(d.id, e.shiftKey || e.ctrlKey || e.metaKey);\n return;\n }\n if (d.reason) setSaid(d.reason);\n else commit(d.origin, d.next);\n };\n\n // --- the ruler and the current time --------------------------------------------------------\n const stepSize = tickStep(zoom);\n const ticks = React.useMemo(() => ticksBetween(from, to, stepSize), [from, to, stepSize]);\n const setPosition = (t: number) => onPositionChange?.(clamp(tidy(t), from, to));\n // The current time is React Aria's slider: the ruler is its track (a press or drag on it moves the\n // time), and the marker is its thumb. The value text goes through `formatTime`, and the keys are a\n // capture handler on the input (see `onSliderKey`), for the reasons in the opening comment.\n const scrubTrack = React.useRef<HTMLDivElement>(null);\n const scrubInput = React.useRef<HTMLInputElement>(null);\n const spokenTime = React.useMemo(\n () => ({ format: formatTime, formatRange: (a: number, b: number) => `${formatTime(a)} to ${formatTime(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) }) as unknown as Intl.NumberFormat,\n [formatTime],\n );\n const scrubState = useSliderState({\n minValue: from,\n maxValue: Math.max(to, from + 1e-9),\n step: 0.001,\n value: [clamp(position ?? from, from, to)],\n onChange: ([t]) => setPosition(t),\n numberFormatter: spokenTime,\n isDisabled: position === undefined || !onPositionChange,\n });\n const { trackProps: rulerProps } = useSlider({ \"aria-label\": \"Current time\", isDisabled: position === undefined || !onPositionChange }, scrubState, scrubTrack);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: scrubTrack, inputRef: scrubInput, \"aria-label\": \"Current time\", isDisabled: position === undefined || !onPositionChange }, scrubState);\n const { focusProps, isFocusVisible } = useFocusRing();\n const onSliderKey = (e: React.KeyboardEvent) => {\n if (position === undefined) return;\n const big = e.shiftKey ? 10 : 1;\n const moves: Record<string, number> = { ArrowLeft: -step * big, ArrowDown: -step * big, ArrowRight: step * big, ArrowUp: step * big, PageDown: -step * 10, PageUp: step * 10 };\n if (e.key in moves) setPosition(position + moves[e.key]);\n else if (e.key === \"Home\") setPosition(from);\n else if (e.key === \"End\") setPosition(to);\n else return;\n e.preventDefault();\n e.stopPropagation();\n };\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (!onZoomChange || e.ctrlKey || e.metaKey || e.altKey) return;\n if (e.key === \"+\" || e.key === \"=\") onZoomChange(zoom * 1.5);\n else if (e.key === \"-\") onZoomChange(zoom / 1.5);\n else if (e.key === \"0\") onZoomChange(view.width / Math.max(to - from, 1e-6));\n else return;\n e.preventDefault();\n };\n\n // Ctrl or Cmd with the wheel zooms about the pointer (a plain wheel scrolls). Attached natively\n // because React's wheel listener is passive and cannot stop the page zooming.\n React.useEffect(() => {\n const el = scroller.current;\n if (!el || !onZoomChange) return;\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n onZoomChange(e.deltaY < 0 ? zoom * 1.25 : zoom / 1.25);\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, [onZoomChange, zoom]);\n\n const rovingId = focusId && items.some((i) => i.id === focusId) ? focusId : (sorted.get(lanes[0]?.id ?? \"\")?.[0]?.id ?? items[0]?.id ?? null);\n // Only items near the view are drawn, and always the focused one so focus is never lost.\n const lo = view.left - view.width;\n const hi = view.left + 2 * view.width;\n const visible = (i: TimelineItem) => i.id === focusId || i.id === rovingId || (x(i.start + i.length) >= lo && x(i.start) <= hi);\n\n const itemLabel = (i: TimelineItem) => `${i.label}, ${formatTime(i.start)} to ${formatTime(i.start + i.length)}, ${laneLabel(i.lane)}`;\n\n return (\n <div role=\"group\" aria-label={label} onKeyDown={onKeyDown} className={cn(\"min-w-0 text-foreground\", className)} style={{ \"--lane-h\": `calc(var(--control-h) * ${Math.max(laneRows, 1)})` } as React.CSSProperties}>\n <p role=\"status\" className=\"sr-only\">\n {said}\n </p>\n <div className=\"flex\">\n <div className=\"w-max max-w-80 min-w-40 shrink-0 border-r border-border\">\n <div className=\"h-8 border-b border-border\" aria-hidden />\n {lanes.map((l) => (\n <div key={l.id} className=\"flex h-(--lane-h) items-center gap-1 border-b border-border px-2 type-label\">\n <span className=\"min-w-0 flex-1 truncate\" title={l.label}>\n {l.label}\n </span>\n {l.header}\n </div>\n ))}\n </div>\n <div ref={scroller} className=\"relative min-w-0 flex-1 overflow-x-auto\">\n <div className=\"relative\" style={{ width }}>\n {/* The ruler: ticks and labels on a ladder of steps, thinned so they never collide, the end labels kept inside the axis. */}\n <div {...rulerProps} ref={scrubTrack} className=\"relative h-8 touch-none border-b border-border\" data-ruler>\n {ticks.map((t) => {\n const px = x(t);\n const last = px > width - 40;\n return (\n <span key={t} aria-hidden className=\"absolute top-0 h-full border-l border-border pl-1 type-caption text-muted-foreground tabular-nums\" style={{ left: px, transform: last ? \"translateX(-100%)\" : undefined, borderLeftWidth: last ? 0 : 1, paddingRight: last ? 4 : 0 }}>\n {formatTime === defaultFormat ? tickLabel(t, stepSize) : formatTime(t)}\n </span>\n );\n })}\n {markers.map((m) => (\n <button\n key={m.id}\n type=\"button\"\n aria-label={`Marker: ${m.label}, ${formatTime(m.time)}`}\n onPointerDown={(e) => e.stopPropagation()}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={() => setPosition(m.time)}\n className=\"absolute bottom-0 max-w-32 -translate-x-px truncate rounded-control border-l-2 border-foreground bg-muted px-1 type-caption\"\n style={{ left: x(m.time) }}\n >\n {m.label}\n </button>\n ))}\n {position !== undefined && (\n <div {...thumbProps} className={cn(\"absolute top-0 -ml-2 h-full w-4 cursor-ew-resize\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")} style={{ left: x(position) }}>\n <span aria-hidden className=\"mx-auto block size-3 rounded-pill bg-primary\" />\n <VisuallyHidden>\n <input ref={scrubInput} {...mergeProps(inputProps, focusProps)} aria-labelledby={undefined} onKeyDownCapture={onSliderKey} />\n </VisuallyHidden>\n </div>\n )}\n </div>\n {lanes.length === 0 && <div className=\"p-4\">{empty}</div>}\n {lanes.map((l) => (\n <LaneRow\n key={l.id}\n label={l.label}\n register={(el) => void (el ? laneRefs.current.set(l.id, el) : laneRefs.current.delete(l.id))}\n types={dropsOn ? dropTypes : undefined}\n onHover={(px) => onLaneHover(l.id, px)}\n onLeave={() => setHover(null)}\n onDropItems={(px, dropped) => onLaneDrop(l.id, px, dropped)}\n >\n {hover && hover.next.lane === l.id && (\n <div aria-hidden className={cn(\"pointer-events-none absolute top-1 bottom-1 rounded-control border border-dashed\", hover.reason ? \"border-danger bg-danger-subtle\" : \"border-primary bg-muted\")} style={{ left: x(hover.next.start), width: Math.max(hover.next.length * zoom, 4) }} />\n )}\n {(sorted.get(l.id) ?? []).filter(visible).map((item) => {\n const live = drag?.id === item.id && drag.moved ? drag : null;\n // Stays mounted in its own lane while dragged (it holds the pointer capture) and is\n // shifted by whole lanes to show where it would land.\n const shown = live ? live.next : item;\n const laneShift = live ? (laneIndex.get(live.next.lane) ?? 0) - (laneIndex.get(item.lane) ?? 0) : 0;\n const isSel = selected.has(item.id);\n const px = x(shown.start);\n const w = Math.max(shown.length * zoom, 4);\n return (\n <div\n key={item.id}\n data-item={item.id}\n role=\"button\"\n aria-pressed={isSel}\n aria-label={itemLabel(item)}\n tabIndex={item.id === rovingId ? 0 : -1}\n onFocus={() => setFocusId(item.id)}\n onKeyDown={(e) => onItemKeyDown(e, item)}\n onPointerDown={(e) => begin(e, item, \"move\")}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n className={cn(\n \"absolute top-1 bottom-1 min-w-1 cursor-grab touch-none overflow-hidden rounded-control border border-input border-t-4 bg-background px-1.5 type-caption select-none\",\n isSel && \"bg-muted font-medium outline-2 outline-offset-1 outline-primary\",\n live?.reason && \"border-dashed border-danger bg-danger-subtle\",\n )}\n style={{ left: px, width: w, borderTopColor: item.kind ? (kindColours?.[item.kind] ?? kindColour(item.kind, items)) : undefined, transform: laneShift ? `translateY(calc(var(--lane-h) * ${laneShift}))` : undefined, zIndex: live ? 10 : undefined }}\n >\n {renderItem ? renderItem(item, { selected: isSel, width: w }) : <DefaultItem item={item} width={w} />}\n {/* Trim handles: pointer-only. The keyboard trims with Alt+arrows. */}\n <span aria-hidden className=\"absolute inset-y-0 left-0 cursor-ew-resize touch-none\" style={{ width: EDGE_PX }} onPointerDown={(e) => begin(e, item, \"start\")} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />\n <span aria-hidden className=\"absolute inset-y-0 right-0 cursor-ew-resize touch-none\" style={{ width: EDGE_PX }} onPointerDown={(e) => begin(e, item, \"end\")} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />\n </div>\n );\n })}\n </LaneRow>\n ))}\n {position !== undefined && <div aria-hidden className=\"pointer-events-none absolute top-8 bottom-0 w-0.5 bg-primary\" style={{ left: x(position) - 1 }} />}\n {(() => {\n const guide = drag?.moved ? drag.guide : (hover?.guide ?? null);\n return guide !== null && <div aria-hidden className=\"pointer-events-none absolute top-0 bottom-0 w-px bg-foreground\" style={{ left: x(guide) }} />;\n })()}\n </div>\n </div>\n </div>\n {(() => {\n const info = drag?.moved ? { next: drag.next, reason: drag.reason } : hover;\n return (\n info && (\n <p aria-hidden className=\"mt-1 flex items-center gap-1.5 type-body-sm tabular-nums text-muted-foreground\">\n {info.reason ? (\n <>\n <Ban className=\"size-4 shrink-0 text-danger\" />\n <span className=\"text-danger\">{info.reason}</span>\n </>\n ) : (\n <>\n {formatTime(info.next.start)} to {formatTime(info.next.start + info.next.length)}, {laneLabel(info.next.lane)}\n </>\n )}\n </p>\n )\n );\n })()}\n </div>\n );\n}\n\nfunction kindColour(kind: string, items: readonly TimelineItem[]) {\n const kinds = [...new Set(items.map((i) => i.kind).filter(Boolean))] as string[];\n return `var(--chart-${(Math.max(kinds.indexOf(kind), 0) % 5) + 1})`;\n}\n\nfunction DefaultItem({ item, width }: { item: TimelineItem; width: number }) {\n return (\n <span className=\"flex h-full min-w-0 items-center gap-1.5\">\n <span className=\"min-w-0 flex-1 truncate\">{item.label}</span>\n {item.kind && width > 120 && <span className=\"shrink-0 text-muted-foreground\">{item.kind}</span>}\n </span>\n );\n}\n\n/** One lane: a labelled group that is a React Aria drop target when `types` is given. `px` is the pointer's distance along the lane, or null for a keyboard drag (the lane is then the focused element). */\nfunction LaneRow({ label, register, types, onHover, onLeave, onDropItems, children }: { label: string; register: (el: HTMLDivElement | null) => void; types?: readonly string[]; onHover: (px: number | null) => void; onLeave: () => void; onDropItems: (px: number | null, items: DropItem[]) => void; children: React.ReactNode }) {\n const ref = React.useRef<HTMLDivElement | null>(null);\n const keyboard = () => document.activeElement === ref.current;\n const { dropProps } = useDrop({\n ref,\n isDisabled: !types,\n // A pointer drag hands over a `DragTypes` and a keyboard (virtual) drag a plain `Set` (checked in\n // `DragManager`), and only the first takes an array in `has`, so each type is asked on its own.\n getDropOperation: (t) => (types?.some((type) => t.has(type)) ? \"copy\" : \"cancel\"),\n onDropEnter: (e) => onHover(keyboard() ? null : e.x),\n onDropMove: (e) => onHover(keyboard() ? null : e.x),\n onDropExit: onLeave,\n // A browser sends no drop for a refused type; a keyboard drag's event says so in `dropOperation`.\n onDrop: (e) => e.dropOperation !== \"cancel\" && onDropItems(keyboard() ? null : e.x, e.items),\n });\n return (\n <div\n {...(types ? dropProps : {})}\n ref={(el) => {\n ref.current = el;\n register(el);\n }}\n role=\"group\"\n aria-label={label}\n // Focusable by script only: React Aria's keyboard drag moves focus to the lane it is over.\n tabIndex={types ? -1 : undefined}\n className=\"relative h-(--lane-h) border-b border-border\"\n >\n {children}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Ban, GripVertical } from \"lucide-react\";\nimport { Button as AriaButton, DropIndicator, GridList, GridListItem, useDragAndDrop } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A list whose items can be reordered and moved to other lists (strata issue #76, from a video\n// editor's tracks and library). One component for both because they are one gesture: pick an item\n// up, see where it will land, drop or cancel.\n//\n// React Aria first, and this is a case where it is the whole answer, so nothing else is added\n// (`@dnd-kit`, which the app being moved used, is not needed). `GridList` with `useDragAndDrop` gives:\n// the keyboard path (focus the grip, Enter picks up, arrows move between positions and between\n// lists that accept the item, Enter drops, Escape cancels, the item goes back), screen-reader\n// announcements at each step (React Aria's own words, localised; they name the item by `getLabel`),\n// a drop indicator line between rows, auto-scroll near a scroll container's edge, and a drag\n// preview. Checked in `useDragAndDrop.d.ts` and `GridList.d.ts`: `renderEmptyState` receives\n// `isDropTarget`, so an empty list can say \"Drop here\". What it cannot do is say WHY a target\n// refuses (a refusing target is simply not a target), so we read the dragged kinds in\n// `getDropOperation` and show the reason in the list, with an icon and words, never colour alone.\n//\n// Click and drag are separate by construction: dragging starts from the grip (`slot=\"drag\"`), a\n// real named button, so clicking the row selects it and pressing its own actions runs them.\n//\n// Kinds: each item has a kind (`getKind`, default \"item\") carried in the drag as a type\n// (`strata-kind/<kind>`). A list takes kinds listed in `accepts`; reordering within itself always\n// works. That is enough to say \"tracks take video and audio, not text\" before the drop.\n//\n// The list never changes the data. `onReorder` and `onInsert` say what was asked for and the app\n// applies it (and makes it undoable, patterns.md §7: a move is reversed, not confirmed). A drop on\n// a refusing list changes nothing: React Aria never calls them.\n//\n// No motion beyond the drop indicator appearing: dragging happens tens of times a session and the\n// item follows the pointer with no lag (ux-character.md, by frequency).\n\nconst KIND = \"strata-kind/\";\nconst ID = \"strata-item/id\";\nconst LIST = \"strata-list/\";\n\n/** Where a drop landed, relative to the item with `key`. */\nexport type DropTarget = { key: string; position: \"before\" | \"after\" | \"on\" } | { key: null; position: \"root\" };\n\nexport type SortableListProps<T> = {\n /** Names the list (\"Tracks\"). Required. */\n label: string;\n items: readonly T[];\n getKey: (item: T) => string;\n /** The item's name for a screen reader, typeahead and announcements (\"Picked up Moonbeam bowl\"). */\n getLabel: (item: T) => string;\n /** The row's content, beside the grip. Plain text and marks; actions go in `renderActions`. */\n children: (item: T) => React.ReactNode;\n /** Controls for the row (a `RowAction`), outside the row's selection target. */\n renderActions?: (item: T) => React.ReactNode;\n /** Shown when the list is empty, and \"Drop here\" while something is dragged over it. */\n empty: React.ReactNode;\n /** The item was moved within this list: `keys` now sit at `target`. */\n onReorder: (keys: string[], target: DropTarget) => void;\n /** An item of another list was dropped here. The app finds it by id and moves it. Needs `accepts`. */\n onInsert?: (ids: string[], target: DropTarget) => void;\n /** What an item is, for deciding which lists take it. Default: every item is \"item\". */\n getKind?: (item: T) => string;\n /** Kinds this list takes from other lists. Default none: it only reorders. */\n accepts?: readonly string[];\n /** Why a kind is refused, in the product's words, shown while one is dragged over: `{ text: \"Tracks take video and audio, not text clips.\" }`. React Aria cannot list what is being dragged, only ask about a kind, so name the kinds that exist. */\n refuses?: Readonly<Record<string, string>>;\n selectionMode?: \"none\" | \"single\" | \"multiple\";\n selectedKeys?: ReadonlySet<string>;\n onSelectionChange?: (keys: Set<string>) => void;\n className?: string;\n};\n\n/** A list that reorders by drag and by keyboard, and takes items from other lists by kind. It reports what was asked and never changes the data itself. */\nexport function SortableList<T>({\n label,\n items,\n getKey,\n getLabel,\n children,\n renderActions,\n empty,\n onReorder,\n onInsert,\n getKind = () => \"item\",\n accepts = [],\n refuses = {},\n selectionMode = \"none\",\n selectedKeys,\n onSelectionChange,\n className,\n}: SortableListProps<T>) {\n const listId = React.useId();\n const byKey = React.useMemo(() => new Map(items.map((i) => [getKey(i), i])), [items, getKey]);\n // The reason a drag over this list is refused, while one is. Cleared when the drag ends or leaves.\n const [refused, setRefused] = React.useState<string | null>(null);\n const root = React.useRef<HTMLDivElement>(null);\n React.useEffect(() => {\n if (!refused) return;\n const clear = () => setRefused(null);\n document.addEventListener(\"dragend\", clear);\n document.addEventListener(\"drop\", clear);\n return () => {\n document.removeEventListener(\"dragend\", clear);\n document.removeEventListener(\"drop\", clear);\n };\n }, [refused]);\n\n const toTarget = (t: { type: string; key?: unknown; dropPosition?: string }): DropTarget =>\n t.type === \"root\" ? { key: null, position: \"root\" } : { key: String(t.key), position: t.dropPosition as \"before\" | \"after\" | \"on\" };\n\n const { dragAndDropHooks } = useDragAndDrop<T>({\n getItems: (keys) =>\n [...keys].map((k) => {\n const item = byKey.get(String(k));\n return { [`${KIND}${item ? getKind(item) : \"item\"}`]: \"\", [`${LIST}${listId}`]: \"\", [ID]: String(k), \"text/plain\": item ? getLabel(item) : String(k) };\n }),\n // React Aria filters on this before `getDropOperation`: a refused kind must still reach it, to be explained.\n acceptedDragTypes: \"all\",\n getDropOperation: (_target, types) => {\n // Reordering is allowed for what came from this list; anything else must be a kind in `accepts`,\n // even if this list happens to hold an item of the same kind.\n const accepted = types.has(`${LIST}${listId}`) || accepts.some((k) => types.has(`${KIND}${k}`));\n if (accepted) {\n setRefused(null);\n return \"move\";\n }\n const kind = Object.keys(refuses).find((k) => types.has(`${KIND}${k}`));\n if (kind) setRefused(refuses[kind]);\n return \"cancel\";\n },\n onReorder: (e) => onReorder([...e.keys].map(String), toTarget(e.target)),\n onInsert: async (e) => {\n const ids = (await Promise.all(e.items.filter((i) => i.kind === \"text\").map((i) => i.getText(ID)))).filter(Boolean);\n onInsert?.(ids, toTarget(e.target));\n },\n onRootDrop: async (e) => {\n const ids = (await Promise.all(e.items.filter((i) => i.kind === \"text\").map((i) => i.getText(ID)))).filter(Boolean);\n onInsert?.(ids, { key: null, position: \"root\" });\n },\n renderDropIndicator: (target) => (\n <DropIndicator\n target={target}\n // A line with ends, so a position is a shape and not only a tint; zero height so rows do not shift.\n className={({ isDropTarget }) =>\n cn(\"relative h-0 data-[drop-target]:after:absolute data-[drop-target]:after:inset-x-0 data-[drop-target]:after:-top-px data-[drop-target]:after:h-0.5 data-[drop-target]:after:rounded-pill data-[drop-target]:after:bg-primary\", isDropTarget && \"z-10\")\n }\n />\n ),\n });\n\n return (\n <div ref={root} className={cn(\"min-w-0\", className)} // Capture phase: React Aria's drop handlers stop dragleave from bubbling.\n onDragLeaveCapture={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && setRefused(null)}>\n <GridList\n aria-label={label}\n items={items.map((item) => ({ item, id: getKey(item) }))}\n dragAndDropHooks={dragAndDropHooks}\n selectionMode={selectionMode}\n selectedKeys={selectedKeys}\n onSelectionChange={(keys) => onSelectionChange?.(keys === \"all\" ? new Set(items.map(getKey)) : new Set([...keys].map(String)))}\n renderEmptyState={({ isDropTarget }) => (\n <div className={cn(\"rounded-surface border border-dashed py-6 text-center\", isDropTarget ? \"border-solid border-primary bg-muted\" : \"border-input\")}>\n {isDropTarget ? <p className=\"type-body\">Drop here</p> : empty}\n </div>\n )}\n className={({ isDropTarget }) => cn(\"grid divide-y divide-border border-y border-border\", isDropTarget && \"outline-2 outline-offset-2 outline-primary\")}\n >\n {({ item }) => (\n <GridListItem\n id={getKey(item)}\n textValue={getLabel(item)}\n className=\"group relative flex min-h-(--control-h) cursor-default items-center gap-2 py-1 pr-1 pl-1 outline-none data-[focus-visible]:outline-2 data-[focus-visible]:-outline-offset-2 data-[focus-visible]:outline-ring data-[selected]:bg-muted data-[selected]:before:absolute data-[selected]:before:inset-y-1 data-[selected]:before:left-0 data-[selected]:before:w-0.5 data-[selected]:before:rounded-pill data-[selected]:before:bg-primary data-[dragging]:opacity-50\"\n >\n <AriaButton slot=\"drag\" className=\"grid size-(--control-h-sm) shrink-0 cursor-grab place-items-center rounded-control text-muted-foreground hover:bg-muted data-[focus-visible]:outline-2 data-[focus-visible]:outline-ring\">\n <GripVertical aria-hidden className=\"size-4\" />\n </AriaButton>\n <div className=\"min-w-0 flex-1\">{children(item)}</div>\n {renderActions && <div className=\"flex shrink-0 items-center gap-1\">{renderActions(item)}</div>}\n </GridListItem>\n )}\n </GridList>\n {refused && (\n <p role=\"status\" className=\"mt-2 flex items-start gap-1.5 type-body-sm text-danger\">\n <Ban aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n {refused}\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, FileQuestion, Loader, Upload, X } from \"lucide-react\";\nimport { DropZone, FileTrigger } from \"react-aria-components\";\nimport type { FileIntake, FileOutcome } from \"../lib/file-intake\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button, IconButton, RowAction, type ButtonProps } from \"./button\";\nimport { Status } from \"./status\";\n\n// Bringing local files into an app (strata issue #75). Four pieces over `useFileIntake`:\n//\n// FileButton opens the picker. The one route that needs no pointer, so it is also the keyboard\n// and phone way in: a drop zone always carries one.\n// FileDropZone a region files can be dropped on, that says what it takes and shows when a drag\n// is over it. Rejection happens after the drop, in `useFileIntake`, so a wrong\n// file is named with its reason instead of the drop silently doing nothing.\n// FileOutcomes one row per file: pending, added, rejected or failed, each with its word and,\n// where a person must act, the reason and a retry. Inline, never a full-screen\n// overlay (components.md §3.6).\n// MissingFile a saved item whose file is gone: a status word and a relink button that opens the\n// picker for that one item.\n//\n// React Aria first. The picker is `FileTrigger` (it renders the hidden input and opens it from a\n// real `Button`, so the control is focusable and named; the old `<label>` around a hidden input\n// is not) and the zone is `DropZone` (drop events, `isDropTarget`, its own focus ring). Checked in\n// their `.d.ts`: `DropZone` filters nothing by type unless `getDropOperation` says so, and a\n// refusal there shows no message, so we accept any file drop and judge in the hook. `isDropTarget`\n// comes from React Aria's enter and leave bookkeeping, which is why the state does not flicker as\n// the pointer crosses the zone's children (a plain `dragenter` handler on the zone does).\n// The dropped `File`s are read from the drop items (`kind: \"file\"`); directories are ignored.\n//\n// Drop-over state is a word as well as a border: \"Drop to add …\" replaces the prompt, so it does\n// not rest on colour alone. Nothing animates (character by frequency; the zone is used a handful\n// of times a session, but its state change is itself the feedback).\n\n/** The picker as a button. `children` is its visible name (\"Add files\"); `accept` narrows what the dialog shows. */\nexport function FileButton({\n accept,\n multiple = false,\n onFiles,\n icon: Icon,\n children,\n ...props\n}: Omit<ButtonProps, \"onChange\" | \"children\"> & {\n /** What the dialog offers: extensions (`.gpx`), exact types or families (`video/*`). */\n accept: readonly string[];\n multiple?: boolean;\n /** Called with the files chosen. Not called when the dialog is cancelled. */\n onFiles: (files: File[]) => void;\n icon?: IconComponent;\n children: string;\n}) {\n return (\n <FileTrigger\n acceptedFileTypes={accept}\n allowsMultiple={multiple}\n onSelect={(list) => {\n const files = list ? Array.from(list) : [];\n if (files.length) onFiles(files);\n }}\n >\n <Button {...props}>\n {Icon && <Icon aria-hidden />}\n {children}\n </Button>\n </FileTrigger>\n );\n}\n\n/** A region that takes dropped files and offers the picker as its keyboard alternative. */\nexport function FileDropZone({\n onFiles,\n acceptLabel,\n title,\n disabled,\n children,\n className,\n}: {\n onFiles: (files: File[]) => void;\n /** What it takes, in words (\"a video, an audio file or a GPX track\"). Shown while a drag is over it. */\n acceptLabel: string;\n /** The resting prompt (\"Drag files here\"). */\n title: string;\n disabled?: boolean;\n /** The `FileButton` (required in practice: it is how a keyboard or phone gets files in). */\n children?: React.ReactNode;\n className?: string;\n}) {\n const onDrop = async (e: Parameters<NonNullable<React.ComponentProps<typeof DropZone>[\"onDrop\"]>>[0]) => {\n const items = e.items.filter((i) => i.kind === \"file\");\n const files = await Promise.all(items.map((i) => i.getFile()));\n if (files.length) onFiles(files);\n };\n return (\n <DropZone\n aria-label={title}\n isDisabled={disabled}\n onDrop={onDrop}\n className={({ isDropTarget, isFocusVisible }) =>\n cn(\n \"grid min-w-0 justify-items-center gap-2 rounded-surface border border-dashed border-input px-4 py-6 text-center\",\n isDropTarget && \"border-solid border-primary bg-muted\",\n isFocusVisible && \"outline-2 outline-offset-2 outline-ring\",\n className,\n )\n }\n >\n {({ isDropTarget }) => (\n <>\n <Upload aria-hidden className=\"size-5 text-muted-foreground\" />\n <p className=\"type-body\">{isDropTarget ? `Drop to add ${acceptLabel}` : title}</p>\n {children}\n </>\n )}\n </DropZone>\n );\n}\n\nconst rowStatus: Record<FileOutcome[\"status\"], { tone: \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\"; word: string; icon: IconComponent }> = {\n processing: { tone: \"info\", word: \"Adding…\", icon: Loader },\n added: { tone: \"success\", word: \"Added\", icon: CircleCheck },\n rejected: { tone: \"warning\", word: \"Not added\", icon: CircleAlert },\n failed: { tone: \"danger\", word: \"Failed\", icon: CircleAlert },\n};\n\n/** One row per file offered: its name, a status word, and for a rejected or failed file the reason and (for failed) a retry. Announces a summary politely when a batch finishes. */\nexport function FileOutcomes({ intake, className }: { intake: FileIntake; className?: string }) {\n const { outcomes, retry, dismiss, pending } = intake;\n // A polite summary once nothing is pending, covering the files not yet announced, so a six-file\n // drop is one announcement and not six, and a drop that is all rejections is still heard.\n const [summary, setSummary] = React.useState(\"\");\n const announced = React.useRef(new Set<string>());\n React.useEffect(() => {\n if (pending > 0) return;\n const fresh = outcomes.filter((o) => !announced.current.has(o.id));\n if (!fresh.length) return;\n for (const o of fresh) announced.current.add(o.id);\n const added = fresh.filter((o) => o.status === \"added\").length;\n const problems = fresh.length - added;\n setSummary([added && `${added} added`, problems && `${problems} not added`].filter(Boolean).join(\", \"));\n }, [pending, outcomes]);\n\n return (\n <div className={cn(\"min-w-0\", className)}>\n <p role=\"status\" className=\"sr-only\">\n {summary}\n </p>\n {outcomes.length > 0 && (\n <ul className=\"grid divide-y divide-border border-y border-border\">\n {outcomes.map((o) => {\n const s = rowStatus[o.status];\n const reason = o.status === \"rejected\" || o.status === \"failed\" ? o.reason : undefined;\n return (\n <li key={o.id} className=\"grid gap-1 py-2\">\n <div className=\"flex items-center gap-3\">\n <span className=\"min-w-0 flex-1 truncate type-body\" title={o.name}>\n {o.name}\n </span>\n <Status tone={s.tone} icon={s.icon}>\n {s.word}\n </Status>\n {o.status === \"failed\" && <RowAction label=\"Try again\" subject={o.name} onClick={() => retry(o.id)} />}\n {o.status !== \"processing\" && <IconButton icon={X} label={`Dismiss ${o.name}`} onClick={() => dismiss(o.id)} />}\n </div>\n {reason && <p className=\"type-body-sm text-muted-foreground\">{reason}</p>}\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n}\n\n/**\n * A saved item whose file is gone: the item's name, a \"File missing\" status (a word and an icon) and a \"Relink\" button that opens the picker for this one item.\n * In a narrow column the name keeps its own line, in full, and the status and button wrap under it. An optional `thumbnail` sits beside all three.\n */\nexport function MissingFile({\n name,\n accept,\n onRelink,\n thumbnail,\n className,\n}: {\n /** The item's name as the person knows it (\"run-02.mp4\"). */\n name: string;\n accept: readonly string[];\n /** Called with the file the person chose to stand in for it. */\n onRelink: (file: File) => void;\n /** A picture of the item (what it last looked like), drawn at the start. */\n thumbnail?: React.ReactNode;\n className?: string;\n}) {\n // In a 300px library a name, a status and a button on one row left the name \"parkru…\" (strata-react\n // issue #122). The name is the one thing that must stay readable, so it wraps rather than truncates,\n // takes at least ten ems, and pushes the status and button to the next row when the row is short.\n return (\n <div className={cn(\"flex min-w-0 items-center gap-3\", className)}>\n {thumbnail && <div className=\"shrink-0\">{thumbnail}</div>}\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1\">\n <span className=\"min-w-40 flex-auto break-words type-body\" title={name}>\n {name}\n </span>\n <div className=\"flex items-center gap-2\">\n <Status tone=\"warning\" icon={FileQuestion}>\n File missing\n </Status>\n <FileButton accept={accept} variant=\"ghost\" size=\"sm\" aria-label={`Relink ${name}`} onFiles={([file]) => onRelink(file)}>\n Relink\n </FileButton>\n </div>\n </div>\n </div>\n );\n}\n","import * as React from \"react\";\n\n// Bringing local files into an app (strata issue #75, from a video editor's library): pick or\n// drop, then one outcome per file. This is the logic with no drawing, so a screen can render the\n// outcomes however it likes (`FileOutcomes` is the default) and a test can feed it `File`s without\n// a dialog.\n//\n// Why a hook of per-file outcomes and not one \"upload\" state: a drop of six files has six stories\n// (two added, one still processing, one the wrong type, one too big, one the app could not read),\n// and the person needs to hear about each by name, inline, without the screen being blocked\n// (patterns.md §7: an error a person must act on is inline with its recovery, not a toast). The\n// rest of the batch is never held up by one file: each runs on its own.\n//\n// Nothing here assumes a server. `process` is the app's own work on a file (parse a GPX, make a\n// thumbnail, upload it); it may throw, and its message is shown as the reason, so write it in the\n// product's words (\"run-02.mp4 is not a video this browser can play. Convert it to MP4 (H.264)\n// and add it again.\"). Without `process`, an accepted file counts as added at once.\n\nexport type FileOutcome =\n | { id: string; name: string; size: number; status: \"processing\" }\n | { id: string; name: string; size: number; status: \"added\" }\n | { id: string; name: string; size: number; status: \"rejected\"; reason: string }\n | { id: string; name: string; size: number; status: \"failed\"; reason: string };\n\nexport type FileIntakeOptions = {\n /** What is accepted, as the picker's `accept` list: extensions (`.gpx`), exact types (`audio/mpeg`) or families (`video/*`). */\n accept: readonly string[];\n /** The accepted kinds in words, used in the rejection reason and the drop hint: \"a video, an audio file or a GPX track\". */\n acceptLabel: string;\n /** More than one file at a time. Default true; with false, extra files in one drop are rejected by name. */\n multiple?: boolean;\n /** Largest size in bytes. Larger files are rejected with their size in the reason. */\n maxBytes?: number;\n /** Extra checks after the type check, for what a type cannot say. Return the reason in the product's words, or `null` to accept. */\n check?: (file: File) => string | null | Promise<string | null>;\n /** The app's own work on an accepted file. A throw marks it `failed` with the error's message and offers a retry. */\n process?: (file: File, context: { signal: AbortSignal }) => void | Promise<void>;\n};\n\nexport type FileIntake = {\n /** One outcome per file offered, in the order offered, newest batch last. */\n outcomes: readonly FileOutcome[];\n /** Offers files (from the picker or a drop). Rejections appear as outcomes at once; accepted files are processed. */\n add: (files: Iterable<File> | ArrayLike<File>) => void;\n /** Runs `process` again for a failed file. */\n retry: (id: string) => void;\n /** Removes an outcome (and aborts its processing if still running). */\n dismiss: (id: string) => void;\n /** Removes every finished outcome (added, rejected and failed), leaving those still processing. */\n clear: () => void;\n /** Files still being processed. */\n pending: number;\n};\n\n/** Whether a file matches one entry of an `accept` list: extension, exact type or `family/*`, ignoring case. */\nexport function matchesAccept(file: { name: string; type: string }, accept: readonly string[]): boolean {\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return accept.some((entry) => {\n const a = entry.trim().toLowerCase();\n if (a.startsWith(\".\")) return name.endsWith(a);\n if (a.endsWith(\"/*\")) return type.startsWith(a.slice(0, -1));\n return type === a;\n });\n}\n\nconst MB = 1024 * 1024;\nconst sizeWords = (bytes: number) => (bytes >= MB ? `${(bytes / MB).toFixed(bytes >= 100 * MB ? 0 : 1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} kB`);\n\n/** Per-file outcomes for files picked or dropped: type and size checks with a named reason, the app's own `process` per file, retry and dismiss. */\nexport function useFileIntake(options: FileIntakeOptions): FileIntake {\n const [outcomes, setOutcomes] = React.useState<readonly FileOutcome[]>([]);\n const opts = React.useRef(options);\n opts.current = options;\n const files = React.useRef(new Map<string, File>());\n const controllers = React.useRef(new Map<string, AbortController>());\n const counter = React.useRef(0);\n const alive = React.useRef(true);\n\n const patch = React.useCallback((id: string, next: (o: FileOutcome) => FileOutcome) => {\n setOutcomes((all) => all.map((o) => (o.id === id ? next(o) : o)));\n }, []);\n\n const run = React.useCallback(\n (id: string, file: File) => {\n const controller = new AbortController();\n controllers.current.set(id, controller);\n const base = { id, name: file.name, size: file.size };\n patch(id, () => ({ ...base, status: \"processing\" }));\n Promise.resolve()\n .then(() => opts.current.process?.(file, { signal: controller.signal }))\n .then(\n () => !controller.signal.aborted && patch(id, () => ({ ...base, status: \"added\" })),\n (error: unknown) => {\n if (controller.signal.aborted) return;\n const reason = error instanceof Error && error.message ? error.message : `${file.name} could not be added. Try again.`;\n patch(id, () => ({ ...base, status: \"failed\", reason }));\n },\n )\n .finally(() => controllers.current.delete(id));\n },\n [patch],\n );\n\n // The app's own check, then its `process`. A check that throws (synchronously or not) fails the\n // file with a retry rather than accepting it unchecked or escaping `add`; nothing runs after the\n // screen is gone or the file was dismissed.\n const start = React.useCallback(\n (id: string, file: File) => {\n const base = { id, name: file.name, size: file.size };\n patch(id, () => ({ ...base, status: \"processing\" }));\n Promise.resolve()\n .then(() => opts.current.check?.(file))\n .then(\n (reason) => {\n if (!alive.current || !files.current.has(id)) return;\n if (reason) {\n files.current.delete(id);\n patch(id, () => ({ ...base, status: \"rejected\", reason }));\n } else run(id, file);\n },\n (error: unknown) => {\n if (!alive.current || !files.current.has(id)) return;\n const reason = error instanceof Error && error.message ? error.message : `${file.name} could not be checked. Try again.`;\n patch(id, () => ({ ...base, status: \"failed\", reason }));\n },\n );\n },\n [patch, run],\n );\n\n const add = React.useCallback(\n (offered: Iterable<File> | ArrayLike<File>) => {\n const list = Array.from(offered as ArrayLike<File>);\n const { accept, acceptLabel, multiple = true, maxBytes } = opts.current;\n list.forEach((file, index) => {\n const id = `f${++counter.current}`;\n const base = { id, name: file.name, size: file.size };\n const reject = (reason: string) => setOutcomes((all) => [...all, { ...base, status: \"rejected\", reason }]);\n if (!multiple && index > 0) return reject(`${file.name} was not added: this takes one file at a time.`);\n if (!matchesAccept(file, accept)) return reject(`${file.name} is not a type this accepts. Add ${acceptLabel}.`);\n if (maxBytes !== undefined && file.size > maxBytes) {\n return reject(`${file.name} is ${sizeWords(file.size)}, over the ${sizeWords(maxBytes)} limit.`);\n }\n files.current.set(id, file);\n setOutcomes((all) => [...all, { ...base, status: \"processing\" }]);\n start(id, file);\n });\n },\n [patch, start],\n );\n\n const dismiss = React.useCallback((id: string) => {\n controllers.current.get(id)?.abort();\n controllers.current.delete(id);\n files.current.delete(id);\n setOutcomes((all) => all.filter((o) => o.id !== id));\n }, []);\n\n const retry = React.useCallback(\n (id: string) => {\n const file = files.current.get(id);\n if (file) start(id, file);\n },\n [start],\n );\n\n const clear = React.useCallback(() => {\n setOutcomes((all) => {\n for (const o of all) if (o.status !== \"processing\") files.current.delete(o.id);\n return all.filter((o) => o.status === \"processing\");\n });\n }, []);\n\n React.useEffect(() => {\n alive.current = true;\n const live = controllers.current;\n return () => {\n alive.current = false;\n for (const c of live.values()) c.abort();\n live.clear();\n };\n }, []);\n\n const pending = outcomes.filter((o) => o.status === \"processing\").length;\n return React.useMemo(() => ({ outcomes, add, retry, dismiss, clear, pending }), [outcomes, add, retry, dismiss, clear, pending]);\n}\n","import * as React from \"react\";\nimport { ChevronRight, RotateCcw } from \"lucide-react\";\nimport { Button as AriaButton, Disclosure, DisclosurePanel, Heading } from \"react-aria-components\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\nimport { Field } from \"./field\";\n\n// An inspector shows and edits the properties of whatever is selected (strata issue #74, from a\n// video editor's metadata and clip panels). Four parts that compose, so a settings sidebar, a file\n// manager's details pane and an editor's property panel are the same few pieces:\n//\n// Inspector the panel: a labelled region, a heading naming the selection, and the empty\n// state when nothing is selected. Remembers which sections the person closed.\n// InspectorSection a titled, collapsible group of rows, with room for its few actions.\n// PropertyRow one editable property: a `Field` (label, hint, error) with an optional\n// \"Reset\" that appears only while the value differs from its default.\n// PropertyList read-only facts as a description list (size, duration, codec, created).\n//\n// React Aria first. Sections are React Aria's `Disclosure`, which gives the heading + trigger\n// button + panel wiring (`aria-expanded`, `aria-controls`, the panel as a labelled region). We\n// extend it two ways. React Aria keeps a closed panel in the DOM (`hidden`), so a closed section's\n// controls would still be mounted, and in a long inspector that is dozens of controls and any\n// request inside them; the body here renders only while the section is open, as `Disclosure`\n// does, by reading `isExpanded` from the render props. And the open state is held by the\n// Inspector, so it can be remembered. Checked in `Disclosure.d.ts`: no prop unmounts the panel.\n// The separator-less look follows patterns.md §2: space and hairlines, never cards, never nested.\n//\n// Order is the caller's: the research (patterns.md §1) orders blocks by the next question a\n// person asks, not by the data model, and a component cannot know that. What the component does is\n// make a long panel survivable: every section but the first few can start closed (`defaultOpen`),\n// and what the person opens or closes is remembered per `storageKey`.\n//\n// The selection changing underneath is handled here, not by each app: pass `selectionKey` (the\n// selected thing's id) and the sections' bodies remount for a new selection, so no control keeps\n// the last item's typed text; if the control that had focus left the DOM, focus goes to the\n// panel's heading, not to the page. A deleted selection (`title` null) shows the empty state.\n//\n// No motion on open and close: people do it many times a session (ux-character.md, by frequency).\n\ntype Remembered = Record<string, boolean>;\n\nfunction readRemembered(key: string | null | undefined): Remembered {\n if (!key) return {};\n try {\n const raw = window.localStorage.getItem(key);\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return parsed && typeof parsed === \"object\" ? (parsed as Remembered) : {};\n } catch {\n // Storage throws in private windows and when blocked; the panel then works for this visit.\n return {};\n }\n}\n\ntype InspectorState = { isOpen: (id: string, defaultOpen: boolean) => boolean; setOpen: (id: string, open: boolean) => void };\nconst InspectorContext = React.createContext<InspectorState | null>(null);\n\nexport type InspectorProps = {\n /** The selection's name, as the panel's heading (\"run-02.mp4\", \"Clip: Title card\"). `null` when nothing is selected. */\n title: string | null;\n /** What kind of thing it is, under the heading (\"Video\", \"Text clip\"). */\n kind?: string;\n /** Shown when `title` is `null`: an `EmptyState` that says what to select and what appears (\"Select a clip on the timeline to change how it looks\"). */\n empty: React.ReactNode;\n /** The selected thing's id. A new value remounts the sections' bodies so no control shows the last item's typed text. */\n selectionKey?: string;\n /** localStorage key under which closed and opened sections are remembered. Omit to remember only for this visit. */\n storageKey?: string;\n /** The panel's few actions (a menu, a \"Delete\"), beside the heading. */\n actions?: React.ReactNode;\n /** A picture or summary of the selection above the sections (a `Thumbnail`). */\n summary?: React.ReactNode;\n /** `InspectorSection`s and `PropertyList`s. */\n children?: React.ReactNode;\n className?: string;\n};\n\n/** A panel of properties for the selected thing: a labelled region with a heading, an empty state when `title` is null, and sections whose open state is remembered. */\nexport function Inspector({ title, kind, empty, selectionKey, storageKey, actions, summary, children, className }: InspectorProps) {\n const headingId = React.useId();\n const [remembered, setRemembered] = React.useState<Remembered>(() => readRemembered(storageKey));\n const root = React.useRef<HTMLElement>(null);\n const heading = React.useRef<HTMLHeadingElement>(null);\n\n const state = React.useMemo<InspectorState>(\n () => ({\n isOpen: (id, defaultOpen) => remembered[id] ?? defaultOpen,\n setOpen: (id, open) =>\n setRemembered((prev) => {\n const next = { ...prev, [id]: open };\n if (storageKey) {\n try {\n window.localStorage.setItem(storageKey, JSON.stringify(next));\n } catch {\n // Not remembered; still applies to this visit.\n }\n }\n return next;\n }),\n }),\n [remembered, storageKey],\n );\n\n // When the selection changes and the focused control went with the old one, focus would fall to\n // the page body. Put it on the heading instead, so a keyboard user stays in the panel.\n const hadFocus = React.useRef(false);\n React.useEffect(() => {\n const el = root.current;\n const onFocus = () => (hadFocus.current = true);\n const onBlur = (e: FocusEvent) => {\n if (!e.relatedTarget) return; // focus left to nowhere: decided in the effect below\n hadFocus.current = false;\n };\n el?.addEventListener(\"focusin\", onFocus);\n el?.addEventListener(\"focusout\", onBlur);\n return () => {\n el?.removeEventListener(\"focusin\", onFocus);\n el?.removeEventListener(\"focusout\", onBlur);\n };\n }, []);\n React.useEffect(() => {\n if (hadFocus.current && (document.activeElement === document.body || !document.activeElement)) (heading.current ?? root.current)?.focus(); // the panel itself when the heading is gone (nothing selected)\n }, [selectionKey, title]);\n\n return (\n <InspectorContext.Provider value={state}>\n <aside ref={root} tabIndex={-1} aria-labelledby={title === null ? undefined : headingId} aria-label={title === null ? \"Properties\" : undefined} className={cn(\"min-w-0\", className)}>\n {title === null ? (\n empty\n ) : (\n <div className=\"grid grid-cols-1 gap-4\">\n <header className=\"flex items-start gap-3\">\n <div className=\"min-w-0 flex-1\">\n <Heading level={2} id={headingId} ref={heading} tabIndex={-1} title={title} className=\"truncate type-heading outline-offset-2\">\n {title}\n </Heading>\n {kind && <p className=\"type-body-sm text-muted-foreground\">{kind}</p>}\n </div>\n {actions && <div className=\"flex shrink-0 items-center gap-1\">{actions}</div>}\n </header>\n {summary}\n <div key={selectionKey} className=\"grid grid-cols-1 *:min-w-0\">\n {children}\n </div>\n </div>\n )}\n </aside>\n </InspectorContext.Provider>\n );\n}\n\nexport type InspectorSectionProps = {\n /** Identifies the section for remembering, stable across selections of the same kind (\"audio\", \"text-style\"). */\n id: string;\n title: string;\n /** Open when the person has not chosen. Default true; start the few that answer the next question open and the rest closed. */\n defaultOpen?: boolean;\n /** The section's few actions (add, reset all), beside its heading and outside its toggle. Name them for the section (\"Add track\"). */\n actions?: React.ReactNode;\n /** Mounted only while the section is open. */\n children: React.ReactNode;\n className?: string;\n};\n\n/** A titled group of rows that collapses. The body is mounted only while open; the open state is remembered by the surrounding `Inspector` (and held locally outside one). */\nexport function InspectorSection({ id, title, defaultOpen = true, actions, children, className }: InspectorSectionProps) {\n const inspector = React.useContext(InspectorContext);\n const [own, setOwn] = React.useState(defaultOpen);\n const expanded = inspector ? inspector.isOpen(id, defaultOpen) : own;\n const onChange = (open: boolean) => (inspector ? inspector.setOpen(id, open) : setOwn(open));\n return (\n <Disclosure isExpanded={expanded} onExpandedChange={onChange} className={cn(\"min-w-0 border-t border-border first:border-t-0\", className)}>\n {({ isExpanded }) => (\n <>\n <div className=\"flex items-center gap-2\">\n <Heading level={3} className=\"min-w-0 flex-1\">\n <AriaButton\n slot=\"trigger\"\n className=\"-mx-1 flex min-h-(--control-h-sm) w-full cursor-pointer items-center gap-2 rounded-control px-1 text-left type-label hover:bg-muted\"\n >\n <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", isExpanded && \"rotate-90\")} />\n <span className=\"min-w-0 flex-1 truncate\">{title}</span>\n </AriaButton>\n </Heading>\n {actions && <div className=\"flex shrink-0 items-center gap-1\">{actions}</div>}\n </div>\n <DisclosurePanel>{isExpanded && <div className=\"grid grid-cols-1 gap-4 pt-2 pb-4 pl-6 *:min-w-0\">{children}</div>}</DisclosurePanel>\n </>\n )}\n </Disclosure>\n );\n}\n\nexport type PropertyRowProps = {\n label: string;\n hint?: React.ReactNode;\n error?: string;\n /** Whether the value differs from its default. With `onReset`, shows a \"Reset\" button named for the property. */\n modified?: boolean;\n /** Puts the value back to its default. */\n onReset?: () => void;\n /** The control: an `Input`, `NumberField`, `Slider`, `NativeSelect`… It picks up the label from the row. */\n children: React.ReactNode;\n className?: string;\n};\n\n/** One editable property: a `Field` (label, hint, error wired to the control) with a \"Reset <label>\" that shows only while `modified`. */\nexport function PropertyRow({ label, hint, error, modified, onReset, children, className }: PropertyRowProps) {\n const reset =\n modified && onReset ? <IconButton icon={RotateCcw} label={`Reset ${label.toLowerCase()}`} onClick={onReset} /> : undefined;\n return (\n <Field label={label} hint={hint} error={error} action={reset} className={className}>\n {children}\n </Field>\n );\n}\n\nexport type Property = {\n /** The fact's name (\"Frame rate\"). */\n term: string;\n /** Its value. `null` or `undefined` prints the missing mark; a string is truncated with the whole value in a tooltip. */\n value: React.ReactNode | null | undefined;\n /** A unit, joined with a non-breaking space and muted. */\n unit?: string;\n};\n\nexport type PropertyListProps = {\n items: readonly Property[];\n /** Names the list for a screen reader (\"Video details\") when a visible heading does not. */\n label?: string;\n className?: string;\n};\n\n/** Read-only facts as a description list: term left, value right, long strings truncated with the full value on hover, a missing value printed as an en dash, units muted after a non-breaking space. */\nexport function PropertyList({ items, label, className }: PropertyListProps) {\n return (\n <dl aria-label={label} className={cn(\"grid gap-y-1.5\", className)}>\n {items.map(({ term, value, unit }) => {\n const missing = value === null || value === undefined || value === \"\";\n return (\n // A wrapping div per pair is valid inside <dl> and keeps term and value on one row.\n <div key={term} className=\"grid grid-cols-5 gap-x-3 type-body-sm\">\n <dt className=\"col-span-2 min-w-0 text-muted-foreground\">{term}</dt>\n <dd className=\"col-span-3 min-w-0 tabular-nums\">\n <span className=\"block truncate\" title={typeof value === \"string\" ? value : undefined}>\n {missing ? (\n <>\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">Not known</span>\n </>\n ) : (\n value\n )}\n {!missing && unit && <span className=\"text-muted-foreground\">{` ${unit}`}</span>}\n </span>\n </dd>\n </div>\n );\n })}\n </dl>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox as AriaCheckbox, GridLayout, GridList, GridListItem, Virtualizer, type Selection } from \"react-aria-components\";\nimport { Size } from \"react-stately\";\nimport { Check } from \"lucide-react\";\nimport { Checkbox, useShiftNote } from \"./checkbox\";\nimport type { RowSelection } from \"./data-table\";\nimport { useSelectRows } from \"./selection\";\n\n// Choosing from pictures: a review screen of face crops, a set of glaze test tiles, photos to\n// archive. It is `DataTable`'s selection drawn as a grid (strata-react issue #32, from the Bright\n// Horizons port, where the Groups screen had to be built by hand from `Checkbox` and\n// `useSelection`), and it shares the state and the rules: `useSelection` holds the keys, a\n// `BulkBar` holds the actions, select-all covers the selectable tiles shown (all of them, rendered\n// or not) and is mixed when some are chosen, and Shift-click or Shift+Space chooses or clears the\n// run from the last tile clicked (`useSelectRows`, the same code the table uses).\n//\n// It is React Aria's GridList with `layout=\"grid\"` (arrow keys move across and down the tiles) and\n// its own selection: each tile is one row, a press anywhere on it toggles it (Google Photos and Apple\n// Photos select from the picture, not only from the box), Shift extends a range, Space toggles. The\n// box is React Aria's selection checkbox, named from the row (`rowLabel` is required, as the\n// table's is), so a screen reader hears \"Select Ada Lovelace, crop 3\", not twelve \"checkbox, not\n// checked\". The box sits on a chip of the page's ground in the picture's corner, so it stays\n// visible on any photo. A chosen tile takes the sunken fill and a primary border, not a ring: the\n// focus outline is the only ring, so a selection never reads as focus. Shift-click on the box also\n// extends a range, as before (a checkbox always toggles one tile in React Aria), through\n// `useSelectRows`. \"Select all shown\" is ours, outside the grid, since the tiles shown may be a\n// part of the keys held.\n//\n// The picture is the caller's (`renderImage`), in a frame of fixed aspect (`aspect`, square by\n// default) so tiles line up and nothing shifts as images load; an <img> or Strata's `Thumbnail`\n// fills it. Tiles are sized by a minimum width (`tileSize`) and fill the row. From\n// `virtualizeFrom` tiles (100, as the table and list) React Aria's Virtualizer with `GridLayout`\n// draws only the visible rows of tiles in the grid's own scroll box, working out how many fit a row\n// and measuring each row of tiles. (Its tiles keep a margin of one gap at the edges of the box, which\n// the plain grid does not have.)\n\n/** The frame each picture is drawn in. */\nexport type TileAspect = \"square\" | \"portrait\" | \"landscape\";\n\n/** Smallest tile width: `sm` 96px (dense crops), `md` 144px, `lg` 192px. Tiles grow to fill the row. */\nexport type TileSize = \"sm\" | \"md\" | \"lg\";\n\nexport type SelectableGridProps<T> = {\n /** Names the grid of tiles. */\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n /** The picture, drawn to fill a frame of `aspect`. An `<img className=\"size-full object-cover\">` or a `Thumbnail`. */\n renderImage: (row: T) => React.ReactNode;\n /** A short line under the picture (a name, a date, a score). Truncated to one line. */\n detail?: (row: T) => React.ReactNode;\n /** The chosen keys and how to change them, as `DataTable` takes them; `rowLabel` names each tile's box. */\n selection: RowSelection<T>;\n /** Default `square`. `portrait` is 3:4, `landscape` 4:3. */\n aspect?: TileAspect;\n /** Default `md`. */\n tileSize?: TileSize;\n /** Tile count from which only the visible rows of tiles render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n className?: string;\n};\n\nconst minWidth: Record<TileSize, number> = { sm: 96, md: 144, lg: 192 };\nconst aspectClass: Record<TileAspect, string> = { square: \"aspect-square\", portrait: \"aspect-3/4\", landscape: \"aspect-4/3\" };\nconst aspectRatio: Record<TileAspect, number> = { square: 1, portrait: 4 / 3, landscape: 3 / 4 };\n// gap-3, in px.\nconst GAP = 12;\n// The detail line and the tile's padding, for the first estimate of a tile's height.\nconst TILE_CHROME = 40;\n\n/** A grid of pictures to choose from: each tile one labelled target, \"Select all shown\", Shift-click ranges, virtualised from `virtualizeFrom` tiles. Pair with `useSelection` and a `BulkBar`. */\nexport function SelectableGrid<T>({\n label,\n rows,\n rowKey,\n renderImage,\n detail,\n selection,\n aspect = \"square\",\n tileSize = \"md\",\n virtualizeFrom = 100,\n maxHeight = 480,\n className,\n}: SelectableGridProps<T>) {\n const select = useSelectRows(rows, rowKey, selection);\n const virtual = rows.length >= virtualizeFrom;\n const shownKeys = React.useMemo(() => new Set(rows.map(rowKey)), [rows, rowKey]);\n const disabledKeys = rows.filter((r) => !(selection.isSelectable?.(r) ?? true)).map(rowKey);\n\n // React Aria owns the selection of tiles: a press anywhere on a tile toggles it, Shift extends a\n // range from the last one, Space toggles from the keyboard. Our `RowSelection` holds keys only, and\n // keeps the keys of rows that are not shown (a filter), so the two are translated here.\n // A checkbox always toggles one tile in React Aria, and Shift-click on one still extends a range\n // (issue #32): Shift is noted on the press, and a change of exactly one tile is a click on it.\n // A press on the picture with Shift is React Aria's own range and changes several at once.\n const shift = useShiftNote();\n // The row last pressed (React Aria marks each row with `data-key`), to anchor a range it extended itself.\n const pressed = React.useRef<string | null>(null);\n const notePress = (e: React.SyntheticEvent) => void (pressed.current = (e.target as HTMLElement).closest(\"[data-key]\")?.getAttribute(\"data-key\") ?? null);\n const changeSelection = (next: Selection) => {\n if (next !== \"all\") {\n const nextShown = new Set([...next].map(String).filter((k) => shownKeys.has(k)));\n const added = [...nextShown].filter((k) => !selection.selected.has(k));\n const removed = [...selection.selected].filter((k) => shownKeys.has(k) && !nextShown.has(k));\n if (added.length + removed.length === 1) {\n select.toggle(added[0] ?? removed[0], added.length === 1, shift.take());\n return;\n }\n select.setAnchor(pressed.current);\n }\n const outside = [...selection.selected].filter((k) => !shownKeys.has(k));\n const picked = next === \"all\" ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [...next].map(String).filter((k) => shownKeys.has(k));\n selection.onChange(new Set([...outside, ...picked]));\n };\n\n // Tiles grow from `tileSize` to fill the row, and each row is as tall as its tallest tile as\n // measured (the first guess is the frame at the minimum width plus the detail line).\n const layoutOptions = React.useMemo(\n () => ({\n minItemSize: new Size(minWidth[tileSize], Math.round(minWidth[tileSize] * aspectRatio[aspect]) + TILE_CHROME),\n minSpace: new Size(GAP, GAP),\n }),\n [tileSize, aspect],\n );\n\n const grid = (\n <GridList\n aria-label={label}\n layout=\"grid\"\n selectionMode=\"multiple\"\n selectionBehavior=\"toggle\"\n selectedKeys={new Set([...selection.selected].filter((k) => shownKeys.has(k)))}\n onSelectionChange={changeSelection}\n disabledKeys={disabledKeys}\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 outline-none\", virtual ? \"overflow-y-auto\" : \"grid gap-3\")}\n style={\n virtual\n ? { height: maxHeight }\n : { gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` }\n }\n >\n {rows.map((row, index) => {\n const key = rowKey(row);\n const name = selection.rowLabel(row);\n return (\n <GridListItem\n key={key}\n id={key}\n textValue={name}\n data-index={index}\n className={cn(\n // select-none: a Shift-click range would otherwise also select the text between the tiles.\n \"group relative grid min-w-0 gap-1.5 rounded-surface border border-transparent p-1.5 select-none outline-offset-2 transition-state\",\n \"selected:border-primary selected:bg-surface-sunken disabled:cursor-not-allowed disabled:opacity-50\",\n \"cursor-pointer hover:bg-surface-sunken disabled:hover:bg-transparent\",\n )}\n >\n <span className={cn(\"block overflow-hidden rounded-control bg-muted *:size-full *:object-cover\", aspectClass[aspect])}>\n {renderImage(row)}\n </span>\n <TileBox label={`Select ${name}`} />\n {detail?.(row) != null && <span className=\"truncate type-body-sm text-muted-foreground\">{detail(row)}</span>}\n </GridListItem>\n );\n })}\n </GridList>\n );\n\n return (\n <div\n className={cn(\"grid min-w-0 gap-3\", className)}\n onMouseDownCapture={(e) => {\n shift.handlers.onMouseDown(e);\n notePress(e);\n }}\n onKeyDownCapture={(e) => {\n shift.handlers.onKeyDown(e);\n notePress(e);\n }}\n >\n <Checkbox\n className=\"justify-self-start\"\n label=\"Select all shown\"\n checked={select.all.checked}\n disabled={select.all.disabled}\n onCheckedChange={select.all.toggle}\n />\n {virtual ? (\n <Virtualizer layout={GridLayout} layoutOptions={layoutOptions}>\n {grid}\n </Virtualizer>\n ) : (\n grid\n )}\n </div>\n );\n}\n\n// The box in the tile's corner: React Aria's selection checkbox for this row (`slot=\"selection\"`),\n// named from the row, on a chip of the page's ground so it stays visible on any photo.\nfunction TileBox({ label }: { label: string }) {\n // The grid would name the box from its own label and the row's; ours is named by `rowLabel`\n // alone, so it labels itself.\n const id = React.useId();\n return (\n <AriaCheckbox slot=\"selection\" id={id} aria-labelledby={id} aria-label={label} className=\"absolute top-3 left-3 grid size-7 place-items-center rounded-control bg-background\">\n {({ isSelected }) => (\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 place-items-center rounded-control border border-input bg-background\",\n isSelected && \"border-primary bg-primary text-primary-foreground\",\n )}\n >\n {isSelected && <Check className=\"size-3.5\" strokeWidth={3} />}\n </span>\n )}\n </AriaCheckbox>\n );\n}\n","import * as React from \"react\";\nimport { Collection, GridList, GridListItem, ListLayout, Virtualizer } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A long list that keeps only its visible rows in the DOM, for feeds, logs and pickers with hundreds\n// of items. It is React Aria's `GridList` inside its `Virtualizer` (`ListLayout`), not a list we\n// virtualise ourselves: one keyboard model (arrows between rows, Home and End, type-ahead is off\n// because rows are arbitrary content), one set of ARIA (`row`s in a labelled `grid`, with\n// `aria-rowindex` and the row count so a screen reader still hears \"12 of 480\"), and focus that\n// survives a row scrolling out of the DOM. Rows are measured after render, so variable heights\n// work; `estimateSize` only sets the first paint, and `rowHeight` says every row is exactly that\n// tall, which skips measuring (and is what a test DOM, which does no layout, needs). Under\n// `virtualizeFrom` items it renders the same grid without the Virtualizer, so the roles do not\n// change as a list grows past it.\n//\n// The scroll region is the grid itself (`data-strata-scroll`, which `useInView` looks for), so there\n// is no wrapper region: the grid is labelled and focusable, and scrolls from the keyboard.\n// `bounded` keeps a short list in the same scroll box (capped at `height`) that the virtual one\n// uses, so a list that grows past `virtualizeFrom` while someone scrolls it (InfiniteList) does not\n// jump from the page's flow into a box. `footer` is one more row after the last item, inside the\n// scroll box: where InfiniteList puts its next-page row (a virtualised collection can only hold\n// rows, so the footer is one). Rows carry `data-index` in both modes.\n//\n// This replaced a list built on TanStack Virtual with `ul` and `li` (Jonathan, 2026-11-12). The roles\n// changed from list and listitem to grid and row; UPGRADING.md has it.\n\nconst FOOTER = \"\\u0000footer\";\n\n/** A list that renders only its visible rows (React Aria's GridList and Virtualizer) from `virtualizeFrom` items, with arrow-key navigation between rows. */\nexport function VirtualList<T>({\n label,\n items,\n itemKey,\n children,\n estimateSize = 48,\n rowHeight,\n height = 480,\n virtualizeFrom = 100,\n bounded = false,\n footer,\n className,\n}: {\n label: string;\n items: T[];\n itemKey: (item: T) => string;\n children: (item: T, index: number) => React.ReactNode;\n /** First-paint height of a row, in px; rows are measured after they render. */\n estimateSize?: number;\n /** Every row is exactly this tall (px): nothing is measured. */\n rowHeight?: number;\n height?: number;\n virtualizeFrom?: number;\n /** Scroll inside a box capped at `height` even below `virtualizeFrom`, so growing past it changes nothing on screen. */\n bounded?: boolean;\n /** After the last row, inside the scroll box (a next-page row, an end note). */\n footer?: React.ReactNode;\n className?: string;\n}) {\n const virtual = items.length >= virtualizeFrom;\n const rows = React.useMemo(() => items.map((item, index) => ({ id: itemKey(item), item, index })), [items, itemKey]);\n const layoutOptions = React.useMemo(() => (rowHeight ? { rowHeight } : { estimatedRowHeight: estimateSize }), [rowHeight, estimateSize]);\n // A bounded list (InfiniteList) is virtualised from its first row, so its scroll box and its\n // rows are never remounted as it grows past `virtualizeFrom`: a remount would reset the scroll\n // position in the middle of a scroll. The Virtualizer only draws what is visible, so a short\n // list costs nothing extra.\n const virtualise = virtual || bounded;\n const scrolls = virtualise;\n\n const list = (\n <GridList\n aria-label={label}\n selectionMode=\"none\"\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 outline-none\", scrolls && \"overflow-y-auto\", className)}\n style={scrolls ? (virtual ? { height } : { maxHeight: height }) : undefined}\n >\n <Collection items={rows}>\n {(row) => (\n <GridListItem id={row.id} textValue={row.id} data-index={row.index} className={cn(\"min-w-0 outline-offset-[-2px]\", row.index > 0 && \"border-t border-border\")}>\n {children(row.item, row.index)}\n </GridListItem>\n )}\n </Collection>\n {footer && (\n <GridListItem id={FOOTER} textValue=\"More\" className=\"min-w-0\">\n {footer}\n </GridListItem>\n )}\n </GridList>\n );\n\n return virtualise ? (\n <Virtualizer layout={ListLayout} layoutOptions={layoutOptions}>\n {list}\n </Virtualizer>\n ) : (\n list\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, RotateCcw } from \"lucide-react\";\nimport { ListStateContext } from \"react-aria-components\";\nimport { Button } from \"./button\";\nimport { DataView, type LoadFailure } from \"./data-view\";\nimport { VirtualList } from \"./virtual-list\";\nimport type { InfiniteLoad } from \"../query/infinite\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A list that loads its next page as the person nears the end: the view for `useInfiniteLoad`.\n// It is DataView for the first page (skeleton, error with Try again, empty state, all required)\n// and VirtualList for the rows (virtualised from 100, so a long session stays fast), with one row\n// after the last item that is always in one of four states:\n//\n// - more to come: an IntersectionObserver sentinel with a root margin, so the next page is asked\n// for before the person reaches the end, and a real \"Show more\" button behind it. The button is\n// the keyboard and screen-reader path (an automatic load is invisible to them) and the fallback\n// where the observer never fires.\n// - loading: `moreSkeleton`, mirroring the rows that are coming, not a spinner, and a polite\n// status so a screen reader hears it.\n// - a later page failed: an alert row with the reason and Try again. The items already loaded\n// stay; a failed page 4 is not a failed list. The sentinel stops asking until Try again, so a\n// dead server is not called in a loop.\n// - the end: `end`, if given (\"That's every firing since March\"), so the person knows it is all.\n//\n// `keepAtLeast` loads more whenever fewer items than that are held: a queue people work through\n// (answered items `dismiss`ed) refills before it runs dry, even when nothing scrolls. Showing\n// more by button moves focus to the first new item, because the button the person pressed is\n// gone. The list scrolls in its own region (`height`) from the first page, so passing 100 items\n// and switching to virtual rows changes nothing on screen.\n//\n// Not every paged view is a list in a box (strata-react issue #49, from the Tubes viewer, whose\n// videos are a responsive card grid that scrolls with the page). So the next-page row is its own\n// export, `LoadMore`, which an app puts after any list or grid it draws itself, and InfiniteList\n// is built on it. `scroll=\"page\"` is the same in InfiniteList: no scroll region of its own and no\n// virtual rows, the items in a plain `ul` laid out by `listClassName` (a grid), and the sentinel\n// watching the viewport. Virtual rows need a box of known height, which a page-scrolled grid is\n// not; a feed long enough to need them belongs in the region. `error` and `moreError` replace the\n// look of a failed first page and a failed later page, as DataView's `error` does.\n\n// The row a virtualised list draws for `LoadMore` is recycled when its height changes (button to\n// skeleton to button), which remounts `LoadMore` and drops what it remembers. The index to focus after\n// a click on Show more therefore lives in the list around it (InfiniteList), reached through this\n// context; a `LoadMore` used on its own keeps it in itself.\nconst PendingFocus = React.createContext<React.MutableRefObject<number | null> | null>(null);\n\n/** The next-page row's props: `InfiniteList`'s, for a list or grid the app draws itself. */\nexport type LoadMoreProps<T> = {\n state: InfiniteLoad<T>;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The items of a page on its way, mirroring the ones already drawn. */\n moreSkeleton: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). Default 400px. */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** Draws a failed later page, given the reason and the Try again. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n};\n\nfunction MoreFailed({ message, retry }: LoadFailure) {\n return (\n <div className=\"flex flex-wrap items-start gap-3 border-t border-border bg-danger-subtle px-3 py-2 text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultMoreError = (failure: LoadFailure) => <MoreFailed {...failure} />;\n\n/**\n * The row after a cursor-paged list or grid: loads the next page as it nears the screen, shows\n * `moreSkeleton` while it comes, says why it failed with Try again, offers Show more for the\n * keyboard, and `end` after the last page. After Show more it focuses the first new item: mark\n * each item with `data-index` and put this row beside the list, in the same parent.\n */\nexport function LoadMore<T>({\n state,\n moreLabel,\n moreSkeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n error: drawError = defaultMoreError,\n className,\n}: LoadMoreProps<T>) {\n const { more } = state;\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const box = React.useRef<HTMLDivElement>(null);\n const near = useInView({ active: ready && more.hasMore, rootMargin });\n // Inside a VirtualList the rows are React Aria's grid rows, which keep their own idea of which row\n // has focus; moving focus to a new row has to tell that state, or it takes focus back.\n const grid = React.useContext(ListStateContext);\n\n // Load on approach, and keep a worked-through queue topped up. Not after a failure: that waits\n // for Try again. Re-runs when a page lands, so a sentinel still in view asks for the next one.\n const { hasMore, loadingMore, error, loadMore } = more;\n React.useEffect(() => {\n if (!ready || !hasMore || loadingMore || error) return;\n if (near.inView || held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, error, near.inView, held, keepAtLeast, loadMore]);\n\n // After a click on Show more or Try again, focus the first new item: the button is gone.\n const own = React.useRef<number | null>(null);\n const shared = React.useContext(PendingFocus);\n const focusFrom = shared ?? own;\n const loadByHand = () => {\n focusFrom.current = held;\n loadMore();\n };\n React.useEffect(() => {\n const from = focusFrom.current;\n if (from === null || loadingMore) return;\n if (held <= from) {\n if (error || !hasMore) focusFrom.current = null;\n return;\n }\n // The new row may not be in the DOM yet: a virtualised list draws it a frame after its data\n // arrives. Look for it for a few frames, then give up rather than wait for ever.\n let frames = 0;\n let frame = 0;\n const find = () => {\n const scope = box.current?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? box.current?.parentElement;\n const item = scope?.querySelector<HTMLElement>(`[data-index=\"${from}\"]`);\n if (!item) {\n if (frames++ < 30) frame = requestAnimationFrame(find);\n else focusFrom.current = null;\n return;\n }\n const key = item.getAttribute(\"data-key\");\n if (grid && key !== null) {\n grid.selectionManager.setFocused(true);\n grid.selectionManager.setFocusedKey(key);\n }\n item.tabIndex = -1;\n item.focus();\n focusFrom.current = null;\n };\n find();\n return () => cancelAnimationFrame(frame);\n }, [held, loadingMore, error, hasMore, grid]);\n\n if (!ready) return null;\n return (\n <div ref={box} className={className}>\n {hasMore && !error && <div ref={near.ref} aria-hidden className=\"h-px\" />}\n {loadingMore ? (\n <div aria-hidden className=\"border-t border-border\">{moreSkeleton}</div>\n ) : error ? (\n <div role=\"alert\">{drawError({ message: error, retry: loadByHand })}</div>\n ) : hasMore ? (\n <div className=\"border-t border-border py-3\">\n <Button size=\"sm\" onClick={loadByHand}>\n {moreLabel}\n </Button>\n </div>\n ) : (\n end && <div className=\"border-t border-border py-3 type-body-sm text-muted-foreground\">{end}</div>\n )}\n <p role=\"status\" className=\"sr-only\">\n {loadingMore ? \"Loading more\" : \"\"}\n </p>\n </div>\n );\n}\n\n/** The infinite list's props. */\nexport type InfiniteListProps<T> = {\n state: InfiniteLoad<T>;\n /** The list's accessible name, e.g. \"Firing log, newest first\". */\n label: string;\n children: (item: T, index: number) => React.ReactNode;\n /** The first load. Mirrors the final layout, so nothing jumps when data arrives. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it, when the first page is empty and there are no more. */\n empty: React.ReactNode;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The rows of a page on its way. Defaults to `skeleton`. */\n moreSkeleton?: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** `region` (default): rows in a scroll region of `height`, virtual from `virtualizeFrom`. `page`: a plain list that scrolls with the page, laid out by `listClassName`. */\n scroll?: \"region\" | \"page\";\n /** With `scroll=\"page\"`: the classes of the `ul`, such as a responsive grid (`grid gap-4 sm:grid-cols-2 lg:grid-cols-3`). */\n listClassName?: string;\n /** Draws a failed first page. Defaults to DataView's `LoadError`. */\n error?: (failure: LoadFailure) => React.ReactNode;\n /** Draws a failed later page. Defaults to a danger row with Try again. */\n moreError?: (failure: LoadFailure) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n className?: string;\n};\n\n/** A cursor-paged list for `useInfiniteLoad`: DataView's first-page states, virtual rows (or a page-scrolled grid), and a `LoadMore` row that loads on approach, shows a skeleton, or says why it failed with Try again. */\nexport function InfiniteList<T>({\n state,\n label,\n children,\n skeleton,\n empty,\n moreLabel,\n moreSkeleton = skeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n scroll = \"region\",\n listClassName,\n error,\n moreError,\n estimateSize,\n height = 480,\n virtualizeFrom,\n className,\n}: InfiniteListProps<T>) {\n const { more, itemKey } = state;\n const pendingFocus = React.useRef<number | null>(null);\n // The queue refill lives here, not in LoadMore: in a virtualised region the footer row is only\n // mounted while it is near the viewport, and a queue below `keepAtLeast` must refill regardless.\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const { hasMore, loadingMore, error: moreFailure, loadMore } = more;\n React.useEffect(() => {\n if (ready && hasMore && !loadingMore && !moreFailure && held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, moreFailure, held, keepAtLeast, loadMore]);\n const footer = (\n <PendingFocus.Provider value={pendingFocus}>\n <LoadMore\n // A grid's cards have their own edges, so the row keeps a gap from them.\n className={scroll === \"page\" ? \"mt-4\" : undefined}\n state={state}\n moreLabel={moreLabel}\n moreSkeleton={moreSkeleton}\n end={end}\n rootMargin={rootMargin}\n error={moreError}\n />\n </PendingFocus.Provider>\n );\n\n return (\n <DataView\n state={state}\n isEmpty={(items) => items.length === 0 && !more.hasMore}\n skeleton={skeleton}\n empty={empty}\n error={error}\n className={className}\n >\n {(items) =>\n scroll === \"page\" ? (\n <div aria-busy={more.loadingMore || undefined}>\n <ul aria-label={label} className={cn(\"min-w-0\", listClassName ?? \"grid\")}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"min-w-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n {footer}\n </div>\n ) : (\n <div aria-busy={more.loadingMore || undefined}>\n <VirtualList\n label={label}\n items={items}\n itemKey={itemKey}\n estimateSize={estimateSize}\n height={height}\n virtualizeFrom={virtualizeFrom}\n bounded\n footer={footer}\n >\n {children}\n </VirtualList>\n </div>\n )\n }\n </DataView>\n );\n}\n","import * as React from \"react\";\nimport { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport { useSliderState } from \"react-stately\";\nimport { cn } from \"../lib/utils\";\n\n// A line chart with the defaults real product screens use: one measured series in one hue, a 2px\n// straight line with no fill and no markers, 3 to 5 faint gridlines, no y-axis line, no legend for a\n// single series (the series is labelled where it ends). Values never live only in a hover tooltip:\n// the latest and peak readings are labelled on the chart and every reading is in a table for screen\n// readers. Optional extras exist only where they answer a question: a dashed `planned` series, a\n// horizontal `band` (a threshold that matters), and a `now` marker.\n//\n//\n// `colourScale` colours the measured line by its own value, for subjects where that colour is a\n// fact rather than decoration: a kiln's glow by temperature, water by depth. The y position still\n// carries the value, so the colour is never the only cue. Without a reason in DESIGN.md, use one\n// hue.\n//\n// It draws in real pixels (measured with ResizeObserver) rather than scaling a fixed viewBox, so\n// the 12px labels stay 12px on a phone. Because the labels keep their size, the chart thins the\n// x ticks itself when they would collide (every second, third… tick, so the rhythm stays even)\n// and keeps the first and last label inside the chart, rather than overlapping on a phone.\n//\n// The y-axis autoscales to four gridline steps of a size people write on a scale, from zero (or\n// below it, if a reading is negative). `yMin` and `yMax` pin either end for a quantity whose range\n// is a fact of the subject (a percentage is 0 to 100, a battery 0 to 1): autoscaling a machine at\n// 1% CPU gives a 0 to 8% axis that makes it look busy (strata-react issue #23). A pin is a floor on\n// the extent, never a crop: a reading outside it widens the axis, because a chart that hides a\n// reading is worse than one with an untidy scale.\n//\n// Reading a value (`readout`, `onPick`) is React Aria's slider hooks (`useSlider`, `useSliderThumb`,\n// `useSliderState`) laid over the plot as `ReadingSlider`: the pointer press, the thumb's ARIA and the\n// hidden range input come from them. Two things are ours on top, checked in the hooks' source. The value\n// text: `useSliderState` formats through an object with `format`, `formatRange` and `resolvedOptions`, so\n// it is given one that says \"300 m: 60 m up\" instead of an `Intl.NumberFormat`. The stepping: the\n// state steps a continuous number by a fixed step, and a series has uneven readings, so a drag or a\n// press is snapped to the nearest reading and the keys (arrows, Home, End, Enter) are a capture handler\n// on the input that moves between readings; the hooks' own arrow handling is stopped. Hover is drawn\n// by the plot itself, since a hook has no notion of a pointer that is only resting.\n//\nexport type Point = { x: number; y: number };\n\nexport type LineChartProps = {\n /** What the chart shows, as a sentence. Used as the accessible name and the table caption. */\n label: string;\n series: Point[];\n seriesLabel: string;\n planned?: Point[];\n plannedLabel?: string;\n band?: { below: number; label: string };\n formatX: (x: number) => string;\n /** What x is, as the screen-reader table's first column heading: \"Distance\", \"Day\". Default \"Time\". */\n xLabel?: string;\n formatY: (y: number) => string;\n /** Where to put x labels, in x units. The chart drops every other one (and so on) when they would overlap at its width. */\n xTicks: number[];\n /** Pin the bottom of the y-axis (default: 0, or lower if a reading is negative). A reading below it still shows. */\n yMin?: number;\n /** Pin the top of the y-axis, for a bounded quantity such as a percentage (`yMax={100}`), so a low reading looks low. Choose a range that divides into four steps. A reading above it still shows. */\n yMax?: number;\n /** CSS colour for the measured series. Defaults to the first chart token. */\n colour?: string;\n /** Colour the measured series by value: each stop applies from `at` upwards, blending to the\n * next. Only where the colour means something in the subject; record the reason in DESIGN.md. */\n colourScale?: { at: number; colour: string }[];\n /** Says what the colours mean, shown beside the legend swatch when `colourScale` is set. */\n colourScaleLabel?: string;\n /** What the end of the line is. `\"now\"` marks the last reading with a rule, a dot and \"<value> now\": right for a live reading, where the last point is the present. `\"none\"` leaves it unmarked: right for a series whose x is not time running up to now (an elevation profile, where the last point is the finish). Default `\"now\"`, or `\"none\"` when `current` is set, since `current` already says where now is. The peak label stays either way. */\n end?: \"now\" | \"none\";\n /** The current x, supplied by the app and drawn as a rule with its value (\"now\" in a replay, a playhead). Cheap to update often. */\n current?: number;\n /** The value at the rule, as a sentence part. Default: `formatX` and the value read off the line. */\n formatCurrent?: (at: { x: number; y: number }) => string;\n /** Read values at the pointer, and by keyboard on the plot (arrows, Home, End). `readout` words the reading; default `formatX: formatY`. */\n readout?: boolean | ((p: Point) => string);\n /** The viewer chose a reading (a click, or Enter on the plot): its x, so the app can seek or select. */\n onPick?: (x: number) => void;\n /** One flat, pale tint under the line. Only where the area carries the meaning (a profile, a running total). */\n area?: boolean;\n height?: number;\n className?: string;\n};\n\nfunction useWidth<T extends HTMLElement>() {\n const ref = React.useRef<T>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n setWidth(el.getBoundingClientRect().width);\n const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n\n/** The smallest step of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ) at least `raw`. */\nfunction niceStep(raw: number) {\n const mag = 10 ** Math.floor(Math.log10(raw));\n return [1, 2, 2.5, 4, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)) ?? 10 * mag;\n}\n\n/**\n * The y-axis: four equal gridline steps covering every value. With no pins the steps are a size\n * people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), from zero or a round number below the lowest\n * reading. A pinned end is used as given unless a value lies beyond it.\n */\nexport function yScale(values: number[], pin: { min?: number; max?: number } = {}) {\n const finite = values.filter(Number.isFinite);\n const dMin = finite.length ? Math.min(...finite) : 0;\n const dMax = finite.length ? Math.max(...finite) : 0;\n const pinMin = pin.min !== undefined && dMin >= pin.min ? pin.min : undefined;\n const pinMax = pin.max !== undefined && dMax <= pin.max ? pin.max : undefined;\n let lo = pinMin ?? Math.min(0, dMin);\n // Readings all at a pinned top (say all -10 under yMax={-10}) leave no span: open one below.\n if (pinMax !== undefined && pinMin === undefined && !(pinMax > lo)) lo = pinMax - (Math.abs(pinMax) || 4);\n let min: number;\n let max: number;\n if (pinMax !== undefined) {\n max = pinMax;\n // Only the bottom is free: round it down to a step of the span, so 0 stays 0.\n min = pinMin ?? (lo < 0 ? Math.floor(lo / niceStep((max - lo) / 4)) * niceStep((max - lo) / 4) : 0);\n } else {\n const hi = Math.max(dMax, pin.max ?? -Infinity);\n // All-zero (or empty) data still needs a positive extent, or every coordinate divides by zero.\n let step = hi > lo ? niceStep((hi - lo) / 4) : 1;\n let base = pinMin ?? Math.floor(lo / step) * step;\n while (base + 4 * step < hi) {\n step = niceStep(step * 1.01);\n base = pinMin ?? Math.floor(lo / step) * step;\n }\n min = base;\n max = base + 4 * step;\n }\n if (!(max > min)) max = min + 4;\n return { min, max, ticks: [0, 1, 2, 3, 4].map((i) => min + ((max - min) * i) / 4) };\n}\n\n/** Roughly how wide a 12px caption label is, in px. jsdom cannot measure text, so the chart estimates. */\nconst labelWidth = (text: string) => text.length * 7;\n\n/**\n * The x ticks that fit at this width: every k-th tick, the smallest k for which neighbouring labels\n * leave a gap, so the spacing stays even. `scale` maps an x value to a pixel.\n */\nexport function fitTicks(ticks: number[], scale: (x: number) => number, widthOf: (t: number) => number, gap = 12) {\n if (ticks.length < 3) return ticks;\n const sorted = [...ticks].sort((a, b) => a - b);\n for (let k = 1; k < sorted.length; k++) {\n const kept = sorted.filter((_, i) => i % k === 0);\n const fits = kept.every((t, i) => i === 0 || scale(t) - scale(kept[i - 1]) >= (widthOf(t) + widthOf(kept[i - 1])) / 2 + gap);\n if (fits) return kept;\n }\n return sorted.slice(0, 1);\n}\n\n/** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */\nexport function LineChart({\n label,\n series,\n seriesLabel,\n planned,\n plannedLabel,\n band,\n formatX,\n xLabel = \"Time\",\n formatY,\n xTicks,\n yMin,\n yMax,\n colour = \"var(--chart-1)\",\n colourScale,\n colourScaleLabel,\n current,\n end,\n formatCurrent,\n readout,\n onPick,\n area,\n height = 280,\n className,\n}: LineChartProps) {\n const [ref, width] = useWidth<HTMLDivElement>();\n const gradientId = `heat-${React.useId().replace(/[^\\w-]/g, \"\")}`;\n const all = [...series, ...(planned ?? [])];\n const xMin = Math.min(...all.map((p) => p.x));\n const xMax = Math.max(...all.map((p) => p.x));\n const y = yScale(\n all.map((p) => p.y),\n { min: yMin, max: yMax },\n );\n\n const pad = { top: 16, right: 16, bottom: 28, left: 56 };\n const w = Math.max(0, width - pad.left - pad.right);\n const h = height - pad.top - pad.bottom;\n const sx = (x: number) => pad.left + ((x - xMin) / (xMax - xMin || 1)) * w;\n const sy = (v: number) => pad.top + h - ((v - y.min) / (y.max - y.min)) * h;\n const xLabelWidth = (t: number) => labelWidth(formatX(t));\n // Keep the first and last labels inside the chart instead of centring them past its edge.\n const xLabelAt = (t: number) => {\n const half = xLabelWidth(t) / 2;\n return Math.min(Math.max(sx(t), half), Math.max(half, width - half));\n };\n // Fit against where the labels are drawn, so pulling an end label in cannot make it collide.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const shownXTicks = React.useMemo(() => fitTicks(xTicks, xLabelAt, xLabelWidth), [xTicks, width, xMin, xMax, formatX]);\n const path = (pts: Point[]) => pts.map((p, i) => `${i ? \"L\" : \"M\"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(\"\");\n\n const last = series[series.length - 1];\n const showEnd = (end ?? (current === undefined ? \"now\" : \"none\")) === \"now\";\n const peak = series.reduce((a, b) => (b.y > a.y ? b : a), series[0]);\n const stops = colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : [];\n /** The colour a value lands on: the highest stop at or below it. Used for the labelled points. */\n const colourAt = (y: number) => (stops.length ? [...stops].reverse().find((s) => s.at <= y)?.colour ?? stops[0].colour : colour);\n const stroke = stops.length ? `url(#${gradientId})` : colour;\n\n // The plot itself, memoised: moving `current` or a pointer readout redraws only the overlay below.\n /* eslint-disable react-hooks/exhaustive-deps */\n const plot = React.useMemo(\n () => (\n <>\n {stops.length > 0 && (\n // A vertical gradient in chart space, so a colour sits at a temperature, not at a\n // point along the line: the line is the same red wherever it crosses 600 °C.\n <defs>\n <linearGradient id={gradientId} gradientUnits=\"userSpaceOnUse\" x1={0} x2={0} y1={sy(y.min)} y2={sy(y.max)}>\n {stops.map((s) => (\n <stop key={s.at} offset={Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min)))} stopColor={s.colour} />\n ))}\n </linearGradient>\n </defs>\n )}\n {band && band.below > y.min && (\n <g>\n <rect x={pad.left} y={sy(Math.min(band.below, y.max))} width={w} height={sy(y.min) - sy(Math.min(band.below, y.max))} fill=\"var(--success-subtle)\" />\n <text x={pad.left + 8} y={sy(Math.min(band.below, y.max)) + 16} className=\"fill-success type-caption\">\n {band.label}\n </text>\n </g>\n )}\n {y.ticks.map((t) => (\n <g key={t}>\n <line x1={pad.left} x2={pad.left + w} y1={sy(t)} y2={sy(t)} stroke=\"var(--border)\" strokeWidth={1} />\n <text x={pad.left - 8} y={sy(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatY(t)}\n </text>\n </g>\n ))}\n {shownXTicks.map((t) => (\n <text key={t} x={xLabelAt(t)} y={height - 8} textAnchor=\"middle\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatX(t)}\n </text>\n ))}\n {planned && (\n <path d={path(planned)} fill=\"none\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n )}\n {area && series.length > 1 && (\n // One flat pale tint, never a gradient: the area is the meaning, so it is a plain fill.\n <path d={`${path(series)}L${sx(series[series.length - 1].x).toFixed(1)},${sy(y.min).toFixed(1)}L${sx(series[0].x).toFixed(1)},${sy(y.min).toFixed(1)}Z`} fill={colour} fillOpacity={0.12} stroke=\"none\" />\n )}\n <path d={path(series)} fill=\"none\" stroke={stroke} strokeWidth={stops.length ? 2.5 : 2} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n {/* Direct labels instead of a legend and a tooltip. */}\n <circle cx={sx(peak.x)} cy={sy(peak.y)} r={3} fill={colourAt(peak.y)} />\n <text x={sx(peak.x) + 8} y={sy(peak.y) - 8} className=\"fill-foreground type-caption tabular-nums\">\n {formatY(peak.y)} peak\n </text>\n {showEnd && (\n <>\n <line x1={sx(last.x)} x2={sx(last.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--foreground)\" strokeWidth={1} />\n <circle cx={sx(last.x)} cy={sy(last.y)} r={3.5} fill={colourAt(last.y)} />\n <text x={sx(last.x) - 8} y={sy(last.y) - 10} textAnchor=\"end\" className=\"fill-foreground type-label tabular-nums\">\n {formatY(last.y)} now\n </text>\n </>\n )}\n </>\n ),\n [width, height, series, planned, band, xTicks, yMin, yMax, colour, colourScale, formatX, formatY, area, showEnd],\n );\n /* eslint-enable react-hooks/exhaustive-deps */\n\n // The screen-reader table is memoised with the plot: a moving rule must not rebuild every row.\n /* eslint-disable react-hooks/exhaustive-deps */\n const tableEl = React.useMemo(\n () => (\n // sr-only on a wrapper: a table ignores width: 1px and would widen the page.\n <div className=\"sr-only\">\n <table>\n <caption>{label}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{xLabel}</th>\n <th scope=\"col\">{seriesLabel}</th>\n </tr>\n </thead>\n <tbody>\n {series.map((p) => (\n <tr key={p.x}>\n <td>{formatX(p.x)}</td>\n <td>{formatY(p.y)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ),\n [label, seriesLabel, series, formatX, formatY, xLabel],\n );\n /* eslint-enable react-hooks/exhaustive-deps */\n\n // --- tied to the rest of the screen: the current rule, a readout, picking a reading --------\n const sorted = React.useMemo(() => [...series].sort((p, q) => p.x - q.x), [series]);\n const interactive = Boolean(readout || onPick);\n const [hover, setHover] = React.useState<number | null>(null);\n const [kbd, setKbd] = React.useState<number | null>(null);\n const [focused, setFocused] = React.useState(false);\n const readoutText = (pt: Point) => (typeof readout === \"function\" ? readout(pt) : `${formatX(pt.x)}: ${formatY(pt.y)}`);\n const nearest = (px: number) => {\n const target = xMin + ((px - pad.left) / (w || 1)) * (xMax - xMin || 1);\n let best = 0;\n for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - target) < Math.abs(sorted[best].x - target)) best = i;\n return best;\n };\n /** The value of the line at x, read between the two readings either side (flat beyond the ends). */\n const yAt = (x: number) => {\n if (!sorted.length) return 0;\n if (x <= sorted[0].x) return sorted[0].y;\n for (let i = 1; i < sorted.length; i++) {\n if (x <= sorted[i].x) {\n const [p0, p1] = [sorted[i - 1], sorted[i]];\n return p0.y + ((p1.y - p0.y) * (x - p0.x)) / (p1.x - p0.x || 1);\n }\n }\n return sorted[sorted.length - 1].y;\n };\n const currentAt = current === undefined ? null : { x: Math.min(Math.max(current, xMin), xMax), y: yAt(current) };\n // One reading is \"the\" selection for the announced value, the drawn marker and Enter: the pointer's\n // while it is over the plot, else the keyboard's (clamped, since `series` can be replaced by a shorter\n // one), else where the current rule is, else the last reading.\n const fallbackIdx = sorted.length ? (currentAt ? nearest(sx(currentAt.x)) : sorted.length - 1) : 0;\n const heldIdx = kbd === null ? fallbackIdx : Math.min(kbd, Math.max(sorted.length - 1, 0));\n const selectedIdx = hover === null ? heldIdx : Math.min(hover, Math.max(sorted.length - 1, 0));\n const active = (hover !== null || focused) && sorted.length ? sorted[selectedIdx] : null;\n const onKey = (e: React.KeyboardEvent) => {\n const at = selectedIdx;\n let next = at;\n if (e.key === \"ArrowRight\" || e.key === \"ArrowUp\") next = Math.min(at + 1, sorted.length - 1);\n else if (e.key === \"ArrowLeft\" || e.key === \"ArrowDown\") next = Math.max(at - 1, 0);\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = sorted.length - 1;\n else if ((e.key === \"Enter\" || e.key === \" \") && onPick) {\n e.preventDefault();\n onPick(sorted[at].x);\n return;\n } else return;\n e.preventDefault();\n setHover(null); // the key takes over from a pointer left resting on the plot\n setKbd(next);\n };\n const flip = (px: number, text: string) => (px + labelWidth(text) + 16 > width ? { x: px - 8, anchor: \"end\" as const } : { x: px + 8, anchor: \"start\" as const });\n\n return (\n <figure className={cn(\"grid min-w-0 gap-2\", className)}>\n <div ref={ref} className=\"relative min-w-0\">\n {width > 0 && (\n <svg width={width} height={height} role=\"img\" aria-label={label} className=\"block overflow-visible\">\n {plot}\n {currentAt && (\n <g aria-hidden>\n <line x1={sx(currentAt.x)} x2={sx(currentAt.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--primary)\" strokeWidth={1.5} />\n <circle cx={sx(currentAt.x)} cy={sy(currentAt.y)} r={4} fill=\"var(--background)\" stroke=\"var(--primary)\" strokeWidth={2} />\n {(() => {\n const text = formatCurrent ? formatCurrent(currentAt) : `${formatX(currentAt.x)}: ${formatY(currentAt.y)}`;\n const at = flip(sx(currentAt.x), text);\n return (\n <text x={at.x} y={pad.top + 12} textAnchor={at.anchor} className=\"fill-foreground type-caption tabular-nums\">\n {text}\n </text>\n );\n })()}\n </g>\n )}\n {active && (\n <g aria-hidden>\n <line x1={sx(active.x)} x2={sx(active.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--muted-foreground)\" strokeWidth={1} strokeDasharray=\"2 3\" />\n <circle cx={sx(active.x)} cy={sy(active.y)} r={4} fill=\"var(--foreground)\" />\n {(() => {\n const text = readoutText(active);\n const at = flip(sx(active.x), text);\n return (\n <text x={at.x} y={sy(active.y) - 10} textAnchor={at.anchor} className=\"fill-foreground type-label tabular-nums\" paintOrder=\"stroke\" stroke=\"var(--background)\" strokeWidth={3}>\n {text}\n </text>\n );\n })()}\n </g>\n )}\n </svg>\n )}\n {width > 0 && interactive && sorted.length > 0 && (\n <ReadingSlider\n label={`${label}: read values`}\n sorted={sorted}\n selected={selectedIdx}\n text={readoutText}\n onSelect={(i) => {\n setHover(null);\n setKbd(i);\n }}\n onPick={onPick}\n onKeyDownCapture={onKey}\n onHover={(px) => setHover(px === null ? null : nearest(px))}\n onFocusChange={setFocused}\n box={{ left: pad.left, top: pad.top, width: w, height: h }}\n />\n )}\n </div>\n <figcaption className=\"flex flex-wrap gap-x-5 gap-y-1 type-caption text-muted-foreground\">\n <span className=\"inline-flex items-center gap-2\">\n {stops.length ? (\n <svg width={stops.length * 8} height=\"3\" aria-hidden>\n {stops.map((s, i) => (\n <line key={s.at} x1={i * 8} x2={i * 8 + 8} y1=\"1.5\" y2=\"1.5\" stroke={s.colour} strokeWidth={3} />\n ))}\n </svg>\n ) : (\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke={colour} strokeWidth={2} />\n </svg>\n )}\n {seriesLabel}\n {stops.length > 0 && colourScaleLabel && <span>({colourScaleLabel})</span>}\n </span>\n {planned && plannedLabel && (\n <span className=\"inline-flex items-center gap-2\">\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n </svg>\n {plannedLabel}\n </span>\n )}\n </figcaption>\n {tableEl}\n </figure>\n );\n}\n\n\ntype ReadingSliderProps = {\n label: string;\n sorted: readonly Point[];\n selected: number;\n text: (p: Point) => string;\n onSelect: (index: number) => void;\n onPick?: (x: number) => void;\n onKeyDownCapture: (e: React.KeyboardEvent) => void;\n /** The pointer's x in the plot's own pixels, or null when it leaves. */\n onHover: (px: number | null) => void;\n onFocusChange: (focused: boolean) => void;\n box: { left: number; top: number; width: number; height: number };\n};\n\n/** The slider over the plot: React Aria's hooks, snapped to the readings, with the reading as its spoken value. */\nfunction ReadingSlider({ label, sorted, selected, text, onSelect, onPick, onKeyDownCapture, onHover, onFocusChange, box }: ReadingSliderProps) {\n const track = React.useRef<HTMLDivElement>(null);\n const input = React.useRef<HTMLInputElement>(null);\n const lo = sorted[0].x;\n const hi = Math.max(sorted[sorted.length - 1].x, lo + 1e-9);\n const indexAt = (x: number) => {\n let best = 0;\n for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - x) < Math.abs(sorted[best].x - x)) best = i;\n return best;\n };\n const spoken = React.useMemo(() => {\n const say = (x: number) => text(sorted[indexAt(x)]);\n return { format: say, formatRange: (a: number, b: number) => `${say(a)} to ${say(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) } as unknown as Intl.NumberFormat;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sorted, text]);\n const state = useSliderState({\n minValue: lo,\n maxValue: hi,\n step: (hi - lo) / 10000,\n value: [sorted[selected].x],\n onChange: ([x]) => onSelect(indexAt(x)),\n onChangeEnd: ([x]) => onPick?.(sorted[indexAt(x)].x),\n numberFormatter: spoken,\n });\n const { groupProps, trackProps } = useSlider({ \"aria-label\": label }, state, track);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: track, inputRef: input, \"aria-label\": label }, state);\n const { focusProps, isFocusVisible } = useFocusRing();\n return (\n <div {...groupProps} className=\"absolute\" style={box}>\n <div\n {...trackProps}\n ref={track}\n onPointerMove={(e) => onHover(e.clientX - e.currentTarget.getBoundingClientRect().left + box.left)}\n onPointerLeave={() => onHover(null)}\n className={cn(\"relative size-full cursor-crosshair touch-none\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")}\n >\n <div {...thumbProps} className=\"absolute inset-y-0 w-0\" style={{ left: `${state.getThumbPercent(0) * 100}%` }}>\n <VisuallyHidden>\n <input\n ref={input}\n {...mergeProps(inputProps, focusProps, { onFocus: () => onFocusChange(true), onBlur: () => onFocusChange(false) })}\n aria-labelledby={undefined}\n onKeyDownCapture={(e) => {\n onKeyDownCapture(e);\n if (e.defaultPrevented) e.stopPropagation();\n }}\n />\n </VisuallyHidden>\n </div>\n </div>\n </div>\n );\n}\n","import * as React from \"react\";\n\n// The top of every Operate screen: a noun title at 24px (never \"Welcome back\"), its scope, the\n// screen's main action, and the finding. The finding is the one fact in today's data that most\n// needs attention; it sits where it is read first, beside the action it drives.\n\n/** The top of an Operate screen: a noun title, its scope, the main action, and the finding (the one fact in today's data that most needs attention). */\nexport function PageHeader({\n title,\n scope,\n actions,\n finding,\n as: Heading = \"h1\",\n}: {\n title: string;\n /** The title's element: h1 on a screen, h2 where the header is shown inside another page. */\n as?: \"h1\" | \"h2\";\n /** What the screen covers: a date, a range, a filter. */\n scope?: React.ReactNode;\n actions?: React.ReactNode;\n finding?: { text: React.ReactNode; action?: React.ReactNode };\n}) {\n return (\n <header className=\"grid gap-4\">\n <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-3\">\n <div className=\"grid min-w-0 gap-0.5\">\n <Heading className=\"type-title text-balance\">{title}</Heading>\n {scope && <p className=\"type-body-sm text-muted-foreground\">{scope}</p>}\n </div>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions}</div>}\n </div>\n {finding && (\n <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-3 border-y border-border py-3\">\n <p className=\"max-w-prose min-w-0 type-body text-pretty\">{finding.text}</p>\n {finding.action}\n </div>\n )}\n </header>\n );\n}\n","import * as React from \"react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\n\n// Destructive actions take effect visibly at once and commit after a window, with Undo in reach.\n// For reversible removals this beats a confirm dialog: the dialog interrupts every time to protect\n// against the rare mistake, and people learn to click through it. Keep a confirm dialog for\n// actions that cannot be undone (deleting an account, firing a kiln).\n\n// A bulk removal is one removal with `ids`: the selected rows go, come back on Undo, and fail\n// together, under one message and one commit, because the person did one thing.\n//\n// One removal is pending at a time. Scheduling a second commits the first at once: in rapid-fire\n// triage (withdraw, withdraw, withdraw) Undo reaches back one step, and the bar never stacks up a\n// queue of messages nobody reads. Undo is for the slip just made, not for an audit trail.\n//\n// The hook owns which items are out of view (`isRemoved`), so a screen filters its rows by it and\n// never keeps a second \"hidden\" set that can drift from the pending one. An item stays removed\n// from when it is scheduled; Undo brings it back; a commit that fails brings it back and puts the\n// failure in the same bar, with \"Try again\", because the screen told the person it was done and a\n// silent failure would leave the screen lying. A committed item stays removed until the screen's\n// data drops it (the commit should invalidate the query it came from), so it never flickers back.\n//\n// `flush()` exists for the action that depends on the removal having happened (retrain on the\n// answers, export the list): commit now and await it, rather than racing the window.\n//\n// Failures are described like any other failed action (`describeActionError`, as AsyncButton uses,\n// unless the product passes its own): the same HTTP sentences as reads, without promising that\n// nothing changed, since a write that failed may still have reached the server.\n\n/** A removal waiting out its undo window: what to say, what to do when the window closes, and what to say if that fails. */\nexport type PendingRemoval = {\n /** Identifies the removed item: `isRemoved(id)` is true from `schedule` until Undo or a failed commit. */\n id: string;\n /** A bulk removal's items, all removed, undone, committed and restored together (one `commit` for the batch). `isRemoved` is true for each. Default `[id]`. */\n ids?: readonly string[];\n /** What happened, in the product's words: \"Withdrew Tom Ellery's 3 pieces from kiln 2.\" */\n message: string;\n /** What the person reads if the commit fails, saying the item is back: \"Tom Ellery's 3 pieces are back in kiln 2: the withdrawal did not go through.\" */\n failure: string;\n /** Makes the removal real (usually a request, then invalidating the query the item came from). Runs once per attempt: when the window closes, on `flush()`, when a second removal is scheduled, or when the owner unmounts. */\n commit: () => void | Promise<unknown>;\n /** Called after a failed commit, for anything beyond restoring the item and showing the failure (which the hook does). The only failure path once the owner has unmounted. */\n onError?: (error: unknown) => void;\n};\n\n/** A removal whose commit failed: the removal, and the error described for a person. */\nexport type FailedRemoval = { removal: PendingRemoval; message?: string };\n\n/** Options for `useUndoable`. */\nexport type UndoableOptions = {\n /** How long Undo stays in reach, in milliseconds. Default 8000. */\n windowMs?: number;\n /** Describes a failed commit for a person, or returns undefined to show the removal's `failure` alone. Default `describeActionError`, as for `useAsyncAction`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useUndoable` returns. Pass it whole to `UndoBar`. */\nexport type Undoable = {\n /** The removal inside its window, or null. */\n pending: PendingRemoval | null;\n /** The last removal whose commit failed, until it is retried, dismissed or another removal is scheduled. */\n failed: FailedRemoval | null;\n /** Whether an item is out of view: scheduled, committing or committed, and not undone or failed. Filter rows with it. */\n isRemoved: (id: string) => boolean;\n /** Removes an item and starts its window. Commits any removal already pending first: only one is pending at a time. */\n schedule: (next: PendingRemoval) => void;\n /** Cancels the pending removal and brings the item back; its `commit` never runs. */\n undo: () => void;\n /** Commits the pending removal now and resolves when it and every earlier commit still in flight have settled; rejects if any failed, so a dependent action does not run. Resolves at once when nothing is pending or running. */\n flush: () => Promise<void>;\n /** Removes the failed item again and commits it now (the person already waited out the window); settles like `flush`. */\n retry: () => Promise<void>;\n /** Clears the failure from the bar; the item stays back. */\n dismiss: () => void;\n};\n\n/**\n * Schedules a reversible removal to commit after a window unless undone, and owns which items\n * are out of view meanwhile.\n *\n * Only one removal is pending at a time: scheduling a second commits the first immediately.\n * Unmounting inside the window commits the pending removal (leaving is not Undo), so a navigation\n * or a test that unmounts still sends the commit's request: await `flush()` before a dependent\n * action, and in tests let MSW answer the request or flush before unmounting.\n */\nexport function useUndoable(options: number | UndoableOptions = {}): Undoable {\n const { windowMs = 8000, describeError = describeActionError } =\n typeof options === \"number\" ? { windowMs: options } : options;\n const [pending, setPending] = React.useState<PendingRemoval | null>(null);\n const [failed, setFailed] = React.useState<FailedRemoval | null>(null);\n const [removed, setRemoved] = React.useState<ReadonlySet<string>>(() => new Set());\n const current = React.useRef<PendingRemoval | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n // Every commit still running, whoever started it: flush() waits for all of them, not only the\n // pending one, because an earlier removal's request may still be in flight (its window closed,\n // or a second removal committed it) and a dependent action must not overtake it.\n const inFlight = React.useRef(new Set<Promise<void>>());\n const describe = React.useRef(describeError);\n describe.current = describeError;\n\n const hide = React.useCallback((p: PendingRemoval, out: boolean) => {\n const ids = p.ids ?? [p.id];\n setRemoved((s) => {\n if (ids.every((id) => s.has(id) === out)) return s;\n const n = new Set(s);\n for (const id of ids) {\n if (out) n.add(id);\n else n.delete(id);\n }\n return n;\n });\n }, []);\n\n // Runs one attempt at a removal's commit. A synchronous throw is treated like a rejection, so\n // there is one failure path: bring the item back, show the failure, tell onError, reject.\n const attempt = React.useCallback(\n (p: PendingRemoval): Promise<void> => {\n let result: void | Promise<unknown>;\n try {\n result = p.commit();\n } catch (error) {\n result = Promise.reject(error);\n }\n const done = Promise.resolve(result).then(\n () => undefined,\n (error: unknown) => {\n if (mounted.current) {\n hide(p, false);\n setFailed({ removal: p, message: describe.current(error) });\n }\n p.onError?.(error);\n throw error;\n },\n );\n inFlight.current.add(done);\n const settle = () => void inFlight.current.delete(done);\n done.then(settle, settle);\n return done;\n },\n [hide],\n );\n\n // Takes the pending removal out (so it commits only once) and attempts it.\n const take = React.useCallback((): { removal: PendingRemoval; done: Promise<void> } | null => {\n window.clearTimeout(timer.current);\n const p = current.current;\n if (!p) return null;\n current.current = null;\n if (mounted.current) setPending(null);\n return { removal: p, done: attempt(p) };\n }, [attempt]);\n\n // Commits the hook starts itself (window closed, second removal, unmount) have no caller to\n // await them. A failure is handled once it is in the bar or onError has it; only a failure\n // nobody can see (unmounted, no onError) is left to surface as an unhandled rejection.\n const commitDetached = React.useCallback(() => {\n const t = take();\n t?.done.catch((error: unknown) => {\n if (!mounted.current && !t.removal.onError) throw error;\n });\n }, [take]);\n\n const schedule = React.useCallback(\n (next: PendingRemoval) => {\n commitDetached(); // a second removal commits the first\n setFailed(null);\n hide(next, true);\n current.current = next;\n setPending(next);\n timer.current = window.setTimeout(commitDetached, windowMs);\n },\n [commitDetached, hide, windowMs],\n );\n\n const undo = React.useCallback(() => {\n window.clearTimeout(timer.current);\n const p = current.current;\n current.current = null;\n setPending(null);\n if (p) hide(p, false);\n }, [hide]);\n\n const flush = React.useCallback(async () => {\n take();\n const results = await Promise.allSettled([...inFlight.current]);\n const failure = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\");\n if (failure) throw failure.reason;\n }, [take]);\n\n const retry = React.useCallback(() => {\n if (!failed) return Promise.resolve();\n setFailed(null);\n hide(failed.removal, true);\n return attempt(failed.removal);\n }, [attempt, failed, hide]);\n\n const dismiss = React.useCallback(() => setFailed(null), []);\n\n const isRemoved = React.useCallback((id: string) => removed.has(id), [removed]);\n\n // Leaving the screen is not Undo: if the owner unmounts inside the window (the person navigated\n // away), commit what was scheduled rather than silently dropping it.\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n commitDetached();\n };\n }, [commitDetached]);\n\n return { pending, failed, isRemoved, schedule, undo, flush, retry, dismiss };\n}\n\n// The bar lives in a polite live region that is always mounted, so screen readers hear the message\n// when it appears, and a failure replaces the message in the same place the person was looking.\n// It is fixed to the bottom of the viewport; a page that uses it keeps that much bottom padding so\n// the bar never covers the focused row. A failure stays until it is retried or dismissed: an error\n// that times out is one a person can miss.\n/** The polite live region that shows a pending removal with Undo, or a failed one with Try again. Pass it the whole `useUndoable()` result. */\nexport function UndoBar({\n undoable,\n inline = false,\n}: {\n undoable: Pick<Undoable, \"pending\" | \"failed\" | \"undo\" | \"retry\" | \"dismiss\">;\n /** Render in the flow instead of fixed to the viewport; for the state-matrix page. */\n inline?: boolean;\n}) {\n const { pending, failed, undo, retry, dismiss } = undoable;\n const ghost = \"text-background hover:bg-neutral-11\";\n return (\n <div\n aria-live=\"polite\"\n className={\n inline ? \"flex\" : \"layer-bar pointer-events-none fixed inset-x-0 bottom-4 flex justify-center px-4\"\n }\n >\n {(pending || failed) && (\n <div className=\"pointer-events-auto flex max-w-lg items-center gap-4 rounded-overlay bg-foreground py-2 pr-2 pl-4 text-background shadow-overlay\">\n {pending ? (\n <>\n <p className=\"min-w-0 type-body-sm\">{pending.message}</p>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={undo}>\n Undo\n </Button>\n </>\n ) : (\n failed && (\n <>\n <p className=\"min-w-0 type-body-sm\">\n {failed.message ? `${failed.removal.failure} ${failed.message}` : failed.removal.failure}\n </p>\n <div className=\"flex shrink-0 gap-1\">\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={() => void retry().catch(() => undefined)}>\n Try again\n </Button>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={dismiss}>\n Dismiss\n </Button>\n </div>\n </>\n )\n )}\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Check } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// The completion moment: what a person sees after finishing something that took effort (a\n// booking, a submission, an import). It is the one place on an Operate product where the library\n// spends its delight budget (character.md §3), so it is a component with rules rather than a\n// confetti call:\n// - `title` says what happened, in the past tense, with the object: \"Booked: 6 pieces in kiln 2\".\n// - `next` is required. A finish that does not say what happens now is a dead end, however\n// pleasant.\n// - `figure` is optional and must be drawn from the person's own data in the subject's terms\n// (their pieces on a shelf, their route on a map), never a stock illustration.\n// - The part of the figure that is the person's result enters once, with the `enter-moment`\n// utility (500ms, hard ease-out, no overshoot): their pieces set down on the shelf. Reduced\n// motion makes it instant. Nothing loops and nothing plays a sound.\n// - Focus moves to the heading on mount, so keyboard and screen-reader users land on the result.\n\n/** The completion moment for a rare, earned finish: what happened (past tense, with its object), what happens next, and optionally a figure drawn from the person's own data. Focus moves to the heading. */\nexport function Done({\n title,\n next,\n figure,\n actions,\n focusOnMount = true,\n className,\n}: {\n /** What happened, past tense, with its object. */\n title: string;\n /** What the person does now, or what happens next and when. */\n next: React.ReactNode;\n /** A drawing of the result made from the person's data in the subject's own terms. */\n figure?: React.ReactNode;\n actions?: React.ReactNode;\n /** Off only where the result is not the page's subject (the state-matrix page). */\n focusOnMount?: boolean;\n className?: string;\n}) {\n const heading = React.useRef<HTMLHeadingElement>(null);\n const titleId = React.useId();\n React.useEffect(() => {\n if (focusOnMount) heading.current?.focus();\n }, [focusOnMount]);\n return (\n <section aria-labelledby={titleId} className={cn(\"grid gap-5\", className)}>\n <div className=\"grid gap-2\">\n <h1 id={titleId} ref={heading} tabIndex={-1} className=\"flex items-start gap-2 type-title\">\n <Check aria-hidden className=\"mt-1 size-6 shrink-0 text-success\" />\n {title}\n </h1>\n <div className=\"max-w-prose type-body text-muted-foreground\">{next}</div>\n </div>\n {figure}\n {actions && <div className=\"flex flex-wrap items-center gap-3\">{actions}</div>}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Link, NavLink } from \"react-router\";\nimport { cn } from \"../lib/utils\";\nimport type { IconComponent } from \"../lib/icon\";\n\n// The frame of an app: a side nav on the page ground (not a navy or tinted sidebar), the current\n// item as a neutral pill (no left bar, no accent), and the page beside it. A top bar exists only\n// when it holds something used on every screen, so it is a slot, not a default. Built on React\n// Router's NavLink, so \"current\" is the router's answer and aria-current is set for free. On\n// phones the nav becomes a horizontal, scrollable row above the page rather than a hamburger, so\n// every destination stays one tap away.\n\nexport type NavItem = {\n to: string;\n label: string;\n icon?: IconComponent;\n /** Match only this exact path, for an index route such as \"/\". */\n end?: boolean;\n};\n\n/** The app frame: product name, side nav on the page ground (a scrollable row on phones), optional top bar, and the main region. */\nexport function AppShell({\n product,\n nav,\n navLabel = \"Main\",\n topBar,\n children,\n className,\n}: {\n /** The product's name or mark, linking home. */\n product: React.ReactNode;\n nav: NavItem[];\n navLabel?: string;\n topBar?: React.ReactNode;\n children: React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-h-dvh md:grid md:grid-cols-[14rem_minmax(0,1fr)]\", className)}>\n <aside className=\"border-b border-border md:border-r md:border-b-0\">\n <div className=\"flex items-center gap-4 px-4 py-3 md:block md:px-3 md:py-4\">\n <Link to=\"/\" className=\"shrink-0 rounded-control px-2 type-heading text-foreground no-underline\">\n {product}\n </Link>\n <SideNav items={nav} label={navLabel} className=\"min-w-0 flex-1 md:mt-4\" />\n </div>\n </aside>\n <div className=\"min-w-0\">\n {topBar && <div className=\"flex items-center gap-3 border-b border-border px-4 py-2 md:px-8\">{topBar}</div>}\n <main className=\"px-4 py-6 md:px-8 md:py-8\">{children}</main>\n </div>\n </div>\n );\n}\n\n/** Navigation links (React Router `NavLink`); the current route is a neutral pill with `aria-current`. */\nexport function SideNav({ items, label, className }: { items: NavItem[]; label: string; className?: string }) {\n return (\n <nav aria-label={label} className={cn(\"min-w-0\", className)}>\n <ul className=\"flex gap-1 overflow-x-auto md:grid md:overflow-visible\">\n {items.map(({ to, label, icon: Icon, end }) => (\n <li key={to} className=\"shrink-0\">\n <NavLink\n to={to}\n end={end}\n className={({ isActive }) =>\n cn(\n \"flex h-(--control-h-sm) items-center gap-2 rounded-control px-2 type-label whitespace-nowrap no-underline transition-state\",\n isActive ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n )\n }\n >\n {Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />}\n {label}\n </NavLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\n// Plain links with a \"/\" separator in muted ink. The last crumb is the current page: text, not a\n// link, with aria-current.\n/** Plain links separated by `/`; the last crumb is the current page. */\nexport function Breadcrumb({ items }: { items: { label: string; to?: string }[] }) {\n return (\n <nav aria-label=\"Breadcrumb\">\n <ol className=\"flex flex-wrap items-center gap-x-2 type-body-sm text-muted-foreground\">\n {items.map((item, i) => {\n const last = i === items.length - 1;\n return (\n <li key={`${item.label}-${i}`} className=\"flex items-center gap-2\">\n {item.to && !last ? (\n <Link to={item.to} className=\"text-muted-foreground underline hover:text-foreground\">\n {item.label}\n </Link>\n ) : (\n <span aria-current={last ? \"page\" : undefined} className={cn(last && \"text-foreground\")}>\n {item.label}\n </span>\n )}\n {!last && <span aria-hidden>/</span>}\n </li>\n );\n })}\n </ol>\n </nav>\n );\n}\n","import * as React from \"react\";\nimport { useSearchParams } from \"react-router\";\nimport { Tab, TabList, TabPanel, Tabs as AriaTabs } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// Tabs whose state lives in the URL (?view=readings), so a tab can be linked, survives reload and\n// works with Back. Built on React Aria Tabs (ARIA tabs pattern: arrow keys move between tabs and\n// select them, Home and End jump, only the selected tab is in the tab order). The selected tab is marked by weight and a\n// 2px rule in ink, not by colour alone. The first tab is the default and is not written to the URL.\n\nexport type TabItem = { value: string; label: string };\n\n/** Tabs whose selection lives in a URL search parameter (React Router), with the ARIA tabs keyboard model. */\nexport function Tabs({\n param,\n items,\n label,\n children,\n className,\n}: {\n /** The search parameter that holds the selected tab. */\n param: string;\n items: TabItem[];\n /** Names the tab list for screen readers. */\n label: string;\n /** Renders the selected panel. */\n children: (value: string) => React.ReactNode;\n className?: string;\n}) {\n const [params, setParams] = useSearchParams();\n const fallback = items[0]?.value ?? \"\";\n const raw = params.get(param);\n const value = items.some((i) => i.value === raw) ? raw! : fallback;\n const select = (next: string) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n if (next === fallback) out.delete(param);\n else out.set(param, next);\n return out;\n },\n { replace: true },\n );\n\n // React Aria's Tabs owns the keyboard model (arrows, Home and End, roving tab stop, automatic\n // activation) and the ids that tie each tab to the panel; the selected key is the URL's.\n return (\n <AriaTabs selectedKey={value} onSelectionChange={(key) => select(String(key))} className={cn(\"grid gap-4\", className)}>\n <TabList aria-label={label} className=\"flex gap-4 overflow-x-auto border-b border-border\">\n {items.map((item) => (\n <Tab\n key={item.value}\n id={item.value}\n className={cn(\n \"-mb-px cursor-pointer border-b-2 py-2 type-label whitespace-nowrap transition-state\",\n \"border-transparent text-muted-foreground hover:text-foreground\",\n \"selected:border-foreground selected:font-semibold selected:text-foreground\",\n )}\n >\n {item.label}\n </Tab>\n ))}\n </TabList>\n <TabPanel id={value} shouldForceMount={false}>\n {children(value)}\n </TabPanel>\n </AriaTabs>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget, type Shortcut } from \"./hotkeys\";\n\n// A queue someone works through from the keyboard: one item is active, j/k (or the arrow keys\n// inside the list) move it, and answering an item moves straight on to the next one. Three\n// decisions shape it:\n// 1. The active item is the one with focus. It is a roving tab stop (only it is in the tab order)\n// and carries aria-current, so a screen reader hears which item an answer applies to. It is\n// marked by a 2px rule in ink as well as a tint, not by colour alone.\n// 2. When the active item leaves the list (accepted, rejected, removed), the item that took its\n// place becomes active, or the one before it at the end of the list, and focus follows if it\n// was in the list. Otherwise focus would fall to <body> and the next key would do nothing.\n// 3. The hook remembers which item the person chose, not just a position. If an Undo puts the\n// item back, it is active again (pairs with `useUndoable`).\n// Moving is instant: no transition on the highlight (ux-research `ux-character.md`, 100+ a day).\n\n/** What `useActiveItem` returns: the active item, ways to move it, and the props each item element needs. */\nexport type ActiveItem<T> = {\n items: readonly T[];\n getKey: (item: T) => string;\n activeKey: string | null;\n activeItem: T | null;\n /** Position of the active item, or -1 when the list is empty. */\n index: number;\n next: () => void;\n prev: () => void;\n first: () => void;\n last: () => void;\n setActive: (key: string) => void;\n /** The j/k shortcuts for `useHotkeys` and `KeysLegend`. */\n shortcuts: Shortcut[];\n /** Props for the element that represents an item: ref, tabIndex, aria-current and focus tracking. */\n itemProps: (key: string) => {\n ref: (el: HTMLElement | null) => void;\n tabIndex: number;\n \"aria-current\": \"true\" | undefined;\n \"data-active\": \"\" | undefined;\n onFocus: () => void;\n onBlur: (e: React.FocusEvent) => void;\n };\n};\n\n/** Tracks the active item in a list worked through from the keyboard: moving, roving focus, and moving on when the active item is removed. */\nexport function useActiveItem<T>(\n items: readonly T[],\n getKey: (item: T) => string,\n {\n initial,\n noun,\n }: {\n /** Key of the item active at first; the first item otherwise. */\n initial?: string;\n /** Names an item in the shortcut labels: \"Next booking\". */\n noun?: string;\n } = {},\n): ActiveItem<T> {\n const [chosen, setChosen] = React.useState<string | null>(initial ?? null);\n const lastIndex = React.useRef(0);\n const elements = React.useRef(new Map<string, HTMLElement>());\n const navigated = React.useRef(false);\n const focusWithin = React.useRef(false);\n\n const keys = items.map(getKey);\n let index = chosen === null ? -1 : keys.indexOf(chosen);\n if (index === -1 && keys.length > 0) index = Math.min(lastIndex.current, keys.length - 1);\n const activeKey = index >= 0 ? keys[index] : null;\n\n // Remember the position, and the last item that left the list while active. Answering two in a\n // row (at the end of the queue, say) must make the second the one an Undo brings back as\n // active, not the first.\n const prevActive = React.useRef<string | null>(activeKey);\n React.useLayoutEffect(() => {\n if (index >= 0) lastIndex.current = index;\n const gone = prevActive.current;\n prevActive.current = activeKey;\n if (gone !== null && gone !== chosen && !keys.includes(gone)) setChosen(gone);\n });\n\n // Move focus to the active item when the person moved it, when the focused item was removed\n // (focus has fallen to <body>), or when focus is on another item in the list (an Undo made the\n // restored item active again). Never take focus from somewhere else on the page.\n React.useLayoutEffect(() => {\n const el = activeKey === null ? undefined : elements.current.get(activeKey);\n const focused = document.activeElement;\n const lost = focusWithin.current && (focused === null || focused === document.body);\n const elsewhereInList =\n focused !== null && !el?.contains(focused) && [...elements.current.values()].some((item) => item.contains(focused));\n if (el && (navigated.current || lost || elsewhereInList)) {\n el.focus({ preventScroll: true });\n el.scrollIntoView?.({ block: \"nearest\" });\n }\n navigated.current = false;\n }, [activeKey]);\n\n const moveTo = (i: number) => {\n if (keys.length === 0) return;\n const to = Math.max(0, Math.min(keys.length - 1, i));\n navigated.current = true;\n if (to === index) {\n // Already there: still bring focus back to it, as the person asked to move.\n const el = elements.current.get(keys[to]);\n el?.focus({ preventScroll: true });\n el?.scrollIntoView?.({ block: \"nearest\" });\n navigated.current = false;\n }\n setChosen(keys[to]);\n };\n\n const next = () => moveTo(index + 1);\n const prev = () => moveTo(index - 1);\n const first = () => moveTo(0);\n const last = () => moveTo(keys.length - 1);\n const setActive = (key: string) => {\n const i = keys.indexOf(key);\n if (i >= 0) moveTo(i);\n };\n\n const name = noun ? ` ${noun}` : \"\";\n const shortcuts: Shortcut[] = [\n { keys: [\"j\"], label: `Next${name}`, run: next, repeat: true, disabled: keys.length === 0 },\n { keys: [\"k\"], label: `Previous${name}`, run: prev, repeat: true, disabled: keys.length === 0 },\n ];\n\n const itemProps: ActiveItem<T>[\"itemProps\"] = (key) => ({\n ref: (el) => {\n if (el) elements.current.set(key, el);\n else elements.current.delete(key);\n },\n tabIndex: key === activeKey ? 0 : -1,\n \"aria-current\": key === activeKey ? \"true\" : undefined,\n \"data-active\": key === activeKey ? \"\" : undefined,\n onFocus: () => {\n focusWithin.current = true;\n // Clicking or tabbing into an item makes it active. If it already is (it took a removed\n // item's place), keep remembering the removed one so an Undo makes that active again.\n if (key !== activeKey) setChosen(key);\n },\n onBlur: (e) => {\n // Focus going nowhere (null) is what removal looks like, so only a move to a real element\n // outside the list counts as leaving it.\n const to = e.relatedTarget;\n if (to instanceof Node && ![...elements.current.values()].some((el) => el.contains(to))) focusWithin.current = false;\n },\n });\n\n return {\n items,\n getKey,\n activeKey,\n activeItem: index >= 0 ? items[index] : null,\n index,\n next,\n prev,\n first,\n last,\n setActive,\n shortcuts,\n itemProps,\n };\n}\n\n// The list renders the queue from `useActiveItem`. The arrow keys, Home and End move the active\n// item while focus is in the list (the window-wide j/k come from `active.shortcuts` via\n// `useHotkeys`, because only the screen knows whether it has one queue or two). An empty queue\n// is a state the list cannot be written without: say what clearing it means and what is next.\n/** A keyboard-worked queue: the active item is a roving tab stop with aria-current, and the arrow keys, Home and End move it. */\nexport function ActiveList<T>({\n label,\n active,\n empty,\n children,\n className,\n}: {\n /** Names the list for screen readers. */\n label: string;\n active: ActiveItem<T>;\n /** Shown when the queue is clear: what that means and what to do next. */\n empty: React.ReactNode;\n children: (item: T, state: { active: boolean }) => React.ReactNode;\n className?: string;\n}) {\n if (active.items.length === 0) return <>{empty}</>;\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.ctrlKey || e.metaKey || e.altKey || isTypingTarget(e.target)) return;\n const move =\n e.key === \"ArrowDown\" ? active.next\n : e.key === \"ArrowUp\" ? active.prev\n : e.key === \"Home\" ? active.first\n : e.key === \"End\" ? active.last\n : undefined;\n if (!move) return;\n e.preventDefault();\n move();\n };\n\n return (\n <ul aria-label={label} onKeyDown={onKeyDown} className={cn(\"grid gap-px\", className)}>\n {active.items.map((item) => {\n const key = active.getKey(item);\n const isActive = key === active.activeKey;\n return (\n <li\n key={key}\n {...active.itemProps(key)}\n className={cn(\n \"rounded-control border-l-2 px-3 py-2 -outline-offset-2\",\n isActive ? \"border-foreground bg-accent text-accent-foreground\" : \"border-transparent\",\n )}\n >\n {children(item, { active: isActive })}\n </li>\n );\n })}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { hashKey, useInfiniteQuery, type QueryKey } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport { describeHttpError, staleOf, type DescribeError } from \"./index\";\n\n// Cursor-paged reads, the Strata way. `useLoad` covers a read that arrives whole; a feed, a log or\n// a triage queue arrives a page at a time. This is the same bridge for those: TanStack's\n// useInfiniteQuery underneath, a `Load<T[]>` on top (so `DataView` takes it unchanged for the\n// first page's loading, error and empty states), and a `more` object for everything after it.\n//\n// Three opinions:\n// 1. The cursor is \"after the last item held\", never an offset, and the hook works it out: the\n// app says how to make a cursor from an item (`cursorAfter`) and whether a page says there are\n// more (`hasMore`). In a queue people work through (answered reviews, archived firings), items\n// leave the server's list between pages, and an offset would skip the ones that moved up to\n// fill the gap. Two cases fall back to the last item *seen*, dismissed or not: when everything\n// held has been dismissed (there is no held item to go after, and starting again from the top\n// could fetch the same dismissed page forever), and when the last page brought nothing new\n// (only items already held or dismissed came back, so going after the last held item again\n// would ask for the same page in a loop).\n// 2. Items have keys. Pages are merged by key, so an item that shifts across a page boundary is\n// shown once, and `dismiss(key)` hides one at once (an optimistic remove, paired with\n// useUndoable) without the app rewriting TanStack's page cache by hand. Dismissals belong to\n// one query: a new `queryKey` (another filter) starts with none. A screen that removes items\n// with `useUndoable` passes its `isRemoved` instead, so the undo hook stays the one owner of\n// what is out of view (Undo, a failed commit and Try again all show through) and the cursor\n// still skips past what it hides.\n// 3. A later page failing is not the list failing. The held items stay; `more.error` says what\n// happened and `more.loadMore` is the Try again. A refetch of the held pages failing is not the\n// list failing either: the items stay and `stale` says how old they are, as with `useLoad`.\n// Only a failed first page is a `Load` error.\n\n/** The state of the pages after the first: whether there are more, whether one is on its way, and why the last one failed. */\nexport type More = {\n /** The server has said there is another page. */\n hasMore: boolean;\n /** A page after the first is being fetched. */\n loadingMore: boolean;\n /** Why the last page after the first failed, for a person. Cleared when a retry succeeds. */\n error?: string;\n /** Fetch the next page; also the Try again after `error`. Does nothing while one is loading or when there are no more. */\n loadMore: () => void;\n};\n\n/** A cursor-paged read: a `Load<T[]>` of the items held (so `DataView` takes it), plus the next page's state and keyed removal. */\nexport type InfiniteLoad<T> = Load<T[]> & {\n more: More;\n itemKey: (item: T) => string;\n /** Hide an item at once (an optimistic removal). The next cursor goes after the last item still held. */\n dismiss: (key: string) => void;\n /** Show a dismissed item again: the Undo of `dismiss`. */\n restore: (key: string) => void;\n};\n\n/** Options for `useInfiniteLoad`. */\nexport type InfiniteLoadOptions<T, Page, Cursor, K extends QueryKey> = {\n queryKey: K;\n /** Fetch one page. `cursor` is undefined for the first page, else `cursorAfter` of the last item held. */\n queryFn: (context: { cursor: Cursor | undefined; signal: AbortSignal }) => Promise<Page>;\n /** The items in a page. For an API that returns a bare array, `(page) => page`. */\n items: (page: Page) => T[];\n /** A stable key per item: merges pages, and is what `dismiss` takes. */\n itemKey: (item: T) => string;\n /** Whether the server says there is a page after this one. */\n hasMore: (lastPage: Page) => boolean;\n /** The cursor that asks for the items after this one; usually its id. Defaults to `itemKey`. */\n cursorAfter?: (item: T) => Cursor;\n /** Items hidden by someone else, usually `useUndoable().isRemoved`: treated like dismissed ones. */\n isRemoved?: (key: string) => boolean;\n describeError?: DescribeError;\n enabled?: boolean;\n staleTime?: number;\n};\n\ntype Dismissed = { query: string; keys: ReadonlySet<string> };\ntype PageParam<Cursor> = { cursor: Cursor | undefined };\n\n/** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */\nexport function useInfiniteLoad<T, Page, Cursor = string, K extends QueryKey = QueryKey>({\n queryKey,\n queryFn,\n items,\n itemKey,\n hasMore,\n cursorAfter = itemKey as unknown as (item: T) => Cursor,\n isRemoved,\n describeError = describeHttpError,\n enabled,\n staleTime,\n}: InfiniteLoadOptions<T, Page, Cursor, K>): InfiniteLoad<T> {\n const queryHash = hashKey(queryKey);\n const [stored, setStored] = React.useState<Dismissed>(() => ({ query: queryHash, keys: new Set() }));\n const dismissed = stored.query === queryHash ? stored.keys : none;\n const hidden = React.useCallback((key: string) => dismissed.has(key) || (isRemoved?.(key) ?? false), [dismissed, isRemoved]);\n // TanStack calls getNextPageParam outside render; it reads the latest hidden set and accessors.\n const latest = React.useRef({ hidden, items, itemKey, hasMore, cursorAfter });\n latest.current = { hidden, items, itemKey, hasMore, cursorAfter };\n\n const query = useInfiniteQuery({\n queryKey,\n queryFn: ({ pageParam, signal }) => queryFn({ cursor: pageParam.cursor, signal }),\n initialPageParam: { cursor: undefined } as PageParam<Cursor>,\n getNextPageParam: (lastPage, pages): PageParam<Cursor> | null => {\n const l = latest.current;\n if (!l.hasMore(lastPage)) return null;\n const after = nextAfter(pages, l.items, l.itemKey, l.hidden);\n return { cursor: after === undefined ? undefined : l.cursorAfter(after) };\n },\n enabled,\n staleTime,\n });\n\n const pages = query.data?.pages;\n // Keyed on the pages and dismissals only, so inline `items`/`itemKey` arrows do not hand the\n // list a new array every render.\n const list = React.useMemo(\n () => (pages ? merge(pages, latest.current.items, latest.current.itemKey, hidden).held : undefined),\n [pages, hidden],\n );\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage, refetch } = query;\n const loadMore = React.useCallback(() => {\n if (hasNextPage && !isFetchingNextPage) void fetchNextPage();\n }, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n const change = React.useCallback(\n (edit: (keys: Set<string>) => void) =>\n setStored((s) => {\n const keys = new Set(s.query === queryHash ? s.keys : none);\n edit(keys);\n return { query: queryHash, keys };\n }),\n [queryHash],\n );\n const dismiss = React.useCallback((key: string) => change((keys) => keys.add(key)), [change]);\n const restore = React.useCallback((key: string) => change((keys) => keys.delete(key)), [change]);\n\n const more: More = {\n hasMore: Boolean(hasNextPage),\n loadingMore: isFetchingNextPage,\n error: query.isFetchNextPageError ? describeError(query.error) : undefined,\n loadMore,\n };\n const extra = { more, itemKey, dismiss, restore };\n if (list) {\n // isRefetchError excludes a failed next page, which is `more.error`'s to report.\n const stale = query.isRefetchError ? staleOf(query, describeError) : undefined;\n return { status: \"ready\", data: list, ...(stale && { stale }), ...extra };\n }\n if (query.status === \"error\") return { status: \"error\", message: describeError(query.error), retry: () => void refetch(), ...extra };\n return { status: \"loading\", ...extra };\n}\n\nconst none: ReadonlySet<string> = new Set();\n\n/** Every page's items, in order, once each by key: the ones held (not dismissed) and the last one seen. */\nfunction merge<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const seen = new Set<string>();\n const held: T[] = [];\n let last: T | undefined;\n let lastPageAddedAny = false;\n pages.forEach((page, p) => {\n for (const item of items(page)) {\n const key = itemKey(item);\n if (seen.has(key)) continue;\n seen.add(key);\n last = item;\n if (p === pages.length - 1) lastPageAddedAny = true;\n if (!hidden(key)) held.push(item);\n }\n });\n return { held, last, lastPageAddedAny };\n}\n\n/** The item the next page goes after: the last held, or the last seen when nothing is held or the last page brought nothing new. */\nfunction nextAfter<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const { held, last, lastPageAddedAny } = merge(pages, items, itemKey, hidden);\n if (held.length === 0 || (pages.length > 1 && !lastPageAddedAny)) return last;\n return held[held.length - 1];\n}\n","import * as React from \"react\";\nimport { hashKey, useQuery, useQueryClient, type QueryKey, type UseQueryOptions } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport type { DescribeError } from \"../lib/errors\";\nimport { toLoad } from \"./index\";\n\n// The read behind `JobStatus` (strata-react issue #45): a job's status, polled while it runs and\n// not otherwise, and the data it changed read again once, when it ends. Tubes wrote this as\n// `useLoad({ refetchInterval })` plus an effect watching `running` go from true to false; every\n// app with a job would write the same two pieces and get the second one subtly wrong (invalidating\n// on the first read of a job that had already finished, or on every poll). Here:\n//\n// - `isRunning(data)` says whether the job is going; the query polls `every` ms (default 2000)\n// only then, so an idle screen makes one request, not one every two seconds.\n// - `invalidates` names the queries the job changes; they are invalidated once, on the poll that\n// first sees the job stopped after one that saw it running, for the same query: a first read\n// of a finished job invalidates nothing, and neither does switching to another job's key (the\n// new query has no status yet, which is not the old job ending). The keys invalidated are the\n// ones given while that job was seen running.\n// - `poll()` reads the status now: the commit of the button that starts the job calls it, so\n// polling begins without waiting for a stale time.\n// - The result is a `Load<T>` (so a failed poll keeps the last status on screen with `stale`, as\n// any read does), plus `running`.\n\n/** Options for `useJob`: a query's, plus how to tell the job is running, how often to poll, and what it changes. */\nexport type JobOptions<T, K extends QueryKey = QueryKey> = UseQueryOptions<T, Error, T, K> & {\n /** Whether the status says the job is still going. */\n isRunning: (data: T) => boolean;\n /** Milliseconds between polls while it runs. Default 2000. */\n every?: number;\n /** Query keys the job changes, invalidated once when it ends. */\n invalidates?: QueryKey[];\n describeError?: DescribeError;\n};\n\n/** What `useJob` returns: the status as a `Load<T>`, whether the job is running, and `poll` to read it now. */\nexport type Job<T> = Load<T> & {\n /** The latest status says the job is going. */\n running: boolean;\n /** Read the status now, as after starting the job. */\n poll: () => void;\n};\n\n/** A long-running job's status: polled every `every` ms while `isRunning`, with the `invalidates` queries read again once when it ends. */\nexport function useJob<T, K extends QueryKey = QueryKey>({\n isRunning,\n every = 2000,\n invalidates = [],\n describeError,\n ...options\n}: JobOptions<T, K>): Job<T> {\n const client = useQueryClient();\n const query = useQuery({\n ...options,\n refetchInterval: (q) => (q.state.data !== undefined && isRunning(q.state.data) ? every : false),\n });\n const running = query.data !== undefined && isRunning(query.data);\n\n // What was last seen, for one query: whether its job ran, and what it said it would change.\n // Only a status that has arrived counts; no data yet (a new key loading) is not \"stopped\".\n const queryHash = hashKey(options.queryKey);\n const seen = query.data === undefined ? undefined : running;\n const was = React.useRef<{ query: string; running: boolean; invalidates: QueryKey[] } | undefined>(undefined);\n React.useEffect(() => {\n if (seen === undefined) return;\n const before = was.current;\n if (before && before.query === queryHash && before.running && !seen) {\n for (const queryKey of before.invalidates) void client.invalidateQueries({ queryKey });\n }\n was.current = { query: queryHash, running: seen, invalidates };\n });\n\n const { refetch } = query;\n const poll = React.useCallback(() => void refetch(), [refetch]);\n return { ...toLoad(query, describeError), running, poll };\n}\n","import * as React from \"react\";\nimport { Dialog as AriaDialog, Modal, ModalOverlay } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Full screen for a picture, a pair to compare or a player: the thing being judged gets the whole\n// screen, with its controls still around it. The browser's Fullscreen API is the first choice,\n// because it hides the browser's own chrome too; the iPhone's Safari has no such API for anything\n// but video, so there the same content opens in a React Aria modal that fills the window. Either\n// way the caller holds `active` (so a key and a button can both toggle it), and zoom, mode and the\n// question being answered live in the caller's state, so they survive the change. In the modal the\n// content is re-mounted (an image is drawn again from the browser's cache); natively it is not.\n//\n// React Aria checked: `Modal`/`ModalOverlay` give the fallback its focus containment, inert page\n// behind it and Escape; they do not offer the Fullscreen API, which is why the native path is\n// ours (an effect on `requestFullscreen` and the `fullscreenchange` event, the browser's own way\n// to say the person pressed Escape). If the browser refuses (it needs a recent click or key) the\n// fallback is used, so asking for full screen never silently does nothing.\n\n/** Props for `FullscreenFrame`. */\nexport type FullscreenFrameProps = {\n /** Names the full-screen view for screen readers: \"Compare renderings\". Required. */\n label: string;\n /** Whether the frame is full screen. The caller owns it so a button and a key can share it. */\n active: boolean;\n /** Called with `false` when the person leaves with Escape or the browser's own control. */\n onActiveChange: (active: boolean) => void;\n children: React.ReactNode;\n className?: string;\n};\n\n/** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */\nexport function canFullscreen(): boolean {\n return typeof document !== \"undefined\" && document.fullscreenEnabled === true && typeof Element.prototype.requestFullscreen === \"function\";\n}\n\n/** Shows its children full screen while `active`: the browser's Fullscreen API where there is one, a window-filling modal where there is not. */\nexport function FullscreenFrame({ label, active, onActiveChange, children, className }: FullscreenFrameProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const [native, setNative] = React.useState(false);\n const [refused, setRefused] = React.useState(false);\n const change = React.useRef(onActiveChange);\n change.current = onActiveChange;\n\n React.useEffect(() => {\n const el = ref.current;\n if (!active) {\n setNative(false);\n setRefused(false);\n if (document.fullscreenElement && document.fullscreenElement === el) void document.exitFullscreen();\n return;\n }\n if (!el || !canFullscreen()) return;\n let cancelled = false;\n el.requestFullscreen().then(\n () => !cancelled && setNative(true),\n () => !cancelled && setRefused(true), // refused (no recent click or key, say): the modal below opens instead\n );\n const onChange = () => {\n if (document.fullscreenElement !== el && !cancelled) change.current(false);\n };\n document.addEventListener(\"fullscreenchange\", onChange);\n return () => {\n cancelled = true;\n document.removeEventListener(\"fullscreenchange\", onChange);\n };\n }, [active]);\n\n // The modal is the answer where the browser cannot, or has refused. While a request is in flight the content stays in place.\n const modal = active && !native && (!canFullscreen() || refused);\n const inner = (\n <div ref={ref} className={cn(active && \"flex h-full min-h-0 flex-col bg-background p-4\", className)}>\n {children}\n </div>\n );\n if (!modal) return inner;\n return (\n <ModalOverlay isOpen onOpenChange={(o) => !o && onActiveChange(false)} isDismissable className=\"layer-overlay fixed inset-0 scrim\">\n <Modal className={cn(\"h-full w-full outline-none\", overlaySurface, \"rounded-none\")}>\n <AriaDialog aria-label={label} className=\"h-full outline-none\">\n {inner}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n );\n}\n","// The arithmetic of a shared zoom and pan, kept apart from the DOM so it is unit tested without a\n// layout engine (jsdom has none). Used by `ViewportFrame` and so by every comparison view.\n//\n// Scale is relative to \"fit\" (1 = the whole picture inside its frame). The offset is in pixels from\n// the frame's centre, and the picture's transform origin is that centre, so zooming about a point\n// is one line of algebra and a fit picture is always centred.\n\n/** Zoom and pan of a picture inside its frame. `scale` 1 is the picture fitted; `x` and `y` are pixels from the centre. */\nexport type Viewport = { scale: number; x: number; y: number };\n\n/** The picture fitted in its frame, not panned. */\nexport const FIT: Viewport = { scale: 1, x: 0, y: 0 };\n\n/** The least zoom: the whole picture fitted. */\nexport const MIN_SCALE = 1;\n/** The most zoom, 32 times the fit. */\nexport const MAX_SCALE = 32;\n\n/** Keeps the picture from being dragged out of its frame: at most half the extra width or height past each edge. */\nexport function clampViewport(v: Viewport, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.scale));\n if (scale === MIN_SCALE) return FIT;\n const mx = ((scale - 1) * frame.width) / 2;\n const my = ((scale - 1) * frame.height) / 2;\n return { scale, x: Math.min(mx, Math.max(-mx, v.x)), y: Math.min(my, Math.max(-my, v.y)) };\n}\n\n/** A new scale with the point under `at` (pixels from the frame's centre) staying under it. */\nexport function zoomAt(v: Viewport, nextScale: number, at: { x: number; y: number }, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, nextScale));\n const k = scale / v.scale;\n return clampViewport({ scale, x: at.x - k * (at.x - v.x), y: at.y - k * (at.y - v.y) }, frame);\n}\n\n/** The scale at which the picture's own pixels are drawn one to one: its natural width over the width it is fitted at. */\nexport function actualPixelsScale(naturalWidth: number, fittedWidth: number): number {\n if (!naturalWidth || !fittedWidth) return 1;\n return Math.min(MAX_SCALE, Math.max(MIN_SCALE, naturalWidth / fittedWidth));\n}\n\n/** The CSS transform for a viewport. */\nexport function viewportTransform(v: Viewport): string {\n return `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;\n}\n","import * as React from \"react\";\nimport { ImageOff, Maximize, Minimize, Scan, ZoomIn, ZoomOut } from \"lucide-react\";\nimport { FIT, actualPixelsScale, zoomAt, type Viewport } from \"../lib/viewport\";\nimport { Button, IconButton } from \"./button\";\nimport { Skeleton } from \"./data-view\";\nimport type { Shortcut } from \"./hotkeys\";\nimport type { Candidate } from \"./compare\";\n\n// The pieces `Compare` and `CompareGrid` share, not exported from the package: a picture in its\n// loading, ready and failed states, the caption under it, and the zoom controls and keys, so the\n// two views behave the same way and cannot drift apart.\n\n// 100svh less the toolbar (about 3rem), captions (2rem), a vote bar (4rem), the legend (4rem) and gaps.\nexport const VIEWPORT_HEIGHT = \"max(16rem, calc(100svh - 14rem))\";\n\n/** A word for a picture's name on the page: its label, with its note unless blind. */\nexport function Caption({ c, blind }: { c: Candidate<unknown>; blind: boolean }) {\n return (\n <div className=\"flex items-baseline gap-2\">\n <span className=\"type-label\">{c.label}</span>\n {!blind && c.note && <span className=\"type-caption text-muted-foreground\">{c.note}</span>}\n </div>\n );\n}\n\n/** One picture inside a frame: a skeleton while it loads, the product's words if it fails. */\nexport function Picture({ c, blind, missing, onNatural, imgRef }: { c: Candidate; blind: boolean; missing: string; onNatural?: (w: number, h: number) => void; imgRef?: React.Ref<HTMLImageElement> }) {\n const [state, setState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\"loading\");\n React.useEffect(() => setState(\"loading\"), [c.media.src]);\n const alt = blind ? c.label : c.media.alt;\n if (state === \"failed\")\n return (\n <div role=\"img\" aria-label={`${alt}: ${missing}`} className=\"absolute inset-0 grid place-content-center justify-items-center gap-2 text-muted-foreground\">\n <ImageOff aria-hidden className=\"size-6\" />\n <span className=\"type-body-sm\">{missing}</span>\n </div>\n );\n return (\n <>\n {state === \"loading\" && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none\" />}\n <img\n ref={imgRef}\n src={c.media.src}\n alt={alt}\n draggable={false}\n onLoad={(e) => {\n setState(\"ready\");\n onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);\n }}\n onError={() => setState(\"failed\")}\n className=\"absolute inset-0 size-full object-contain\"\n />\n </>\n );\n}\n\n\ntype ZoomProps = {\n viewport: Viewport;\n setViewport: (next: Viewport) => void;\n /** The frame whose size zoom is measured against. */\n frame: React.RefObject<HTMLElement | null>;\n /** The picture's natural size, if known, for 1:1. */\n natural: readonly [number, number] | null;\n};\n\nconst frameSize = (frame: React.RefObject<HTMLElement | null>) => {\n const r = frame.current?.getBoundingClientRect();\n return { width: r?.width ?? 0, height: r?.height ?? 0 };\n};\n\n/** Zoom steps about the frame's centre, and 1:1. */\nexport function useZoom({ viewport, setViewport, frame, natural }: ZoomProps) {\n const by = (k: number) => setViewport(zoomAt(viewport, viewport.scale * k, { x: 0, y: 0 }, frameSize(frame)));\n const actual = () => {\n const f = frameSize(frame);\n // The width the picture is drawn at when fitted: the frame's, unless the picture is taller than it is wide for the frame.\n const fitted = natural ? Math.min(f.width, f.height * (natural[0] / natural[1])) : f.width;\n setViewport(zoomAt(viewport, actualPixelsScale(natural?.[0] ?? 0, fitted), { x: 0, y: 0 }, f));\n };\n return { by, actual, fit: () => setViewport(FIT) };\n}\n\n/** The shortcuts for zoom and full screen, to join a screen's own list. */\nexport function zoomShortcuts(zoom: ReturnType<typeof useZoom>, full: boolean, setFull: (f: boolean) => void): Shortcut[] {\n return [\n { keys: [\"+\", \"=\"], label: \"Zoom in\", run: () => zoom.by(1.5), repeat: true },\n { keys: [\"-\"], label: \"Zoom out\", run: () => zoom.by(1 / 1.5), repeat: true },\n { keys: [\"0\"], label: \"Fit\", run: zoom.fit },\n { keys: [\"f\"], label: full ? \"Leave full screen\" : \"Full screen\", run: () => setFull(!full) },\n ];\n}\n\n/** Zoom out, in, fit, 1:1 and the zoom now, for inside a `Toolbar`. */\nexport function ZoomControls({ viewport, zoom, natural }: { viewport: Viewport; zoom: ReturnType<typeof useZoom>; natural: readonly [number, number] | null }) {\n return (\n <>\n <IconButton icon={ZoomOut} label=\"Zoom out\" onPress={() => zoom.by(1 / 1.5)} disabled={viewport.scale <= 1} />\n <IconButton icon={ZoomIn} label=\"Zoom in\" onPress={() => zoom.by(1.5)} />\n <IconButton icon={Scan} label=\"Fit\" onPress={zoom.fit} disabled={viewport.scale === 1} />\n <Button size=\"sm\" variant=\"ghost\" onPress={zoom.actual} disabled={!natural}>1:1</Button>\n <span aria-live=\"off\" className=\"type-caption tabular-nums text-muted-foreground\">{viewport.scale === 1 ? \"Fit\" : `${viewport.scale.toFixed(1)}×`}</span>\n </>\n );\n}\n\n/** The full-screen button, for inside a `Toolbar`. */\nexport function FullscreenButton({ full, setFull }: { full: boolean; setFull: (f: boolean) => void }) {\n return <IconButton icon={full ? Minimize : Maximize} label={full ? \"Leave full screen\" : \"Full screen\"} onPress={() => setFull(!full)} />;\n}\n","// Which pixels differ between two renderings of one picture, for the difference view of `Compare`.\n// pixelmatch does the comparing (it is already a dependency: the visual runner uses it); this file\n// is the part around it: getting both pictures to the same size, reading pixels from a picture, and\n// telling the person how much of the picture differs. The arithmetic takes plain RGBA buffers, so it\n// is unit tested without a canvas; reading pixels needs a browser and is covered by the Storybook\n// shots, which run in Chromium.\n//\n// Why a tolerance rather than \"any difference\": two JPEGs of one edit differ in almost every\n// pixel by a level or two of compression noise, and a person comparing them cares about what they\n// can see. pixelmatch's threshold is a colour distance (OKLab, 0 to 1, 1 is black against white);\n// the default 0.1 is its own and the one `strata-visual` uses on screenshots. It also ignores\n// anti-aliased edge pixels by default, which are the same edge drawn slightly differently, not a\n// change in the picture.\n//\n// Pictures larger than `MAX_SIDE` on their long side are compared at that size: a 24-megapixel\n// photo would take seconds on the page's thread, and a difference that vanishes at 2048 pixels is\n// not one the person sees in a comparison view. The counts are of the pixels compared, so the share\n// printed is the share of the picture either way.\nimport pixelmatch from \"pixelmatch\";\n\n/** Decoded pixels: RGBA, 4 bytes each, row by row. */\nexport type Pixels = { data: Uint8ClampedArray; width: number; height: number };\n\n/** The result of comparing two pictures. */\nexport type Difference = {\n /** RGBA, `width` × `height`: opaque where a pixel differs, transparent elsewhere. */\n marks: Uint8ClampedArray;\n width: number;\n height: number;\n /** Pixels judged different. */\n differing: number;\n /** Pixels compared. */\n total: number;\n};\n\n/** The longest side, in pixels, a picture is compared at. */\nexport const MAX_SIDE = 2048;\n/** pixelmatch's own default colour distance below which two pixels are the same. */\nexport const DEFAULT_TOLERANCE = 0.1;\n\n/** The picture drawn at another size, each new pixel taken from the nearest old one. Used to bring the second picture to the first's size. */\nexport function resample(p: Pixels, width: number, height: number): Pixels {\n if (p.width === width && p.height === height) return p;\n const data = new Uint8ClampedArray(width * height * 4);\n for (let y = 0; y < height; y++) {\n const sy = Math.min(p.height - 1, Math.floor(((y + 0.5) * p.height) / height));\n for (let x = 0; x < width; x++) {\n const sx = Math.min(p.width - 1, Math.floor(((x + 0.5) * p.width) / width));\n const from = (sy * p.width + sx) * 4;\n const to = (y * width + x) * 4;\n data[to] = p.data[from];\n data[to + 1] = p.data[from + 1];\n data[to + 2] = p.data[from + 2];\n data[to + 3] = p.data[from + 3];\n }\n }\n return { data, width, height };\n}\n\n/**\n * Which pixels differ between two pictures. `b` is resampled to `a`'s size first when they differ,\n * so a re-encoded or resized rendering still lines up. `tolerance` is pixelmatch's `threshold`, 0 to 1.\n */\nexport function differences(a: Pixels, b: Pixels, tolerance: number = DEFAULT_TOLERANCE): Difference {\n const other = resample(b, a.width, a.height);\n const marks = new Uint8ClampedArray(a.width * a.height * 4);\n const differing = pixelmatch(a.data, other.data, marks, a.width, a.height, {\n threshold: tolerance,\n diffMask: true,\n alpha: 0,\n });\n return { marks, width: a.width, height: a.height, differing, total: a.width * a.height };\n}\n\n/** Reads a picture's pixels by drawing it on a canvas, scaled down so its long side is at most `maxSide`. Rejects when the picture cannot be loaded or the browser will not let a page read it (a picture from another site without CORS headers). */\nexport async function readPixels(src: string, maxSide: number = MAX_SIDE): Promise<Pixels> {\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n img.src = src;\n await img.decode();\n const scale = Math.min(1, maxSide / Math.max(img.naturalWidth, img.naturalHeight));\n const width = Math.max(1, Math.round(img.naturalWidth * scale));\n const height = Math.max(1, Math.round(img.naturalHeight * scale));\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (!ctx) throw new Error(\"This browser cannot read a picture's pixels.\");\n ctx.drawImage(img, 0, 0, width, height);\n const { data } = ctx.getImageData(0, 0, width, height);\n return { data, width, height };\n}\n","import * as React from \"react\";\nimport { differences, readPixels, type Difference, type Pixels } from \"../lib/image-diff\";\n\n// The pixel half of `Compare`'s difference view: loads both pictures' pixels once per pair, and\n// recomputes which differ when the tolerance moves. The tolerance is deferred (`useDeferredValue`),\n// so dragging its slider stays smooth while a 2048-pixel comparison runs behind it; the marks lag\n// by a frame or two and the readout beside the slider says what it is showing. Pixels are not\n// asked for until the view is open (`enabled`), since most comparisons never use it.\n\n/** How pictures become pixels. The default draws them on a canvas; supply another where that does not fit (an authenticated request, a picture the browser will not let a page read). */\nexport type ReadPixels = (src: string) => Promise<Pixels>;\n\n/** The state of a difference: reading the pictures, unable to, or the result. */\nexport type DifferenceState = { status: \"loading\" } | { status: \"failed\" } | { status: \"ready\"; difference: Difference };\n\n/** The pixels that differ between two pictures at a tolerance (0 to 1), read only while `enabled`. */\nexport function useDifference(a: string, b: string, tolerance: number, enabled: boolean, read: ReadPixels = readPixels): DifferenceState {\n const [loaded, setLoaded] = React.useState<{ key: string; a: Pixels; b: Pixels } | \"failed\" | null>(null);\n const key = `${a}|${b}`;\n const reader = React.useRef(read);\n reader.current = read;\n React.useEffect(() => {\n if (!enabled) return;\n let cancelled = false;\n setLoaded(null);\n Promise.all([reader.current(a), reader.current(b)]).then(\n ([pa, pb]) => !cancelled && setLoaded({ key, a: pa, b: pb }),\n () => !cancelled && setLoaded(\"failed\"),\n );\n return () => {\n cancelled = true;\n };\n }, [a, b, key, enabled]);\n const deferred = React.useDeferredValue(tolerance);\n const difference = React.useMemo(() => (loaded && loaded !== \"failed\" && loaded.key === key ? differences(loaded.a, loaded.b, deferred) : null), [loaded, key, deferred]);\n if (loaded === \"failed\") return { status: \"failed\" };\n return difference ? { status: \"ready\", difference } : { status: \"loading\" };\n}\n\n/** The marks of a difference drawn over the picture: a canvas that fits its frame the way the picture does (`object-contain`). */\nexport function DifferenceMarks({ difference }: { difference: Difference }) {\n const ref = React.useRef<HTMLCanvasElement>(null);\n React.useEffect(() => {\n const canvas = ref.current;\n const ctx = canvas?.getContext(\"2d\");\n if (!canvas || !ctx) return;\n canvas.width = difference.width;\n canvas.height = difference.height;\n // createImageData, not `new ImageData`: the same in a browser, and it works where the page has a canvas but no ImageData global (jsdom with @napi-rs/canvas installed).\n const image = ctx.createImageData(difference.width, difference.height);\n image.data.set(difference.marks);\n ctx.putImageData(image, 0, 0);\n }, [difference]);\n return <canvas ref={ref} aria-hidden className=\"absolute inset-0 size-full object-contain\" />;\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { FIT, clampViewport, viewportTransform, zoomAt, type Viewport } from \"../lib/viewport\";\n\n// One picture's frame, with zoom and pan that other frames can share (strata-react issue: shared\n// comparison and voting components). Judging two renderings of a photo is mostly looking at the same\n// detail in both, so the viewport is state the caller holds and gives to every frame: zoom one, the\n// other follows. `ViewportFrame` is only the frame; `Compare` holds the state and draws the controls.\n//\n// React Aria checked: Aria Components has no zoom or pan part, and its `useMove` (in the\n// `react-aria` package, which is not a dependency here) only reports deltas that a pointer capture\n// gives us as well, so the gestures are pointer events on the frame. Keyboard, which is not\n// optional: the frame is focusable, `+` `-` `0` zoom and the arrow keys pan once zoomed in.\n// Plain wheel scrolls the page (a frame in the middle of a page must not trap it); Ctrl or Cmd with\n// the wheel zooms, which is also what a trackpad pinch sends. Touch pinch is not handled yet.\n\n/** The caller's zoom and pan, and how to change them. */\nexport type ViewportState = { viewport: Viewport; setViewport: (next: Viewport) => void };\n\n/** Zoom and pan held in React state, to give to every `ViewportFrame` that should move together. */\nexport function useViewport(initial: Viewport = FIT): ViewportState {\n const [viewport, setViewport] = React.useState(initial);\n return { viewport, setViewport };\n}\n\nconst PAN_STEP = 48;\n\n/** Props for `ViewportFrame`. */\nexport type ViewportFrameProps = ViewportState & {\n /** Names the frame for screen readers: \"Picture A\". Required. */\n label: string;\n /** Width over height of the frame before anything inside it has loaded. */\n aspect: number;\n children: React.ReactNode;\n /** A second picture layer above `children`, zoomed and panned with them but cut at `shown` percent of the *frame's* width from the left, so a swipe divider in `overlay` stays where the cut is at any zoom. */\n cover?: { content: React.ReactNode; shown: number };\n /** Drawn over the frame, not zoomed with it: a divider to drag, a corner label. Its pointer, key and double-click events do not reach the frame, so using it never pans the picture. */\n overlay?: React.ReactNode;\n /** The tallest the frame may be, as a CSS length (`\"60svh\"`). The width follows, narrower than the space it has and centred, so the picture keeps its shape. Default: no limit, the frame is as tall as its width and aspect make it. */\n maxHeight?: string;\n className?: string;\n};\n\n/** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */\nexport const ViewportFrame = React.forwardRef<HTMLDivElement, ViewportFrameProps>(function ViewportFrame(\n { label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, className },\n forwardedRef,\n) {\n const ref = React.useRef<HTMLDivElement>(null);\n React.useImperativeHandle(forwardedRef, () => ref.current!);\n const latest = React.useRef(viewport);\n latest.current = viewport;\n const drag = React.useRef<{ x: number; y: number } | null>(null);\n\n const size = () => {\n const r = ref.current!.getBoundingClientRect();\n return { width: r.width, height: r.height };\n };\n const fromCentre = (clientX: number, clientY: number) => {\n const r = ref.current!.getBoundingClientRect();\n return { x: clientX - r.left - r.width / 2, y: clientY - r.top - r.height / 2 };\n };\n\n // React attaches wheel listeners as passive, so preventing the browser's page zoom needs a native one.\n const setViewportRef = React.useRef(setViewport);\n setViewportRef.current = setViewport;\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n const r = el.getBoundingClientRect();\n const at = { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 };\n setViewportRef.current(zoomAt(latest.current, latest.current.scale * Math.exp(-e.deltaY / 200), at, { width: r.width, height: r.height }));\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, []);\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n const v = latest.current;\n const centre = { x: 0, y: 0 };\n if (e.key === \"+\" || e.key === \"=\") setViewport(zoomAt(v, v.scale * 1.5, centre, size()));\n else if (e.key === \"-\") setViewport(zoomAt(v, v.scale / 1.5, centre, size()));\n else if (e.key === \"0\") setViewport(FIT);\n else if (v.scale > 1 && e.key.startsWith(\"Arrow\")) {\n // Arrow right looks right: the picture moves left.\n const dx = e.key === \"ArrowRight\" ? -PAN_STEP : e.key === \"ArrowLeft\" ? PAN_STEP : 0;\n const dy = e.key === \"ArrowDown\" ? -PAN_STEP : e.key === \"ArrowUp\" ? PAN_STEP : 0;\n setViewport(clampViewport({ ...v, x: v.x + dx, y: v.y + dy }, size()));\n } else return;\n e.preventDefault();\n e.stopPropagation();\n };\n\n const zoomed = viewport.scale > 1;\n return (\n <div\n ref={ref}\n role=\"group\"\n aria-label={label}\n aria-roledescription=\"zoomable picture\"\n tabIndex={0}\n onKeyDown={onKeyDown}\n onPointerDown={(e) => {\n if (!zoomed || e.button !== 0) return;\n drag.current = { x: e.clientX, y: e.clientY };\n e.currentTarget.setPointerCapture?.(e.pointerId);\n }}\n onPointerMove={(e) => {\n if (!drag.current) return;\n const dx = e.clientX - drag.current.x;\n const dy = e.clientY - drag.current.y;\n drag.current = { x: e.clientX, y: e.clientY };\n setViewport(clampViewport({ ...latest.current, x: latest.current.x + dx, y: latest.current.y + dy }, size()));\n }}\n onPointerUp={() => (drag.current = null)}\n onPointerCancel={() => (drag.current = null)}\n onDoubleClick={(e) => {\n const v = latest.current;\n setViewport(v.scale > 1 ? FIT : zoomAt(v, 2, fromCentre(e.clientX, e.clientY), size()));\n }}\n style={{ aspectRatio: String(aspect), ...(maxHeight ? { maxWidth: `calc(${maxHeight} * ${aspect})`, marginInline: \"auto\" } : {}), touchAction: zoomed ? \"none\" : \"pan-y\" }}\n className={cn(\n \"relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none\",\n zoomed ? \"cursor-grab active:cursor-grabbing\" : \"cursor-zoom-in\",\n \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\",\n className,\n )}\n >\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {children}\n </div>\n {cover && (\n <div className=\"absolute inset-0\" style={{ clipPath: `inset(0 ${100 - cover.shown}% 0 0)` }}>\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {cover.content}\n </div>\n </div>\n )}\n {overlay != null && (\n <div\n className=\"pointer-events-none absolute inset-0\"\n onPointerDown={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n onDoubleClick={(e) => e.stopPropagation()}\n >\n {overlay}\n </div>\n )}\n </div>\n );\n});\n","import * as React from \"react\";\nimport { Slider as AriaSlider, SliderThumb, SliderTrack } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { Skeleton } from \"./data-view\";\nimport { Caption, FullscreenButton, Picture, VIEWPORT_HEIGHT, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Slider } from \"./value-controls\";\nimport { DifferenceMarks, useDifference, type ReadPixels } from \"./difference\";\nimport { format } from \"../lib/format\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\n\n// Two renderings of the same thing, to be looked at closely and judged. It exists because four\n// apps draw this by hand (the stills arena, the models judge, the listory match queue, the\n// Bright Horizons review) and none of them can zoom both sides together, lay one over the other or\n// look at it full screen. The design and the survey are in the project's design.md; this file is the\n// first piece, for pictures. Text, audio, video and data kinds, a difference view and voting come\n// in later changes and join the same `Candidate` and `CompareMode` types.\n//\n// Four views, because each answers a different question: side by side (which do I prefer),\n// swipe (where exactly do they differ, along this edge), fade (the same, softly) and blink (flip\n// between them in place, the most sensitive way to see a small change). Zoom and pan are one state\n// for both sides, so the same detail is in view in both. Full screen keeps everything.\n//\n// Blind by type: `blind` is required with no default, because showing a judge which variant is which\n// is a validity bug, not a style choice. When it is true the picture's name is its `label` (the\n// caller passes \"A\" and \"B\"), the caller's `alt` and `note` are never put on the page, and the\n// real `id` is never rendered at all. Mind the URL: `src` reaches the DOM, so a blind caller serves\n// the pictures under neutral addresses (the arena's `img/{token}/left`).\n//\n// Failure is a state: a picture that does not load says so in `missing` (required, in the product's\n// words) in its own place, and the other side is still usable. One filled button rule: this\n// component draws none, a vote bar will be the view's filled control.\n\n/** A picture to compare. */\nexport type ImageMedia = {\n kind: \"image\";\n src: string;\n /** What it shows. Ignored when the comparison is `blind`: the label names it then. */\n alt: string;\n /** Its natural size in pixels, if known, so the frame has its shape and \"1:1\" is exact before the picture loads. */\n size?: readonly [number, number];\n};\n\n/** A clip to compare by listening (`CompareAudio`). Serve it under a neutral address when the comparison is blind. */\nexport type AudioMedia = {\n kind: \"audio\";\n src: string;\n};\n\n/** A text to compare by reading (`CompareText`). */\nexport type TextMedia = {\n kind: \"text\";\n text: string;\n};\n\n/** A video to compare (`CompareVideo`). Serve it under a neutral address when the comparison is blind: `src` reaches the page. */\nexport type VideoMedia = {\n kind: \"video\";\n src: string;\n /** A still shown before the first frame. */\n poster?: string;\n /** Its size in pixels, for the shape of the frame, \"1:1\" and drawing candidates of different sizes in one box. */\n width: number;\n height: number;\n /** Frames per second, if known: the unit of the sync tolerance and of the frame readout. Default 30. */\n fps?: number;\n};\n\n/** One side of a comparison. */\nexport type Candidate<M = ImageMedia> = {\n /** Who it is: a variant name, a model. Never put on the page when `blind`, and never needed by it. */\n id: string;\n /** What the person sees it called: \"Original\", or \"A\" when blind. */\n label: string;\n media: M;\n /** A line under the label (\"auto2, 14 s\"). Not shown when `blind`. */\n note?: string;\n};\n\n/** How two pictures are laid out. */\nexport type CompareMode = \"side\" | \"swipe\" | \"fade\" | \"blink\" | \"difference\";\n\nconst MODE_LABEL: Record<CompareMode, string> = { side: \"Side by side\", swipe: \"Swipe\", fade: \"Fade\", blink: \"Blink\", difference: \"Difference\" };\nconst ALL_MODES: readonly CompareMode[] = [\"side\", \"swipe\", \"fade\", \"blink\", \"difference\"];\n\n/** Props for `Compare`. */\nexport type CompareProps = {\n /** Names the comparison for screen readers: \"Photo 1 of 12, two versions\". Required. */\n label: string;\n a: Candidate;\n b: Candidate;\n /** Whether the person must not learn which variant is which. Required, no default. */\n blind: boolean;\n /** The words shown where a picture could not be loaded: \"Picture not found\". Required. */\n missing: string;\n mode: CompareMode;\n onModeChange: (mode: CompareMode) => void;\n /** Words for when the difference view cannot read the pictures' pixels (a picture from another site without CORS headers). Default says so plainly. */\n cannotCompare?: string;\n /** Which difference the difference view opens on: `brightness` (live, any picture) or `pixels` (the changed pixels marked, with a tolerance and the share that differ). Default `brightness`. */\n defaultDifference?: \"brightness\" | \"pixels\";\n /** How pictures become pixels for the difference view. Default draws them on a canvas. */\n readPixels?: ReadPixels;\n /** Which views are offered. Default all five. Must include `mode`. */\n modes?: readonly CompareMode[];\n /** How tall a frame may be, so the pair and the answer fit on one screen: a CSS length (`\"60svh\"`) or `\"viewport\"` (the window's height less room for the toolbar, captions, a vote bar and the key legend). The frame narrows to keep the picture's shape. Default: as tall as the width makes it. */\n maxHeight?: string;\n /** Bind the view, zoom and full-screen keys on the window. Default true; turn off when a surrounding screen binds the same keys. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen (the answer keys of a `PairVote`), bound with Compare's own and drawn in the same legend, so there is one list and the two cannot clash unseen. Listed first. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the picture, above the legend, and kept in full screen: where a vote bar goes so the answer is never out of reach of the pictures. */\n footer?: React.ReactNode;\n className?: string;\n};\n\n/** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */\nexport function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = \"Could not read these pictures to compare their pixels.\", readPixels, defaultDifference = \"brightness\", className }: CompareProps) {\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n // Learned from the picture once it loads, and only for the pair it was learned from: a new pair starts again.\n const pairKey = `${a.media.src}|${b.media.src}`;\n const [learned, setLearned] = React.useState<{ key: string; size: readonly [number, number] } | null>(null);\n const natural = a.media.size ?? (learned?.key === pairKey ? learned.size : null);\n const [divider, setDivider] = React.useState(50);\n const [blend, setBlend] = React.useState(50);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [style, setStyle] = React.useState<\"brightness\" | \"pixels\">(defaultDifference);\n const [amplify, setAmplify] = React.useState(4);\n const [tolerance, setTolerance] = React.useState(10); // percent; pixelmatch's threshold is this over 100\n const diff = useDifference(a.media.src, b.media.src, tolerance / 100, mode === \"difference\" && style === \"pixels\", readPixels);\n const frameRef = React.useRef<HTMLDivElement>(null);\n const imgRef = React.useRef<HTMLImageElement>(null);\n const aspect = natural ? natural[0] / natural[1] : 3 / 2;\n\n const zoom = useZoom({ viewport, setViewport, frame: frameRef, natural });\n const flip = () => setShowing((s) => (s === \"a\" ? \"b\" : \"a\"));\n\n const offered = modes.includes(mode) ? modes : [mode, ...modes];\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n ...offered.map((m, i): Shortcut => ({ keys: [String(i + 1)], label: MODE_LABEL[m], run: () => onModeChange(m) })),\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip, disabled: mode !== \"blink\" },\n ...zoomShortcuts(zoom, full, setFull),\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const pane = (c: Candidate, ref?: React.Ref<HTMLImageElement>, onNatural?: (w: number, h: number) => void) => (\n <Picture c={c} blind={blind} missing={missing} imgRef={ref} onNatural={onNatural} />\n );\n const learn = (w: number, h: number) => setLearned({ key: pairKey, size: [w, h] });\n const frameProps = { viewport, setViewport, aspect, maxHeight: maxHeight === \"viewport\" ? VIEWPORT_HEIGHT : maxHeight };\n\n let body: React.ReactNode;\n if (mode === \"side\") {\n body = (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {[a, b].map((c, i) => (\n <figure key={i} className=\"grid gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame {...frameProps} label={blind ? `Picture ${c.label}` : `${c.label}`} ref={i === 0 ? frameRef : undefined}>\n {pane(c, i === 0 ? imgRef : undefined, i === 0 ? learn : undefined)}\n </ViewportFrame>\n </figure>\n ))}\n </div>\n );\n } else if (mode === \"difference\") {\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n <Caption c={a} blind={blind} />\n <span className=\"type-caption text-muted-foreground\">against</span>\n <Caption c={b} blind={blind} />\n </div>\n <ViewportFrame {...frameProps} ref={frameRef} label={`Difference between ${a.label} and ${b.label}`}>\n {style === \"brightness\" ? (\n <div className=\"absolute inset-0 isolate\" style={{ filter: `brightness(${amplify})` }}>\n <div className=\"absolute inset-0 bg-background\">{pane(a, imgRef, learn)}</div>\n <div className=\"absolute inset-0 bg-background mix-blend-difference\">{pane(b)}</div>\n </div>\n ) : (\n <>\n <div className=\"absolute inset-0 opacity-35\">{pane(a, imgRef, learn)}</div>\n {diff.status === \"ready\" && <DifferenceMarks difference={diff.difference} />}\n {diff.status === \"loading\" && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none opacity-40\" />}\n {diff.status === \"failed\" && <p role=\"alert\" className=\"absolute inset-x-0 bottom-0 bg-background/90 p-2 type-body-sm text-danger\">{cannotCompare}</p>}\n </>\n )}\n </ViewportFrame>\n </figure>\n );\n } else {\n // One frame, both pictures in it. Swipe clips the top one at the divider; fade lays it over at an opacity; blink shows one.\n const top = mode === \"blink\" ? (showing === \"a\" ? a : b) : a;\n const bottom = b;\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n {mode === \"blink\" ? <Caption c={top} blind={blind} /> : <Caption c={a} blind={blind} />}\n {mode !== \"blink\" && <Caption c={b} blind={blind} />}\n </div>\n <ViewportFrame\n {...frameProps}\n ref={frameRef}\n cover={mode === \"swipe\" ? { content: pane(a, imgRef, learn), shown: divider } : undefined}\n label={mode === \"blink\" ? `Picture ${top.label}` : `${a.label} over ${b.label}`}\n overlay={\n mode === \"swipe\" && (\n <AriaSlider\n aria-label={`Divider between ${a.label} and ${b.label}`}\n value={divider}\n onChange={(v) => setDivider(v as number)}\n minValue={0}\n maxValue={100}\n step={1}\n className=\"absolute inset-0\"\n >\n <SliderTrack className=\"pointer-events-none h-full w-full\">\n <SliderThumb\n className=\"pointer-events-auto grid h-full w-8 cursor-ew-resize place-items-center focus-visible:outline-2 focus-visible:outline-ring\"\n style={{ top: \"50%\" }}\n >\n <span aria-hidden className=\"col-start-1 row-start-1 h-full w-1 border-x border-background bg-foreground\" />\n <span aria-hidden className=\"col-start-1 row-start-1 size-6 rounded-pill border-2 border-foreground bg-background\" />\n </SliderThumb>\n </SliderTrack>\n </AriaSlider>\n )\n }\n >\n {pane(bottom)}\n {mode !== \"swipe\" && (\n <div className=\"absolute inset-0\" style={mode === \"fade\" ? { opacity: 1 - blend / 100 } : undefined}>\n {pane(top, imgRef, learn)}\n </div>\n )}\n </ViewportFrame>\n </figure>\n );\n }\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Comparison view\" className=\"items-center gap-2\">\n <ToggleGroup label=\"View\" options={offered.map((m) => ({ value: m, label: MODE_LABEL[m] }))} value={mode} onChange={(v) => onModeChange(v as CompareMode)} size=\"sm\" />\n <ToolbarSeparator />\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n {mode === \"fade\" && (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">{a.label}</span>\n <Slider aria-label={`Blend from ${a.label} to ${b.label}`} value={blend} onChange={setBlend} min={0} max={100} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"type-caption text-muted-foreground\">{b.label}</span>\n </div>\n )}\n {mode === \"difference\" && (\n <div className=\"grid gap-2\">\n <ToggleGroup label=\"Difference style\" options={[{ value: \"brightness\", label: \"Brightness\" }, { value: \"pixels\", label: \"Changed pixels\" }]} value={style} onChange={(v) => setStyle(v as \"brightness\" | \"pixels\")} size=\"sm\" className=\"justify-self-start\" />\n {style === \"brightness\" ? (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">Amplify</span>\n <Slider aria-label=\"Amplify differences\" value={amplify} onChange={setAmplify} min={1} max={8} hideValue className=\"flex-1\" />\n <span className=\"w-8 type-caption tabular-nums text-muted-foreground\">{amplify}×</span>\n </div>\n ) : (\n <>\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">Tolerance</span>\n <Slider aria-label=\"Tolerance for a changed pixel\" value={tolerance} onChange={setTolerance} min={0} max={50} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"w-10 type-caption tabular-nums text-muted-foreground\">{tolerance}%</span>\n </div>\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {diff.status === \"ready\"\n ? diff.difference.differing === 0\n ? \"No pixels differ at this tolerance.\"\n : `${format.share(diff.difference.differing / diff.difference.total)} of pixels differ at this tolerance.`\n : diff.status === \"loading\"\n ? \"Comparing pixels…\"\n : \"\"}\n </p>\n </>\n )}\n </div>\n )}\n {mode === \"blink\" && (\n <div>\n <ToggleGroup label=\"Showing\" options={[{ value: \"a\", label: a.label }, { value: \"b\", label: b.label }]} value={showing} onChange={(v) => setShowing(v as \"a\" | \"b\")} size=\"sm\" />\n </div>\n )}\n {body}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","import * as React from \"react\";\nimport { Flag } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { Menu } from \"./commands\";\nimport { Compare, type Candidate, type CompareProps, type ImageMedia } from \"./compare\";\nimport { DataView, type Load } from \"./data-view\";\nimport type { Shortcut } from \"./hotkeys\";\nimport { cn } from \"../lib/utils\";\n\n// The answering half of a blind pairwise judgment (\"which is better: A, B, or about the same?\"),\n// wrapped around `Compare` because the two share one keyboard and one legend. It exists because\n// strata-models' judge and the stills arena each drew their own bar and their own keys beside\n// Compare's: two legends, answer keys nobody could guess (`[` `]` `t`) because the natural ones\n// were taken, and the pictures lost \"click to choose\" once a click panned.\n//\n// - Keys come from one list merged into Compare's (`extraShortcuts`), so there is one legend and\n// a clash is visible: `a` and `b` choose a side, `t` is about the same, `s` is can't tell. None\n// of them is a view, zoom or full-screen key. Arrow keys are left to panning and the swipe\n// divider on purpose: a person who zooms in and presses an arrow to pan must not cast a vote.\n// - Choosing is a button under the pictures, not a click on them: a click on a picture pans.\n// The bar is part of Compare's footer so it stays on screen in full screen.\n// - No button is filled: while either side can win, nothing is the default (ux-research\n// `patterns.md` §2, one filled button, and a filled \"A\" would lean on the judge).\n// - The last answer's Undo sits in the same footer, so it is inside full screen too: a judge who answers\n// there must be able to take it back without leaving.\n// - `pending` disables the buttons and the keys, and says so in words, because an answer\n// that is still being saved must not be answered twice.\n// - The pair is a `Load` so a pair that is on its way, an empty queue and a failed read each have\n// their own words (`skeleton`, `empty` required, the failure with Try again).\n// - Blind is Compare's: `blind` stays required here, and the buttons are named with the labels\n// only (\"Prefer A\"), never the id.\n// - `PairVote` draws the pair with `Compare`; `PairJudge` is the same answering around any `view`\n// (`CompareAudio`, `CompareText`), because the answers are the same whatever is judged.\n// - Statistics (ratings, confidence, which pair comes next) stay on the server; this draws the\n// question and reports the answer.\n// Checked: React Aria has no vote or pairwise-choice part; the bar is `Button`s and a `Menu`\n// (React Aria's) for the flag reasons.\n\n/** One answer to a pair: a side, \"about the same\", \"can't tell\", or a flag with its reason. */\nexport type PairAnswer = { answer: \"a\" | \"b\" | \"tie\" | \"skip\" } | { answer: \"flag\"; reason: string };\n\n/** A pair to judge: pictures by default, or any media a `view` draws (`CompareAudio`, `CompareText`). */\nexport type Pair<M = ImageMedia> = { label: string; a: Candidate<M>; b: Candidate<M> };\n\n/** What `PairVote` hands a `view`: the answer keys for the view's legend and the vote bar for its footer. Pass both to `CompareAudio`, `CompareText` or your own. */\nexport type PairVoteSlot = { extraShortcuts: Shortcut[]; footer: React.ReactNode };\n\n/** Words for the vote bar, all in the product's voice. */\nexport type PairVoteWords = {\n /** Default \"About the same\". */\n tie?: string;\n /** Default \"Can't tell\". */\n skip?: string;\n /** What choosing a side says: `(label) => \"Prefer \" + label`. Default \"Prefer …\". */\n prefer?: (label: string) => string;\n /** Said while an answer is being saved. Default \"Saving your answer…\". */\n pending?: string;\n /** The flag menu's button. Default \"Flag this pair\". */\n flag?: string;\n};\n\n/** What every pair judgment takes, whatever it draws. */\nexport type PairJudgeProps<M> = {\n /** The pair now being judged, as a read. */\n pair: Load<Pair<M> | null>;\n /** Mirrors the pictures and the bar while the pair loads. Required. */\n skeleton: React.ReactNode;\n /** What to show when there is nothing left to judge, and what to do next. Required. */\n empty: React.ReactNode;\n /** Receives the answer. The caller sends it and sets `pending` meanwhile. */\n onAnswer: (answer: PairAnswer) => void;\n /** An answer is being saved: buttons and keys are off. */\n pending: boolean;\n /** A line above the pictures: \"12 pairs left\". */\n progress?: React.ReactNode;\n /** Reasons the judge can give for setting a pair aside (\"Picture missing\", \"Not the same scene\"); no flag menu without them. */\n flagReasons?: readonly string[];\n /** Addresses of the next pairs' pictures or clips, fetched ahead so the next pair is ready the moment this one is answered. */\n preload?: readonly string[];\n /** The answer just given: what it was, how to take it back, and what to show of the pair after (`reveal`, never during the judgment). */\n last?: { text: string; onUndo: () => void; reveal?: React.ReactNode };\n words?: PairVoteWords;\n /** Draws the pair: `(slot, pair) => <CompareAudio {...pair} {...slot} blind missing=… />`. Pass the whole `slot` through so the answer keys share the view's legend and the bar sits in its footer. */\n view: (slot: PairVoteSlot, pair: Pair<M>) => React.ReactNode;\n};\n\n/** Props for `PairVote`: the pair judgment, drawn with `Compare`. */\nexport type PairVoteProps = Omit<PairJudgeProps<ImageMedia>, \"view\"> & Omit<CompareProps, \"label\" | \"a\" | \"b\" | \"extraShortcuts\" | \"footer\">;\n\n/** A blind pairwise judgment of two pictures: `Compare`, answer keys in its legend, and a vote bar that never leans on either side. */\nexport function PairVote({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words, ...compare }: PairVoteProps) {\n return (\n <PairJudge\n {...{ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words }}\n view={(slot, p) => <Compare {...compare} label={p.label} a={p.a} b={p.b} {...slot} />}\n />\n );\n}\n\n/** A blind pairwise judgment of anything: the answer keys, vote bar, pending, flag menu, progress, preload and Undo around a `view` that draws the pair (`CompareAudio`, `CompareText`, your own). */\nexport function PairJudge<M>({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words = {}, view }: PairJudgeProps<M>) {\n React.useEffect(() => {\n // Warm the cache only; the elements are dropped at once.\n for (const src of preload ?? []) new Image().src = src;\n }, [preload]);\n const w = { tie: \"About the same\", skip: \"Can't tell\", pending: \"Saving your answer…\", flag: \"Flag this pair\", prefer: (l: string) => `Prefer ${l}`, ...words };\n return (\n <div className=\"grid gap-3\">\n {progress && <p className=\"type-body-sm text-muted-foreground\">{progress}</p>}\n <DataView state={pair} isEmpty={(p) => p === null} skeleton={skeleton} empty={empty}>\n {(p) => p && <Judged pair={p} onAnswer={onAnswer} pending={pending} flagReasons={flagReasons} words={w} last={last} view={view} />}\n </DataView>\n {/* With no pair on screen (the queue just ran out) the last answer can still be taken back. */}\n {last && !(pair.status === \"ready\" && pair.data) && <LastAnswer last={last} />}\n </div>\n );\n}\n\nfunction LastAnswer({ last }: { last: NonNullable<PairJudgeProps<unknown>[\"last\"]> }) {\n return (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-3 type-body-sm text-muted-foreground\">\n <span>{last.text}</span>\n <Button size=\"sm\" variant=\"ghost\" onPress={last.onUndo}>\n Undo\n </Button>\n {last.reveal}\n </div>\n );\n}\n\nfunction Judged<M>({ pair, onAnswer, pending, flagReasons, words, last, view }: { pair: Pair<M>; last?: PairJudgeProps<M>[\"last\"]; onAnswer: (a: PairAnswer) => void; pending: boolean; flagReasons?: readonly string[]; words: Required<PairVoteWords>; view: PairJudgeProps<M>[\"view\"] }) {\n const { a, b } = pair;\n const answer = (x: PairAnswer) => !pending && onAnswer(x);\n const shortcuts: Shortcut[] = [\n { keys: [\"a\"], label: words.prefer(a.label), run: () => answer({ answer: \"a\" }), disabled: pending },\n { keys: [\"b\"], label: words.prefer(b.label), run: () => answer({ answer: \"b\" }), disabled: pending },\n { keys: [\"t\"], label: words.tie, run: () => answer({ answer: \"tie\" }), disabled: pending },\n { keys: [\"s\"], label: words.skip, run: () => answer({ answer: \"skip\" }), disabled: pending },\n ];\n const footer = (\n <div className={cn(\"grid gap-2\")} aria-busy={pending || undefined}>\n <div role=\"group\" aria-label=\"Your answer\" className=\"flex flex-wrap items-center gap-2\">\n <Button disabled={pending} onPress={() => answer({ answer: \"a\" })}>{words.prefer(a.label)}</Button>\n <Button disabled={pending} onPress={() => answer({ answer: \"tie\" })}>{words.tie}</Button>\n <Button disabled={pending} onPress={() => answer({ answer: \"b\" })}>{words.prefer(b.label)}</Button>\n <Button variant=\"ghost\" disabled={pending} onPress={() => answer({ answer: \"skip\" })}>{words.skip}</Button>\n {flagReasons && flagReasons.length > 0 && (\n <Menu\n label={words.flag}\n trigger={\n <Button variant=\"ghost\" disabled={pending}>\n <Flag aria-hidden />\n {words.flag}\n </Button>\n }\n items={flagReasons.map((reason) => ({ id: reason, label: reason, run: () => answer({ answer: \"flag\", reason }) }))}\n />\n )}\n </div>\n {pending && <p role=\"status\" className=\"type-body-sm text-muted-foreground\">{words.pending}</p>}\n {last && <LastAnswer last={last} />}\n </div>\n );\n return <>{view({ extraShortcuts: shortcuts, footer }, pair)}</>;\n}\n","// How loud a clip is, for the audio comparison: so the louder of two clips does not win by being\n// louder (a few tenths of a dB already shifts preference), the comparison can turn the louder one\n// down to match.\n//\n// The measure is RMS over the whole clip (up to `MAX_SECONDS`) in dB relative to full scale, with\n// the sample peak beside it. It is not LUFS (ITU-R BS.1770): no K-weighting, no gating of silence.\n// For two renderings of the same sentence that is close enough to match them, and it is honest\n// about what it is; a product that needs broadcast loudness measures it on the server and passes\n// `measure`. The arithmetic takes plain channel arrays so it is unit tested without a browser;\n// decoding needs the Web Audio API and is covered by the Storybook shots in Chromium.\n\n/** A clip's level in dB relative to full scale: its RMS (what the ear follows) and its highest sample. */\nexport type Loudness = { rms: number; peak: number };\n\n/** The most of a clip that is measured, in seconds. */\nexport const MAX_SECONDS = 120;\n\nconst db = (x: number) => (x > 0 ? 20 * Math.log10(x) : -Infinity);\n\n/** The RMS and peak of channel data (-1 to 1), over all channels together. */\nexport function loudnessOf(channels: readonly Float32Array[]): Loudness {\n let sum = 0;\n let count = 0;\n let peak = 0;\n for (const c of channels)\n for (let i = 0; i < c.length; i++) {\n const v = c[i];\n sum += v * v;\n const a = Math.abs(v);\n if (a > peak) peak = a;\n }\n count = channels.reduce((n, c) => n + c.length, 0);\n return { rms: db(Math.sqrt(count ? sum / count : 0)), peak: db(peak) };\n}\n\n/** How much to turn each of two clips down (in dB, zero or less) so they play at the same RMS: the louder is lowered to the quieter. */\nexport function matchGains(a: Loudness, b: Loudness): { a: number; b: number } {\n if (!Number.isFinite(a.rms) || !Number.isFinite(b.rms)) return { a: 0, b: 0 };\n const diff = a.rms - b.rms;\n return diff > 0 ? { a: -diff, b: 0 } : { a: 0, b: diff };\n}\n\n/** dB to a media element's volume (0 to 1). */\nexport const gainToVolume = (decibels: number) => Math.min(1, Math.max(0, 10 ** (decibels / 20)));\n\n/** Fetches and decodes a clip and measures it. Needs the Web Audio API; reads at most `MAX_SECONDS`. */\nexport async function measureLoudness(src: string): Promise<Loudness> {\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Could not read ${src}: ${response.status}`);\n const Context = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;\n const context = new Context();\n try {\n const buffer = await context.decodeAudioData(await response.arrayBuffer());\n const frames = Math.min(buffer.length, Math.floor(buffer.sampleRate * MAX_SECONDS));\n return loudnessOf(Array.from({ length: buffer.numberOfChannels }, (_, c) => buffer.getChannelData(c).subarray(0, frames)));\n } finally {\n void context.close();\n }\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\nimport { gainToVolume, matchGains, measureLoudness, type Loudness } from \"../lib/loudness\";\nimport { Button } from \"./button\";\nimport type { AudioMedia, Candidate } from \"./compare\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\nimport { useMediaElement } from \"./media-player\";\nimport { Switch } from \"./switch\";\nimport { ToggleGroup } from \"./toggle\";\n\n// Two clips of the same thing, heard one after the other in the same place. What the TTS and\n// transcription evals in strata-models needed, and two independent players cannot give: the useful\n// comparison is the ABX-style one, so there is ONE transport and a switch between A and B that keeps\n// the playhead, and a person hears the same word in each voice without scrubbing twice.\n//\n// Only the chosen clip plays. Switching copies the position to the other (the same time, or the same\n// proportion when the clips differ in length: `align`, default \"auto\" is proportion when they differ\n// by more than 2%, since a clip that is 10% longer has its words later, not at the same second) and,\n// if it was playing, carries on in the other. A brief gap at the switch is the other element\n// starting, not a seek.\n//\n// Level: the louder of two clips tends to be judged better, so by default (`levelMatch`) the louder\n// is turned down to the quieter by RMS (`lib/loudness.ts`; not LUFS, and the file says so), and the\n// readout says by how much, in the candidates' labels, so a blind judge learns nothing about which\n// is which. It only ever turns a clip DOWN: a media element's volume cannot go above 1. Measuring\n// decodes the clip with the Web Audio API; `measure` replaces it (a server's figure, a test).\n//\n// Looping a range (set a start and an end at the playhead, clear them) lets a judge hear the same two\n// seconds in A, then B. The range is kept as shares of the clip, so it lands on the same words in the\n// other clip under proportional alignment and is the same seconds under time alignment. The end is\n// watched on `requestAnimationFrame` while playing, because `timeupdate` fires about four times a\n// second and the loop would overshoot by a quarter of a second.\n//\n// Keys: `1` and `2` choose A and B, `x` flips, Space and `k` play, `j` and `l` go back and forward a\n// second, `i` and `o` set the loop's start and end, `c` clears it. `a`, `b`, `t` and `s` are left for\n// a `PairVote`'s answers, and arrows are left to the seek bar. They come from one list, drawn in one\n// legend with the screen's (`extraShortcuts`).\n//\n// Blind: the same rules as `Compare`. Only the label names a clip on the page (the `<audio>` element\n// is \"Clip A\"); the id and note are never written. `src` reaches the DOM, so a blind caller serves\n// clips under neutral addresses.\n//\n// Checked: React Aria has no media player or A/B switch. The seek bar, transport, readout and volume\n// are strata's own parts built on its slider and toolbar hooks; the switch is a `ToggleGroup`.\n\n/** Props for `CompareAudio`. */\nexport type CompareAudioProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<AudioMedia>;\n b: Candidate<AudioMedia>;\n /** Whether the person must not learn which clip is which. Required, no default. */\n blind: boolean;\n /** The words shown when a clip cannot be loaded: \"Clip not found\". Required. */\n missing: string;\n /** Turn the louder clip down to the quieter one. Default true. */\n levelMatch?: boolean;\n /** How a switch carries the playhead over: the same time, the same share of the clip, or by share when the lengths differ by more than 2%. Default \"auto\". */\n align?: \"time\" | \"proportion\" | \"auto\";\n /** Measures a clip's level. Default decodes it in the browser. */\n measure?: (src: string) => Promise<Loudness>;\n /** Bind the keys on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen, bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the controls, above the legend: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\ntype Loop = { start: number | null; end: number | null };\n\nconst db = (x: number) => `${Math.abs(x).toFixed(1)} dB`;\n\n/** Two clips to judge by ear: one transport, a switch that keeps the playhead, a loop, and matched levels. */\nexport function CompareAudio({ label, a, b, blind, missing, levelMatch = true, align = \"auto\", measure = measureLoudness, keys = true, extraShortcuts = [], footer, className }: CompareAudioProps) {\n const refA = React.useRef<HTMLAudioElement>(null);\n const refB = React.useRef<HTMLAudioElement>(null);\n const sa = useMediaElement(refA);\n const sb = useMediaElement(refB);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [volume, setVolume] = React.useState(100);\n const [matching, setMatching] = React.useState(levelMatch);\n const [loop, setLoop] = React.useState<Loop>({ start: null, end: null });\n const [levels, setLevels] = React.useState<{ key: string; a: Loudness; b: Loudness } | \"failed\" | null>(null);\n\n const active = showing === \"a\" ? sa : sb;\n const keyOf = `${a.media.src}|${b.media.src}`;\n\n // Measure both clips once per pair, and only while matching.\n React.useEffect(() => {\n if (!matching) return;\n let live = true;\n setLevels(null);\n Promise.all([measure(a.media.src), measure(b.media.src)]).then(\n ([la, lb]) => live && setLevels({ key: keyOf, a: la, b: lb }),\n () => live && setLevels(\"failed\"),\n );\n return () => {\n live = false;\n };\n }, [matching, keyOf, a.media.src, b.media.src, measure]);\n\n const gains = matching && levels && levels !== \"failed\" && levels.key === keyOf ? matchGains(levels.a, levels.b) : { a: 0, b: 0 };\n React.useEffect(() => {\n if (refA.current) refA.current.volume = (volume / 100) * gainToVolume(gains.a);\n if (refB.current) refB.current.volume = (volume / 100) * gainToVolume(gains.b);\n }, [volume, gains.a, gains.b]);\n\n // Which share of the other clip is the same place as `time` in this one.\n const carry = (time: number, from: { duration: number | null }, to: { duration: number | null }) => {\n const known = from.duration && to.duration;\n if (!known || align === \"time\") return time;\n const differ = Math.abs(from.duration! - to.duration!) / Math.max(from.duration!, to.duration!) > 0.02;\n return align === \"proportion\" || differ ? (time / from.duration!) * to.duration! : time;\n };\n const hear = (side: \"a\" | \"b\") => {\n if (side === showing) return;\n const from = showing === \"a\" ? sa : sb;\n const to = side === \"a\" ? sa : sb;\n const wasPlaying = from.playing;\n from.pause();\n to.seek(carry(from.time, from, to));\n // The loop moves with the playhead's policy: under `time` it keeps its seconds, so its shares change.\n if (from.duration && to.duration) {\n const move = (share: number | null) => (share === null ? null : Math.min(1, carry(share * from.duration!, from, to) / to.duration!));\n setLoop((l) => ({ start: move(l.start), end: move(l.end) }));\n }\n if (wasPlaying) void to.play();\n setShowing(side);\n };\n const flip = () => hear(showing === \"a\" ? \"b\" : \"a\");\n\n const duration = active.duration ?? 0;\n const at = (share: number | null) => (share === null || !duration ? null : share * duration);\n const setPoint = (point: \"start\" | \"end\") => {\n if (!duration) return;\n const share = active.time / duration;\n setLoop((l) => {\n const next = { ...l, [point]: share };\n // A start after the end (or an end before the start) replaces the other point.\n if (next.start !== null && next.end !== null && next.start >= next.end) return point === \"start\" ? { start: share, end: null } : { start: null, end: share };\n return next;\n });\n };\n const clearLoop = () => setLoop({ start: null, end: null });\n\n // Back to the start of the range when the end is reached.\n const looping = loop.start !== null && loop.end !== null;\n const enforce = React.useCallback(() => {\n const e = (showing === \"a\" ? refA : refB).current;\n if (!e || !looping || !Number.isFinite(e.duration)) return;\n if (e.currentTime >= loop.end! * e.duration || e.currentTime < loop.start! * e.duration - 0.05) e.currentTime = loop.start! * e.duration;\n }, [showing, looping, loop.start, loop.end]);\n // Only while playing: a paused judge may park the playhead anywhere (to set a new start, say).\n React.useEffect(() => {\n if (looping && active.playing && active.time >= loop.end! * duration) enforce();\n }, [active.time, active.playing, looping, loop.end, duration, enforce]);\n React.useEffect(() => {\n if (!looping || !active.playing) return;\n let frame = requestAnimationFrame(function tick() {\n enforce();\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [looping, active.playing, enforce]);\n\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n { keys: [\"1\"], label: `Hear ${a.label}`, run: () => hear(\"a\") },\n { keys: [\"2\"], label: `Hear ${b.label}`, run: () => hear(\"b\") },\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip },\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: active.toggle },\n { keys: [\"j\"], label: \"Back 1 s\", run: () => active.seek(Math.max(0, active.time - 1)), repeat: true },\n { keys: [\"l\"], label: \"Forward 1 s\", run: () => active.seek(active.time + 1), repeat: true },\n { keys: [\"i\"], label: \"Loop starts here\", run: () => setPoint(\"start\") },\n { keys: [\"o\"], label: \"Loop ends here\", run: () => setPoint(\"end\") },\n { keys: [\"c\"], label: \"Clear the loop\", run: clearLoop, disabled: loop.start === null && loop.end === null },\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const failed = sa.error || sb.error;\n const marks = [\n ...(loop.start !== null && at(loop.start) !== null ? [{ time: at(loop.start)!, label: \"Loop start\" }] : []),\n ...(loop.end !== null && at(loop.end) !== null ? [{ time: at(loop.end)!, label: \"Loop end\" }] : []),\n ];\n const range = (share: number | null) => (share === null || !duration ? format.missing : format.timecode(share * duration, { precision: \"seconds\" }));\n\n let levelLine: string | null = null;\n if (matching) {\n if (levels === \"failed\") levelLine = \"Could not measure the levels, so the clips are not matched.\";\n else if (!levels || levels.key !== keyOf) levelLine = \"Measuring levels…\";\n else if (gains.a === 0 && gains.b === 0) levelLine = \"Both clips are at the same level.\";\n else {\n const [loud, quiet, cut] = gains.a < 0 ? [a.label, b.label, gains.a] : [b.label, a.label, gains.b];\n levelLine = `${loud} is louder than ${quiet}, so it is turned down by ${db(cut)}.`;\n }\n }\n\n return (\n <section aria-label={label} className={cn(\"grid gap-3\", className)}>\n <audio ref={refA} src={a.media.src} preload=\"auto\" aria-label={`Clip ${a.label}`} />\n <audio ref={refB} src={b.media.src} preload=\"auto\" aria-label={`Clip ${b.label}`} />\n <div className=\"flex flex-wrap items-center gap-3\">\n <ToggleGroup\n label=\"Listen to\"\n options={[\n { value: \"a\", label: a.label },\n { value: \"b\", label: b.label },\n ]}\n value={showing}\n onChange={(v) => hear(v as \"a\" | \"b\")}\n />\n <Switch label=\"Match loudness\" on={matching} onChange={setMatching} />\n </div>\n {!blind && (a.note || b.note) && (\n <p className=\"type-caption text-muted-foreground\">\n {[a, b].filter((c) => c.note).map((c) => `${c.label}: ${c.note}`).join(\" · \")}\n </p>\n )}\n {failed && (\n <p role=\"alert\" className=\"type-body-sm text-danger\">\n {missing}\n </p>\n )}\n <Transport playing={active.playing} onPlayPause={active.toggle}>\n <TimeReadout time={active.time} duration={active.duration} />\n <SeekBar time={active.time} duration={active.duration} onSeek={active.seek} marks={marks} buffered={active.buffered} label={`Position in ${(showing === \"a\" ? a : b).label}`} step={1} />\n <VolumeControl volume={volume} onVolumeChange={setVolume} />\n </Transport>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button size=\"sm\" onPress={() => setPoint(\"start\")} disabled={!duration}>\n Loop starts here\n </Button>\n <Button size=\"sm\" onPress={() => setPoint(\"end\")} disabled={!duration}>\n Loop ends here\n </Button>\n <Button size=\"sm\" variant=\"ghost\" onPress={clearLoop} disabled={loop.start === null && loop.end === null}>\n Clear the loop\n </Button>\n <span role=\"status\" className=\"type-caption tabular-nums text-muted-foreground\">\n {looping ? `Looping ${range(loop.start)} to ${range(loop.end)}` : loop.start !== null ? `Loop starts at ${range(loop.start)}` : loop.end !== null ? `Loop ends at ${range(loop.end)}` : \"No loop\"}\n </span>\n </div>\n {levelLine && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {levelLine}\n </p>\n )}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Slider as AriaSlider, SliderThumb, SliderTrack } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { Skeleton } from \"./data-view\";\nimport { Caption, FullscreenButton, VIEWPORT_HEIGHT, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport type { Candidate, CompareMode, VideoMedia } from \"./compare\";\nimport { RateChoice, SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\nimport { useMediaElement } from \"./media-player\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Slider } from \"./value-controls\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\n\n// Two videos of the same thing on ONE clock, to be judged blind by eye. What the video-enhance eval\n// in strata-models needs and two plain <video> elements cannot give: the interesting views (the swipe\n// divider over moving picture, blink between A and B on the same frame) only mean something if both\n// sides show the same instant, and zoom and pan must stay locked across them while they play.\n//\n// The clock: play, pause, seek and rate go to both elements; the first video is the leader. While it\n// plays, a requestAnimationFrame loop keeps the follower within a frame (`fps`, default 30) of it: a\n// follower more than a frame off has its rate nudged by 3% towards the leader, one more than 0.3 s\n// off is seeked to it, and when either side has not got its next frames (readyState below 3) BOTH\n// are paused until both have, so a stall on one side is never seen as the other side running ahead.\n// requestVideoFrameCallback was considered for the loop and not used: it fires only when the leader\n// presents a frame, which is the one time a stall cannot be seen; a display-frame loop sees both and\n// costs nothing at 25 to 50 fps content. Known limit: a seek is not hidden while the two decoders\n// catch up (a video element cannot hold its old frame), it is corrected by the same loop; playback\n// after a seek waits for both.\n//\n// Sizes: candidates may differ in pixels (1440×1080 against 2816×2304). Both are drawn `object-contain`\n// in the same box whose shape is the first candidate's `width`/`height`, so neither looks bigger.\n// Zoom is the shared `useViewport` of `Compare`; `pixelated` draws nearest-neighbour once the picture\n// is shown larger than its own pixels (default), so a judge sees real pixels, not a smoothed guess.\n//\n// Views: side by side, swipe, fade and blink, the same as pictures. Changing view puts the videos in\n// a different place in the tree, so the browser makes new elements; the clock remembers the time and\n// whether it was playing and puts the new ones back there when they have their metadata.\n//\n// Sound: one source, the app's choice (`audio`, default \"a\"; the outputs normally share it), the\n// other muted, so two soundtracks never play at once.\n//\n// Blind: the same rules as `Compare`. Only `label` names a video on the page; id, note and any\n// description are never written. `src` and `poster` reach the DOM, so a blind caller serves them\n// under neutral addresses.\n//\n// Keys: `1` to `4` views, `x` flips in blink, Space and `k` play, `j` and `l` go back and forward a\n// second, `m` mutes, `+` `-` `0` `f` zoom and full screen. `a`, `b`, `t` and `s` are left to a\n// `PairVote`; arrows are left to the picture (they pan once zoomed). One list for the keys and the\n// legend (`extraShortcuts`).\n//\n// Checked: React Aria has no video player or comparison part; the transport, seek bar and rate\n// choice are the media parts built on its slider, toolbar and select, and the swipe divider is its\n// slider, as in `Compare`.\n\n/** The views a pair of videos has: pictures' views without the difference, which needs pixels. */\nexport type VideoMode = Exclude<CompareMode, \"difference\">;\n\nconst MODES: readonly VideoMode[] = [\"side\", \"swipe\", \"fade\", \"blink\"];\nconst MODE_LABEL: Record<VideoMode, string> = { side: \"Side by side\", swipe: \"Swipe\", fade: \"Fade\", blink: \"Blink\" };\n\n/** Props for `CompareVideo`. */\nexport type CompareVideoProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<VideoMedia>;\n b: Candidate<VideoMedia>;\n /** Whether the person must not learn which video is which. Required, no default. */\n blind: boolean;\n /** The words shown when a video cannot be loaded: \"Video not found\". Required. */\n missing: string;\n mode: VideoMode;\n onModeChange: (mode: VideoMode) => void;\n /** Which video's sound is heard; the other is muted. Default \"a\". */\n audio?: \"a\" | \"b\" | \"none\";\n /** Draw nearest-neighbour when shown larger than the video's own pixels (`zoomed`, default), always, or never. */\n pixelated?: \"zoomed\" | \"always\" | \"never\";\n /** How tall a frame may be: a CSS length or `\"viewport\"`, as in `Compare`. */\n maxHeight?: string;\n /** Bind the keys on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen, bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the video, above the legend, and kept in full screen: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\n// Width of an element, kept current, for \"is this shown larger than its pixels\".\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const read = () => setWidth(el.getBoundingClientRect().width);\n read();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n });\n return width;\n}\n\n/** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */\nexport function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio = \"a\", pixelated = \"zoomed\", maxHeight, keys = true, extraShortcuts = [], footer, className }: CompareVideoProps) {\n const refA = React.useRef<HTMLVideoElement>(null);\n const refB = React.useRef<HTMLVideoElement>(null);\n const sa = useMediaElement(refA);\n const sb = useMediaElement(refB);\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n const [divider, setDivider] = React.useState(50);\n const [blend, setBlend] = React.useState(50);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [volume, setVolume] = React.useState(100);\n const [muted, setMuted] = React.useState(false);\n // What the person asked for, which can differ from what the elements are doing while one waits for the other.\n const [wanted, setWanted] = React.useState(false);\n const frameRef = React.useRef<HTMLDivElement>(null);\n const frameWidth = useWidth(frameRef);\n\n const fps = a.media.fps ?? 30;\n const known = [sa.duration, sb.duration].filter((d): d is number => d !== null);\n const duration = known.length ? Math.min(...known) : null;\n const failed = sa.error || sb.error;\n\n // ---- the clock ----\n const play = () => {\n setWanted(true);\n void sa.play();\n void sb.play();\n };\n const pause = () => {\n setWanted(false);\n sa.pause();\n sb.pause();\n };\n const toggle = () => (wanted ? pause() : play());\n const seek = (time: number) => {\n const t = Math.max(0, duration === null ? time : Math.min(time, duration));\n sa.seek(t);\n sb.seek(t);\n };\n // Kept here, not read back from an element, so a view change's new elements get it too.\n const chosenRate = React.useRef(1);\n const setRate = (rate: number) => {\n chosenRate.current = rate;\n sa.setRate(rate);\n sb.setRate(rate);\n };\n\n // Either video reaching its end ends the play for both: the clock runs to the shorter one's end, which is the length shown.\n React.useEffect(() => {\n if (sa.ended || sb.ended) {\n setWanted(false);\n refA.current?.pause();\n refB.current?.pause();\n }\n }, [sa.ended, sb.ended]);\n\n React.useEffect(() => {\n if (!wanted) return;\n let held = false;\n let frame = requestAnimationFrame(function tick() {\n const A = refA.current;\n const B = refB.current;\n if (A && B && !A.ended && !B.ended) {\n const ready = A.readyState >= 3 && B.readyState >= 3;\n if (!ready) {\n if (!held) {\n held = true;\n A.pause();\n B.pause();\n }\n } else if (held) {\n held = false;\n void A.play();\n void B.play();\n } else if (!A.paused) {\n const drift = B.currentTime - A.currentTime;\n const one = 1 / fps;\n if (Math.abs(drift) > 0.3) B.currentTime = A.currentTime;\n else if (Math.abs(drift) > one) B.playbackRate = A.playbackRate * (drift > 0 ? 0.97 : 1.03);\n else if (Math.abs(drift) < one / 2 && B.playbackRate !== A.playbackRate) B.playbackRate = A.playbackRate;\n }\n }\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [wanted, fps]);\n\n // New elements (a view change) come back to where the old ones were.\n const resume = React.useRef({ time: 0, playing: false });\n if (sa.duration !== null) resume.current = { time: sa.time, playing: wanted };\n const restore = (e: React.SyntheticEvent<HTMLVideoElement>) => {\n const el = e.currentTarget;\n el.defaultPlaybackRate = chosenRate.current;\n el.playbackRate = chosenRate.current;\n if (resume.current.time > 0) el.currentTime = resume.current.time;\n if (resume.current.playing) void el.play();\n };\n\n // One sound: the chosen video at the volume, the rest muted.\n React.useEffect(() => {\n [[refA.current, \"a\"], [refB.current, \"b\"]].forEach(([el, side]) => {\n if (!(el instanceof HTMLVideoElement)) return;\n el.muted = audio !== side || muted || volume === 0;\n el.volume = volume / 100;\n });\n });\n\n // ---- the picture ----\n const aspect = a.media.width / a.media.height;\n const natural = [a.media.width, a.media.height] as const;\n // Each video against its own pixels: the one drawn larger than its pixels is nearest-neighbour, the other not.\n const frameHeight = frameWidth / aspect;\n const sharpFor = (c: Candidate<VideoMedia>) => {\n if (pixelated !== \"zoomed\") return pixelated === \"always\";\n const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));\n return drawn > 0 && (viewport.scale * drawn) / c.media.width > 1;\n };\n const zoom = useZoom({ viewport, setViewport, frame: frameRef, natural });\n const flip = () => setShowing((s) => (s === \"a\" ? \"b\" : \"a\"));\n\n const video = (c: Candidate<VideoMedia>, ref: React.RefObject<HTMLVideoElement | null>) => (\n <video\n ref={ref}\n src={c.media.src}\n poster={c.media.poster}\n preload=\"auto\"\n playsInline\n aria-label={`Video ${c.label}`}\n onLoadedMetadata={restore}\n style={sharpFor(c) ? { imageRendering: \"pixelated\" } : undefined}\n className=\"absolute inset-0 size-full object-contain\"\n />\n );\n const loading = !failed && (sa.duration === null || sb.duration === null);\n const skeleton = loading && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none\" />;\n const frameProps = { viewport, setViewport, aspect, maxHeight: maxHeight === \"viewport\" ? VIEWPORT_HEIGHT : maxHeight };\n\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n ...MODES.map((m, i): Shortcut => ({ keys: [String(i + 1)], label: MODE_LABEL[m], run: () => onModeChange(m) })),\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip, disabled: mode !== \"blink\" },\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: toggle },\n { keys: [\"j\"], label: \"Back 1 s\", run: () => seek(sa.time - 1), repeat: true },\n { keys: [\"l\"], label: \"Forward 1 s\", run: () => seek(sa.time + 1), repeat: true },\n ...(audio === \"none\" ? [] : [{ keys: [\"m\"], label: \"Mute\", run: () => setMuted((m) => !m) }]),\n ...zoomShortcuts(zoom, full, setFull),\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n let body: React.ReactNode;\n if (mode === \"side\") {\n body = (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {([[a, refA], [b, refB]] as const).map(([c, ref], i) => (\n <figure key={i} className=\"grid gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame {...frameProps} label={`Frame ${c.label}`} ref={i === 0 ? frameRef : undefined}>\n {i === 0 && skeleton}\n {video(c, ref)}\n </ViewportFrame>\n </figure>\n ))}\n </div>\n );\n } else {\n // One frame, both videos in it. Swipe clips A at the divider; fade lays A over B at an opacity; blink shows one at a time. Both always play.\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n {mode === \"blink\" ? <Caption c={showing === \"a\" ? a : b} blind={blind} /> : <Caption c={a} blind={blind} />}\n {mode !== \"blink\" && <Caption c={b} blind={blind} />}\n </div>\n <ViewportFrame\n {...frameProps}\n ref={frameRef}\n cover={mode === \"swipe\" ? { content: video(a, refA), shown: divider } : undefined}\n label={mode === \"blink\" ? `Frame ${(showing === \"a\" ? a : b).label}` : `${a.label} over ${b.label}`}\n overlay={\n mode === \"swipe\" && (\n <AriaSlider aria-label={`Divider between ${a.label} and ${b.label}`} value={divider} onChange={(v) => setDivider(v as number)} minValue={0} maxValue={100} step={1} className=\"absolute inset-0\">\n <SliderTrack className=\"pointer-events-none h-full w-full\">\n <SliderThumb className=\"pointer-events-auto grid h-full w-8 cursor-ew-resize place-items-center focus-visible:outline-2 focus-visible:outline-ring\" style={{ top: \"50%\" }}>\n <span aria-hidden className=\"col-start-1 row-start-1 h-full w-1 border-x border-background bg-foreground\" />\n <span aria-hidden className=\"col-start-1 row-start-1 size-6 rounded-pill border-2 border-foreground bg-background\" />\n </SliderThumb>\n </SliderTrack>\n </AriaSlider>\n )\n }\n >\n {skeleton}\n {video(b, refB)}\n {mode !== \"swipe\" && <div className=\"absolute inset-0\" style={mode === \"fade\" ? { opacity: 1 - blend / 100 } : mode === \"blink\" ? { opacity: showing === \"a\" ? 1 : 0 } : undefined}>{video(a, refA)}</div>}\n </ViewportFrame>\n </figure>\n );\n }\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Comparison view\" className=\"items-center gap-2\">\n <ToggleGroup label=\"View\" options={MODES.map((m) => ({ value: m, label: MODE_LABEL[m] }))} value={mode} onChange={(v) => onModeChange(v as VideoMode)} size=\"sm\" />\n <ToolbarSeparator />\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n {mode === \"fade\" && (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">{a.label}</span>\n <Slider aria-label={`Blend from ${a.label} to ${b.label}`} value={blend} onChange={setBlend} min={0} max={100} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"type-caption text-muted-foreground\">{b.label}</span>\n </div>\n )}\n {mode === \"blink\" && <ToggleGroup label=\"Showing\" options={[{ value: \"a\", label: a.label }, { value: \"b\", label: b.label }]} value={showing} onChange={(v) => setShowing(v as \"a\" | \"b\")} size=\"sm\" className=\"justify-self-start\" />}\n {failed && (\n <p role=\"alert\" className=\"type-body-sm text-danger\">\n {missing}\n </p>\n )}\n {body}\n <Transport playing={wanted} onPlayPause={toggle}>\n <TimeReadout time={sa.time} duration={duration} />\n <SeekBar time={sa.time} duration={duration} onSeek={seek} buffered={sa.buffered} label=\"Position\" step={1} precision=\"frames\" fps={fps} />\n <RateChoice rate={sa.rate} onRateChange={setRate} />\n {audio !== \"none\" && <VolumeControl volume={muted ? 0 : volume} onVolumeChange={(v) => (setMuted(false), setVolume(v))} />}\n </Transport>\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","// A word-level difference between two texts, for `CompareText`. Our own and deliberately simple\n// (Jonathan, 2026-11-12: \"do a simple diff ourselves for now and see what text similarity is better\n// in future\"): split on whitespace, find the longest common subsequence of words, and mark the words\n// on each side that are not in it. Case and punctuation count, because a transcript that drops a\n// comma or a capital differs from one that keeps it, and the judge decides whether that matters.\n// What it does not do: notice a moved sentence (it shows as removed here and added there), weigh a\n// word by how different it is, or align by meaning. Those are what a text-similarity method would\n// add, and are the reason this stays behind one function.\n//\n// The table is words × words, so a very long pair is refused (`null`) rather than freezing the\n// page; the caller says so in words and still shows both texts.\n\n/** A run of one text: its words and spaces as written, and whether the words are not in the other text. */\nexport type TextSegment = { text: string; changed: boolean };\n\n/** The two texts cut into segments, and how many words differ on each side. */\nexport type TextDifference = { a: TextSegment[]; b: TextSegment[]; changedA: number; changedB: number };\n\n/** The most words in A times the most in B that are compared; a bigger pair is not. */\nexport const MAX_CELLS = 2_500_000;\n\nconst tokens = (text: string) => text.split(/(\\s+)/).filter((t) => t !== \"\");\nconst isSpace = (t: string) => /^\\s+$/.test(t);\n\n/** Marks the words that differ between two texts, or returns null when the pair is too long to compare. */\nexport function diffWords(a: string, b: string): TextDifference | null {\n const ta = tokens(a);\n const tb = tokens(b);\n const wa = ta.filter((t) => !isSpace(t));\n const wb = tb.filter((t) => !isSpace(t));\n if ((wa.length + 1) * (wb.length + 1) > MAX_CELLS) return null;\n const w = wb.length + 1;\n const table = new Uint32Array((wa.length + 1) * w);\n for (let i = wa.length - 1; i >= 0; i--)\n for (let j = wb.length - 1; j >= 0; j--)\n table[i * w + j] = wa[i] === wb[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);\n const sameA = new Set<number>();\n const sameB = new Set<number>();\n for (let i = 0, j = 0; i < wa.length && j < wb.length; ) {\n if (wa[i] === wb[j]) {\n sameA.add(i++);\n sameB.add(j++);\n } else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) i++;\n else j++;\n }\n const cut = (all: string[], same: Set<number>) => {\n let word = 0;\n const out: TextSegment[] = [];\n let changed = 0;\n for (const t of all) {\n if (isSpace(t)) {\n out.push({ text: t, changed: false });\n continue;\n }\n const diff = !same.has(word++);\n if (diff) changed++;\n out.push({ text: t, changed: diff });\n }\n return { out, changed };\n };\n const ra = cut(ta, sameA);\n const rb = cut(tb, sameB);\n return { a: ra.out, b: rb.out, changedA: ra.changed, changedB: rb.changed };\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { diffWords, type TextSegment } from \"../lib/text-diff\";\nimport type { Candidate, TextMedia } from \"./compare\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Switch } from \"./switch\";\n\n// Two texts side by side to be read and judged: the transcripts of one recording from two models,\n// or two answers to one question. A person reading both wants the same line next to the same line,\n// so the two panes scroll together, and wants the words that differ shown without having to find\n// them, so there is a word diff behind a switch (off by default: a diff is an answer, and a judge\n// who is reading for quality should read first).\n//\n// The diff is our own and simple (`lib/text-diff.ts`: words, longest common subsequence). A changed\n// word is marked with a background AND an underline, so it survives a colour-blind reading and a\n// print, and is a `<mark>`, which a screen reader announces as highlighted. A pair too long to\n// compare is refused in words and both texts are still shown.\n//\n// `reference` is a third text, a ground truth (the transcript a person wrote). It is shown above\n// the two, labelled, and the diff can be taken against it instead of against the other candidate:\n// \"which is closer to what was said\" is the question a transcription judge asks, so with a reference\n// the diff starts against it.\n//\n// Keys: `d` marks the differences; a screen's own keys (a `PairJudge`'s answers) join the same legend\n// through `extraShortcuts`, and its vote bar goes in `footer`.\n//\n// Blind: only the label names a text; the id and note are never written, and `reference` is a\n// separate, labelled thing the caller chooses to show. Text is data, never markup: it is rendered as\n// text with whitespace kept (`whitespace-pre-wrap`), so a model's output cannot inject HTML.\n//\n// Checked: React Aria has no text-diff or synchronised-scroll part. Scrolling is a plain scroll\n// listener on two native scroll boxes; each is a focusable region (`tabIndex=0`, labelled) so a\n// keyboard user can scroll it, which a scrollable `div` otherwise denies them.\n\n/** Props for `CompareText`. */\nexport type CompareTextProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<TextMedia>;\n b: Candidate<TextMedia>;\n /** Whether the person must not learn which text is which. Required, no default. */\n blind: boolean;\n /** A ground-truth text, shown above both; the diff starts against it, and can be switched to the other candidate. */\n reference?: { label: string; text: string };\n /** Start with the word differences marked. Default false. */\n defaultDiff?: boolean;\n /** Said when the pair is too long to compare word by word. Default says so plainly. */\n tooLong?: string;\n /** Scroll the two panes together. Default true. */\n linkedScroll?: boolean;\n /** Bind the keys (`d` marks the differences) on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen (a `PairJudge`'s answer keys), bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the texts, above the legend: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\nfunction Words({ segments, changed }: { segments: TextSegment[]; changed: boolean }) {\n return (\n <>\n {segments.map((s, i) =>\n changed && s.changed ? (\n <mark key={i} className=\"rounded-control bg-warning-subtle text-foreground underline decoration-2 underline-offset-2\">\n {s.text}\n </mark>\n ) : (\n <React.Fragment key={i}>{s.text}</React.Fragment>\n ),\n )}\n </>\n );\n}\n\n/** Two texts side by side with scrolling together, an optional reference, and a word diff on request. */\nexport function CompareText({ label, a, b, blind, reference, defaultDiff = false, tooLong = \"These texts are too long to compare word by word.\", linkedScroll = true, keys = true, extraShortcuts = [], footer, className }: CompareTextProps) {\n const [diff, setDiff] = React.useState(defaultDiff);\n const [against, setAgainst] = React.useState<\"other\" | \"reference\">(reference ? \"reference\" : \"other\");\n const boxA = React.useRef<HTMLDivElement>(null);\n const boxB = React.useRef<HTMLDivElement>(null);\n const syncing = React.useRef(false);\n\n const result = React.useMemo(() => {\n if (!diff) return null;\n if (against === \"reference\" && reference) {\n const ra = diffWords(a.media.text, reference.text);\n const rb = diffWords(b.media.text, reference.text);\n // `changedB` of each is the reference's words the candidate lacks: a model that drops words must not score as a match.\n return ra && rb ? { a: ra.a, b: rb.a, changedA: ra.changedA, changedB: rb.changedA, missingA: ra.changedB, missingB: rb.changedB } : \"long\";\n }\n const r = diffWords(a.media.text, b.media.text);\n return r ? { ...r, missingA: 0, missingB: 0 } : \"long\";\n }, [diff, against, reference, a.media.text, b.media.text]);\n\n // Keep the two panes at the same share of their scroll range: texts differ in length, so the\n // same pixel is not the same line, but the same share is close.\n const follow = (from: HTMLDivElement | null, to: HTMLDivElement | null) => {\n if (!linkedScroll || !from || !to || syncing.current) return;\n const range = from.scrollHeight - from.clientHeight;\n syncing.current = true;\n to.scrollTop = range > 0 ? (from.scrollTop / range) * (to.scrollHeight - to.clientHeight) : 0;\n requestAnimationFrame(() => (syncing.current = false));\n };\n\n const pane = (c: Candidate<TextMedia>, ref: React.RefObject<HTMLDivElement | null>, other: React.RefObject<HTMLDivElement | null>, segments: TextSegment[] | null) => (\n <figure className=\"grid min-w-0 gap-1.5\">\n <figcaption className=\"flex items-baseline gap-2\">\n <span className=\"type-label\">{c.label}</span>\n {!blind && c.note && <span className=\"type-caption text-muted-foreground\">{c.note}</span>}\n </figcaption>\n <div\n ref={ref}\n tabIndex={0}\n role=\"region\"\n aria-label={`Text ${c.label}`}\n onScroll={() => follow(ref.current, other.current)}\n className=\"max-h-96 overflow-auto whitespace-pre-wrap rounded-surface border border-border bg-muted p-3 type-body focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\"\n >\n {segments ? <Words segments={segments} changed /> : c.media.text}\n </div>\n </figure>\n );\n\n const counts = result && result !== \"long\" ? result : null;\n const words = (n: number) => `${n} ${n === 1 ? \"word\" : \"words\"}`;\n const ref = against === \"reference\" && reference;\n const say = (who: string, differ: number, missing: number) => (ref ? `${who}: ${words(differ)} ${differ === 1 ? \"differs\" : \"differ\"}, ${missing} missing.` : `${who}: ${words(differ)} ${differ === 1 ? \"differs\" : \"differ\"}.`);\n const shortcuts: Shortcut[] = [...extraShortcuts, { keys: [\"d\"], label: diff ? \"Hide the differences\" : \"Mark the differences\", run: () => setDiff((d) => !d) }];\n useHotkeys(shortcuts, { enabled: keys });\n return (\n <section aria-label={label} className={cn(\"grid gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-3\">\n <Switch label=\"Mark the words that differ\" on={diff} onChange={setDiff} />\n {diff && reference && (\n <ToggleGroup\n label=\"Differences against\"\n options={[\n { value: \"other\", label: \"The other text\" },\n { value: \"reference\", label: reference.label },\n ]}\n value={against}\n onChange={(v) => setAgainst(v as \"other\" | \"reference\")}\n size=\"sm\"\n />\n )}\n </div>\n {reference && (\n <figure className=\"grid gap-1.5\">\n <figcaption className=\"type-label\">{reference.label}</figcaption>\n <p className=\"whitespace-pre-wrap rounded-surface border border-border p-3 type-body\">{reference.text}</p>\n </figure>\n )}\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {pane(a, boxA, boxB, counts ? counts.a : null)}\n {pane(b, boxB, boxA, counts ? counts.b : null)}\n </div>\n {diff && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {result === \"long\"\n ? tooLong\n : counts && counts.changedA + counts.missingA + counts.changedB + counts.missingB === 0\n ? ref && reference\n ? `Both match ${reference.label} word for word.`\n : \"The texts are the same word for word.\"\n : counts\n ? `${say(a.label, counts.changedA, counts.missingA)} ${say(b.label, counts.changedB, counts.missingB)}`\n : null}\n </p>\n )}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { Caption, FullscreenButton, Picture, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport type { Candidate } from \"./compare\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys } from \"./hotkeys\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\n\n// Every candidate's picture for one item at once, with one zoom for all of them (the models app's\n// \"Outputs\" tab, which lists each candidate's output, and Bright Horizons' pick-which-to-keep).\n// Looking at the same detail in every tile is the point, so the viewport is shared exactly as it is\n// in `Compare`; the rest of `Compare` (blind, `missing`, the keys from one list, full screen) is\n// the same too, and shares its parts. What each tile offers beyond looking (open it in a\n// comparison, choose it, flag it) is the caller's: `actions` draws it under the caption, so the grid\n// does not decide that a tile is a button.\n\n/** Props for `CompareGrid`. */\nexport type CompareGridProps = {\n /** Names the grid for screen readers: \"Four versions of this photo\". Required. */\n label: string;\n items: readonly Candidate[];\n /** Whether the person must not learn which variant is which: tiles are named by label only. Required, no default. */\n blind: boolean;\n /** The words shown where a picture could not be loaded. Required. */\n missing: string;\n /** What goes under a tile's caption: a button to compare it, a choice, a flag. */\n actions?: (item: Candidate) => React.ReactNode;\n /** Tiles per row at full width. Default 3. A narrow screen uses fewer. */\n columns?: 2 | 3 | 4;\n /** Bind the zoom and full-screen keys on the window. Default true. */\n keys?: boolean;\n className?: string;\n};\n\nconst COLUMNS = { 2: \"sm:grid-cols-2\", 3: \"sm:grid-cols-2 lg:grid-cols-3\", 4: \"sm:grid-cols-2 lg:grid-cols-4\" } as const;\n\n/** Many pictures in a grid, zoomed and panned together, and full screen. */\nexport function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys = true, className }: CompareGridProps) {\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n const key = items.map((i) => i.media.src).join(\"|\");\n const [learned, setLearned] = React.useState<{ key: string; size: readonly [number, number] } | null>(null);\n const natural = items[0]?.media.size ?? (learned?.key === key ? learned.size : null);\n const aspect = natural ? natural[0] / natural[1] : 3 / 2;\n const first = React.useRef<HTMLDivElement>(null);\n const zoom = useZoom({ viewport, setViewport, frame: first, natural });\n const shortcuts = zoomShortcuts(zoom, full, setFull);\n useHotkeys(shortcuts, { enabled: keys });\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Zoom\" className=\"items-center gap-2\">\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n <div className={cn(\"grid gap-3\", COLUMNS[columns])}>\n {items.map((c, i) => (\n <figure key={c.id} className=\"grid content-start gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame viewport={viewport} setViewport={setViewport} aspect={aspect} label={blind ? `Picture ${c.label}` : c.label} ref={i === 0 ? first : undefined}>\n <Picture c={c} blind={blind} missing={missing} onNatural={i === 0 ? (w, h) => setLearned({ key, size: [w, h] }) : undefined} />\n </ViewportFrame>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions(c)}</div>}\n </figure>\n ))}\n </div>\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","import * as React from \"react\";\nimport { useMove, mergeProps } from \"react-aria\";\nimport {\n PanelBottomClose,\n PanelBottomOpen,\n PanelLeftClose,\n PanelLeftOpen,\n PanelRightClose,\n PanelRightOpen,\n PanelTopClose,\n PanelTopOpen,\n} from \"lucide-react\";\nimport { IconButton } from \"./button\";\nimport { cn } from \"../lib/utils\";\n\n// A screen that is a workspace of panes: a stage in the middle, side panels, a bottom panel, a bar\n// across the top (strata-react issue #68, from strata-vid; ux-research components.md §3.20). It is\n// for tools (editors, IDE-style screens, mail with a reading pane), where the person sizes the\n// screen to the job and the same screen stays on view together. `AppShell` is for moving between\n// screens; this is for one screen with many regions.\n//\n// Shape: `<Workspace label state>` holds `<Split direction>`s, which hold `<Pane>`s and other\n// `<Split>`s. A pane with `grow` takes what is left; any other pane has a size the person sets.\n// Between a fixed pane and its neighbour sits a separator that controls the fixed one.\n//\n// - Panes are regions. Each is a `section` named by its own header, so a screen-reader user can\n// move between them by landmark, and every pane in an app has the same header: its name, the\n// few `actions` it owns, and a collapse button. A pane is a region, never a card (patterns.md §2).\n// - The separator is the window-splitter pattern: `role=\"separator\"` with `aria-valuenow`, `-min`\n// and `-max`, in the tab order. Arrow keys move it by 10px (Shift: 50), Home and End go to the\n// limits, Enter or a double-click restores the default size. Pointer drag, touch and the arrow\n// keys are React Aria's `useMove`.\n// - Limits: a pane never goes under its `min` or over its `max`, and the window shrinking takes\n// from the panes only down to their `min` (flex shrink with `min-width`), while the central pane\n// keeps its own minimum, so the stage never disappears. A drag stops where the central pane would\n// fall under its minimum.\n// - Collapse. A collapsible pane folds to a rail one control wide (beside the stage) or to its\n// header bar (above or below it), with a visible \"Show Library\" button, so there is always a way\n// back. `state.toggle(id)` does it from outside (a View menu, a shortcut). A collapsed pane's\n// body stays mounted but hidden, so what is in it (a timeline's scroll, a form) is kept.\n// - Remembered: `useWorkspaceState(\"editor\")` keeps sizes and collapsed panes in localStorage, in\n// try/catch (storage throws in private windows and with blocked site data), so the app writes no\n// storage code and a failure falls back to the defaults.\n// - Narrow: below `narrowBelow` (720px of the workspace's own width) side-by-side splits stack, and\n// their collapsible panes start folded to their header bars, one tap to open. That is a rule of the\n// component so every app does the same thing; it is not remembered, since it is the width and not\n// a choice.\n// - Density comes from the tokens: header and rail sizes are `--control-h`.\n// Motion: none. Resizing and folding are done many times a session (character.md §3).\n//\n// Checked for React Aria first: react-aria-components 1.22 has no splitter or panel part (its\n// `Separator` is a static rule, and `useSeparator` is for a non-focusable one), and the table's column\n// resizing is its own. So the layout is ours, on `useMove` for the interaction.\n\ntype Persisted = { sizes: Record<string, number>; collapsed: Record<string, boolean> };\n\nconst readPersisted = (key: string | undefined): Persisted => {\n const empty: Persisted = { sizes: {}, collapsed: {} };\n if (!key) return empty;\n try {\n const raw = JSON.parse(window.localStorage.getItem(`strata:workspace:${key}`) ?? \"null\") as Partial<Persisted> | null;\n if (!raw || typeof raw !== \"object\") return empty;\n const sizes: Record<string, number> = {};\n for (const [k, v] of Object.entries(raw.sizes ?? {})) if (typeof v === \"number\" && Number.isFinite(v)) sizes[k] = v;\n const collapsed: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(raw.collapsed ?? {})) if (typeof v === \"boolean\") collapsed[k] = v;\n return { sizes, collapsed };\n } catch {\n return empty;\n }\n};\n\n/** What `useWorkspaceState` returns: pass it to `Workspace`, and use it from outside (a menu, a shortcut) to fold or reset panes. */\nexport type WorkspaceState = {\n /** Whether a pane is folded now. `fallback` is the pane's `defaultCollapsed`. */\n isCollapsed: (id: string, fallback?: boolean) => boolean;\n setCollapsed: (id: string, collapsed: boolean) => void;\n /** Folds an open pane, opens a folded one. */\n toggle: (id: string) => void;\n /** Forgets every size and fold, back to the defaults. */\n reset: () => void;\n /** @internal */\n sizeOf: (id: string) => number | undefined;\n /** @internal */\n setSize: (id: string, size: number | null) => void;\n /** @internal */\n register: (id: string, defaultCollapsed: boolean) => void;\n /** @internal */\n narrow: boolean;\n /** @internal */\n setNarrow: (narrow: boolean) => void;\n};\n\n/** The sizes and folded panes of a `Workspace`; with `persist`, remembered in localStorage under that name. */\nexport function useWorkspaceState(persist?: string): WorkspaceState {\n const [saved, setSaved] = React.useState<Persisted>(() => readPersisted(persist));\n const [narrow, setNarrow] = React.useState(false);\n const [narrowOpen, setNarrowOpen] = React.useState<Record<string, boolean>>({});\n // Each pane's `defaultCollapsed`, so a toggle from outside (a View menu) acts on what is on screen.\n const defaults = React.useRef(new Map<string, boolean>());\n\n React.useEffect(() => {\n if (!persist) return;\n try {\n window.localStorage.setItem(`strata:workspace:${persist}`, JSON.stringify(saved));\n } catch {\n // Storage is a convenience; a workspace that cannot remember still works.\n }\n }, [persist, saved]);\n\n return React.useMemo<WorkspaceState>(() => {\n const isCollapsed = (id: string, fallback = defaults.current.get(id) ?? false) => (narrow ? !narrowOpen[id] : (saved.collapsed[id] ?? fallback));\n const setCollapsed = (id: string, collapsed: boolean) => {\n if (narrow) setNarrowOpen((o) => ({ ...o, [id]: !collapsed }));\n else setSaved((s) => ({ ...s, collapsed: { ...s.collapsed, [id]: collapsed } }));\n };\n return {\n isCollapsed,\n setCollapsed,\n toggle: (id) => setCollapsed(id, !isCollapsed(id)),\n reset: () => setSaved({ sizes: {}, collapsed: {} }),\n sizeOf: (id) => saved.sizes[id],\n setSize: (id, size) =>\n setSaved((s) => {\n const sizes = { ...s.sizes };\n if (size === null) delete sizes[id];\n else sizes[id] = Math.round(size);\n return { ...s, sizes };\n }),\n register: (id, defaultCollapsed) => void defaults.current.set(id, defaultCollapsed),\n narrow,\n setNarrow,\n };\n }, [saved, narrow, narrowOpen]);\n}\n\nconst StateContext = React.createContext<WorkspaceState | null>(null);\nconst useState_ = () => {\n const state = React.useContext(StateContext);\n if (!state) throw new Error(\"strata-react: a Pane or Split must be inside a Workspace.\");\n return state;\n};\n\ntype Slot = { direction: \"row\" | \"column\"; edge: \"start\" | \"end\" | \"only\"; stacked: boolean };\nconst SlotContext = React.createContext<Slot>({ direction: \"row\", edge: \"only\", stacked: false });\n\n/** The workspace: a labelled region that holds the splits and panes, and stacks them when narrow. */\nexport function Workspace({\n label,\n state,\n narrowBelow = 720,\n className,\n children,\n}: {\n label: string;\n state: WorkspaceState;\n /** Stack side-by-side splits when the workspace is narrower than this many pixels. Default 720. */\n narrowBelow?: number;\n className?: string;\n children: React.ReactNode;\n}) {\n const ref = React.useRef<HTMLDivElement>(null);\n const { setNarrow } = state;\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n const measure = () => {\n const width = el.getBoundingClientRect().width;\n setNarrow(width > 0 && width < narrowBelow);\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(el);\n return () => observer.disconnect();\n }, [narrowBelow, setNarrow]);\n\n return (\n <StateContext.Provider value={state}>\n <div ref={ref} role=\"group\" aria-label={label} className={cn(\"flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background\", className)}>\n {children}\n </div>\n </StateContext.Provider>\n );\n}\n\n/** What a `Pane` is, for the split that lays it out. */\nexport type PaneProps = {\n /** Identifies the pane in the remembered state: unique in the workspace. */\n id: string;\n /** The pane's name, in its header and as its landmark: \"Library\", \"Inspector\". */\n name: string;\n /** Takes the space the fixed panes leave. One per split (a nested `Split` always does). */\n grow?: boolean;\n /** Starting size in pixels (width beside the stage, height above or below it). Default 280. */\n size?: number;\n /** Smallest size in pixels. Default 160; for a growing pane, the least it keeps (default 240 wide, 120 high). */\n min?: number;\n /** Largest size in pixels. Default none. */\n max?: number;\n /** Shows a collapse button in the header and lets the pane fold to a rail or its header. */\n collapsible?: boolean;\n /** Starts folded until the person opens it. */\n defaultCollapsed?: boolean;\n /** The pane's few actions, drawn in its header before the collapse button. */\n actions?: React.ReactNode;\n className?: string;\n children?: React.ReactNode;\n};\n\nconst iconsFor = (direction: \"row\" | \"column\", edge: Slot[\"edge\"], stacked: boolean) => {\n if (stacked || direction === \"column\") return edge === \"start\" ? [PanelTopClose, PanelTopOpen] : [PanelBottomClose, PanelBottomOpen];\n return edge === \"end\" ? [PanelRightClose, PanelRightOpen] : [PanelLeftClose, PanelLeftOpen];\n};\n\n/** A region of a workspace with a consistent header (name, actions, fold button) and a body that scrolls. */\nexport function Pane({ id, name, grow, size = 280, min, max, collapsible, defaultCollapsed, actions, className, children }: PaneProps) {\n const state = useState_();\n const { direction, edge, stacked } = React.useContext(SlotContext);\n const headingId = React.useId();\n const { register } = state;\n React.useLayoutEffect(() => register(id, Boolean(defaultCollapsed)), [register, id, defaultCollapsed]);\n const folded = Boolean(collapsible) && state.isCollapsed(id, Boolean(defaultCollapsed));\n const rail = folded && direction === \"row\" && !stacked;\n const least = min ?? (grow ? (direction === \"row\" ? 240 : 120) : 160);\n const current = state.sizeOf(id) ?? size;\n const [closeIcon, openIcon] = iconsFor(direction, edge, stacked);\n\n const style: React.CSSProperties = grow\n ? { flex: \"1 1 0%\", [direction === \"row\" ? \"minWidth\" : \"minHeight\"]: least }\n : folded\n ? { flex: \"0 0 auto\" }\n : stacked\n ? { flex: \"0 1 auto\", maxHeight: \"50%\" }\n : {\n flex: `0 1 ${Math.max(least, Math.min(current, max ?? Infinity))}px`,\n [direction === \"row\" ? \"minWidth\" : \"minHeight\"]: least,\n ...(max ? { [direction === \"row\" ? \"maxWidth\" : \"maxHeight\"]: max } : {}),\n };\n\n return (\n <section\n id={`pane-${id}`}\n aria-labelledby={headingId}\n data-pane={id}\n data-collapsed={folded || undefined}\n data-grow={grow || undefined}\n data-min={grow ? least : undefined}\n data-size={grow || folded ? undefined : current}\n style={style}\n className={cn(\"flex min-h-0 min-w-0 flex-col overflow-hidden bg-background\", rail && cn(\"w-(--control-h) items-center\", edge === \"end\" ? \"border-l border-border\" : \"border-r border-border\"), className)}\n >\n <header className={cn(\"flex shrink-0 items-center gap-1 pl-3 pr-1\", rail ? \"h-auto flex-col py-1 pl-1\" : \"h-(--control-h) border-b border-border\")}>\n <h2 id={headingId} className={cn(\"type-label min-w-0 flex-1 truncate\", rail && \"sr-only\")}>\n {name}\n </h2>\n {!folded && actions}\n {collapsible && (\n <IconButton\n size=\"sm\"\n icon={folded ? openIcon : closeIcon}\n label={folded ? `Show ${name}` : `Hide ${name}`}\n aria-expanded={!folded}\n aria-controls={`pane-body-${id}`}\n onPress={() => state.toggle(id)}\n />\n )}\n </header>\n <div id={`pane-body-${id}`} hidden={folded} className=\"min-h-0 min-w-0 flex-1 overflow-auto\">\n {children}\n </div>\n </section>\n );\n}\n\ntype PaneElement = React.ReactElement<PaneProps>;\nconst isPane = (c: React.ReactNode): c is PaneElement => React.isValidElement(c) && c.type === Pane;\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(n, lo), hi);\n\nfunction Separator({\n pane,\n direction,\n sign,\n container,\n}: {\n pane: PaneProps;\n direction: \"row\" | \"column\";\n /** +1 when the controlled pane is before the separator, -1 when after. */\n sign: 1 | -1;\n container: React.RefObject<HTMLDivElement | null>;\n}) {\n const state = useState_();\n const [moving, setMoving] = React.useState(false);\n const min = pane.min ?? 160;\n const start = pane.size ?? 280;\n const size = state.sizeOf(pane.id) ?? start;\n const latest = React.useRef(size);\n latest.current = size;\n\n // A window smaller than the layout squeezes a pane under its saved size (flex shrink). Resizing and\n // the value reported start from what is drawn, or the next step would jump. Only where the layout\n // has been measured (jsdom has none).\n const measure = () => {\n const kids = Array.from(container.current?.children ?? []) as HTMLElement[];\n const own = kids.find((el) => el.dataset.pane === pane.id);\n return own ? Math.round(own.getBoundingClientRect()[direction === \"row\" ? \"width\" : \"height\"]) : 0;\n };\n const current = () => {\n const drawn = measure();\n return drawn > 0 && drawn < latest.current ? drawn : latest.current;\n };\n const [drawn, setDrawn] = React.useState(0);\n // A passive effect: the split's ref is attached after its children's layout effects have run.\n React.useEffect(() => {\n const root = container.current;\n if (!root || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => setDrawn(measure()));\n observer.observe(root);\n setDrawn(measure());\n return () => observer.disconnect();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [size, direction]);\n const shown = drawn > 0 && drawn < size ? drawn : size;\n\n // How far the controlled pane can grow before the stage falls under its own minimum. Only when the\n // layout has been measured (jsdom has none), and never under `min`.\n const room = () => {\n const root = container.current;\n const kids = Array.from(root?.children ?? []) as HTMLElement[];\n const own = kids.find((el) => el.dataset.pane === pane.id);\n const stage = kids.find((el) => el.dataset.grow !== undefined || el.dataset.split !== undefined);\n if (!own || !stage) return Infinity;\n const dim = direction === \"row\" ? \"width\" : \"height\";\n const stageSize = stage.getBoundingClientRect()[dim];\n if (stageSize <= 0) return Infinity;\n const stageMin = Number(stage.dataset.min ?? 0);\n return own.getBoundingClientRect()[dim] + stageSize - stageMin;\n };\n const upper = () => Math.max(min, Math.min(pane.max ?? Infinity, room()));\n const apply = (next: number) => state.setSize(pane.id, clamp(next, min, upper()));\n\n const { moveProps } = useMove({\n onMoveStart: () => setMoving(true),\n onMove: ({ deltaX, deltaY, pointerType, shiftKey }) => {\n const delta = (direction === \"row\" ? deltaX : deltaY) * (pointerType === \"keyboard\" ? (shiftKey ? 50 : 10) : 1);\n if (!delta) return;\n const next = clamp(current() + sign * delta, min, upper());\n latest.current = next;\n apply(next);\n },\n onMoveEnd: () => setMoving(false),\n });\n\n const restore = () => state.setSize(pane.id, null);\n const keys = {\n onKeyDown: (e: React.KeyboardEvent) => {\n if (e.key === \"Home\") apply(min);\n else if (e.key === \"End\") apply(upper());\n else if (e.key === \"Enter\") restore();\n else return;\n e.preventDefault();\n },\n onDoubleClick: restore,\n };\n\n const vertical = direction === \"row\";\n return (\n <div\n role=\"separator\"\n tabIndex={0}\n aria-orientation={vertical ? \"vertical\" : \"horizontal\"}\n aria-label={`Resize ${pane.name}`}\n aria-controls={`pane-${pane.id}`}\n aria-valuenow={Math.round(shown)}\n aria-valuemin={min}\n aria-valuemax={Number.isFinite(pane.max ?? Infinity) ? pane.max : undefined}\n data-moving={moving || undefined}\n {...mergeProps(moveProps, keys)}\n className={cn(\n \"relative shrink-0 touch-none bg-border transition-state hover:bg-primary focus-visible:bg-primary data-[moving]:bg-primary\",\n vertical ? \"w-px cursor-col-resize before:absolute before:inset-y-0 before:-inset-x-1\" : \"h-px cursor-row-resize before:absolute before:inset-x-0 before:-inset-y-1\",\n \"pointer-coarse:before:-inset-x-2\",\n )}\n />\n );\n}\n\n/** Lays its children out in a row or a column, with a separator between a fixed pane and its neighbour. A nested split takes the space the fixed panes leave. */\nexport function Split({ direction, className, children }: { direction: \"row\" | \"column\"; className?: string; children: React.ReactNode }) {\n const state = useState_();\n const ref = React.useRef<HTMLDivElement>(null);\n const stacked = direction === \"row\" && state.narrow;\n const effective = stacked ? \"column\" : direction;\n const items = React.Children.toArray(children);\n const slotted = (c: React.ReactNode) => isPane(c) || (React.isValidElement(c) && c.type === Split);\n const grows = (c: React.ReactNode) => (isPane(c) ? Boolean(c.props.grow) : true);\n\n const out: React.ReactNode[] = [];\n items.forEach((child, i) => {\n const growIndex = items.findIndex((c) => slotted(c) && grows(c));\n const edge: Slot[\"edge\"] = growIndex < 0 ? \"only\" : i < growIndex ? \"start\" : i > growIndex ? \"end\" : \"only\";\n out.push(\n <SlotContext.Provider key={React.isValidElement(child) && child.key != null ? child.key : i} value={{ direction: effective, edge, stacked }}>\n {child}\n </SlotContext.Provider>,\n );\n const next = items[i + 1];\n if (next === undefined || !slotted(child) || !slotted(next)) return;\n const fixed = (c: React.ReactNode) => isPane(c) && !c.props.grow && !(c.props.collapsible && state.isCollapsed(c.props.id, c.props.defaultCollapsed));\n const before = fixed(child);\n const after = fixed(next);\n if (stacked || (!before && !after)) return;\n const controlled = (before ? child : next) as PaneElement;\n out.push(<Separator key={`sep-${i}`} pane={controlled.props} direction={effective} sign={before ? 1 : -1} container={ref} />);\n });\n\n const growPane = items.find((c): c is PaneElement => isPane(c) && Boolean(c.props.grow));\n return (\n <div\n ref={ref}\n data-split={direction}\n data-min={growPane ? (growPane.props.min ?? (direction === \"row\" ? 240 : 120)) : undefined}\n className={cn(\"flex min-h-0 min-w-0 flex-1\", effective === \"row\" ? \"flex-row\" : \"flex-col\", className)}\n >\n {out}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Redo2, Undo2 } from \"lucide-react\";\nimport type { Command } from \"./commands\";\n\n// Undo and redo across a whole editing session (components.md §3.17; strata-react issue #81, from\n// strata-vid). `useUndoable` is the other half: one removal, a few seconds to take it back, then\n// it commits to a server. Use that for a row or an item that leaves a list; use this for a\n// document the person keeps editing, where every change can be walked back for as long as the\n// session lasts. A removal inside a document is a step here, not an `UndoBar` message.\n//\n// The model is the smallest one that does not care what the app's store is: a step is a name and\n// two functions, `undo` and `redo`. An app on a patch store pushes patches, one on snapshots pushes\n// the old and new value (`useHistoryState` does exactly that for plain React state), one on a\n// command pattern pushes its commands. The history never reads or holds the document.\n//\n// - A step is named by the phrase that follows the verb: \"move clip\" gives \"Undo move clip\" and\n// \"Redo move clip\". A person can tell what Undo will do before pressing it (Photoshop and Figma\n// say it; a bare \"Undo\" does not).\n// - A continuous change is one step. `begin(label)` returns `end`: every step pushed in between\n// becomes one, so a drag undoes in one press. For a change that arrives as many events (a slider)\n// pass the same `key` on each push: consecutive pushes with one key, with no undo between them,\n// merge into one step.\n// - A new step after an undo drops what could have been redone (the usual rule); `limit` drops the\n// oldest steps, and `atLimit` says it is happening so the app can say so.\n// - `commands` is Undo and Redo as `Command`s, with their label, shortcut and disabled reason, so a\n// menu, a toolbar button and the key handler (`useCommands`) all read the same object. Chords are\n// Mod+Z, and Mod+Shift+Z or Mod+Y for Redo. They do not fire in a text field, which keeps its own\n// undo: this history is the document's.\n// Motion: none. Undo is used 100+ times a day, so nothing moves.\n//\n// Checked: React Aria has no history part and no hook for one (react-stately's `useUndo` does not\n// exist; its `useControlledState` is for controlled values only), so this is our own.\n\n/** One undoable step. `label` is the phrase after the verb (\"move clip\"); `undo` and `redo` must be inverses. */\nexport type HistoryStep = {\n label: string;\n undo: () => void;\n redo: () => void;\n /** Consecutive pushes with the same key merge into one step (a slider, a text drag). */\n key?: string;\n};\n\n/** Options for `useHistory`. */\nexport type HistoryOptions = {\n /** The most steps kept; the oldest is dropped past it. Default 100. */\n limit?: number;\n};\n\n/** What `useHistory` returns. */\nexport type History = {\n /** Records a step the app has just done. Clears what could have been redone. Inside `begin`/`end` it joins the group. */\n push: (step: HistoryStep) => void;\n /** Starts a group named `label`; every push until the returned `end()` is one step. Nested groups join the outer one. An empty group records nothing. */\n begin: (label: string) => () => void;\n /** `begin`, run a function, `end`. */\n group: <T>(label: string, run: () => T) => T;\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n /** The name of the step Undo would take back, or undefined. */\n undoLabel: string | undefined;\n /** The name of the step Redo would repeat, or undefined. */\n redoLabel: string | undefined;\n /** Names of the steps that can be undone, oldest first. */\n past: string[];\n /** Names of the steps that can be redone, next first. */\n future: string[];\n /** The history holds `limit` steps, so the next push drops the oldest. */\n atLimit: boolean;\n /** Forgets every step (a document was opened or saved to a new place). */\n clear: () => void;\n /** Undo then Redo as commands: \"Undo move clip\", disabled with \"Nothing to undo\". Pass to `useCommands` and a `Menu`. */\n commands: [undo: Command, redo: Command];\n};\n\nconst compose = (older: HistoryStep, newer: HistoryStep): HistoryStep => ({\n label: older.label,\n key: older.key,\n undo: () => {\n newer.undo();\n older.undo();\n },\n redo: () => {\n older.redo();\n newer.redo();\n },\n});\n\n/** A history of named, undoable steps with grouping, a limit, and Undo and Redo as commands. */\nexport function useHistory({ limit = 100 }: HistoryOptions = {}): History {\n const store = React.useRef({ past: [] as HistoryStep[], future: [] as HistoryStep[], open: [] as HistoryStep[][], merge: false });\n const [version, bump] = React.useReducer((n: number) => n + 1, 0);\n const max = Math.max(1, limit);\n\n const api = React.useMemo(() => {\n const s = store.current;\n const record = (step: HistoryStep) => {\n const last = s.past[s.past.length - 1];\n if (s.merge && step.key && last && last.key === step.key) s.past[s.past.length - 1] = compose(last, step);\n else {\n s.past.push(step);\n if (s.past.length > max) s.past.splice(0, s.past.length - max);\n }\n s.future = [];\n s.merge = Boolean(step.key);\n bump();\n };\n const push = (step: HistoryStep) => {\n const group = s.open[s.open.length - 1];\n if (group) group.push(step);\n else record(step);\n };\n const begin = (label: string) => {\n const steps: HistoryStep[] = [];\n s.open.push(steps);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n s.open.pop();\n if (!steps.length) return;\n const grouped: HistoryStep = {\n label,\n undo: () => [...steps].reverse().forEach((x) => x.undo()),\n redo: () => steps.forEach((x) => x.redo()),\n };\n push(grouped);\n };\n };\n return {\n push,\n begin,\n group: <T,>(label: string, run: () => T): T => {\n const end = begin(label);\n try {\n return run();\n } finally {\n end();\n }\n },\n undo: () => {\n if (s.open.length) return;\n const step = s.past.pop();\n if (!step) return;\n step.undo();\n s.future.unshift(step);\n s.merge = false;\n bump();\n },\n redo: () => {\n if (s.open.length) return;\n const step = s.future.shift();\n if (!step) return;\n step.redo();\n s.past.push(step);\n s.merge = false;\n bump();\n },\n clear: () => {\n s.past = [];\n s.future = [];\n s.merge = false;\n bump();\n },\n };\n }, [max]);\n\n return React.useMemo(() => {\n const { past, future } = store.current;\n const undoLabel = past[past.length - 1]?.label;\n const redoLabel = future[0]?.label;\n const commands: [Command, Command] = [\n {\n id: \"history.undo\",\n label: undoLabel ? `Undo ${undoLabel}` : \"Undo\",\n icon: Undo2,\n keys: [\"Mod+Z\"],\n disabled: undoLabel ? false : \"Nothing to undo\",\n run: api.undo,\n },\n {\n id: \"history.redo\",\n label: redoLabel ? `Redo ${redoLabel}` : \"Redo\",\n icon: Redo2,\n keys: [\"Mod+Shift+Z\", \"Mod+Y\"],\n disabled: redoLabel ? false : \"Nothing to redo\",\n run: api.redo,\n },\n ];\n return {\n ...api,\n canUndo: past.length > 0,\n canRedo: future.length > 0,\n undoLabel,\n redoLabel,\n past: past.map((x) => x.label),\n future: future.map((x) => x.label),\n atLimit: past.length >= max,\n commands,\n };\n // `version` is the change signal: the stacks live in a ref so a step can be pushed from an event handler or a store subscription.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [api, version, max]);\n}\n\n/** Options for `useHistoryState`. */\nexport type HistoryStateOptions = HistoryOptions;\n\n/** What `setValue` takes besides the new value. */\nexport type SetOptions = {\n /** Merges consecutive changes with this key into one step (a slider, a drag). */\n key?: string;\n};\n\n/**\n * React state with a history: `set(next, \"move clip\")` changes the value and records the step; Undo\n * and Redo put the old and new values back. For an app whose document is a plain value. An app on its\n * own store uses `useHistory` and pushes steps from its actions.\n */\nexport function useHistoryState<S>(initial: S | (() => S), options?: HistoryStateOptions) {\n const [value, setValue] = React.useState(initial);\n const latest = React.useRef(value);\n const history = useHistory(options);\n const { push } = history;\n\n const write = React.useCallback((next: S) => {\n latest.current = next;\n setValue(next);\n }, []);\n\n const set = React.useCallback(\n (next: S | ((previous: S) => S), label: string, { key }: SetOptions = {}) => {\n const before = latest.current;\n const after = typeof next === \"function\" ? (next as (previous: S) => S)(before) : next;\n if (Object.is(before, after)) return;\n write(after);\n push({ label, key, undo: () => write(before), redo: () => write(after) });\n },\n [push, write],\n );\n\n /** Replaces the value without a step and forgets the history (a document was opened). */\n const reset = React.useCallback(\n (next: S) => {\n write(next);\n history.clear();\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [write, history.clear],\n );\n\n return { value, set, reset, history };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\n\n// Whether a document's work is safe (components.md §3.17; strata-react issue #81, from strata-vid,\n// whose project saved itself with no sign on screen that it had, or had not).\n//\n// `useAutoSave` is the state machine and `SaveStatus` the sign. The states are the four a person\n// asks about: saved (and when), saving, unsaved changes, and not saved (and why, with a retry).\n// - The same verb through every state (\"Saving…\", \"Saved\", \"Not saved\", \"Try again\"), in place,\n// with the labels stacked in one grid cell so the sign is as wide as its longest and nothing\n// beside it moves (the `AsyncButton` technique). The `failed` reason is cut to that width and\n// shown whole in the announcement and as a tooltip title.\n// - A routine save is quiet: no toast, no tick animation, no announcement. A failed save is the bad\n// day, so it is announced politely, once per failure, saying what happened and what is still\n// safe (\"Not saved: the connection dropped. Your changes are still here.\"). The recovery after\n// it is announced too, so a person who heard the failure hears that it is over.\n// - The time is a clock time (`format.clock`), which does not go stale on screen the way \"2 minutes\n// ago\" does; nothing here ticks.\n// - Saves are debounced (`delayMs`, default 1500) and never overlap: edits made while a save runs\n// are saved after it, so the last write is always the latest value. `delayMs: null` is a document\n// with an explicit Save command: the state is `dirty` until `saveNow()`.\n// - A document that saves itself needs no `beforeunload` prompt except while a save is pending or\n// failed; `useLeaveGuard(state.status !== \"saved\")` is that, on only while there is something to\n// lose (patterns.md §6). A router blocker is the app's: it needs a data router.\n// Motion: none; the spinner turns only under `motion-safe`.\n//\n// Checked: React Aria has no save indicator or autosave part; its `ProgressBar` and live regions\n// are what a sign like this would sit on, and a plain status text is the right element.\n\n/** The state of a document's saving. */\nexport type SaveState =\n | { status: \"saved\"; /** When it last saved here; null for a document just opened. */ at: Date | null }\n | { status: \"dirty\" }\n | { status: \"saving\" }\n | { status: \"failed\"; /** What happened, in the product's words. */ reason?: string };\n\n/** Options for `useAutoSave`. */\nexport type AutoSaveOptions<V> = {\n /** The document's current value. Compared with what was last saved by `equals`. */\n value: V;\n /** Saves a value. Throw (or reject) to fail. */\n save: (value: V) => void | Promise<unknown>;\n /** Wait this long after the last change before saving. `null`: never on its own, only `saveNow()`. Default 1500. */\n delayMs?: number | null;\n /** Whether two values are the same document. Default `Object.is`. */\n equals?: (a: V, b: V) => boolean;\n /** Turns a thrown error into the sentence shown. Default `describeActionError`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useAutoSave` returns. */\nexport type AutoSave = {\n state: SaveState;\n /** Saves now (and is \"Try again\" after a failure). Resolves when the save has finished, failed or not. */\n saveNow: () => Promise<void>;\n};\n\n/** Saves `value` after changes settle, never two at once, and says where it stands. The document's first `value` counts as saved. */\nexport function useAutoSave<V>({ value, save, delayMs = 1500, equals = Object.is, describeError = describeActionError }: AutoSaveOptions<V>): AutoSave {\n const [state, setState] = React.useState<SaveState>({ status: \"saved\", at: null });\n const latest = React.useRef({ value, save, equals, describeError, delayMs });\n latest.current = { value, save, equals, describeError, delayMs };\n const saved = React.useRef(value);\n const savedAt = React.useRef<Date | null>(null);\n const running = React.useRef<Promise<void> | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n window.clearTimeout(timer.current);\n };\n }, []);\n\n const schedule = React.useCallback(() => {\n window.clearTimeout(timer.current);\n if (latest.current.delayMs === null) return;\n timer.current = window.setTimeout(() => void run(), latest.current.delayMs);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const run = React.useCallback((): Promise<void> => {\n window.clearTimeout(timer.current);\n if (running.current) return running.current;\n const current = latest.current.value;\n if (latest.current.equals(current, saved.current)) {\n setState((s) => (s.status === \"saved\" ? s : { status: \"saved\", at: new Date() }));\n return Promise.resolve();\n }\n setState({ status: \"saving\" });\n // `settled` covers a saver that throws before its first await: the catch and finally then run\n // inside this call, before `attempt` exists, and the lock must not be taken after that.\n let settled = false;\n const attempt = (async () => {\n try {\n await latest.current.save(current);\n saved.current = current;\n savedAt.current = new Date();\n if (!mounted.current) return;\n if (latest.current.equals(latest.current.value, current)) setState({ status: \"saved\", at: savedAt.current });\n else {\n setState({ status: \"dirty\" });\n schedule();\n }\n } catch (error) {\n if (mounted.current) setState({ status: \"failed\", reason: latest.current.describeError(error) });\n } finally {\n settled = true;\n running.current = null;\n }\n })();\n if (!settled) running.current = attempt;\n return attempt;\n }, [schedule]);\n\n // A change: unsaved until it is saved. A failed state stays failed (the person has not been\n // told it is fine), and a save already running picks the change up when it ends.\n React.useEffect(() => {\n if (latest.current.equals(value, saved.current)) {\n // Edited back to what is saved: nothing to lose, so the sign says so (and the leave guard goes off).\n if (!running.current) {\n window.clearTimeout(timer.current);\n setState((s) => (s.status === \"dirty\" || s.status === \"failed\" ? { status: \"saved\", at: savedAt.current } : s));\n }\n return;\n }\n if (!running.current) setState((s) => (s.status === \"failed\" ? s : { status: \"dirty\" }));\n if (!running.current) schedule();\n }, [value, schedule]);\n\n return { state, saveNow: run };\n}\n\n/** Asks the browser to confirm before the page is closed or reloaded, while `active`. Off when there is nothing to lose. */\nexport function useLeaveGuard(active: boolean) {\n React.useEffect(() => {\n if (!active) return;\n const onBeforeUnload = (e: BeforeUnloadEvent) => {\n e.preventDefault();\n e.returnValue = \"\";\n };\n window.addEventListener(\"beforeunload\", onBeforeUnload);\n return () => window.removeEventListener(\"beforeunload\", onBeforeUnload);\n }, [active]);\n}\n\nconst labelOf = (s: SaveState) =>\n s.status === \"saved\" ? (s.at ? `Saved ${format.clock(s.at)}` : \"Saved\") : s.status === \"saving\" ? \"Saving…\" : s.status === \"dirty\" ? \"Unsaved changes\" : \"Not saved\";\n\n/**\n * The sign of whether the work is safe: \"Saved 10:42\", \"Saving…\", \"Unsaved changes\", or \"Not saved\"\n * with the reason and \"Try again\". Fixed width, so it never moves what is beside it. Announces a\n * failure, and the recovery from one, politely; a routine save is silent.\n */\nexport function SaveStatus({ state, onRetry, className }: { state: SaveState; onRetry: () => void; className?: string }) {\n const lastFailure = React.useRef(false);\n const failed = state.status === \"failed\";\n let announcement = \"\";\n if (failed) announcement = `Not saved${state.reason ? `: ${state.reason}` : \".\"} Your changes are still here.`;\n else if (lastFailure.current && state.status === \"saved\") announcement = \"Saved.\";\n React.useEffect(() => {\n if (failed) lastFailure.current = true;\n else if (state.status === \"saved\") lastFailure.current = false;\n }, [failed, state.status]);\n\n const Icon = { saved: Check, saving: LoaderCircle, dirty: null, failed: CircleAlert }[state.status];\n const current = labelOf(state);\n const all = [\"Saved 00:00\", \"Saving…\", \"Unsaved changes\", \"Not saved\"];\n const shown = failed && state.reason ? `Not saved: ${state.reason}` : current;\n\n return (\n <span\n data-status={state.status}\n title={failed ? shown : undefined}\n className={cn(\n \"inline-flex w-72 items-center justify-end gap-2 type-body-sm\",\n failed ? \"text-danger\" : \"text-muted-foreground\",\n className,\n )}\n >\n {Icon && <Icon aria-hidden className={cn(\"size-4 shrink-0\", state.status === \"saving\" && \"motion-safe:animate-spin\")} />}\n {failed ? (\n <span className=\"min-w-0 truncate\">{shown}</span>\n ) : (\n <span className=\"grid\">\n {all.map((l) => {\n const active = l === current || (l === \"Saved 00:00\" && state.status === \"saved\");\n return (\n <span key={l} aria-hidden={!active} className={active ? \"[grid-area:1/1] text-end tabular-nums\" : \"invisible [grid-area:1/1] text-end\"}>\n {active ? current : l}\n </span>\n );\n })}\n </span>\n )}\n {failed && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onRetry} className=\"shrink-0\">\n Try again\n </Button>\n )}\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </span>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,UAAU,EAAE,SAAS,MAAM,aAAa,OAAO,OAAO,OAAO,cAAc,UAAyB,CAAC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AA;GAEV,oBAAC,QAAD;IAAM,MAAK;IAAS,WAAU;IAC3B,UAAA;GACG,CAAA;EACF;;AAEV"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_Fragment","AriaPopover","AriaMenu","AriaDialog","AriaInput","AriaToolbar","sizes","_Fragment","AriaToggleButton","AriaSwitch","AriaDialog","_Fragment","AriaPopover","Dialog","AriaCheckbox","_Fragment","_Fragment","idle","tones","_Fragment","_Fragment","AriaNumberField","AriaInput","AriaSlider","_Fragment","_Fragment","defaultFormat","format","Table","AriaTable","AriaColumn","AriaRow","AriaCell","AriaButton","clamp","clamp","clamp","_Fragment","AriaButton","_Fragment","Disclosure","_Fragment","AriaButton","AriaCheckbox","useWidth","_Fragment","_Fragment","AriaTabs","_Fragment","AriaDialog","_Fragment","MODE_LABEL","_Fragment","AriaSlider","_Fragment","db","AriaSlider","_Fragment","Separator","labelOf"],"sources":["../src/lib/in-view.ts","../src/lib/chords.ts","../src/components/hotkeys.tsx","../src/components/commands.tsx","../src/components/toolbar.tsx","../src/components/toggle.tsx","../src/components/switch.tsx","../src/components/dialog.tsx","../src/components/popover.tsx","../src/components/checkbox.tsx","../src/components/async-button.tsx","../src/components/status.tsx","../src/components/metric.tsx","../src/components/meter.tsx","../src/components/composition.tsx","../src/components/link-card.tsx","../src/components/data-view.tsx","../src/lib/number-input.ts","../src/components/value-controls.tsx","../src/components/alert.tsx","../src/lib/client-work.ts","../src/components/job-status.tsx","../src/components/thumbnail.tsx","../src/components/selection.tsx","../src/components/disclosure.tsx","../src/components/data-table.tsx","../src/components/media.tsx","../src/components/media-player.tsx","../src/lib/timeline.ts","../src/components/timeline.tsx","../src/components/sortable-list.tsx","../src/components/file-intake.tsx","../src/lib/file-intake.ts","../src/components/inspector.tsx","../src/components/selectable-grid.tsx","../src/components/virtual-list.tsx","../src/components/infinite-list.tsx","../src/components/line-chart.tsx","../src/components/page-header.tsx","../src/components/undo.tsx","../src/components/done.tsx","../src/components/app-shell.tsx","../src/components/tabs.tsx","../src/components/active-list.tsx","../src/query/infinite.ts","../src/query/job.ts","../src/components/fullscreen-frame.tsx","../src/lib/viewport.ts","../src/components/compare-parts.tsx","../src/lib/image-diff.ts","../src/components/difference.tsx","../src/components/viewport.tsx","../src/components/compare-regions.tsx","../src/components/compare.tsx","../src/components/pair-vote.tsx","../src/lib/loudness.ts","../src/components/compare-audio.tsx","../src/components/compare-video.tsx","../src/lib/text-diff.ts","../src/components/compare-text.tsx","../src/components/compare-grid.tsx","../src/components/workspace.tsx","../src/components/history.tsx","../src/components/save.tsx"],"sourcesContent":["import * as React from \"react\";\n\n// One IntersectionObserver hook for everything that waits until it is near the screen: the\n// sentinel at the end of an InfiniteList and an image in a Thumbnail. Both watch from the nearest\n// `[data-strata-scroll]` region (a VirtualList's) or else the viewport, with a root\n// margin so the work starts before the element is reached. They differ in two ways, which are\n// options rather than two hooks:\n//\n// - `once`: an image, once asked for, stays asked for; scrolling it away again must not unload it.\n// A sentinel reports in and out of view every time.\n// - `unsupported`: where there is no IntersectionObserver (an old browser, a test without the\n// fake), an image loads at once, because a photo that never loads is worse than one loaded\n// early. A sentinel reports out of view, because InfiniteList's Show more button is the path\n// that always works.\n\n/** Options for {@link useInView}. */\nexport type InViewOptions = {\n /** Watch only while this is true. Default true. */\n active?: boolean;\n /** How far outside the scroll region still counts as in view (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Stay in view after the first time, and stop watching. */\n once?: boolean;\n /** What to report where `IntersectionObserver` does not exist. Default false. */\n unsupported?: boolean;\n};\n\n/**\n * Whether an element is within `rootMargin` of its scroll region (the nearest\n * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the\n * element as it mounts and unmounts.\n */\nexport function useInView({ active = true, rootMargin = \"0px\", once = false, unsupported = false }: InViewOptions = {}) {\n const [inView, setInView] = React.useState(false);\n const [el, setEl] = React.useState<Element | null>(null);\n const seen = once && inView;\n React.useEffect(() => {\n if (seen) return;\n if (!active || !el) {\n setInView(false);\n return;\n }\n if (typeof IntersectionObserver === \"undefined\") {\n setInView(unsupported);\n return;\n }\n const root = el.parentElement?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? null;\n const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), { root, rootMargin });\n observer.observe(el);\n return () => observer.disconnect();\n }, [active, el, rootMargin, seen, unsupported]);\n return { ref: setEl, inView };\n}\n","// Chords: a shortcut written once (\"Mod+Shift+Z\") and shown per platform (⌘⇧Z on macOS, Ctrl+Shift+Z\n// elsewhere). `Mod` is the platform's command key: Meta on macOS, Ctrl everywhere else. The other\n// modifiers are Ctrl, Meta, Alt and Shift. The key is a `KeyboardEvent.key` value, compared without\n// case (\"z\" and \"Z\" are the same key; Shift is part of the chord when written).\n//\n// Matching is exact on the modifiers: \"Mod+Z\" is not \"Mod+Shift+Z\", so Undo and Redo cannot both\n// fire. Shift is ignored for a symbol key (\"?\" is typed with Shift on most layouts), and Alt is\n// matched on the physical key for letters, since Alt+Z types \"Ω\" on a Mac.\n\n/** `\"mac\"` or `\"other\"`: which modifier glyphs to draw and what `Mod` means. */\nexport type Platform = \"mac\" | \"other\";\n\n/** The platform this page runs on, read from the browser (`mac` for macOS and iOS). Server and test default: `other`. */\nexport function detectPlatform(): Platform {\n if (typeof navigator === \"undefined\") return \"other\";\n const nav = navigator as Navigator & { userAgentData?: { platform?: string } };\n const text = nav.userAgentData?.platform ?? nav.platform ?? \"\";\n return /mac|iphone|ipad|ipod/i.test(text) ? \"mac\" : \"other\";\n}\n\ntype Parsed = { ctrl: boolean; meta: boolean; alt: boolean; shift: boolean; key: string };\n\n/** Splits \"Mod+Shift+Z\" into modifiers and key for a platform. A bare \"+\" key is written \"Mod++\". */\nexport function parseChord(chord: string, platform: Platform = detectPlatform()): Parsed {\n const parts = chord.endsWith(\"++\") ? [...chord.slice(0, -2).split(\"+\").filter(Boolean), \"+\"] : chord.split(\"+\");\n const key = parts.pop() ?? \"\";\n const mods = new Set(parts.map((p) => p.toLowerCase()));\n const mod = mods.has(\"mod\");\n return {\n ctrl: mods.has(\"ctrl\") || (mod && platform !== \"mac\"),\n meta: mods.has(\"meta\") || (mod && platform === \"mac\"),\n alt: mods.has(\"alt\"),\n shift: mods.has(\"shift\"),\n key,\n };\n}\n\nconst symbol = (key: string) => key.length === 1 && key.toUpperCase() === key.toLowerCase();\n\n/** Whether a key event is this chord. Exact on Ctrl, Meta and Alt; Shift is exact for letters and named keys. */\nexport function matchesChord(e: Pick<KeyboardEvent, \"key\" | \"code\" | \"ctrlKey\" | \"metaKey\" | \"altKey\" | \"shiftKey\">, chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n if (e.ctrlKey !== c.ctrl || e.metaKey !== c.meta || e.altKey !== c.alt) return false;\n if (!symbol(c.key) && e.shiftKey !== c.shift) return false;\n if (symbol(c.key) && c.shift && !e.shiftKey) return false;\n if (e.key.toLowerCase() === c.key.toLowerCase()) return true;\n return c.alt && /^[a-z]$/i.test(c.key) && e.code === `Key${c.key.toUpperCase()}`;\n}\n\nconst NAMES: Record<string, { mac: string; other: string }> = {\n ArrowUp: { mac: \"↑\", other: \"↑\" },\n ArrowDown: { mac: \"↓\", other: \"↓\" },\n ArrowLeft: { mac: \"←\", other: \"←\" },\n ArrowRight: { mac: \"→\", other: \"→\" },\n Escape: { mac: \"⎋\", other: \"Esc\" },\n Enter: { mac: \"↩\", other: \"Enter\" },\n Backspace: { mac: \"⌫\", other: \"Backspace\" },\n Delete: { mac: \"⌦\", other: \"Delete\" },\n \" \": { mac: \"Space\", other: \"Space\" },\n Tab: { mac: \"⇥\", other: \"Tab\" },\n Home: { mac: \"↖\", other: \"Home\" },\n End: { mac: \"↘\", other: \"End\" },\n};\n\n/** A chord as a person reads it on this platform: \"⌘⇧Z\" on macOS, \"Ctrl+Shift+Z\" elsewhere. */\nexport function formatChord(chord: string, platform: Platform = detectPlatform()): string {\n const c = parseChord(chord, platform);\n const key = NAMES[c.key]?.[platform] ?? (c.key.length === 1 ? c.key.toUpperCase() : c.key);\n if (platform === \"mac\") return `${c.ctrl ? \"⌃\" : \"\"}${c.alt ? \"⌥\" : \"\"}${c.shift ? \"⇧\" : \"\"}${c.meta ? \"⌘\" : \"\"}${key}`;\n return [c.ctrl && \"Ctrl\", c.meta && \"Meta\", c.alt && \"Alt\", c.shift && \"Shift\", key].filter(Boolean).join(\"+\");\n}\n\n// Chords the browser or the OS uses for itself. An app takes one over only on purpose (`claim` on\n// the command): silently stealing Ctrl+S from a person who wanted the browser's own is a choice.\nconst RESERVED = [\n \"Mod+S\", \"Mod+P\", \"Mod+F\", \"Mod+G\", \"Mod+O\", \"Mod+N\", \"Mod+T\", \"Mod+W\", \"Mod+R\", \"Mod+L\", \"Mod+D\", \"Mod+Q\", \"Mod+H\",\n \"Mod+J\", \"Mod+U\", \"Mod+Shift+T\", \"Mod+Shift+N\", \"Mod+Shift+W\", \"Alt+ArrowLeft\", \"Alt+ArrowRight\", \"F5\", \"F11\", \"F12\",\n];\n\n/** Whether the browser uses this chord for itself, so a command may take it only with `claim`. */\nexport function isReservedChord(chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n return RESERVED.some((r) => {\n const p = parseChord(r, platform);\n return p.ctrl === c.ctrl && p.meta === c.meta && p.alt === c.alt && p.shift === c.shift && p.key.toLowerCase() === c.key.toLowerCase();\n });\n}\n","import { KeyText } from \"./key-glyphs\";\nimport * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Single-key shortcuts for Operate screens that clear a queue (accept, reject, next). A person\n// doing the same answer a hundred times a day wants one key, no pointer and no motion\n// (ux-research `ux-character.md`: 100+ a day gets nothing but an instant change). Three rules\n// keep single keys from hurting anyone:\n// 1. They never fire while the person is typing: not in an input, textarea, select or\n// contenteditable (WCAG 2.1.4 Character Key Shortcuts), and not mid-composition (IME).\n// 2. They never take a chord: with Ctrl, Meta or Alt held the browser and the OS keep the key.\n// Shift is part of the key itself, so \"?\" works and \"A\" is not \"a\".\n// 3. Holding a key does not repeat an answer; only shortcuts marked `repeat` (moving) repeat.\n// The same list drives the handler and the legend, so a shortcut cannot exist without being\n// shown, and the legend cannot advertise a key that does nothing.\n\n/** One shortcut: the keys that run it (as `KeyboardEvent.key`), what it does in the product's words, and the action. */\nexport type Shortcut = {\n /** `KeyboardEvent.key` values, e.g. `[\"j\", \"ArrowDown\"]`. The first is the one the legend leads with. */\n keys: string[];\n /** What it does, in the product's words: \"Accept booking\", not \"Action 1\". */\n label: string;\n run: () => void;\n /** Fire again while the key is held. On for moving through a list, off (the default) for answers. */\n repeat?: boolean;\n /** Ignore the key for now, and show it muted in the legend (nothing is active, say). */\n disabled?: boolean;\n};\n\nconst TEXT_INPUTS_EXEMPT = new Set([\"checkbox\", \"radio\", \"button\", \"submit\", \"reset\", \"range\", \"color\", \"file\"]);\n\n/** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */\nexport function isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n if (target.isContentEditable || target.closest(\"[contenteditable=''],[contenteditable='true']\")) return true;\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;\n if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);\n return false;\n}\n\nfunction toShortcuts(input: Shortcut[] | Record<string, () => void>): Shortcut[] {\n return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({ keys: [key], label: key, run }));\n}\n\n/**\n * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta\n * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.\n */\nexport function useHotkeys(shortcuts: Shortcut[] | Record<string, () => void>, { enabled = true }: { enabled?: boolean } = {}) {\n // The listener is bound once; it reads the latest list, so handlers can close over fresh state.\n const latest = React.useRef<Shortcut[]>([]);\n latest.current = toShortcuts(shortcuts);\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;\n if (isTypingTarget(e.target)) return;\n const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));\n if (!hit || (e.repeat && !hit.repeat)) return;\n e.preventDefault();\n hit.run();\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled]);\n}\n\nconst KEY_NAMES: Record<string, string> = {\n ArrowDown: \"↓\",\n ArrowUp: \"↑\",\n ArrowLeft: \"←\",\n ArrowRight: \"→\",\n Escape: \"Esc\",\n Enter: \"Enter\",\n Backspace: \"Backspace\",\n Delete: \"Delete\",\n \" \": \"Space\",\n};\n\n// The legend is quiet, caption-sized and muted: it is there to be found, not read every time.\n// It hides on coarse pointers (phones, tablets without a keyboard), where the keys do not exist.\n// Each key is a <kbd>; alternatives are read as \"j or down arrow\".\n/** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */\nexport function KeysLegend({\n shortcuts,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n shortcuts: Pick<Shortcut, \"keys\" | \"label\" | \"disabled\">[];\n /** Names the legend for screen readers. */\n label?: string;\n className?: string;\n}) {\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shortcuts.map((s) => (\n <div key={s.keys.join(\" \")} className={cn(\"flex items-center gap-1.5\", s.disabled && \"opacity-50\")}>\n <dt className=\"flex items-center gap-1\">\n {s.keys.map((k, i) => (\n <React.Fragment key={k}>\n {i > 0 && <span className=\"sr-only\"> or </span>}\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n <KeyText>{KEY_NAMES[k] ?? k}</KeyText>\n </kbd>\n </React.Fragment>\n ))}\n </dt>\n <dd>{s.label}</dd>\n </div>\n ))}\n </dl>\n );\n}\n","import { KeyText } from \"./key-glyphs\";\nimport * as React from \"react\";\nimport {\n Autocomplete,\n Dialog as AriaDialog,\n Header,\n Heading,\n Keyboard,\n Menu as AriaMenu,\n MenuItem,\n MenuSection,\n MenuTrigger,\n Modal,\n ModalOverlay,\n Popover as AriaPopover,\n SearchField,\n Input as AriaInput,\n Separator,\n SubmenuTrigger,\n Text,\n useFilter,\n} from \"react-aria-components\";\nimport { Check, ChevronRight, Search, Trash2 } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { formatChord, detectPlatform, isReservedChord, matchesChord, type Platform } from \"../lib/chords\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// One command, declared once, used everywhere a person can reach it: a dropdown or menu-bar menu,\n// a context menu, the command menu, the key handler and the legend. Each of those reads the same\n// object, so the label, the enabled state and the shortcut text cannot disagree (components.md\n// §3.16 and §3.11; strata-react issue #71). This is the single-key `Shortcut` idea of `useHotkeys`\n// carried to menus and chords: `useHotkeys` is unchanged for a queue worked with single keys.\n//\n// - A label is a string or a function, so Undo can say \"Undo move clip\" and follow the history.\n// - `keys` are chords written once (\"Mod+Z\"), shown per platform (⌘Z or Ctrl+Z). They never fire\n// while the person is typing (a field's own Ctrl+Z is the field's) unless the command says\n// `inFields`, never during IME composition, and a chord the browser uses (Ctrl+S, Ctrl+P, ...)\n// is taken only with `claim: true`, an explicit choice.\n// - `disabled` is `true` or a sentence saying why (\"Nothing to undo\"); a disabled command's chord\n// does nothing, and every menu shows the item as unavailable, with the reason.\n// - Menus use React Aria's menu: roles, arrows, Home and End, typeahead, Escape back to the\n// trigger, submenus. A destructive item carries an icon as well as its colour, since colour\n// alone is not a signal (components.md §3.4). A group whose commands all have `checked` is a\n// group of checkable items.\n// Motion: shortcuts and the command menu are used 100+ times a day, so they appear at once.\n\n/** A command: what it is called, how it is run, and everything the menus need to draw it. */\nexport type Command = {\n /** Stable key for the command. */\n id: string;\n /** The verb phrase, sentence case, in the product's words (\"Split clip\"); a function when it follows state (\"Undo move clip\"). */\n label: string | (() => string);\n run: () => void;\n /** Chords that run it, written once (\"Mod+Z\", \"Delete\", \"Shift+?\"); the first is the one shown. */\n keys?: string[];\n /** Cannot run now. A sentence says why (\"Nothing to undo\") and is shown in menus. */\n disabled?: boolean | string;\n /** Cannot be undone or removes something: drawn with an icon and the danger colour. */\n destructive?: boolean;\n /** Makes a menu item checkable: whether it is on now. `run` toggles it. */\n checked?: boolean;\n icon?: IconComponent;\n /** Fire again while the key is held (for moving). Default false. */\n repeat?: boolean;\n /** Run from inside a text field too. Default false: a field keeps its own keys. */\n inFields?: boolean;\n /** Take over a chord the browser uses (Ctrl+S, Ctrl+P). Required for those; otherwise the command is not bound. */\n claim?: boolean;\n};\n\n/** What goes in a menu: a command, a separator, a titled group, or a submenu. */\nexport type MenuEntry = Command | \"separator\" | { group: string; items: Command[] } | { submenu: string; items: MenuEntry[] };\n\n/** The text of a command's label, whether it is a string or a function. */\nexport const labelOf = (c: Command) => (typeof c.label === \"function\" ? c.label() : c.label);\nconst isDisabled = (c: Command) => Boolean(c.disabled);\nconst reasonOf = (c: Command) => (typeof c.disabled === \"string\" ? c.disabled : undefined);\nconst isCommand = (e: MenuEntry): e is Command => typeof e === \"object\" && \"run\" in e;\n\n/** Options for `useCommands`. */\nexport type CommandsOptions = {\n enabled?: boolean;\n /** Which platform's `Mod` to use; read from the browser when left out. */\n platform?: Platform;\n};\n\n/**\n * Binds every command's chords on the window. Never while typing (unless the command says\n * `inFields`), never during IME composition, not on a held key (unless `repeat`), not for a disabled\n * command, and not for a chord the browser uses unless the command `claim`s it. A command's chord\n * that clashes with another's is a mistake: the first in the list wins, and a dev warning names both.\n */\nexport function useCommands(commands: readonly Command[], { enabled = true, platform }: CommandsOptions = {}) {\n const latest = React.useRef<readonly Command[]>([]);\n latest.current = commands;\n const where = platform ?? detectPlatform();\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing) return;\n for (const c of latest.current) {\n const chord = c.keys?.find((k) => matchesChord(e, k, where));\n if (!chord) continue;\n if (isReservedChord(chord, where) && !c.claim) continue;\n if (isTypingTarget(e.target) && !c.inFields) continue;\n if (isDisabled(c) || (e.repeat && !c.repeat)) return;\n e.preventDefault();\n c.run();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled, where]);\n\n if (import.meta.env?.DEV) warnOnClashes(commands, where);\n}\n\nfunction warnOnClashes(commands: readonly Command[], platform: Platform) {\n const seen = new Map<string, string>();\n for (const c of commands) {\n for (const k of c.keys ?? []) {\n const shown = formatChord(k, platform);\n const other = seen.get(shown);\n if (other && other !== c.id) console.warn(`strata-react: \"${shown}\" is bound to both \"${other}\" and \"${c.id}\"; the first wins.`);\n else seen.set(shown, c.id);\n }\n if (c.keys?.some((k) => isReservedChord(k, platform)) && !c.claim) {\n console.warn(`strata-react: \"${c.id}\" uses a chord the browser keeps for itself; add \\`claim: true\\` to take it over.`);\n }\n }\n}\n\n/** The shortcut a command shows in menus and legends (\"⌘Z\", \"Ctrl+Z\"), or undefined. */\nexport function commandShortcut(c: Command, platform: Platform = detectPlatform()): string | undefined {\n return c.keys?.[0] ? formatChord(c.keys[0], platform) : undefined;\n}\n\n/** A quiet legend built from the same commands the key handler runs: only commands with keys, disabled ones muted. */\nexport function CommandLegend({\n commands,\n platform,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n commands: readonly Command[];\n platform?: Platform;\n label?: string;\n className?: string;\n}) {\n const where = platform ?? detectPlatform();\n const shown = commands.filter((c) => c.keys?.length);\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shown.map((c) => (\n <div key={c.id} className={cn(\"flex items-center gap-1.5\", isDisabled(c) && \"opacity-50\")}>\n <dt>\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n <KeyText>{commandShortcut(c, where) ?? \"\"}</KeyText>\n </kbd>\n </dt>\n <dd>{labelOf(c)}</dd>\n </div>\n ))}\n </dl>\n );\n}\n\nconst itemClass = cn(\n \"flex min-h-(--control-h-sm) cursor-pointer items-center gap-2 rounded-control px-2 type-body-sm outline-none\",\n \"focus:bg-muted disabled:cursor-not-allowed disabled:text-muted-foreground disabled:opacity-70\",\n \"open:bg-muted\",\n);\n\nfunction Item({ command, platform }: { command: Command; platform: Platform }) {\n const Icon = command.icon ?? (command.destructive ? Trash2 : undefined);\n const shortcut = commandShortcut(command, platform);\n const reason = reasonOf(command);\n return (\n <MenuItem\n id={command.id}\n textValue={labelOf(command)}\n isDisabled={isDisabled(command)}\n onAction={command.run}\n className={cn(itemClass, command.destructive && !isDisabled(command) && \"text-danger\", \"flex-wrap\")}\n >\n {({ isSelected, selectionMode }) => (\n <>\n {selectionMode !== \"none\" ? (\n <span aria-hidden className=\"grid size-4 shrink-0 place-items-center\">{isSelected && <Check className=\"size-4\" />}</span>\n ) : (\n Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />\n )}\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{labelOf(command)}</Text>\n {shortcut && <Keyboard className=\"ml-6 shrink-0 font-mono type-caption text-muted-foreground\"><KeyText>{shortcut}</KeyText></Keyboard>}\n {reason && <Text slot=\"description\" className=\"w-full pl-6 type-caption text-muted-foreground\">{reason}</Text>}\n </>\n )}\n </MenuItem>\n );\n}\n\nfunction Entries({ entries, platform }: { entries: readonly MenuEntry[]; platform: Platform }) {\n return (\n <>\n {entries.map((entry, i) => {\n if (entry === \"separator\") return <Separator key={`sep-${i}`} className=\"my-1 h-px border-0 bg-border\" />;\n if (isCommand(entry)) return <Item key={entry.id} command={entry} platform={platform} />;\n if (\"group\" in entry) {\n const checkable = entry.items.length > 0 && entry.items.every((c) => c.checked !== undefined);\n return (\n <MenuSection\n key={`group-${entry.group}`}\n selectionMode={checkable ? \"multiple\" : undefined}\n selectedKeys={checkable ? entry.items.filter((c) => c.checked).map((c) => c.id) : undefined}\n >\n <Header className=\"px-2 pt-1 type-caption text-muted-foreground\">{entry.group}</Header>\n {entry.items.map((c) => <Item key={c.id} command={c} platform={platform} />)}\n </MenuSection>\n );\n }\n return (\n <SubmenuTrigger key={`sub-${entry.submenu}`}>\n <MenuItem textValue={entry.submenu} className={itemClass}>\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{entry.submenu}</Text>\n <ChevronRight aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n </MenuItem>\n <AriaPopover offset={0} crossOffset={-4} className={cn(\"layer-overlay min-w-48 p-1\", overlaySurface)}>\n <AriaMenu aria-label={entry.submenu} className=\"outline-none\">\n <Entries entries={entry.items} platform={platform} />\n </AriaMenu>\n </AriaPopover>\n </SubmenuTrigger>\n );\n })}\n </>\n );\n}\n\nconst surface = cn(\"layer-overlay min-w-48 p-1\", overlaySurface);\n\n/** Props for `Menu`. */\nexport type MenuProps = {\n /** Names the menu: \"File\", \"Edit\". Required. */\n label: string;\n /** The control that opens it. */\n trigger: React.ReactElement;\n items: readonly MenuEntry[];\n /** Controlled open state, for a story or a test that needs it shown. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n platform?: Platform;\n className?: string;\n};\n\n/** A dropdown menu of commands: the menu roles and keyboard model, shortcuts shown per platform, unavailable items with their reason, separators, groups, checkable groups and submenus. */\nexport function Menu({ label, trigger, items, open, onOpenChange, platform, className }: MenuProps) {\n const where = platform ?? detectPlatform();\n return (\n <MenuTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement=\"bottom start\" offset={4} className={cn(surface, className)}>\n <AriaMenu aria-label={label} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </MenuTrigger>\n );\n}\n\n/** Props for `ContextMenu`. */\nexport type ContextMenuProps = {\n /** Names the menu: \"Clip actions\". Required. */\n label: string;\n items: readonly MenuEntry[];\n /** The object it belongs to. It becomes the thing the menu opens on: right-click, the context-menu key and Shift+F10. */\n children: React.ReactElement<React.HTMLAttributes<HTMLElement>>;\n platform?: Platform;\n disabled?: boolean;\n};\n\n/**\n * A context menu for an object: opens on right-click at the pointer, and from the keyboard (the\n * context-menu key or Shift+F10) beside the focused object, with the same items and shortcuts as\n * every other menu. The child gets the handlers, so it should be focusable (a row, a clip).\n */\nexport function ContextMenu({ label, items, children, platform, disabled }: ContextMenuProps) {\n const where = platform ?? detectPlatform();\n const [at, setAt] = React.useState<{ x: number; y: number } | null>(null);\n const anchor = React.useRef<HTMLSpanElement>(null);\n const open = (x: number, y: number) => setAt({ x, y });\n const child = React.Children.only(children);\n return (\n <>\n {React.cloneElement(child, {\n onContextMenu: (e: React.MouseEvent<HTMLElement>) => {\n child.props.onContextMenu?.(e);\n if (disabled || e.defaultPrevented) return;\n e.preventDefault();\n open(e.clientX, e.clientY);\n },\n onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {\n child.props.onKeyDown?.(e);\n if (disabled || e.defaultPrevented) return;\n if (e.key === \"ContextMenu\" || (e.key === \"F10\" && e.shiftKey)) {\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n open(r.left + 8, r.bottom);\n }\n },\n })}\n {at && (\n <span ref={anchor} aria-hidden style={{ position: \"fixed\", left: at.x, top: at.y, width: 0, height: 0 }} />\n )}\n <AriaPopover triggerRef={anchor} isOpen={at !== null} onOpenChange={(o) => !o && setAt(null)} placement=\"bottom start\" offset={0} className={surface}>\n <AriaMenu aria-label={label} autoFocus=\"first\" onAction={() => setAt(null)} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </>\n );\n}\n\n/** Props for `CommandMenu`. */\nexport type CommandMenuProps = {\n /** The commands to search, usually the same list given to `useCommands`. Entries may be grouped. */\n commands: readonly MenuEntry[];\n /** Controlled open state; otherwise it opens on `shortcut`. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** The chord that opens it. Default `Mod+K`. `null` for none. */\n shortcut?: string | null;\n /** The search field's name and placeholder. Default \"Search commands\". */\n label?: string;\n platform?: Platform;\n};\n\nfunction flatten(entries: readonly MenuEntry[]): Command[] {\n return entries.flatMap((e) => (e === \"separator\" ? [] : isCommand(e) ? [e] : flatten(e.items)));\n}\n\n/** A searchable list of every command, opened by a chord (default Mod+K). Choosing one closes it and runs it; an unavailable command is shown with its reason and does nothing. */\nexport function CommandMenu({ commands, open, onOpenChange, shortcut = \"Mod+K\", label = \"Search commands\", platform }: CommandMenuProps) {\n const where = platform ?? detectPlatform();\n const [own, setOwn] = React.useState(false);\n const isOpen = open ?? own;\n const set = (next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n };\n React.useEffect(() => {\n if (!shortcut) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || !matchesChord(e, shortcut, where)) return;\n e.preventDefault();\n // A held key repeats keydown; toggling on each would flicker the dialog open and shut.\n if (e.repeat) return;\n set(!isOpen);\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n });\n const { contains } = useFilter({ sensitivity: \"base\" });\n const all = flatten(commands);\n return (\n <ModalOverlay isOpen={isOpen} onOpenChange={set} isDismissable className=\"layer-overlay fixed inset-0 grid justify-items-center overflow-hidden scrim p-4 pt-24\">\n <Modal className={cn(\"flex max-h-full w-full max-w-lg flex-col self-start outline-none\", overlaySurface)}>\n <AriaDialog aria-label={label} className=\"flex min-h-0 flex-col outline-none\">\n <Autocomplete filter={contains}>\n <SearchField aria-label={label} autoFocus className=\"flex items-center gap-2 border-b border-border px-3\">\n <Search aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <AriaInput placeholder={label} className=\"h-(--control-h) min-w-0 flex-1 bg-transparent type-body outline-none placeholder:text-muted-foreground\" />\n </SearchField>\n <AriaMenu\n aria-label=\"Commands\"\n className=\"min-h-0 overflow-y-auto overscroll-contain p-1 outline-none\"\n renderEmptyState={() => <p className=\"px-3 py-4 type-body-sm text-muted-foreground\">No command matches.</p>}\n onAction={() => set(false)}\n >\n {all.map((c) => <Item key={c.id} command={c} platform={where} />)}\n </AriaMenu>\n </Autocomplete>\n </AriaDialog>\n <Heading slot=\"title\" className=\"sr-only\">{label}</Heading>\n </Modal>\n </ModalOverlay>\n );\n}\n","import * as React from \"react\";\nimport { Toolbar as AriaToolbar, Separator } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// A toolbar groups controls that act on what is shown (a preview's grid and quality, a timeline's\n// snap, a table's density). React Aria gives it the WAI-ARIA toolbar keyboard model: one tab stop,\n// arrow keys (and Home and End) move inside it, Tab leaves it. It needs a `label`, as an unnamed\n// toolbar is announced as nothing. Groups inside it are separated by a hairline (`ToolbarSeparator`)\n// rather than by space alone, so a row of eight small controls reads as three groups. It lays out\n// as one wrapping row: when it runs out of width, controls wrap to the next line instead of being\n// hidden behind an overflow menu, which keeps every control reachable with no extra state\n// (an overflow menu is the later step, once the Menu exists).\n\n/** Props for `Toolbar`. */\nexport type ToolbarProps = {\n /** Names the toolbar for screen readers: \"Preview options\". Required. */\n label: string;\n orientation?: \"horizontal\" | \"vertical\";\n children: React.ReactNode;\n className?: string;\n};\n\n/** A group of controls with one tab stop and arrow-key movement (the WAI-ARIA toolbar pattern). Needs a `label`. */\nexport function Toolbar({ label, orientation = \"horizontal\", children, className }: ToolbarProps) {\n // React Aria's toolbar moves with the arrow keys; Home and End (to the first and last control) are\n // added here, as the WAI-ARIA toolbar pattern lists them. The capture phase runs before React\n // Aria's own handler, and a typing target (a number field inside the toolbar) keeps its Home and End.\n const jump = (e: React.KeyboardEvent<HTMLElement>) => {\n // Only events from inside the toolbar's own DOM: a Popover opened from a control here renders in\n // a portal, and its events still reach this handler through React's tree.\n if ((e.key !== \"Home\" && e.key !== \"End\") || isTypingTarget(e.target) || !e.currentTarget.contains(e.target as Node)) return;\n const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"button, input, select, textarea, a[href], [tabindex]\")].filter(\n (el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\" && el.tabIndex >= -1 && el.getAttribute(\"role\") !== \"separator\",\n );\n const target = e.key === \"Home\" ? items[0] : items[items.length - 1];\n if (!target) return;\n e.preventDefault();\n e.stopPropagation();\n target.focus();\n };\n return (\n <div className=\"contents\" onKeyDownCapture={jump}>\n <AriaToolbar\n aria-label={label}\n orientation={orientation}\n className={cn(\"flex flex-wrap items-center gap-1\", orientation === \"vertical\" && \"flex-col items-stretch\", className)}\n >\n {children}\n </AriaToolbar>\n </div>\n );\n}\n\n/** A hairline between groups of controls inside a `Toolbar`. */\nexport function ToolbarSeparator({ className }: { className?: string }) {\n return <Separator className={cn(\"mx-1 h-5 w-px self-center border-0 bg-border\", className)} />;\n}\n","import * as React from \"react\";\nimport { ToggleButton as AriaToggleButton, ToggleButtonGroup } from \"react-aria-components\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// On/off and one-of-a-few controls for what acts on the view: grid, snap, quality, view mode,\n// density. `Toggle` is one pressed-or-not button (`aria-pressed`); `ToggleGroup` is a single-choice\n// set of them for 2 to 7 short options that switch a view (components.md §3.3; for 2 to 5 options\n// that each need a sentence use `ChoiceGroup`).\n//\n// The chosen state must be seen without colour and must not look like the view's one filled\n// primary button (patterns.md §2, the one-filled-button rule): chosen is an ink border on a\n// neutral tint, with the label unchanged in weight (no layout shift), never `bg-primary`. An\n// icon-only toggle cannot be written without its name: `label` is required, becomes the accessible\n// name and is shown as a tooltip, as for `IconButton`. Toggles are used tens of times a day, so\n// they get the press and colour transitions and nothing more (character.md §3).\n\nconst base =\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control border type-label transition-state press [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 \" +\n \"border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground \" +\n \"selected:border-foreground selected:bg-muted selected:text-foreground \" +\n \"disabled:pointer-events-none disabled:opacity-50\";\n\nconst sizes = { default: \"h-(--control-h)\", sm: \"h-(--control-h-sm)\" } as const;\ntype Size = keyof typeof sizes;\n\n/** Props for `Toggle`. */\nexport type ToggleProps = {\n /** The name, always. Shown as the text unless `icon` is given with `iconOnly`, then it is the accessible name and the tooltip. */\n label: string;\n icon?: IconComponent;\n /** Show only the icon; `label` stays the name and tooltip. */\n iconOnly?: boolean;\n pressed?: boolean;\n defaultPressed?: boolean;\n onChange?: (pressed: boolean) => void;\n disabled?: boolean;\n size?: Size;\n className?: string;\n};\n\nfunction Face({ label, icon: Icon, iconOnly, pad }: { label: string; icon?: IconComponent; iconOnly?: boolean; pad: string }) {\n return (\n <>\n {Icon && <Icon aria-hidden />}\n {!iconOnly && <span className={pad}>{label}</span>}\n </>\n );\n}\n\n/** A button that is pressed or not (`aria-pressed`). Chosen reads as an ink border on a tint, never as the filled primary. */\nexport function Toggle({ label, icon, iconOnly = false, pressed, defaultPressed, onChange, disabled, size = \"default\", className }: ToggleProps) {\n const button = (\n <AriaToggleButton\n isSelected={pressed}\n defaultSelected={defaultPressed}\n onChange={onChange}\n isDisabled={disabled}\n aria-label={icon && iconOnly ? label : undefined}\n className={cn(base, sizes[size], icon && iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\", className)}\n >\n <Face label={label} icon={icon} iconOnly={iconOnly && Boolean(icon)} pad=\"\" />\n </AriaToggleButton>\n );\n return icon && iconOnly ? <Tooltip label={label}>{button}</Tooltip> : button;\n}\n\n/** One option of a `ToggleGroup`. */\nexport type ToggleOption = { value: string; label: string; icon?: IconComponent; iconOnly?: boolean };\n\n/** Props for `ToggleGroup`. */\nexport type ToggleGroupProps = {\n /** Names the group for screen readers: \"Preview quality\". Required. */\n label: string;\n options: readonly ToggleOption[];\n value: string;\n onChange: (value: string) => void;\n size?: Size;\n className?: string;\n};\n\n/** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */\nexport function ToggleGroup({ label, options, value, onChange, size = \"default\", className }: ToggleGroupProps) {\n return (\n <ToggleButtonGroup\n aria-label={label}\n selectionMode=\"single\"\n disallowEmptySelection\n selectedKeys={[value]}\n onSelectionChange={(keys) => {\n const next = [...keys][0];\n if (next !== undefined) onChange(String(next));\n }}\n className={cn(\"inline-flex gap-0.5 rounded-surface border border-border bg-background p-0.5\", className)}\n >\n {options.map((o) => {\n const iconOnly = Boolean(o.icon && o.iconOnly);\n const item = (\n <AriaToggleButton\n id={o.value}\n aria-label={iconOnly ? o.label : undefined}\n className={cn(\n base,\n // Inside the group the segments are 4px, the outer 6px less its 2px padding; the group's own\n // hairline replaces each segment's, and the chosen one keeps the ink border.\n \"border-transparent bg-transparent selected:border-foreground\",\n sizes[size],\n iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\",\n )}\n >\n <Face label={o.label} icon={o.icon} iconOnly={iconOnly} pad=\"\" />\n </AriaToggleButton>\n );\n return iconOnly ? <Tooltip key={o.value} label={o.label}>{item}</Tooltip> : React.cloneElement(item, { key: o.value });\n })}\n </ToggleButtonGroup>\n );\n}\n","import * as React from \"react\";\nimport { Switch as AriaSwitch } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A switch is for a setting that applies the moment it is flipped (show the grid, enable the\n// heatmap), never for one that needs a Save: that is a Checkbox in a form (components.md §3.3).\n// The label and the control are one target. \"On\" is shown by position and by a tick in the thumb\n// as well as by colour, so it survives a colour-blind reading. `role=\"switch\"` and its on state\n// come from React Aria. `detail` is the description, not part of the name: React Aria puts all the\n// text inside the switch into its label, so the label span names the control (`aria-labelledby`)\n// and the detail is pointed at by `aria-describedby`, as `Checkbox` and `Field` do (issue #152).\n// Used many times a day, so only a short colour and position transition.\n\n/** Props for `Switch`. */\nexport type SwitchProps = {\n /** What it turns on, as the visible label: \"Show elevation profile\". Required. */\n label: string;\n /** A muted second line under the label. */\n detail?: string;\n on?: boolean;\n defaultOn?: boolean;\n onChange?: (on: boolean) => void;\n disabled?: boolean;\n className?: string;\n};\n\n/** An on/off setting that applies at once, its label and control one target. */\nexport function Switch({ label, detail, on, defaultOn, onChange, disabled, className }: SwitchProps) {\n const id = React.useId();\n return (\n <AriaSwitch\n isSelected={on}\n defaultSelected={defaultOn}\n onChange={onChange}\n isDisabled={disabled}\n aria-labelledby={`${id}-label`}\n aria-describedby={detail ? `${id}-detail` : undefined}\n className={cn(\"group inline-flex min-h-6 cursor-pointer items-start gap-3 disabled:cursor-not-allowed disabled:opacity-50\", className)}\n >\n <span\n aria-hidden\n className={cn(\n \"mt-0.5 flex h-5 w-9 shrink-0 items-center rounded-pill border border-input bg-muted p-0.5 transition-state\",\n \"group-selected:border-primary group-selected:bg-primary\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n )}\n >\n <span className=\"grid size-3.5 place-items-center rounded-pill bg-background text-primary group-selected:translate-x-4\">\n <span className=\"hidden size-1.5 rounded-pill bg-primary group-selected:block\" />\n </span>\n </span>\n <span className=\"grid\">\n <span id={`${id}-label`} className=\"type-body\">{label}</span>\n {detail && <span id={`${id}-detail`} className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n </AriaSwitch>\n );\n}\n","import * as React from \"react\";\nimport {\n Dialog as AriaDialog,\n DialogTrigger,\n Heading,\n Modal,\n ModalOverlay,\n} from \"react-aria-components\";\nimport { X } from \"lucide-react\";\nimport { Button, IconButton } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Dialog is for a task that needs its own space; \"a modal is never the first idea for a form that\n// fits on the page\" (components.md §3.11). AlertDialog is the only confirm in the library, for what\n// cannot be undone: a reversible removal uses `UndoBar` instead (patterns.md §7).\n//\n// What the types and the component settle, so an app cannot get them wrong:\n// - A title is required (visible, or `hideTitle` for a screen-reader-only one): an unnamed dialog is\n// announced as \"dialog\" and nothing else. An AlertDialog's `confirm` is required and is the verb,\n// \"Delete 3 firings\", never \"OK\".\n// - React Aria moves focus in on open and back to the trigger on close, makes the page behind inert\n// and stops it scrolling. Content scrolls inside the dialog when tall (`overscroll-contain`), and\n// everything is portalled onto `layer-overlay`, above panes, sticky headers and the undo bar.\n// - A dialog can be made not closable while work runs (`closable={false}`: no close control, no\n// Escape, no outside press), so an export cannot lose its Close button halfway, as strata-vid's did.\n// - An AlertDialog ignores outside presses, focuses its safe choice (Cancel) first, and stays open\n// with the reason when an async confirm fails, since closing would hide that it did not happen.\n// - The same surface is a Sheet with `placement=\"end\"`: a side panel for a long form or a detail.\n\ntype Common = {\n /** What it is for: \"Export video\", \"Delete 3 firings?\". Required. */\n title: string;\n /** Shown under the title when it is not enough alone. */\n description?: React.ReactNode;\n /** The control that opens it. Leave out and drive it with `open` and `onOpenChange`. */\n trigger?: React.ReactElement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n};\n\n/** Props for `Dialog`. */\nexport type DialogProps = Common & {\n /** The body. It scrolls inside the dialog when it is taller than the window. */\n children?: React.ReactNode;\n /** The buttons along the bottom, built with `DialogActions`'s `close` render prop when one should close it. One filled button at most. */\n actions?: React.ReactNode | ((close: () => void) => React.ReactNode);\n /** Keep the title for screen readers only, when the body already says it. */\n hideTitle?: boolean;\n /** `false` while work cannot be interrupted: no close control, Escape or outside press. Default true. */\n closable?: boolean;\n /** `center` is a dialog; `end` is a sheet down the right edge. Default `center`. */\n placement?: \"center\" | \"end\";\n size?: \"sm\" | \"md\" | \"lg\";\n};\n\nconst sizes = { sm: \"max-w-sm\", md: \"max-w-lg\", lg: \"max-w-3xl\" } as const;\n\n// A dialog with a `trigger` is React Aria's DialogTrigger around it. One driven only by `open` has\n// nothing pressable to put in a trigger, and React Aria warns \"A PressResponder was rendered without a\n// pressable child\" for an empty one on every mount (issue #116), so it gets the controlled\n// ModalOverlay alone: it still traps focus and, on close, returns it to whatever had it before.\nfunction Overlay({ trigger, open, onOpenChange, children }: { trigger?: React.ReactElement; open?: boolean; onOpenChange?: (open: boolean) => void; children: React.ReactElement<React.ComponentProps<typeof ModalOverlay>> }) {\n if (trigger) {\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n {children}\n </DialogTrigger>\n );\n }\n return <Driven open={open} onOpenChange={onOpenChange}>{children}</Driven>;\n}\n\n// Without a trigger, React Aria has no element to hand focus back to, so the one that had it when\n// the dialog opened is kept (read while rendering, before the dialog moves focus in) and given it\n// back on close, unless the app has already put focus somewhere on purpose.\nfunction Driven({ open, onOpenChange, children }: { open?: boolean; onOpenChange?: (open: boolean) => void; children: React.ReactElement<React.ComponentProps<typeof ModalOverlay>> }) {\n const opener = React.useRef<Element | null>(null);\n const wasOpen = React.useRef(false);\n if (open && !wasOpen.current) opener.current = typeof document === \"undefined\" ? null : document.activeElement;\n wasOpen.current = Boolean(open);\n React.useEffect(() => {\n if (!open) return;\n return () => {\n const back = opener.current;\n opener.current = null;\n requestAnimationFrame(() => {\n const idle = !document.activeElement || document.activeElement === document.body;\n if (idle && back instanceof HTMLElement && back.isConnected) back.focus();\n });\n };\n }, [open]);\n return React.cloneElement(children, { isOpen: open, onOpenChange });\n}\n\nconst overlayClass = \"layer-overlay fixed inset-0 grid overflow-hidden scrim\";\n\n/** A modal dialog with a required title; focus goes in and returns, Escape and a close control dismiss it. `placement=\"end\"` makes it a sheet. */\nexport function Dialog({\n title, description, trigger, open, onOpenChange, className, children, actions,\n hideTitle, closable = true, placement = \"center\", size = \"md\",\n}: DialogProps) {\n const descriptionId = React.useId();\n return (\n <Overlay trigger={trigger} open={open} onOpenChange={onOpenChange}>\n <ModalOverlay isDismissable={closable} isKeyboardDismissDisabled={!closable} className={cn(overlayClass, placement === \"end\" ? \"justify-items-end\" : \"place-items-center p-4\")}>\n <Modal\n className={cn(\n \"flex max-h-full min-h-0 w-full flex-col outline-none\",\n overlaySurface,\n placement === \"end\" ? \"h-full max-w-md rounded-r-none\" : sizes[size],\n className,\n )}\n >\n <AriaDialog aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className={cn(\"type-heading\", hideTitle && \"sr-only\")}>\n {title}\n </Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {closable && <IconButton icon={X} label=\"Close\" onPress={close} className=\"-mr-2 -mt-2 shrink-0\" />}\n </div>\n {children != null && <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\">{children}</div>}\n {actions != null && (\n <div className=\"flex flex-wrap justify-end gap-2\">{typeof actions === \"function\" ? actions(close) : actions}</div>\n )}\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </Overlay>\n );\n}\n\n/** Props for `AlertDialog`. */\nexport type AlertDialogProps = Common & {\n /** The verb, repeating the action: \"Delete 3 firings\". Required; \"OK\" and \"Confirm\" are what this prevents. */\n confirm: string;\n /** Runs on confirm. When it returns a promise the dialog waits, shows the button busy, and stays open with the reason if it rejects. */\n onConfirm: () => void | Promise<unknown>;\n /** The safe choice, which has initial focus. Default \"Cancel\". */\n cancel?: string;\n /** `destructive` fills the confirm button with the destructive role. Default `destructive`. */\n tone?: \"destructive\" | \"default\";\n};\n\n/**\n * A confirm for what cannot be undone. Names the object and the consequence in `title`, repeats the\n * verb on the confirm button, focuses Cancel first and ignores outside presses.\n */\nexport function AlertDialog({\n title, description, trigger, open, onOpenChange, className, confirm, onConfirm, cancel = \"Cancel\", tone = \"destructive\",\n}: AlertDialogProps) {\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string>();\n const [inner, setInner] = React.useState(false);\n const descriptionId = React.useId();\n const isOpen = open ?? inner;\n const change = (next: boolean) => {\n if (busy) return;\n setError(undefined);\n setInner(next);\n onOpenChange?.(next);\n };\n const run = async () => {\n try {\n const result = onConfirm();\n if (result && typeof (result as Promise<unknown>).then === \"function\") {\n setBusy(true);\n await result;\n }\n setBusy(false);\n change(false);\n } catch (thrown) {\n setBusy(false);\n setError(describeActionError(thrown) ?? \"That did not go through. Nothing was confirmed; try again.\");\n }\n };\n return (\n <Overlay trigger={trigger} open={isOpen} onOpenChange={change}>\n <ModalOverlay isDismissable={false} isKeyboardDismissDisabled={busy} className={cn(overlayClass, \"place-items-center p-4\")}>\n <Modal className={cn(\"flex max-h-full w-full max-w-sm flex-col outline-none\", overlaySurface, className)}>\n <AriaDialog role=\"alertdialog\" aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n {/* The message scrolls inside the dialog on a short window or with large text; the buttons stay in view. */}\n <div className=\"grid min-h-0 gap-3 overflow-y-auto overscroll-contain\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className=\"type-heading\">{title}</Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-control bg-danger-subtle px-3 py-2 type-body-sm text-danger\">\n {error}\n </p>\n )}\n </div>\n <div className=\"flex flex-wrap justify-end gap-2\">\n <Button autoFocus disabled={busy} onPress={close}>{cancel}</Button>\n <Button variant={tone === \"destructive\" ? \"destructive\" : \"default\"} disabled={busy} aria-busy={busy || undefined} onPress={run}>\n {busy ? `${confirm}…` : confirm}\n </Button>\n </div>\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </Overlay>\n );\n}\n\n","import * as React from \"react\";\nimport { Dialog, DialogTrigger, Popover as AriaPopover } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A popover holds a small form or a choice anchored to the control that opened it (a colour, a\n// sort, a few filters) where a dialog would take the whole screen. Unlike a tooltip it may hold\n// anything interactive. React Aria keeps it inside the viewport (flips and shifts at the edges),\n// closes it on Escape and on a press outside, and returns focus to the trigger. It is a labelled\n// `dialog`, so `label` is required: an unnamed floating region is the same defect as an unnamed\n// icon button. It is portalled to the body on `layer-overlay`, so panes and sticky headers cannot\n// clip or cover it.\n\n/** Props for `Popover`. */\nexport type PopoverProps = {\n /** What the popover is, as a screen reader names it: \"Line colour\", \"Filters\". Required. */\n label: string;\n /** The control that opens it (a `Button`); it gets `aria-expanded` and focus back on close. */\n trigger: React.ReactElement;\n children: React.ReactNode;\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n /** Where along the trigger it lines up. Default `start`. */\n align?: \"start\" | \"center\" | \"end\";\n /** Controlled open state. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** Width of the surface. Default `md` (18rem). */\n size?: \"sm\" | \"md\" | \"lg\";\n className?: string;\n};\n\nconst widths = { sm: \"w-52\", md: \"w-72\", lg: \"w-96\" } as const;\n\n/** A floating panel anchored to its trigger, for a small form or choice. Requires a `label`; closes on Escape and outside press, and returns focus. */\nexport function Popover({ label, trigger, children, side = \"bottom\", align = \"start\", open, onOpenChange, size = \"md\", className }: PopoverProps) {\n const placement = (align === \"center\" ? side : `${side} ${align}`) as React.ComponentProps<typeof AriaPopover>[\"placement\"];\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement={placement} offset={6} className={cn(\"layer-overlay p-3\", widths[size], overlaySurface, className)}>\n <Dialog aria-label={label} className=\"outline-none\">\n {children}\n </Dialog>\n </AriaPopover>\n </DialogTrigger>\n );\n}\n","import * as React from \"react\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check, Minus } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A checkbox cannot be written without a name: `label` is required, as `IconButton`'s is. Shown,\n// it sits beside the box inside one <label>, so the label and the control are a single target\n// with no dead zone between them (Vercel's interface guidelines; ux-design audit.md). Hidden\n// (`hideLabel`, for a table cell where the row already says what it is), it becomes the\n// accessible name through aria-label, never through visually hidden text: a hidden span inside a\n// label joined to a neighbour did not form a name with its space in dom-testing-library (strata-\n// react issue #11), and an aria-label leaves no room for that.\n//\n// It is React Aria's Checkbox (a visually hidden native input inside the label), so keyboard,\n// forms, `aria-checked=\"mixed\"` and press handling are the library's, and the 18px box is drawn\n// from our tokens (it is no longer the platform's `accent-primary` control: that one could not show\n// a tick and a dash in the theme's own roles). `checked=\"mixed\"` is the indeterminate state a\n// select-all needs. It used to be native; the visual baselines changed for it (CHANGELOG).\n//\n// `onCheckedChange` also says whether Shift was held, which is how a list of checkboxes extends a\n// range (strata-react issue #32). A change event carries no modifier keys, so the label notes Shift\n// on the press that leads to it: a mouse press anywhere on the target, or Space on the box.\n\n/** A checkbox with its label as one target. `label` is required; `checked=\"mixed\"` is indeterminate. */\nexport type CheckboxProps = Omit<React.ComponentProps<\"input\">, \"type\" | \"checked\" | \"onChange\" | \"aria-label\" | \"children\" | \"style\"> & {\n /** Names the checkbox. Shown beside it unless `hideLabel`. */\n label: string;\n /** Keep the label as the accessible name only, for a cell or toolbar where the context shows what it is. */\n hideLabel?: boolean;\n /** A muted second line under a shown label. */\n detail?: string;\n checked: boolean | \"mixed\";\n /** Called with the new state, and whether Shift was held (a range click or Shift+Space). */\n onCheckedChange: (checked: boolean, gesture: CheckboxGesture) => void;\n};\n\n/** How a checkbox was changed: `shiftKey` is true for Shift+click and Shift+Space, which extend a range in a list. */\nexport type CheckboxGesture = { shiftKey: boolean };\n\n/** A checkbox and its label as one target. `label` is required; `hideLabel` keeps it as the accessible name only. */\nexport function Checkbox({ label, hideLabel = false, detail, checked, onCheckedChange, className, disabled, required, ...props }: CheckboxProps) {\n const shift = useShiftNote();\n const id = React.useId();\n // Shift is noted in the capture phase on a wrapper, because React Aria's press handling stops the\n // events it uses before they bubble. `contents` keeps the wrapper out of layout.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={checked === true}\n isIndeterminate={checked === \"mixed\"}\n isDisabled={disabled}\n isRequired={required}\n onChange={(selected) => onCheckedChange(selected, shift.take())}\n aria-label={hideLabel ? label : undefined}\n aria-labelledby={hideLabel ? undefined : `${id}-label`}\n aria-describedby={!hideLabel && detail ? `${id}-detail` : undefined}\n {...(props as object)}\n className={cn(\n \"group inline-flex min-h-6 min-w-6 items-start gap-3\",\n hideLabel && \"items-center justify-center\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\",\n className,\n )}\n >\n {({ isSelected, isIndeterminate }) => (\n <>\n <CheckboxBox selected={isSelected} indeterminate={isIndeterminate} hideLabel={hideLabel} />\n {!hideLabel && (\n <span className=\"grid\">\n <span id={`${id}-label`} className=\"type-body\">{label}</span>\n {detail && <span id={`${id}-detail`} className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n )}\n </>\n )}\n </AriaCheckbox>\n </span>\n );\n}\n\n/** Notes Shift on the press that leads to a checkbox's change event, which has no modifier keys of its own. */\nexport function useShiftNote() {\n const held = React.useRef(false);\n return React.useMemo(\n () => ({\n handlers: {\n onMouseDown: (e: React.MouseEvent) => void (held.current = e.shiftKey),\n onKeyDown: (e: React.KeyboardEvent) => void (held.current = e.shiftKey),\n },\n take: (): CheckboxGesture => {\n const shiftKey = held.current;\n held.current = false;\n return { shiftKey };\n },\n }),\n [],\n );\n}\n\n// The drawn box, shared by `Checkbox` and the table's selection checkbox.\nfunction CheckboxBox({ selected, indeterminate, hideLabel }: { selected: boolean; indeterminate: boolean; hideLabel: boolean }) {\n return (\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 shrink-0 place-items-center rounded-control border border-input bg-background transition-state\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n (selected || indeterminate) && \"border-primary bg-primary text-primary-foreground\",\n !hideLabel && \"mt-0.5\",\n )}\n >\n {indeterminate ? <Minus className=\"size-3.5\" strokeWidth={3} /> : selected ? <Check className=\"size-3.5\" strokeWidth={3} /> : null}\n </span>\n );\n}\n\n/**\n * The checkbox of a React Aria `Table` row or header (`slot=\"selection\"`): its checked, mixed and\n * disabled state come from the table, so it takes only a name. A `Checkbox` is controlled and would\n * fight the table's own selection state. Not exported from the package: `DataTable` uses it.\n * @internal\n */\nexport function TableSelectionCheckbox({ label, className, disabled }: { label: string; className?: string; disabled?: boolean }) {\n // The table names a row's checkbox from its own label and the row header's text; ours is named\n // by the caller's `rowLabel` alone (\"Select Tom Ellery\"), so it labels itself.\n const id = React.useId();\n return (\n <AriaCheckbox\n slot=\"selection\"\n isDisabled={disabled}\n id={id}\n aria-labelledby={id}\n aria-label={label}\n className={({ isDisabled }) =>\n cn(\"group inline-flex min-h-6 min-w-6 items-center justify-center\", isDisabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\", className)\n }\n >\n {({ isSelected, isIndeterminate }) => <CheckboxBox selected={isSelected} indeterminate={isIndeterminate} hideLabel />}\n </AriaCheckbox>\n );\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button, type ButtonProps } from \"./button\";\nimport { describeActionError, fieldErrorsOf } from \"../lib/errors\";\n\n// One object through its states: \"Book firing\" becomes \"Booking…\" becomes \"Booked\", in the same\n// button, rather than the button being swapped for a spinner. The labels are stacked in one grid\n// cell so the button is always as wide as its longest label and nothing around it shifts. The\n// button stays enabled until the request starts (so a person can always try), and the outcome is\n// announced politely for screen readers. When the action fails, the announcement carries what\n// went wrong in the product's words before the retry label (\"Kiln 2 is already booked. Try\n// again\"), because \"Try again\" alone does not say whether trying again can help.\n//\n// The button carries `data-phase` (and Button's `data-variant`), so a test reads which phase it is\n// in without matching four stacked labels in its text (strata-react issue #48); `asyncButtonPhase`\n// in strata-react/testing reads it.\n//\n// `useAsyncAction` also owns a form's field messages (strata-react issues #42 and #46). `validate`\n// runs before the action, and messages it returns stop the run and land on `fieldErrors`, keyed by\n// field; a server's per-field messages (an HttpError's `fieldErrors`, from a 422) land there too.\n// A screen passes `fieldErrors.link` to `Field error=` and keeps no `problem` state of its own.\n// Failing validation leaves the button idle, not \"Try again\": nothing was tried. `onInvalid` runs\n// once the messages are on screen, to move focus to the first field named.\n\nexport type Phase = \"idle\" | \"pending\" | \"done\" | \"error\";\n\nexport type AsyncLabels = {\n idle: string;\n /** Ends in an ellipsis: \"Saving…\", \"Booking…\". */\n pending: string;\n /** The same verb, finished: \"Saved\", \"Booked\". */\n done: string;\n error?: string;\n};\n\n/** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */\nexport function AsyncButton({\n phase,\n labels,\n error,\n disabled,\n ...props\n}: Omit<ButtonProps, \"children\"> & {\n phase: Phase;\n labels: AsyncLabels;\n /** What went wrong, in the product's words (`useAsyncAction`'s `error`). Announced with the error label when `phase` is `error`. */\n error?: string;\n}) {\n const errorLabel = labels.error ?? \"Try again\";\n const current = { idle: labels.idle, pending: labels.pending, done: labels.done, error: errorLabel }[phase];\n const Icon = { idle: null, pending: LoaderCircle, done: Check, error: CircleAlert }[phase];\n const announcement = phase === \"done\" ? labels.done : phase === \"error\" ? (error ? `${error} ${errorLabel}` : errorLabel) : \"\";\n\n return (\n <>\n <Button {...props} data-phase={phase} disabled={disabled || phase === \"pending\"} aria-disabled={phase === \"pending\" || undefined}>\n {Icon && <Icon aria-hidden className={phase === \"pending\" ? \"motion-safe:animate-spin\" : undefined} />}\n <span className=\"grid\">\n {[labels.idle, labels.pending, labels.done, errorLabel].map((l) => (\n <span key={l} aria-hidden={l !== current} className={l === current ? \"[grid-area:1/1]\" : \"invisible [grid-area:1/1]\"}>\n {l}\n </span>\n ))}\n </span>\n </Button>\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </>\n );\n}\n\n/** Messages for a form's fields, keyed by field name. */\nexport type FieldErrors = Readonly<Record<string, string>>;\n\n/** Options for `useAsyncAction`. */\nexport type AsyncActionOptions<A extends unknown[] = unknown[]> = {\n /** How long `done` shows before returning to `idle`. Default 2000ms. */\n settleMs?: number;\n /** Called with whatever the action threw, once the `error` render has committed: for logging, or to move focus to the retry button or an error message. */\n onError?: (error: unknown) => void;\n /** Turns what was thrown into `error`'s sentence, in the product's words. Default `describeActionError`: HTTP status sentences for `fetchJson`'s `HttpError`, else the Error's message. */\n describeError?: (error: unknown) => string | undefined;\n /** Checks the arguments before the action runs. A message for any field stops the run and is put on `fieldErrors`; the button stays idle. */\n validate?: (...args: A) => Record<string, string | undefined> | undefined;\n /** Called once validation's messages are on screen: to move focus to the first field named. */\n onInvalid?: (fieldErrors: FieldErrors) => void;\n};\n\n/** What `useAsyncAction` returns: the phase for `AsyncButton`, a stable `run`, and what went wrong while `phase` is `error`. */\nexport type AsyncAction<A extends unknown[]> = {\n phase: Phase;\n run: (...args: A) => Promise<void>;\n /** What went wrong, from `describeError`, while `phase` is `error`; otherwise undefined. Pass it to `AsyncButton`'s `error`. */\n error: string | undefined;\n /** What the action threw, while `phase` is `error`: to read more than the sentence (an HttpError's `status` or `body`). */\n thrown: unknown;\n /** Messages per field, from `validate` or from the server (an HttpError's `fieldErrors`). Pass each to its `Field`'s `error`. Cleared by the next run. */\n fieldErrors: FieldErrors;\n /** Clears one field's message (as the person edits it), or all of them. */\n clearFieldError: (field?: string) => void;\n};\n\n// The action and its options are read through a ref so `run` keeps one identity for the\n// component's life: a caller can pass an inline arrow without re-rendering every child that takes\n// `run`, and without the try/catch and error state each caller used to write to reach the phase.\n\n/** Runs an async action and reports its phase, its error and any field messages. `done` returns to `idle` after `settleMs`; `run` never changes identity. */\nexport function useAsyncAction<A extends unknown[]>(\n action: (...args: A) => Promise<unknown>,\n { settleMs = 2000, onError, describeError = describeActionError, validate, onInvalid }: AsyncActionOptions<A> = {},\n): AsyncAction<A> {\n const [state, setState] = React.useState<ActionState>(idle);\n const timer = React.useRef<number | undefined>(undefined);\n const unreported = React.useRef<{ thrown: unknown } | { invalid: FieldErrors } | undefined>(undefined);\n const latest = React.useRef({ action, onError, settleMs, describeError, validate, onInvalid });\n React.useLayoutEffect(() => {\n latest.current = { action, onError, settleMs, describeError, validate, onInvalid };\n });\n React.useEffect(() => () => window.clearTimeout(timer.current), []);\n const run = React.useCallback(async (...args: A) => {\n window.clearTimeout(timer.current);\n const invalid = messages(latest.current.validate?.(...args));\n if (invalid) {\n unreported.current = { invalid };\n setState({ ...idle, fieldErrors: invalid });\n return;\n }\n setState({ ...idle, phase: \"pending\" });\n try {\n await latest.current.action(...args);\n setState({ ...idle, phase: \"done\" });\n timer.current = window.setTimeout(() => setState(idle), latest.current.settleMs);\n } catch (thrown) {\n unreported.current = { thrown };\n setState({ phase: \"error\", error: latest.current.describeError(thrown), thrown, fieldErrors: fieldErrorsOf(thrown) });\n }\n }, []);\n // onError and onInvalid run after their render commits, not inside run: there the button is\n // still disabled from `pending` and a message rendered on `error` does not exist yet, so a\n // callback that moves focus to either would find nothing to focus.\n React.useEffect(() => {\n const note = unreported.current;\n if (!note) return;\n if (\"thrown\" in note && state.phase === \"error\") latest.current.onError?.(note.thrown);\n else if (\"invalid\" in note) latest.current.onInvalid?.(note.invalid);\n else return;\n unreported.current = undefined;\n }, [state]);\n const clearFieldError = React.useCallback(\n (field?: string) =>\n setState((s) => {\n if (field === undefined) return Object.keys(s.fieldErrors).length ? { ...s, fieldErrors: {} } : s;\n if (!(field in s.fieldErrors)) return s;\n const { [field]: _gone, ...rest } = s.fieldErrors;\n return { ...s, fieldErrors: rest };\n }),\n [],\n );\n return { phase: state.phase, run, error: state.error, thrown: state.thrown, fieldErrors: state.fieldErrors, clearFieldError };\n}\n\ntype ActionState = { phase: Phase; error: string | undefined; thrown: unknown; fieldErrors: FieldErrors };\nconst idle: ActionState = { phase: \"idle\", error: undefined, thrown: undefined, fieldErrors: {} };\n\n/** The messages `validate` returned, without the empty ones; undefined when there are none. */\nfunction messages(found: Record<string, string | undefined> | undefined): FieldErrors | undefined {\n if (!found) return undefined;\n const kept = Object.fromEntries(Object.entries(found).filter((e): e is [string, string] => Boolean(e[1])));\n return Object.keys(kept).length ? kept : undefined;\n}\n","import type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\n\n// Status is a word first. `children` is required and must be a string, so a status can never be a\n// bare coloured dot. The tint and ink come from the fixed status roles, which are kept apart from\n// the brand accent: pale tint, dark ink of the same hue, never a saturated chip with white text.\n// No pulsing variant exists; nothing on a status mark moves unless the data behind it is live.\n\nexport type Tone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\nconst tones: Record<Tone, string> = {\n neutral: \"bg-muted text-muted-foreground\",\n info: \"bg-info-subtle text-info\",\n success: \"bg-success-subtle text-success\",\n warning: \"bg-warning-subtle text-warning\",\n danger: \"bg-danger-subtle text-danger\",\n};\n\n/** A status as a word on a pale tint of its tone, with an optional icon. Never colour alone. */\nexport function Status({\n tone,\n icon: Icon,\n children,\n className,\n}: {\n tone: Tone;\n icon?: IconComponent;\n children: string;\n className?: string;\n}) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 whitespace-nowrap rounded-pill py-0.5 pr-2.5 pl-2 type-caption font-medium\",\n tones[tone],\n className,\n )}\n >\n {Icon && <Icon aria-hidden className=\"size-3.5 shrink-0\" />}\n {children}\n </span>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Headline figures as one container split by hairlines, label over value: what real product screens\n// do, instead of four cards each with an icon in a tinted circle. There is deliberately no `icon`,\n// `sparkline` or `trend` prop. A change is written in words with its window (\"4 more than last\n// Thursday\"), because a green \"+12.5%\" pill says neither what changed nor since when, and the trend\n// gets its own chart.\n\n/** Headline figures as one description list split by hairlines. Holds `Metric`s. */\nexport function MetricStrip({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <dl\n aria-label={label}\n className={cn(\n \"grid grid-cols-1 border-y border-border sm:auto-cols-fr sm:grid-flow-col sm:divide-x sm:divide-border\",\n className,\n )}\n >\n {children}\n </dl>\n );\n}\n\nexport type MetricProps = {\n label: string;\n /** Already formatted. Ink colour, 28px, tabular figures: never the brand colour, never 48px. */\n value: string;\n unit?: string;\n /** One sentence: the change in words with its window, or what the figure means right now. */\n note?: React.ReactNode;\n};\n\n/** One figure: label over value, an optional muted unit and a note that states any change in words with its window. */\nexport function Metric({ label, value, unit, note }: MetricProps) {\n return (\n <div className=\"grid content-start gap-0.5 border-border py-3 not-first:border-t sm:px-5 sm:not-first:border-t-0 sm:first:pl-0\">\n <dt className=\"type-label text-muted-foreground\">{label}</dt>\n <dd className=\"type-figure text-foreground\">\n {value}\n {unit && <span className=\"type-body text-muted-foreground\">{\" \" + unit}</span>}\n </dd>\n {note && <dd className=\"type-body-sm text-muted-foreground\">{note}</dd>}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Status } from \"./status\";\n\n// A usage bar: how full one thing is (a disk, a quota, a kiln's shelves), for status dashboards\n// that otherwise hand-roll a div with a width (strata-react issue #25, from jburnhams/homepage).\n// The rules it encodes, from ux-research ui-library/components.md §3.8 and patterns.md §5:\n// - It is a `meter`, not a `progressbar`: a progress bar is a task moving to done, a meter is a\n// level that can go up or down. Its accessible name is what is measured (\"Disk /\") and its\n// value text says the reading in words (\"72% used\"), so a screen reader hears \"Disk /, meter,\n// 72% used\" rather than a bare 72.\n// - The figure is always printed beside the bar. A bar alone is read to ±10% at best.\n// - Thresholds are what the person compares against, so they are drawn on the track as notches,\n// like LineChart's `band`. Each threshold must name its state (\"Filling up\", \"Nearly full\"):\n// when the reading crosses one, the fill takes the status ink and the word is shown as a\n// `Status`, so colour is never the only cue. Thresholds are shares of `max` (0.8 is 80%),\n// because a dashboard of disks of different sizes shares one set of them.\n// - `worseWhen=\"lower\"` turns the thresholds round for levels where empty is the problem (a\n// battery, credit left): a threshold then applies at or below its share.\n// - Below every threshold the fill is one chart hue (`--chart-1` unless `colour` says otherwise),\n// the same default as LineChart, never the brand accent and never a status colour, since\n// \"fine\" needs no colour of its own.\n// - `hideLabel` is for a meter in a table row, where the row already says what it measures; the\n// label stays as the meter's accessible name.\n// - No animation on the fill: a dashboard re-renders readings, and a bar that slides on each one\n// draws the eye to nothing.\n\n/** A level on a `Meter` at which the reading changes state, with the word for that state. */\nexport type MeterThreshold = {\n /** A share of `max`, from 0 to 1: 0.8 is 80%. */\n at: number;\n tone: \"warning\" | \"danger\";\n /** What the state is called, in the product's words: \"Filling up\", \"Nearly full\". */\n label: string;\n};\n\nexport type MeterProps = {\n /** What is measured, such as \"Disk /\". The meter's accessible name. */\n label: string;\n value: number;\n /** The full scale, in the same units as `value`. Defaults to 1, so a share can be passed as is. */\n max?: number;\n /** The reading in words, shown beside the bar and used as `aria-valuetext`. Defaults to \"72% used\". */\n valueText?: string;\n /** A second line of fact, such as \"36 of 50 GB\". */\n detail?: React.ReactNode;\n thresholds?: MeterThreshold[];\n /** \"lower\" when an emptier reading is the worse one (a battery, credit left). */\n worseWhen?: \"higher\" | \"lower\";\n /** Keeps the label as the accessible name only, for a meter in a table row that names it. */\n hideLabel?: boolean;\n /** CSS colour for the fill below every threshold. Defaults to the first chart token. */\n colour?: string;\n className?: string;\n};\n\n/** The threshold a share has crossed, if any: the most severe one reached in the worse direction. */\nexport function crossedThreshold(\n share: number,\n thresholds: readonly MeterThreshold[] = [],\n worseWhen: \"higher\" | \"lower\" = \"higher\",\n): MeterThreshold | undefined {\n const reached = thresholds.filter((t) => (worseWhen === \"higher\" ? share >= t.at : share <= t.at));\n // The one furthest in the worse direction wins, so danger beats warning when both are reached.\n return reached.sort((a, b) => (worseWhen === \"higher\" ? b.at - a.at : a.at - b.at))[0];\n}\n\nconst fills = { warning: \"var(--warning)\", danger: \"var(--danger)\" } as const;\n\n/** How full one thing is: a labelled `meter` with its reading in words, threshold notches, and a status word once a threshold is crossed. */\nexport function Meter({\n label,\n value,\n max = 1,\n valueText,\n detail,\n thresholds,\n worseWhen = \"higher\",\n hideLabel = false,\n colour = \"var(--chart-1)\",\n className,\n}: MeterProps) {\n const labelId = React.useId();\n const statusId = React.useId();\n const detailId = React.useId();\n const share = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;\n const crossed = crossedThreshold(share, thresholds, worseWhen);\n // `share`, not `percent`: a disk with a little on it reads \"<1% used\", never \"0% used\".\n const text = valueText ?? `${format.share(share)} used`;\n const hasNote = Boolean(crossed || detail);\n // Two ids rather than one wrapper, so the description reads \"Nearly full, 431 GB of 466 GB\"\n // with a break between the parts instead of running them together.\n const describedBy = [crossed && statusId, detail && detailId].filter(Boolean).join(\" \") || undefined;\n\n const bar = (\n <div\n role=\"meter\"\n aria-labelledby={hideLabel ? undefined : labelId}\n aria-label={hideLabel ? label : undefined}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-valuenow={Math.min(max, Math.max(0, value))}\n aria-valuetext={text}\n aria-describedby={describedBy}\n className=\"relative h-2 min-w-16 flex-1 overflow-hidden rounded-pill bg-muted\"\n >\n <div\n className=\"absolute inset-y-0 left-0\"\n style={{ width: `${share * 100}%`, background: crossed ? fills[crossed.tone] : colour }}\n />\n {/* Notches in the ground colour: the levels the reading is judged against. */}\n {thresholds?.map((t) => (\n <div\n key={t.at}\n className=\"absolute inset-y-0 w-0.5 -translate-x-1/2 bg-background\"\n style={{ left: `${Math.min(1, Math.max(0, t.at)) * 100}%` }}\n />\n ))}\n </div>\n );\n\n // The visible figure is the meter's value text, so it is hidden from the accessibility tree\n // rather than read twice.\n const figure = (\n <span aria-hidden className=\"shrink-0 type-body-sm tabular-nums text-foreground\">\n {text}\n </span>\n );\n\n const note = hasNote && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n {crossed && (\n <span id={statusId} className=\"contents\">\n <Status tone={crossed.tone}>{crossed.label}</Status>\n </span>\n )}\n {detail && (\n <span id={detailId} className=\"type-body-sm text-muted-foreground tabular-nums\">\n {detail}\n </span>\n )}\n </div>\n );\n\n if (hideLabel) {\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-3\">\n {bar}\n {figure}\n </div>\n {note}\n </div>\n );\n }\n\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-baseline justify-between gap-3\">\n <span id={labelId} className=\"min-w-0 truncate type-label text-foreground\">\n {label}\n </span>\n {figure}\n </div>\n <div className=\"flex\">{bar}</div>\n {note}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// What a whole is made of (memory: used, cached, buffers, free; a kiln load: bisque, glaze, empty\n// shelves), as one stacked bar over a table. strata-react issue #25 asked for it after\n// jburnhams/homepage hand-rolled one. The rules, from ux-research ui-library/components.md §3.8\n// and patterns.md §5:\n// - Colour is never the only cue. The bar shows proportion at a glance; the table under it says\n// every part's name, amount and share in words, with a swatch that ties the row to its\n// segment. The bar is hidden from screen readers because the table already carries all of it.\n// - The parts stay in the order given, in the bar and the table, so the order is the caller's\n// meaning (used before cached before free), not sorted by size.\n// - Categorical colours come from `--chart-1…5` in order, which palette.mjs checks are told apart\n// by colour-blind readers. A sixth part has no token to take, so it must bring its own colour;\n// more than five parts usually means the small ones belong in an \"Other\" part.\n// - Segments are split by a 2px gap in the ground colour, so two neighbours of similar lightness\n// still read as two.\n// - When the parts do not fill the whole (`total` is larger than their sum), the remainder is the\n// empty track, and it must be named (`restLabel`, such as \"Free\"), so the table can say what the\n// gap is. Neither the remainder nor a part is ever left unlabelled.\n// - Values are formatted by the caller (`formatValue`), as LineChart's `formatY` is, so units stay\n// the product's; shares go through `format.share` unless `formatShare` says otherwise.\n// - A part that is there is never shown as nothing (strata-react issue #43: 2.4 GB of a 512 GB\n// disk read \"0%\"). Its share prints \"<1%\" (`format.share`), and its segment keeps a 4px sliver\n// however small it is; the table carries the exact figure.\n\n/** One part of a `CompositionBar`'s whole. */\nexport type CompositionPart = {\n /** Stable key for the part. */\n key: string;\n label: string;\n value: number;\n /** CSS colour for the segment and swatch. Defaults to the chart token for its position. */\n colour?: string;\n};\n\nexport type CompositionBarProps = {\n /** What the whole is, such as \"Memory\". Shown above the bar and names the table. */\n label: string;\n parts: CompositionPart[];\n formatValue: (value: number) => string;\n /** Formats a part's share of the whole (0 to 1). Defaults to `format.share` (\"<1%\" for a part that rounds to 0). */\n formatShare?: (share: number) => string;\n /** Header of the parts column, for screen readers and over the table. Defaults to \"Part\". */\n partHeader?: string;\n /** Header of the amounts column. Defaults to \"Amount\". */\n valueHeader?: string;\n /** Header of the shares column. Defaults to \"Share\". */\n shareHeader?: string;\n className?: string;\n} & (\n | {\n /** The size of the whole, when the parts do not fill it. The remainder is the empty track. */\n total: number;\n /** What the remainder is called (\"Free\", \"Empty shelves\"). Required with `total`. */\n restLabel: string;\n }\n | { total?: undefined; restLabel?: undefined }\n);\n\nconst MAX_TOKENS = 5;\n\n/** A part's colour: its own, or the chart token for its position. Throws past the fifth token. */\nfunction colourFor(part: CompositionPart, index: number) {\n if (part.colour) return part.colour;\n if (index >= MAX_TOKENS) {\n throw new Error(\n `CompositionBar: part \"${part.label}\" is number ${index + 1}, and there are only ${MAX_TOKENS} chart colours. ` +\n `Combine the smallest parts into one \"Other\" part, or give this part a colour.`,\n );\n }\n return `var(--chart-${index + 1})`;\n}\n\n/** What a whole is made of: a stacked bar for proportion and a table that names every part, its amount and its share, so colour is never the only cue. */\nexport function CompositionBar({\n label,\n parts,\n formatValue,\n formatShare = format.share,\n partHeader = \"Part\",\n valueHeader = \"Amount\",\n shareHeader = \"Share\",\n className,\n ...whole\n}: CompositionBarProps) {\n const captionId = React.useId();\n const sum = parts.reduce((n, p) => n + Math.max(0, p.value), 0);\n const total = Math.max(whole.total ?? sum, sum);\n const rest = whole.total !== undefined ? total - sum : 0;\n const shareOf = (value: number) => (total > 0 ? Math.max(0, value) / total : 0);\n const rows = parts.map((p, i) => ({ ...p, colour: colourFor(p, i), share: shareOf(p.value) }));\n\n return (\n <figure className={cn(\"grid min-w-0 gap-3\", className)}>\n <figcaption id={captionId} className=\"type-label text-foreground\">\n {label}\n </figcaption>\n <div aria-hidden className=\"flex h-3 gap-0.5 overflow-hidden rounded-pill bg-muted\">\n {rows\n .filter((r) => r.value > 0)\n .map((r) => (\n // Grow by share from a zero basis, so the gaps come out of every segment fairly and the\n // parts fill the track exactly. Shares, not raw values: flex-grow factors that sum to\n // less than 1 fill only that fraction of the track (found in review).\n <div key={r.key} className=\"h-full min-w-1\" style={{ flex: `${r.share} 1 0`, background: r.colour }} />\n ))}\n {rest > 0 && <div className=\"h-full min-w-0\" style={{ flex: `${shareOf(rest)} 1 0` }} />}\n </div>\n <table aria-labelledby={captionId} className=\"w-full border-collapse type-body-sm\">\n <thead className=\"sr-only\">\n <tr>\n <th scope=\"col\">{partHeader}</th>\n <th scope=\"col\">{valueHeader}</th>\n <th scope=\"col\">{shareHeader}</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => (\n <tr key={r.key} className=\"border-t border-border first:border-t-0\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n <span aria-hidden className=\"size-3 shrink-0 rounded-control\" style={{ background: r.colour }} />\n {r.label}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(r.value)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(r.share)}\n </td>\n </tr>\n ))}\n {whole.total !== undefined && (\n <tr className=\"border-t border-border\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n {/* The empty track's colour with a hairline, so the swatch reads as \"nothing here\". */}\n <span aria-hidden className=\"size-3 shrink-0 rounded-control border border-border bg-muted\" />\n {whole.restLabel}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(rest)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(shareOf(rest))}\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </figure>\n );\n}\n","import * as React from \"react\";\nimport { Link, type To } from \"react-router\";\nimport { ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A card that is a way to somewhere: an app on a homepage, a project in a list of projects.\n// strata-react issue #25 asked for it after jburnhams/homepage built `AppCard` by hand. A card is\n// right here because each destination *is* a separate object a person picks (ux-research\n// ui-library/patterns.md §3); a section of a screen is not, and gets space and hairlines instead.\n// - The whole card is the target, but it is one link with a short name. The link sits on the\n// title and its `::after` covers the card, so a pointer can press anywhere while a screen reader\n// hears \"Kiln log, link\" and then the description and status marks as its description, instead\n// of a link named with every word on the card. There is one tab stop per card.\n// - Because the whole card is one link, nothing else on it can be interactive (a button or a\n// second link inside a link is invalid and unreachable). `marks` is for `Status` words only.\n// - Status marks are words (`Status`), never a coloured dot in a corner.\n// - `to` is a route in this app (React Router's `Link`); `href` leaves it (a plain anchor) and is\n// marked with an arrow, so a person knows before pressing that they will leave.\n// - Hover and focus change the border and draw the ring around the card, not the title. There is\n// no lift, scale or shadow: elevation is for what floats above the page, and a card on a\n// homepage is pressed many times a day (ux-research ux-character.md, character by frequency).\n\n/** A destination card's props: `to` for a route in this app, or `href` for anywhere else, never both. */\nexport type LinkCardProps = (\n | {\n /** A route in this app, followed with React Router. */\n to: To;\n href?: undefined;\n }\n | {\n /** Somewhere outside this app; the card shows an arrow. */\n href: string;\n to?: undefined;\n }\n) & {\n /** The destination's name, and the link's accessible name. */\n title: string;\n /** One sentence on what is there. Read as the link's description. */\n description?: string;\n /** `Status` words about the destination (\"Running\", \"Updated today\"). Nothing interactive. */\n marks?: React.ReactNode;\n /** The title's element. h3 under a section heading; h2 when the cards are the page's sections. */\n as?: \"h2\" | \"h3\" | \"h4\";\n className?: string;\n};\n\n/** A destination as a card that is one link: its title is the link's name, the description and status marks are its description, and the whole card is the target. */\nexport function LinkCard({ title, description, marks, as: Heading = \"h3\", className, ...destination }: LinkCardProps) {\n const descriptionId = React.useId();\n const marksId = React.useId();\n const describedBy = [description && descriptionId, marks && marksId].filter(Boolean).join(\" \") || undefined;\n const linkClass =\n \"rounded-control outline-none after:absolute after:inset-0 after:rounded-surface\";\n\n return (\n <div\n className={cn(\n \"relative grid content-start gap-1.5 rounded-surface border border-border bg-background p-4 transition-state\",\n \"hover:border-muted-foreground has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring\",\n className,\n )}\n >\n <Heading className=\"flex items-start justify-between gap-3 type-heading text-foreground\">\n {destination.href !== undefined ? (\n <>\n <a href={destination.href} aria-describedby={describedBy} className={linkClass}>\n {title}\n </a>\n <ArrowUpRight aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n </>\n ) : (\n <Link to={destination.to} aria-describedby={describedBy} className={linkClass}>\n {title}\n </Link>\n )}\n </Heading>\n {description && (\n <p id={descriptionId} className=\"type-body-sm text-pretty text-muted-foreground\">\n {description}\n </p>\n )}\n {marks && (\n <div id={marksId} className=\"mt-1.5 flex flex-wrap gap-2\">\n {marks}\n </div>\n )}\n </div>\n );\n}\n\n/** A labelled list of `LinkCard`s in a grid: one column on a phone, up to three on a wide screen. */\nexport function LinkCardList({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <ul aria-label={label} className={cn(\"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3\", className)}>\n {React.Children.toArray(children).map((child, i) => (\n <li key={React.isValidElement(child) && child.key != null ? child.key : i} className=\"grid\">\n {child}\n </li>\n ))}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, History, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// Every view of remote data goes through DataView, and DataView will not type-check without a\n// skeleton and an empty state. Generated UI renders the happy path; this makes the other three\n// states part of the component's signature rather than a review comment.\n//\n// A failed refresh is not a failed read (strata-react issue #26). Once data has arrived, a later\n// refetch that fails (a poll while the server restarts, a Try again on a flaky link) leaves the\n// data on screen with `stale` set: a polite notice above it says what happened, when the data\n// shown was read, and offers Try again. Swapping a whole dashboard for an error panel throws away\n// readings the person was using, and a silent failure lets them act on old numbers as if live, so\n// the data stays and its age is said in words. Only a read that never produced data is an error.\n//\n// The failed read's look is replaceable (strata-react issue #50): an app with a second look (the\n// Tubes viewer, with its own tokens and pill buttons) passes `error`, a render function given the\n// message and the retry, and keeps the state machine (loading, error, ready, stale, empty) rather\n// than copying DataView to change one panel. Whatever it draws sits inside a `role=\"alert\"` box,\n// so the failure is still announced; the default is `LoadError`, exported for reuse.\n\n/** Data still shown after a refresh failed: why the refresh failed, when the data was read, and the Try again. */\nexport type Stale = {\n /** Why the refresh failed, for a person: the sentence an error panel would have shown. */\n message: string;\n /** When the data on screen was read. */\n readAt: Date;\n /** Fetch again. */\n retry: () => void;\n /** A fetch is on its way (a Try again or the next poll). */\n retrying?: boolean;\n};\n\n/** The state of one remote read, for `DataView`: loading, failed with no data, or ready (and `stale` when a later refresh failed). */\nexport type Load<T> =\n | { status: \"loading\" }\n | { status: \"error\"; message: string; retry: () => void }\n | { status: \"ready\"; data: T; stale?: Stale };\n\n/** What a failed read hands to an `error` renderer: the sentence for a person, and the Try again. */\nexport type LoadFailure = { message: string; retry: () => void };\n\n/** The default failed-read panel: the reason on the danger tint, with Try again. Its parent carries `role=\"alert\"`. */\nexport function LoadError({ message, retry, className }: LoadFailure & { className?: string }) {\n return (\n <div className={cn(\"flex flex-wrap items-start gap-3 rounded-surface bg-danger-subtle p-4 text-danger\", className)}>\n <CircleAlert aria-hidden className=\"mt-0.5 size-5 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultError = (failure: LoadFailure) => <LoadError {...failure} />;\n\n/** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */\nexport function DataView<T>({\n state,\n isEmpty,\n skeleton,\n empty,\n children,\n staleNotice = (stale) => <StaleNotice stale={stale} />,\n error = defaultError,\n className,\n}: {\n state: Load<T>;\n /** When the loaded data counts as empty. For arrays, `(rows) => rows.length === 0`. */\n isEmpty: (data: T) => boolean;\n /** Mirrors the final layout, so nothing jumps when data arrives. Not a centred spinner. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it. An `EmptyState`, not an illustration. */\n empty: React.ReactNode;\n children: (data: T) => React.ReactNode;\n /** Shown above the data when a refresh failed. Defaults to a `StaleNotice`; pass one with the product's words for what is old (\"Readings from 13:50\"). */\n staleNotice?: (stale: Stale) => React.ReactNode;\n /** Draws a read that failed with no data, given the message and the retry. Defaults to `LoadError`. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-w-0\", className)} aria-busy={state.status === \"loading\" || undefined}>\n {state.status === \"loading\" && skeleton}\n {state.status === \"error\" && <div role=\"alert\">{error({ message: state.message, retry: state.retry })}</div>}\n {state.status === \"ready\" && (\n <>\n {state.stale && staleNotice(state.stale)}\n {isEmpty(state.data) ? empty : children(state.data)}\n </>\n )}\n </div>\n );\n}\n\n/** When `readAt` was, for a person: the clock time today, else the weekday and time. */\nfunction readTime(readAt: Date, now = new Date()) {\n return readAt.toDateString() === now.toDateString() ? format.clock.format(readAt) : format.shortDay.format(readAt);\n}\n\n/** The notice over data whose refresh failed: what happened, how old the data shown is, and Try again. A polite status, not an alert: nothing was lost. */\nexport function StaleNotice({\n stale,\n shown,\n className,\n}: {\n stale: Stale;\n /** What is old, in the product's words, given when it was read (\"13:50\", or \"Sat 13:50\" before today). Defaults to \"Showing data from 13:50.\" */\n shown?: (when: string) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div role=\"status\" className={cn(\"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\", className)}>\n <History aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">\n {stale.message} {shown ? shown(readTime(stale.readAt)) : `Showing data from ${readTime(stale.readAt)}.`}\n </p>\n <Button size=\"sm\" onClick={stale.retry} disabled={stale.retrying}>\n <RotateCcw aria-hidden />\n {stale.retrying ? \"Trying again…\" : \"Try again\"}\n </Button>\n </div>\n );\n}\n\n// An empty state teaches the next action. No illustration slot exists, on purpose.\n/** An empty state that teaches the next action: a title, a sentence and an action. No illustration slot, on purpose. */\nexport function EmptyState({ title, children, action }: { title: string; children?: React.ReactNode; action?: React.ReactNode }) {\n return (\n <div className=\"grid justify-items-start gap-2 border-y border-border py-6\">\n <p className=\"type-heading\">{title}</p>\n {children && <p className=\"max-w-prose type-body text-muted-foreground\">{children}</p>}\n {action && <div className=\"mt-2\">{action}</div>}\n </div>\n );\n}\n\n/** A placeholder block for a loading layout. Size it with layout classes so it mirrors the final content. */\nexport function Skeleton({ className }: { className?: string }) {\n return <div aria-hidden className={cn(\"rounded-control bg-muted motion-safe:animate-pulse\", className)} />;\n}\n","// Colour rules for `ColorField` (issue #73): reading a typed hex, and the WCAG contrast ratio\n// against what the colour is drawn on, which a user-chosen colour (content, not theme) is checked\n// with. Number parsing and stepping are React Aria's.\n\n/** Reads `#rgb`, `#rrggbb` (with or without the #) as lower-case `#rrggbb`, or null. */\nexport function parseHex(text: string): string | null {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());\n if (!m) return null;\n const h = m[1].toLowerCase();\n return \"#\" + (h.length === 3 ? [...h].map((c) => c + c).join(\"\") : h);\n}\n\nfunction luminance(hex: string): number {\n const v = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));\n return 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];\n}\n\n/** WCAG contrast ratio between two `#rrggbb` colours, 1 to 21. */\nexport function contrastRatio(a: string, b: string): number {\n const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);\n return (hi + 0.05) / (lo + 0.05);\n}\n","import * as React from \"react\";\nimport {\n I18nProvider,\n Input as AriaInput,\n NumberField as AriaNumberField,\n Slider as AriaSlider,\n SliderOutput,\n SliderThumb,\n SliderTrack,\n} from \"react-aria-components\";\nimport { useFieldControl } from \"./field\";\nimport { NBSP, format } from \"../lib/format\";\nimport { contrastRatio, parseHex } from \"../lib/number-input\";\nimport { cn } from \"../lib/utils\";\nimport { controlHeight, type ControlSize } from \"../lib/control\";\n\n// Controls for setting a number or a colour precisely (strata-react issue #73, from moving\n// strata-vid onto Strata: opacity, rotation, volume, bitrate, a line colour). The native ones fail\n// in the same few ways, and each rule below answers one:\n//\n// - `parseFloat(e.target.value)` turns an empty field into NaN. Here a value that is not known is\n// `null`, stays `null`, and prints `format.missing`; a typed value outside the limits is NOT\n// clamped and NOT passed on: React Aria's field runs with `commitBehavior=\"validate\"` (it keeps\n// what was typed instead of snapping 600 to 500), and the control tells the surrounding `Field`\n// what is wrong (\"Enter a value from 0% to 500%.\"), the same place a server's 422 appears. The\n// callback only ever receives a number inside the limits, or null.\n// - The unit lives inside the control, muted. A slider's spoken value carries it (\"40%\", \"90°\")\n// when `Intl` knows the unit (percent, degree, millisecond, megabit-per-second and the like):\n// React Aria builds `aria-valuetext` from an `Intl.NumberFormat`, so \"px\" or \"steps\" are in the\n// printed value and the label but cannot be in the spoken one.\n// - Digits are the locale's: what is printed and what is read back go through `Intl` (React Aria's\n// `NumberParser`), so 12,5 works in a de-DE app, and the message is in the same digits.\n// - Behaviour is React Aria's: arrows step, PageUp/PageDown take ten steps, Home/End jump to the\n// limits, a field commits on Enter and blur. Nothing animates when a value changes: these are\n// dragged and stepped dozens of times a minute (character.md, the frequency budget).\n// - A colour a person picks for their own content (a route's line) is content, not theme, so it is\n// the one place a raw colour value is right; `against` checks it against what it is drawn on.\n// The colour field's text box is ours: React Aria's colour field puts the old colour back when\n// the text is not a colour, where this one says so under the control; the swatch opens the\n// platform picker.\n\nconst box =\n \"flex w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring\";\n\n/** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */\nfunction withUnit(text: string, unit?: string) {\n if (!unit) return text;\n return unit === \"%\" || unit === \"°\" ? text + unit : text + NBSP + unit;\n}\n\n// Units `Intl` can speak, by the symbol an app prints. Anything else is printed but not spoken.\nconst intlUnits: Record<string, string> = {\n \"%\": \"percent\",\n \"°\": \"degree\",\n ms: \"millisecond\",\n s: \"second\",\n kB: \"kilobyte\",\n MB: \"megabyte\",\n GB: \"gigabyte\",\n kbps: \"kilobit-per-second\",\n Mbps: \"megabit-per-second\",\n};\n\nfunction decimalsOf(n: number): number {\n const s = String(n);\n if (s.includes(\"e-\")) return Number(s.split(\"e-\")[1]) + (s.split(\"e-\")[0].split(\".\")[1]?.length ?? 0);\n return s.split(\".\")[1]?.length ?? 0;\n}\n\nfunction useNumberText(locale: string, places: number) {\n return React.useMemo(() => {\n const f = new Intl.NumberFormat(locale, { maximumFractionDigits: places, minimumFractionDigits: 0 });\n return (n: number) => f.format(n);\n }, [locale, places]);\n}\n\nfunction formatOptionsFor(places: number, unit?: string): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = { maximumFractionDigits: places, minimumFractionDigits: 0 };\n const known = unit ? intlUnits[unit] : undefined;\n return known ? { ...base, style: \"unit\", unit: known, unitDisplay: \"narrow\" } : base;\n}\n\n/** Props shared by the number field and the slider. */\nexport type RangeProps = {\n min?: number;\n max?: number;\n /** The size of one arrow-key step. Default 1. */\n step?: number;\n /** The unit shown with the value: \"%\", \"°\", \"Mbps\", \"px\". Spoken too when `Intl` has it (%, °, ms, s, kB, MB, GB, kbps, Mbps). */\n unit?: string;\n /** The locale for digits and the decimal mark. Default the app's `format` locale. */\n locale?: string;\n};\n\n/** Props for `NumberField`. */\nexport type NumberFieldProps = RangeProps & {\n /** The current value; `null` when it is not known (shown as an en dash, not 0). */\n value: number | null;\n /** Receives a number inside the limits, or `null` when the field is cleared. Never NaN, never out of range. */\n onChange: (value: number | null) => void;\n /** Decimal places to show and keep. Default the places in `step` (and `min`). */\n places?: number;\n /** An empty field is an error (\"Enter a value.\") rather than `null`. */\n required?: boolean;\n disabled?: boolean;\n /** Names the control when it is used without a `Field`. */\n \"aria-label\"?: string;\n id?: string;\n name?: string;\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `IconButton` beside it. Default --control-h. */\n size?: ControlSize;\n className?: string;\n};\n\nfunction describeRange(min: number | undefined, max: number | undefined, show: (n: number) => string, unit?: string) {\n const a = min === undefined ? \"\" : withUnit(show(min), unit);\n const b = max === undefined ? \"\" : withUnit(show(max), unit);\n if (min !== undefined && max !== undefined) return `Enter a value from ${a} to ${b}.`;\n if (min !== undefined) return `Enter ${a} or more.`;\n if (max !== undefined) return `Enter ${b} or less.`;\n return \"Enter a number.\";\n}\n\n/** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */\nexport function NumberField({\n value,\n onChange,\n min,\n max,\n step = 1,\n places,\n unit,\n locale = format.locale,\n required = false,\n disabled,\n id: idProp,\n name,\n size = \"default\",\n className,\n \"aria-label\": ariaLabel,\n}: NumberFieldProps) {\n const { field, report } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), min === undefined ? 0 : decimalsOf(min));\n const show = useNumberText(locale, digits);\n const [own, setOwn] = React.useState(false); // invalid, when there is no Field to say so\n const unitId = React.useId();\n // What the field shows. It follows `value`, but also holds an entry we refused, so the person sees\n // (and can correct) what they typed instead of the field snapping back to the old value.\n const [local, setLocal] = React.useState<number>(value ?? Number.NaN);\n const [seen, setSeen] = React.useState(value);\n if (seen !== value) {\n setSeen(value);\n setLocal(value ?? Number.NaN);\n }\n\n const fail = (message: string) => {\n setOwn(true);\n report(message);\n };\n const ok = () => {\n setOwn(false);\n report(undefined);\n };\n\n const handle = (n: number) => {\n setLocal(n);\n if (Number.isNaN(n)) {\n if (required) return fail(\"Enter a value.\");\n ok();\n if (value !== null) onChange(null);\n return;\n }\n if ((min !== undefined && n < min) || (max !== undefined && n > max)) return fail(describeRange(min, max, show, unit));\n ok();\n if (n !== value) onChange(n);\n };\n\n const invalid = field?.invalid || own;\n return (\n <I18nProvider locale={locale}>\n <AriaNumberField\n value={local}\n onChange={handle}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={{ maximumFractionDigits: digits, minimumFractionDigits: 0 }}\n commitBehavior=\"validate\"\n isDisabled={disabled}\n isInvalid={invalid || undefined}\n name={name}\n aria-label={ariaLabel ?? field?.label}\n className={cn(box, controlHeight[size], className)}\n >\n <AriaInput\n id={idProp ?? field?.id}\n placeholder={format.missing}\n aria-describedby={[field?.describedBy, unit ? unitId : undefined].filter(Boolean).join(\" \") || undefined}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n {unit && (\n <span id={unitId} className=\"ml-2 shrink-0 type-body-sm text-muted-foreground\">\n <span aria-hidden>{unit}</span>\n <span className=\"sr-only\">{intlUnits[unit] ? intlUnits[unit].replace(/-/g, \" \") : unit}</span>\n </span>\n )}\n </AriaNumberField>\n </I18nProvider>\n );\n}\n\n/** Props for `Slider`. */\nexport type SliderProps = RangeProps & {\n value: number;\n onChange: (value: number) => void;\n /** Both limits are required: a slider with no ends is not a slider. */\n min: number;\n max: number;\n /** Replace the printed value with a `NumberField` beside the track, so an exact value can be typed. */\n editable?: boolean;\n /** Hide the printed value (when something else beside it already shows it). */\n hideValue?: boolean;\n /** Decimal places in the printed and spoken value. Default the places in `step`. */\n places?: number;\n disabled?: boolean;\n /** Names the slider when it is used without a `Field`. */\n \"aria-label\"?: string;\n className?: string;\n};\n\n/** A slider on React Aria with its current value always printed beside the track (and spoken with the unit when `Intl` knows it); `editable` adds a number field to type an exact value. */\nexport function Slider({\n value,\n onChange,\n min,\n max,\n step = 1,\n unit,\n locale = format.locale,\n editable = false,\n hideValue = false,\n places,\n disabled,\n className,\n \"aria-label\": ariaLabel,\n}: SliderProps) {\n const { field } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), decimalsOf(min));\n const show = useNumberText(locale, digits);\n const name = ariaLabel ?? field?.label ?? \"Value\";\n const text = withUnit(show(value), unit);\n return (\n <I18nProvider locale={locale}>\n <AriaSlider\n value={value}\n onChange={(v) => onChange(v as number)}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={formatOptionsFor(digits, unit)}\n isDisabled={disabled}\n aria-label={name}\n aria-describedby={field?.describedBy}\n className={cn(\"flex min-w-0 items-center gap-3\", className)}\n >\n <SliderTrack className=\"relative flex h-(--control-h) min-w-0 flex-1 cursor-pointer items-center disabled:cursor-not-allowed disabled:opacity-50\">\n {({ state }) => (\n <>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${state.getThumbPercent(0) * 100}%` }} />\n <SliderThumb className=\"top-1/2 size-5 rounded-pill border-2 border-primary bg-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\" />\n </>\n )}\n </SliderTrack>\n {editable ? (\n <NumberField className=\"w-28 shrink-0\" aria-label={`${name}, exact value`} value={value} onChange={(v) => v !== null && onChange(v)} min={min} max={max} step={step} unit={unit} locale={locale} places={digits} required disabled={disabled} />\n ) : (\n !hideValue && (\n <SliderOutput aria-hidden className=\"w-16 shrink-0 text-right type-body-sm tabular-nums text-foreground\">\n {text}\n </SliderOutput>\n )\n )}\n </AriaSlider>\n </I18nProvider>\n );\n}\n\n/** Props for `ColorField`. */\nexport type ColorFieldProps = {\n /** `#rrggbb`, or `null` when no colour is set. */\n value: string | null;\n /** Receives a valid `#rrggbb` (lower case) or `null` when cleared; never a half-typed value. */\n onChange: (value: string | null) => void;\n /** A short list the app suggests, as `#rrggbb`. Pressing one chooses it. */\n suggestions?: readonly string[];\n /** The colour this will be drawn on, `#rrggbb`: a note appears when the contrast would be low. */\n against?: string;\n /** What it is drawn on, in words: \"the map\". Completes the note. */\n againstLabel?: string;\n /** The lowest contrast ratio accepted before the note shows. Default 3, the WCAG minimum for graphics. */\n minContrast?: number;\n disabled?: boolean;\n \"aria-label\"?: string;\n id?: string;\n className?: string;\n};\n\n/** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */\nexport function ColorField({ value, onChange, suggestions, against, againstLabel = \"the background\", minContrast = 3, disabled, id: idProp, className, \"aria-label\": ariaLabel }: ColorFieldProps) {\n const { field, report } = useFieldControl();\n // Named for the `aria-label` or, failing that, the surrounding Field's label, so two colour fields in one panel never share a name (issue #116).\n const label = ariaLabel ?? field?.label;\n const pickerName = label ? `${label}, picker` : \"Colour picker\";\n const [draft, setDraft] = React.useState<string | null>(null);\n const [own, setOwn] = React.useState(false);\n const text = draft ?? value ?? \"\";\n const ratio = value && against ? contrastRatio(value, against) : null;\n\n const commitText = (t: string): boolean => {\n if (t.trim() === \"\") {\n setOwn(false);\n report(undefined);\n if (value !== null) onChange(null);\n return true;\n }\n const hex = parseHex(t);\n if (!hex) {\n setOwn(true);\n report(\"Enter a colour like #1a7f64.\");\n return false;\n }\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n return true;\n };\n\n const pick = (hex: string) => {\n setDraft(null);\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n };\n\n const invalid = field?.invalid || own;\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div className={cn(box, controlHeight.default, \"gap-2 px-2\")} aria-invalid={invalid || undefined}>\n <span className=\"relative size-6 shrink-0 overflow-hidden rounded-control border border-input\">\n {/* The swatch is the chosen colour itself: user content, not a theme role. */}\n <span aria-hidden className={cn(\"absolute inset-0\", value === null && \"bg-muted\")} style={value ? { background: value } : undefined} />\n <input\n type=\"color\"\n aria-label={pickerName}\n value={value ?? \"#000000\"}\n disabled={disabled}\n onChange={(e) => pick(e.target.value)}\n className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n />\n </span>\n <input\n id={idProp ?? field?.id}\n type=\"text\"\n autoComplete=\"off\"\n spellCheck={false}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-describedby={field?.describedBy}\n aria-invalid={invalid || undefined}\n placeholder={format.missing}\n value={text}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n if (draft !== null && commitText(draft)) setDraft(null);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && draft !== null && commitText(draft)) setDraft(null);\n if (e.key === \"Escape\" && draft !== null) {\n setDraft(null);\n setOwn(false);\n report(undefined);\n }\n }}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n </div>\n {suggestions && suggestions.length > 0 && (\n <div role=\"group\" aria-label=\"Suggested colours\" className=\"flex flex-wrap gap-1.5\">\n {suggestions.map((hex) => (\n <button\n key={hex}\n type=\"button\"\n disabled={disabled}\n aria-label={hex}\n aria-pressed={value === hex}\n onClick={() => pick(hex)}\n className=\"size-6 cursor-pointer rounded-control border border-input transition-state aria-pressed:outline-2 aria-pressed:outline-offset-2 aria-pressed:outline-foreground disabled:cursor-not-allowed disabled:opacity-50\"\n style={{ background: hex }}\n />\n ))}\n </div>\n )}\n {ratio !== null && ratio < minContrast && (\n <p className=\"type-body-sm text-warning\">\n Hard to see on {againstLabel}: contrast {format.decimal(ratio)}:1, aim for {format.decimal(minContrast)}:1 or more.\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, Info, TriangleAlert } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { Tone } from \"./status\";\n\n// An alert is one inline sentence about a problem or a fact, where it applies: a failed export\n// under the export, a stale reading above the chart. It is how an error a person must act on is\n// shown, with its recovery as `action`; a toast is not (components.md §3.13, patterns.md §7).\n//\n// Drawn as a pale tint of its tone with its icon and, for `title`, a heavier first line: never a\n// coloured stripe down one side of a rounded box (the tell in ux-slop-taxonomy), and never colour\n// alone, since the icon and the words carry the tone. `role=\"alert\"` interrupts a screen reader,\n// so it is on only when the alert appears in response to something the person just did\n// (`announce`); a banner that is simply there on load is a plain region the reader finds in order.\n\n/** Props for `Alert`. */\nexport type AlertProps = {\n tone: Exclude<Tone, \"neutral\">;\n /** A short first line, when the sentence needs one: \"Export failed\". */\n title?: string;\n /** The sentence, in the product's words: what happened and what to do. */\n children: React.ReactNode;\n /** One recovery, a `Button` (\"Try again\"). */\n action?: React.ReactNode;\n /** It appeared because of something the person just did (a failed submit): announce it at once (`role=\"alert\"`). */\n announce?: boolean;\n className?: string;\n};\n\nconst tones: Record<Exclude<Tone, \"neutral\">, { box: string; icon: IconComponent }> = {\n info: { box: \"bg-info-subtle text-info\", icon: Info },\n success: { box: \"bg-success-subtle text-success\", icon: CircleCheck },\n warning: { box: \"bg-warning-subtle text-warning\", icon: TriangleAlert },\n danger: { box: \"bg-danger-subtle text-danger\", icon: CircleAlert },\n};\n\n/** An inline sentence about a problem or a fact, in a tone with an icon, with one optional action. `announce` makes it `role=\"alert\"` for a result of the person's own action. */\nexport function Alert({ tone, title, children, action, announce = false, className }: AlertProps) {\n const { box, icon: Icon } = tones[tone];\n return (\n <div role={announce ? \"alert\" : \"region\"} aria-label={announce ? undefined : title ?? \"Notice\"} className={cn(\"flex items-start gap-3 rounded-surface px-3 py-2.5\", box, className)}>\n <Icon aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <div className=\"grid min-w-0 flex-1 gap-0.5\">\n {title && <p className=\"type-label\">{title}</p>}\n <div className=\"type-body-sm\">{children}</div>\n </div>\n {action && <div className=\"shrink-0 self-center\">{action}</div>}\n </div>\n );\n}\n","import * as React from \"react\";\n\n// Work the browser does for a while (an export, an upload, a render) has the same shape as a\n// server job: it runs, reports how far it is, and ends finished, failed or cancelled (issue #72).\n// `useClientWork` holds that shape so a screen hands it straight to `JobStatus` and a toast,\n// instead of each screen keeping its own booleans. Cancelling aborts the `signal` the work was\n// given (pass it to `fetch`, or check it between steps) and ends as `cancelled`, never as a\n// failure: an abort is the person's decision, and its error is not reported. Starting again while\n// running is ignored, so a double click does not run the work twice. A stale run (cancelled, then\n// restarted) cannot write over the newer one.\n\n/** What the work is given: a signal that aborts on cancel, and a way to report progress. */\nexport type WorkContext = {\n signal: AbortSignal;\n /** Report items done, and the total when it is known. */\n progress: (current: number, total?: number) => void;\n};\n\n/** Where client work is. */\nexport type WorkPhase = \"idle\" | \"running\" | \"finished\" | \"failed\" | \"cancelled\";\n\n/** The state `useClientWork` returns. */\nexport type ClientWork<T> = {\n phase: WorkPhase;\n current?: number;\n total?: number;\n result?: T;\n error?: unknown;\n /** Runs the work. Ignored while it is already running. */\n start: () => Promise<void>;\n /** Aborts the work's signal; the phase becomes `cancelled`. */\n cancel: () => void;\n /** Back to `idle`, forgetting the result. */\n dismiss: () => void;\n};\n\ntype State<T> = { phase: WorkPhase; current?: number; total?: number; result?: T; error?: unknown };\n\n/** Runs browser-side work with progress, cancel and a clear end state, ready for `JobStatus`. */\nexport function useClientWork<T>(run: (ctx: WorkContext) => Promise<T>): ClientWork<T> {\n const [state, setState] = React.useState<State<T>>({ phase: \"idle\" });\n const controller = React.useRef<AbortController | null>(null);\n const runRef = React.useRef(run);\n runRef.current = run;\n\n const start = React.useCallback(async () => {\n if (controller.current) return;\n const mine = new AbortController();\n controller.current = mine;\n const live = () => controller.current === mine;\n setState({ phase: \"running\" });\n try {\n const result = await runRef.current({\n signal: mine.signal,\n progress: (current, total) => live() && setState((s) => ({ ...s, current, total: total ?? s.total })),\n });\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"finished\", result });\n } catch (error) {\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"failed\", error });\n } finally {\n if (live()) controller.current = null;\n }\n }, []);\n\n const cancel = React.useCallback(() => {\n const c = controller.current;\n if (!c) return;\n c.abort();\n controller.current = null;\n setState({ phase: \"cancelled\" });\n }, []);\n\n const dismiss = React.useCallback(() => {\n if (!controller.current) setState({ phase: \"idle\" });\n }, []);\n\n // Unmounting aborts the run and forgets it, so a remount (Strict Mode's setup, cleanup, setup) can\n // start again and the aborted run can no longer write state.\n React.useEffect(\n () => () => {\n controller.current?.abort();\n controller.current = null;\n },\n [],\n );\n\n return { ...state, start, cancel, dismiss };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle, TriangleAlert, Ban } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Status, type Tone } from \"./status\";\n\n// A job the server runs for a while (syncing sources one after another, an import, a re-index),\n// as the screen that started it shows it (strata-react issue #45, from the Tubes Library screen,\n// which built each part by hand). Three things are true of every such job, and the props make\n// each one impossible to leave out:\n//\n// - Its state is a word, as `Status` is: `words` names running, finished and failed in the\n// product's terms (\"Syncing\", \"Finished\", \"Finished with failures\"), all three required, so a\n// screen cannot forget the end it did not test. Beside the word, `summary` is the app's own\n// sentence (\"Syncing 2 of 3: Night Sky. 42 new videos so far.\").\n// - How far it has got is a bar only when the total is known (`current` of `total`), a\n// `progressbar`, not a `meter`: this is a task moving to done. Without a total there is no bar,\n// because a bar that guesses is worse than the sentence.\n// - When it ends, each item that failed is named with its reason (`failures`), because \"3\n// failed\" alone sends the person hunting. A job that failed as a whole (`failed`, the summary\n// saying why) names no item.\n//\n// It is announced, politely, only when something a person waits for happens: the item changes\n// (`current`) or the job ends. A poll every two seconds that rewrites \"42 new videos so far\" in\n// a live region would talk over everything else, so the visible sentence is not the live region;\n// a separate one carries the word and the sentence at those moments.\n//\n// Work the browser does (an export, an upload, a render; issue #72) uses the same component, so one\n// idea of \"a job\" covers both: `onCancel` shows a Cancel button while it runs (work the person can\n// stop is stoppable), `cancelled` is a fourth ending in neutral (\"Cancelled\": not a failure, nothing\n// to retry), and `onDismiss` shows Dismiss once it has ended so the result does not linger. With no\n// `total` there is no bar, only the turning mark and the sentence, which is the indeterminate case. The spinner turns only\n// while running, the one case where a status mark's data is live. Polling and re-reading what\n// the job changed is `useJob`'s.\n\n/** An item a job could not do, and why, in the product's words. */\nexport type JobFailure = { key: string; label: string; reason: string };\n\n/** A job's three states as words, all required: \"Syncing\", \"Finished\", \"Finished with failures\". */\nexport type JobWords = { running: string; finished: string; failed: string; /** Shown when `cancelled`. Default \"Cancelled\". */ cancelled?: string };\n\n/** The job status's props. */\nexport type JobStatusProps = {\n /** What the job is (\"Library sync\"): names the section and the progress bar. */\n label: string;\n /** The job is still going. */\n running: boolean;\n words: JobWords;\n /** The app's sentence for where the job is or how it went: \"Syncing 2 of 3: Night Sky.\" */\n summary: string;\n /** Items done or being done, with `total`, for the bar. */\n current?: number;\n /** Items in all, when known. No bar without it. */\n total?: number;\n /** Each item that failed, with its reason. Any failure makes a finished job `failed`'s word. */\n failures?: JobFailure[];\n /** The job failed as a whole, for a reason that names no item (the summary says it). */\n failed?: boolean;\n /** Names the list of failures for screen readers. Default \"Failures\". */\n failuresLabel?: string;\n /** The person stopped it. A neutral ending, not a failure. */\n cancelled?: boolean;\n /** Stops the job. Shows a Cancel button while it runs. */\n onCancel?: () => void;\n /** Label of the cancel button. Default \"Cancel\". */\n cancelLabel?: string;\n /** Clears the result. Shows a Dismiss button once the job has ended. */\n onDismiss?: () => void;\n className?: string;\n};\n\nconst Spinner: IconComponent = ({ className, ...props }) => (\n <LoaderCircle {...props} className={cn(className, \"motion-safe:animate-spin\")} />\n);\n\n/** A long-running server job: its state as a required word beside the app's sentence, a progress bar when the total is known, each failure named with its reason, and a polite announcement only when the item changes or the job ends. */\nexport function JobStatus({\n label,\n running,\n words,\n summary,\n current,\n total,\n failures = [],\n failed = false,\n failuresLabel = \"Failures\",\n cancelled = false,\n onCancel,\n cancelLabel = \"Cancel\",\n onDismiss,\n className,\n}: JobStatusProps) {\n const ended: { tone: Tone; icon: IconComponent; word: string } = cancelled\n ? { tone: \"neutral\", icon: Ban, word: words.cancelled ?? \"Cancelled\" }\n : failed\n ? { tone: \"danger\", icon: CircleAlert, word: words.failed }\n : failures.length\n ? { tone: \"warning\", icon: TriangleAlert, word: words.failed }\n : { tone: \"success\", icon: Check, word: words.finished };\n const { tone, icon, word } = running ? { tone: \"info\" as const, icon: Spinner, word: words.running } : ended;\n\n // What is announced changes only with the item or the end, not with every poll's sentence.\n const moment = running ? `running:${current ?? \"\"}` : `ended:${word}`;\n const [said, setSaid] = React.useState({ moment, text: \"\" });\n if (said.moment !== moment) setSaid({ moment, text: `${word}. ${summary}` });\n\n const bar = running && total !== undefined && total > 0 && current !== undefined;\n const done = Math.min(total ?? 0, Math.max(0, current ?? 0));\n\n return (\n <section aria-label={label} className={cn(\"grid min-w-0 gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <Status tone={tone} icon={icon}>\n {word}\n </Status>\n <p className=\"min-w-0 flex-1 type-body-sm text-foreground\">{summary}</p>\n {running && onCancel && (\n <Button size=\"sm\" onPress={onCancel}>\n {cancelLabel}\n </Button>\n )}\n {!running && onDismiss && (\n <Button size=\"sm\" variant=\"ghost\" onPress={onDismiss}>\n Dismiss\n </Button>\n )}\n </div>\n {bar && (\n <div\n role=\"progressbar\"\n aria-label={label}\n aria-valuemin={0}\n aria-valuemax={total}\n aria-valuenow={done}\n aria-valuetext={`${format.integer(done)} of ${format.integer(total)}`}\n className=\"relative h-2 overflow-hidden rounded-pill bg-muted\"\n >\n <div className=\"absolute inset-y-0 left-0\" style={{ width: `${(done / total) * 100}%`, background: \"var(--chart-1)\" }} />\n </div>\n )}\n {!running && failures.length > 0 && (\n <ul aria-label={failuresLabel} className=\"grid gap-1 border-l-2 border-warning pl-3 type-body-sm\">\n {failures.map((f) => (\n <li key={f.key}>\n <span className=\"type-label\">{f.label}</span>\n <span className=\"text-muted-foreground\">: {f.reason}</span>\n </li>\n ))}\n </ul>\n )}\n <p role=\"status\" className=\"sr-only\">\n {said.text}\n </p>\n </section>\n );\n}\n","import * as React from \"react\";\nimport { ImageOff } from \"lucide-react\";\nimport { Skeleton } from \"./data-view\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A photo or crop from an API, in a list, a table cell or a grid (strata-react issue #33, from\n// the Bright Horizons review app, where some crops 404 because the file is missing on disk). A\n// plain <img> gets three things wrong there, and each is a state generated UI leaves out:\n//\n// - it has no size until it loads, so the rows below jump as each one arrives. The box here has\n// its aspect ratio before anything is fetched, and the image is cropped (`cover`) or fitted\n// (`contain`) into it, so nothing moves.\n// - while it loads it is a blank, and on a slow connection a blank reads as \"no photo\". Here it\n// is a `Skeleton`, the same placeholder DataView's loading layouts are made of.\n// - when it fails it is the browser's broken-image icon and the alt text crammed into the box.\n// Here it says what happened in the product's words: `missing` is required (\"Photo not\n// found\"), for the same reason DataView requires `empty`. A record with no photo at all\n// (`src={null}`) shows the same words without a request.\n//\n// `alt` is required too; pass \"\" only when the name beside the thumbnail already says everything\n// it shows. The missing state is an `img` named \"<alt>: <missing>\", so a screen reader hears\n// which photo is gone. Thumbnails come in dozens, so the request waits until the box is near the\n// screen (`useInView`, the hook InfiniteList's sentinel uses, with the same scroll region and a\n// root margin), and once asked for it is not unloaded. `eager` is for the first few on screen.\n// There is no fade-in: a list of thumbnails is seen many times a day (ux-character.md, character\n// by frequency), so the photo simply replaces its skeleton.\n//\n// Two more uses from the Tubes viewer (strata-react issue #51), which drew plain <img>s and lost\n// all of the above:\n//\n// - `children` are drawn above the image in the same positioned box: a video's running time in\n// one corner, \"Saved\" in another. They keep their place while the image loads, fails or is\n// missing, because the box, not the image, holds them. Position them yourself (`absolute\n// bottom-1 right-1`); they are not part of the image's name.\n// - `fallback` replaces the icon and words with the product's own drawing, such as a channel's\n// first letter on a disc for an avatar with no picture. The missing state is still one `img`,\n// named `alt` (with `missing` after it, when given, as \"Night Sky: No picture\"), so a person\n// using a screen reader hears whose picture it is either way. A round avatar is `aspect={1}`\n// with `className=\"rounded-pill\"`.\n\n/** A width-over-height ratio: a number (`1.5`) or a fraction (`\"4/3\"`). */\nexport type AspectRatio = number | `${number}/${number}`;\n\n/** The thumbnail's props. Either `missing` (the words shown when there is no image) or a `fallback` drawing is required. */\nexport type ThumbnailProps = {\n /** The image URL. `null` when the record has no photo: the `missing` words show without a request. */\n src: string | null;\n /** What the photo shows (\"Celadon bowl, front\"). `\"\"` only when the text beside it already says it. */\n alt: string;\n /** Width over height. The box has this shape before the image loads. Default `1`. */\n aspect?: AspectRatio;\n /** `cover` crops to fill the box (default); `contain` fits the whole image in it. */\n fit?: \"cover\" | \"contain\";\n srcSet?: string;\n sizes?: string;\n /** Load at once rather than when near the screen: for the first few above the fold. */\n eager?: boolean;\n /** How far outside the scroll region the request starts (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Layout at the call site: a width (`w-24`, `w-full`), or `rounded-pill` for an avatar. The height follows from `aspect`. */\n className?: string;\n /** Overlays drawn above the image in the same box (a running time, a \"Saved\" badge), in place whether the image has loaded, failed or is missing. */\n children?: React.ReactNode;\n} & (\n | {\n /** What to show when there is no photo or it cannot be loaded, in the product's words: \"Photo not found\". */\n missing: string;\n /** Drawn instead of the icon and `missing` words when there is no image: a letter on a disc for an avatar. */\n fallback?: React.ReactNode;\n }\n | {\n /** Added to the missing state's name after `alt` (\"Night Sky: No picture\"), when given. */\n missing?: string;\n /** Drawn when there is no image or it cannot be loaded: a letter on a disc for an avatar. */\n fallback: React.ReactNode;\n }\n);\n\ntype Phase = \"loading\" | \"loaded\" | \"missing\";\n\nconst ratio = (aspect: AspectRatio) => (typeof aspect === \"number\" ? String(aspect) : aspect.replace(\"/\", \" / \"));\n\n/** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */\nexport function Thumbnail({\n src,\n alt,\n missing,\n aspect = 1,\n fit = \"cover\",\n srcSet,\n sizes,\n eager = false,\n rootMargin = \"200px\",\n className,\n fallback,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (`src` and `srcSet`, since the browser may\n // have loaded a candidate from either), so a new request starts loading again without an effect\n // to reset it, and a late event from the old image cannot mark the new one.\n const request = src ? `${src} ${srcSet ?? \"\"}` : null;\n const [result, setResult] = React.useState<{ request: string; ok: boolean } | null>(null);\n const phase: Phase = !request ? \"missing\" : result?.request === request ? (result.ok ? \"loaded\" : \"missing\") : \"loading\";\n const near = useInView({ active: !eager && !!src, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView;\n\n return (\n <div\n ref={near.ref}\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n aria-busy={phase === \"loading\" || undefined}\n >\n {phase === \"loading\" && <Skeleton className=\"absolute inset-0\" />}\n {src && request && phase !== \"missing\" && requested && (\n <img\n key={request}\n src={src}\n srcSet={srcSet}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={() => setResult({ request, ok: true })}\n onError={() => setResult({ request, ok: false })}\n className={cn(\"absolute inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\", phase === \"loading\" && \"opacity-0\")}\n />\n )}\n {phase === \"missing\" && (\n <div\n role=\"img\"\n aria-label={[alt, missing].filter(Boolean).join(\": \")}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined && \"content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground\",\n )}\n >\n {fallback === undefined ? (\n <>\n <ImageOff aria-hidden className=\"size-4 shrink-0\" />\n <span className=\"type-caption text-balance\">{missing}</span>\n </>\n ) : (\n <div aria-hidden className=\"grid size-full min-h-0 min-w-0\">\n {fallback}\n </div>\n )}\n </div>\n )}\n {children}\n </div>\n );\n}\n\n/** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */\nexport function ThumbnailSkeleton({ aspect = 1, className }: { aspect?: AspectRatio; className?: string }) {\n return (\n <div aria-hidden className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)} style={{ aspectRatio: ratio(aspect) }}>\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\nimport { X } from \"lucide-react\";\nimport { format as defaultFormat, type Format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\n\n// Select many, then act: the state (`useSelection`), and the bar that says how many are chosen and\n// holds what can be done to them (`BulkBar`). `DataTable`'s `selection` prop draws the checkboxes.\n//\n// The selection is pruned to the rows that exist. After a bulk removal, a refetch or a new filter,\n// a key whose row is gone is not counted and not acted on: the bar never says \"3 selected\" over\n// two visible rows, and an action never reaches a row the person cannot see. (Gmail and Linear\n// both drop a selection a filter hides; acting on hidden rows is how a bulk delete surprises.)\n//\n// Shift extends a range from the last row clicked, on every surface (`useSelectRows`), and\n// `initial` chooses a row when it first appears rather than only on mount, so a selection seeded\n// from data still applies once the data arrives (both from strata-react issue #32, a review screen\n// of face crops with the likely matches pre-chosen).\n//\n// The count is the bar's live region, and only the count: it is always mounted, so a screen reader\n// hears \"2 bookings selected\" on each change, and the buttons are outside it, so their names are\n// not read again with every tick. The actions are a labelled group. Per the research, at most one\n// of them is filled (`variant=\"default\"`), named with its verb and count (\"Withdraw 3\"), and a\n// reversible bulk removal goes through `useUndoable` like a single one, not through a confirm.\n\n/** Which rows start chosen: their keys, or a test on each row. Either applies to a row the first time it appears. */\nexport type InitialSelection<T> = Iterable<string> | ((row: T) => boolean);\n\ntype SelectionState = { keys: readonly string[]; seen: ReadonlySet<string>; raw: ReadonlySet<string> };\n\n// Bring the state up to the rows now shown: drop keys whose row has gone, and choose the rows seen\n// for the first time that `initial` names. A row seen before keeps the person's choice, even if it\n// left and came back (it returns unchosen, as it was forgotten when it left).\nfunction reconcile<T>(prev: SelectionState, rows: readonly T[], keys: readonly string[], initial: (row: T, key: string) => boolean): SelectionState {\n const present = new Set(keys);\n const raw = new Set([...prev.raw].filter((k) => present.has(k)));\n const seen = new Set(prev.seen);\n rows.forEach((row, i) => {\n const key = keys[i];\n if (seen.has(key)) return;\n seen.add(key);\n if (initial(row, key)) raw.add(key);\n });\n return { keys, seen, raw };\n}\n\nconst sameKeys = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((k, i) => k === b[i]);\n\n/**\n * Chosen row keys, pruned to the rows that exist, and the calls that change them. Spread into\n * `DataTable`'s or `SelectableGrid`'s `selection` with a `rowLabel`. `initial` (keys, or a test on\n * the row) chooses each row the first time it appears, so a selection seeded from data that loads\n * later, or a next page, still starts right.\n */\nexport function useSelection<T>(rows: readonly T[], rowKey: (row: T) => string, initial: InitialSelection<T> = []) {\n // `initial` is read when a row first appears, so a new function each render is fine.\n const initialRef = React.useRef(initial);\n initialRef.current = initial;\n // Keys are read into a set once per `initial` value, not once per row: a single-use iterable (a\n // generator, `set.values()`) would otherwise be used up by the first row, and an array rebuilt\n // for every row. The set is kept for rows that arrive later.\n const initialKeys = React.useRef<{ source: InitialSelection<T>; keys: ReadonlySet<string> } | undefined>(undefined);\n const test = (row: T, key: string) => {\n const init = initialRef.current;\n if (typeof init === \"function\") return init(row);\n if (initialKeys.current?.source !== init) initialKeys.current = { source: init, keys: new Set(init) };\n return initialKeys.current.keys.has(key);\n };\n const keys = rows.map(rowKey);\n const [state, setState] = React.useState<SelectionState>(() =>\n reconcile({ keys: [], seen: new Set(), raw: new Set() }, rows, keys, test),\n );\n // Adjusted while rendering (React's pattern for state derived from props), not in an effect, so\n // the first paint of new rows already shows them chosen. Compared by key, not by array identity,\n // so `rows={data ?? []}` does not loop.\n let current = state;\n if (!sameKeys(state.keys, keys)) {\n current = reconcile(state, rows, keys, test);\n setState(current);\n }\n const selected = current.raw;\n // rowKey is usually an inline arrow, so it is left out of the dependencies: the rows change.\n const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);\n // A key with no row is never kept, so an action never reaches a row the person cannot see.\n const onChange = React.useCallback(\n (next: Set<string>) =>\n setState((s) => {\n const present = new Set(s.keys);\n return { ...s, raw: new Set([...next].filter((k) => present.has(k))) };\n }),\n [],\n );\n const clear = React.useCallback(() => setState((s) => ({ ...s, raw: new Set() })), []);\n return { selected, selectedRows, count: selected.size, onChange, clear };\n}\n\n/** The part of a selection the surfaces drawing it (`DataTable`, `SelectableGrid`) need. */\ntype SelectionLike<T> = {\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n isSelectable?: (row: T) => boolean;\n};\n\n/**\n * Selecting rows of a surface in the order it shows them: one row, a range with Shift, and all\n * shown. Shared by `DataTable` and `SelectableGrid`, so a range and select-all behave the same on\n * both. `rows` are in display order (after sorting) and include rows a virtualised surface has not\n * rendered.\n *\n * A range runs from the last row clicked (the anchor) to this one, over the selectable rows\n * between, and sets them all to this row's new state, as Gmail and Finder do: Shift-clicking an\n * unchosen row chooses the run, Shift-clicking a chosen one clears it. Every click moves the\n * anchor. An anchor that has left the rows (filtered, removed) makes the next Shift-click a plain\n * one.\n * @internal\n */\nexport function useSelectRows<T>(rows: readonly T[], rowKey: (row: T) => string, selection?: SelectionLike<T>) {\n const anchor = React.useRef<string | undefined>(undefined);\n const keys = selection ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [];\n const chosen = selection ? keys.filter((k) => selection.selected.has(k)).length : 0;\n const allChecked: boolean | \"mixed\" = chosen === 0 ? false : chosen === keys.length ? true : \"mixed\";\n\n const toggle = (key: string, on: boolean, { shiftKey }: { shiftKey: boolean }) => {\n if (!selection) return;\n const next = new Set(selection.selected);\n const from = shiftKey && anchor.current !== undefined ? keys.indexOf(anchor.current) : -1;\n const to = keys.indexOf(key);\n if (from >= 0 && to >= 0) {\n const [a, b] = from < to ? [from, to] : [to, from];\n for (const k of keys.slice(a, b + 1)) {\n if (on) next.add(k);\n else next.delete(k);\n }\n } else if (on) next.add(key);\n else next.delete(key);\n anchor.current = key;\n selection.onChange(next);\n };\n\n // A full or mixed box clears what is shown; an empty one selects every selectable row shown.\n // Keys outside `rows` (filtered away) are left as they are.\n const toggleAll = () => {\n if (!selection) return;\n const next = new Set(selection.selected);\n if (allChecked === false) keys.forEach((k) => next.add(k));\n else keys.forEach((k) => next.delete(k));\n selection.onChange(next);\n };\n\n // A range React Aria makes itself (Shift on a row press) moves the anchor too, so the next\n // Shift-click on a checkbox runs from where the last press was, whichever path it came by.\n const setAnchor = (key: string | null) => {\n if (key !== null) anchor.current = key;\n };\n\n return { toggle, setAnchor, all: { checked: allChecked, toggle: toggleAll, disabled: keys.length === 0 } };\n}\n\n/** The bar for a selection: a polite live count (\"2 bookings selected\"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */\nexport function BulkBar({\n count,\n noun,\n onClear,\n children,\n format = defaultFormat,\n className,\n}: {\n count: number;\n /** What is chosen, singular, or singular and plural: `\"booking\"`, `[\"person\", \"people\"]`. */\n noun: string | [one: string, many: string];\n onClear: () => void;\n /** The actions. At most one filled button, named with its verb and count; while the bar is up it is the view's only filled button, so the screen's own primary goes to `outline`. */\n children: React.ReactNode;\n /** The product's formatters, for the count's figures and plural. Default en-GB. */\n format?: Format;\n className?: string;\n}) {\n const [one, many] = typeof noun === \"string\" ? [noun, `${noun}s`] : noun;\n const label = `${format.count(count, one, many)} selected`;\n return (\n <div\n className={cn(\n count > 0 && \"flex flex-wrap items-center gap-x-4 gap-y-2 rounded-surface bg-surface-sunken py-1.5 pr-1.5 pl-3\",\n className,\n )}\n >\n <p aria-live=\"polite\" className={count > 0 ? \"type-label tabular-nums\" : \"sr-only\"}>\n {count > 0 ? label : `No ${many} selected`}\n </p>\n {count > 0 && (\n <div role=\"group\" aria-label={`Actions for the selected ${many}`} className=\"flex flex-1 flex-wrap items-center gap-2\">\n {children}\n <Button size=\"sm\" variant=\"ghost\" className=\"ml-auto\" onClick={onClear}>\n <X aria-hidden />\n Clear selection\n </Button>\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ChevronRight } from \"lucide-react\";\nimport { useSearchParams } from \"react-router\";\nimport { cn } from \"../lib/utils\";\n\n// Show more of one thing in place: a batch's faces under its row in a history list, a firing's\n// pieces under its line in the log. Strata issue #34, from an app that wrote its own <details>.\n//\n// Not <details>. A closed <details> still mounts its content, so every row's detail component\n// runs, and a list of forty batches makes forty requests on load for bodies nobody opened. Here\n// the body is mounted only while it is open: a `useLoad` inside it runs on the first open, and on\n// a later open the query cache answers at once. Closed, nothing of the body is in the DOM.\n//\n// The trigger is a native button (Enter and Space, focus outline from the base layer) with\n// `aria-expanded`, and `aria-controls` naming the body while it exists (the WAI-ARIA disclosure\n// pattern). Focus stays on the button through open and close, so a keyboard user walks a list of\n// rows with Tab and opens each in place. The summary is the button's name, so it holds text and\n// marks (a Status, a count), never controls; actions for the row go in `actions`, beside it.\n//\n// No height animation: people open rows in a list many times a session, and character by\n// frequency (ux-research ux-character.md) gives frequent actions no motion. The chevron turns\n// with the state, which is the only signal besides the body itself.\n//\n// Many disclosures over one list share their state through `useExpanded`, which can keep it in\n// the URL (`?open=f-0412`), so an opened row survives a reload and can be linked. `DataTable`'s\n// `expansion` prop draws the same thing as a detail row under a table row.\n\n/** Open and closed disclosure state: controlled with `open` and `onOpenChange`, or uncontrolled from `defaultOpen`. */\nexport type DisclosureOpenProps =\n | { open: boolean; onOpenChange: (open: boolean) => void; defaultOpen?: never }\n | { open?: never; onOpenChange?: (open: boolean) => void; defaultOpen?: boolean };\n\nexport type DisclosureProps = DisclosureOpenProps & {\n /** The always-visible line, and the button's accessible name: text and marks, no controls. */\n summary: React.ReactNode;\n /** Mounted only while open, so a request inside runs when the person opens it. */\n children: React.ReactNode;\n /** Controls for the row (a `RowAction`), beside the summary and outside its button. */\n actions?: React.ReactNode;\n className?: string;\n};\n\n/** Shows more of one thing in place: a button with `aria-expanded` around `summary`, and a body mounted only while open (so a request inside it runs on first open). Controlled with `open`/`onOpenChange` or `useExpanded`, or uncontrolled with `defaultOpen`. */\nexport function Disclosure({ summary, children, actions, open, defaultOpen = false, onOpenChange, className }: DisclosureProps) {\n const [own, setOwn] = React.useState(defaultOpen);\n const isOpen = open ?? own;\n const bodyId = React.useId();\n const toggle = () => {\n if (open === undefined) setOwn(!isOpen);\n onOpenChange?.(!isOpen);\n };\n return (\n <div className={cn(\"min-w-0\", className)}>\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n aria-expanded={isOpen}\n aria-controls={isOpen ? bodyId : undefined}\n onClick={toggle}\n className=\"-mx-1 flex min-h-(--control-h-sm) min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-control px-1 text-left hover:bg-muted\"\n >\n <Chevron open={isOpen} />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </button>\n {actions && <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>}\n </div>\n {isOpen && (\n <div id={bodyId} className=\"pt-2 pb-3 pl-6\">\n {children}\n </div>\n )}\n </div>\n );\n}\n\n/** The disclosure chevron: points right when closed, down when open. Shared with `DataTable`'s row toggle. */\nexport function Chevron({ open, className }: { open: boolean; className?: string }) {\n return <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", open && \"rotate-90\", className)} />;\n}\n\n/** Which of many disclosures are open, by key: spread into `DataTable`'s `expansion`, or read with `isOpen`/`setOpen` for a list of `Disclosure`s. */\nexport type Expanded = {\n /** Keys of the open items. */\n expanded: ReadonlySet<string>;\n /** Replaces the open set. `DataTable` calls this. */\n onChange: (next: Set<string>) => void;\n isOpen: (key: string) => boolean;\n setOpen: (key: string, open: boolean) => void;\n collapseAll: () => void;\n};\n\nexport type ExpandedOptions = {\n /** Keep the open keys in this URL search parameter (`?open=a&open=b`), so an opened row can be linked and survives a reload. Needs a React Router context. */\n param?: string;\n /** Keys open at first. Ignored with `param`: there the URL says what is open, so a link that opens a row carries it. */\n initial?: Iterable<string>;\n /** Opening one closes the others (an accordion). Default false: people compare two rows. */\n single?: boolean;\n};\n\n/** Shared open state for the disclosures of one list or table, optionally kept in the URL (`param`). */\nexport function useExpanded(options: ExpandedOptions = {}): Expanded {\n // One of two hooks, chosen by whether `param` is given; a screen does not switch between the two\n // while mounted (as with DataTable's `sortParam`), so the hook order is stable.\n return options.param ? useUrlExpanded(options.param, options) : useLocalExpanded(options);\n}\n\nfunction api(expanded: ReadonlySet<string>, set: (next: Set<string>) => void, single?: boolean): Expanded {\n return {\n expanded,\n // With `single`, a change that opens a key keeps only that key, so `DataTable` (which calls\n // onChange with the whole set) gets the accordion too, not only `setOpen`.\n onChange: (next) => {\n const opened = single ? [...next].filter((k) => !expanded.has(k)) : [];\n set(opened.length ? new Set([opened[opened.length - 1]]) : next);\n },\n isOpen: (key) => expanded.has(key),\n setOpen: (key, open) => {\n const next = single ? new Set<string>() : new Set(expanded);\n if (open) next.add(key);\n else next.delete(key);\n set(next);\n },\n collapseAll: () => set(new Set()),\n };\n}\n\nfunction useLocalExpanded({ initial = [], single }: ExpandedOptions): Expanded {\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set(initial));\n return React.useMemo(() => api(expanded, setExpanded, single), [expanded, single]);\n}\n\nfunction useUrlExpanded(param: string, { single }: ExpandedOptions): Expanded {\n const [params, setParams] = useSearchParams();\n const fromUrl = params.getAll(param);\n const joined = fromUrl.join(\"\\u0000\");\n // `fromUrl` is a new array each render; its joined form is the dependency.\n const expanded = React.useMemo<ReadonlySet<string>>(() => new Set(fromUrl), [joined]);\n const set = React.useCallback(\n (next: Set<string>) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.delete(param);\n for (const k of next) out.append(param, k);\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return React.useMemo(() => api(expanded, set, single), [expanded, set, single]);\n}\n","import * as React from \"react\";\nimport { ArrowDown, ArrowUp, ArrowUpDown } from \"lucide-react\";\nimport {\n createSortedRowModel,\n flexRender,\n rowSortingFeature,\n tableFeatures,\n useTable,\n type ColumnDef,\n type SortingState,\n} from \"@tanstack/react-table\";\nimport {\n Button as AriaButton,\n Cell as AriaCell,\n Column as AriaColumn,\n Row as AriaRow,\n Table as AriaTable,\n TableBody,\n TableHeader,\n TableLayout,\n Virtualizer,\n type Selection,\n} from \"react-aria-components\";\nimport { useSearchParams } from \"react-router\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { TableSelectionCheckbox, useShiftNote } from \"./checkbox\";\nimport { useSelectRows } from \"./selection\";\nimport { Chevron } from \"./disclosure\";\n\n// The table real product screens use: 12px muted sentence-case headers, row rules (no zebra),\n// numbers right-aligned in tabular figures, one status mark and at most one action per row.\n//\n// The split (Jonathan, 2026-11-12): React Aria's Table draws it and owns what a person does with it\n// (focus and arrow-key navigation, a header that sorts, selection, row and cell semantics for screen\n// readers), and TanStack Table owns the data model (here the sort: `useTable` with the row-sorting\n// feature, so the data model can grow pagination, filtering or grouping without touching the markup).\n// From `virtualizeFrom` rows React Aria's Virtualizer with `TableLayout` draws only the visible rows\n// and keeps the header in place (a table with no detail rows uses a fixed 41px row; one with them\n// measures its rows). The column API stays small on purpose (key, header, cell, numeric, sort), so a\n// screen reads as a list of decisions about columns, not as table plumbing. `sortParam` keeps the\n// sort in the URL (?sort=when.desc) so a sorted view can be linked and survives a reload.\n//\n// A table is a `grid`, its rows `row`s and its cells `gridcell`s (the first column is the row\n// header, which React Aria requires): that is the role the keyboard model belongs to. A sortable\n// header is the column header itself, pressed or Enter: `aria-sort` is \"none\" until it is sorted.\n//\n// Selection is opt-in (`selection`), because checkboxes belong only where a bulk action exists\n// (one of 23 real product screens had them; a checkbox on every row is a generated-UI tell). When\n// it is on, the first column is a checkbox per row (React Aria's selection checkbox), named from the\n// row (`rowLabel` is required), disabled where `isSelectable` says no; the header's \"Select all shown\"\n// covers the selectable rows in `rows` (all of them, not only the rendered ones of a virtualised\n// table) and is mixed when some are chosen, and then clears them. Only the checkbox or Space\n// chooses a row: a click on a cell does nothing to the selection. Shift-click on a checkbox (or\n// Shift+Space) chooses or clears the run from the last row clicked, in the sorted order shown\n// (`useSelectRows`, shared with `SelectableGrid`; React Aria extends a range on a row press, but a\n// checkbox always toggles one row). Selected rows take the sunken fill, not a ring, so a selection\n// never reads as focus. The table only draws the selection; the state is the caller's, usually\n// `useSelection`, and the actions live in a `BulkBar`.\n//\n// Expansion is opt-in too (`expansion`): a row opens a detail row under it, for what belongs to\n// the row but would crowd the table (a firing's pieces, a batch's faces). It follows `Disclosure`:\n// the toggle is a button with `aria-expanded`, named for what it shows (`rowLabel`, \"Pieces in\n// firing 412\"), and the detail is mounted only while open, so a `useLoad` inside it runs on the\n// first open and not for every row on load. The detail is one more row of the grid, spanning the\n// data columns and starting under the first of them, with no rule between it and its row; it can\n// be focused but never chosen. The toggle does not carry `aria-controls`: a grid cell has no DOM id\n// to point at. State is the caller's, usually `useExpanded` (which can keep it in the URL).\n//\n// Missing values (strata-react issue #47, from the Tubes Library table): a column that gives\n// `value` gets a typed sort (numbers, then text in the locale's order with numbers in it read as\n// numbers, then dates) and a placeholder for a row whose value is `null` or `undefined`: an en\n// dash in the muted ink, named \"No value\" for a screen reader, or the column's `missing` word\n// where the word carries meaning (\"Never\"). Missing rows sort after every real value in both\n// directions, because \"not known\" is not \"smallest\"; a column's own `sort` still decides the\n// order among the rows that have a value. Without `value` a column works as before.\n\n/** What a column's `value` may be: a number, text or a date, or `null`/`undefined` when the row has none. */\nexport type CellValue = number | string | Date | null | undefined;\n\nexport type Column<T> = {\n key: string;\n header: string;\n /** Right-aligns and sets tabular figures. Use for every quantity. */\n numeric?: boolean;\n /** Orders two rows. With `value`, it orders only rows that have one (missing ones go last); `false` turns off `value`'s default sort. */\n sort?: ((a: T, b: T) => number) | false;\n /** What the cell shows when the row's `value` is missing, where the word carries meaning (\"Never\"). Default an en dash. */\n missing?: string;\n /** Cells that may hold long text get truncated rather than stretching the table. */\n truncate?: boolean;\n /** Keep the header for screen readers only, as for a column of row actions. `header` still names it. */\n hideHeader?: boolean;\n className?: string;\n} & (\n | {\n cell: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value?: (row: T) => CellValue;\n }\n | {\n /** How a row with a value is drawn. Default: numbers through `format.decimal`, dates through `format.date`, text as it is. */\n cell?: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value: (row: T) => CellValue;\n }\n);\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" });\nconst kind = (v: number | string | Date) => (typeof v === \"number\" ? 0 : typeof v === \"string\" ? 1 : 2);\n\n/** Orders two present values: numbers, then text (locale order, numbers in text read as numbers), then dates. */\nfunction compareValues(a: number | string | Date, b: number | string | Date) {\n if (kind(a) !== kind(b)) return kind(a) - kind(b);\n if (typeof a === \"string\") return collator.compare(a, b as string);\n return Number(a) - Number(b);\n}\n\n/** A cell with no value: the column's word, or an en dash named \"No value\" for a screen reader. */\nfunction Missing({ word }: { word?: string }) {\n return word ? (\n <span className=\"text-muted-foreground\">{word}</span>\n ) : (\n <span className=\"text-muted-foreground\">\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">No value</span>\n </span>\n );\n}\n\nfunction drawValue(v: number | string | Date) {\n return typeof v === \"number\" ? format.decimal(v) : v instanceof Date ? format.date(v) : v;\n}\n\n/** Row selection for a `DataTable`: the chosen row keys, how to change them, and how to name each row's checkbox. */\nexport type RowSelection<T> = {\n /** Keys (from `rowKey`) of the chosen rows. */\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row in its checkbox (\"Select <rowLabel>\"). Required: an unnamed checkbox is a column of \"checkbox, not checked\". */\n rowLabel: (row: T) => string;\n /** Rows that cannot be chosen get a disabled checkbox and are left out of select-all. Default: every row. */\n isSelectable?: (row: T) => boolean;\n};\n\n/** Row expansion for a `DataTable`: the open row keys, how to change them, how to name each toggle, and the detail to show. */\nexport type RowExpansion<T> = {\n /** Keys (from `rowKey`) of the open rows. */\n expanded: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row's toggle by what it shows: \"Pieces in firing 412\". Its state is `aria-expanded`, so the name stays the same open or closed. */\n rowLabel: (row: T) => string;\n /** The row's detail, mounted only while it is open. Return an element whose component makes any request, so the request runs on open. */\n detail: (row: T) => React.ReactNode;\n /** Rows with nothing to show get no toggle. Default: every row. */\n isExpandable?: (row: T) => boolean;\n};\n\nexport type Sort = { key: string; dir: \"ascending\" | \"descending\" };\n\nexport type DataTableProps<T> = {\n /** Names the table for screen readers and labels the scroll region. */\n caption: string;\n columns: Column<T>[];\n rows: T[];\n rowKey: (row: T) => string;\n initialSort?: Sort;\n /** Keep the sort in this URL search parameter. Needs a React Router context. */\n sortParam?: string;\n /** Row count from which only the visible rows render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n /** Adds a checkbox column and \"Select all shown\". Use only where a `BulkBar` acts on the selection. */\n selection?: RowSelection<T>;\n /** Adds a toggle per row that opens a detail row under it. Spread `useExpanded()` in with a `rowLabel` and `detail`. */\n expansion?: RowExpansion<T>;\n className?: string;\n};\n\ntype SortState = [Sort | undefined, (next: Sort) => void];\n\nfunction useLocalSort(initial?: Sort): SortState {\n const [sort, setSort] = React.useState(initial);\n return [sort, setSort];\n}\n\n/** Reads a sort from its URL form (`pieces.desc`). */\nexport function parseSort(value: string | null): Sort | undefined {\n if (!value) return undefined;\n const [key, dir] = value.split(\".\");\n if (!key) return undefined;\n return { key, dir: dir === \"desc\" ? \"descending\" : \"ascending\" };\n}\n\n/** Writes a sort in its URL form (`pieces.desc`). */\nexport function serialiseSort(sort: Sort) {\n return `${sort.key}.${sort.dir === \"descending\" ? \"desc\" : \"asc\"}`;\n}\n\nfunction useUrlSort(param: string, initial?: Sort): SortState {\n const [params, setParams] = useSearchParams();\n const sort = parseSort(params.get(param)) ?? initial;\n const set = React.useCallback(\n (next: Sort) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.set(param, serialiseSort(next));\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return [sort, set];\n}\n\n/** A table on React Aria's Table with TanStack Table's data model: muted headers, row rules, right-aligned tabular numbers, sortable headers with `aria-sort`, virtualised from `virtualizeFrom` rows, sort optionally kept in the URL (`sortParam`). */\nexport function DataTable<T>(props: DataTableProps<T>) {\n // Two thin wrappers so each calls its hooks unconditionally.\n return props.sortParam ? <UrlSortedTable {...props} sortParam={props.sortParam} /> : <LocalSortedTable {...props} />;\n}\n\nfunction LocalSortedTable<T>(props: DataTableProps<T>) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useLocalSort(props.initialSort)} />;\n}\n\nfunction UrlSortedTable<T>(props: DataTableProps<T> & { sortParam: string }) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useUrlSort(props.sortParam, props.initialSort)} />;\n}\n\n// The one TanStack feature in use for now: sorting, on the client. TanStack Table 9 is tree-shaken by feature, so\n// nothing else (pagination, filtering, TanStack's own selection or expansion) is bundled.\nconst features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel() });\n// TanStack Table 9 requires object or array rows. Every row a DataTable draws is a record, but the\n// public `T` stays unconstrained so an app's row types need no change: the cast is in the two wrappers.\ntype Rec = Record<string, any>; // TanStack's own RowData\n\nfunction Table<T extends Rec>({\n caption,\n columns,\n rows,\n rowKey,\n sortState: [sort, setSort],\n virtualizeFrom = 100,\n maxHeight = 480,\n selection,\n expansion,\n className,\n}: DataTableProps<T> & { sortState: SortState }) {\n const defs = React.useMemo<ColumnDef<typeof features, T, unknown>[]>(\n () =>\n columns.map((c): ColumnDef<typeof features, T, unknown> => {\n const { value, sort } = c;\n if (!value) {\n return {\n id: c.key,\n // TanStack only sorts columns with an accessor; the row itself is enough, since the\n // column's own comparator does the work.\n accessorFn: (row) => row,\n header: c.header,\n cell: (info) => c.cell?.(info.row.original),\n enableSorting: Boolean(sort),\n sortFn: sort ? (a, b) => sort(a.original, b.original) : undefined,\n };\n }\n // The accessor is the value, with null as undefined, so TanStack's `sortUndefined: \"last\"`\n // keeps missing rows at the end whichever way the column is sorted (it applies before the\n // direction is). The comparator then sees only rows that have a value.\n return {\n id: c.key,\n accessorFn: (row) => value(row) ?? undefined,\n header: c.header,\n cell: (info) => {\n const v = value(info.row.original);\n if (v == null) return <Missing word={c.missing} />;\n return c.cell ? c.cell(info.row.original) : drawValue(v);\n },\n enableSorting: sort !== false,\n sortUndefined: \"last\",\n sortFn: sort\n ? (a, b) => sort(a.original, b.original)\n : (a, b) => compareValues(a.getValue<number | string | Date>(c.key), b.getValue<number | string | Date>(c.key)),\n };\n }),\n [columns],\n );\n\n const sortable = (c: Column<T>) => (c.value ? c.sort !== false : Boolean(c.sort));\n const sorting: SortingState = sort && columns.some((c) => c.key === sort.key && sortable(c))\n ? [{ id: sort.key, desc: sort.dir === \"descending\" }]\n : [];\n\n const table = useTable({\n features,\n data: rows,\n columns: defs,\n state: { sorting },\n getRowId: (row) => rowKey(row),\n // No pagination here, and expansion is the caller's state, not TanStack's: nothing to reset. Left on, TanStack resets the page\n // index whenever `rows` is a new array; a screen that filters its rows on every render (the\n // kiln room after Withdraw) then re-renders forever and the tab freezes. Found by the\n // example app's visual suite, which jsdom did not show.\n autoResetAll: false,\n });\n\n const modelRows = table.getRowModel().rows;\n const canExpand = (row: T) => expansion?.isExpandable?.(row) ?? true;\n const virtual = modelRows.length >= virtualizeFrom;\n const lead = (selection ? 1 : 0) + (expansion ? 1 : 0);\n\n // Selection is React Aria's: its checkboxes (`slot=\"selection\"`), its Space and Shift-range\n // keys, its select-all. We translate to and from our `RowSelection`, which holds keys of rows\n // only (an open detail row is a row of the grid too, and is never chosen).\n const shownKeys = React.useMemo(() => new Set(modelRows.map((r) => r.id)), [modelRows]);\n const selectableKeys = modelRows.filter((r) => selection?.isSelectable?.(r.original) ?? true).map((r) => r.id);\n const detailKey = (id: string) => `${id}\\u0000detail`;\n const disabledKeys = React.useMemo(() => {\n const keys: string[] = [];\n for (const r of modelRows) {\n if (selection && !(selection.isSelectable?.(r.original) ?? true)) keys.push(r.id);\n if (expansion && canExpand(r.original)) keys.push(detailKey(r.id));\n }\n return keys;\n // canExpand reads `expansion`.\n }, [modelRows, selection, expansion]);\n // Shift-click on a checkbox extends a range from the last one clicked (issue #32). React Aria\n // extends on a row press and Shift+Space, but a checkbox always toggles one row, so the range is\n // still ours: Shift is noted on the press, and a change of exactly one row is a click.\n const shift = useShiftNote();\n // The row last pressed (React Aria marks each row with `data-key`), to anchor a range it extended itself.\n const pressed = React.useRef<string | null>(null);\n const notePress = (e: React.SyntheticEvent) => void (pressed.current = (e.target as HTMLElement).closest(\"[data-key]\")?.getAttribute(\"data-key\") ?? null);\n const sortedRows = React.useMemo(() => modelRows.map((r) => r.original), [modelRows]);\n const select = useSelectRows(sortedRows, rowKey, selection);\n const changeSelection = (next: Selection) => {\n if (!selection) return;\n if (next !== \"all\") {\n const nextShown = new Set([...next].map(String).filter((k) => shownKeys.has(k)));\n const added = [...nextShown].filter((k) => !selection.selected.has(k));\n const removed = [...selection.selected].filter((k) => shownKeys.has(k) && !nextShown.has(k));\n if (added.length + removed.length === 1) {\n select.toggle(added[0] ?? removed[0], added.length === 1, shift.take());\n return;\n }\n select.setAnchor(pressed.current);\n }\n // What the table does not show (filtered away) is left as it is, as `useSelection` prunes it.\n const outside = [...selection.selected].filter((k) => !shownKeys.has(k));\n // React Aria's select-all chooses everything when only some are chosen; a mixed box clears\n // what is shown here (Gmail's rule, kept from before), so \"all\" over a part-chosen set clears.\n const chosen = selectableKeys.filter((k) => selection.selected.has(k)).length;\n const picked =\n next === \"all\" ? (chosen > 0 && chosen < selectableKeys.length ? [] : selectableKeys) : [...next].map(String).filter((k) => shownKeys.has(k));\n selection.onChange(new Set([...outside, ...picked]));\n };\n\n const grid = (\n <AriaTable\n aria-label={caption}\n selectionMode={selection ? \"multiple\" : \"none\"}\n selectionBehavior=\"toggle\"\n selectedKeys={selection ? new Set([...selection.selected].filter((k) => shownKeys.has(k))) : undefined}\n onSelectionChange={changeSelection}\n disabledKeys={disabledKeys}\n sortDescriptor={sort && columns.some((c) => c.key === sort.key && sortable(c)) ? { column: sort.key, direction: sort.dir } : undefined}\n onSortChange={(d) => setSort({ key: String(d.column), dir: d.direction })}\n className={cn(\"w-full border-collapse type-body-sm outline-none\", virtual && \"overflow-auto\")}\n style={virtual ? { maxHeight } : undefined}\n >\n <TableHeader className={cn(virtual && \"bg-background\")}>\n {selection && (\n <AriaColumn id={SELECT} textValue=\"Select all shown\" width={32} className=\"w-8 py-2 pr-2 text-left align-bottom outline-offset-[-2px]\">\n <TableSelectionCheckbox label=\"Select all shown\" className=\"-my-1\" disabled={selectableKeys.length === 0} />\n </AriaColumn>\n )}\n {expansion && (\n <AriaColumn id={EXPAND} textValue=\"Details\" width={40} className=\"w-10 py-2 pr-2 outline-offset-[-2px]\">\n <span className=\"sr-only\">Details</span>\n </AriaColumn>\n )}\n {columns.map((c, i) => (\n <AriaColumn\n key={c.key}\n id={c.key}\n textValue={c.header}\n // React Aria requires a row header; the first data column is the row's name.\n isRowHeader={i === 0}\n allowsSorting={sortable(c)}\n // Widths apply only to a virtualised table (a plain one sizes its columns to their\n // content): numbers take less than text. `last:pr-0` would match every cell of a\n // virtualised table, where each sits alone in a wrapper, so the last column is named.\n width={c.numeric ? \"0.6fr\" : \"1fr\"}\n className={cn(\n \"py-2 text-left align-bottom type-caption font-normal text-muted-foreground outline-offset-[-2px]\",\n i < columns.length - 1 && \"pr-4\",\n c.numeric && \"text-right\",\n )}\n >\n {({ allowsSorting, sortDirection }) => {\n const Icon = sortDirection === \"ascending\" ? ArrowUp : sortDirection === \"descending\" ? ArrowDown : ArrowUpDown;\n const label = c.hideHeader ? <span className=\"sr-only\">{c.header}</span> : c.header;\n return allowsSorting ? (\n <span\n className={cn(\n \"-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-control px-1 transition-state hover:text-foreground\",\n c.numeric && \"flex-row-reverse\",\n sortDirection && \"text-foreground\",\n )}\n >\n {label}\n <Icon aria-hidden className={cn(\"size-3.5\", !sortDirection && \"opacity-50\")} />\n </span>\n ) : (\n label\n );\n }}\n </AriaColumn>\n ))}\n </TableHeader>\n <TableBody>\n {modelRows.flatMap((row) => {\n const open = (expansion?.expanded.has(row.id) ?? false) && canExpand(row.original);\n const cells = new Map(row.getAllCells().map((cell) => [cell.column.id, cell]));\n const items = [\n <AriaRow\n key={row.id}\n id={row.id}\n textValue={selection?.rowLabel(row.original) ?? expansion?.rowLabel(row.original) ?? row.id}\n // A row's own press does nothing: only its checkbox, or Space, chooses it, so a click on\n // a cell never changes the selection (React Aria's \"toggle\" would otherwise make every row a switch).\n onAction={selection ? noop : undefined}\n className={cn(\"border-t border-border outline-offset-[-2px] selected:bg-surface-sunken\", open && \"selected:bg-surface-sunken\")}\n >\n {selection && (\n <AriaCell className=\"w-8 py-2.5 pr-2 align-middle\">\n <TableSelectionCheckbox label={`Select ${selection.rowLabel(row.original)}`} className=\"-my-0.5\" />\n </AriaCell>\n )}\n {expansion && (\n <AriaCell className=\"w-10 py-2.5 pr-2 align-middle\">\n {canExpand(row.original) && (\n <AriaButton\n aria-expanded={open}\n aria-label={expansion.rowLabel(row.original)}\n onPress={() => {\n const next = new Set(expansion.expanded);\n if (open) next.delete(row.id);\n else next.add(row.id);\n expansion.onChange(next);\n }}\n className=\"-my-1.5 grid size-(--control-h-sm) cursor-pointer place-items-center rounded-control hover:bg-muted\"\n >\n <Chevron open={open} />\n </AriaButton>\n )}\n </AriaCell>\n )}\n {columns.map((c, i) => {\n const cell = cells.get(c.key)!;\n return (\n <AriaCell\n key={c.key}\n className={cn(\n \"py-2.5 align-middle\",\n i < columns.length - 1 && \"pr-4\",\n c.numeric && \"text-right tabular-nums\",\n c.truncate && \"max-w-48 truncate\",\n c.className,\n )}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </AriaCell>\n );\n })}\n </AriaRow>,\n ];\n if (open && expansion)\n items.push(\n <AriaRow key={detailKey(row.id)} id={detailKey(row.id)} textValue={expansion.rowLabel(row.original)} className=\"outline-offset-[-2px]\">\n {lead > 0 && <AriaCell colSpan={lead} />}\n <AriaCell colSpan={columns.length} className=\"pt-0.5 pb-4 align-top\">\n {expansion.detail(row.original)}\n </AriaCell>\n </AriaRow>,\n );\n return items;\n })}\n </TableBody>\n </AriaTable>\n );\n\n return (\n <div\n className={cn(\"relative min-w-0\", !virtual && \"overflow-x-auto\", className)}\n onMouseDownCapture={(e) => {\n shift.handlers.onMouseDown(e);\n notePress(e);\n }}\n onKeyDownCapture={(e) => {\n shift.handlers.onKeyDown(e);\n notePress(e);\n }}\n >\n {virtual ? (\n <Virtualizer layout={TableLayout} layoutOptions={expansion ? { estimatedRowHeight: 41, headingHeight: 36 } : { rowHeight: 41, headingHeight: 36 }}>\n {grid}\n </Virtualizer>\n ) : (\n grid\n )}\n </div>\n );\n}\n\nconst SELECT = \"\\u0000select\";\nconst EXPAND = \"\\u0000expand\";\nconst noop = () => {};\n\n/** The loading placeholder for a `DataTable`, shaped like its rows. */\nexport function TableSkeleton({ rows = 4, columns = 5 }: { rows?: number; columns?: number }) {\n return (\n <div aria-hidden className=\"grid gap-0\">\n <div className=\"flex gap-4 py-2\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-3 flex-1 rounded-control bg-muted\" />\n ))}\n </div>\n {Array.from({ length: rows }, (_, r) => (\n <div key={r} className=\"flex gap-4 border-t border-border py-3.5\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-4 flex-1 rounded-control bg-muted motion-safe:animate-pulse\" />\n ))}\n </div>\n ))}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Pause, Play, SkipBack, SkipForward, Square, StepBack, StepForward, Volume2, VolumeX } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\nimport { NativeSelect } from \"./field\";\nimport type { Shortcut } from \"./hotkeys\";\nimport { Toolbar } from \"./toolbar\";\nimport { Slider } from \"./value-controls\";\nimport { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport { useSliderState } from \"react-stately\";\n\n// The controls around anything that plays (strata issue #78): transport, a time readout, a seek\n// bar, volume with mute, a playback rate, and a stage that holds a picture at its aspect ratio.\n// Video and audio editors, media viewers, lesson players and replays of recorded data (a kiln\n// firing played back) share them. Nothing here is tied to `<video>`: the app owns its player (HTML\n// media, Web Audio, a canvas compositor, a data replay) and passes the state in and takes the\n// requests out, so a replay with no media element at all uses the same controls.\n//\n// Transport is used hundreds of times a session, so it changes instantly with no motion and is\n// driven from the one shortcut list (`transportShortcuts`, for `useHotkeys` and `KeysLegend`), not\n// from key handlers of its own (ux-character.md, by frequency; components.md §3.16). Each control is\n// a named `IconButton`, and the play button's NAME follows the state (\"Play\" / \"Pause\"). It is not\n// also `aria-pressed`: a button whose name flips and whose pressed state flips reads as a toggle of\n// a toggle in a screen reader. (The issue asked for both; one is the WAI-ARIA way, so the name.)\n// The group is React Aria's toolbar through `Toolbar` (one tab stop, arrows between controls).\n//\n// The seek bar is React Aria's slider hooks (`useSlider`, `useSliderThumb`, `useSliderState`): the\n// pointer, the thumb, the hidden range input and its label come from them. Two things are ours on top,\n// each checked in the hooks' source. The value text: `useSliderState` formats through an object with\n// `format`, `formatRange` and `resolvedOptions`, so it is given one that says \"1:23\" instead of an\n// `Intl.NumberFormat` (which would read seconds as a bare number). The keys: the state has one\n// `step`, and a seek bar needs a fine one so a drag lands on any moment, so arrows (`step` seconds),\n// Page keys (`bigStep`) and Home and End are handled in a capture handler on the input and the hooks'\n// own arrow handling is stopped. Volume has neither limit, and stays React Aria's component.\n//\n// Readouts are `tabular-nums` and are padded to the width of the longest value they will show\n// (`duration`), so they do not change width as the time runs.\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);\n\nexport type Precision = \"seconds\" | \"ms\" | \"frames\";\n\ntype TimeProps = { precision?: Precision; fps?: number };\n\nconst timecode = (t: number, { precision, fps }: TimeProps) => format.timecode(t, { precision, fps });\n\n/** The current and total time, in `tabular-nums`, as `<time>` elements. */\nexport function TimeReadout({ time, duration, precision = \"seconds\", fps = 30, className }: { time: number; duration: number | null } & TimeProps & { className?: string }) {\n const total = duration === null ? null : timecode(duration, { precision, fps });\n return (\n <span className={cn(\"inline-flex items-baseline gap-1 type-body-sm tabular-nums\", className)}>\n <time dateTime={`PT${Math.floor(time)}S`} aria-label={`Position ${timecode(time, { precision, fps })}`} className=\"text-foreground\" style={total ? { minWidth: `${total.length}ch` } : undefined}>\n {timecode(time, { precision, fps })}\n </time>\n <span aria-hidden className=\"text-muted-foreground\">\n /\n </span>\n <time dateTime={duration === null ? undefined : `PT${Math.floor(duration)}S`} aria-label={`Length ${total ?? format.missing}`} className=\"text-muted-foreground\">\n {total ?? format.missing}\n </time>\n </span>\n );\n}\n\nexport type SeekBarProps = TimeProps & {\n time: number;\n /** Seconds; null, NaN or 0 while it is not known (a stream before its metadata): the bar is drawn disabled, with no thumb. */\n duration: number | null;\n /** The viewer asked for this time (drag, click or key). */\n onSeek: (time: number) => void;\n /** Named points on the bar (chapters, markers). Pressing one seeks to it. */\n marks?: readonly { time: number; label: string }[];\n /** What pressing a mark does. Default seeks to it; a screen that wants to land on it and pause (a moment to look at) passes its own. */\n onMarkPress?: (mark: { time: number; label: string }) => void;\n /** How far has loaded or been recorded, drawn behind the played part. */\n buffered?: number;\n /** Arrow key step in seconds. Default 5. */\n step?: number;\n /** Page Up and Page Down step in seconds. Default 30. */\n bigStep?: number;\n label?: string;\n disabled?: boolean;\n className?: string;\n};\n\n/** A seek bar: dragged, clicked and moved by keys (arrows `step`, Page keys `bigStep`, Home and End), with its time as the accessible value. */\nexport function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffered, step = 5, bigStep = 30, label = \"Seek\", precision = \"seconds\", fps = 30, disabled: off, className }: SeekBarProps) {\n const duration = known && Number.isFinite(known) && known > 0 ? known : 0;\n const disabled = off || duration === 0;\n const track = React.useRef<HTMLDivElement>(null);\n const input = React.useRef<HTMLInputElement>(null);\n const frac = duration > 0 ? clamp(time / duration, 0, 1) : 0;\n const seekTo = (t: number) => onSeek(clamp(t, 0, duration));\n // React Aria's state with a formatter that says \"1:23\" (it only needs `format`, `formatRange` and\n // `resolvedOptions`, which is all `useSliderState` calls) and a fine step, so a drag lands on any\n // moment and not on every 5 s.\n const timeText = React.useMemo(() => {\n const say = (t: number) => timecode(t, { precision, fps });\n return { format: say, formatRange: (a: number, b: number) => `${say(a)} to ${say(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) } as unknown as Intl.NumberFormat;\n }, [precision, fps]);\n const fine = precision === \"frames\" ? 1 / fps : precision === \"ms\" ? 0.001 : 0.01;\n const state = useSliderState({ minValue: 0, maxValue: Math.max(duration, fine), step: fine, value: [clamp(time, 0, duration)], onChange: ([t]) => seekTo(t), numberFormatter: timeText, isDisabled: disabled });\n const { groupProps, trackProps } = useSlider({ \"aria-label\": label, isDisabled: disabled }, state, track);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: track, inputRef: input, \"aria-label\": label, isDisabled: disabled }, state);\n const { focusProps, isFocusVisible } = useFocusRing();\n // The keys are ours, because the hooks step by `state.step` and this one has to be fine for the\n // drag: arrows move `step` seconds, Page keys `bigStep`, Home and End the ends. Captured so the\n // hook's own arrow handling (one fine step) does not also run.\n const keys: Record<string, number> = { ArrowLeft: -step, ArrowDown: -step, ArrowRight: step, ArrowUp: step, PageDown: -bigStep, PageUp: bigStep };\n const onKeyDownCapture = (e: React.KeyboardEvent) => {\n if (disabled) return;\n if (e.key in keys) seekTo(time + keys[e.key]);\n else if (e.key === \"Home\") seekTo(0);\n else if (e.key === \"End\") seekTo(duration);\n else return;\n e.preventDefault();\n e.stopPropagation();\n };\n return (\n <div {...groupProps} className={cn(\"relative flex h-(--control-h) min-w-0 flex-1 items-center\", disabled && \"cursor-not-allowed opacity-50\", className)}>\n <div {...trackProps} ref={track} className={cn(\"relative flex h-full w-full cursor-pointer touch-none items-center\", disabled && \"cursor-not-allowed\")}>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n {buffered !== undefined && duration > 0 && <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-neutral-4\" style={{ width: `${clamp(buffered / duration, 0, 1) * 100}%` }} />}\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${frac * 100}%` }} />\n {duration > 0 &&\n marks.map((m) => (\n <button\n key={`${m.time}-${m.label}`}\n type=\"button\"\n tabIndex={-1}\n disabled={disabled}\n title={`${m.label}, ${timecode(m.time, { precision, fps })}`}\n aria-label={`${m.label}, ${timecode(m.time, { precision, fps })}`}\n onPointerDown={(e) => e.stopPropagation()}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={() => (onMarkPress ? onMarkPress(m) : seekTo(m.time))}\n className=\"absolute top-1/2 h-3 w-1 -translate-y-1/2 cursor-pointer rounded-pill bg-foreground\"\n style={{ left: `${(m.time / duration) * 100}%` }}\n />\n ))}\n <div {...thumbProps} className={cn(\"absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-pill border-2 border-primary bg-background\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")} style={{ left: `${frac * 100}%` }}>\n <VisuallyHidden>\n <input ref={input} {...mergeProps(inputProps, focusProps)} aria-labelledby={undefined} onKeyDownCapture={onKeyDownCapture} />\n </VisuallyHidden>\n </div>\n </div>\n </div>\n );\n}\n\nexport type TransportProps = {\n playing: boolean;\n onPlayPause: () => void;\n onStop?: () => void;\n onToStart?: () => void;\n onToEnd?: () => void;\n onStepBack?: () => void;\n onStepForward?: () => void;\n /** What a step is called in the buttons' names: \"frame\" (default) or \"second\". */\n stepUnit?: string;\n /** Anything else on the row: the time readout, a seek bar, volume. */\n children?: React.ReactNode;\n className?: string;\n};\n\n/** The transport buttons for a player the app owns. Every control is a named icon button; the play button's name is \"Play\" or \"Pause\" from `playing`. Only the buttons whose handler is passed are drawn. */\nexport function Transport({ playing, onPlayPause, onStop, onToStart, onToEnd, onStepBack, onStepForward, stepUnit = \"frame\", children, className }: TransportProps) {\n return (\n <Toolbar label=\"Playback\" className={cn(\"gap-2\", className)}>\n {onToStart && <IconButton icon={SkipBack} label=\"Go to start\" hint=\"Home\" onClick={onToStart} />}\n {onStepBack && <IconButton icon={StepBack} label={`Back one ${stepUnit}`} hint=\"←\" onClick={onStepBack} />}\n <IconButton icon={playing ? Pause : Play} label={playing ? \"Pause\" : \"Play\"} hint=\"Space\" variant=\"outline\" onClick={onPlayPause} />\n {onStop && <IconButton icon={Square} label=\"Stop\" onClick={onStop} />}\n {onStepForward && <IconButton icon={StepForward} label={`Forward one ${stepUnit}`} hint=\"→\" onClick={onStepForward} />}\n {onToEnd && <IconButton icon={SkipForward} label=\"Go to end\" hint=\"End\" onClick={onToEnd} />}\n {children}\n </Toolbar>\n );\n}\n\nexport type VolumeControlProps = {\n /** 0 to 100. */\n volume: number;\n onVolumeChange: (volume: number) => void;\n /** Allow over 100 (a boost), up to this. Default 100. */\n max?: number;\n disabled?: boolean;\n className?: string;\n};\n\n/** A mute button and a volume slider with its value in percent. Muting sets the volume to 0 and remembers the level; unmuting puts it back. Moving the slider from 0 unmutes. */\nexport function VolumeControl({ volume, onVolumeChange, max = 100, disabled, className }: VolumeControlProps) {\n const last = React.useRef(volume > 0 ? volume : 100);\n if (volume > 0) last.current = volume;\n const muted = volume === 0;\n return (\n <div className={cn(\"flex items-center gap-2\", className)}>\n <IconButton icon={muted ? VolumeX : Volume2} label={muted ? \"Unmute\" : \"Mute\"} hint=\"M\" disabled={disabled} onClick={() => onVolumeChange(muted ? last.current : 0)} />\n <Slider aria-label=\"Volume\" value={volume} onChange={onVolumeChange} min={0} max={max} unit=\"%\" disabled={disabled} className=\"w-40\" />\n </div>\n );\n}\n\n/** A choice of playback speed (\"0.5×\", \"1×\", \"1.5×\") on a native select, named \"Playback speed\". */\nexport function RateChoice({ rate, onRateChange, rates = [0.5, 1, 1.25, 1.5, 2], className }: { rate: number; onRateChange: (rate: number) => void; rates?: readonly number[]; className?: string }) {\n return (\n <NativeSelect aria-label=\"Playback speed\" value={String(rate)} onChange={(e) => onRateChange(Number(e.target.value))} className={cn(\"w-auto\", className)}>\n {rates.map((r) => (\n <option key={r} value={String(r)}>\n {`${r}×`}\n </option>\n ))}\n </NativeSelect>\n );\n}\n\n/**\n * The shortcuts a player takes, as one list for `useHotkeys` and `KeysLegend`: Space and K play\n * or pause, J and L go back or forward `jump` seconds, the arrows by `frame` seconds, Home and End\n * to the ends, M mutes. Pass the player's actions; the labels are the legend's words.\n */\nexport function transportShortcuts({ toggle, seek, time, duration, frame = 1 / 30, jump = 1, toggleMute }: { toggle: () => void; seek: (time: number) => void; time: number; duration: number; frame?: number; jump?: number; toggleMute?: () => void }): Shortcut[] {\n const to = (t: number) => () => seek(clamp(t, 0, duration));\n return [\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: toggle },\n { keys: [\"j\"], label: `Back ${jump} s`, run: to(time - jump), repeat: true },\n { keys: [\"l\"], label: `Forward ${jump} s`, run: to(time + jump), repeat: true },\n { keys: [\"ArrowLeft\"], label: \"Back one frame\", run: to(time - frame), repeat: true },\n { keys: [\"ArrowRight\"], label: \"Forward one frame\", run: to(time + frame), repeat: true },\n { keys: [\"Home\"], label: \"Go to start\", run: to(0) },\n { keys: [\"End\"], label: \"Go to end\", run: to(duration) },\n ...(toggleMute ? [{ keys: [\"m\"], label: \"Mute\", run: toggleMute }] : []),\n ];\n}\n\n/** A frame that fits content of an aspect ratio into the pane, letterboxed on the sunken surface role (light and dark both), with room for the app's overlays. */\nexport function MediaStage({ aspect, children, label, className }: { aspect: number | `${number}/${number}`; children: React.ReactNode; label: string; className?: string }) {\n const outer = React.useRef<HTMLDivElement>(null);\n const [box, setBox] = React.useState<{ w: number; h: number } | null>(null);\n const ratio = typeof aspect === \"number\" ? aspect : (() => { const [w, h] = aspect.split(\"/\").map(Number); return w / h; })();\n React.useEffect(() => {\n const el = outer.current;\n if (!el) return;\n const read = () => setBox({ w: el.clientWidth, h: el.clientHeight });\n read();\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n // Contain-fit by arithmetic: CSS aspect-ratio with max-width breaks the ratio when the width is clamped.\n const fit = box && box.w > 0 && box.h > 0 ? (box.w / box.h > ratio ? { w: box.h * ratio, h: box.h } : { w: box.w, h: box.w / ratio }) : null;\n return (\n <div ref={outer} role=\"group\" aria-label={label} className={cn(\"grid min-h-0 min-w-0 place-items-center overflow-hidden bg-surface-sunken\", className)}>\n <div className=\"relative overflow-hidden bg-background\" style={fit ? { width: fit.w, height: fit.h } : { width: \"100%\", aspectRatio: String(ratio) }}>\n {children}\n </div>\n </div>\n );\n}\n\n/** Guides over a stage: action-safe and title-safe frames (90% and 80%), a centre cross and a rule-of-thirds grid. Drawn as two strokes (light over dark) so they read on any picture. */\nexport function StageGuides({ safe, thirds, centre, className }: { safe?: boolean; thirds?: boolean; centre?: boolean; className?: string }) {\n const lines: [number, number, number, number][] = [];\n if (thirds) lines.push([100 / 3, 0, 100 / 3, 100], [200 / 3, 0, 200 / 3, 100], [0, 100 / 3, 100, 100 / 3], [0, 200 / 3, 100, 200 / 3]);\n if (centre) lines.push([50, 46, 50, 54], [46, 50, 54, 50]);\n const rects = safe ? [5, 10] : [];\n const draw = (cls: string, w: number) => (\n <g className={cls} strokeWidth={w} fill=\"none\" vectorEffect=\"non-scaling-stroke\">\n {lines.map((l, i) => <line key={i} x1={l[0]} y1={l[1]} x2={l[2]} y2={l[3]} vectorEffect=\"non-scaling-stroke\" />)}\n {rects.map((m) => <rect key={m} x={m} y={m} width={100 - 2 * m} height={100 - 2 * m} vectorEffect=\"non-scaling-stroke\" />)}\n </g>\n );\n return (\n <svg aria-hidden viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className={cn(\"pointer-events-none absolute inset-0 size-full\", className)}>\n {draw(\"stroke-foreground\", 3)}\n {draw(\"stroke-background\", 1)}\n </svg>\n );\n}\n","import * as React from \"react\";\nimport { SkipBack, SkipForward } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\nimport { Alert } from \"./alert\";\nimport { Button, IconButton } from \"./button\";\nimport { useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { RateChoice, SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\n\n// Playing a file without writing the glue (strata-react issue #134, from strata-listory, whose two\n// players stayed `<audio controls>` because the parts of #78 take state in and requests out, and\n// every app that plays a file would write the same event handling). Two pieces, one on the other:\n//\n// - `useMediaElement(ref)` owns the element's state. It listens to the events a player needs\n// (`timeupdate`, `durationchange`, `progress`, `play`, `pause`, `ended`, `volumechange`,\n// `ratechange`, `waiting`, `error`, and the ones that say loading has started or finished) and\n// hands back plain values that spread straight into `Transport`, `SeekBar`, `TimeReadout`,\n// `VolumeControl` and `RateChoice`, and the requests (`play`, `pause`, `toggle`, `seek`,\n// `setVolume`, `setRate`, `retry`). It catches the rejection of `play()` (autoplay refused) into\n// `error` instead of an unhandled promise, applies a seek made before the metadata has loaded\n// once it has, and gives `duration` as `null` until it is known (a stream says `NaN` or `Infinity`),\n// so `SeekBar` draws a disabled bar with an en dash and no thumb stuck at 0. It only listens, so it\n// reads an element drawn with the browser's own controls just as well.\n// - `MediaPlayer` is the 90% case: the element, the hook, the parts and the keys. `controls` is\n// `\"auto\"` (the browser's own bar on a touch device, `(pointer: coarse)`, Strata's on a desktop),\n// `\"native\"` or `\"strata\"`. Native stays an option because the browser's bar brings what a custom\n// one will not (lock-screen and headset controls, AirPlay and Cast, picture in picture, caption\n// menus); `session` sets `navigator.mediaSession` for the same reason. The stack table's rule,\n// \"native elements stay where the platform does it better\", applies to playback of a file.\n// - A sequence (chapters, a playlist) is `sources`: ending moves to the next and keeps playing by\n// changing the element's `src`, never remounting it, because a browser allows playback to continue\n// only on an element the person has already started. When every source gives its `duration` the\n// seek bar spans the whole sequence, with a mark at each source's title; otherwise it spans the\n// current one.\n//\n// Checked: React Aria has no media element hook (its `VisuallyHidden`, `useSlider` and toolbar are\n// what the parts are built on), so the hook is ours. Volume is 0 to 100 and 0 is muted, the way\n// `VolumeControl` has it; unmuting restores the element's own level.\n\n/** Why a player is not playing, for the app to word. */\nexport type MediaProblem = { kind: \"load\"; message: string } | { kind: \"blocked\"; message: string };\n\n/** What `useMediaElement` returns: the element's state as values, and the requests a player makes of it. */\nexport type MediaElementState = {\n playing: boolean;\n /** Seconds. */\n time: number;\n /** Seconds, or null until the element knows it (a stream reports NaN or Infinity). */\n duration: number | null;\n /** Seconds buffered from the start of the range holding `time`. */\n buffered: number;\n /** 0 to 100; 0 while muted. */\n volume: number;\n muted: boolean;\n rate: number;\n ended: boolean;\n /** Waiting for data (the first load, or a seek into what is not buffered yet). */\n loading: boolean;\n error: MediaProblem | null;\n play: () => Promise<void>;\n pause: () => void;\n toggle: () => void;\n /** Seeks; before the metadata has loaded, remembers the time and applies it when it has. */\n seek: (time: number) => void;\n /** 0 to 100. 0 mutes; more unmutes at that level. */\n setVolume: (volume: number) => void;\n setRate: (rate: number) => void;\n /** Loads again, and plays if it was playing. For the error state's \"Try again\". */\n retry: () => void;\n};\n\ntype Snapshot = Omit<MediaElementState, \"play\" | \"pause\" | \"toggle\" | \"seek\" | \"setVolume\" | \"setRate\" | \"retry\">;\n\nconst idle: Snapshot = { playing: false, time: 0, duration: null, buffered: 0, volume: 100, muted: false, rate: 1, ended: false, loading: false, error: null };\n\nconst LOAD_MESSAGES: Record<number, string> = {\n 2: \"The connection dropped while it was loading.\",\n 3: \"The file could not be decoded.\",\n 4: \"This format is not supported or the file is not there.\",\n};\n\nfunction bufferedAhead(el: HTMLMediaElement) {\n const ranges = el.buffered;\n for (let i = 0; i < ranges.length; i++) if (el.currentTime >= ranges.start(i) && el.currentTime <= ranges.end(i)) return ranges.end(i);\n return 0;\n}\n\n// Subscribes while an element is mounted, and again if the ref later holds another one (a player that\n// changes `kind` replaces its DOM node, and the old node's listeners are gone with it).\nfunction useElementListeners(ref: React.RefObject<HTMLMediaElement | null>, bind: (el: HTMLMediaElement) => () => void) {\n const bound = React.useRef<{ el: HTMLMediaElement; unbind: () => void } | null>(null);\n const latest = React.useRef(bind);\n latest.current = bind;\n // No dependency list on purpose: a ref changing does not render, but whatever replaced the node did.\n React.useEffect(() => {\n const el = ref.current;\n if (bound.current?.el === el) return;\n bound.current?.unbind();\n bound.current = el ? { el, unbind: latest.current(el) } : null;\n });\n React.useEffect(\n () => () => {\n bound.current?.unbind();\n bound.current = null;\n },\n [],\n );\n}\n\nconst EVENTS = [\n \"loadstart\", \"loadedmetadata\", \"durationchange\", \"timeupdate\", \"progress\", \"play\", \"playing\", \"pause\", \"ended\",\n \"volumechange\", \"ratechange\", \"seeking\", \"seeked\", \"waiting\", \"canplay\", \"emptied\", \"error\",\n] as const;\n\n/** Follows an `<audio>` or `<video>` and returns its state and the requests a player makes. Works with the browser's own controls too. */\nexport function useMediaElement(ref: React.RefObject<HTMLMediaElement | null>): MediaElementState {\n const [snapshot, setSnapshot] = React.useState<Snapshot>(idle);\n const blocked = React.useRef<MediaProblem | null>(null);\n const pendingSeek = React.useRef<number | null>(null);\n\n const read = React.useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const finite = Number.isFinite(el.duration) && el.duration > 0;\n let error: MediaProblem | null = blocked.current;\n // Code 1 is the load being abandoned on purpose (a new src), not a failure.\n if (el.error && el.error.code !== 1) error = { kind: \"load\", message: LOAD_MESSAGES[el.error.code] ?? \"It could not be played.\" };\n const next: Snapshot = {\n playing: !el.paused && !el.ended,\n time: Number.isFinite(el.currentTime) ? el.currentTime : 0,\n duration: finite ? el.duration : null,\n buffered: bufferedAhead(el),\n volume: el.muted ? 0 : Math.round(el.volume * 100),\n muted: el.muted,\n rate: el.playbackRate,\n ended: el.ended,\n loading: !error && el.networkState === 2 && el.readyState < 3 && !el.paused,\n error,\n };\n setSnapshot((previous) => (Object.keys(next) as (keyof Snapshot)[]).every((k) => Object.is(previous[k], next[k]) || (k === \"error\" && previous.error?.message === next.error?.message && previous.error?.kind === next.error?.kind)) ? previous : next);\n }, [ref]);\n\n useElementListeners(ref, (el) => {\n const on = (e: Event) => {\n if (e.type === \"play\" || e.type === \"playing\") blocked.current = null;\n if (e.type === \"loadedmetadata\" && pendingSeek.current !== null) {\n el.currentTime = pendingSeek.current;\n pendingSeek.current = null;\n }\n if (e.type === \"emptied\" || e.type === \"loadstart\") blocked.current = null;\n read();\n };\n for (const type of EVENTS) el.addEventListener(type, on);\n read();\n return () => {\n for (const type of EVENTS) el.removeEventListener(type, on);\n };\n });\n\n return React.useMemo<MediaElementState>(() => {\n const play = async () => {\n const el = ref.current;\n if (!el) return;\n try {\n await el.play();\n } catch (e) {\n // A load error also rejects play(); it is reported through the element's own error.\n if (e instanceof DOMException && e.name === \"NotAllowedError\") {\n blocked.current = { kind: \"blocked\", message: \"The browser blocked playback until you press Play.\" };\n read();\n } else if (!(e instanceof DOMException && e.name === \"AbortError\")) read();\n }\n };\n return {\n ...snapshot,\n play,\n pause: () => ref.current?.pause(),\n toggle: () => {\n const el = ref.current;\n if (!el) return;\n if (el.paused || el.ended) void play();\n else el.pause();\n },\n seek: (time) => {\n const el = ref.current;\n if (!el) return;\n if (el.readyState < 1) pendingSeek.current = Math.max(0, time);\n else el.currentTime = Math.max(0, Number.isFinite(el.duration) ? Math.min(time, el.duration) : time);\n read();\n },\n setVolume: (volume) => {\n const el = ref.current;\n if (!el) return;\n const v = Math.min(Math.max(volume, 0), 100);\n el.muted = v === 0;\n if (v > 0) el.volume = v / 100;\n },\n setRate: (rate) => {\n const el = ref.current;\n if (!el) return;\n // The default too: loading another source resets `playbackRate` to `defaultPlaybackRate`, which would drop the chosen speed at every chapter.\n el.defaultPlaybackRate = rate;\n el.playbackRate = rate;\n },\n retry: () => {\n const el = ref.current;\n if (!el) return;\n const resume = !el.paused;\n const at = el.currentTime;\n blocked.current = null;\n el.load();\n if (at > 0) pendingSeek.current = at;\n read();\n if (resume) void play();\n },\n };\n }, [snapshot, ref, read]);\n}\n\n/** One file in a sequence. */\nexport type MediaSource = {\n src: string;\n /** Names the source on the seek bar's marks and in \"Chapter 2 of 5\". */\n title: string;\n /** Seconds. When every source gives it, the seek bar spans the whole sequence. */\n duration?: number;\n};\n\n/** Lock-screen and headset metadata (`navigator.mediaSession`). */\nexport type MediaSession = { title: string; artist?: string; album?: string; artwork?: string };\n\nexport type MediaPlayerProps = {\n /** Names the player and its element. */\n label: string;\n kind?: \"audio\" | \"video\";\n /** One file. */\n src?: string;\n /** Or a sequence; ending moves to the next and keeps playing. */\n sources?: readonly MediaSource[];\n /** The current source, when the app holds it (a chapter list beside the player). */\n index?: number;\n onIndexChange?: (index: number) => void;\n /** Move to the next source when one ends. Default true. */\n autoAdvance?: boolean;\n /** `\"auto\"`: the browser's controls on a touch device, Strata's on a desktop. Default. */\n controls?: \"auto\" | \"native\" | \"strata\";\n autoPlay?: boolean;\n poster?: string;\n session?: MediaSession;\n /** The playback speeds offered. Default 0.5 to 2; for speech use {@link SPEECH_RATES}. */\n rates?: readonly number[];\n /** Keys on the page (Space or K, J and L for 10 s, M). Default true; turn off when the screen binds its own. With several players on a page the keys go to the one last played, focused or pressed. */\n shortcuts?: boolean;\n /** The last source has ended. */\n onEnded?: () => void;\n /** Called as the element plays, with the time in the whole sequence. */\n onTimeChange?: (time: number) => void;\n className?: string;\n};\n\n// Which player the page's keys belong to. A page with one player binds them for it, as ever. With\n// several, binding Space once per player played and paused every one of them at once, so the keys go\n// to the player last used (played, focused or pressed) and the others leave them alone (issue #147,\n// from strata-models' blind A/B of two voices). A tiny store outside React so the players on a page\n// can see each other without a provider the app would have to add.\nconst keyPlayers = (() => {\n const ids = new Set<string>();\n let active: string | null = null;\n let warned = false;\n const listeners = new Set<() => void>();\n let snapshot = { count: 0, active: null as string | null };\n const emit = () => {\n snapshot = { count: ids.size, active };\n listeners.forEach((l) => l());\n };\n return {\n subscribe: (l: () => void) => {\n listeners.add(l);\n return () => void listeners.delete(l);\n },\n get: () => snapshot,\n add(id: string) {\n ids.add(id);\n if (ids.size === 2 && !warned && typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\") {\n warned = true;\n console.warn(\"strata-react: several MediaPlayers are on this page, so Space, K, J, L and M go to the one last played or focused. Pass shortcuts={false} to one you bind your own keys for.\");\n }\n emit();\n },\n remove(id: string) {\n ids.delete(id);\n if (active === id) active = null;\n emit();\n },\n use(id: string) {\n // A player with shortcuts off is not registered and must not take the keys from the others.\n if (active === id || !ids.has(id)) return;\n active = id;\n emit();\n },\n };\n})();\n\n/** Playback speeds an audiobook or lecture listener expects. */\nexport const SPEECH_RATES: readonly number[] = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3];\n\nconst JUMP = 10;\n\nfunction useCoarsePointer() {\n const [coarse, setCoarse] = React.useState(false);\n React.useEffect(() => {\n if (typeof matchMedia !== \"function\") return;\n const query = matchMedia(\"(pointer: coarse)\");\n const read = () => setCoarse(query.matches);\n read();\n query.addEventListener?.(\"change\", read);\n return () => query.removeEventListener?.(\"change\", read);\n }, []);\n return coarse;\n}\n\n/**\n * Plays a file or a sequence: the element, its state, and Strata's controls (or the browser's own on\n * a touch device), with the failure to load shown and retried. For an editor or a replay, use the\n * parts and `useMediaElement` directly.\n */\nexport function MediaPlayer({\n label,\n kind = \"audio\",\n src,\n sources,\n index: controlledIndex,\n onIndexChange,\n autoAdvance = true,\n controls = \"auto\",\n autoPlay,\n poster,\n session,\n rates,\n shortcuts = true,\n onEnded,\n onTimeChange,\n className,\n}: MediaPlayerProps) {\n const list = React.useMemo<readonly MediaSource[]>(() => sources ?? (src ? [{ src, title: label }] : []), [sources, src, label]);\n const [ownIndex, setOwnIndex] = React.useState(0);\n const index = Math.min(controlledIndex ?? ownIndex, Math.max(list.length - 1, 0));\n const current = list[index];\n const ref = React.useRef<HTMLMediaElement>(null);\n const media = useMediaElement(ref);\n const coarse = useCoarsePointer();\n const native = controls === \"native\" || (controls === \"auto\" && coarse);\n\n const go = React.useCallback(\n (to: number) => {\n if (controlledIndex === undefined) setOwnIndex(to);\n onIndexChange?.(to);\n },\n [controlledIndex, onIndexChange],\n );\n // Changing src on the same element: whether to carry on playing, and where to start, are applied once the new file is loaded.\n const resume = React.useRef(false);\n const startAt = React.useRef<number | null>(null);\n const keep = React.useRef({ index, playing: media.playing, go, onEnded, autoAdvance, last: list.length - 1 });\n keep.current = { index, playing: media.playing, go, onEnded, autoAdvance, last: list.length - 1 };\n\n const wasSrc = React.useRef(current?.src);\n React.useEffect(() => {\n if (wasSrc.current === current?.src) return;\n wasSrc.current = current?.src;\n const el = ref.current;\n if (!el) return;\n if (startAt.current !== null) {\n media.seek(startAt.current);\n startAt.current = null;\n }\n if (resume.current) {\n resume.current = false;\n void media.play();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [current?.src]);\n\n const onEnd = React.useCallback(() => {\n const k = keep.current;\n if (k.autoAdvance && k.index < k.last) {\n resume.current = true;\n k.go(k.index + 1);\n } else k.onEnded?.();\n }, []);\n useElementListeners(ref, (el) => {\n el.addEventListener(\"ended\", onEnd);\n return () => el.removeEventListener(\"ended\", onEnd);\n });\n\n // The sequence as one timeline, when every source says how long it is.\n const offsets = React.useMemo(() => {\n if (list.length < 2 || !list.every((s) => s.duration && s.duration > 0)) return null;\n let at = 0;\n return list.map((s) => {\n const start = at;\n at += s.duration!;\n return start;\n });\n }, [list]);\n const total = offsets ? offsets[offsets.length - 1] + list[list.length - 1].duration! : null;\n const time = (offsets ? offsets[index] : 0) + media.time;\n const duration = total ?? media.duration;\n\n const seek = (t: number) => {\n if (!offsets) return media.seek(t);\n let to = offsets.length - 1;\n while (to > 0 && offsets[to] > t) to--;\n if (to === index) return media.seek(t - offsets[to]);\n resume.current = media.playing;\n startAt.current = t - offsets[to];\n go(to);\n };\n const step = (by: number) => {\n const to = index + by;\n if (to < 0 || to > list.length - 1) return;\n resume.current = media.playing;\n go(to);\n };\n\n React.useEffect(() => {\n if (onTimeChange) onTimeChange(time);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [time]);\n\n const keys = React.useMemo<Shortcut[]>(\n () => [\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: media.toggle },\n { keys: [\"j\"], label: `Back ${JUMP} s`, run: () => seek(time - JUMP), repeat: true },\n { keys: [\"l\"], label: `Forward ${JUMP} s`, run: () => seek(time + JUMP), repeat: true },\n { keys: [\"m\"], label: \"Mute\", run: () => media.setVolume(media.muted ? 100 : 0) },\n ],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [media, time, offsets, index],\n );\n // Several players on a page: the keys follow the last used (see keyPlayers); alone, they are this one's.\n const id = React.useId();\n React.useEffect(() => {\n if (!shortcuts || native) return;\n keyPlayers.add(id);\n return () => keyPlayers.remove(id);\n }, [id, shortcuts, native]);\n const page = React.useSyncExternalStore(keyPlayers.subscribe, keyPlayers.get, keyPlayers.get);\n React.useEffect(() => {\n if (media.playing && shortcuts && !native) keyPlayers.use(id);\n }, [media.playing, id, shortcuts, native]);\n useHotkeys(keys, { enabled: shortcuts && !native && (page.count <= 1 || page.active === id) });\n\n // Lock-screen and headset controls.\n React.useEffect(() => {\n if (!session || typeof navigator === \"undefined\" || !(\"mediaSession\" in navigator) || typeof MediaMetadata === \"undefined\") return;\n const s = navigator.mediaSession;\n s.metadata = new MediaMetadata({ title: current?.title ?? session.title, artist: session.artist, album: session.album ?? (list.length > 1 ? session.title : undefined), artwork: session.artwork ? [{ src: session.artwork }] : [] });\n return () => {\n s.metadata = null;\n };\n }, [session, current?.title, list.length]);\n React.useEffect(() => {\n if (!session || typeof navigator === \"undefined\" || !(\"mediaSession\" in navigator)) return;\n const s = navigator.mediaSession;\n const set = (action: MediaSessionAction, handler: MediaSessionActionHandler | null) => {\n try {\n s.setActionHandler(action, handler);\n } catch {\n // An action this browser does not offer.\n }\n };\n set(\"play\", () => void media.play());\n set(\"pause\", media.pause);\n set(\"seekbackward\", () => seek(time - JUMP));\n set(\"seekforward\", () => seek(time + JUMP));\n set(\"previoustrack\", index > 0 ? () => step(-1) : null);\n set(\"nexttrack\", index < list.length - 1 ? () => step(1) : null);\n return () => {\n for (const a of [\"play\", \"pause\", \"seekbackward\", \"seekforward\", \"previoustrack\", \"nexttrack\"] as const) set(a, null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session, media, time, index, list.length]);\n\n const common = { ref: ref as React.Ref<never>, src: current?.src, controls: native, autoPlay, preload: \"metadata\" as const, \"aria-label\": `${label}, ${kind}` };\n const element = kind === \"video\" ? <video {...common} poster={poster} playsInline className=\"w-full rounded-surface bg-surface-sunken\" /> : <audio {...common} className={native ? \"w-full\" : \"hidden\"} />;\n const what = kind === \"video\" ? \"this video\" : \"this recording\";\n\n return (\n <div role=\"group\" aria-label={label} onFocusCapture={() => keyPlayers.use(id)} onPointerDownCapture={() => keyPlayers.use(id)} className={cn(\"grid w-full gap-2\", className)}>\n {element}\n {media.error?.kind === \"load\" && (\n <Alert\n tone=\"danger\"\n announce\n title={`Could not load ${what}`}\n action={\n <Button size=\"sm\" variant=\"outline\" onClick={media.retry}>\n Try again\n </Button>\n }\n >\n {media.error.message}\n </Alert>\n )}\n {media.error?.kind === \"blocked\" && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {media.error.message}\n </p>\n )}\n {!native && (\n <div className=\"grid gap-2\">\n <div className=\"flex min-w-0 items-center gap-3\">\n <SeekBar\n time={time}\n duration={duration}\n onSeek={seek}\n buffered={offsets ? undefined : media.buffered}\n marks={offsets ? list.map((s, i) => ({ time: offsets[i], label: s.title })).slice(1) : []}\n step={JUMP}\n bigStep={60}\n label={`Seek in ${label}`}\n />\n <TimeReadout time={time} duration={duration} />\n </div>\n <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2\">\n <Transport playing={media.playing} onPlayPause={media.toggle}>\n {list.length > 1 && <IconButton icon={SkipBack} label=\"Previous chapter\" disabled={index === 0} onClick={() => step(-1)} />}\n {list.length > 1 && <IconButton icon={SkipForward} label=\"Next chapter\" disabled={index === list.length - 1} onClick={() => step(1)} />}\n </Transport>\n {list.length > 1 && (\n <span className=\"type-body-sm text-muted-foreground\">\n {current?.title} ({index + 1} of {list.length})\n </span>\n )}\n <span className=\"ml-auto flex items-center gap-3\">\n <RateChoice rate={media.rate} onRateChange={media.setRate} rates={rates} />\n <VolumeControl volume={media.volume} onVolumeChange={media.setVolume} />\n </span>\n </div>\n </div>\n )}\n </div>\n );\n}\n","// The arithmetic of a time axis, kept apart from drawing so it can be tested without a layout\n// (strata issue #77). Times are numbers in one unit the app picks (seconds for media, minutes or\n// hours for a schedule); `pxPerUnit` is the zoom.\n\n/** Steps a person would write on a scale, in seconds: 1, 2, 5 and 10 × 10ⁿ below a minute, then 15 s, 30 s, minutes, quarter hours, hours, days. ux-research components.md §3.8: ticks land on values people would write. */\nconst STEPS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 14400, 21600, 43200, 86400];\n\n/** The smallest step whose ticks are at least `minGapPx` apart at this zoom, so labels thin out instead of colliding. */\nexport function tickStep(pxPerUnit: number, minGapPx = 80): number {\n return STEPS.find((s) => s * pxPerUnit >= minGapPx) ?? STEPS[STEPS.length - 1];\n}\n\n/** Tick times from `from` to `to` inclusive, on multiples of `step`. */\nexport function ticksBetween(from: number, to: number, step: number): number[] {\n const out: number[] = [];\n const first = Math.ceil(from / step - 1e-9);\n for (let i = first; i * step <= to + 1e-9; i++) out.push(Math.round(i * step * 1e6) / 1e6 || 0);\n return out;\n}\n\n/** A tick's label: m:ss, h:mm:ss, with tenths or hundredths when the step is under a second. */\nexport function tickLabel(time: number, step: number): string {\n const decimals = step < 0.1 ? 2 : step < 1 ? 1 : 0;\n const whole = Math.floor(time + 1e-9);\n const h = Math.floor(whole / 3600);\n const m = Math.floor((whole % 3600) / 60);\n const s = whole % 60;\n const two = (n: number) => String(n).padStart(2, \"0\");\n const base = h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`;\n return decimals ? `${base}.${String(Math.round((time - whole) * 10 ** decimals)).padStart(decimals, \"0\")}` : base;\n}\n\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/** The point to snap `time` to: the nearest of `points` within `thresholdPx` at this zoom, or `null`. */\nexport function snapTo(time: number, points: readonly number[], pxPerUnit: number, thresholdPx = 8): { time: number; point: number } | null {\n let best: number | null = null;\n for (const p of points) if (Math.abs(p - time) * pxPerUnit <= thresholdPx && (best === null || Math.abs(p - time) < Math.abs(best - time))) best = p;\n return best === null ? null : { time: best, point: best };\n}\n\n/** Round away float noise from adding steps (0.1 + 0.2). */\nexport const tidy = (n: number) => Math.round(n * 1e6) / 1e6;\n","import * as React from \"react\";\nimport { VisuallyHidden, mergeProps, useDrop, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport type { DropItem } from \"react-aria-components\";\nimport { useSliderState } from \"react-stately\";\nimport { Ban, Maximize2, ZoomIn, ZoomOut } from \"lucide-react\";\nimport { clamp, snapTo, tickLabel, tickStep, ticksBetween, tidy } from \"../lib/timeline\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\n\n// A time axis with lanes of items (strata issue #77, from a video editor's timeline; the research's\n// own example is a kiln schedule). Video and audio editors, rotas, resource bookings, Gantt-style\n// plans and deployment timelines are the same picture: a ruler, lanes, items with a start and a\n// length, a current-time line, markers.\n//\n// The component draws and the app decides. Every change (move, trim, change lane, set the current\n// time, select) is reported through a callback and applied by the app, so the app's own rules\n// (overlap, snapping to its grid, undo) stay in one place and the timeline never holds a second copy\n// of the data. A change the app refuses (`validate` returns a reason) is shown while it is being\n// made, with an icon and the reason in words, and is not reported.\n//\n// Keyboard first (the issue found nothing but Delete working). One tab stop for the items, with the\n// focus moving inside it: Left and Right go to the previous and next item in the lane, Up and Down\n// to the nearest in the lane above or below, Home and End to the lane's first and last. Enter or\n// Space selects (with Ctrl or Shift, adds to the selection). On the focused item: Ctrl+Left/Right\n// nudge it by `step` (Shift: ten steps), Ctrl+Up/Down move it a lane, Alt+Left/Right trim the end,\n// Alt+Shift+Left/Right trim the start, Delete asks the app to remove the selection. The current time\n// is React Aria's slider hooks, with the ruler as its track and the marker as its thumb (a press or\n// drag on the ruler moves it; arrows `step`, Shift ten steps, Page keys ten, Home and End the limits\n// are a capture handler on its input, because the hooks have one step and a drag needs a fine one; the\n// value is spoken through `formatTime`, which `Intl.NumberFormat` options cannot do).\n// `+`, `-` and `0` zoom in, out and to fit when `onZoomChange` is given. Every change is announced\n// politely in words: \"run-02.mp4 moved to 0:14, Track 1\".\n//\n// Items are named for a screen reader as \"run-02.mp4, 0:12 to 0:47, Track 1\" and lanes are labelled\n// groups. The ruler's labels are chosen from a ladder of steps a person would write on a scale\n// (1, 2, 5, 10 s, 15 s, 30 s, minutes…) wide enough apart that they never collide, and the end\n// labels stay inside the axis (components.md §3.8). Nothing animates on zoom, scroll or move: these\n// are the most repeated actions on the screen (ux-character.md, by frequency).\n//\n// Performance: items outside the visible window, plus a margin, are not rendered, so thousands of\n// items cost what is on screen. Widths come from the props (`zoom` is pixels per unit) and one\n// ResizeObserver reading the viewport, not from measuring items.\n//\n// Drops from outside (issue #121, strata-vid's library list). Each lane is a React Aria `useDrop`\n// target, so the pointer path, the keyboard path (React Aria's virtual drag: the lane takes focus\n// and Enter drops) and the screen-reader announcements are its. Checked in `useDrop.d.ts` and\n// `DragManager`: while a drag is over a lane the types are known but the items are not, so the\n// preview is `dropLength` long and the app learns what was dropped only in `onDrop`. A pointer\n// drop lands with its left edge at the pointer, snapped like a move; a virtual drop reports the\n// lane's centre, not a time (and in a different coordinate space from a pointer's), so it is told\n// apart by the lane being the focused element and lands at the current time (`position`, else the\n// start). `validateDrop` is `validate` for a drop: the refusal shows beside the preview while it is\n// over a lane and is announced for the keyboard.\n//\n// Pointer moves are our own pointer events with a 3px threshold between click and drag. React\n// Aria's `useMove` (in `react-aria`, a transitive dependency of `react-aria-components`) would do\n// the pointer and arrow-key deltas, but using it means listing `react-aria` as a direct\n// dependency, which is Jonathan's call (CLAUDE.md), so it is not done here; it is offered in the\n// PR. Native HTML drag and drop (#76's `SortableList`) is for lists and cannot give a live,\n// snapped, zoom-aware position along time, which is why this is not built on it.\n\nexport type TimelineItem = {\n id: string;\n /** The lane's id. */\n lane: string;\n start: number;\n length: number;\n /** The item's name, in the item and for a screen reader. */\n label: string;\n /** What kind of thing it is (video, audio, booking). Shown as a word and a colour stripe, never colour alone. Its colour is `kindColours[kind]`, else the chart palette in order of appearance. */\n kind?: string;\n};\n\nexport type TimelineLane = {\n id: string;\n label: string;\n /** The app's controls for the lane (mute, lock, delete). Drawn in the lane's header, at the left. */\n header?: React.ReactNode;\n};\n\nexport type TimelineMarker = { id: string; time: number; label: string };\n\n/** What a move or trim would produce. */\nexport type TimelineChange = { start: number; length: number; lane: string };\n\n/** Where something dragged in from outside landed. */\nexport type TimelineDrop = TimelineChange & { items: DropItem[] };\n\nexport type TimelineProps = {\n /** Names the timeline for a screen reader (\"Firing schedule\"). */\n label: string;\n lanes: readonly TimelineLane[];\n items: readonly TimelineItem[];\n /** The axis runs from this time. Default 0. */\n from?: number;\n /** ... to this time. */\n to: number;\n /** Pixels per unit of time. Controlled with `onZoomChange`. */\n zoom: number;\n onZoomChange?: (zoom: number) => void;\n /** The current time, drawn as a rule across the lanes and set by the slider on the ruler. */\n position?: number;\n onPositionChange?: (time: number) => void;\n /** Keep the current time in view as it advances. */\n follow?: boolean;\n markers?: readonly TimelineMarker[];\n selectedIds?: ReadonlySet<string>;\n /** The selection changed: `ids` is the whole new selection. */\n onSelect?: (ids: string[]) => void;\n /** The item was moved, trimmed or put in another lane. Not called for a change `validate` refused. */\n onItemChange?: (id: string, next: TimelineChange) => void;\n /** The person asked to remove the selection (Delete). The app does it, undoably. */\n onDelete?: (ids: string[]) => void;\n /** A reason a change cannot be made, in the product's words, or `null`. Called while dragging, so keep it cheap. */\n validate?: (id: string, next: TimelineChange) => string | null;\n /** Extra times items snap to, besides the edges of other items, markers and the current time. */\n snapPoints?: readonly number[];\n /** Turn snapping off. Default on. */\n snap?: boolean;\n /** One keyboard step, in time units. Default 1. */\n step?: number;\n /** Smallest an item may be, in time units. Default `step`. */\n minLength?: number;\n /** The colour of each kind's stripe, chosen by the app: a CSS colour, normally a role or a subject colour of its theme (`var(--info)`, `var(--kind-gpx)`). Without an entry a kind takes the chart palette in order of appearance, which moves when the set of kinds changes. */\n kindColours?: Readonly<Record<string, string>>;\n /** How many control heights tall each lane is. Default 1; 2 or 3 for items that draw thumbnails or a waveform. */\n laneRows?: number;\n /** Drag types a lane accepts from outside the timeline (`\"text/plain\"`, an app type). Without it nothing can be dropped. */\n dropTypes?: readonly string[];\n /** Length of an item dropped from outside, for the preview and for `validateDrop`. Default five steps. */\n dropLength?: number;\n /** Something was dropped on a lane at a time (snapped like a move). The app makes the item. Not called for a drop `validateDrop` refused. */\n onDrop?: (drop: TimelineDrop) => void;\n /** A reason a drop cannot be made, in the product's words, or `null`. Called while a drag is over a lane, so keep it cheap. */\n validateDrop?: (next: TimelineChange) => string | null;\n /** Draws an item's content (a strip of thumbnails, a waveform). Default: the label and kind. */\n renderItem?: (item: TimelineItem, state: { selected: boolean; width: number }) => React.ReactNode;\n /** A time as words (\"0:14\", \"13:30\"). Default `m:ss`, with tenths on the ruler when zoomed far in. Also labels the ruler when given, so a schedule in hours reads as clock times. */\n formatTime?: (time: number) => string;\n /** Shown instead of the lanes' area when there are no lanes. */\n empty?: React.ReactNode;\n className?: string;\n};\n\nconst EDGE_PX = 8;\nconst DRAG_THRESHOLD = 3;\n\nconst defaultFormat = (t: number) => tickLabel(t, 1);\n\ntype Drag = { id: string; mode: \"move\" | \"start\" | \"end\"; originX: number; origin: TimelineItem; next: TimelineChange; reason: string | null; guide: number | null; moved: boolean };\n\n/** Zoom state for a timeline: `zoomIn`, `zoomOut`, and `fit` to a viewport width. Pass `zoom` and `setZoom` as the timeline's `zoom` and `onZoomChange`. */\nexport function useTimelineZoom({ initial = 20, min = 0.5, max = 400 }: { initial?: number; min?: number; max?: number } = {}) {\n const [zoom, set] = React.useState(initial);\n const setZoom = React.useCallback((z: number) => set(clamp(z, min, max)), [min, max]);\n return {\n zoom,\n setZoom,\n zoomIn: () => setZoom(zoom * 1.5),\n zoomOut: () => setZoom(zoom / 1.5),\n /** Zoom so `duration` fills `viewportWidth` pixels. */\n fit: (viewportWidth: number, duration: number) => setZoom(viewportWidth / Math.max(duration, 1e-6)),\n };\n}\n\n/** Zoom in, zoom out and fit, as named icon buttons for a timeline's toolbar. */\nexport function TimelineZoomControls({ zoom }: { zoom: Pick<ReturnType<typeof useTimelineZoom>, \"zoomIn\" | \"zoomOut\"> & { fit: () => void } }) {\n return (\n <div className=\"flex items-center gap-1\">\n <IconButton icon={ZoomOut} label=\"Zoom out\" hint=\"-\" onClick={zoom.zoomOut} />\n <IconButton icon={ZoomIn} label=\"Zoom in\" hint=\"+\" onClick={zoom.zoomIn} />\n <IconButton icon={Maximize2} label=\"Fit to view\" hint=\"0\" onClick={zoom.fit} />\n </div>\n );\n}\n\n/** A rule that refuses an item overlapping another in its lane, for `validate`: names the item in the way. */\nexport function noOverlap(items: readonly TimelineItem[]): (id: string, next: TimelineChange) => string | null {\n return (id, next) => {\n const me = items.find((i) => i.id === id);\n const other = items.find((i) => i.id !== id && i.lane === next.lane && i.start < next.start + next.length - 1e-9 && next.start < i.start + i.length - 1e-9);\n return other ? `${me?.label ?? \"This\"} would overlap ${other.label}.` : null;\n };\n}\n\n/** Items placed on a zoomable time axis in lanes, with a current-time rule and markers. Reports every move, trim, selection and time change; the app applies them. Keyboard-complete, and only the items near the view are rendered. */\nexport function Timeline({\n label,\n lanes,\n items,\n from = 0,\n to,\n zoom,\n onZoomChange,\n position,\n onPositionChange,\n follow,\n markers = [],\n selectedIds,\n onSelect,\n onItemChange,\n onDelete,\n validate,\n snapPoints = [],\n snap = true,\n step = 1,\n minLength,\n renderItem,\n kindColours,\n laneRows = 1,\n dropTypes,\n dropLength,\n onDrop,\n validateDrop,\n formatTime = defaultFormat,\n empty,\n className,\n}: TimelineProps) {\n const min = minLength ?? step;\n const scroller = React.useRef<HTMLDivElement>(null);\n const laneRefs = React.useRef(new Map<string, HTMLElement>());\n const [view, setView] = React.useState({ left: 0, width: 640 });\n const [drag, setDrag] = React.useState<Drag | null>(null);\n const dragRef = React.useRef<Drag | null>(null);\n const [focusId, setFocusId] = React.useState<string | null>(null);\n const [said, setSaid] = React.useState(\"\");\n const [hover, setHover] = React.useState<{ next: TimelineChange; reason: string | null; guide: number | null } | null>(null);\n const refocus = React.useRef<string | null>(null);\n const selected = selectedIds ?? new Set<string>();\n const laneIndex = React.useMemo(() => new Map(lanes.map((l, i) => [l.id, i])), [lanes]);\n const laneLabel = (id: string) => lanes.find((l) => l.id === id)?.label ?? id;\n const width = Math.max((to - from) * zoom, 1);\n const x = (t: number) => (t - from) * zoom;\n\n // The viewport: its width, and where it is scrolled. Items outside it (plus a margin of one\n // viewport on each side) are not rendered.\n React.useEffect(() => {\n const el = scroller.current;\n if (!el) return;\n const read = () => setView({ left: el.scrollLeft, width: el.clientWidth || 640 });\n read();\n const ro = new ResizeObserver(read);\n ro.observe(el);\n el.addEventListener(\"scroll\", read, { passive: true });\n return () => {\n ro.disconnect();\n el.removeEventListener(\"scroll\", read);\n };\n }, []);\n\n // Follow the current time: scroll only when it leaves the view, so a person who scrolled away to\n // look is not dragged back while it is still on screen.\n React.useEffect(() => {\n const el = scroller.current;\n if (!follow || position === undefined || !el) return;\n const px = x(position);\n if (px < el.scrollLeft || px > el.scrollLeft + el.clientWidth - 24) el.scrollLeft = Math.max(px - el.clientWidth * 0.25, 0);\n }, [follow, position, zoom]); // eslint-disable-line react-hooks/exhaustive-deps\n\n React.useEffect(() => {\n const id = refocus.current;\n if (!id) return;\n refocus.current = null;\n const el = scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`);\n if (el && document.activeElement !== el && (!document.activeElement || document.activeElement === document.body || !scroller.current?.contains(document.activeElement))) el.focus();\n }, [items]);\n\n const sorted = React.useMemo(() => {\n const byLane = new Map<string, TimelineItem[]>();\n for (const l of lanes) byLane.set(l.id, []);\n for (const i of items) byLane.get(i.lane)?.push(i);\n for (const list of byLane.values()) list.sort((a, b) => a.start - b.start);\n return byLane;\n }, [lanes, items]);\n\n const snapTimes = React.useMemo(() => {\n const pts = [...snapPoints, ...markers.map((m) => m.time)];\n if (position !== undefined) pts.push(position);\n return pts;\n }, [snapPoints, markers, position]);\n\n /** Apply a change: validate, report, and say it. Returns the refusal, if any. */\n const commit = (item: TimelineItem, next: TimelineChange): string | null => {\n const reason = validate?.(item.id, next) ?? null;\n if (reason) {\n setSaid(reason);\n return reason;\n }\n // A change of lane remounts the item's element in the new lane; put focus back on it once the app has applied the change.\n refocus.current = item.id;\n onItemChange?.(item.id, next);\n const where = next.lane !== item.lane ? `, ${laneLabel(next.lane)}` : \"\";\n setSaid(\n next.start !== item.start && next.length === item.length\n ? `${item.label} moved to ${formatTime(next.start)}${where}.`\n : next.lane !== item.lane\n ? `${item.label} moved to ${laneLabel(next.lane)}.`\n : `${item.label} now ${formatTime(next.start)} to ${formatTime(next.start + next.length)}.`,\n );\n return null;\n };\n\n const select = (id: string, add: boolean) => {\n const next = add ? (selected.has(id) ? [...selected].filter((s) => s !== id) : [...selected, id]) : [id];\n onSelect?.(next);\n };\n\n // --- keyboard on an item -------------------------------------------------------------------\n const focusItem = (id: string) => {\n setFocusId(id);\n requestAnimationFrame(() => scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`)?.focus());\n // jsdom has no layout and runs rAF late; focus now too when the element is already mounted.\n scroller.current?.querySelector<HTMLElement>(`[data-item=\"${CSS.escape(id)}\"]`)?.focus();\n const item = items.find((i) => i.id === id);\n if (item && scroller.current) {\n const el = scroller.current;\n if (x(item.start) < el.scrollLeft) el.scrollLeft = x(item.start) - 16;\n else if (x(item.start + item.length) > el.scrollLeft + el.clientWidth) el.scrollLeft = x(item.start + item.length) - el.clientWidth + 16;\n }\n };\n\n const onItemKeyDown = (e: React.KeyboardEvent, item: TimelineItem) => {\n const k = e.key;\n const big = e.shiftKey ? 10 : 1;\n const lane = sorted.get(item.lane) ?? [];\n const idx = lane.findIndex((i) => i.id === item.id);\n const handled = () => {\n e.preventDefault();\n e.stopPropagation();\n };\n if (e.ctrlKey || e.metaKey) {\n if (k === \"ArrowLeft\" || k === \"ArrowRight\") {\n handled();\n const dir = k === \"ArrowLeft\" ? -1 : 1;\n commit(item, { start: clamp(tidy(item.start + dir * step * big), from, to - item.length), length: item.length, lane: item.lane });\n } else if (k === \"ArrowUp\" || k === \"ArrowDown\") {\n handled();\n const target = lanes[(laneIndex.get(item.lane) ?? 0) + (k === \"ArrowUp\" ? -1 : 1)];\n if (target) commit(item, { start: item.start, length: item.length, lane: target.id });\n return;\n }\n // Ctrl or Cmd with Enter or Space adds to the selection; the switch below handles it.\n if (k !== \"Enter\" && k !== \" \") return;\n }\n if (e.altKey && (k === \"ArrowLeft\" || k === \"ArrowRight\")) {\n handled();\n const dir = k === \"ArrowLeft\" ? -1 : 1;\n if (e.shiftKey) {\n // Trim the start: Right shortens from the start, Left extends it.\n const start = clamp(tidy(item.start + dir * step), from, item.start + item.length - min);\n commit(item, { start, length: tidy(item.start + item.length - start), lane: item.lane });\n } else {\n commit(item, { start: item.start, length: clamp(tidy(item.length + dir * step), min, to - item.start), lane: item.lane });\n }\n return;\n }\n switch (k) {\n case \"ArrowLeft\":\n handled();\n if (lane[idx - 1]) focusItem(lane[idx - 1].id);\n break;\n case \"ArrowRight\":\n handled();\n if (lane[idx + 1]) focusItem(lane[idx + 1].id);\n break;\n case \"ArrowUp\":\n case \"ArrowDown\": {\n handled();\n const neighbour = lanes[(laneIndex.get(item.lane) ?? 0) + (k === \"ArrowUp\" ? -1 : 1)];\n const candidates = neighbour ? (sorted.get(neighbour.id) ?? []) : [];\n const nearest = candidates.reduce<TimelineItem | null>((best, c) => (!best || Math.abs(c.start - item.start) < Math.abs(best.start - item.start) ? c : best), null);\n if (nearest) focusItem(nearest.id);\n break;\n }\n case \"Home\":\n handled();\n if (lane[0]) focusItem(lane[0].id);\n break;\n case \"End\":\n handled();\n if (lane.length) focusItem(lane[lane.length - 1].id);\n break;\n case \"Enter\":\n case \" \":\n handled();\n select(item.id, e.shiftKey || e.ctrlKey || e.metaKey);\n break;\n case \"Delete\":\n case \"Backspace\":\n if (selected.size && onDelete) {\n handled();\n onDelete([...selected]);\n }\n break;\n }\n };\n\n /** Snaps an item of `length` starting at `start` to whichever of its ends is nearer an edge. */\n const snapMove = (start: number, length: number, exclude?: string) => {\n const edges = [...snapTimes, ...items.filter((i) => i.id !== exclude).flatMap((i) => [i.start, i.start + i.length])];\n const a = snap ? snapTo(start, edges, zoom) : null;\n const b = snap ? snapTo(start + length, edges, zoom) : null;\n if (a && (!b || Math.abs(a.time - start) <= Math.abs(b.time - (start + length)))) return { start: a.time, guide: a.point as number | null };\n if (b) return { start: b.time - length, guide: b.point as number | null };\n return { start, guide: null as number | null };\n };\n\n // --- drops from outside ----------------------------------------------------------------------\n const dropLen = dropLength ?? step * 5;\n const dropAt = (lane: string, px: number | null) => {\n const at = px === null ? (position ?? from) : from + px / zoom;\n const snapped = snapMove(at, dropLen);\n const next: TimelineChange = { start: clamp(tidy(snapped.start), from, Math.max(to - dropLen, from)), length: dropLen, lane };\n return { next, guide: snapped.guide, reason: validateDrop?.(next) ?? null };\n };\n const onLaneHover = (lane: string, px: number | null) => {\n const h = dropAt(lane, px);\n setHover(h);\n // A pointer sees the preview; the keyboard is told, as nothing else says where the drop would land.\n if (px === null) setSaid(h.reason ?? `Drop here: ${laneLabel(lane)} at ${formatTime(h.next.start)}.`);\n };\n const onLaneDrop = (lane: string, px: number | null, dropped: DropItem[]) => {\n setHover(null);\n const h = dropAt(lane, px);\n if (h.reason) {\n setSaid(h.reason);\n return;\n }\n onDrop?.({ ...h.next, items: dropped });\n setSaid(`Added at ${formatTime(h.next.start)}, ${laneLabel(lane)}.`);\n };\n const dropsOn = Boolean(dropTypes?.length && onDrop);\n\n // --- pointer: move and trim ----------------------------------------------------------------\n const begin = (e: React.PointerEvent, item: TimelineItem, mode: Drag[\"mode\"]) => {\n if (e.button !== 0) return;\n e.stopPropagation();\n (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);\n const d: Drag = { id: item.id, mode, originX: e.clientX, origin: item, next: { start: item.start, length: item.length, lane: item.lane }, reason: null, guide: null, moved: false };\n dragRef.current = d;\n setDrag(d);\n };\n\n const laneAt = (clientY: number, fallback: string) => {\n for (const [id, el] of laneRefs.current) {\n const r = el.getBoundingClientRect();\n if (clientY >= r.top && clientY < r.bottom) return id;\n }\n return fallback;\n };\n\n const onPointerMove = (e: React.PointerEvent) => {\n const d = dragRef.current;\n if (!d) return;\n const dx = e.clientX - d.originX;\n if (!d.moved && Math.abs(dx) < DRAG_THRESHOLD && d.mode !== \"move\") return;\n const dt = dx / zoom;\n const o = d.origin;\n let next: TimelineChange = { start: o.start, length: o.length, lane: o.lane };\n let guide: number | null = null;\n const edges = [...snapTimes, ...items.filter((i) => i.id !== o.id).flatMap((i) => [i.start, i.start + i.length])];\n const snapped = (t: number) => {\n const s = snap ? snapTo(t, edges, zoom) : null;\n if (s) guide = s.point;\n return s ? s.time : t;\n };\n if (d.mode === \"move\") {\n const m = snapMove(o.start + dt, o.length, o.id);\n const start = m.start;\n guide = m.guide;\n next = { start: clamp(tidy(start), from, to - o.length), length: o.length, lane: laneAt(e.clientY, o.lane) };\n } else if (d.mode === \"end\") {\n next = { start: o.start, length: clamp(tidy(snapped(o.start + o.length + dt) - o.start), min, to - o.start), lane: o.lane };\n } else {\n const start = clamp(tidy(snapped(o.start + dt)), from, o.start + o.length - min);\n next = { start, length: tidy(o.start + o.length - start), lane: o.lane };\n }\n const moved = d.moved || Math.abs(dx) >= DRAG_THRESHOLD || next.lane !== o.lane;\n const updated: Drag = { ...d, next, guide, moved, reason: moved ? (validate?.(o.id, next) ?? null) : null };\n dragRef.current = updated;\n setDrag(updated);\n };\n\n const onPointerUp = (e: React.PointerEvent) => {\n const d = dragRef.current;\n dragRef.current = null;\n setDrag(null);\n if (!d) return;\n (e.currentTarget as HTMLElement).releasePointerCapture?.(e.pointerId);\n if (!d.moved) {\n if (d.mode === \"move\") select(d.id, e.shiftKey || e.ctrlKey || e.metaKey);\n return;\n }\n if (d.reason) setSaid(d.reason);\n else commit(d.origin, d.next);\n };\n\n // --- the ruler and the current time --------------------------------------------------------\n const stepSize = tickStep(zoom);\n const ticks = React.useMemo(() => ticksBetween(from, to, stepSize), [from, to, stepSize]);\n const setPosition = (t: number) => onPositionChange?.(clamp(tidy(t), from, to));\n // The current time is React Aria's slider: the ruler is its track (a press or drag on it moves the\n // time), and the marker is its thumb. The value text goes through `formatTime`, and the keys are a\n // capture handler on the input (see `onSliderKey`), for the reasons in the opening comment.\n const scrubTrack = React.useRef<HTMLDivElement>(null);\n const scrubInput = React.useRef<HTMLInputElement>(null);\n const spokenTime = React.useMemo(\n () => ({ format: formatTime, formatRange: (a: number, b: number) => `${formatTime(a)} to ${formatTime(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) }) as unknown as Intl.NumberFormat,\n [formatTime],\n );\n const scrubState = useSliderState({\n minValue: from,\n maxValue: Math.max(to, from + 1e-9),\n step: 0.001,\n value: [clamp(position ?? from, from, to)],\n onChange: ([t]) => setPosition(t),\n numberFormatter: spokenTime,\n isDisabled: position === undefined || !onPositionChange,\n });\n const { trackProps: rulerProps } = useSlider({ \"aria-label\": \"Current time\", isDisabled: position === undefined || !onPositionChange }, scrubState, scrubTrack);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: scrubTrack, inputRef: scrubInput, \"aria-label\": \"Current time\", isDisabled: position === undefined || !onPositionChange }, scrubState);\n const { focusProps, isFocusVisible } = useFocusRing();\n const onSliderKey = (e: React.KeyboardEvent) => {\n if (position === undefined) return;\n const big = e.shiftKey ? 10 : 1;\n const moves: Record<string, number> = { ArrowLeft: -step * big, ArrowDown: -step * big, ArrowRight: step * big, ArrowUp: step * big, PageDown: -step * 10, PageUp: step * 10 };\n if (e.key in moves) setPosition(position + moves[e.key]);\n else if (e.key === \"Home\") setPosition(from);\n else if (e.key === \"End\") setPosition(to);\n else return;\n e.preventDefault();\n e.stopPropagation();\n };\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (!onZoomChange || e.ctrlKey || e.metaKey || e.altKey) return;\n if (e.key === \"+\" || e.key === \"=\") onZoomChange(zoom * 1.5);\n else if (e.key === \"-\") onZoomChange(zoom / 1.5);\n else if (e.key === \"0\") onZoomChange(view.width / Math.max(to - from, 1e-6));\n else return;\n e.preventDefault();\n };\n\n // Ctrl or Cmd with the wheel zooms about the pointer (a plain wheel scrolls). Attached natively\n // because React's wheel listener is passive and cannot stop the page zooming.\n React.useEffect(() => {\n const el = scroller.current;\n if (!el || !onZoomChange) return;\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n onZoomChange(e.deltaY < 0 ? zoom * 1.25 : zoom / 1.25);\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, [onZoomChange, zoom]);\n\n const rovingId = focusId && items.some((i) => i.id === focusId) ? focusId : (sorted.get(lanes[0]?.id ?? \"\")?.[0]?.id ?? items[0]?.id ?? null);\n // Only items near the view are drawn, and always the focused one so focus is never lost.\n const lo = view.left - view.width;\n const hi = view.left + 2 * view.width;\n const visible = (i: TimelineItem) => i.id === focusId || i.id === rovingId || (x(i.start + i.length) >= lo && x(i.start) <= hi);\n\n const itemLabel = (i: TimelineItem) => `${i.label}, ${formatTime(i.start)} to ${formatTime(i.start + i.length)}, ${laneLabel(i.lane)}`;\n\n return (\n <div role=\"group\" aria-label={label} onKeyDown={onKeyDown} className={cn(\"min-w-0 text-foreground\", className)} style={{ \"--lane-h\": `calc(var(--control-h) * ${Math.max(laneRows, 1)})` } as React.CSSProperties}>\n <p role=\"status\" className=\"sr-only\">\n {said}\n </p>\n <div className=\"flex\">\n <div className=\"w-max max-w-80 min-w-40 shrink-0 border-r border-border\">\n <div className=\"h-8 border-b border-border\" aria-hidden />\n {lanes.map((l) => (\n <div key={l.id} className=\"flex h-(--lane-h) items-center gap-1 border-b border-border px-2 type-label\">\n <span className=\"min-w-0 flex-1 truncate\" title={l.label}>\n {l.label}\n </span>\n {l.header}\n </div>\n ))}\n </div>\n <div ref={scroller} className=\"relative min-w-0 flex-1 overflow-x-auto\">\n <div className=\"relative\" style={{ width }}>\n {/* The ruler: ticks and labels on a ladder of steps, thinned so they never collide, the end labels kept inside the axis. */}\n <div {...rulerProps} ref={scrubTrack} className=\"relative h-8 touch-none border-b border-border\" data-ruler>\n {ticks.map((t) => {\n const px = x(t);\n const last = px > width - 40;\n return (\n <span key={t} aria-hidden className=\"absolute top-0 h-full border-l border-border pl-1 type-caption text-muted-foreground tabular-nums\" style={{ left: px, transform: last ? \"translateX(-100%)\" : undefined, borderLeftWidth: last ? 0 : 1, paddingRight: last ? 4 : 0 }}>\n {formatTime === defaultFormat ? tickLabel(t, stepSize) : formatTime(t)}\n </span>\n );\n })}\n {markers.map((m) => (\n <button\n key={m.id}\n type=\"button\"\n aria-label={`Marker: ${m.label}, ${formatTime(m.time)}`}\n onPointerDown={(e) => e.stopPropagation()}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={() => setPosition(m.time)}\n className=\"absolute bottom-0 max-w-32 -translate-x-px truncate rounded-control border-l-2 border-foreground bg-muted px-1 type-caption\"\n style={{ left: x(m.time) }}\n >\n {m.label}\n </button>\n ))}\n {position !== undefined && (\n <div {...thumbProps} className={cn(\"absolute top-0 -ml-2 h-full w-4 cursor-ew-resize\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")} style={{ left: x(position) }}>\n <span aria-hidden className=\"mx-auto block size-3 rounded-pill bg-primary\" />\n <VisuallyHidden>\n <input ref={scrubInput} {...mergeProps(inputProps, focusProps)} aria-labelledby={undefined} onKeyDownCapture={onSliderKey} />\n </VisuallyHidden>\n </div>\n )}\n </div>\n {lanes.length === 0 && <div className=\"p-4\">{empty}</div>}\n {lanes.map((l) => (\n <LaneRow\n key={l.id}\n label={l.label}\n register={(el) => void (el ? laneRefs.current.set(l.id, el) : laneRefs.current.delete(l.id))}\n types={dropsOn ? dropTypes : undefined}\n onHover={(px) => onLaneHover(l.id, px)}\n onLeave={() => setHover(null)}\n onDropItems={(px, dropped) => onLaneDrop(l.id, px, dropped)}\n >\n {hover && hover.next.lane === l.id && (\n <div aria-hidden className={cn(\"pointer-events-none absolute top-1 bottom-1 rounded-control border border-dashed\", hover.reason ? \"border-danger bg-danger-subtle\" : \"border-primary bg-muted\")} style={{ left: x(hover.next.start), width: Math.max(hover.next.length * zoom, 4) }} />\n )}\n {(sorted.get(l.id) ?? []).filter(visible).map((item) => {\n const live = drag?.id === item.id && drag.moved ? drag : null;\n // Stays mounted in its own lane while dragged (it holds the pointer capture) and is\n // shifted by whole lanes to show where it would land.\n const shown = live ? live.next : item;\n const laneShift = live ? (laneIndex.get(live.next.lane) ?? 0) - (laneIndex.get(item.lane) ?? 0) : 0;\n const isSel = selected.has(item.id);\n const px = x(shown.start);\n const w = Math.max(shown.length * zoom, 4);\n return (\n <div\n key={item.id}\n data-item={item.id}\n role=\"button\"\n aria-pressed={isSel}\n aria-label={itemLabel(item)}\n tabIndex={item.id === rovingId ? 0 : -1}\n onFocus={() => setFocusId(item.id)}\n onKeyDown={(e) => onItemKeyDown(e, item)}\n onPointerDown={(e) => begin(e, item, \"move\")}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n className={cn(\n \"absolute top-1 bottom-1 min-w-1 cursor-grab touch-none overflow-hidden rounded-control border border-input border-t-4 bg-background px-1.5 type-caption select-none\",\n isSel && \"bg-muted font-medium outline-2 outline-offset-1 outline-primary\",\n live?.reason && \"border-dashed border-danger bg-danger-subtle\",\n )}\n style={{ left: px, width: w, borderTopColor: item.kind ? (kindColours?.[item.kind] ?? kindColour(item.kind, items)) : undefined, transform: laneShift ? `translateY(calc(var(--lane-h) * ${laneShift}))` : undefined, zIndex: live ? 10 : undefined }}\n >\n {renderItem ? renderItem(item, { selected: isSel, width: w }) : <DefaultItem item={item} width={w} />}\n {/* Trim handles: pointer-only. The keyboard trims with Alt+arrows. */}\n <span aria-hidden className=\"absolute inset-y-0 left-0 cursor-ew-resize touch-none\" style={{ width: EDGE_PX }} onPointerDown={(e) => begin(e, item, \"start\")} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />\n <span aria-hidden className=\"absolute inset-y-0 right-0 cursor-ew-resize touch-none\" style={{ width: EDGE_PX }} onPointerDown={(e) => begin(e, item, \"end\")} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />\n </div>\n );\n })}\n </LaneRow>\n ))}\n {position !== undefined && <div aria-hidden className=\"pointer-events-none absolute top-8 bottom-0 w-0.5 bg-primary\" style={{ left: x(position) - 1 }} />}\n {(() => {\n const guide = drag?.moved ? drag.guide : (hover?.guide ?? null);\n return guide !== null && <div aria-hidden className=\"pointer-events-none absolute top-0 bottom-0 w-px bg-foreground\" style={{ left: x(guide) }} />;\n })()}\n </div>\n </div>\n </div>\n {(() => {\n const info = drag?.moved ? { next: drag.next, reason: drag.reason } : hover;\n return (\n info && (\n <p aria-hidden className=\"mt-1 flex items-center gap-1.5 type-body-sm tabular-nums text-muted-foreground\">\n {info.reason ? (\n <>\n <Ban className=\"size-4 shrink-0 text-danger\" />\n <span className=\"text-danger\">{info.reason}</span>\n </>\n ) : (\n <>\n {formatTime(info.next.start)} to {formatTime(info.next.start + info.next.length)}, {laneLabel(info.next.lane)}\n </>\n )}\n </p>\n )\n );\n })()}\n </div>\n );\n}\n\nfunction kindColour(kind: string, items: readonly TimelineItem[]) {\n const kinds = [...new Set(items.map((i) => i.kind).filter(Boolean))] as string[];\n return `var(--chart-${(Math.max(kinds.indexOf(kind), 0) % 5) + 1})`;\n}\n\nfunction DefaultItem({ item, width }: { item: TimelineItem; width: number }) {\n return (\n <span className=\"flex h-full min-w-0 items-center gap-1.5\">\n <span className=\"min-w-0 flex-1 truncate\">{item.label}</span>\n {item.kind && width > 120 && <span className=\"shrink-0 text-muted-foreground\">{item.kind}</span>}\n </span>\n );\n}\n\n/** One lane: a labelled group that is a React Aria drop target when `types` is given. `px` is the pointer's distance along the lane, or null for a keyboard drag (the lane is then the focused element). */\nfunction LaneRow({ label, register, types, onHover, onLeave, onDropItems, children }: { label: string; register: (el: HTMLDivElement | null) => void; types?: readonly string[]; onHover: (px: number | null) => void; onLeave: () => void; onDropItems: (px: number | null, items: DropItem[]) => void; children: React.ReactNode }) {\n const ref = React.useRef<HTMLDivElement | null>(null);\n const keyboard = () => document.activeElement === ref.current;\n const { dropProps } = useDrop({\n ref,\n isDisabled: !types,\n // A pointer drag hands over a `DragTypes` and a keyboard (virtual) drag a plain `Set` (checked in\n // `DragManager`), and only the first takes an array in `has`, so each type is asked on its own.\n getDropOperation: (t) => (types?.some((type) => t.has(type)) ? \"copy\" : \"cancel\"),\n onDropEnter: (e) => onHover(keyboard() ? null : e.x),\n onDropMove: (e) => onHover(keyboard() ? null : e.x),\n onDropExit: onLeave,\n // A browser sends no drop for a refused type; a keyboard drag's event says so in `dropOperation`.\n onDrop: (e) => e.dropOperation !== \"cancel\" && onDropItems(keyboard() ? null : e.x, e.items),\n });\n return (\n <div\n {...(types ? dropProps : {})}\n ref={(el) => {\n ref.current = el;\n register(el);\n }}\n role=\"group\"\n aria-label={label}\n // Focusable by script only: React Aria's keyboard drag moves focus to the lane it is over.\n tabIndex={types ? -1 : undefined}\n className=\"relative h-(--lane-h) border-b border-border\"\n >\n {children}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Ban, GripVertical } from \"lucide-react\";\nimport { Button as AriaButton, DropIndicator, GridList, GridListItem, useDragAndDrop } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A list whose items can be reordered and moved to other lists (strata issue #76, from a video\n// editor's tracks and library). One component for both because they are one gesture: pick an item\n// up, see where it will land, drop or cancel.\n//\n// React Aria first, and this is a case where it is the whole answer, so nothing else is added\n// (`@dnd-kit`, which the app being moved used, is not needed). `GridList` with `useDragAndDrop` gives:\n// the keyboard path (focus the grip, Enter picks up, arrows move between positions and between\n// lists that accept the item, Enter drops, Escape cancels, the item goes back), screen-reader\n// announcements at each step (React Aria's own words, localised; they name the item by `getLabel`),\n// a drop indicator line between rows, auto-scroll near a scroll container's edge, and a drag\n// preview. Checked in `useDragAndDrop.d.ts` and `GridList.d.ts`: `renderEmptyState` receives\n// `isDropTarget`, so an empty list can say \"Drop here\". What it cannot do is say WHY a target\n// refuses (a refusing target is simply not a target), so we read the dragged kinds in\n// `getDropOperation` and show the reason in the list, with an icon and words, never colour alone.\n//\n// Click and drag are separate by construction: dragging starts from the grip (`slot=\"drag\"`), a\n// real named button, so clicking the row selects it and pressing its own actions runs them.\n//\n// Kinds: each item has a kind (`getKind`, default \"item\") carried in the drag as a type\n// (`strata-kind/<kind>`). A list takes kinds listed in `accepts`; reordering within itself always\n// works. That is enough to say \"tracks take video and audio, not text\" before the drop.\n//\n// The list never changes the data. `onReorder` and `onInsert` say what was asked for and the app\n// applies it (and makes it undoable, patterns.md §7: a move is reversed, not confirmed). A drop on\n// a refusing list changes nothing: React Aria never calls them.\n//\n// No motion beyond the drop indicator appearing: dragging happens tens of times a session and the\n// item follows the pointer with no lag (ux-character.md, by frequency).\n\nconst KIND = \"strata-kind/\";\nconst ID = \"strata-item/id\";\nconst LIST = \"strata-list/\";\n\n/** Where a drop landed, relative to the item with `key`. */\nexport type DropTarget = { key: string; position: \"before\" | \"after\" | \"on\" } | { key: null; position: \"root\" };\n\nexport type SortableListProps<T> = {\n /** Names the list (\"Tracks\"). Required. */\n label: string;\n items: readonly T[];\n getKey: (item: T) => string;\n /** The item's name for a screen reader, typeahead and announcements (\"Picked up Moonbeam bowl\"). */\n getLabel: (item: T) => string;\n /** The row's content, beside the grip. Plain text and marks; actions go in `renderActions`. */\n children: (item: T) => React.ReactNode;\n /** Controls for the row (a `RowAction`), outside the row's selection target. */\n renderActions?: (item: T) => React.ReactNode;\n /** Shown when the list is empty, and \"Drop here\" while something is dragged over it. */\n empty: React.ReactNode;\n /** The item was moved within this list: `keys` now sit at `target`. */\n onReorder: (keys: string[], target: DropTarget) => void;\n /** An item of another list was dropped here. The app finds it by id and moves it. Needs `accepts`. */\n onInsert?: (ids: string[], target: DropTarget) => void;\n /** What an item is, for deciding which lists take it. Default: every item is \"item\". */\n getKind?: (item: T) => string;\n /** Kinds this list takes from other lists. Default none: it only reorders. */\n accepts?: readonly string[];\n /** Why a kind is refused, in the product's words, shown while one is dragged over: `{ text: \"Tracks take video and audio, not text clips.\" }`. React Aria cannot list what is being dragged, only ask about a kind, so name the kinds that exist. */\n refuses?: Readonly<Record<string, string>>;\n selectionMode?: \"none\" | \"single\" | \"multiple\";\n selectedKeys?: ReadonlySet<string>;\n onSelectionChange?: (keys: Set<string>) => void;\n className?: string;\n};\n\n/** A list that reorders by drag and by keyboard, and takes items from other lists by kind. It reports what was asked and never changes the data itself. */\nexport function SortableList<T>({\n label,\n items,\n getKey,\n getLabel,\n children,\n renderActions,\n empty,\n onReorder,\n onInsert,\n getKind = () => \"item\",\n accepts = [],\n refuses = {},\n selectionMode = \"none\",\n selectedKeys,\n onSelectionChange,\n className,\n}: SortableListProps<T>) {\n const listId = React.useId();\n const byKey = React.useMemo(() => new Map(items.map((i) => [getKey(i), i])), [items, getKey]);\n // The reason a drag over this list is refused, while one is. Cleared when the drag ends or leaves.\n const [refused, setRefused] = React.useState<string | null>(null);\n const root = React.useRef<HTMLDivElement>(null);\n React.useEffect(() => {\n if (!refused) return;\n const clear = () => setRefused(null);\n document.addEventListener(\"dragend\", clear);\n document.addEventListener(\"drop\", clear);\n return () => {\n document.removeEventListener(\"dragend\", clear);\n document.removeEventListener(\"drop\", clear);\n };\n }, [refused]);\n\n const toTarget = (t: { type: string; key?: unknown; dropPosition?: string }): DropTarget =>\n t.type === \"root\" ? { key: null, position: \"root\" } : { key: String(t.key), position: t.dropPosition as \"before\" | \"after\" | \"on\" };\n\n const { dragAndDropHooks } = useDragAndDrop<T>({\n getItems: (keys) =>\n [...keys].map((k) => {\n const item = byKey.get(String(k));\n return { [`${KIND}${item ? getKind(item) : \"item\"}`]: \"\", [`${LIST}${listId}`]: \"\", [ID]: String(k), \"text/plain\": item ? getLabel(item) : String(k) };\n }),\n // React Aria filters on this before `getDropOperation`: a refused kind must still reach it, to be explained.\n acceptedDragTypes: \"all\",\n getDropOperation: (_target, types) => {\n // Reordering is allowed for what came from this list; anything else must be a kind in `accepts`,\n // even if this list happens to hold an item of the same kind.\n const accepted = types.has(`${LIST}${listId}`) || accepts.some((k) => types.has(`${KIND}${k}`));\n if (accepted) {\n setRefused(null);\n return \"move\";\n }\n const kind = Object.keys(refuses).find((k) => types.has(`${KIND}${k}`));\n if (kind) setRefused(refuses[kind]);\n return \"cancel\";\n },\n onReorder: (e) => onReorder([...e.keys].map(String), toTarget(e.target)),\n onInsert: async (e) => {\n const ids = (await Promise.all(e.items.filter((i) => i.kind === \"text\").map((i) => i.getText(ID)))).filter(Boolean);\n onInsert?.(ids, toTarget(e.target));\n },\n onRootDrop: async (e) => {\n const ids = (await Promise.all(e.items.filter((i) => i.kind === \"text\").map((i) => i.getText(ID)))).filter(Boolean);\n onInsert?.(ids, { key: null, position: \"root\" });\n },\n renderDropIndicator: (target) => (\n <DropIndicator\n target={target}\n // A line with ends, so a position is a shape and not only a tint; zero height so rows do not shift.\n className={({ isDropTarget }) =>\n cn(\"relative h-0 data-[drop-target]:after:absolute data-[drop-target]:after:inset-x-0 data-[drop-target]:after:-top-px data-[drop-target]:after:h-0.5 data-[drop-target]:after:rounded-pill data-[drop-target]:after:bg-primary\", isDropTarget && \"z-10\")\n }\n />\n ),\n });\n\n return (\n <div ref={root} className={cn(\"min-w-0\", className)} // Capture phase: React Aria's drop handlers stop dragleave from bubbling.\n onDragLeaveCapture={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && setRefused(null)}>\n <GridList\n aria-label={label}\n items={items.map((item) => ({ item, id: getKey(item) }))}\n dragAndDropHooks={dragAndDropHooks}\n selectionMode={selectionMode}\n selectedKeys={selectedKeys}\n onSelectionChange={(keys) => onSelectionChange?.(keys === \"all\" ? new Set(items.map(getKey)) : new Set([...keys].map(String)))}\n renderEmptyState={({ isDropTarget }) => (\n <div className={cn(\"rounded-surface border border-dashed py-6 text-center\", isDropTarget ? \"border-solid border-primary bg-muted\" : \"border-input\")}>\n {isDropTarget ? <p className=\"type-body\">Drop here</p> : empty}\n </div>\n )}\n className={({ isDropTarget }) => cn(\"grid divide-y divide-border border-y border-border\", isDropTarget && \"outline-2 outline-offset-2 outline-primary\")}\n >\n {({ item }) => (\n <GridListItem\n id={getKey(item)}\n textValue={getLabel(item)}\n className=\"group relative flex min-h-(--control-h) cursor-default items-center gap-2 py-1 pr-1 pl-1 outline-none data-[focus-visible]:outline-2 data-[focus-visible]:-outline-offset-2 data-[focus-visible]:outline-ring data-[selected]:bg-muted data-[selected]:before:absolute data-[selected]:before:inset-y-1 data-[selected]:before:left-0 data-[selected]:before:w-0.5 data-[selected]:before:rounded-pill data-[selected]:before:bg-primary data-[dragging]:opacity-50\"\n >\n <AriaButton slot=\"drag\" className=\"grid size-(--control-h-sm) shrink-0 cursor-grab place-items-center rounded-control text-muted-foreground hover:bg-muted data-[focus-visible]:outline-2 data-[focus-visible]:outline-ring\">\n <GripVertical aria-hidden className=\"size-4\" />\n </AriaButton>\n <div className=\"min-w-0 flex-1\">{children(item)}</div>\n {renderActions && <div className=\"flex shrink-0 items-center gap-1\">{renderActions(item)}</div>}\n </GridListItem>\n )}\n </GridList>\n {refused && (\n <p role=\"status\" className=\"mt-2 flex items-start gap-1.5 type-body-sm text-danger\">\n <Ban aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n {refused}\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, FileQuestion, Loader, Upload, X } from \"lucide-react\";\nimport { DropZone, FileTrigger } from \"react-aria-components\";\nimport type { FileIntake, FileOutcome } from \"../lib/file-intake\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button, IconButton, RowAction, type ButtonProps } from \"./button\";\nimport { Status } from \"./status\";\n\n// Bringing local files into an app (strata issue #75). Four pieces over `useFileIntake`:\n//\n// FileButton opens the picker. The one route that needs no pointer, so it is also the keyboard\n// and phone way in: a drop zone always carries one.\n// FileDropZone a region files can be dropped on, that says what it takes and shows when a drag\n// is over it. Rejection happens after the drop, in `useFileIntake`, so a wrong\n// file is named with its reason instead of the drop silently doing nothing.\n// FileOutcomes one row per file: pending, added, rejected or failed, each with its word and,\n// where a person must act, the reason and a retry. Inline, never a full-screen\n// overlay (components.md §3.6).\n// MissingFile a saved item whose file is gone: a status word and a relink button that opens the\n// picker for that one item.\n//\n// React Aria first. The picker is `FileTrigger` (it renders the hidden input and opens it from a\n// real `Button`, so the control is focusable and named; the old `<label>` around a hidden input\n// is not) and the zone is `DropZone` (drop events, `isDropTarget`, its own focus ring). Checked in\n// their `.d.ts`: `DropZone` filters nothing by type unless `getDropOperation` says so, and a\n// refusal there shows no message, so we accept any file drop and judge in the hook. `isDropTarget`\n// comes from React Aria's enter and leave bookkeeping, which is why the state does not flicker as\n// the pointer crosses the zone's children (a plain `dragenter` handler on the zone does).\n// The dropped `File`s are read from the drop items (`kind: \"file\"`); directories are ignored.\n//\n// Drop-over state is a word as well as a border: \"Drop to add …\" replaces the prompt, so it does\n// not rest on colour alone. Nothing animates (character by frequency; the zone is used a handful\n// of times a session, but its state change is itself the feedback).\n\n/** The picker as a button. `children` is its visible name (\"Add files\"); `accept` narrows what the dialog shows. */\nexport function FileButton({\n accept,\n multiple = false,\n onFiles,\n icon: Icon,\n children,\n ...props\n}: Omit<ButtonProps, \"onChange\" | \"children\"> & {\n /** What the dialog offers: extensions (`.gpx`), exact types or families (`video/*`). */\n accept: readonly string[];\n multiple?: boolean;\n /** Called with the files chosen. Not called when the dialog is cancelled. */\n onFiles: (files: File[]) => void;\n icon?: IconComponent;\n children: string;\n}) {\n return (\n <FileTrigger\n acceptedFileTypes={accept}\n allowsMultiple={multiple}\n onSelect={(list) => {\n const files = list ? Array.from(list) : [];\n if (files.length) onFiles(files);\n }}\n >\n <Button {...props}>\n {Icon && <Icon aria-hidden />}\n {children}\n </Button>\n </FileTrigger>\n );\n}\n\n/** A region that takes dropped files and offers the picker as its keyboard alternative. */\nexport function FileDropZone({\n onFiles,\n acceptLabel,\n title,\n disabled,\n children,\n className,\n}: {\n onFiles: (files: File[]) => void;\n /** What it takes, in words (\"a video, an audio file or a GPX track\"). Shown while a drag is over it. */\n acceptLabel: string;\n /** The resting prompt (\"Drag files here\"). */\n title: string;\n disabled?: boolean;\n /** The `FileButton` (required in practice: it is how a keyboard or phone gets files in). */\n children?: React.ReactNode;\n className?: string;\n}) {\n const onDrop = async (e: Parameters<NonNullable<React.ComponentProps<typeof DropZone>[\"onDrop\"]>>[0]) => {\n const items = e.items.filter((i) => i.kind === \"file\");\n const files = await Promise.all(items.map((i) => i.getFile()));\n if (files.length) onFiles(files);\n };\n return (\n <DropZone\n aria-label={title}\n isDisabled={disabled}\n onDrop={onDrop}\n className={({ isDropTarget, isFocusVisible }) =>\n cn(\n \"grid min-w-0 justify-items-center gap-2 rounded-surface border border-dashed border-input px-4 py-6 text-center\",\n isDropTarget && \"border-solid border-primary bg-muted\",\n isFocusVisible && \"outline-2 outline-offset-2 outline-ring\",\n className,\n )\n }\n >\n {({ isDropTarget }) => (\n <>\n <Upload aria-hidden className=\"size-5 text-muted-foreground\" />\n <p className=\"type-body\">{isDropTarget ? `Drop to add ${acceptLabel}` : title}</p>\n {children}\n </>\n )}\n </DropZone>\n );\n}\n\nconst rowStatus: Record<FileOutcome[\"status\"], { tone: \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\"; word: string; icon: IconComponent }> = {\n processing: { tone: \"info\", word: \"Adding…\", icon: Loader },\n added: { tone: \"success\", word: \"Added\", icon: CircleCheck },\n rejected: { tone: \"warning\", word: \"Not added\", icon: CircleAlert },\n failed: { tone: \"danger\", word: \"Failed\", icon: CircleAlert },\n};\n\n/** One row per file offered: its name, a status word, and for a rejected or failed file the reason and (for failed) a retry. Announces a summary politely when a batch finishes. */\nexport function FileOutcomes({ intake, className }: { intake: FileIntake; className?: string }) {\n const { outcomes, retry, dismiss, pending } = intake;\n // A polite summary once nothing is pending, covering the files not yet announced, so a six-file\n // drop is one announcement and not six, and a drop that is all rejections is still heard.\n const [summary, setSummary] = React.useState(\"\");\n const announced = React.useRef(new Set<string>());\n React.useEffect(() => {\n if (pending > 0) return;\n const fresh = outcomes.filter((o) => !announced.current.has(o.id));\n if (!fresh.length) return;\n for (const o of fresh) announced.current.add(o.id);\n const added = fresh.filter((o) => o.status === \"added\").length;\n const problems = fresh.length - added;\n setSummary([added && `${added} added`, problems && `${problems} not added`].filter(Boolean).join(\", \"));\n }, [pending, outcomes]);\n\n return (\n <div className={cn(\"min-w-0\", className)}>\n <p role=\"status\" className=\"sr-only\">\n {summary}\n </p>\n {outcomes.length > 0 && (\n <ul className=\"grid divide-y divide-border border-y border-border\">\n {outcomes.map((o) => {\n const s = rowStatus[o.status];\n const reason = o.status === \"rejected\" || o.status === \"failed\" ? o.reason : undefined;\n return (\n <li key={o.id} className=\"grid gap-1 py-2\">\n <div className=\"flex items-center gap-3\">\n <span className=\"min-w-0 flex-1 truncate type-body\" title={o.name}>\n {o.name}\n </span>\n <Status tone={s.tone} icon={s.icon}>\n {s.word}\n </Status>\n {o.status === \"failed\" && <RowAction label=\"Try again\" subject={o.name} onClick={() => retry(o.id)} />}\n {o.status !== \"processing\" && <IconButton icon={X} label={`Dismiss ${o.name}`} onClick={() => dismiss(o.id)} />}\n </div>\n {reason && <p className=\"type-body-sm text-muted-foreground\">{reason}</p>}\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n}\n\n/**\n * A saved item whose file is gone: the item's name, a \"File missing\" status (a word and an icon) and a \"Relink\" button that opens the picker for this one item.\n * In a narrow column the name keeps its own line, in full, and the status and button wrap under it. An optional `thumbnail` sits beside all three.\n */\nexport function MissingFile({\n name,\n accept,\n onRelink,\n thumbnail,\n className,\n}: {\n /** The item's name as the person knows it (\"run-02.mp4\"). */\n name: string;\n accept: readonly string[];\n /** Called with the file the person chose to stand in for it. */\n onRelink: (file: File) => void;\n /** A picture of the item (what it last looked like), drawn at the start. */\n thumbnail?: React.ReactNode;\n className?: string;\n}) {\n // In a 300px library a name, a status and a button on one row left the name \"parkru…\" (strata-react\n // issue #122). The name is the one thing that must stay readable, so it wraps rather than truncates,\n // takes at least ten ems, and pushes the status and button to the next row when the row is short.\n return (\n <div className={cn(\"flex min-w-0 items-center gap-3\", className)}>\n {thumbnail && <div className=\"shrink-0\">{thumbnail}</div>}\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1\">\n <span className=\"min-w-40 flex-auto break-words type-body\" title={name}>\n {name}\n </span>\n <div className=\"flex items-center gap-2\">\n <Status tone=\"warning\" icon={FileQuestion}>\n File missing\n </Status>\n <FileButton accept={accept} variant=\"ghost\" size=\"sm\" aria-label={`Relink ${name}`} onFiles={([file]) => onRelink(file)}>\n Relink\n </FileButton>\n </div>\n </div>\n </div>\n );\n}\n","import * as React from \"react\";\n\n// Bringing local files into an app (strata issue #75, from a video editor's library): pick or\n// drop, then one outcome per file. This is the logic with no drawing, so a screen can render the\n// outcomes however it likes (`FileOutcomes` is the default) and a test can feed it `File`s without\n// a dialog.\n//\n// Why a hook of per-file outcomes and not one \"upload\" state: a drop of six files has six stories\n// (two added, one still processing, one the wrong type, one too big, one the app could not read),\n// and the person needs to hear about each by name, inline, without the screen being blocked\n// (patterns.md §7: an error a person must act on is inline with its recovery, not a toast). The\n// rest of the batch is never held up by one file: each runs on its own.\n//\n// Nothing here assumes a server. `process` is the app's own work on a file (parse a GPX, make a\n// thumbnail, upload it); it may throw, and its message is shown as the reason, so write it in the\n// product's words (\"run-02.mp4 is not a video this browser can play. Convert it to MP4 (H.264)\n// and add it again.\"). Without `process`, an accepted file counts as added at once.\n\nexport type FileOutcome =\n | { id: string; name: string; size: number; status: \"processing\" }\n | { id: string; name: string; size: number; status: \"added\" }\n | { id: string; name: string; size: number; status: \"rejected\"; reason: string }\n | { id: string; name: string; size: number; status: \"failed\"; reason: string };\n\nexport type FileIntakeOptions = {\n /** What is accepted, as the picker's `accept` list: extensions (`.gpx`), exact types (`audio/mpeg`) or families (`video/*`). */\n accept: readonly string[];\n /** The accepted kinds in words, used in the rejection reason and the drop hint: \"a video, an audio file or a GPX track\". */\n acceptLabel: string;\n /** More than one file at a time. Default true; with false, extra files in one drop are rejected by name. */\n multiple?: boolean;\n /** Largest size in bytes. Larger files are rejected with their size in the reason. */\n maxBytes?: number;\n /** Extra checks after the type check, for what a type cannot say. Return the reason in the product's words, or `null` to accept. */\n check?: (file: File) => string | null | Promise<string | null>;\n /** The app's own work on an accepted file. A throw marks it `failed` with the error's message and offers a retry. */\n process?: (file: File, context: { signal: AbortSignal }) => void | Promise<void>;\n};\n\nexport type FileIntake = {\n /** One outcome per file offered, in the order offered, newest batch last. */\n outcomes: readonly FileOutcome[];\n /** Offers files (from the picker or a drop). Rejections appear as outcomes at once; accepted files are processed. */\n add: (files: Iterable<File> | ArrayLike<File>) => void;\n /** Runs `process` again for a failed file. */\n retry: (id: string) => void;\n /** Removes an outcome (and aborts its processing if still running). */\n dismiss: (id: string) => void;\n /** Removes every finished outcome (added, rejected and failed), leaving those still processing. */\n clear: () => void;\n /** Files still being processed. */\n pending: number;\n};\n\n/** Whether a file matches one entry of an `accept` list: extension, exact type or `family/*`, ignoring case. */\nexport function matchesAccept(file: { name: string; type: string }, accept: readonly string[]): boolean {\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return accept.some((entry) => {\n const a = entry.trim().toLowerCase();\n if (a.startsWith(\".\")) return name.endsWith(a);\n if (a.endsWith(\"/*\")) return type.startsWith(a.slice(0, -1));\n return type === a;\n });\n}\n\nconst MB = 1024 * 1024;\nconst sizeWords = (bytes: number) => (bytes >= MB ? `${(bytes / MB).toFixed(bytes >= 100 * MB ? 0 : 1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} kB`);\n\n/** Per-file outcomes for files picked or dropped: type and size checks with a named reason, the app's own `process` per file, retry and dismiss. */\nexport function useFileIntake(options: FileIntakeOptions): FileIntake {\n const [outcomes, setOutcomes] = React.useState<readonly FileOutcome[]>([]);\n const opts = React.useRef(options);\n opts.current = options;\n const files = React.useRef(new Map<string, File>());\n const controllers = React.useRef(new Map<string, AbortController>());\n const counter = React.useRef(0);\n const alive = React.useRef(true);\n\n const patch = React.useCallback((id: string, next: (o: FileOutcome) => FileOutcome) => {\n setOutcomes((all) => all.map((o) => (o.id === id ? next(o) : o)));\n }, []);\n\n const run = React.useCallback(\n (id: string, file: File) => {\n const controller = new AbortController();\n controllers.current.set(id, controller);\n const base = { id, name: file.name, size: file.size };\n patch(id, () => ({ ...base, status: \"processing\" }));\n Promise.resolve()\n .then(() => opts.current.process?.(file, { signal: controller.signal }))\n .then(\n () => !controller.signal.aborted && patch(id, () => ({ ...base, status: \"added\" })),\n (error: unknown) => {\n if (controller.signal.aborted) return;\n const reason = error instanceof Error && error.message ? error.message : `${file.name} could not be added. Try again.`;\n patch(id, () => ({ ...base, status: \"failed\", reason }));\n },\n )\n .finally(() => controllers.current.delete(id));\n },\n [patch],\n );\n\n // The app's own check, then its `process`. A check that throws (synchronously or not) fails the\n // file with a retry rather than accepting it unchecked or escaping `add`; nothing runs after the\n // screen is gone or the file was dismissed.\n const start = React.useCallback(\n (id: string, file: File) => {\n const base = { id, name: file.name, size: file.size };\n patch(id, () => ({ ...base, status: \"processing\" }));\n Promise.resolve()\n .then(() => opts.current.check?.(file))\n .then(\n (reason) => {\n if (!alive.current || !files.current.has(id)) return;\n if (reason) {\n files.current.delete(id);\n patch(id, () => ({ ...base, status: \"rejected\", reason }));\n } else run(id, file);\n },\n (error: unknown) => {\n if (!alive.current || !files.current.has(id)) return;\n const reason = error instanceof Error && error.message ? error.message : `${file.name} could not be checked. Try again.`;\n patch(id, () => ({ ...base, status: \"failed\", reason }));\n },\n );\n },\n [patch, run],\n );\n\n const add = React.useCallback(\n (offered: Iterable<File> | ArrayLike<File>) => {\n const list = Array.from(offered as ArrayLike<File>);\n const { accept, acceptLabel, multiple = true, maxBytes } = opts.current;\n list.forEach((file, index) => {\n const id = `f${++counter.current}`;\n const base = { id, name: file.name, size: file.size };\n const reject = (reason: string) => setOutcomes((all) => [...all, { ...base, status: \"rejected\", reason }]);\n if (!multiple && index > 0) return reject(`${file.name} was not added: this takes one file at a time.`);\n if (!matchesAccept(file, accept)) return reject(`${file.name} is not a type this accepts. Add ${acceptLabel}.`);\n if (maxBytes !== undefined && file.size > maxBytes) {\n return reject(`${file.name} is ${sizeWords(file.size)}, over the ${sizeWords(maxBytes)} limit.`);\n }\n files.current.set(id, file);\n setOutcomes((all) => [...all, { ...base, status: \"processing\" }]);\n start(id, file);\n });\n },\n [patch, start],\n );\n\n const dismiss = React.useCallback((id: string) => {\n controllers.current.get(id)?.abort();\n controllers.current.delete(id);\n files.current.delete(id);\n setOutcomes((all) => all.filter((o) => o.id !== id));\n }, []);\n\n const retry = React.useCallback(\n (id: string) => {\n const file = files.current.get(id);\n if (file) start(id, file);\n },\n [start],\n );\n\n const clear = React.useCallback(() => {\n setOutcomes((all) => {\n for (const o of all) if (o.status !== \"processing\") files.current.delete(o.id);\n return all.filter((o) => o.status === \"processing\");\n });\n }, []);\n\n React.useEffect(() => {\n alive.current = true;\n const live = controllers.current;\n return () => {\n alive.current = false;\n for (const c of live.values()) c.abort();\n live.clear();\n };\n }, []);\n\n const pending = outcomes.filter((o) => o.status === \"processing\").length;\n return React.useMemo(() => ({ outcomes, add, retry, dismiss, clear, pending }), [outcomes, add, retry, dismiss, clear, pending]);\n}\n","import * as React from \"react\";\nimport { ChevronRight, RotateCcw } from \"lucide-react\";\nimport { Button as AriaButton, Disclosure, DisclosurePanel, Heading } from \"react-aria-components\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { IconButton } from \"./button\";\nimport { Field } from \"./field\";\n\n// An inspector shows and edits the properties of whatever is selected (strata issue #74, from a\n// video editor's metadata and clip panels). Four parts that compose, so a settings sidebar, a file\n// manager's details pane and an editor's property panel are the same few pieces:\n//\n// Inspector the panel: a labelled region, a heading naming the selection, and the empty\n// state when nothing is selected. Remembers which sections the person closed.\n// InspectorSection a titled, collapsible group of rows, with room for its few actions.\n// PropertyRow one editable property: a `Field` (label, hint, error) with an optional\n// \"Reset\" that appears only while the value differs from its default.\n// PropertyList read-only facts as a description list (size, duration, codec, created).\n//\n// React Aria first. Sections are React Aria's `Disclosure`, which gives the heading + trigger\n// button + panel wiring (`aria-expanded`, `aria-controls`, the panel as a labelled region). We\n// extend it two ways. React Aria keeps a closed panel in the DOM (`hidden`), so a closed section's\n// controls would still be mounted, and in a long inspector that is dozens of controls and any\n// request inside them; the body here renders only while the section is open, as `Disclosure`\n// does, by reading `isExpanded` from the render props. And the open state is held by the\n// Inspector, so it can be remembered. Checked in `Disclosure.d.ts`: no prop unmounts the panel.\n// The separator-less look follows patterns.md §2: space and hairlines, never cards, never nested.\n//\n// Order is the caller's: the research (patterns.md §1) orders blocks by the next question a\n// person asks, not by the data model, and a component cannot know that. What the component does is\n// make a long panel survivable: every section but the first few can start closed (`defaultOpen`),\n// and what the person opens or closes is remembered per `storageKey`.\n//\n// The selection changing underneath is handled here, not by each app: pass `selectionKey` (the\n// selected thing's id) and the sections' bodies remount for a new selection, so no control keeps\n// the last item's typed text; if the control that had focus left the DOM, focus goes to the\n// panel's heading, not to the page. A deleted selection (`title` null) shows the empty state.\n//\n// No motion on open and close: people do it many times a session (ux-character.md, by frequency).\n\ntype Remembered = Record<string, boolean>;\n\nfunction readRemembered(key: string | null | undefined): Remembered {\n if (!key) return {};\n try {\n const raw = window.localStorage.getItem(key);\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return parsed && typeof parsed === \"object\" ? (parsed as Remembered) : {};\n } catch {\n // Storage throws in private windows and when blocked; the panel then works for this visit.\n return {};\n }\n}\n\ntype InspectorState = { isOpen: (id: string, defaultOpen: boolean) => boolean; setOpen: (id: string, open: boolean) => void };\nconst InspectorContext = React.createContext<InspectorState | null>(null);\n\nexport type InspectorProps = {\n /** The selection's name, as the panel's heading (\"run-02.mp4\", \"Clip: Title card\"). `null` when nothing is selected. */\n title: string | null;\n /** What kind of thing it is, under the heading (\"Video\", \"Text clip\"). */\n kind?: string;\n /** Shown when `title` is `null`: an `EmptyState` that says what to select and what appears (\"Select a clip on the timeline to change how it looks\"). */\n empty: React.ReactNode;\n /** The selected thing's id. A new value remounts the sections' bodies so no control shows the last item's typed text. */\n selectionKey?: string;\n /** localStorage key under which closed and opened sections are remembered. Omit to remember only for this visit. */\n storageKey?: string;\n /** The panel's few actions (a menu, a \"Delete\"), beside the heading. */\n actions?: React.ReactNode;\n /** A picture or summary of the selection above the sections (a `Thumbnail`). */\n summary?: React.ReactNode;\n /** `InspectorSection`s and `PropertyList`s. */\n children?: React.ReactNode;\n className?: string;\n};\n\n/** A panel of properties for the selected thing: a labelled region with a heading, an empty state when `title` is null, and sections whose open state is remembered. */\nexport function Inspector({ title, kind, empty, selectionKey, storageKey, actions, summary, children, className }: InspectorProps) {\n const headingId = React.useId();\n const [remembered, setRemembered] = React.useState<Remembered>(() => readRemembered(storageKey));\n const root = React.useRef<HTMLElement>(null);\n const heading = React.useRef<HTMLHeadingElement>(null);\n\n const state = React.useMemo<InspectorState>(\n () => ({\n isOpen: (id, defaultOpen) => remembered[id] ?? defaultOpen,\n setOpen: (id, open) =>\n setRemembered((prev) => {\n const next = { ...prev, [id]: open };\n if (storageKey) {\n try {\n window.localStorage.setItem(storageKey, JSON.stringify(next));\n } catch {\n // Not remembered; still applies to this visit.\n }\n }\n return next;\n }),\n }),\n [remembered, storageKey],\n );\n\n // When the selection changes and the focused control went with the old one, focus would fall to\n // the page body. Put it on the heading instead, so a keyboard user stays in the panel.\n const hadFocus = React.useRef(false);\n React.useEffect(() => {\n const el = root.current;\n const onFocus = () => (hadFocus.current = true);\n const onBlur = (e: FocusEvent) => {\n if (!e.relatedTarget) return; // focus left to nowhere: decided in the effect below\n hadFocus.current = false;\n };\n el?.addEventListener(\"focusin\", onFocus);\n el?.addEventListener(\"focusout\", onBlur);\n return () => {\n el?.removeEventListener(\"focusin\", onFocus);\n el?.removeEventListener(\"focusout\", onBlur);\n };\n }, []);\n React.useEffect(() => {\n if (hadFocus.current && (document.activeElement === document.body || !document.activeElement)) (heading.current ?? root.current)?.focus(); // the panel itself when the heading is gone (nothing selected)\n }, [selectionKey, title]);\n\n return (\n <InspectorContext.Provider value={state}>\n <aside ref={root} tabIndex={-1} aria-labelledby={title === null ? undefined : headingId} aria-label={title === null ? \"Properties\" : undefined} className={cn(\"min-w-0\", className)}>\n {title === null ? (\n empty\n ) : (\n <div className=\"grid grid-cols-1 gap-4\">\n <header className=\"flex items-start gap-3\">\n <div className=\"min-w-0 flex-1\">\n <Heading level={2} id={headingId} ref={heading} tabIndex={-1} title={title} className=\"truncate type-heading outline-offset-2\">\n {title}\n </Heading>\n {kind && <p className=\"type-body-sm text-muted-foreground\">{kind}</p>}\n </div>\n {actions && <div className=\"flex shrink-0 items-center gap-1\">{actions}</div>}\n </header>\n {summary}\n <div key={selectionKey} className=\"grid grid-cols-1 *:min-w-0\">\n {children}\n </div>\n </div>\n )}\n </aside>\n </InspectorContext.Provider>\n );\n}\n\nexport type InspectorSectionProps = {\n /** Identifies the section for remembering, stable across selections of the same kind (\"audio\", \"text-style\"). */\n id: string;\n title: string;\n /** Open when the person has not chosen. Default true; start the few that answer the next question open and the rest closed. */\n defaultOpen?: boolean;\n /** The section's few actions (add, reset all), beside its heading and outside its toggle. Name them for the section (\"Add track\"). */\n actions?: React.ReactNode;\n /** Mounted only while the section is open. */\n children: React.ReactNode;\n className?: string;\n};\n\n/** A titled group of rows that collapses. The body is mounted only while open; the open state is remembered by the surrounding `Inspector` (and held locally outside one). */\nexport function InspectorSection({ id, title, defaultOpen = true, actions, children, className }: InspectorSectionProps) {\n const inspector = React.useContext(InspectorContext);\n const [own, setOwn] = React.useState(defaultOpen);\n const expanded = inspector ? inspector.isOpen(id, defaultOpen) : own;\n const onChange = (open: boolean) => (inspector ? inspector.setOpen(id, open) : setOwn(open));\n return (\n <Disclosure isExpanded={expanded} onExpandedChange={onChange} className={cn(\"min-w-0 border-t border-border first:border-t-0\", className)}>\n {({ isExpanded }) => (\n <>\n <div className=\"flex items-center gap-2\">\n <Heading level={3} className=\"min-w-0 flex-1\">\n <AriaButton\n slot=\"trigger\"\n className=\"-mx-1 flex min-h-(--control-h-sm) w-full cursor-pointer items-center gap-2 rounded-control px-1 text-left type-label hover:bg-muted\"\n >\n <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", isExpanded && \"rotate-90\")} />\n <span className=\"min-w-0 flex-1 truncate\">{title}</span>\n </AriaButton>\n </Heading>\n {actions && <div className=\"flex shrink-0 items-center gap-1\">{actions}</div>}\n </div>\n <DisclosurePanel>{isExpanded && <div className=\"grid grid-cols-1 gap-4 pt-2 pb-4 pl-6 *:min-w-0\">{children}</div>}</DisclosurePanel>\n </>\n )}\n </Disclosure>\n );\n}\n\nexport type PropertyRowProps = {\n label: string;\n hint?: React.ReactNode;\n error?: string;\n /** Whether the value differs from its default. With `onReset`, shows a \"Reset\" button named for the property. */\n modified?: boolean;\n /** Puts the value back to its default. */\n onReset?: () => void;\n /** The control: an `Input`, `NumberField`, `Slider`, `NativeSelect`… It picks up the label from the row. */\n children: React.ReactNode;\n className?: string;\n};\n\n/** One editable property: a `Field` (label, hint, error wired to the control) with a \"Reset <label>\" that shows only while `modified`. */\nexport function PropertyRow({ label, hint, error, modified, onReset, children, className }: PropertyRowProps) {\n const reset =\n modified && onReset ? <IconButton icon={RotateCcw} label={`Reset ${label.toLowerCase()}`} onClick={onReset} /> : undefined;\n return (\n <Field label={label} hint={hint} error={error} action={reset} className={className}>\n {children}\n </Field>\n );\n}\n\nexport type Property = {\n /** The fact's name (\"Frame rate\"). */\n term: string;\n /** Its value. `null` or `undefined` prints the missing mark; a string is truncated with the whole value in a tooltip. */\n value: React.ReactNode | null | undefined;\n /** A unit, joined with a non-breaking space and muted. */\n unit?: string;\n};\n\nexport type PropertyListProps = {\n items: readonly Property[];\n /** Names the list for a screen reader (\"Video details\") when a visible heading does not. */\n label?: string;\n className?: string;\n};\n\n/** Read-only facts as a description list: term left, value right, long strings truncated with the full value on hover, a missing value printed as an en dash, units muted after a non-breaking space. */\nexport function PropertyList({ items, label, className }: PropertyListProps) {\n return (\n <dl aria-label={label} className={cn(\"grid gap-y-1.5\", className)}>\n {items.map(({ term, value, unit }) => {\n const missing = value === null || value === undefined || value === \"\";\n return (\n // A wrapping div per pair is valid inside <dl> and keeps term and value on one row.\n <div key={term} className=\"grid grid-cols-5 gap-x-3 type-body-sm\">\n <dt className=\"col-span-2 min-w-0 text-muted-foreground\">{term}</dt>\n <dd className=\"col-span-3 min-w-0 tabular-nums\">\n <span className=\"block truncate\" title={typeof value === \"string\" ? value : undefined}>\n {missing ? (\n <>\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">Not known</span>\n </>\n ) : (\n value\n )}\n {!missing && unit && <span className=\"text-muted-foreground\">{` ${unit}`}</span>}\n </span>\n </dd>\n </div>\n );\n })}\n </dl>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox as AriaCheckbox, GridLayout, GridList, GridListItem, Virtualizer, type Selection } from \"react-aria-components\";\nimport { Size } from \"react-stately\";\nimport { Check } from \"lucide-react\";\nimport { Checkbox, useShiftNote } from \"./checkbox\";\nimport type { RowSelection } from \"./data-table\";\nimport { useSelectRows } from \"./selection\";\n\n// Choosing from pictures: a review screen of face crops, a set of glaze test tiles, photos to\n// archive. It is `DataTable`'s selection drawn as a grid (strata-react issue #32, from the Bright\n// Horizons port, where the Groups screen had to be built by hand from `Checkbox` and\n// `useSelection`), and it shares the state and the rules: `useSelection` holds the keys, a\n// `BulkBar` holds the actions, select-all covers the selectable tiles shown (all of them, rendered\n// or not) and is mixed when some are chosen, and Shift-click or Shift+Space chooses or clears the\n// run from the last tile clicked (`useSelectRows`, the same code the table uses).\n//\n// It is React Aria's GridList with `layout=\"grid\"` (arrow keys move across and down the tiles) and\n// its own selection: each tile is one row, a press anywhere on it toggles it (Google Photos and Apple\n// Photos select from the picture, not only from the box), Shift extends a range, Space toggles. The\n// box is React Aria's selection checkbox, named from the row (`rowLabel` is required, as the\n// table's is), so a screen reader hears \"Select Ada Lovelace, crop 3\", not twelve \"checkbox, not\n// checked\". The box sits on a chip of the page's ground in the picture's corner, so it stays\n// visible on any photo. A chosen tile takes the sunken fill and a primary border, not a ring: the\n// focus outline is the only ring, so a selection never reads as focus. Shift-click on the box also\n// extends a range, as before (a checkbox always toggles one tile in React Aria), through\n// `useSelectRows`. \"Select all shown\" is ours, outside the grid, since the tiles shown may be a\n// part of the keys held.\n//\n// The picture is the caller's (`renderImage`), in a frame of fixed aspect (`aspect`, square by\n// default) so tiles line up and nothing shifts as images load; an <img> or Strata's `Thumbnail`\n// fills it. Tiles are sized by a minimum width (`tileSize`) and fill the row. From\n// `virtualizeFrom` tiles (100, as the table and list) React Aria's Virtualizer with `GridLayout`\n// draws only the visible rows of tiles in the grid's own scroll box, working out how many fit a row\n// and measuring each row of tiles. (Its tiles keep a margin of one gap at the edges of the box, which\n// the plain grid does not have.)\n\n/** The frame each picture is drawn in. */\nexport type TileAspect = \"square\" | \"portrait\" | \"landscape\";\n\n/** Smallest tile width: `sm` 96px (dense crops), `md` 144px, `lg` 192px. Tiles grow to fill the row. */\nexport type TileSize = \"sm\" | \"md\" | \"lg\";\n\nexport type SelectableGridProps<T> = {\n /** Names the grid of tiles. */\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n /** The picture, drawn to fill a frame of `aspect`. An `<img className=\"size-full object-cover\">` or a `Thumbnail`. */\n renderImage: (row: T) => React.ReactNode;\n /** A short line under the picture (a name, a date, a score). Truncated to one line. */\n detail?: (row: T) => React.ReactNode;\n /** The chosen keys and how to change them, as `DataTable` takes them; `rowLabel` names each tile's box. */\n selection: RowSelection<T>;\n /** Default `square`. `portrait` is 3:4, `landscape` 4:3. */\n aspect?: TileAspect;\n /** Default `md`. */\n tileSize?: TileSize;\n /** Tile count from which only the visible rows of tiles render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n className?: string;\n};\n\nconst minWidth: Record<TileSize, number> = { sm: 96, md: 144, lg: 192 };\nconst aspectClass: Record<TileAspect, string> = { square: \"aspect-square\", portrait: \"aspect-3/4\", landscape: \"aspect-4/3\" };\nconst aspectRatio: Record<TileAspect, number> = { square: 1, portrait: 4 / 3, landscape: 3 / 4 };\n// gap-3, in px.\nconst GAP = 12;\n// The detail line and the tile's padding, for the first estimate of a tile's height.\nconst TILE_CHROME = 40;\n\n/** A grid of pictures to choose from: each tile one labelled target, \"Select all shown\", Shift-click ranges, virtualised from `virtualizeFrom` tiles. Pair with `useSelection` and a `BulkBar`. */\nexport function SelectableGrid<T>({\n label,\n rows,\n rowKey,\n renderImage,\n detail,\n selection,\n aspect = \"square\",\n tileSize = \"md\",\n virtualizeFrom = 100,\n maxHeight = 480,\n className,\n}: SelectableGridProps<T>) {\n const select = useSelectRows(rows, rowKey, selection);\n const virtual = rows.length >= virtualizeFrom;\n const shownKeys = React.useMemo(() => new Set(rows.map(rowKey)), [rows, rowKey]);\n const disabledKeys = rows.filter((r) => !(selection.isSelectable?.(r) ?? true)).map(rowKey);\n\n // React Aria owns the selection of tiles: a press anywhere on a tile toggles it, Shift extends a\n // range from the last one, Space toggles from the keyboard. Our `RowSelection` holds keys only, and\n // keeps the keys of rows that are not shown (a filter), so the two are translated here.\n // A checkbox always toggles one tile in React Aria, and Shift-click on one still extends a range\n // (issue #32): Shift is noted on the press, and a change of exactly one tile is a click on it.\n // A press on the picture with Shift is React Aria's own range and changes several at once.\n const shift = useShiftNote();\n // The row last pressed (React Aria marks each row with `data-key`), to anchor a range it extended itself.\n const pressed = React.useRef<string | null>(null);\n const notePress = (e: React.SyntheticEvent) => void (pressed.current = (e.target as HTMLElement).closest(\"[data-key]\")?.getAttribute(\"data-key\") ?? null);\n const changeSelection = (next: Selection) => {\n if (next !== \"all\") {\n const nextShown = new Set([...next].map(String).filter((k) => shownKeys.has(k)));\n const added = [...nextShown].filter((k) => !selection.selected.has(k));\n const removed = [...selection.selected].filter((k) => shownKeys.has(k) && !nextShown.has(k));\n if (added.length + removed.length === 1) {\n select.toggle(added[0] ?? removed[0], added.length === 1, shift.take());\n return;\n }\n select.setAnchor(pressed.current);\n }\n const outside = [...selection.selected].filter((k) => !shownKeys.has(k));\n const picked = next === \"all\" ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [...next].map(String).filter((k) => shownKeys.has(k));\n selection.onChange(new Set([...outside, ...picked]));\n };\n\n // Tiles grow from `tileSize` to fill the row, and each row is as tall as its tallest tile as\n // measured (the first guess is the frame at the minimum width plus the detail line).\n const layoutOptions = React.useMemo(\n () => ({\n minItemSize: new Size(minWidth[tileSize], Math.round(minWidth[tileSize] * aspectRatio[aspect]) + TILE_CHROME),\n minSpace: new Size(GAP, GAP),\n }),\n [tileSize, aspect],\n );\n\n const grid = (\n <GridList\n aria-label={label}\n layout=\"grid\"\n selectionMode=\"multiple\"\n selectionBehavior=\"toggle\"\n selectedKeys={new Set([...selection.selected].filter((k) => shownKeys.has(k)))}\n onSelectionChange={changeSelection}\n disabledKeys={disabledKeys}\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 outline-none\", virtual ? \"overflow-y-auto\" : \"grid gap-3\")}\n style={\n virtual\n ? { height: maxHeight }\n : { gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` }\n }\n >\n {rows.map((row, index) => {\n const key = rowKey(row);\n const name = selection.rowLabel(row);\n return (\n <GridListItem\n key={key}\n id={key}\n textValue={name}\n data-index={index}\n className={cn(\n // select-none: a Shift-click range would otherwise also select the text between the tiles.\n \"group relative grid min-w-0 gap-1.5 rounded-surface border border-transparent p-1.5 select-none outline-offset-2 transition-state\",\n \"selected:border-primary selected:bg-surface-sunken disabled:cursor-not-allowed disabled:opacity-50\",\n \"cursor-pointer hover:bg-surface-sunken disabled:hover:bg-transparent\",\n )}\n >\n <span className={cn(\"block overflow-hidden rounded-control bg-muted *:size-full *:object-cover\", aspectClass[aspect])}>\n {renderImage(row)}\n </span>\n <TileBox label={`Select ${name}`} />\n {detail?.(row) != null && <span className=\"truncate type-body-sm text-muted-foreground\">{detail(row)}</span>}\n </GridListItem>\n );\n })}\n </GridList>\n );\n\n return (\n <div\n className={cn(\"grid min-w-0 gap-3\", className)}\n onMouseDownCapture={(e) => {\n shift.handlers.onMouseDown(e);\n notePress(e);\n }}\n onKeyDownCapture={(e) => {\n shift.handlers.onKeyDown(e);\n notePress(e);\n }}\n >\n <Checkbox\n className=\"justify-self-start\"\n label=\"Select all shown\"\n checked={select.all.checked}\n disabled={select.all.disabled}\n onCheckedChange={select.all.toggle}\n />\n {virtual ? (\n <Virtualizer layout={GridLayout} layoutOptions={layoutOptions}>\n {grid}\n </Virtualizer>\n ) : (\n grid\n )}\n </div>\n );\n}\n\n// The box in the tile's corner: React Aria's selection checkbox for this row (`slot=\"selection\"`),\n// named from the row, on a chip of the page's ground so it stays visible on any photo.\nfunction TileBox({ label }: { label: string }) {\n // The grid would name the box from its own label and the row's; ours is named by `rowLabel`\n // alone, so it labels itself.\n const id = React.useId();\n return (\n <AriaCheckbox slot=\"selection\" id={id} aria-labelledby={id} aria-label={label} className=\"absolute top-3 left-3 grid size-7 place-items-center rounded-control bg-background\">\n {({ isSelected }) => (\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 place-items-center rounded-control border border-input bg-background\",\n isSelected && \"border-primary bg-primary text-primary-foreground\",\n )}\n >\n {isSelected && <Check className=\"size-3.5\" strokeWidth={3} />}\n </span>\n )}\n </AriaCheckbox>\n );\n}\n","import * as React from \"react\";\nimport { Collection, GridList, GridListItem, ListLayout, Virtualizer } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A long list that keeps only its visible rows in the DOM, for feeds, logs and pickers with hundreds\n// of items. It is React Aria's `GridList` inside its `Virtualizer` (`ListLayout`), not a list we\n// virtualise ourselves: one keyboard model (arrows between rows, Home and End, type-ahead is off\n// because rows are arbitrary content), one set of ARIA (`row`s in a labelled `grid`, with\n// `aria-rowindex` and the row count so a screen reader still hears \"12 of 480\"), and focus that\n// survives a row scrolling out of the DOM. Rows are measured after render, so variable heights\n// work; `estimateSize` only sets the first paint, and `rowHeight` says every row is exactly that\n// tall, which skips measuring (and is what a test DOM, which does no layout, needs). Under\n// `virtualizeFrom` items it renders the same grid without the Virtualizer, so the roles do not\n// change as a list grows past it.\n//\n// The scroll region is the grid itself (`data-strata-scroll`, which `useInView` looks for), so there\n// is no wrapper region: the grid is labelled and focusable, and scrolls from the keyboard.\n// `bounded` keeps a short list in the same scroll box (capped at `height`) that the virtual one\n// uses, so a list that grows past `virtualizeFrom` while someone scrolls it (InfiniteList) does not\n// jump from the page's flow into a box. `footer` is one more row after the last item, inside the\n// scroll box: where InfiniteList puts its next-page row (a virtualised collection can only hold\n// rows, so the footer is one). Rows carry `data-index` in both modes.\n//\n// This replaced a list built on TanStack Virtual with `ul` and `li` (Jonathan, 2026-11-12). The roles\n// changed from list and listitem to grid and row; UPGRADING.md has it.\n\nconst FOOTER = \"\\u0000footer\";\n\n/** A list that renders only its visible rows (React Aria's GridList and Virtualizer) from `virtualizeFrom` items, with arrow-key navigation between rows. */\nexport function VirtualList<T>({\n label,\n items,\n itemKey,\n children,\n estimateSize = 48,\n rowHeight,\n height = 480,\n virtualizeFrom = 100,\n bounded = false,\n footer,\n className,\n}: {\n label: string;\n items: T[];\n itemKey: (item: T) => string;\n children: (item: T, index: number) => React.ReactNode;\n /** First-paint height of a row, in px; rows are measured after they render. */\n estimateSize?: number;\n /** Every row is exactly this tall (px): nothing is measured. */\n rowHeight?: number;\n height?: number;\n virtualizeFrom?: number;\n /** Scroll inside a box capped at `height` even below `virtualizeFrom`, so growing past it changes nothing on screen. */\n bounded?: boolean;\n /** After the last row, inside the scroll box (a next-page row, an end note). */\n footer?: React.ReactNode;\n className?: string;\n}) {\n const virtual = items.length >= virtualizeFrom;\n const rows = React.useMemo(() => items.map((item, index) => ({ id: itemKey(item), item, index })), [items, itemKey]);\n const layoutOptions = React.useMemo(() => (rowHeight ? { rowHeight } : { estimatedRowHeight: estimateSize }), [rowHeight, estimateSize]);\n // A bounded list (InfiniteList) is virtualised from its first row, so its scroll box and its\n // rows are never remounted as it grows past `virtualizeFrom`: a remount would reset the scroll\n // position in the middle of a scroll. The Virtualizer only draws what is visible, so a short\n // list costs nothing extra.\n const virtualise = virtual || bounded;\n const scrolls = virtualise;\n\n const list = (\n <GridList\n aria-label={label}\n selectionMode=\"none\"\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 outline-none\", scrolls && \"overflow-y-auto\", className)}\n style={scrolls ? (virtual ? { height } : { maxHeight: height }) : undefined}\n >\n <Collection items={rows}>\n {(row) => (\n <GridListItem id={row.id} textValue={row.id} data-index={row.index} className={cn(\"min-w-0 outline-offset-[-2px]\", row.index > 0 && \"border-t border-border\")}>\n {children(row.item, row.index)}\n </GridListItem>\n )}\n </Collection>\n {footer && (\n <GridListItem id={FOOTER} textValue=\"More\" className=\"min-w-0\">\n {footer}\n </GridListItem>\n )}\n </GridList>\n );\n\n return virtualise ? (\n <Virtualizer layout={ListLayout} layoutOptions={layoutOptions}>\n {list}\n </Virtualizer>\n ) : (\n list\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, RotateCcw } from \"lucide-react\";\nimport { ListStateContext } from \"react-aria-components\";\nimport { Button } from \"./button\";\nimport { DataView, type LoadFailure } from \"./data-view\";\nimport { VirtualList } from \"./virtual-list\";\nimport type { InfiniteLoad } from \"../query/infinite\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A list that loads its next page as the person nears the end: the view for `useInfiniteLoad`.\n// It is DataView for the first page (skeleton, error with Try again, empty state, all required)\n// and VirtualList for the rows (virtualised from 100, so a long session stays fast), with one row\n// after the last item that is always in one of four states:\n//\n// - more to come: an IntersectionObserver sentinel with a root margin, so the next page is asked\n// for before the person reaches the end, and a real \"Show more\" button behind it. The button is\n// the keyboard and screen-reader path (an automatic load is invisible to them) and the fallback\n// where the observer never fires.\n// - loading: `moreSkeleton`, mirroring the rows that are coming, not a spinner, and a polite\n// status so a screen reader hears it.\n// - a later page failed: an alert row with the reason and Try again. The items already loaded\n// stay; a failed page 4 is not a failed list. The sentinel stops asking until Try again, so a\n// dead server is not called in a loop.\n// - the end: `end`, if given (\"That's every firing since March\"), so the person knows it is all.\n//\n// `keepAtLeast` loads more whenever fewer items than that are held: a queue people work through\n// (answered items `dismiss`ed) refills before it runs dry, even when nothing scrolls. Showing\n// more by button moves focus to the first new item, because the button the person pressed is\n// gone. The list scrolls in its own region (`height`) from the first page, so passing 100 items\n// and switching to virtual rows changes nothing on screen.\n//\n// Not every paged view is a list in a box (strata-react issue #49, from the Tubes viewer, whose\n// videos are a responsive card grid that scrolls with the page). So the next-page row is its own\n// export, `LoadMore`, which an app puts after any list or grid it draws itself, and InfiniteList\n// is built on it. `scroll=\"page\"` is the same in InfiniteList: no scroll region of its own and no\n// virtual rows, the items in a plain `ul` laid out by `listClassName` (a grid), and the sentinel\n// watching the viewport. Virtual rows need a box of known height, which a page-scrolled grid is\n// not; a feed long enough to need them belongs in the region. `error` and `moreError` replace the\n// look of a failed first page and a failed later page, as DataView's `error` does.\n\n// The row a virtualised list draws for `LoadMore` is recycled when its height changes (button to\n// skeleton to button), which remounts `LoadMore` and drops what it remembers. The index to focus after\n// a click on Show more therefore lives in the list around it (InfiniteList), reached through this\n// context; a `LoadMore` used on its own keeps it in itself.\nconst PendingFocus = React.createContext<React.MutableRefObject<number | null> | null>(null);\n\n/** The next-page row's props: `InfiniteList`'s, for a list or grid the app draws itself. */\nexport type LoadMoreProps<T> = {\n state: InfiniteLoad<T>;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The items of a page on its way, mirroring the ones already drawn. */\n moreSkeleton: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). Default 400px. */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** Draws a failed later page, given the reason and the Try again. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n};\n\nfunction MoreFailed({ message, retry }: LoadFailure) {\n return (\n <div className=\"flex flex-wrap items-start gap-3 border-t border-border bg-danger-subtle px-3 py-2 text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultMoreError = (failure: LoadFailure) => <MoreFailed {...failure} />;\n\n/**\n * The row after a cursor-paged list or grid: loads the next page as it nears the screen, shows\n * `moreSkeleton` while it comes, says why it failed with Try again, offers Show more for the\n * keyboard, and `end` after the last page. After Show more it focuses the first new item: mark\n * each item with `data-index` and put this row beside the list, in the same parent.\n */\nexport function LoadMore<T>({\n state,\n moreLabel,\n moreSkeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n error: drawError = defaultMoreError,\n className,\n}: LoadMoreProps<T>) {\n const { more } = state;\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const box = React.useRef<HTMLDivElement>(null);\n const near = useInView({ active: ready && more.hasMore, rootMargin });\n // Inside a VirtualList the rows are React Aria's grid rows, which keep their own idea of which row\n // has focus; moving focus to a new row has to tell that state, or it takes focus back.\n const grid = React.useContext(ListStateContext);\n\n // Load on approach, and keep a worked-through queue topped up. Not after a failure: that waits\n // for Try again. Re-runs when a page lands, so a sentinel still in view asks for the next one.\n const { hasMore, loadingMore, error, loadMore } = more;\n React.useEffect(() => {\n if (!ready || !hasMore || loadingMore || error) return;\n if (near.inView || held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, error, near.inView, held, keepAtLeast, loadMore]);\n\n // After a click on Show more or Try again, focus the first new item: the button is gone.\n const own = React.useRef<number | null>(null);\n const shared = React.useContext(PendingFocus);\n const focusFrom = shared ?? own;\n const loadByHand = () => {\n focusFrom.current = held;\n loadMore();\n };\n React.useEffect(() => {\n const from = focusFrom.current;\n if (from === null || loadingMore) return;\n if (held <= from) {\n if (error || !hasMore) focusFrom.current = null;\n return;\n }\n // The new row may not be in the DOM yet: a virtualised list draws it a frame after its data\n // arrives. Look for it for a few frames, then give up rather than wait for ever.\n let frames = 0;\n let frame = 0;\n const find = () => {\n const scope = box.current?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? box.current?.parentElement;\n const item = scope?.querySelector<HTMLElement>(`[data-index=\"${from}\"]`);\n if (!item) {\n if (frames++ < 30) frame = requestAnimationFrame(find);\n else focusFrom.current = null;\n return;\n }\n const key = item.getAttribute(\"data-key\");\n if (grid && key !== null) {\n grid.selectionManager.setFocused(true);\n grid.selectionManager.setFocusedKey(key);\n }\n item.tabIndex = -1;\n item.focus();\n focusFrom.current = null;\n };\n find();\n return () => cancelAnimationFrame(frame);\n }, [held, loadingMore, error, hasMore, grid]);\n\n if (!ready) return null;\n return (\n <div ref={box} className={className}>\n {hasMore && !error && <div ref={near.ref} aria-hidden className=\"h-px\" />}\n {loadingMore ? (\n <div aria-hidden className=\"border-t border-border\">{moreSkeleton}</div>\n ) : error ? (\n <div role=\"alert\">{drawError({ message: error, retry: loadByHand })}</div>\n ) : hasMore ? (\n <div className=\"border-t border-border py-3\">\n <Button size=\"sm\" onClick={loadByHand}>\n {moreLabel}\n </Button>\n </div>\n ) : (\n end && <div className=\"border-t border-border py-3 type-body-sm text-muted-foreground\">{end}</div>\n )}\n <p role=\"status\" className=\"sr-only\">\n {loadingMore ? \"Loading more\" : \"\"}\n </p>\n </div>\n );\n}\n\n/** The infinite list's props. */\nexport type InfiniteListProps<T> = {\n state: InfiniteLoad<T>;\n /** The list's accessible name, e.g. \"Firing log, newest first\". */\n label: string;\n children: (item: T, index: number) => React.ReactNode;\n /** The first load. Mirrors the final layout, so nothing jumps when data arrives. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it, when the first page is empty and there are no more. */\n empty: React.ReactNode;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The rows of a page on its way. Defaults to `skeleton`. */\n moreSkeleton?: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** `region` (default): rows in a scroll region of `height`, virtual from `virtualizeFrom`. `page`: a plain list that scrolls with the page, laid out by `listClassName`. */\n scroll?: \"region\" | \"page\";\n /** With `scroll=\"page\"`: the classes of the `ul`, such as a responsive grid (`grid gap-4 sm:grid-cols-2 lg:grid-cols-3`). */\n listClassName?: string;\n /** Draws a failed first page. Defaults to DataView's `LoadError`. */\n error?: (failure: LoadFailure) => React.ReactNode;\n /** Draws a failed later page. Defaults to a danger row with Try again. */\n moreError?: (failure: LoadFailure) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n className?: string;\n};\n\n/** A cursor-paged list for `useInfiniteLoad`: DataView's first-page states, virtual rows (or a page-scrolled grid), and a `LoadMore` row that loads on approach, shows a skeleton, or says why it failed with Try again. */\nexport function InfiniteList<T>({\n state,\n label,\n children,\n skeleton,\n empty,\n moreLabel,\n moreSkeleton = skeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n scroll = \"region\",\n listClassName,\n error,\n moreError,\n estimateSize,\n height = 480,\n virtualizeFrom,\n className,\n}: InfiniteListProps<T>) {\n const { more, itemKey } = state;\n const pendingFocus = React.useRef<number | null>(null);\n // The queue refill lives here, not in LoadMore: in a virtualised region the footer row is only\n // mounted while it is near the viewport, and a queue below `keepAtLeast` must refill regardless.\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const { hasMore, loadingMore, error: moreFailure, loadMore } = more;\n React.useEffect(() => {\n if (ready && hasMore && !loadingMore && !moreFailure && held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, moreFailure, held, keepAtLeast, loadMore]);\n const footer = (\n <PendingFocus.Provider value={pendingFocus}>\n <LoadMore\n // A grid's cards have their own edges, so the row keeps a gap from them.\n className={scroll === \"page\" ? \"mt-4\" : undefined}\n state={state}\n moreLabel={moreLabel}\n moreSkeleton={moreSkeleton}\n end={end}\n rootMargin={rootMargin}\n error={moreError}\n />\n </PendingFocus.Provider>\n );\n\n return (\n <DataView\n state={state}\n isEmpty={(items) => items.length === 0 && !more.hasMore}\n skeleton={skeleton}\n empty={empty}\n error={error}\n className={className}\n >\n {(items) =>\n scroll === \"page\" ? (\n <div aria-busy={more.loadingMore || undefined}>\n <ul aria-label={label} className={cn(\"min-w-0\", listClassName ?? \"grid\")}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"min-w-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n {footer}\n </div>\n ) : (\n <div aria-busy={more.loadingMore || undefined}>\n <VirtualList\n label={label}\n items={items}\n itemKey={itemKey}\n estimateSize={estimateSize}\n height={height}\n virtualizeFrom={virtualizeFrom}\n bounded\n footer={footer}\n >\n {children}\n </VirtualList>\n </div>\n )\n }\n </DataView>\n );\n}\n","import * as React from \"react\";\nimport { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from \"react-aria\";\nimport { useSliderState } from \"react-stately\";\nimport { cn } from \"../lib/utils\";\n\n// A line chart with the defaults real product screens use: one measured series in one hue, a 2px\n// straight line with no fill and no markers, 3 to 5 faint gridlines, no y-axis line, no legend for a\n// single series (the series is labelled where it ends). Values never live only in a hover tooltip:\n// the latest and peak readings are labelled on the chart and every reading is in a table for screen\n// readers. Optional extras exist only where they answer a question: a dashed `planned` series, a\n// horizontal `band` (a threshold that matters), and a `now` marker.\n//\n//\n// `colourScale` colours the measured line by its own value, for subjects where that colour is a\n// fact rather than decoration: a kiln's glow by temperature, water by depth. The y position still\n// carries the value, so the colour is never the only cue. Without a reason in DESIGN.md, use one\n// hue.\n//\n// It draws in real pixels (measured with ResizeObserver) rather than scaling a fixed viewBox, so\n// the 12px labels stay 12px on a phone. Because the labels keep their size, the chart thins the\n// x ticks itself when they would collide (every second, third… tick, so the rhythm stays even)\n// and keeps the first and last label inside the chart, rather than overlapping on a phone.\n//\n// The y-axis autoscales to four gridline steps of a size people write on a scale, from zero (or\n// below it, if a reading is negative). `yMin` and `yMax` pin either end for a quantity whose range\n// is a fact of the subject (a percentage is 0 to 100, a battery 0 to 1): autoscaling a machine at\n// 1% CPU gives a 0 to 8% axis that makes it look busy (strata-react issue #23). A pin is a floor on\n// the extent, never a crop: a reading outside it widens the axis, because a chart that hides a\n// reading is worse than one with an untidy scale.\n//\n// Reading a value (`readout`, `onPick`) is React Aria's slider hooks (`useSlider`, `useSliderThumb`,\n// `useSliderState`) laid over the plot as `ReadingSlider`: the pointer press, the thumb's ARIA and the\n// hidden range input come from them. Two things are ours on top, checked in the hooks' source. The value\n// text: `useSliderState` formats through an object with `format`, `formatRange` and `resolvedOptions`, so\n// it is given one that says \"300 m: 60 m up\" instead of an `Intl.NumberFormat`. The stepping: the\n// state steps a continuous number by a fixed step, and a series has uneven readings, so a drag or a\n// press is snapped to the nearest reading and the keys (arrows, Home, End, Enter) are a capture handler\n// on the input that moves between readings; the hooks' own arrow handling is stopped. Hover is drawn\n// by the plot itself, since a hook has no notion of a pointer that is only resting.\n//\nexport type Point = { x: number; y: number };\n\nexport type LineChartProps = {\n /** What the chart shows, as a sentence. Used as the accessible name and the table caption. */\n label: string;\n series: Point[];\n seriesLabel: string;\n planned?: Point[];\n plannedLabel?: string;\n band?: { below: number; label: string };\n formatX: (x: number) => string;\n /** What x is, as the screen-reader table's first column heading: \"Distance\", \"Day\". Default \"Time\". */\n xLabel?: string;\n formatY: (y: number) => string;\n /** Where to put x labels, in x units. The chart drops every other one (and so on) when they would overlap at its width. */\n xTicks: number[];\n /** Pin the bottom of the y-axis (default: 0, or lower if a reading is negative). A reading below it still shows. */\n yMin?: number;\n /** Pin the top of the y-axis, for a bounded quantity such as a percentage (`yMax={100}`), so a low reading looks low. Choose a range that divides into four steps. A reading above it still shows. */\n yMax?: number;\n /** CSS colour for the measured series. Defaults to the first chart token. */\n colour?: string;\n /** Colour the measured series by value: each stop applies from `at` upwards, blending to the\n * next. Only where the colour means something in the subject; record the reason in DESIGN.md. */\n colourScale?: { at: number; colour: string }[];\n /** Says what the colours mean, shown beside the legend swatch when `colourScale` is set. */\n colourScaleLabel?: string;\n /** What the end of the line is. `\"now\"` marks the last reading with a rule, a dot and \"<value> now\": right for a live reading, where the last point is the present. `\"none\"` leaves it unmarked: right for a series whose x is not time running up to now (an elevation profile, where the last point is the finish). Default `\"now\"`, or `\"none\"` when `current` is set, since `current` already says where now is. The peak label stays either way. */\n end?: \"now\" | \"none\";\n /** The current x, supplied by the app and drawn as a rule with its value (\"now\" in a replay, a playhead). Cheap to update often. */\n current?: number;\n /** The value at the rule, as a sentence part. Default: `formatX` and the value read off the line. */\n formatCurrent?: (at: { x: number; y: number }) => string;\n /** Read values at the pointer, and by keyboard on the plot (arrows, Home, End). `readout` words the reading; default `formatX: formatY`. */\n readout?: boolean | ((p: Point) => string);\n /** The viewer chose a reading (a click, or Enter on the plot): its x, so the app can seek or select. */\n onPick?: (x: number) => void;\n /** One flat, pale tint under the line. Only where the area carries the meaning (a profile, a running total). */\n area?: boolean;\n height?: number;\n className?: string;\n};\n\nfunction useWidth<T extends HTMLElement>() {\n const ref = React.useRef<T>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n setWidth(el.getBoundingClientRect().width);\n const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n\n/** The smallest step of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ) at least `raw`. */\nfunction niceStep(raw: number) {\n const mag = 10 ** Math.floor(Math.log10(raw));\n return [1, 2, 2.5, 4, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)) ?? 10 * mag;\n}\n\n/**\n * The y-axis: four equal gridline steps covering every value. With no pins the steps are a size\n * people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), from zero or a round number below the lowest\n * reading. A pinned end is used as given unless a value lies beyond it.\n */\nexport function yScale(values: number[], pin: { min?: number; max?: number } = {}) {\n const finite = values.filter(Number.isFinite);\n const dMin = finite.length ? Math.min(...finite) : 0;\n const dMax = finite.length ? Math.max(...finite) : 0;\n const pinMin = pin.min !== undefined && dMin >= pin.min ? pin.min : undefined;\n const pinMax = pin.max !== undefined && dMax <= pin.max ? pin.max : undefined;\n let lo = pinMin ?? Math.min(0, dMin);\n // Readings all at a pinned top (say all -10 under yMax={-10}) leave no span: open one below.\n if (pinMax !== undefined && pinMin === undefined && !(pinMax > lo)) lo = pinMax - (Math.abs(pinMax) || 4);\n let min: number;\n let max: number;\n if (pinMax !== undefined) {\n max = pinMax;\n // Only the bottom is free: round it down to a step of the span, so 0 stays 0.\n min = pinMin ?? (lo < 0 ? Math.floor(lo / niceStep((max - lo) / 4)) * niceStep((max - lo) / 4) : 0);\n } else {\n const hi = Math.max(dMax, pin.max ?? -Infinity);\n // All-zero (or empty) data still needs a positive extent, or every coordinate divides by zero.\n let step = hi > lo ? niceStep((hi - lo) / 4) : 1;\n let base = pinMin ?? Math.floor(lo / step) * step;\n while (base + 4 * step < hi) {\n step = niceStep(step * 1.01);\n base = pinMin ?? Math.floor(lo / step) * step;\n }\n min = base;\n max = base + 4 * step;\n }\n if (!(max > min)) max = min + 4;\n return { min, max, ticks: [0, 1, 2, 3, 4].map((i) => min + ((max - min) * i) / 4) };\n}\n\n/** Roughly how wide a 12px caption label is, in px. jsdom cannot measure text, so the chart estimates. */\nconst labelWidth = (text: string) => text.length * 7;\n\n/**\n * The x ticks that fit at this width: every k-th tick, the smallest k for which neighbouring labels\n * leave a gap, so the spacing stays even. `scale` maps an x value to a pixel.\n */\nexport function fitTicks(ticks: number[], scale: (x: number) => number, widthOf: (t: number) => number, gap = 12) {\n if (ticks.length < 3) return ticks;\n const sorted = [...ticks].sort((a, b) => a - b);\n for (let k = 1; k < sorted.length; k++) {\n const kept = sorted.filter((_, i) => i % k === 0);\n const fits = kept.every((t, i) => i === 0 || scale(t) - scale(kept[i - 1]) >= (widthOf(t) + widthOf(kept[i - 1])) / 2 + gap);\n if (fits) return kept;\n }\n return sorted.slice(0, 1);\n}\n\n/** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */\nexport function LineChart({\n label,\n series,\n seriesLabel,\n planned,\n plannedLabel,\n band,\n formatX,\n xLabel = \"Time\",\n formatY,\n xTicks,\n yMin,\n yMax,\n colour = \"var(--chart-1)\",\n colourScale,\n colourScaleLabel,\n current,\n end,\n formatCurrent,\n readout,\n onPick,\n area,\n height = 280,\n className,\n}: LineChartProps) {\n const [ref, width] = useWidth<HTMLDivElement>();\n const gradientId = `heat-${React.useId().replace(/[^\\w-]/g, \"\")}`;\n const all = [...series, ...(planned ?? [])];\n const xMin = Math.min(...all.map((p) => p.x));\n const xMax = Math.max(...all.map((p) => p.x));\n const y = yScale(\n all.map((p) => p.y),\n { min: yMin, max: yMax },\n );\n\n const pad = { top: 16, right: 16, bottom: 28, left: 56 };\n const w = Math.max(0, width - pad.left - pad.right);\n const h = height - pad.top - pad.bottom;\n const sx = (x: number) => pad.left + ((x - xMin) / (xMax - xMin || 1)) * w;\n const sy = (v: number) => pad.top + h - ((v - y.min) / (y.max - y.min)) * h;\n const xLabelWidth = (t: number) => labelWidth(formatX(t));\n // Keep the first and last labels inside the chart instead of centring them past its edge.\n const xLabelAt = (t: number) => {\n const half = xLabelWidth(t) / 2;\n return Math.min(Math.max(sx(t), half), Math.max(half, width - half));\n };\n // Fit against where the labels are drawn, so pulling an end label in cannot make it collide.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const shownXTicks = React.useMemo(() => fitTicks(xTicks, xLabelAt, xLabelWidth), [xTicks, width, xMin, xMax, formatX]);\n const path = (pts: Point[]) => pts.map((p, i) => `${i ? \"L\" : \"M\"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(\"\");\n\n const last = series[series.length - 1];\n const showEnd = (end ?? (current === undefined ? \"now\" : \"none\")) === \"now\";\n const peak = series.reduce((a, b) => (b.y > a.y ? b : a), series[0]);\n const stops = colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : [];\n /** The colour a value lands on: the highest stop at or below it. Used for the labelled points. */\n const colourAt = (y: number) => (stops.length ? [...stops].reverse().find((s) => s.at <= y)?.colour ?? stops[0].colour : colour);\n const stroke = stops.length ? `url(#${gradientId})` : colour;\n\n // The plot itself, memoised: moving `current` or a pointer readout redraws only the overlay below.\n /* eslint-disable react-hooks/exhaustive-deps */\n const plot = React.useMemo(\n () => (\n <>\n {stops.length > 0 && (\n // A vertical gradient in chart space, so a colour sits at a temperature, not at a\n // point along the line: the line is the same red wherever it crosses 600 °C.\n <defs>\n <linearGradient id={gradientId} gradientUnits=\"userSpaceOnUse\" x1={0} x2={0} y1={sy(y.min)} y2={sy(y.max)}>\n {stops.map((s) => (\n <stop key={s.at} offset={Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min)))} stopColor={s.colour} />\n ))}\n </linearGradient>\n </defs>\n )}\n {band && band.below > y.min && (\n <g>\n <rect x={pad.left} y={sy(Math.min(band.below, y.max))} width={w} height={sy(y.min) - sy(Math.min(band.below, y.max))} fill=\"var(--success-subtle)\" />\n <text x={pad.left + 8} y={sy(Math.min(band.below, y.max)) + 16} className=\"fill-success type-caption\">\n {band.label}\n </text>\n </g>\n )}\n {y.ticks.map((t) => (\n <g key={t}>\n <line x1={pad.left} x2={pad.left + w} y1={sy(t)} y2={sy(t)} stroke=\"var(--border)\" strokeWidth={1} />\n <text x={pad.left - 8} y={sy(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatY(t)}\n </text>\n </g>\n ))}\n {shownXTicks.map((t) => (\n <text key={t} x={xLabelAt(t)} y={height - 8} textAnchor=\"middle\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatX(t)}\n </text>\n ))}\n {planned && (\n <path d={path(planned)} fill=\"none\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n )}\n {area && series.length > 1 && (\n // One flat pale tint, never a gradient: the area is the meaning, so it is a plain fill.\n <path d={`${path(series)}L${sx(series[series.length - 1].x).toFixed(1)},${sy(y.min).toFixed(1)}L${sx(series[0].x).toFixed(1)},${sy(y.min).toFixed(1)}Z`} fill={colour} fillOpacity={0.12} stroke=\"none\" />\n )}\n <path d={path(series)} fill=\"none\" stroke={stroke} strokeWidth={stops.length ? 2.5 : 2} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n {/* Direct labels instead of a legend and a tooltip. */}\n <circle cx={sx(peak.x)} cy={sy(peak.y)} r={3} fill={colourAt(peak.y)} />\n <text x={sx(peak.x) + 8} y={sy(peak.y) - 8} className=\"fill-foreground type-caption tabular-nums\">\n {formatY(peak.y)} peak\n </text>\n {showEnd && (\n <>\n <line x1={sx(last.x)} x2={sx(last.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--foreground)\" strokeWidth={1} />\n <circle cx={sx(last.x)} cy={sy(last.y)} r={3.5} fill={colourAt(last.y)} />\n <text x={sx(last.x) - 8} y={sy(last.y) - 10} textAnchor=\"end\" className=\"fill-foreground type-label tabular-nums\">\n {formatY(last.y)} now\n </text>\n </>\n )}\n </>\n ),\n [width, height, series, planned, band, xTicks, yMin, yMax, colour, colourScale, formatX, formatY, area, showEnd],\n );\n /* eslint-enable react-hooks/exhaustive-deps */\n\n // The screen-reader table is memoised with the plot: a moving rule must not rebuild every row.\n /* eslint-disable react-hooks/exhaustive-deps */\n const tableEl = React.useMemo(\n () => (\n // sr-only on a wrapper: a table ignores width: 1px and would widen the page.\n <div className=\"sr-only\">\n <table>\n <caption>{label}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{xLabel}</th>\n <th scope=\"col\">{seriesLabel}</th>\n </tr>\n </thead>\n <tbody>\n {series.map((p) => (\n <tr key={p.x}>\n <td>{formatX(p.x)}</td>\n <td>{formatY(p.y)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ),\n [label, seriesLabel, series, formatX, formatY, xLabel],\n );\n /* eslint-enable react-hooks/exhaustive-deps */\n\n // --- tied to the rest of the screen: the current rule, a readout, picking a reading --------\n const sorted = React.useMemo(() => [...series].sort((p, q) => p.x - q.x), [series]);\n const interactive = Boolean(readout || onPick);\n const [hover, setHover] = React.useState<number | null>(null);\n const [kbd, setKbd] = React.useState<number | null>(null);\n const [focused, setFocused] = React.useState(false);\n const readoutText = (pt: Point) => (typeof readout === \"function\" ? readout(pt) : `${formatX(pt.x)}: ${formatY(pt.y)}`);\n const nearest = (px: number) => {\n const target = xMin + ((px - pad.left) / (w || 1)) * (xMax - xMin || 1);\n let best = 0;\n for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - target) < Math.abs(sorted[best].x - target)) best = i;\n return best;\n };\n /** The value of the line at x, read between the two readings either side (flat beyond the ends). */\n const yAt = (x: number) => {\n if (!sorted.length) return 0;\n if (x <= sorted[0].x) return sorted[0].y;\n for (let i = 1; i < sorted.length; i++) {\n if (x <= sorted[i].x) {\n const [p0, p1] = [sorted[i - 1], sorted[i]];\n return p0.y + ((p1.y - p0.y) * (x - p0.x)) / (p1.x - p0.x || 1);\n }\n }\n return sorted[sorted.length - 1].y;\n };\n const currentAt = current === undefined ? null : { x: Math.min(Math.max(current, xMin), xMax), y: yAt(current) };\n // One reading is \"the\" selection for the announced value, the drawn marker and Enter: the pointer's\n // while it is over the plot, else the keyboard's (clamped, since `series` can be replaced by a shorter\n // one), else where the current rule is, else the last reading.\n const fallbackIdx = sorted.length ? (currentAt ? nearest(sx(currentAt.x)) : sorted.length - 1) : 0;\n const heldIdx = kbd === null ? fallbackIdx : Math.min(kbd, Math.max(sorted.length - 1, 0));\n const selectedIdx = hover === null ? heldIdx : Math.min(hover, Math.max(sorted.length - 1, 0));\n const active = (hover !== null || focused) && sorted.length ? sorted[selectedIdx] : null;\n const onKey = (e: React.KeyboardEvent) => {\n const at = selectedIdx;\n let next = at;\n if (e.key === \"ArrowRight\" || e.key === \"ArrowUp\") next = Math.min(at + 1, sorted.length - 1);\n else if (e.key === \"ArrowLeft\" || e.key === \"ArrowDown\") next = Math.max(at - 1, 0);\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = sorted.length - 1;\n else if ((e.key === \"Enter\" || e.key === \" \") && onPick) {\n e.preventDefault();\n onPick(sorted[at].x);\n return;\n } else return;\n e.preventDefault();\n setHover(null); // the key takes over from a pointer left resting on the plot\n setKbd(next);\n };\n const flip = (px: number, text: string) => (px + labelWidth(text) + 16 > width ? { x: px - 8, anchor: \"end\" as const } : { x: px + 8, anchor: \"start\" as const });\n\n return (\n <figure className={cn(\"grid min-w-0 gap-2\", className)}>\n <div ref={ref} className=\"relative min-w-0\">\n {width > 0 && (\n <svg width={width} height={height} role=\"img\" aria-label={label} className=\"block overflow-visible\">\n {plot}\n {currentAt && (\n <g aria-hidden>\n <line x1={sx(currentAt.x)} x2={sx(currentAt.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--primary)\" strokeWidth={1.5} />\n <circle cx={sx(currentAt.x)} cy={sy(currentAt.y)} r={4} fill=\"var(--background)\" stroke=\"var(--primary)\" strokeWidth={2} />\n {(() => {\n const text = formatCurrent ? formatCurrent(currentAt) : `${formatX(currentAt.x)}: ${formatY(currentAt.y)}`;\n const at = flip(sx(currentAt.x), text);\n return (\n <text x={at.x} y={pad.top + 12} textAnchor={at.anchor} className=\"fill-foreground type-caption tabular-nums\">\n {text}\n </text>\n );\n })()}\n </g>\n )}\n {active && (\n <g aria-hidden>\n <line x1={sx(active.x)} x2={sx(active.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--muted-foreground)\" strokeWidth={1} strokeDasharray=\"2 3\" />\n <circle cx={sx(active.x)} cy={sy(active.y)} r={4} fill=\"var(--foreground)\" />\n {(() => {\n const text = readoutText(active);\n const at = flip(sx(active.x), text);\n return (\n <text x={at.x} y={sy(active.y) - 10} textAnchor={at.anchor} className=\"fill-foreground type-label tabular-nums\" paintOrder=\"stroke\" stroke=\"var(--background)\" strokeWidth={3}>\n {text}\n </text>\n );\n })()}\n </g>\n )}\n </svg>\n )}\n {width > 0 && interactive && sorted.length > 0 && (\n <ReadingSlider\n label={`${label}: read values`}\n sorted={sorted}\n selected={selectedIdx}\n text={readoutText}\n onSelect={(i) => {\n setHover(null);\n setKbd(i);\n }}\n onPick={onPick}\n onKeyDownCapture={onKey}\n onHover={(px) => setHover(px === null ? null : nearest(px))}\n onFocusChange={setFocused}\n box={{ left: pad.left, top: pad.top, width: w, height: h }}\n />\n )}\n </div>\n <figcaption className=\"flex flex-wrap gap-x-5 gap-y-1 type-caption text-muted-foreground\">\n <span className=\"inline-flex items-center gap-2\">\n {stops.length ? (\n <svg width={stops.length * 8} height=\"3\" aria-hidden>\n {stops.map((s, i) => (\n <line key={s.at} x1={i * 8} x2={i * 8 + 8} y1=\"1.5\" y2=\"1.5\" stroke={s.colour} strokeWidth={3} />\n ))}\n </svg>\n ) : (\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke={colour} strokeWidth={2} />\n </svg>\n )}\n {seriesLabel}\n {stops.length > 0 && colourScaleLabel && <span>({colourScaleLabel})</span>}\n </span>\n {planned && plannedLabel && (\n <span className=\"inline-flex items-center gap-2\">\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n </svg>\n {plannedLabel}\n </span>\n )}\n </figcaption>\n {tableEl}\n </figure>\n );\n}\n\n\ntype ReadingSliderProps = {\n label: string;\n sorted: readonly Point[];\n selected: number;\n text: (p: Point) => string;\n onSelect: (index: number) => void;\n onPick?: (x: number) => void;\n onKeyDownCapture: (e: React.KeyboardEvent) => void;\n /** The pointer's x in the plot's own pixels, or null when it leaves. */\n onHover: (px: number | null) => void;\n onFocusChange: (focused: boolean) => void;\n box: { left: number; top: number; width: number; height: number };\n};\n\n/** The slider over the plot: React Aria's hooks, snapped to the readings, with the reading as its spoken value. */\nfunction ReadingSlider({ label, sorted, selected, text, onSelect, onPick, onKeyDownCapture, onHover, onFocusChange, box }: ReadingSliderProps) {\n const track = React.useRef<HTMLDivElement>(null);\n const input = React.useRef<HTMLInputElement>(null);\n const lo = sorted[0].x;\n const hi = Math.max(sorted[sorted.length - 1].x, lo + 1e-9);\n const indexAt = (x: number) => {\n let best = 0;\n for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - x) < Math.abs(sorted[best].x - x)) best = i;\n return best;\n };\n const spoken = React.useMemo(() => {\n const say = (x: number) => text(sorted[indexAt(x)]);\n return { format: say, formatRange: (a: number, b: number) => `${say(a)} to ${say(b)}`, resolvedOptions: () => ({ locale: \"en-US\" }) } as unknown as Intl.NumberFormat;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sorted, text]);\n const state = useSliderState({\n minValue: lo,\n maxValue: hi,\n step: (hi - lo) / 10000,\n value: [sorted[selected].x],\n onChange: ([x]) => onSelect(indexAt(x)),\n onChangeEnd: ([x]) => onPick?.(sorted[indexAt(x)].x),\n numberFormatter: spoken,\n });\n const { groupProps, trackProps } = useSlider({ \"aria-label\": label }, state, track);\n const { thumbProps, inputProps } = useSliderThumb({ index: 0, trackRef: track, inputRef: input, \"aria-label\": label }, state);\n const { focusProps, isFocusVisible } = useFocusRing();\n return (\n <div {...groupProps} className=\"absolute\" style={box}>\n <div\n {...trackProps}\n ref={track}\n onPointerMove={(e) => onHover(e.clientX - e.currentTarget.getBoundingClientRect().left + box.left)}\n onPointerLeave={() => onHover(null)}\n className={cn(\"relative size-full cursor-crosshair touch-none\", isFocusVisible && \"outline-2 outline-offset-2 outline-ring\")}\n >\n <div {...thumbProps} className=\"absolute inset-y-0 w-0\" style={{ left: `${state.getThumbPercent(0) * 100}%` }}>\n <VisuallyHidden>\n <input\n ref={input}\n {...mergeProps(inputProps, focusProps, { onFocus: () => onFocusChange(true), onBlur: () => onFocusChange(false) })}\n aria-labelledby={undefined}\n onKeyDownCapture={(e) => {\n onKeyDownCapture(e);\n if (e.defaultPrevented) e.stopPropagation();\n }}\n />\n </VisuallyHidden>\n </div>\n </div>\n </div>\n );\n}\n","import * as React from \"react\";\n\n// The top of every Operate screen: a noun title at 24px (never \"Welcome back\"), its scope, the\n// screen's main action, and the finding. The finding is the one fact in today's data that most\n// needs attention; it sits where it is read first, beside the action it drives.\n\n/** The top of an Operate screen: a noun title, its scope, the main action, and the finding (the one fact in today's data that most needs attention). */\nexport function PageHeader({\n title,\n scope,\n actions,\n finding,\n as: Heading = \"h1\",\n}: {\n title: string;\n /** The title's element: h1 on a screen, h2 where the header is shown inside another page. */\n as?: \"h1\" | \"h2\";\n /** What the screen covers: a date, a range, a filter. */\n scope?: React.ReactNode;\n actions?: React.ReactNode;\n finding?: { text: React.ReactNode; action?: React.ReactNode };\n}) {\n return (\n <header className=\"grid gap-4\">\n <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-3\">\n <div className=\"grid min-w-0 gap-0.5\">\n <Heading className=\"type-title text-balance\">{title}</Heading>\n {scope && <p className=\"type-body-sm text-muted-foreground\">{scope}</p>}\n </div>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions}</div>}\n </div>\n {finding && (\n <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-3 border-y border-border py-3\">\n <p className=\"max-w-prose min-w-0 type-body text-pretty\">{finding.text}</p>\n {finding.action}\n </div>\n )}\n </header>\n );\n}\n","import * as React from \"react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\n\n// Destructive actions take effect visibly at once and commit after a window, with Undo in reach.\n// For reversible removals this beats a confirm dialog: the dialog interrupts every time to protect\n// against the rare mistake, and people learn to click through it. Keep a confirm dialog for\n// actions that cannot be undone (deleting an account, firing a kiln).\n\n// A bulk removal is one removal with `ids`: the selected rows go, come back on Undo, and fail\n// together, under one message and one commit, because the person did one thing.\n//\n// One removal is pending at a time. Scheduling a second commits the first at once: in rapid-fire\n// triage (withdraw, withdraw, withdraw) Undo reaches back one step, and the bar never stacks up a\n// queue of messages nobody reads. Undo is for the slip just made, not for an audit trail.\n//\n// The hook owns which items are out of view (`isRemoved`), so a screen filters its rows by it and\n// never keeps a second \"hidden\" set that can drift from the pending one. An item stays removed\n// from when it is scheduled; Undo brings it back; a commit that fails brings it back and puts the\n// failure in the same bar, with \"Try again\", because the screen told the person it was done and a\n// silent failure would leave the screen lying. A committed item stays removed until the screen's\n// data drops it (the commit should invalidate the query it came from), so it never flickers back.\n//\n// `flush()` exists for the action that depends on the removal having happened (retrain on the\n// answers, export the list): commit now and await it, rather than racing the window.\n//\n// Failures are described like any other failed action (`describeActionError`, as AsyncButton uses,\n// unless the product passes its own): the same HTTP sentences as reads, without promising that\n// nothing changed, since a write that failed may still have reached the server.\n\n/** A removal waiting out its undo window: what to say, what to do when the window closes, and what to say if that fails. */\nexport type PendingRemoval = {\n /** Identifies the removed item: `isRemoved(id)` is true from `schedule` until Undo or a failed commit. */\n id: string;\n /** A bulk removal's items, all removed, undone, committed and restored together (one `commit` for the batch). `isRemoved` is true for each. Default `[id]`. */\n ids?: readonly string[];\n /** What happened, in the product's words: \"Withdrew Tom Ellery's 3 pieces from kiln 2.\" */\n message: string;\n /** What the person reads if the commit fails, saying the item is back: \"Tom Ellery's 3 pieces are back in kiln 2: the withdrawal did not go through.\" */\n failure: string;\n /** Makes the removal real (usually a request, then invalidating the query the item came from). Runs once per attempt: when the window closes, on `flush()`, when a second removal is scheduled, or when the owner unmounts. */\n commit: () => void | Promise<unknown>;\n /** Called after a failed commit, for anything beyond restoring the item and showing the failure (which the hook does). The only failure path once the owner has unmounted. */\n onError?: (error: unknown) => void;\n};\n\n/** A removal whose commit failed: the removal, and the error described for a person. */\nexport type FailedRemoval = { removal: PendingRemoval; message?: string };\n\n/** Options for `useUndoable`. */\nexport type UndoableOptions = {\n /** How long Undo stays in reach, in milliseconds. Default 8000. */\n windowMs?: number;\n /** Describes a failed commit for a person, or returns undefined to show the removal's `failure` alone. Default `describeActionError`, as for `useAsyncAction`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useUndoable` returns. Pass it whole to `UndoBar`. */\nexport type Undoable = {\n /** The removal inside its window, or null. */\n pending: PendingRemoval | null;\n /** The last removal whose commit failed, until it is retried, dismissed or another removal is scheduled. */\n failed: FailedRemoval | null;\n /** Whether an item is out of view: scheduled, committing or committed, and not undone or failed. Filter rows with it. */\n isRemoved: (id: string) => boolean;\n /** Removes an item and starts its window. Commits any removal already pending first: only one is pending at a time. */\n schedule: (next: PendingRemoval) => void;\n /** Cancels the pending removal and brings the item back; its `commit` never runs. */\n undo: () => void;\n /** Commits the pending removal now and resolves when it and every earlier commit still in flight have settled; rejects if any failed, so a dependent action does not run. Resolves at once when nothing is pending or running. */\n flush: () => Promise<void>;\n /** Removes the failed item again and commits it now (the person already waited out the window); settles like `flush`. */\n retry: () => Promise<void>;\n /** Clears the failure from the bar; the item stays back. */\n dismiss: () => void;\n};\n\n/**\n * Schedules a reversible removal to commit after a window unless undone, and owns which items\n * are out of view meanwhile.\n *\n * Only one removal is pending at a time: scheduling a second commits the first immediately.\n * Unmounting inside the window commits the pending removal (leaving is not Undo), so a navigation\n * or a test that unmounts still sends the commit's request: await `flush()` before a dependent\n * action, and in tests let MSW answer the request or flush before unmounting.\n */\nexport function useUndoable(options: number | UndoableOptions = {}): Undoable {\n const { windowMs = 8000, describeError = describeActionError } =\n typeof options === \"number\" ? { windowMs: options } : options;\n const [pending, setPending] = React.useState<PendingRemoval | null>(null);\n const [failed, setFailed] = React.useState<FailedRemoval | null>(null);\n const [removed, setRemoved] = React.useState<ReadonlySet<string>>(() => new Set());\n const current = React.useRef<PendingRemoval | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n // Every commit still running, whoever started it: flush() waits for all of them, not only the\n // pending one, because an earlier removal's request may still be in flight (its window closed,\n // or a second removal committed it) and a dependent action must not overtake it.\n const inFlight = React.useRef(new Set<Promise<void>>());\n const describe = React.useRef(describeError);\n describe.current = describeError;\n\n const hide = React.useCallback((p: PendingRemoval, out: boolean) => {\n const ids = p.ids ?? [p.id];\n setRemoved((s) => {\n if (ids.every((id) => s.has(id) === out)) return s;\n const n = new Set(s);\n for (const id of ids) {\n if (out) n.add(id);\n else n.delete(id);\n }\n return n;\n });\n }, []);\n\n // Runs one attempt at a removal's commit. A synchronous throw is treated like a rejection, so\n // there is one failure path: bring the item back, show the failure, tell onError, reject.\n const attempt = React.useCallback(\n (p: PendingRemoval): Promise<void> => {\n let result: void | Promise<unknown>;\n try {\n result = p.commit();\n } catch (error) {\n result = Promise.reject(error);\n }\n const done = Promise.resolve(result).then(\n () => undefined,\n (error: unknown) => {\n if (mounted.current) {\n hide(p, false);\n setFailed({ removal: p, message: describe.current(error) });\n }\n p.onError?.(error);\n throw error;\n },\n );\n inFlight.current.add(done);\n const settle = () => void inFlight.current.delete(done);\n done.then(settle, settle);\n return done;\n },\n [hide],\n );\n\n // Takes the pending removal out (so it commits only once) and attempts it.\n const take = React.useCallback((): { removal: PendingRemoval; done: Promise<void> } | null => {\n window.clearTimeout(timer.current);\n const p = current.current;\n if (!p) return null;\n current.current = null;\n if (mounted.current) setPending(null);\n return { removal: p, done: attempt(p) };\n }, [attempt]);\n\n // Commits the hook starts itself (window closed, second removal, unmount) have no caller to\n // await them. A failure is handled once it is in the bar or onError has it; only a failure\n // nobody can see (unmounted, no onError) is left to surface as an unhandled rejection.\n const commitDetached = React.useCallback(() => {\n const t = take();\n t?.done.catch((error: unknown) => {\n if (!mounted.current && !t.removal.onError) throw error;\n });\n }, [take]);\n\n const schedule = React.useCallback(\n (next: PendingRemoval) => {\n commitDetached(); // a second removal commits the first\n setFailed(null);\n hide(next, true);\n current.current = next;\n setPending(next);\n timer.current = window.setTimeout(commitDetached, windowMs);\n },\n [commitDetached, hide, windowMs],\n );\n\n const undo = React.useCallback(() => {\n window.clearTimeout(timer.current);\n const p = current.current;\n current.current = null;\n setPending(null);\n if (p) hide(p, false);\n }, [hide]);\n\n const flush = React.useCallback(async () => {\n take();\n const results = await Promise.allSettled([...inFlight.current]);\n const failure = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\");\n if (failure) throw failure.reason;\n }, [take]);\n\n const retry = React.useCallback(() => {\n if (!failed) return Promise.resolve();\n setFailed(null);\n hide(failed.removal, true);\n return attempt(failed.removal);\n }, [attempt, failed, hide]);\n\n const dismiss = React.useCallback(() => setFailed(null), []);\n\n const isRemoved = React.useCallback((id: string) => removed.has(id), [removed]);\n\n // Leaving the screen is not Undo: if the owner unmounts inside the window (the person navigated\n // away), commit what was scheduled rather than silently dropping it.\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n commitDetached();\n };\n }, [commitDetached]);\n\n return { pending, failed, isRemoved, schedule, undo, flush, retry, dismiss };\n}\n\n// The bar lives in a polite live region that is always mounted, so screen readers hear the message\n// when it appears, and a failure replaces the message in the same place the person was looking.\n// It is fixed to the bottom of the viewport; a page that uses it keeps that much bottom padding so\n// the bar never covers the focused row. A failure stays until it is retried or dismissed: an error\n// that times out is one a person can miss.\n/** The polite live region that shows a pending removal with Undo, or a failed one with Try again. Pass it the whole `useUndoable()` result. */\nexport function UndoBar({\n undoable,\n inline = false,\n}: {\n undoable: Pick<Undoable, \"pending\" | \"failed\" | \"undo\" | \"retry\" | \"dismiss\">;\n /** Render in the flow instead of fixed to the viewport; for the state-matrix page. */\n inline?: boolean;\n}) {\n const { pending, failed, undo, retry, dismiss } = undoable;\n const ghost = \"text-background hover:bg-neutral-11\";\n return (\n <div\n aria-live=\"polite\"\n className={\n inline ? \"flex\" : \"layer-bar pointer-events-none fixed inset-x-0 bottom-4 flex justify-center px-4\"\n }\n >\n {(pending || failed) && (\n <div className=\"pointer-events-auto flex max-w-lg items-center gap-4 rounded-overlay bg-foreground py-2 pr-2 pl-4 text-background shadow-overlay\">\n {pending ? (\n <>\n <p className=\"min-w-0 type-body-sm\">{pending.message}</p>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={undo}>\n Undo\n </Button>\n </>\n ) : (\n failed && (\n <>\n <p className=\"min-w-0 type-body-sm\">\n {failed.message ? `${failed.removal.failure} ${failed.message}` : failed.removal.failure}\n </p>\n <div className=\"flex shrink-0 gap-1\">\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={() => void retry().catch(() => undefined)}>\n Try again\n </Button>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={dismiss}>\n Dismiss\n </Button>\n </div>\n </>\n )\n )}\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Check } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// The completion moment: what a person sees after finishing something that took effort (a\n// booking, a submission, an import). It is the one place on an Operate product where the library\n// spends its delight budget (character.md §3), so it is a component with rules rather than a\n// confetti call:\n// - `title` says what happened, in the past tense, with the object: \"Booked: 6 pieces in kiln 2\".\n// - `next` is required. A finish that does not say what happens now is a dead end, however\n// pleasant.\n// - `figure` is optional and must be drawn from the person's own data in the subject's terms\n// (their pieces on a shelf, their route on a map), never a stock illustration.\n// - The part of the figure that is the person's result enters once, with the `enter-moment`\n// utility (500ms, hard ease-out, no overshoot): their pieces set down on the shelf. Reduced\n// motion makes it instant. Nothing loops and nothing plays a sound.\n// - Focus moves to the heading on mount, so keyboard and screen-reader users land on the result.\n\n/** The completion moment for a rare, earned finish: what happened (past tense, with its object), what happens next, and optionally a figure drawn from the person's own data. Focus moves to the heading. */\nexport function Done({\n title,\n next,\n figure,\n actions,\n focusOnMount = true,\n className,\n}: {\n /** What happened, past tense, with its object. */\n title: string;\n /** What the person does now, or what happens next and when. */\n next: React.ReactNode;\n /** A drawing of the result made from the person's data in the subject's own terms. */\n figure?: React.ReactNode;\n actions?: React.ReactNode;\n /** Off only where the result is not the page's subject (the state-matrix page). */\n focusOnMount?: boolean;\n className?: string;\n}) {\n const heading = React.useRef<HTMLHeadingElement>(null);\n const titleId = React.useId();\n React.useEffect(() => {\n if (focusOnMount) heading.current?.focus();\n }, [focusOnMount]);\n return (\n <section aria-labelledby={titleId} className={cn(\"grid gap-5\", className)}>\n <div className=\"grid gap-2\">\n <h1 id={titleId} ref={heading} tabIndex={-1} className=\"flex items-start gap-2 type-title\">\n <Check aria-hidden className=\"mt-1 size-6 shrink-0 text-success\" />\n {title}\n </h1>\n <div className=\"max-w-prose type-body text-muted-foreground\">{next}</div>\n </div>\n {figure}\n {actions && <div className=\"flex flex-wrap items-center gap-3\">{actions}</div>}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Link, NavLink } from \"react-router\";\nimport { cn } from \"../lib/utils\";\nimport type { IconComponent } from \"../lib/icon\";\n\n// The frame of an app: a side nav on the page ground (not a navy or tinted sidebar), the current\n// item as a neutral pill (no left bar, no accent), and the page beside it. A top bar exists only\n// when it holds something used on every screen, so it is a slot, not a default. Built on React\n// Router's NavLink, so \"current\" is the router's answer and aria-current is set for free. On\n// phones the nav becomes a horizontal, scrollable row above the page rather than a hamburger, so\n// every destination stays one tap away.\n\nexport type NavItem = {\n to: string;\n label: string;\n icon?: IconComponent;\n /** Match only this exact path, for an index route such as \"/\". */\n end?: boolean;\n};\n\n/** The app frame: product name, side nav on the page ground (a scrollable row on phones), optional top bar, and the main region. */\nexport function AppShell({\n product,\n nav,\n navLabel = \"Main\",\n topBar,\n children,\n className,\n}: {\n /** The product's name or mark, linking home. */\n product: React.ReactNode;\n nav: NavItem[];\n navLabel?: string;\n topBar?: React.ReactNode;\n children: React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-h-dvh md:grid md:grid-cols-[14rem_minmax(0,1fr)]\", className)}>\n <aside className=\"border-b border-border md:border-r md:border-b-0\">\n <div className=\"flex items-center gap-4 px-4 py-3 md:block md:px-3 md:py-4\">\n <Link to=\"/\" className=\"shrink-0 rounded-control px-2 type-heading text-foreground no-underline\">\n {product}\n </Link>\n <SideNav items={nav} label={navLabel} className=\"min-w-0 flex-1 md:mt-4\" />\n </div>\n </aside>\n <div className=\"min-w-0\">\n {topBar && <div className=\"flex items-center gap-3 border-b border-border px-4 py-2 md:px-8\">{topBar}</div>}\n <main className=\"px-4 py-6 md:px-8 md:py-8\">{children}</main>\n </div>\n </div>\n );\n}\n\n/** Navigation links (React Router `NavLink`); the current route is a neutral pill with `aria-current`. */\nexport function SideNav({ items, label, className }: { items: NavItem[]; label: string; className?: string }) {\n return (\n <nav aria-label={label} className={cn(\"min-w-0\", className)}>\n <ul className=\"flex gap-1 overflow-x-auto md:grid md:overflow-visible\">\n {items.map(({ to, label, icon: Icon, end }) => (\n <li key={to} className=\"shrink-0\">\n <NavLink\n to={to}\n end={end}\n className={({ isActive }) =>\n cn(\n \"flex h-(--control-h-sm) items-center gap-2 rounded-control px-2 type-label whitespace-nowrap no-underline transition-state\",\n isActive ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n )\n }\n >\n {Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />}\n {label}\n </NavLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\n// Plain links with a \"/\" separator in muted ink. The last crumb is the current page: text, not a\n// link, with aria-current.\n/** Plain links separated by `/`; the last crumb is the current page. */\nexport function Breadcrumb({ items }: { items: { label: string; to?: string }[] }) {\n return (\n <nav aria-label=\"Breadcrumb\">\n <ol className=\"flex flex-wrap items-center gap-x-2 type-body-sm text-muted-foreground\">\n {items.map((item, i) => {\n const last = i === items.length - 1;\n return (\n <li key={`${item.label}-${i}`} className=\"flex items-center gap-2\">\n {item.to && !last ? (\n <Link to={item.to} className=\"text-muted-foreground underline hover:text-foreground\">\n {item.label}\n </Link>\n ) : (\n <span aria-current={last ? \"page\" : undefined} className={cn(last && \"text-foreground\")}>\n {item.label}\n </span>\n )}\n {!last && <span aria-hidden>/</span>}\n </li>\n );\n })}\n </ol>\n </nav>\n );\n}\n","import * as React from \"react\";\nimport { useSearchParams } from \"react-router\";\nimport { Tab, TabList, TabPanel, Tabs as AriaTabs } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// Tabs whose state lives in the URL (?view=readings), so a tab can be linked, survives reload and\n// works with Back. Built on React Aria Tabs (ARIA tabs pattern: arrow keys move between tabs and\n// select them, Home and End jump, only the selected tab is in the tab order). The selected tab is marked by weight and a\n// 2px rule in ink, not by colour alone. The first tab is the default and is not written to the URL.\n\nexport type TabItem = { value: string; label: string };\n\n/** Tabs whose selection lives in a URL search parameter (React Router), with the ARIA tabs keyboard model. */\nexport function Tabs({\n param,\n items,\n label,\n children,\n className,\n}: {\n /** The search parameter that holds the selected tab. */\n param: string;\n items: TabItem[];\n /** Names the tab list for screen readers. */\n label: string;\n /** Renders the selected panel. */\n children: (value: string) => React.ReactNode;\n className?: string;\n}) {\n const [params, setParams] = useSearchParams();\n const fallback = items[0]?.value ?? \"\";\n const raw = params.get(param);\n const value = items.some((i) => i.value === raw) ? raw! : fallback;\n const select = (next: string) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n if (next === fallback) out.delete(param);\n else out.set(param, next);\n return out;\n },\n { replace: true },\n );\n\n // React Aria's Tabs owns the keyboard model (arrows, Home and End, roving tab stop, automatic\n // activation) and the ids that tie each tab to the panel; the selected key is the URL's.\n return (\n <AriaTabs selectedKey={value} onSelectionChange={(key) => select(String(key))} className={cn(\"grid gap-4\", className)}>\n <TabList aria-label={label} className=\"flex gap-4 overflow-x-auto border-b border-border\">\n {items.map((item) => (\n <Tab\n key={item.value}\n id={item.value}\n className={cn(\n \"-mb-px cursor-pointer border-b-2 py-2 type-label whitespace-nowrap transition-state\",\n \"border-transparent text-muted-foreground hover:text-foreground\",\n \"selected:border-foreground selected:font-semibold selected:text-foreground\",\n )}\n >\n {item.label}\n </Tab>\n ))}\n </TabList>\n <TabPanel id={value} shouldForceMount={false}>\n {children(value)}\n </TabPanel>\n </AriaTabs>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget, type Shortcut } from \"./hotkeys\";\n\n// A queue someone works through from the keyboard: one item is active, j/k (or the arrow keys\n// inside the list) move it, and answering an item moves straight on to the next one. Three\n// decisions shape it:\n// 1. The active item is the one with focus. It is a roving tab stop (only it is in the tab order)\n// and carries aria-current, so a screen reader hears which item an answer applies to. It is\n// marked by a 2px rule in ink as well as a tint, not by colour alone.\n// 2. When the active item leaves the list (accepted, rejected, removed), the item that took its\n// place becomes active, or the one before it at the end of the list, and focus follows if it\n// was in the list. Otherwise focus would fall to <body> and the next key would do nothing.\n// 3. The hook remembers which item the person chose, not just a position. If an Undo puts the\n// item back, it is active again (pairs with `useUndoable`).\n// Moving is instant: no transition on the highlight (ux-research `ux-character.md`, 100+ a day).\n\n/** What `useActiveItem` returns: the active item, ways to move it, and the props each item element needs. */\nexport type ActiveItem<T> = {\n items: readonly T[];\n getKey: (item: T) => string;\n activeKey: string | null;\n activeItem: T | null;\n /** Position of the active item, or -1 when the list is empty. */\n index: number;\n next: () => void;\n prev: () => void;\n first: () => void;\n last: () => void;\n setActive: (key: string) => void;\n /** The j/k shortcuts for `useHotkeys` and `KeysLegend`. */\n shortcuts: Shortcut[];\n /** Props for the element that represents an item: ref, tabIndex, aria-current and focus tracking. */\n itemProps: (key: string) => {\n ref: (el: HTMLElement | null) => void;\n tabIndex: number;\n \"aria-current\": \"true\" | undefined;\n \"data-active\": \"\" | undefined;\n onFocus: () => void;\n onBlur: (e: React.FocusEvent) => void;\n };\n};\n\n/** Tracks the active item in a list worked through from the keyboard: moving, roving focus, and moving on when the active item is removed. */\nexport function useActiveItem<T>(\n items: readonly T[],\n getKey: (item: T) => string,\n {\n initial,\n noun,\n }: {\n /** Key of the item active at first; the first item otherwise. */\n initial?: string;\n /** Names an item in the shortcut labels: \"Next booking\". */\n noun?: string;\n } = {},\n): ActiveItem<T> {\n const [chosen, setChosen] = React.useState<string | null>(initial ?? null);\n const lastIndex = React.useRef(0);\n const elements = React.useRef(new Map<string, HTMLElement>());\n const navigated = React.useRef(false);\n const focusWithin = React.useRef(false);\n\n const keys = items.map(getKey);\n let index = chosen === null ? -1 : keys.indexOf(chosen);\n if (index === -1 && keys.length > 0) index = Math.min(lastIndex.current, keys.length - 1);\n const activeKey = index >= 0 ? keys[index] : null;\n\n // Remember the position, and the last item that left the list while active. Answering two in a\n // row (at the end of the queue, say) must make the second the one an Undo brings back as\n // active, not the first.\n const prevActive = React.useRef<string | null>(activeKey);\n React.useLayoutEffect(() => {\n if (index >= 0) lastIndex.current = index;\n const gone = prevActive.current;\n prevActive.current = activeKey;\n if (gone !== null && gone !== chosen && !keys.includes(gone)) setChosen(gone);\n });\n\n // Move focus to the active item when the person moved it, when the focused item was removed\n // (focus has fallen to <body>), or when focus is on another item in the list (an Undo made the\n // restored item active again). Never take focus from somewhere else on the page.\n React.useLayoutEffect(() => {\n const el = activeKey === null ? undefined : elements.current.get(activeKey);\n const focused = document.activeElement;\n const lost = focusWithin.current && (focused === null || focused === document.body);\n const elsewhereInList =\n focused !== null && !el?.contains(focused) && [...elements.current.values()].some((item) => item.contains(focused));\n if (el && (navigated.current || lost || elsewhereInList)) {\n el.focus({ preventScroll: true });\n el.scrollIntoView?.({ block: \"nearest\" });\n }\n navigated.current = false;\n }, [activeKey]);\n\n const moveTo = (i: number) => {\n if (keys.length === 0) return;\n const to = Math.max(0, Math.min(keys.length - 1, i));\n navigated.current = true;\n if (to === index) {\n // Already there: still bring focus back to it, as the person asked to move.\n const el = elements.current.get(keys[to]);\n el?.focus({ preventScroll: true });\n el?.scrollIntoView?.({ block: \"nearest\" });\n navigated.current = false;\n }\n setChosen(keys[to]);\n };\n\n const next = () => moveTo(index + 1);\n const prev = () => moveTo(index - 1);\n const first = () => moveTo(0);\n const last = () => moveTo(keys.length - 1);\n const setActive = (key: string) => {\n const i = keys.indexOf(key);\n if (i >= 0) moveTo(i);\n };\n\n const name = noun ? ` ${noun}` : \"\";\n const shortcuts: Shortcut[] = [\n { keys: [\"j\"], label: `Next${name}`, run: next, repeat: true, disabled: keys.length === 0 },\n { keys: [\"k\"], label: `Previous${name}`, run: prev, repeat: true, disabled: keys.length === 0 },\n ];\n\n const itemProps: ActiveItem<T>[\"itemProps\"] = (key) => ({\n ref: (el) => {\n if (el) elements.current.set(key, el);\n else elements.current.delete(key);\n },\n tabIndex: key === activeKey ? 0 : -1,\n \"aria-current\": key === activeKey ? \"true\" : undefined,\n \"data-active\": key === activeKey ? \"\" : undefined,\n onFocus: () => {\n focusWithin.current = true;\n // Clicking or tabbing into an item makes it active. If it already is (it took a removed\n // item's place), keep remembering the removed one so an Undo makes that active again.\n if (key !== activeKey) setChosen(key);\n },\n onBlur: (e) => {\n // Focus going nowhere (null) is what removal looks like, so only a move to a real element\n // outside the list counts as leaving it.\n const to = e.relatedTarget;\n if (to instanceof Node && ![...elements.current.values()].some((el) => el.contains(to))) focusWithin.current = false;\n },\n });\n\n return {\n items,\n getKey,\n activeKey,\n activeItem: index >= 0 ? items[index] : null,\n index,\n next,\n prev,\n first,\n last,\n setActive,\n shortcuts,\n itemProps,\n };\n}\n\n// The list renders the queue from `useActiveItem`. The arrow keys, Home and End move the active\n// item while focus is in the list (the window-wide j/k come from `active.shortcuts` via\n// `useHotkeys`, because only the screen knows whether it has one queue or two). An empty queue\n// is a state the list cannot be written without: say what clearing it means and what is next.\n/** A keyboard-worked queue: the active item is a roving tab stop with aria-current, and the arrow keys, Home and End move it. */\nexport function ActiveList<T>({\n label,\n active,\n empty,\n children,\n className,\n}: {\n /** Names the list for screen readers. */\n label: string;\n active: ActiveItem<T>;\n /** Shown when the queue is clear: what that means and what to do next. */\n empty: React.ReactNode;\n children: (item: T, state: { active: boolean }) => React.ReactNode;\n className?: string;\n}) {\n if (active.items.length === 0) return <>{empty}</>;\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.ctrlKey || e.metaKey || e.altKey || isTypingTarget(e.target)) return;\n const move =\n e.key === \"ArrowDown\" ? active.next\n : e.key === \"ArrowUp\" ? active.prev\n : e.key === \"Home\" ? active.first\n : e.key === \"End\" ? active.last\n : undefined;\n if (!move) return;\n e.preventDefault();\n move();\n };\n\n return (\n <ul aria-label={label} onKeyDown={onKeyDown} className={cn(\"grid gap-px\", className)}>\n {active.items.map((item) => {\n const key = active.getKey(item);\n const isActive = key === active.activeKey;\n return (\n <li\n key={key}\n {...active.itemProps(key)}\n className={cn(\n \"rounded-control border-l-2 px-3 py-2 -outline-offset-2\",\n isActive ? \"border-foreground bg-accent text-accent-foreground\" : \"border-transparent\",\n )}\n >\n {children(item, { active: isActive })}\n </li>\n );\n })}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { hashKey, useInfiniteQuery, type QueryKey } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport { describeHttpError, staleOf, type DescribeError } from \"./index\";\n\n// Cursor-paged reads, the Strata way. `useLoad` covers a read that arrives whole; a feed, a log or\n// a triage queue arrives a page at a time. This is the same bridge for those: TanStack's\n// useInfiniteQuery underneath, a `Load<T[]>` on top (so `DataView` takes it unchanged for the\n// first page's loading, error and empty states), and a `more` object for everything after it.\n//\n// Three opinions:\n// 1. The cursor is \"after the last item held\", never an offset, and the hook works it out: the\n// app says how to make a cursor from an item (`cursorAfter`) and whether a page says there are\n// more (`hasMore`). In a queue people work through (answered reviews, archived firings), items\n// leave the server's list between pages, and an offset would skip the ones that moved up to\n// fill the gap. Two cases fall back to the last item *seen*, dismissed or not: when everything\n// held has been dismissed (there is no held item to go after, and starting again from the top\n// could fetch the same dismissed page forever), and when the last page brought nothing new\n// (only items already held or dismissed came back, so going after the last held item again\n// would ask for the same page in a loop).\n// 2. Items have keys. Pages are merged by key, so an item that shifts across a page boundary is\n// shown once, and `dismiss(key)` hides one at once (an optimistic remove, paired with\n// useUndoable) without the app rewriting TanStack's page cache by hand. Dismissals belong to\n// one query: a new `queryKey` (another filter) starts with none. A screen that removes items\n// with `useUndoable` passes its `isRemoved` instead, so the undo hook stays the one owner of\n// what is out of view (Undo, a failed commit and Try again all show through) and the cursor\n// still skips past what it hides.\n// 3. A later page failing is not the list failing. The held items stay; `more.error` says what\n// happened and `more.loadMore` is the Try again. A refetch of the held pages failing is not the\n// list failing either: the items stay and `stale` says how old they are, as with `useLoad`.\n// Only a failed first page is a `Load` error.\n\n/** The state of the pages after the first: whether there are more, whether one is on its way, and why the last one failed. */\nexport type More = {\n /** The server has said there is another page. */\n hasMore: boolean;\n /** A page after the first is being fetched. */\n loadingMore: boolean;\n /** Why the last page after the first failed, for a person. Cleared when a retry succeeds. */\n error?: string;\n /** Fetch the next page; also the Try again after `error`. Does nothing while one is loading or when there are no more. */\n loadMore: () => void;\n};\n\n/** A cursor-paged read: a `Load<T[]>` of the items held (so `DataView` takes it), plus the next page's state and keyed removal. */\nexport type InfiniteLoad<T> = Load<T[]> & {\n more: More;\n itemKey: (item: T) => string;\n /** Hide an item at once (an optimistic removal). The next cursor goes after the last item still held. */\n dismiss: (key: string) => void;\n /** Show a dismissed item again: the Undo of `dismiss`. */\n restore: (key: string) => void;\n};\n\n/** Options for `useInfiniteLoad`. */\nexport type InfiniteLoadOptions<T, Page, Cursor, K extends QueryKey> = {\n queryKey: K;\n /** Fetch one page. `cursor` is undefined for the first page, else `cursorAfter` of the last item held. */\n queryFn: (context: { cursor: Cursor | undefined; signal: AbortSignal }) => Promise<Page>;\n /** The items in a page. For an API that returns a bare array, `(page) => page`. */\n items: (page: Page) => T[];\n /** A stable key per item: merges pages, and is what `dismiss` takes. */\n itemKey: (item: T) => string;\n /** Whether the server says there is a page after this one. */\n hasMore: (lastPage: Page) => boolean;\n /** The cursor that asks for the items after this one; usually its id. Defaults to `itemKey`. */\n cursorAfter?: (item: T) => Cursor;\n /** Items hidden by someone else, usually `useUndoable().isRemoved`: treated like dismissed ones. */\n isRemoved?: (key: string) => boolean;\n describeError?: DescribeError;\n enabled?: boolean;\n staleTime?: number;\n};\n\ntype Dismissed = { query: string; keys: ReadonlySet<string> };\ntype PageParam<Cursor> = { cursor: Cursor | undefined };\n\n/** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */\nexport function useInfiniteLoad<T, Page, Cursor = string, K extends QueryKey = QueryKey>({\n queryKey,\n queryFn,\n items,\n itemKey,\n hasMore,\n cursorAfter = itemKey as unknown as (item: T) => Cursor,\n isRemoved,\n describeError = describeHttpError,\n enabled,\n staleTime,\n}: InfiniteLoadOptions<T, Page, Cursor, K>): InfiniteLoad<T> {\n const queryHash = hashKey(queryKey);\n const [stored, setStored] = React.useState<Dismissed>(() => ({ query: queryHash, keys: new Set() }));\n const dismissed = stored.query === queryHash ? stored.keys : none;\n const hidden = React.useCallback((key: string) => dismissed.has(key) || (isRemoved?.(key) ?? false), [dismissed, isRemoved]);\n // TanStack calls getNextPageParam outside render; it reads the latest hidden set and accessors.\n const latest = React.useRef({ hidden, items, itemKey, hasMore, cursorAfter });\n latest.current = { hidden, items, itemKey, hasMore, cursorAfter };\n\n const query = useInfiniteQuery({\n queryKey,\n queryFn: ({ pageParam, signal }) => queryFn({ cursor: pageParam.cursor, signal }),\n initialPageParam: { cursor: undefined } as PageParam<Cursor>,\n getNextPageParam: (lastPage, pages): PageParam<Cursor> | null => {\n const l = latest.current;\n if (!l.hasMore(lastPage)) return null;\n const after = nextAfter(pages, l.items, l.itemKey, l.hidden);\n return { cursor: after === undefined ? undefined : l.cursorAfter(after) };\n },\n enabled,\n staleTime,\n });\n\n const pages = query.data?.pages;\n // Keyed on the pages and dismissals only, so inline `items`/`itemKey` arrows do not hand the\n // list a new array every render.\n const list = React.useMemo(\n () => (pages ? merge(pages, latest.current.items, latest.current.itemKey, hidden).held : undefined),\n [pages, hidden],\n );\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage, refetch } = query;\n const loadMore = React.useCallback(() => {\n if (hasNextPage && !isFetchingNextPage) void fetchNextPage();\n }, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n const change = React.useCallback(\n (edit: (keys: Set<string>) => void) =>\n setStored((s) => {\n const keys = new Set(s.query === queryHash ? s.keys : none);\n edit(keys);\n return { query: queryHash, keys };\n }),\n [queryHash],\n );\n const dismiss = React.useCallback((key: string) => change((keys) => keys.add(key)), [change]);\n const restore = React.useCallback((key: string) => change((keys) => keys.delete(key)), [change]);\n\n const more: More = {\n hasMore: Boolean(hasNextPage),\n loadingMore: isFetchingNextPage,\n error: query.isFetchNextPageError ? describeError(query.error) : undefined,\n loadMore,\n };\n const extra = { more, itemKey, dismiss, restore };\n if (list) {\n // isRefetchError excludes a failed next page, which is `more.error`'s to report.\n const stale = query.isRefetchError ? staleOf(query, describeError) : undefined;\n return { status: \"ready\", data: list, ...(stale && { stale }), ...extra };\n }\n if (query.status === \"error\") return { status: \"error\", message: describeError(query.error), retry: () => void refetch(), ...extra };\n return { status: \"loading\", ...extra };\n}\n\nconst none: ReadonlySet<string> = new Set();\n\n/** Every page's items, in order, once each by key: the ones held (not dismissed) and the last one seen. */\nfunction merge<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const seen = new Set<string>();\n const held: T[] = [];\n let last: T | undefined;\n let lastPageAddedAny = false;\n pages.forEach((page, p) => {\n for (const item of items(page)) {\n const key = itemKey(item);\n if (seen.has(key)) continue;\n seen.add(key);\n last = item;\n if (p === pages.length - 1) lastPageAddedAny = true;\n if (!hidden(key)) held.push(item);\n }\n });\n return { held, last, lastPageAddedAny };\n}\n\n/** The item the next page goes after: the last held, or the last seen when nothing is held or the last page brought nothing new. */\nfunction nextAfter<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const { held, last, lastPageAddedAny } = merge(pages, items, itemKey, hidden);\n if (held.length === 0 || (pages.length > 1 && !lastPageAddedAny)) return last;\n return held[held.length - 1];\n}\n","import * as React from \"react\";\nimport { hashKey, useQuery, useQueryClient, type QueryKey, type UseQueryOptions } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport type { DescribeError } from \"../lib/errors\";\nimport { toLoad } from \"./index\";\n\n// The read behind `JobStatus` (strata-react issue #45): a job's status, polled while it runs and\n// not otherwise, and the data it changed read again once, when it ends. Tubes wrote this as\n// `useLoad({ refetchInterval })` plus an effect watching `running` go from true to false; every\n// app with a job would write the same two pieces and get the second one subtly wrong (invalidating\n// on the first read of a job that had already finished, or on every poll). Here:\n//\n// - `isRunning(data)` says whether the job is going; the query polls `every` ms (default 2000)\n// only then, so an idle screen makes one request, not one every two seconds.\n// - `invalidates` names the queries the job changes; they are invalidated once, on the poll that\n// first sees the job stopped after one that saw it running, for the same query: a first read\n// of a finished job invalidates nothing, and neither does switching to another job's key (the\n// new query has no status yet, which is not the old job ending). The keys invalidated are the\n// ones given while that job was seen running.\n// - `poll()` reads the status now: the commit of the button that starts the job calls it, so\n// polling begins without waiting for a stale time.\n// - The result is a `Load<T>` (so a failed poll keeps the last status on screen with `stale`, as\n// any read does), plus `running`.\n\n/** Options for `useJob`: a query's, plus how to tell the job is running, how often to poll, and what it changes. */\nexport type JobOptions<T, K extends QueryKey = QueryKey> = UseQueryOptions<T, Error, T, K> & {\n /** Whether the status says the job is still going. */\n isRunning: (data: T) => boolean;\n /** Milliseconds between polls while it runs. Default 2000. */\n every?: number;\n /** Query keys the job changes, invalidated once when it ends. */\n invalidates?: QueryKey[];\n describeError?: DescribeError;\n};\n\n/** What `useJob` returns: the status as a `Load<T>`, whether the job is running, and `poll` to read it now. */\nexport type Job<T> = Load<T> & {\n /** The latest status says the job is going. */\n running: boolean;\n /** Read the status now, as after starting the job. */\n poll: () => void;\n};\n\n/** A long-running job's status: polled every `every` ms while `isRunning`, with the `invalidates` queries read again once when it ends. */\nexport function useJob<T, K extends QueryKey = QueryKey>({\n isRunning,\n every = 2000,\n invalidates = [],\n describeError,\n ...options\n}: JobOptions<T, K>): Job<T> {\n const client = useQueryClient();\n const query = useQuery({\n ...options,\n refetchInterval: (q) => (q.state.data !== undefined && isRunning(q.state.data) ? every : false),\n });\n const running = query.data !== undefined && isRunning(query.data);\n\n // What was last seen, for one query: whether its job ran, and what it said it would change.\n // Only a status that has arrived counts; no data yet (a new key loading) is not \"stopped\".\n const queryHash = hashKey(options.queryKey);\n const seen = query.data === undefined ? undefined : running;\n const was = React.useRef<{ query: string; running: boolean; invalidates: QueryKey[] } | undefined>(undefined);\n React.useEffect(() => {\n if (seen === undefined) return;\n const before = was.current;\n if (before && before.query === queryHash && before.running && !seen) {\n for (const queryKey of before.invalidates) void client.invalidateQueries({ queryKey });\n }\n was.current = { query: queryHash, running: seen, invalidates };\n });\n\n const { refetch } = query;\n const poll = React.useCallback(() => void refetch(), [refetch]);\n return { ...toLoad(query, describeError), running, poll };\n}\n","import * as React from \"react\";\nimport { Dialog as AriaDialog, Modal, ModalOverlay } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Full screen for a picture, a pair to compare or a player: the thing being judged gets the whole\n// screen, with its controls still around it. The browser's Fullscreen API is the first choice,\n// because it hides the browser's own chrome too; the iPhone's Safari has no such API for anything\n// but video, so there the same content opens in a React Aria modal that fills the window. Either\n// way the caller holds `active` (so a key and a button can both toggle it), and zoom, mode and the\n// question being answered live in the caller's state, so they survive the change. In the modal the\n// content is re-mounted (an image is drawn again from the browser's cache); natively it is not.\n//\n// React Aria checked: `Modal`/`ModalOverlay` give the fallback its focus containment, inert page\n// behind it and Escape; they do not offer the Fullscreen API, which is why the native path is\n// ours (an effect on `requestFullscreen` and the `fullscreenchange` event, the browser's own way\n// to say the person pressed Escape). If the browser refuses (it needs a recent click or key) the\n// fallback is used, so asking for full screen never silently does nothing.\n\n/** Props for `FullscreenFrame`. */\nexport type FullscreenFrameProps = {\n /** Names the full-screen view for screen readers: \"Compare renderings\". Required. */\n label: string;\n /** Whether the frame is full screen. The caller owns it so a button and a key can share it. */\n active: boolean;\n /** Called with `false` when the person leaves with Escape or the browser's own control. */\n onActiveChange: (active: boolean) => void;\n children: React.ReactNode;\n className?: string;\n};\n\n/** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */\nexport function canFullscreen(): boolean {\n return typeof document !== \"undefined\" && document.fullscreenEnabled === true && typeof Element.prototype.requestFullscreen === \"function\";\n}\n\n/** Shows its children full screen while `active`: the browser's Fullscreen API where there is one, a window-filling modal where there is not. */\nexport function FullscreenFrame({ label, active, onActiveChange, children, className }: FullscreenFrameProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const [native, setNative] = React.useState(false);\n const [refused, setRefused] = React.useState(false);\n const change = React.useRef(onActiveChange);\n change.current = onActiveChange;\n\n React.useEffect(() => {\n const el = ref.current;\n if (!active) {\n setNative(false);\n setRefused(false);\n if (document.fullscreenElement && document.fullscreenElement === el) void document.exitFullscreen();\n return;\n }\n if (!el || !canFullscreen()) return;\n let cancelled = false;\n el.requestFullscreen().then(\n () => !cancelled && setNative(true),\n () => !cancelled && setRefused(true), // refused (no recent click or key, say): the modal below opens instead\n );\n const onChange = () => {\n if (document.fullscreenElement !== el && !cancelled) change.current(false);\n };\n document.addEventListener(\"fullscreenchange\", onChange);\n return () => {\n cancelled = true;\n document.removeEventListener(\"fullscreenchange\", onChange);\n };\n }, [active]);\n\n // The modal is the answer where the browser cannot, or has refused. While a request is in flight the content stays in place.\n const modal = active && !native && (!canFullscreen() || refused);\n const inner = (\n <div ref={ref} className={cn(active && \"flex h-full min-h-0 flex-col bg-background p-4\", className)}>\n {children}\n </div>\n );\n if (!modal) return inner;\n return (\n <ModalOverlay isOpen onOpenChange={(o) => !o && onActiveChange(false)} isDismissable className=\"layer-overlay fixed inset-0 scrim\">\n <Modal className={cn(\"h-full w-full outline-none\", overlaySurface, \"rounded-none\")}>\n <AriaDialog aria-label={label} className=\"h-full outline-none\">\n {inner}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n );\n}\n","// The arithmetic of a shared zoom and pan, kept apart from the DOM so it is unit tested without a\n// layout engine (jsdom has none). Used by `ViewportFrame` and so by every comparison view.\n//\n// Scale is relative to \"fit\" (1 = the whole picture inside its frame). The offset is in pixels from\n// the frame's centre, and the picture's transform origin is that centre, so zooming about a point\n// is one line of algebra and a fit picture is always centred.\n\n/** Zoom and pan of a picture inside its frame. `scale` 1 is the picture fitted; `x` and `y` are pixels from the centre. */\nexport type Viewport = { scale: number; x: number; y: number };\n\n/** The picture fitted in its frame, not panned. */\nexport const FIT: Viewport = { scale: 1, x: 0, y: 0 };\n\n/** The least zoom: the whole picture fitted. */\nexport const MIN_SCALE = 1;\n/** The most zoom, 32 times the fit. */\nexport const MAX_SCALE = 32;\n\n/** Keeps the picture from being dragged out of its frame: at most half the extra width or height past each edge. */\nexport function clampViewport(v: Viewport, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.scale));\n if (scale === MIN_SCALE) return FIT;\n const mx = ((scale - 1) * frame.width) / 2;\n const my = ((scale - 1) * frame.height) / 2;\n return { scale, x: Math.min(mx, Math.max(-mx, v.x)), y: Math.min(my, Math.max(-my, v.y)) };\n}\n\n/** A new scale with the point under `at` (pixels from the frame's centre) staying under it. */\nexport function zoomAt(v: Viewport, nextScale: number, at: { x: number; y: number }, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, nextScale));\n const k = scale / v.scale;\n return clampViewport({ scale, x: at.x - k * (at.x - v.x), y: at.y - k * (at.y - v.y) }, frame);\n}\n\n/** The scale at which the picture's own pixels are drawn one to one: its natural width over the width it is fitted at. */\nexport function actualPixelsScale(naturalWidth: number, fittedWidth: number): number {\n if (!naturalWidth || !fittedWidth) return 1;\n return Math.min(MAX_SCALE, Math.max(MIN_SCALE, naturalWidth / fittedWidth));\n}\n\n/** The CSS transform for a viewport. */\nexport function viewportTransform(v: Viewport): string {\n return `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;\n}\n\n/** A box in a picture, as shares (0 to 1) of its width and height from the top left: `[x, y, width, height]`. */\nexport type ShareBox = readonly [number, number, number, number];\n\n/** A named box in the source's coordinates: `of` is the reference size in pixels, and without it the box is already shares. */\nexport type Region = { id: string; label: string; box: readonly [number, number, number, number]; of?: readonly [number, number] };\n\n/** A region as shares of the frame, so it lands on the same part of every candidate whatever its pixel size. */\nexport function regionShares(region: Region): ShareBox {\n const [x, y, w, h] = region.box;\n if (!region.of) return [x, y, w, h];\n const [ow, oh] = region.of;\n return [x / ow, y / oh, w / ow, h / oh];\n}\n\n/** The viewport that fills the frame with a box (as much of it as fits, centred): the scale that fits the box, the offset that puts its centre at the frame's centre. */\nexport function boxViewport(box: ShareBox, frame: { width: number; height: number }): Viewport {\n const [x, y, w, h] = box;\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, Math.min(1 / Math.max(w, 1e-6), 1 / Math.max(h, 1e-6))));\n return clampViewport({ scale, x: -scale * (x + w / 2 - 0.5) * frame.width, y: -scale * (y + h / 2 - 0.5) * frame.height }, frame);\n}\n\n/** A rectangle drawn on the frame (pixels from its top left) as shares of the picture under the viewport now. */\nexport function frameBoxToShares(rect: { x0: number; y0: number; x1: number; y1: number }, v: Viewport, frame: { width: number; height: number }): ShareBox {\n const toShare = (p: number, offset: number, size: number) => (size ? (p - size / 2 - offset) / v.scale / size + 0.5 : 0);\n const clamp = (n: number) => Math.min(1, Math.max(0, n));\n const xa = clamp(toShare(Math.min(rect.x0, rect.x1), v.x, frame.width));\n const xb = clamp(toShare(Math.max(rect.x0, rect.x1), v.x, frame.width));\n const ya = clamp(toShare(Math.min(rect.y0, rect.y1), v.y, frame.height));\n const yb = clamp(toShare(Math.max(rect.y0, rect.y1), v.y, frame.height));\n return [xa, ya, xb - xa, yb - ya];\n}\n","import * as React from \"react\";\nimport { ImageOff, Maximize, Minimize, Scan, ZoomIn, ZoomOut } from \"lucide-react\";\nimport { FIT, actualPixelsScale, zoomAt, type Viewport } from \"../lib/viewport\";\nimport { Button, IconButton } from \"./button\";\nimport { Skeleton } from \"./data-view\";\nimport type { Shortcut } from \"./hotkeys\";\nimport type { Candidate } from \"./compare\";\n\n// The pieces `Compare` and `CompareGrid` share, not exported from the package: a picture in its\n// loading, ready and failed states, the caption under it, and the zoom controls and keys, so the\n// two views behave the same way and cannot drift apart.\n\n// 100svh less the toolbar (about 3rem), captions (2rem), a vote bar (4rem), the legend (4rem) and gaps.\nexport const VIEWPORT_HEIGHT = \"max(16rem, calc(100svh - 14rem))\";\n\n/** A word for a picture's name on the page: its label, with its note unless blind. */\nexport function Caption({ c, blind }: { c: Candidate<unknown>; blind: boolean }) {\n return (\n <div className=\"flex items-baseline gap-2\">\n <span className=\"type-label\">{c.label}</span>\n {!blind && c.note && <span className=\"type-caption text-muted-foreground\">{c.note}</span>}\n </div>\n );\n}\n\n/** One picture inside a frame: a skeleton while it loads, the product's words if it fails. */\nexport function Picture({ c, blind, missing, onNatural, imgRef, pixelated }: { c: Candidate; blind: boolean; missing: string; onNatural?: (w: number, h: number) => void; imgRef?: React.Ref<HTMLImageElement>; pixelated?: boolean }) {\n const [state, setState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\"loading\");\n React.useEffect(() => setState(\"loading\"), [c.media.src]);\n const alt = blind ? c.label : c.media.alt;\n if (state === \"failed\")\n return (\n <div role=\"img\" aria-label={`${alt}: ${missing}`} className=\"absolute inset-0 grid place-content-center justify-items-center gap-2 text-muted-foreground\">\n <ImageOff aria-hidden className=\"size-6\" />\n <span className=\"type-body-sm\">{missing}</span>\n </div>\n );\n return (\n <>\n {state === \"loading\" && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none\" />}\n <img\n ref={imgRef}\n src={c.media.src}\n alt={alt}\n draggable={false}\n style={pixelated ? { imageRendering: \"pixelated\" } : undefined}\n onLoad={(e) => {\n setState(\"ready\");\n onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);\n }}\n onError={() => setState(\"failed\")}\n className=\"absolute inset-0 size-full object-contain\"\n />\n </>\n );\n}\n\n\ntype ZoomProps = {\n viewport: Viewport;\n setViewport: (next: Viewport) => void;\n /** The frame whose size zoom is measured against. */\n frame: React.RefObject<HTMLElement | null>;\n /** The picture's natural size, if known, for 1:1. */\n natural: readonly [number, number] | null;\n};\n\nconst frameSize = (frame: React.RefObject<HTMLElement | null>) => {\n const r = frame.current?.getBoundingClientRect();\n return { width: r?.width ?? 0, height: r?.height ?? 0 };\n};\n\n/** Zoom steps about the frame's centre, and 1:1. */\nexport function useZoom({ viewport, setViewport, frame, natural }: ZoomProps) {\n const by = (k: number) => setViewport(zoomAt(viewport, viewport.scale * k, { x: 0, y: 0 }, frameSize(frame)));\n const actual = () => {\n const f = frameSize(frame);\n // The width the picture is drawn at when fitted: the frame's, unless the picture is taller than it is wide for the frame.\n const fitted = natural ? Math.min(f.width, f.height * (natural[0] / natural[1])) : f.width;\n setViewport(zoomAt(viewport, actualPixelsScale(natural?.[0] ?? 0, fitted), { x: 0, y: 0 }, f));\n };\n return { by, actual, fit: () => setViewport(FIT) };\n}\n\n/** The shortcuts for zoom and full screen, to join a screen's own list. */\nexport function zoomShortcuts(zoom: ReturnType<typeof useZoom>, full: boolean, setFull: (f: boolean) => void): Shortcut[] {\n return [\n { keys: [\"+\", \"=\"], label: \"Zoom in\", run: () => zoom.by(1.5), repeat: true },\n { keys: [\"-\"], label: \"Zoom out\", run: () => zoom.by(1 / 1.5), repeat: true },\n { keys: [\"0\"], label: \"Fit\", run: zoom.fit },\n { keys: [\"f\"], label: full ? \"Leave full screen\" : \"Full screen\", run: () => setFull(!full) },\n ];\n}\n\n/** Zoom out, in, fit, 1:1 and the zoom now, for inside a `Toolbar`. */\nexport function ZoomControls({ viewport, zoom, natural }: { viewport: Viewport; zoom: ReturnType<typeof useZoom>; natural: readonly [number, number] | null }) {\n return (\n <>\n <IconButton icon={ZoomOut} label=\"Zoom out\" onPress={() => zoom.by(1 / 1.5)} disabled={viewport.scale <= 1} />\n <IconButton icon={ZoomIn} label=\"Zoom in\" onPress={() => zoom.by(1.5)} />\n <IconButton icon={Scan} label=\"Fit\" onPress={zoom.fit} disabled={viewport.scale === 1} />\n <Button size=\"sm\" variant=\"ghost\" onPress={zoom.actual} disabled={!natural}>1:1</Button>\n <span aria-live=\"off\" className=\"type-caption tabular-nums text-muted-foreground\">{viewport.scale === 1 ? \"Fit\" : `${viewport.scale.toFixed(1)}×`}</span>\n </>\n );\n}\n\n/** The full-screen button, for inside a `Toolbar`. */\nexport function FullscreenButton({ full, setFull }: { full: boolean; setFull: (f: boolean) => void }) {\n return <IconButton icon={full ? Minimize : Maximize} label={full ? \"Leave full screen\" : \"Full screen\"} onPress={() => setFull(!full)} />;\n}\n","// Which pixels differ between two renderings of one picture, for the difference view of `Compare`.\n// pixelmatch does the comparing (it is already a dependency: the visual runner uses it); this file\n// is the part around it: getting both pictures to the same size, reading pixels from a picture, and\n// telling the person how much of the picture differs. The arithmetic takes plain RGBA buffers, so it\n// is unit tested without a canvas; reading pixels needs a browser and is covered by the Storybook\n// shots, which run in Chromium.\n//\n// Why a tolerance rather than \"any difference\": two JPEGs of one edit differ in almost every\n// pixel by a level or two of compression noise, and a person comparing them cares about what they\n// can see. pixelmatch's threshold is a colour distance (OKLab, 0 to 1, 1 is black against white);\n// the default 0.1 is its own and the one `strata-visual` uses on screenshots. It also ignores\n// anti-aliased edge pixels by default, which are the same edge drawn slightly differently, not a\n// change in the picture.\n//\n// Pictures larger than `MAX_SIDE` on their long side are compared at that size: a 24-megapixel\n// photo would take seconds on the page's thread, and a difference that vanishes at 2048 pixels is\n// not one the person sees in a comparison view. The counts are of the pixels compared, so the share\n// printed is the share of the picture either way.\nimport pixelmatch from \"pixelmatch\";\n\n/** Decoded pixels: RGBA, 4 bytes each, row by row. */\nexport type Pixels = { data: Uint8ClampedArray; width: number; height: number };\n\n/** The result of comparing two pictures. */\nexport type Difference = {\n /** RGBA, `width` × `height`: opaque where a pixel differs, transparent elsewhere. */\n marks: Uint8ClampedArray;\n width: number;\n height: number;\n /** Pixels judged different. */\n differing: number;\n /** Pixels compared. */\n total: number;\n};\n\n/** The longest side, in pixels, a picture is compared at. */\nexport const MAX_SIDE = 2048;\n/** pixelmatch's own default colour distance below which two pixels are the same. */\nexport const DEFAULT_TOLERANCE = 0.1;\n\n/** The picture drawn at another size, each new pixel taken from the nearest old one. Used to bring the second picture to the first's size. */\nexport function resample(p: Pixels, width: number, height: number): Pixels {\n if (p.width === width && p.height === height) return p;\n const data = new Uint8ClampedArray(width * height * 4);\n for (let y = 0; y < height; y++) {\n const sy = Math.min(p.height - 1, Math.floor(((y + 0.5) * p.height) / height));\n for (let x = 0; x < width; x++) {\n const sx = Math.min(p.width - 1, Math.floor(((x + 0.5) * p.width) / width));\n const from = (sy * p.width + sx) * 4;\n const to = (y * width + x) * 4;\n data[to] = p.data[from];\n data[to + 1] = p.data[from + 1];\n data[to + 2] = p.data[from + 2];\n data[to + 3] = p.data[from + 3];\n }\n }\n return { data, width, height };\n}\n\n/**\n * Which pixels differ between two pictures. `b` is resampled to `a`'s size first when they differ,\n * so a re-encoded or resized rendering still lines up. `tolerance` is pixelmatch's `threshold`, 0 to 1.\n */\nexport function differences(a: Pixels, b: Pixels, tolerance: number = DEFAULT_TOLERANCE): Difference {\n const other = resample(b, a.width, a.height);\n const marks = new Uint8ClampedArray(a.width * a.height * 4);\n const differing = pixelmatch(a.data, other.data, marks, a.width, a.height, {\n threshold: tolerance,\n diffMask: true,\n alpha: 0,\n });\n return { marks, width: a.width, height: a.height, differing, total: a.width * a.height };\n}\n\n/** Reads a picture's pixels by drawing it on a canvas, scaled down so its long side is at most `maxSide`. Rejects when the picture cannot be loaded or the browser will not let a page read it (a picture from another site without CORS headers). */\nexport async function readPixels(src: string, maxSide: number = MAX_SIDE): Promise<Pixels> {\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n img.src = src;\n await img.decode();\n const scale = Math.min(1, maxSide / Math.max(img.naturalWidth, img.naturalHeight));\n const width = Math.max(1, Math.round(img.naturalWidth * scale));\n const height = Math.max(1, Math.round(img.naturalHeight * scale));\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (!ctx) throw new Error(\"This browser cannot read a picture's pixels.\");\n ctx.drawImage(img, 0, 0, width, height);\n const { data } = ctx.getImageData(0, 0, width, height);\n return { data, width, height };\n}\n","import * as React from \"react\";\nimport { differences, readPixels, type Difference, type Pixels } from \"../lib/image-diff\";\n\n// The pixel half of `Compare`'s difference view: loads both pictures' pixels once per pair, and\n// recomputes which differ when the tolerance moves. The tolerance is deferred (`useDeferredValue`),\n// so dragging its slider stays smooth while a 2048-pixel comparison runs behind it; the marks lag\n// by a frame or two and the readout beside the slider says what it is showing. Pixels are not\n// asked for until the view is open (`enabled`), since most comparisons never use it.\n\n/** How pictures become pixels. The default draws them on a canvas; supply another where that does not fit (an authenticated request, a picture the browser will not let a page read). */\nexport type ReadPixels = (src: string) => Promise<Pixels>;\n\n/** The state of a difference: reading the pictures, unable to, or the result. */\nexport type DifferenceState = { status: \"loading\" } | { status: \"failed\" } | { status: \"ready\"; difference: Difference };\n\n/** The pixels that differ between two pictures at a tolerance (0 to 1), read only while `enabled`. */\nexport function useDifference(a: string, b: string, tolerance: number, enabled: boolean, read: ReadPixels = readPixels): DifferenceState {\n const [loaded, setLoaded] = React.useState<{ key: string; a: Pixels; b: Pixels } | \"failed\" | null>(null);\n const key = `${a}|${b}`;\n const reader = React.useRef(read);\n reader.current = read;\n React.useEffect(() => {\n if (!enabled) return;\n let cancelled = false;\n setLoaded(null);\n Promise.all([reader.current(a), reader.current(b)]).then(\n ([pa, pb]) => !cancelled && setLoaded({ key, a: pa, b: pb }),\n () => !cancelled && setLoaded(\"failed\"),\n );\n return () => {\n cancelled = true;\n };\n }, [a, b, key, enabled]);\n const deferred = React.useDeferredValue(tolerance);\n const difference = React.useMemo(() => (loaded && loaded !== \"failed\" && loaded.key === key ? differences(loaded.a, loaded.b, deferred) : null), [loaded, key, deferred]);\n if (loaded === \"failed\") return { status: \"failed\" };\n return difference ? { status: \"ready\", difference } : { status: \"loading\" };\n}\n\n/** The marks of a difference drawn over the picture: a canvas that fits its frame the way the picture does (`object-contain`). */\nexport function DifferenceMarks({ difference }: { difference: Difference }) {\n const ref = React.useRef<HTMLCanvasElement>(null);\n React.useEffect(() => {\n const canvas = ref.current;\n const ctx = canvas?.getContext(\"2d\");\n if (!canvas || !ctx) return;\n canvas.width = difference.width;\n canvas.height = difference.height;\n // createImageData, not `new ImageData`: the same in a browser, and it works where the page has a canvas but no ImageData global (jsdom with @napi-rs/canvas installed).\n const image = ctx.createImageData(difference.width, difference.height);\n image.data.set(difference.marks);\n ctx.putImageData(image, 0, 0);\n }, [difference]);\n return <canvas ref={ref} aria-hidden className=\"absolute inset-0 size-full object-contain\" />;\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { FIT, clampViewport, viewportTransform, zoomAt, type ShareBox, type Viewport } from \"../lib/viewport\";\n\n// One picture's frame, with zoom and pan that other frames can share (strata-react issue: shared\n// comparison and voting components). Judging two renderings of a photo is mostly looking at the same\n// detail in both, so the viewport is state the caller holds and gives to every frame: zoom one, the\n// other follows. `ViewportFrame` is only the frame; `Compare` holds the state and draws the controls.\n//\n// React Aria checked: Aria Components has no zoom or pan part, and its `useMove` (in the\n// `react-aria` package, which is not a dependency here) only reports deltas that a pointer capture\n// gives us as well, so the gestures are pointer events on the frame. Keyboard, which is not\n// optional: the frame is focusable, `+` `-` `0` zoom and the arrow keys pan once zoomed in.\n// Plain wheel scrolls the page (a frame in the middle of a page must not trap it); Ctrl or Cmd with\n// the wheel zooms, which is also what a trackpad pinch sends. Touch pinch is not handled yet.\n\n/** The caller's zoom and pan, and how to change them. */\nexport type ViewportState = { viewport: Viewport; setViewport: (next: Viewport) => void };\n\n/** Zoom and pan held in React state, to give to every `ViewportFrame` that should move together. */\nexport function useViewport(initial: Viewport = FIT): ViewportState {\n const [viewport, setViewport] = React.useState(initial);\n return { viewport, setViewport };\n}\n\nconst PAN_STEP = 48;\n\n/** Props for `ViewportFrame`. */\nexport type ViewportFrameProps = ViewportState & {\n /** Names the frame for screen readers: \"Picture A\". Required. */\n label: string;\n /** Width over height of the frame before anything inside it has loaded. */\n aspect: number;\n children: React.ReactNode;\n /** A second picture layer above `children`, zoomed and panned with them but cut at `shown` percent of the *frame's* width from the left, so a swipe divider in `overlay` stays where the cut is at any zoom. */\n cover?: { content: React.ReactNode; shown: number };\n /** Drawn over the frame, not zoomed with it: a divider to drag, a corner label. Its pointer, key and double-click events do not reach the frame, so using it never pans the picture. */\n overlay?: React.ReactNode;\n /** The tallest the frame may be, as a CSS length (`\"60svh\"`). The width follows, narrower than the space it has and centred, so the picture keeps its shape. Default: no limit, the frame is as tall as its width and aspect make it. */\n maxHeight?: string;\n /** Shift-drag draws a rectangle on the frame and calls this with it when let go (pixels from the frame's top left). Without it Shift-drag does nothing special. */\n onBox?: (rect: { x0: number; y0: number; x1: number; y1: number }) => void;\n /** A box to outline on the whole picture (a region being pointed at), as shares of it. Drawn only while the picture is fitted. */\n outline?: ShareBox | null;\n className?: string;\n};\n\n/** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */\nexport const ViewportFrame = React.forwardRef<HTMLDivElement, ViewportFrameProps>(function ViewportFrame(\n { label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, onBox, outline, className },\n forwardedRef,\n) {\n const ref = React.useRef<HTMLDivElement>(null);\n React.useImperativeHandle(forwardedRef, () => ref.current!);\n const latest = React.useRef(viewport);\n latest.current = viewport;\n const drag = React.useRef<{ x: number; y: number } | null>(null);\n // A rectangle being drawn with Shift held (frame pixels), which asks for a region instead of panning.\n const [band, setBand] = React.useState<{ x0: number; y0: number; x1: number; y1: number } | null>(null);\n const bandRef = React.useRef(band);\n bandRef.current = band;\n const inFrame = (clientX: number, clientY: number) => {\n const r = ref.current!.getBoundingClientRect();\n return { x: clientX - r.left, y: clientY - r.top };\n };\n\n const size = () => {\n const r = ref.current!.getBoundingClientRect();\n return { width: r.width, height: r.height };\n };\n const fromCentre = (clientX: number, clientY: number) => {\n const r = ref.current!.getBoundingClientRect();\n return { x: clientX - r.left - r.width / 2, y: clientY - r.top - r.height / 2 };\n };\n\n // React attaches wheel listeners as passive, so preventing the browser's page zoom needs a native one.\n const setViewportRef = React.useRef(setViewport);\n setViewportRef.current = setViewport;\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n const r = el.getBoundingClientRect();\n const at = { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 };\n setViewportRef.current(zoomAt(latest.current, latest.current.scale * Math.exp(-e.deltaY / 200), at, { width: r.width, height: r.height }));\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, []);\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n const v = latest.current;\n const centre = { x: 0, y: 0 };\n if (e.key === \"+\" || e.key === \"=\") setViewport(zoomAt(v, v.scale * 1.5, centre, size()));\n else if (e.key === \"-\") setViewport(zoomAt(v, v.scale / 1.5, centre, size()));\n else if (e.key === \"0\") setViewport(FIT);\n else if (v.scale > 1 && e.key.startsWith(\"Arrow\")) {\n // Arrow right looks right: the picture moves left.\n const dx = e.key === \"ArrowRight\" ? -PAN_STEP : e.key === \"ArrowLeft\" ? PAN_STEP : 0;\n const dy = e.key === \"ArrowDown\" ? -PAN_STEP : e.key === \"ArrowUp\" ? PAN_STEP : 0;\n setViewport(clampViewport({ ...v, x: v.x + dx, y: v.y + dy }, size()));\n } else return;\n e.preventDefault();\n e.stopPropagation();\n };\n\n const zoomed = viewport.scale > 1;\n return (\n <div\n ref={ref}\n role=\"group\"\n aria-label={label}\n aria-roledescription=\"zoomable picture\"\n tabIndex={0}\n onKeyDown={onKeyDown}\n onPointerDown={(e) => {\n if (e.shiftKey && onBox && e.button === 0) {\n const p = inFrame(e.clientX, e.clientY);\n setBand({ x0: p.x, y0: p.y, x1: p.x, y1: p.y });\n e.currentTarget.setPointerCapture?.(e.pointerId);\n return;\n }\n if (!zoomed || e.button !== 0) return;\n drag.current = { x: e.clientX, y: e.clientY };\n e.currentTarget.setPointerCapture?.(e.pointerId);\n }}\n onPointerMove={(e) => {\n if (bandRef.current) {\n const p = inFrame(e.clientX, e.clientY);\n setBand({ ...bandRef.current, x1: p.x, y1: p.y });\n return;\n }\n if (!drag.current) return;\n const dx = e.clientX - drag.current.x;\n const dy = e.clientY - drag.current.y;\n drag.current = { x: e.clientX, y: e.clientY };\n setViewport(clampViewport({ ...latest.current, x: latest.current.x + dx, y: latest.current.y + dy }, size()));\n }}\n onPointerUp={() => {\n drag.current = null;\n const b = bandRef.current;\n if (b) {\n setBand(null);\n if (Math.abs(b.x1 - b.x0) > 6 && Math.abs(b.y1 - b.y0) > 6) onBox?.(b);\n }\n }}\n onPointerCancel={() => {\n drag.current = null;\n setBand(null);\n }}\n onDoubleClick={(e) => {\n const v = latest.current;\n setViewport(v.scale > 1 ? FIT : zoomAt(v, 2, fromCentre(e.clientX, e.clientY), size()));\n }}\n style={{ aspectRatio: String(aspect), ...(maxHeight ? { maxWidth: `calc(${maxHeight} * ${aspect})`, marginInline: \"auto\" } : {}), touchAction: zoomed ? \"none\" : \"pan-y\" }}\n className={cn(\n \"relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none\",\n zoomed ? \"cursor-grab active:cursor-grabbing\" : \"cursor-zoom-in\",\n \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\",\n className,\n )}\n >\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {children}\n </div>\n {cover && (\n <div className=\"absolute inset-0\" style={{ clipPath: `inset(0 ${100 - cover.shown}% 0 0)` }}>\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {cover.content}\n </div>\n </div>\n )}\n {outline && viewport.scale === 1 && (\n <div aria-hidden className=\"pointer-events-none absolute border-2 border-foreground ring-1 ring-background\" style={{ left: `${outline[0] * 100}%`, top: `${outline[1] * 100}%`, width: `${outline[2] * 100}%`, height: `${outline[3] * 100}%` }} />\n )}\n {band && <div aria-hidden className=\"pointer-events-none absolute border-2 border-dashed border-foreground\" style={{ left: Math.min(band.x0, band.x1), top: Math.min(band.y0, band.y1), width: Math.abs(band.x1 - band.x0), height: Math.abs(band.y1 - band.y0) }} />}\n {overlay != null && (\n <div\n className=\"pointer-events-none absolute inset-0\"\n onPointerDown={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n onDoubleClick={(e) => e.stopPropagation()}\n >\n {overlay}\n </div>\n )}\n </div>\n );\n});\n","import * as React from \"react\";\nimport { boxViewport, frameBoxToShares, regionShares, type Region, type ShareBox, type Viewport } from \"../lib/viewport\";\nimport type { Shortcut } from \"./hotkeys\";\nimport { ToggleGroup } from \"./toggle\";\n\n// The region view of `Compare`, `CompareVideo` and `CompareGrid`: the same small part of every\n// candidate, enlarged to fill the frame, because at full size the difference between two outputs of\n// one source (a face, the stripes on a sofa, handwriting) is hard to see.\n//\n// A region is a box in the source's coordinates (`of` is the reference size; without it the box is\n// already shares of the frame). It is turned into SHARES of the frame, and every candidate is drawn\n// in the same box (`object-contain`, the first candidate's shape), so the same share is the same\n// part of each whatever its pixel size: \"mapped to its own pixel size\" is the box scaled by the\n// frame, not a sum per candidate. A candidate of another shape letterboxes inside the box, and its\n// region is then of the frame, not of its picture; say so in the region's label if it matters.\n//\n// A region is not a new kind of view. It is a viewport (zoom and pan) that fills the frame with the\n// box, so swipe, fade, blink, the shared clock and the locked zoom of every candidate work inside\n// it with no change, and `0` (Fit) is \"the whole frame\" with no extra code. What it adds: a chip\n// strip, keys `q w e r y u` for the first six (`t` is a pair vote's tie), nearest-neighbour drawing\n// while a region is shown, an outline of the box on the whole frame while its chip is pointed at,\n// and Shift-drag to make one more (\"Region 3\") that lasts until the item changes.\n//\n// The active region is state of its own, cleared by any zoom or pan that is not ours, so a chip is\n// never shown pressed for a view that has moved off it. Blind: region labels describe the content\n// (\"Face\"), never a candidate.\n//\n// Checked: React Aria has no zoom, crop or region part; the chip strip is its toggle button group\n// (`ToggleGroup`) and the drag is pointer events on the frame, as in `ViewportFrame`.\n\nconst REGION_KEYS = [\"q\", \"w\", \"e\", \"r\", \"y\", \"u\"] as const;\n\n/** What a view needs to show regions. */\nexport type RegionState = {\n /** The given regions, then the ones drawn by hand. */\n regions: readonly Region[];\n /** The chosen region's id, `null` for the whole frame or any other zoom. */\n active: string | null;\n /** Choose a region (fill the frame with it) or `null` for the whole frame. */\n choose: (id: string | null) => void;\n /** Wrap the view's own `setViewport`, so a zoom or pan by hand clears the chosen region. */\n setViewport: (next: Viewport) => void;\n /** A box drawn by hand, as a new region. */\n add: (rect: { x0: number; y0: number; x1: number; y1: number }) => void;\n /** The box to outline on the whole frame (the chip being pointed at). */\n peek: ShareBox | null;\n setPeek: (id: string | null) => void;\n shortcuts: Shortcut[];\n};\n\n/** Regions for one item: `reset` is a key that changes with the item, which drops the regions drawn by hand. */\nexport function useRegions({ regions = [], viewport, setViewport, frame, reset }: { regions?: readonly Region[]; viewport: Viewport; setViewport: (v: Viewport) => void; frame: React.RefObject<HTMLElement | null>; reset: string }): RegionState {\n const [drawn, setDrawn] = React.useState<{ key: string; list: Region[] }>({ key: reset, list: [] });\n const hand = drawn.key === reset ? drawn.list : [];\n const all = React.useMemo(() => [...regions, ...hand], [regions, hand]);\n const [active, setActive] = React.useState<string | null>(null);\n const [peekId, setPeek] = React.useState<string | null>(null);\n const size = () => {\n const r = frame.current?.getBoundingClientRect();\n return { width: r?.width ?? 0, height: r?.height ?? 0 };\n };\n const choose = (id: string | null) => {\n const region = all.find((r) => r.id === id);\n if (!region) {\n setActive(null);\n setViewport({ scale: 1, x: 0, y: 0 });\n return;\n }\n applied.current = size();\n setViewport(boxViewport(regionShares(region), applied.current));\n setActive(region.id);\n setPeek(null);\n };\n // The item changed: no region is chosen any more (its hand-drawn ones went with it).\n React.useEffect(() => setActive(null), [reset]);\n const add = (rect: { x0: number; y0: number; x1: number; y1: number }) => {\n const box = frameBoxToShares(rect, viewport, size());\n if (box[2] <= 0 || box[3] <= 0) return;\n const region: Region = { id: `region-${all.length + 1}`, label: `Region ${all.length + 1}`, box };\n setDrawn({ key: reset, list: [...hand, region] });\n applied.current = size();\n setViewport(boxViewport(box, applied.current));\n setActive(region.id);\n };\n // The viewport is pixels, so it is only right for the frame it was worked out for. A change of view (side by side to swipe, full screen, a window resize, a picture's size learned) changes the frame, and the chosen region is worked out again for it. `applied` is the size it was last right for.\n const applied = React.useRef({ width: 0, height: 0 });\n const [, bump] = React.useState(0);\n React.useLayoutEffect(() => {\n const now = size();\n if (now.width === applied.current.width && now.height === applied.current.height) return;\n applied.current = now;\n const region = all.find((r) => r.id === active);\n if (region && now.width > 0) setViewport(boxViewport(regionShares(region), now));\n });\n React.useLayoutEffect(() => {\n const el = frame.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(() => {\n const r = el.getBoundingClientRect();\n if (r.width !== applied.current.width || r.height !== applied.current.height) bump((n) => n + 1);\n });\n ro.observe(el);\n return () => ro.disconnect();\n });\n const peekRegion = all.find((r) => r.id === peekId);\n return {\n regions: all,\n active,\n choose,\n setViewport: (next) => {\n setActive(null);\n setViewport(next);\n },\n add,\n peek: peekRegion ? regionShares(peekRegion) : null,\n setPeek,\n shortcuts: all.slice(0, REGION_KEYS.length).map((r, i): Shortcut => ({ keys: [REGION_KEYS[i]], label: `Region: ${r.label}`, run: () => choose(r.id) })),\n };\n}\n\n/** The chip strip: the whole frame and each region, one chosen. Renders nothing when there are no regions. */\nexport function RegionChips({ state }: { state: RegionState }) {\n if (state.regions.length === 0) return null;\n const byLabel = (target: EventTarget) => {\n const text = (target as HTMLElement).closest?.('[role=\"radio\"]')?.textContent;\n return state.regions.find((r) => r.label === text)?.id ?? null;\n };\n return (\n <div onPointerOver={(e) => state.setPeek(byLabel(e.target))} onFocus={(e) => state.setPeek(byLabel(e.target))} onPointerLeave={() => state.setPeek(null)} onBlur={() => state.setPeek(null)}>\n <ToggleGroup\n label=\"Region\"\n options={[{ value: \"\", label: \"Whole frame\" }, ...state.regions.map((r) => ({ value: r.id, label: r.label }))]}\n value={state.active ?? \"\"}\n onChange={(v) => state.choose(v === \"\" ? null : v)}\n size=\"sm\"\n />\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Slider as AriaSlider, SliderThumb, SliderTrack } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { Skeleton } from \"./data-view\";\nimport { Caption, FullscreenButton, Picture, VIEWPORT_HEIGHT, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Slider } from \"./value-controls\";\nimport { DifferenceMarks, useDifference, type ReadPixels } from \"./difference\";\nimport { format } from \"../lib/format\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\nimport { RegionChips, useRegions } from \"./compare-regions\";\nimport type { Region } from \"../lib/viewport\";\n\n// Two renderings of the same thing, to be looked at closely and judged. It exists because four\n// apps draw this by hand (the stills arena, the models judge, the listory match queue, the\n// Bright Horizons review) and none of them can zoom both sides together, lay one over the other or\n// look at it full screen. The design and the survey are in the project's design.md; this file is the\n// first piece, for pictures. Text, audio, video and data kinds, a difference view and voting come\n// in later changes and join the same `Candidate` and `CompareMode` types.\n//\n// Four views, because each answers a different question: side by side (which do I prefer),\n// swipe (where exactly do they differ, along this edge), fade (the same, softly) and blink (flip\n// between them in place, the most sensitive way to see a small change). Zoom and pan are one state\n// for both sides, so the same detail is in view in both. Full screen keeps everything.\n//\n// Blind by type: `blind` is required with no default, because showing a judge which variant is which\n// is a validity bug, not a style choice. When it is true the picture's name is its `label` (the\n// caller passes \"A\" and \"B\"), the caller's `alt` and `note` are never put on the page, and the\n// real `id` is never rendered at all. Mind the URL: `src` reaches the DOM, so a blind caller serves\n// the pictures under neutral addresses (the arena's `img/{token}/left`).\n//\n// Failure is a state: a picture that does not load says so in `missing` (required, in the product's\n// words) in its own place, and the other side is still usable. One filled button rule: this\n// component draws none, a vote bar will be the view's filled control.\n\n/** A picture to compare. */\nexport type ImageMedia = {\n kind: \"image\";\n src: string;\n /** What it shows. Ignored when the comparison is `blind`: the label names it then. */\n alt: string;\n /** Its natural size in pixels, if known, so the frame has its shape and \"1:1\" is exact before the picture loads. */\n size?: readonly [number, number];\n};\n\n/** A clip to compare by listening (`CompareAudio`). Serve it under a neutral address when the comparison is blind. */\nexport type AudioMedia = {\n kind: \"audio\";\n src: string;\n};\n\n/** A text to compare by reading (`CompareText`). */\nexport type TextMedia = {\n kind: \"text\";\n text: string;\n};\n\n/** A video to compare (`CompareVideo`). Serve it under a neutral address when the comparison is blind: `src` reaches the page. */\nexport type VideoMedia = {\n kind: \"video\";\n src: string;\n /** A still shown before the first frame. */\n poster?: string;\n /** Its size in pixels, for the shape of the frame, \"1:1\" and drawing candidates of different sizes in one box. */\n width: number;\n height: number;\n /** Frames per second, if known: the unit of the sync tolerance and of the frame readout. Default 30. */\n fps?: number;\n};\n\n/** One side of a comparison. */\nexport type Candidate<M = ImageMedia> = {\n /** Who it is: a variant name, a model. Never put on the page when `blind`, and never needed by it. */\n id: string;\n /** What the person sees it called: \"Original\", or \"A\" when blind. */\n label: string;\n media: M;\n /** A line under the label (\"auto2, 14 s\"). Not shown when `blind`. */\n note?: string;\n};\n\n/** How two pictures are laid out. */\nexport type CompareMode = \"side\" | \"swipe\" | \"fade\" | \"blink\" | \"difference\";\n\nconst MODE_LABEL: Record<CompareMode, string> = { side: \"Side by side\", swipe: \"Swipe\", fade: \"Fade\", blink: \"Blink\", difference: \"Difference\" };\nconst ALL_MODES: readonly CompareMode[] = [\"side\", \"swipe\", \"fade\", \"blink\", \"difference\"];\n\n/** Props for `Compare`. */\nexport type CompareProps = {\n /** Names the comparison for screen readers: \"Photo 1 of 12, two versions\". Required. */\n label: string;\n a: Candidate;\n b: Candidate;\n /** Whether the person must not learn which variant is which. Required, no default. */\n blind: boolean;\n /** The words shown where a picture could not be loaded: \"Picture not found\". Required. */\n missing: string;\n mode: CompareMode;\n onModeChange: (mode: CompareMode) => void;\n /** Words for when the difference view cannot read the pictures' pixels (a picture from another site without CORS headers). Default says so plainly. */\n cannotCompare?: string;\n /** Which difference the difference view opens on: `brightness` (live, any picture) or `pixels` (the changed pixels marked, with a tolerance and the share that differ). Default `brightness`. */\n defaultDifference?: \"brightness\" | \"pixels\";\n /** How pictures become pixels for the difference view. Default draws them on a canvas. */\n readPixels?: ReadPixels;\n /** Which views are offered. Default all five. Must include `mode`. */\n modes?: readonly CompareMode[];\n /** How tall a frame may be, so the pair and the answer fit on one screen: a CSS length (`\"60svh\"`) or `\"viewport\"` (the window's height less room for the toolbar, captions, a vote bar and the key legend). The frame narrows to keep the picture's shape. Default: as tall as the width makes it. */\n maxHeight?: string;\n /** Named boxes in the source's coordinates to look at enlarged: a strip of chips, keys `q` `w` `e` `r` `y` `u`, nearest-neighbour drawing while one is shown, and Shift-drag to make another. They work in every view. The same share of each side is shown, whatever its pixel size. Label them by content (\"Face\"), never by candidate. */\n regions?: readonly Region[];\n /** Bind the view, zoom and full-screen keys on the window. Default true; turn off when a surrounding screen binds the same keys. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen (the answer keys of a `PairVote`), bound with Compare's own and drawn in the same legend, so there is one list and the two cannot clash unseen. Listed first. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the picture, above the legend, and kept in full screen: where a vote bar goes so the answer is never out of reach of the pictures. */\n footer?: React.ReactNode;\n className?: string;\n};\n\n/** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */\nexport function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, regions, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = \"Could not read these pictures to compare their pixels.\", readPixels, defaultDifference = \"brightness\", className }: CompareProps) {\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n // Learned from the picture once it loads, and only for the pair it was learned from: a new pair starts again.\n const pairKey = `${a.media.src}|${b.media.src}`;\n const [learned, setLearned] = React.useState<{ key: string; size: readonly [number, number] } | null>(null);\n const natural = a.media.size ?? (learned?.key === pairKey ? learned.size : null);\n const [divider, setDivider] = React.useState(50);\n const [blend, setBlend] = React.useState(50);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [style, setStyle] = React.useState<\"brightness\" | \"pixels\">(defaultDifference);\n const [amplify, setAmplify] = React.useState(4);\n const [tolerance, setTolerance] = React.useState(10); // percent; pixelmatch's threshold is this over 100\n const diff = useDifference(a.media.src, b.media.src, tolerance / 100, mode === \"difference\" && style === \"pixels\", readPixels);\n const frameRef = React.useRef<HTMLDivElement>(null);\n const imgRef = React.useRef<HTMLImageElement>(null);\n const aspect = natural ? natural[0] / natural[1] : 3 / 2;\n\n const rg = useRegions({ regions, viewport, setViewport, frame: frameRef, reset: pairKey });\n const zoom = useZoom({ viewport, setViewport: rg.setViewport, frame: frameRef, natural });\n const flip = () => setShowing((s) => (s === \"a\" ? \"b\" : \"a\"));\n\n const offered = modes.includes(mode) ? modes : [mode, ...modes];\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n ...offered.map((m, i): Shortcut => ({ keys: [String(i + 1)], label: MODE_LABEL[m], run: () => onModeChange(m) })),\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip, disabled: mode !== \"blink\" },\n ...rg.shortcuts,\n ...zoomShortcuts(zoom, full, setFull),\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const pane = (c: Candidate, ref?: React.Ref<HTMLImageElement>, onNatural?: (w: number, h: number) => void) => (\n <Picture c={c} blind={blind} missing={missing} imgRef={ref} onNatural={onNatural} pixelated={rg.active !== null} />\n );\n const learn = (w: number, h: number) => setLearned({ key: pairKey, size: [w, h] });\n const frameProps = { viewport, setViewport: rg.setViewport, onBox: rg.add, outline: rg.peek, aspect, maxHeight: maxHeight === \"viewport\" ? VIEWPORT_HEIGHT : maxHeight };\n\n let body: React.ReactNode;\n if (mode === \"side\") {\n body = (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {[a, b].map((c, i) => (\n <figure key={i} className=\"grid gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame {...frameProps} label={blind ? `Picture ${c.label}` : `${c.label}`} ref={i === 0 ? frameRef : undefined}>\n {pane(c, i === 0 ? imgRef : undefined, i === 0 ? learn : undefined)}\n </ViewportFrame>\n </figure>\n ))}\n </div>\n );\n } else if (mode === \"difference\") {\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n <Caption c={a} blind={blind} />\n <span className=\"type-caption text-muted-foreground\">against</span>\n <Caption c={b} blind={blind} />\n </div>\n <ViewportFrame {...frameProps} ref={frameRef} label={`Difference between ${a.label} and ${b.label}`}>\n {style === \"brightness\" ? (\n <div className=\"absolute inset-0 isolate\" style={{ filter: `brightness(${amplify})` }}>\n <div className=\"absolute inset-0 bg-background\">{pane(a, imgRef, learn)}</div>\n <div className=\"absolute inset-0 bg-background mix-blend-difference\">{pane(b)}</div>\n </div>\n ) : (\n <>\n <div className=\"absolute inset-0 opacity-35\">{pane(a, imgRef, learn)}</div>\n {diff.status === \"ready\" && <DifferenceMarks difference={diff.difference} />}\n {diff.status === \"loading\" && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none opacity-40\" />}\n {diff.status === \"failed\" && <p role=\"alert\" className=\"absolute inset-x-0 bottom-0 bg-background/90 p-2 type-body-sm text-danger\">{cannotCompare}</p>}\n </>\n )}\n </ViewportFrame>\n </figure>\n );\n } else {\n // One frame, both pictures in it. Swipe clips the top one at the divider; fade lays it over at an opacity; blink shows one.\n const top = mode === \"blink\" ? (showing === \"a\" ? a : b) : a;\n const bottom = b;\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n {mode === \"blink\" ? <Caption c={top} blind={blind} /> : <Caption c={a} blind={blind} />}\n {mode !== \"blink\" && <Caption c={b} blind={blind} />}\n </div>\n <ViewportFrame\n {...frameProps}\n ref={frameRef}\n cover={mode === \"swipe\" ? { content: pane(a, imgRef, learn), shown: divider } : undefined}\n label={mode === \"blink\" ? `Picture ${top.label}` : `${a.label} over ${b.label}`}\n overlay={\n mode === \"swipe\" && (\n <AriaSlider\n aria-label={`Divider between ${a.label} and ${b.label}`}\n value={divider}\n onChange={(v) => setDivider(v as number)}\n minValue={0}\n maxValue={100}\n step={1}\n className=\"absolute inset-0\"\n >\n <SliderTrack className=\"pointer-events-none h-full w-full\">\n <SliderThumb\n className=\"pointer-events-auto grid h-full w-8 cursor-ew-resize place-items-center focus-visible:outline-2 focus-visible:outline-ring\"\n style={{ top: \"50%\" }}\n >\n <span aria-hidden className=\"col-start-1 row-start-1 h-full w-1 border-x border-background bg-foreground\" />\n <span aria-hidden className=\"col-start-1 row-start-1 size-6 rounded-pill border-2 border-foreground bg-background\" />\n </SliderThumb>\n </SliderTrack>\n </AriaSlider>\n )\n }\n >\n {pane(bottom)}\n {mode !== \"swipe\" && (\n <div className=\"absolute inset-0\" style={mode === \"fade\" ? { opacity: 1 - blend / 100 } : undefined}>\n {pane(top, imgRef, learn)}\n </div>\n )}\n </ViewportFrame>\n </figure>\n );\n }\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Comparison view\" className=\"items-center gap-2\">\n <ToggleGroup label=\"View\" options={offered.map((m) => ({ value: m, label: MODE_LABEL[m] }))} value={mode} onChange={(v) => onModeChange(v as CompareMode)} size=\"sm\" />\n <ToolbarSeparator />\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n <RegionChips state={rg} />\n {mode === \"fade\" && (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">{a.label}</span>\n <Slider aria-label={`Blend from ${a.label} to ${b.label}`} value={blend} onChange={setBlend} min={0} max={100} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"type-caption text-muted-foreground\">{b.label}</span>\n </div>\n )}\n {mode === \"difference\" && (\n <div className=\"grid gap-2\">\n <ToggleGroup label=\"Difference style\" options={[{ value: \"brightness\", label: \"Brightness\" }, { value: \"pixels\", label: \"Changed pixels\" }]} value={style} onChange={(v) => setStyle(v as \"brightness\" | \"pixels\")} size=\"sm\" className=\"justify-self-start\" />\n {style === \"brightness\" ? (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">Amplify</span>\n <Slider aria-label=\"Amplify differences\" value={amplify} onChange={setAmplify} min={1} max={8} hideValue className=\"flex-1\" />\n <span className=\"w-8 type-caption tabular-nums text-muted-foreground\">{amplify}×</span>\n </div>\n ) : (\n <>\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">Tolerance</span>\n <Slider aria-label=\"Tolerance for a changed pixel\" value={tolerance} onChange={setTolerance} min={0} max={50} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"w-10 type-caption tabular-nums text-muted-foreground\">{tolerance}%</span>\n </div>\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {diff.status === \"ready\"\n ? diff.difference.differing === 0\n ? \"No pixels differ at this tolerance.\"\n : `${format.share(diff.difference.differing / diff.difference.total)} of pixels differ at this tolerance.`\n : diff.status === \"loading\"\n ? \"Comparing pixels…\"\n : \"\"}\n </p>\n </>\n )}\n </div>\n )}\n {mode === \"blink\" && (\n <div>\n <ToggleGroup label=\"Showing\" options={[{ value: \"a\", label: a.label }, { value: \"b\", label: b.label }]} value={showing} onChange={(v) => setShowing(v as \"a\" | \"b\")} size=\"sm\" />\n </div>\n )}\n {body}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","import * as React from \"react\";\nimport { Flag } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { Menu } from \"./commands\";\nimport { Compare, type Candidate, type CompareProps, type ImageMedia } from \"./compare\";\nimport { DataView, type Load } from \"./data-view\";\nimport type { Shortcut } from \"./hotkeys\";\nimport { cn } from \"../lib/utils\";\n\n// The answering half of a blind pairwise judgment (\"which is better: A, B, or about the same?\"),\n// wrapped around `Compare` because the two share one keyboard and one legend. It exists because\n// strata-models' judge and the stills arena each drew their own bar and their own keys beside\n// Compare's: two legends, answer keys nobody could guess (`[` `]` `t`) because the natural ones\n// were taken, and the pictures lost \"click to choose\" once a click panned.\n//\n// - Keys come from one list merged into Compare's (`extraShortcuts`), so there is one legend and\n// a clash is visible: `a` and `b` choose a side, `t` is about the same, `s` is can't tell. None\n// of them is a view, zoom or full-screen key. Arrow keys are left to panning and the swipe\n// divider on purpose: a person who zooms in and presses an arrow to pan must not cast a vote.\n// - Choosing is a button under the pictures, not a click on them: a click on a picture pans.\n// The bar is part of Compare's footer so it stays on screen in full screen.\n// - No button is filled: while either side can win, nothing is the default (ux-research\n// `patterns.md` §2, one filled button, and a filled \"A\" would lean on the judge).\n// - The last answer's Undo sits in the same footer, so it is inside full screen too: a judge who answers\n// there must be able to take it back without leaving.\n// - `pending` disables the buttons and the keys, and says so in words, because an answer\n// that is still being saved must not be answered twice.\n// - The pair is a `Load` so a pair that is on its way, an empty queue and a failed read each have\n// their own words (`skeleton`, `empty` required, the failure with Try again).\n// - Blind is Compare's: `blind` stays required here, and the buttons are named with the labels\n// only (\"Prefer A\"), never the id.\n// - `PairVote` draws the pair with `Compare`; `PairJudge` is the same answering around any `view`\n// (`CompareAudio`, `CompareText`), because the answers are the same whatever is judged.\n// - Statistics (ratings, confidence, which pair comes next) stay on the server; this draws the\n// question and reports the answer.\n// Checked: React Aria has no vote or pairwise-choice part; the bar is `Button`s and a `Menu`\n// (React Aria's) for the flag reasons.\n\n/** One answer to a pair: a side, \"about the same\", \"can't tell\", or a flag with its reason. */\nexport type PairAnswer = { answer: \"a\" | \"b\" | \"tie\" | \"skip\" } | { answer: \"flag\"; reason: string };\n\n/** A pair to judge: pictures by default, or any media a `view` draws (`CompareAudio`, `CompareText`). */\nexport type Pair<M = ImageMedia> = { label: string; a: Candidate<M>; b: Candidate<M> };\n\n/** What `PairVote` hands a `view`: the answer keys for the view's legend and the vote bar for its footer. Pass both to `CompareAudio`, `CompareText` or your own. */\nexport type PairVoteSlot = { extraShortcuts: Shortcut[]; footer: React.ReactNode };\n\n/** Words for the vote bar, all in the product's voice. */\nexport type PairVoteWords = {\n /** Default \"About the same\". */\n tie?: string;\n /** Default \"Can't tell\". */\n skip?: string;\n /** What choosing a side says: `(label) => \"Prefer \" + label`. Default \"Prefer …\". */\n prefer?: (label: string) => string;\n /** Said while an answer is being saved. Default \"Saving your answer…\". */\n pending?: string;\n /** The flag menu's button. Default \"Flag this pair\". */\n flag?: string;\n};\n\n/** What every pair judgment takes, whatever it draws. */\nexport type PairJudgeProps<M> = {\n /** The pair now being judged, as a read. */\n pair: Load<Pair<M> | null>;\n /** Mirrors the pictures and the bar while the pair loads. Required. */\n skeleton: React.ReactNode;\n /** What to show when there is nothing left to judge, and what to do next. Required. */\n empty: React.ReactNode;\n /** Receives the answer. The caller sends it and sets `pending` meanwhile. */\n onAnswer: (answer: PairAnswer) => void;\n /** An answer is being saved: buttons and keys are off. */\n pending: boolean;\n /** A line above the pictures: \"12 pairs left\". */\n progress?: React.ReactNode;\n /** Reasons the judge can give for setting a pair aside (\"Picture missing\", \"Not the same scene\"); no flag menu without them. */\n flagReasons?: readonly string[];\n /** Addresses of the next pairs' pictures or clips, fetched ahead so the next pair is ready the moment this one is answered. */\n preload?: readonly string[];\n /** The answer just given: what it was, how to take it back, and what to show of the pair after (`reveal`, never during the judgment). */\n last?: { text: string; onUndo: () => void; reveal?: React.ReactNode };\n words?: PairVoteWords;\n /** Draws the pair: `(slot, pair) => <CompareAudio {...pair} {...slot} blind missing=… />`. Pass the whole `slot` through so the answer keys share the view's legend and the bar sits in its footer. */\n view: (slot: PairVoteSlot, pair: Pair<M>) => React.ReactNode;\n};\n\n/** Props for `PairVote`: the pair judgment, drawn with `Compare`. */\nexport type PairVoteProps = Omit<PairJudgeProps<ImageMedia>, \"view\"> & Omit<CompareProps, \"label\" | \"a\" | \"b\" | \"extraShortcuts\" | \"footer\">;\n\n/** A blind pairwise judgment of two pictures: `Compare`, answer keys in its legend, and a vote bar that never leans on either side. */\nexport function PairVote({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words, ...compare }: PairVoteProps) {\n return (\n <PairJudge\n {...{ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words }}\n view={(slot, p) => <Compare {...compare} label={p.label} a={p.a} b={p.b} {...slot} />}\n />\n );\n}\n\n/** A blind pairwise judgment of anything: the answer keys, vote bar, pending, flag menu, progress, preload and Undo around a `view` that draws the pair (`CompareAudio`, `CompareText`, your own). */\nexport function PairJudge<M>({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words = {}, view }: PairJudgeProps<M>) {\n React.useEffect(() => {\n // Warm the cache only; the elements are dropped at once.\n for (const src of preload ?? []) new Image().src = src;\n }, [preload]);\n const w = { tie: \"About the same\", skip: \"Can't tell\", pending: \"Saving your answer…\", flag: \"Flag this pair\", prefer: (l: string) => `Prefer ${l}`, ...words };\n return (\n <div className=\"grid gap-3\">\n {progress && <p className=\"type-body-sm text-muted-foreground\">{progress}</p>}\n <DataView state={pair} isEmpty={(p) => p === null} skeleton={skeleton} empty={empty}>\n {(p) => p && <Judged pair={p} onAnswer={onAnswer} pending={pending} flagReasons={flagReasons} words={w} last={last} view={view} />}\n </DataView>\n {/* With no pair on screen (the queue just ran out) the last answer can still be taken back. */}\n {last && !(pair.status === \"ready\" && pair.data) && <LastAnswer last={last} />}\n </div>\n );\n}\n\nfunction LastAnswer({ last }: { last: NonNullable<PairJudgeProps<unknown>[\"last\"]> }) {\n return (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-3 type-body-sm text-muted-foreground\">\n <span>{last.text}</span>\n <Button size=\"sm\" variant=\"ghost\" onPress={last.onUndo}>\n Undo\n </Button>\n {last.reveal}\n </div>\n );\n}\n\nfunction Judged<M>({ pair, onAnswer, pending, flagReasons, words, last, view }: { pair: Pair<M>; last?: PairJudgeProps<M>[\"last\"]; onAnswer: (a: PairAnswer) => void; pending: boolean; flagReasons?: readonly string[]; words: Required<PairVoteWords>; view: PairJudgeProps<M>[\"view\"] }) {\n const { a, b } = pair;\n const answer = (x: PairAnswer) => !pending && onAnswer(x);\n const shortcuts: Shortcut[] = [\n { keys: [\"a\"], label: words.prefer(a.label), run: () => answer({ answer: \"a\" }), disabled: pending },\n { keys: [\"b\"], label: words.prefer(b.label), run: () => answer({ answer: \"b\" }), disabled: pending },\n { keys: [\"t\"], label: words.tie, run: () => answer({ answer: \"tie\" }), disabled: pending },\n { keys: [\"s\"], label: words.skip, run: () => answer({ answer: \"skip\" }), disabled: pending },\n ];\n const footer = (\n <div className={cn(\"grid gap-2\")} aria-busy={pending || undefined}>\n <div role=\"group\" aria-label=\"Your answer\" className=\"flex flex-wrap items-center gap-2\">\n <Button disabled={pending} onPress={() => answer({ answer: \"a\" })}>{words.prefer(a.label)}</Button>\n <Button disabled={pending} onPress={() => answer({ answer: \"tie\" })}>{words.tie}</Button>\n <Button disabled={pending} onPress={() => answer({ answer: \"b\" })}>{words.prefer(b.label)}</Button>\n <Button variant=\"ghost\" disabled={pending} onPress={() => answer({ answer: \"skip\" })}>{words.skip}</Button>\n {flagReasons && flagReasons.length > 0 && (\n <Menu\n label={words.flag}\n trigger={\n <Button variant=\"ghost\" disabled={pending}>\n <Flag aria-hidden />\n {words.flag}\n </Button>\n }\n items={flagReasons.map((reason) => ({ id: reason, label: reason, run: () => answer({ answer: \"flag\", reason }) }))}\n />\n )}\n </div>\n {pending && <p role=\"status\" className=\"type-body-sm text-muted-foreground\">{words.pending}</p>}\n {last && <LastAnswer last={last} />}\n </div>\n );\n return <>{view({ extraShortcuts: shortcuts, footer }, pair)}</>;\n}\n","// How loud a clip is, for the audio comparison: so the louder of two clips does not win by being\n// louder (a few tenths of a dB already shifts preference), the comparison can turn the louder one\n// down to match.\n//\n// The measure is RMS over the whole clip (up to `MAX_SECONDS`) in dB relative to full scale, with\n// the sample peak beside it. It is not LUFS (ITU-R BS.1770): no K-weighting, no gating of silence.\n// For two renderings of the same sentence that is close enough to match them, and it is honest\n// about what it is; a product that needs broadcast loudness measures it on the server and passes\n// `measure`. The arithmetic takes plain channel arrays so it is unit tested without a browser;\n// decoding needs the Web Audio API and is covered by the Storybook shots in Chromium.\n\n/** A clip's level in dB relative to full scale: its RMS (what the ear follows) and its highest sample. */\nexport type Loudness = { rms: number; peak: number };\n\n/** The most of a clip that is measured, in seconds. */\nexport const MAX_SECONDS = 120;\n\nconst db = (x: number) => (x > 0 ? 20 * Math.log10(x) : -Infinity);\n\n/** The RMS and peak of channel data (-1 to 1), over all channels together. */\nexport function loudnessOf(channels: readonly Float32Array[]): Loudness {\n let sum = 0;\n let count = 0;\n let peak = 0;\n for (const c of channels)\n for (let i = 0; i < c.length; i++) {\n const v = c[i];\n sum += v * v;\n const a = Math.abs(v);\n if (a > peak) peak = a;\n }\n count = channels.reduce((n, c) => n + c.length, 0);\n return { rms: db(Math.sqrt(count ? sum / count : 0)), peak: db(peak) };\n}\n\n/** How much to turn each of two clips down (in dB, zero or less) so they play at the same RMS: the louder is lowered to the quieter. */\nexport function matchGains(a: Loudness, b: Loudness): { a: number; b: number } {\n if (!Number.isFinite(a.rms) || !Number.isFinite(b.rms)) return { a: 0, b: 0 };\n const diff = a.rms - b.rms;\n return diff > 0 ? { a: -diff, b: 0 } : { a: 0, b: diff };\n}\n\n/** dB to a media element's volume (0 to 1). */\nexport const gainToVolume = (decibels: number) => Math.min(1, Math.max(0, 10 ** (decibels / 20)));\n\n/** Fetches and decodes a clip and measures it. Needs the Web Audio API; reads at most `MAX_SECONDS`. */\nexport async function measureLoudness(src: string): Promise<Loudness> {\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Could not read ${src}: ${response.status}`);\n const Context = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;\n const context = new Context();\n try {\n const buffer = await context.decodeAudioData(await response.arrayBuffer());\n const frames = Math.min(buffer.length, Math.floor(buffer.sampleRate * MAX_SECONDS));\n return loudnessOf(Array.from({ length: buffer.numberOfChannels }, (_, c) => buffer.getChannelData(c).subarray(0, frames)));\n } finally {\n void context.close();\n }\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\nimport { gainToVolume, matchGains, measureLoudness, type Loudness } from \"../lib/loudness\";\nimport { Button } from \"./button\";\nimport type { AudioMedia, Candidate } from \"./compare\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\nimport { useMediaElement } from \"./media-player\";\nimport { Switch } from \"./switch\";\nimport { ToggleGroup } from \"./toggle\";\n\n// Two clips of the same thing, heard one after the other in the same place. What the TTS and\n// transcription evals in strata-models needed, and two independent players cannot give: the useful\n// comparison is the ABX-style one, so there is ONE transport and a switch between A and B that keeps\n// the playhead, and a person hears the same word in each voice without scrubbing twice.\n//\n// Only the chosen clip plays. Switching copies the position to the other (the same time, or the same\n// proportion when the clips differ in length: `align`, default \"auto\" is proportion when they differ\n// by more than 2%, since a clip that is 10% longer has its words later, not at the same second) and,\n// if it was playing, carries on in the other. A brief gap at the switch is the other element\n// starting, not a seek.\n//\n// Level: the louder of two clips tends to be judged better, so by default (`levelMatch`) the louder\n// is turned down to the quieter by RMS (`lib/loudness.ts`; not LUFS, and the file says so), and the\n// readout says by how much, in the candidates' labels, so a blind judge learns nothing about which\n// is which. It only ever turns a clip DOWN: a media element's volume cannot go above 1. Measuring\n// decodes the clip with the Web Audio API; `measure` replaces it (a server's figure, a test).\n//\n// Looping a range (set a start and an end at the playhead, clear them) lets a judge hear the same two\n// seconds in A, then B. The range is kept as shares of the clip, so it lands on the same words in the\n// other clip under proportional alignment and is the same seconds under time alignment. The end is\n// watched on `requestAnimationFrame` while playing, because `timeupdate` fires about four times a\n// second and the loop would overshoot by a quarter of a second.\n//\n// Keys: `1` and `2` choose A and B, `x` flips, Space and `k` play, `j` and `l` go back and forward a\n// second, `i` and `o` set the loop's start and end, `c` clears it. `a`, `b`, `t` and `s` are left for\n// a `PairVote`'s answers, and arrows are left to the seek bar. They come from one list, drawn in one\n// legend with the screen's (`extraShortcuts`).\n//\n// Blind: the same rules as `Compare`. Only the label names a clip on the page (the `<audio>` element\n// is \"Clip A\"); the id and note are never written. `src` reaches the DOM, so a blind caller serves\n// clips under neutral addresses.\n//\n// Checked: React Aria has no media player or A/B switch. The seek bar, transport, readout and volume\n// are strata's own parts built on its slider and toolbar hooks; the switch is a `ToggleGroup`.\n\n/** Props for `CompareAudio`. */\nexport type CompareAudioProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<AudioMedia>;\n b: Candidate<AudioMedia>;\n /** Whether the person must not learn which clip is which. Required, no default. */\n blind: boolean;\n /** The words shown when a clip cannot be loaded: \"Clip not found\". Required. */\n missing: string;\n /** Turn the louder clip down to the quieter one. Default true. */\n levelMatch?: boolean;\n /** How a switch carries the playhead over: the same time, the same share of the clip, or by share when the lengths differ by more than 2%. Default \"auto\". */\n align?: \"time\" | \"proportion\" | \"auto\";\n /** Measures a clip's level. Default decodes it in the browser. */\n measure?: (src: string) => Promise<Loudness>;\n /** Bind the keys on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen, bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the controls, above the legend: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\ntype Loop = { start: number | null; end: number | null };\n\nconst db = (x: number) => `${Math.abs(x).toFixed(1)} dB`;\n\n/** Two clips to judge by ear: one transport, a switch that keeps the playhead, a loop, and matched levels. */\nexport function CompareAudio({ label, a, b, blind, missing, levelMatch = true, align = \"auto\", measure = measureLoudness, keys = true, extraShortcuts = [], footer, className }: CompareAudioProps) {\n const refA = React.useRef<HTMLAudioElement>(null);\n const refB = React.useRef<HTMLAudioElement>(null);\n const sa = useMediaElement(refA);\n const sb = useMediaElement(refB);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [volume, setVolume] = React.useState(100);\n const [matching, setMatching] = React.useState(levelMatch);\n const [loop, setLoop] = React.useState<Loop>({ start: null, end: null });\n const [levels, setLevels] = React.useState<{ key: string; a: Loudness; b: Loudness } | \"failed\" | null>(null);\n\n const active = showing === \"a\" ? sa : sb;\n const keyOf = `${a.media.src}|${b.media.src}`;\n\n // Measure both clips once per pair, and only while matching.\n React.useEffect(() => {\n if (!matching) return;\n let live = true;\n setLevels(null);\n Promise.all([measure(a.media.src), measure(b.media.src)]).then(\n ([la, lb]) => live && setLevels({ key: keyOf, a: la, b: lb }),\n () => live && setLevels(\"failed\"),\n );\n return () => {\n live = false;\n };\n }, [matching, keyOf, a.media.src, b.media.src, measure]);\n\n const gains = matching && levels && levels !== \"failed\" && levels.key === keyOf ? matchGains(levels.a, levels.b) : { a: 0, b: 0 };\n React.useEffect(() => {\n if (refA.current) refA.current.volume = (volume / 100) * gainToVolume(gains.a);\n if (refB.current) refB.current.volume = (volume / 100) * gainToVolume(gains.b);\n }, [volume, gains.a, gains.b]);\n\n // Which share of the other clip is the same place as `time` in this one.\n const carry = (time: number, from: { duration: number | null }, to: { duration: number | null }) => {\n const known = from.duration && to.duration;\n if (!known || align === \"time\") return time;\n const differ = Math.abs(from.duration! - to.duration!) / Math.max(from.duration!, to.duration!) > 0.02;\n return align === \"proportion\" || differ ? (time / from.duration!) * to.duration! : time;\n };\n const hear = (side: \"a\" | \"b\") => {\n if (side === showing) return;\n const from = showing === \"a\" ? sa : sb;\n const to = side === \"a\" ? sa : sb;\n const wasPlaying = from.playing;\n from.pause();\n to.seek(carry(from.time, from, to));\n // The loop moves with the playhead's policy: under `time` it keeps its seconds, so its shares change.\n if (from.duration && to.duration) {\n const move = (share: number | null) => (share === null ? null : Math.min(1, carry(share * from.duration!, from, to) / to.duration!));\n setLoop((l) => ({ start: move(l.start), end: move(l.end) }));\n }\n if (wasPlaying) void to.play();\n setShowing(side);\n };\n const flip = () => hear(showing === \"a\" ? \"b\" : \"a\");\n\n const duration = active.duration ?? 0;\n const at = (share: number | null) => (share === null || !duration ? null : share * duration);\n const setPoint = (point: \"start\" | \"end\") => {\n if (!duration) return;\n const share = active.time / duration;\n setLoop((l) => {\n const next = { ...l, [point]: share };\n // A start after the end (or an end before the start) replaces the other point.\n if (next.start !== null && next.end !== null && next.start >= next.end) return point === \"start\" ? { start: share, end: null } : { start: null, end: share };\n return next;\n });\n };\n const clearLoop = () => setLoop({ start: null, end: null });\n\n // Back to the start of the range when the end is reached.\n const looping = loop.start !== null && loop.end !== null;\n const enforce = React.useCallback(() => {\n const e = (showing === \"a\" ? refA : refB).current;\n if (!e || !looping || !Number.isFinite(e.duration)) return;\n if (e.currentTime >= loop.end! * e.duration || e.currentTime < loop.start! * e.duration - 0.05) e.currentTime = loop.start! * e.duration;\n }, [showing, looping, loop.start, loop.end]);\n // Only while playing: a paused judge may park the playhead anywhere (to set a new start, say).\n React.useEffect(() => {\n if (looping && active.playing && active.time >= loop.end! * duration) enforce();\n }, [active.time, active.playing, looping, loop.end, duration, enforce]);\n React.useEffect(() => {\n if (!looping || !active.playing) return;\n let frame = requestAnimationFrame(function tick() {\n enforce();\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [looping, active.playing, enforce]);\n\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n { keys: [\"1\"], label: `Hear ${a.label}`, run: () => hear(\"a\") },\n { keys: [\"2\"], label: `Hear ${b.label}`, run: () => hear(\"b\") },\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip },\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: active.toggle },\n { keys: [\"j\"], label: \"Back 1 s\", run: () => active.seek(Math.max(0, active.time - 1)), repeat: true },\n { keys: [\"l\"], label: \"Forward 1 s\", run: () => active.seek(active.time + 1), repeat: true },\n { keys: [\"i\"], label: \"Loop starts here\", run: () => setPoint(\"start\") },\n { keys: [\"o\"], label: \"Loop ends here\", run: () => setPoint(\"end\") },\n { keys: [\"c\"], label: \"Clear the loop\", run: clearLoop, disabled: loop.start === null && loop.end === null },\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const failed = sa.error || sb.error;\n const marks = [\n ...(loop.start !== null && at(loop.start) !== null ? [{ time: at(loop.start)!, label: \"Loop start\" }] : []),\n ...(loop.end !== null && at(loop.end) !== null ? [{ time: at(loop.end)!, label: \"Loop end\" }] : []),\n ];\n const range = (share: number | null) => (share === null || !duration ? format.missing : format.timecode(share * duration, { precision: \"seconds\" }));\n\n let levelLine: string | null = null;\n if (matching) {\n if (levels === \"failed\") levelLine = \"Could not measure the levels, so the clips are not matched.\";\n else if (!levels || levels.key !== keyOf) levelLine = \"Measuring levels…\";\n else if (gains.a === 0 && gains.b === 0) levelLine = \"Both clips are at the same level.\";\n else {\n const [loud, quiet, cut] = gains.a < 0 ? [a.label, b.label, gains.a] : [b.label, a.label, gains.b];\n levelLine = `${loud} is louder than ${quiet}, so it is turned down by ${db(cut)}.`;\n }\n }\n\n return (\n <section aria-label={label} className={cn(\"grid gap-3\", className)}>\n <audio ref={refA} src={a.media.src} preload=\"auto\" aria-label={`Clip ${a.label}`} />\n <audio ref={refB} src={b.media.src} preload=\"auto\" aria-label={`Clip ${b.label}`} />\n <div className=\"flex flex-wrap items-center gap-3\">\n <ToggleGroup\n label=\"Listen to\"\n options={[\n { value: \"a\", label: a.label },\n { value: \"b\", label: b.label },\n ]}\n value={showing}\n onChange={(v) => hear(v as \"a\" | \"b\")}\n />\n <Switch label=\"Match loudness\" on={matching} onChange={setMatching} />\n </div>\n {!blind && (a.note || b.note) && (\n <p className=\"type-caption text-muted-foreground\">\n {[a, b].filter((c) => c.note).map((c) => `${c.label}: ${c.note}`).join(\" · \")}\n </p>\n )}\n {failed && (\n <p role=\"alert\" className=\"type-body-sm text-danger\">\n {missing}\n </p>\n )}\n <Transport playing={active.playing} onPlayPause={active.toggle}>\n <TimeReadout time={active.time} duration={active.duration} />\n <SeekBar time={active.time} duration={active.duration} onSeek={active.seek} marks={marks} buffered={active.buffered} label={`Position in ${(showing === \"a\" ? a : b).label}`} step={1} />\n <VolumeControl volume={volume} onVolumeChange={setVolume} />\n </Transport>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button size=\"sm\" onPress={() => setPoint(\"start\")} disabled={!duration}>\n Loop starts here\n </Button>\n <Button size=\"sm\" onPress={() => setPoint(\"end\")} disabled={!duration}>\n Loop ends here\n </Button>\n <Button size=\"sm\" variant=\"ghost\" onPress={clearLoop} disabled={loop.start === null && loop.end === null}>\n Clear the loop\n </Button>\n <span role=\"status\" className=\"type-caption tabular-nums text-muted-foreground\">\n {looping ? `Looping ${range(loop.start)} to ${range(loop.end)}` : loop.start !== null ? `Loop starts at ${range(loop.start)}` : loop.end !== null ? `Loop ends at ${range(loop.end)}` : \"No loop\"}\n </span>\n </div>\n {levelLine && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {levelLine}\n </p>\n )}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Slider as AriaSlider, SliderThumb, SliderTrack } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\nimport { Button } from \"./button\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { Skeleton } from \"./data-view\";\nimport { Caption, FullscreenButton, VIEWPORT_HEIGHT, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport type { Candidate, CompareMode, VideoMedia } from \"./compare\";\nimport { RateChoice, SeekBar, TimeReadout, Transport, VolumeControl } from \"./media\";\nimport { useMediaElement } from \"./media-player\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Slider } from \"./value-controls\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\nimport { RegionChips, useRegions } from \"./compare-regions\";\nimport type { Region } from \"../lib/viewport\";\n\n// Two videos of the same thing on ONE clock, to be judged blind by eye. What the video-enhance eval\n// in strata-models needs and two plain <video> elements cannot give: the interesting views (the swipe\n// divider over moving picture, blink between A and B on the same frame) only mean something if both\n// sides show the same instant, and zoom and pan must stay locked across them while they play.\n//\n// The clock: play, pause, seek and rate go to both elements; the first video is the leader. While it\n// plays, a requestAnimationFrame loop keeps the follower within a frame (`fps`, default 30) of it: a\n// follower more than a frame off has its rate nudged by 3% towards the leader, one more than 0.3 s\n// off is seeked to it, and when either side has not got its next frames (readyState below 3) BOTH\n// are paused until both have, so a stall on one side is never seen as the other side running ahead.\n// requestVideoFrameCallback was considered for the loop and not used: it fires only when the leader\n// presents a frame, which is the one time a stall cannot be seen; a display-frame loop sees both and\n// costs nothing at 25 to 50 fps content. Known limit: a seek is not hidden while the two decoders\n// catch up (a video element cannot hold its old frame), it is corrected by the same loop; playback\n// after a seek waits for both.\n//\n// Sizes: candidates may differ in pixels (1440×1080 against 2816×2304). Both are drawn `object-contain`\n// in the same box whose shape is the first candidate's `width`/`height`, so neither looks bigger.\n// Zoom is the shared `useViewport` of `Compare`; `pixelated` draws nearest-neighbour once the picture\n// is shown larger than its own pixels (default), so a judge sees real pixels, not a smoothed guess.\n//\n// Views: side by side, swipe, fade and blink, the same as pictures. Changing view puts the videos in\n// a different place in the tree, so the browser makes new elements; the clock remembers the time and\n// whether it was playing and puts the new ones back there when they have their metadata.\n//\n// Sound: one source, the app's choice (`audio`, default \"a\"; the outputs normally share it), the\n// other muted, so two soundtracks never play at once.\n//\n// Blind: the same rules as `Compare`. Only `label` names a video on the page; id, note and any\n// description are never written. `src` and `poster` reach the DOM, so a blind caller serves them\n// under neutral addresses.\n//\n// Looking at a moment: `,` and `.` step one frame (to the centre of the next frame, so a step cannot\n// land on a boundary and show the wrong one; they repeat when held), `i` and `o` set a loop's start\n// and end at the playhead and `c` clears it, kept in seconds because both videos show the same\n// moments; the app may hold the range (`loop`, `onLoopChange`) so it survives a change of pair.\n// Speeds go down to 0.1. `moments` are the app's named points on the seek bar; pressing one goes\n// there and pauses. Not done: dragging the loop's ends on the seek bar (the marks show them, the keys\n// and buttons set them) and confirming a step with requestVideoFrameCallback's `mediaTime`.\n//\n// Keys: `1` to `4` views, `x` flips in blink, Space and `k` play, `j` and `l` go back and forward a\n// second, `m` mutes, `+` `-` `0` `f` zoom and full screen. `a`, `b`, `t` and `s` are left to a\n// `PairVote`; arrows are left to the picture (they pan once zoomed). One list for the keys and the\n// legend (`extraShortcuts`).\n//\n// Checked: React Aria has no video player or comparison part; the transport, seek bar and rate\n// choice are the media parts built on its slider, toolbar and select, and the swipe divider is its\n// slider, as in `Compare`.\n\n/** The views a pair of videos has: pictures' views without the difference, which needs pixels. */\nexport type VideoMode = Exclude<CompareMode, \"difference\">;\n\nconst MODES: readonly VideoMode[] = [\"side\", \"swipe\", \"fade\", \"blink\"];\nconst MODE_LABEL: Record<VideoMode, string> = { side: \"Side by side\", swipe: \"Swipe\", fade: \"Fade\", blink: \"Blink\" };\n\n/** A range to loop, in seconds of the clip; the same seconds in both videos. */\nexport type VideoLoop = { start: number | null; end: number | null };\n\nconst SLOW_RATES = [0.1, 0.25, 0.5, 1, 1.25, 1.5, 2] as const;\n\n/** Props for `CompareVideo`. */\nexport type CompareVideoProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<VideoMedia>;\n b: Candidate<VideoMedia>;\n /** Whether the person must not learn which video is which. Required, no default. */\n blind: boolean;\n /** The words shown when a video cannot be loaded: \"Video not found\". Required. */\n missing: string;\n mode: VideoMode;\n onModeChange: (mode: VideoMode) => void;\n /** Speeds offered. Default 0.1, 0.25, 0.5, 1, 1.25, 1.5, 2: slow motion for sitting on a moment. */\n rates?: readonly number[];\n /** Moments the app names (\"fast motion\"), drawn on the seek bar; pressing one goes there and pauses. */\n moments?: readonly { time: number; label: string }[];\n /** The looped range in seconds, `null` for an end not set. Give it (with `onLoopChange`) to keep the range when the pair changes to another of the same item. Without it the component keeps its own. */\n loop?: VideoLoop;\n onLoopChange?: (loop: VideoLoop) => void;\n /** Named boxes to look at enlarged, as in `Compare`, on the same clock; a box drawn by hand (Shift-drag) is for a paused clip. Nearest-neighbour while one is shown. */\n regions?: readonly Region[];\n /** Which video's sound is heard; the other is muted. Default \"a\". */\n audio?: \"a\" | \"b\" | \"none\";\n /** Draw nearest-neighbour when shown larger than the video's own pixels (`zoomed`, default), always, or never. */\n pixelated?: \"zoomed\" | \"always\" | \"never\";\n /** How tall a frame may be: a CSS length or `\"viewport\"`, as in `Compare`. */\n maxHeight?: string;\n /** Bind the keys on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen, bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the video, above the legend, and kept in full screen: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\n// Width of an element, kept current, for \"is this shown larger than its pixels\".\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const read = () => setWidth(el.getBoundingClientRect().width);\n read();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n });\n return width;\n}\n\n/** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */\nexport function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates = SLOW_RATES, regions, moments = [], loop: loopProp, onLoopChange, audio = \"a\", pixelated = \"zoomed\", maxHeight, keys = true, extraShortcuts = [], footer, className }: CompareVideoProps) {\n const refA = React.useRef<HTMLVideoElement>(null);\n const refB = React.useRef<HTMLVideoElement>(null);\n const sa = useMediaElement(refA);\n const sb = useMediaElement(refB);\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n const [divider, setDivider] = React.useState(50);\n const [blend, setBlend] = React.useState(50);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const [volume, setVolume] = React.useState(100);\n const [muted, setMuted] = React.useState(false);\n // What the person asked for, which can differ from what the elements are doing while one waits for the other.\n const [wanted, setWanted] = React.useState(false);\n const frameRef = React.useRef<HTMLDivElement>(null);\n const frameWidth = useWidth(frameRef);\n\n const fps = a.media.fps ?? 30;\n const known = [sa.duration, sb.duration].filter((d): d is number => d !== null);\n const duration = known.length ? Math.min(...known) : null;\n const failed = sa.error || sb.error;\n\n // ---- the clock ----\n const play = () => {\n setWanted(true);\n void sa.play();\n void sb.play();\n };\n const pause = () => {\n setWanted(false);\n sa.pause();\n sb.pause();\n };\n const toggle = () => (wanted ? pause() : play());\n const seek = (time: number) => {\n const t = Math.max(0, duration === null ? time : Math.min(time, duration));\n sa.seek(t);\n sb.seek(t);\n };\n // Frame by frame: the centre of the next or previous frame, so a step cannot land on a boundary and show the wrong one.\n // The leader's own time, not the snapshot: that is only as fresh as the last media event, and a step during playback would jump back.\n const now = () => refA.current?.currentTime ?? sa.time;\n const step = (direction: 1 | -1) => {\n pause();\n const frame = Math.floor(now() * fps + 1e-6);\n seek(Math.max(0, (frame + direction + 0.5) / fps));\n };\n // The loop is the app's when it gives one, so it survives a change of pair; otherwise ours.\n const [ownLoop, setOwnLoop] = React.useState<VideoLoop>({ start: null, end: null });\n const loop = loopProp ?? ownLoop;\n const setLoop = (next: VideoLoop) => {\n setOwnLoop(next);\n onLoopChange?.(next);\n };\n const loopRef = React.useRef(loop);\n loopRef.current = loop;\n const setPoint = (point: \"start\" | \"end\") => {\n const t = now();\n const other = point === \"start\" ? loop.end : loop.start;\n // A start after the end (or an end before the start) replaces the other point.\n const clash = other !== null && (point === \"start\" ? t >= other : t <= other);\n setLoop(clash ? { start: point === \"start\" ? t : null, end: point === \"end\" ? t : null } : { ...loop, [point]: t });\n };\n const clearLoop = () => setLoop({ start: null, end: null });\n const looping = loop.start !== null && loop.end !== null;\n // Kept here, not read back from an element, so a view change's new elements get it too.\n const chosenRate = React.useRef(1);\n const setRate = (rate: number) => {\n chosenRate.current = rate;\n sa.setRate(rate);\n sb.setRate(rate);\n };\n\n // Either video reaching its end ends the play for both: the clock runs to the shorter one's end, which is the length shown.\n // Unless a loop is set: then the end is where the loop goes back from (a range that ends at the clip's end never gets another frame to be caught on).\n React.useEffect(() => {\n if (!(sa.ended || sb.ended)) return;\n const { start, end } = loopRef.current;\n const A = refA.current;\n const B = refB.current;\n if (wanted && start !== null && end !== null && A && B) {\n A.currentTime = start;\n B.currentTime = start;\n void A.play();\n void B.play();\n return;\n }\n setWanted(false);\n A?.pause();\n B?.pause();\n }, [sa.ended, sb.ended]);\n\n React.useEffect(() => {\n if (!wanted) return;\n let held = false;\n let frame = requestAnimationFrame(function tick() {\n const A = refA.current;\n const B = refB.current;\n if (A && B && !A.ended && !B.ended) {\n const ready = A.readyState >= 3 && B.readyState >= 3;\n if (!ready) {\n if (!held) {\n held = true;\n A.pause();\n B.pause();\n }\n } else if (held) {\n held = false;\n void A.play();\n void B.play();\n } else if (!A.paused) {\n const { start, end } = loopRef.current;\n if (start !== null && end !== null && A.currentTime >= end) {\n A.currentTime = start;\n B.currentTime = start;\n frame = requestAnimationFrame(tick);\n return;\n }\n const drift = B.currentTime - A.currentTime;\n const one = 1 / fps;\n if (Math.abs(drift) > 0.3) B.currentTime = A.currentTime;\n else if (Math.abs(drift) > one) B.playbackRate = A.playbackRate * (drift > 0 ? 0.97 : 1.03);\n else if (Math.abs(drift) < one / 2 && B.playbackRate !== A.playbackRate) B.playbackRate = A.playbackRate;\n }\n }\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [wanted, fps]);\n\n // New elements (a view change) come back to where the old ones were.\n const resume = React.useRef({ time: 0, playing: false });\n if (sa.duration !== null) resume.current = { time: sa.time, playing: wanted };\n const restore = (e: React.SyntheticEvent<HTMLVideoElement>) => {\n const el = e.currentTarget;\n el.defaultPlaybackRate = chosenRate.current;\n el.playbackRate = chosenRate.current;\n if (resume.current.time > 0) el.currentTime = resume.current.time;\n if (resume.current.playing) void el.play();\n };\n\n // One sound: the chosen video at the volume, the rest muted.\n React.useEffect(() => {\n [[refA.current, \"a\"], [refB.current, \"b\"]].forEach(([el, side]) => {\n if (!(el instanceof HTMLVideoElement)) return;\n el.muted = audio !== side || muted || volume === 0;\n el.volume = volume / 100;\n });\n });\n\n // ---- the picture ----\n const aspect = a.media.width / a.media.height;\n const natural = [a.media.width, a.media.height] as const;\n // Each video against its own pixels: the one drawn larger than its pixels is nearest-neighbour, the other not.\n const frameHeight = frameWidth / aspect;\n const sharpFor = (c: Candidate<VideoMedia>) => {\n if (rg.active !== null) return true;\n if (pixelated !== \"zoomed\") return pixelated === \"always\";\n const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));\n return drawn > 0 && (viewport.scale * drawn) / c.media.width > 1;\n };\n const rg = useRegions({ regions, viewport, setViewport, frame: frameRef, reset: `${a.media.src}|${b.media.src}` });\n const zoom = useZoom({ viewport, setViewport: rg.setViewport, frame: frameRef, natural });\n const flip = () => setShowing((s) => (s === \"a\" ? \"b\" : \"a\"));\n\n const video = (c: Candidate<VideoMedia>, ref: React.RefObject<HTMLVideoElement | null>) => (\n <video\n ref={ref}\n src={c.media.src}\n poster={c.media.poster}\n preload=\"auto\"\n playsInline\n aria-label={`Video ${c.label}`}\n onLoadedMetadata={restore}\n style={sharpFor(c) ? { imageRendering: \"pixelated\" } : undefined}\n className=\"absolute inset-0 size-full object-contain\"\n />\n );\n const loading = !failed && (sa.duration === null || sb.duration === null);\n const skeleton = loading && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none\" />;\n const frameProps = { viewport, setViewport: rg.setViewport, onBox: wanted ? undefined : rg.add, outline: rg.peek, aspect, maxHeight: maxHeight === \"viewport\" ? VIEWPORT_HEIGHT : maxHeight };\n\n const shortcuts: Shortcut[] = [\n ...extraShortcuts,\n ...MODES.map((m, i): Shortcut => ({ keys: [String(i + 1)], label: MODE_LABEL[m], run: () => onModeChange(m) })),\n { keys: [\"x\"], label: `Flip ${a.label} and ${b.label}`, run: flip, disabled: mode !== \"blink\" },\n { keys: [\" \", \"k\"], label: \"Play or pause\", run: toggle },\n { keys: [\"j\"], label: \"Back 1 s\", run: () => seek(sa.time - 1), repeat: true },\n { keys: [\"l\"], label: \"Forward 1 s\", run: () => seek(sa.time + 1), repeat: true },\n { keys: [\",\"], label: \"Back one frame\", run: () => step(-1), repeat: true },\n { keys: [\".\"], label: \"Forward one frame\", run: () => step(1), repeat: true },\n { keys: [\"i\"], label: \"Loop starts here\", run: () => setPoint(\"start\") },\n { keys: [\"o\"], label: \"Loop ends here\", run: () => setPoint(\"end\") },\n { keys: [\"c\"], label: \"Clear the loop\", run: clearLoop, disabled: loop.start === null && loop.end === null },\n ...(audio === \"none\" ? [] : [{ keys: [\"m\"], label: \"Mute\", run: () => setMuted((m) => !m) }]),\n ...rg.shortcuts,\n ...zoomShortcuts(zoom, full, setFull),\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const at = (t: number | null) => (t === null ? format.missing : format.timecode(t, { precision: \"frames\", fps }));\n const marks = [\n ...moments,\n ...(loop.start !== null ? [{ time: loop.start, label: \"Loop start\" }] : []),\n ...(loop.end !== null ? [{ time: loop.end, label: \"Loop end\" }] : []),\n ];\n\n let body: React.ReactNode;\n if (mode === \"side\") {\n body = (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {([[a, refA], [b, refB]] as const).map(([c, ref], i) => (\n <figure key={i} className=\"grid gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame {...frameProps} label={`Frame ${c.label}`} ref={i === 0 ? frameRef : undefined}>\n {i === 0 && skeleton}\n {video(c, ref)}\n </ViewportFrame>\n </figure>\n ))}\n </div>\n );\n } else {\n // One frame, both videos in it. Swipe clips A at the divider; fade lays A over B at an opacity; blink shows one at a time. Both always play.\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n {mode === \"blink\" ? <Caption c={showing === \"a\" ? a : b} blind={blind} /> : <Caption c={a} blind={blind} />}\n {mode !== \"blink\" && <Caption c={b} blind={blind} />}\n </div>\n <ViewportFrame\n {...frameProps}\n ref={frameRef}\n cover={mode === \"swipe\" ? { content: video(a, refA), shown: divider } : undefined}\n label={mode === \"blink\" ? `Frame ${(showing === \"a\" ? a : b).label}` : `${a.label} over ${b.label}`}\n overlay={\n mode === \"swipe\" && (\n <AriaSlider aria-label={`Divider between ${a.label} and ${b.label}`} value={divider} onChange={(v) => setDivider(v as number)} minValue={0} maxValue={100} step={1} className=\"absolute inset-0\">\n <SliderTrack className=\"pointer-events-none h-full w-full\">\n <SliderThumb className=\"pointer-events-auto grid h-full w-8 cursor-ew-resize place-items-center focus-visible:outline-2 focus-visible:outline-ring\" style={{ top: \"50%\" }}>\n <span aria-hidden className=\"col-start-1 row-start-1 h-full w-1 border-x border-background bg-foreground\" />\n <span aria-hidden className=\"col-start-1 row-start-1 size-6 rounded-pill border-2 border-foreground bg-background\" />\n </SliderThumb>\n </SliderTrack>\n </AriaSlider>\n )\n }\n >\n {skeleton}\n {video(b, refB)}\n {mode !== \"swipe\" && <div className=\"absolute inset-0\" style={mode === \"fade\" ? { opacity: 1 - blend / 100 } : mode === \"blink\" ? { opacity: showing === \"a\" ? 1 : 0 } : undefined}>{video(a, refA)}</div>}\n </ViewportFrame>\n </figure>\n );\n }\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Comparison view\" className=\"items-center gap-2\">\n <ToggleGroup label=\"View\" options={MODES.map((m) => ({ value: m, label: MODE_LABEL[m] }))} value={mode} onChange={(v) => onModeChange(v as VideoMode)} size=\"sm\" />\n <ToolbarSeparator />\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n <RegionChips state={rg} />\n {mode === \"fade\" && (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">{a.label}</span>\n <Slider aria-label={`Blend from ${a.label} to ${b.label}`} value={blend} onChange={setBlend} min={0} max={100} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"type-caption text-muted-foreground\">{b.label}</span>\n </div>\n )}\n {mode === \"blink\" && <ToggleGroup label=\"Showing\" options={[{ value: \"a\", label: a.label }, { value: \"b\", label: b.label }]} value={showing} onChange={(v) => setShowing(v as \"a\" | \"b\")} size=\"sm\" className=\"justify-self-start\" />}\n {failed && (\n <p role=\"alert\" className=\"type-body-sm text-danger\">\n {missing}\n </p>\n )}\n {body}\n <Transport playing={wanted} onPlayPause={toggle} onStepBack={() => step(-1)} onStepForward={() => step(1)}>\n <TimeReadout time={sa.time} duration={duration} precision=\"frames\" fps={fps} />\n <SeekBar time={sa.time} duration={duration} onSeek={seek} marks={marks} onMarkPress={(m) => (pause(), seek(m.time))} buffered={sa.buffered} label=\"Position\" step={1} precision=\"frames\" fps={fps} />\n <RateChoice rate={sa.rate} onRateChange={setRate} rates={rates} />\n {audio !== \"none\" && <VolumeControl volume={muted ? 0 : volume} onVolumeChange={(v) => (setMuted(false), setVolume(v))} />}\n </Transport>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button size=\"sm\" onPress={() => setPoint(\"start\")} disabled={duration === null}>\n Loop starts here\n </Button>\n <Button size=\"sm\" onPress={() => setPoint(\"end\")} disabled={duration === null}>\n Loop ends here\n </Button>\n <Button size=\"sm\" variant=\"ghost\" onPress={clearLoop} disabled={loop.start === null && loop.end === null}>\n Clear the loop\n </Button>\n <span role=\"status\" className=\"type-caption tabular-nums text-muted-foreground\">\n {looping ? `Looping ${at(loop.start)} to ${at(loop.end)}` : loop.start !== null ? `Loop starts at ${at(loop.start)}` : loop.end !== null ? `Loop ends at ${at(loop.end)}` : \"No loop\"}\n </span>\n </div>\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","// A word-level difference between two texts, for `CompareText`. Our own and deliberately simple\n// (Jonathan, 2026-11-12: \"do a simple diff ourselves for now and see what text similarity is better\n// in future\"): split on whitespace, find the longest common subsequence of words, and mark the words\n// on each side that are not in it. Case and punctuation count, because a transcript that drops a\n// comma or a capital differs from one that keeps it, and the judge decides whether that matters.\n// What it does not do: notice a moved sentence (it shows as removed here and added there), weigh a\n// word by how different it is, or align by meaning. Those are what a text-similarity method would\n// add, and are the reason this stays behind one function.\n//\n// The table is words × words, so a very long pair is refused (`null`) rather than freezing the\n// page; the caller says so in words and still shows both texts.\n\n/** A run of one text: its words and spaces as written, and whether the words are not in the other text. */\nexport type TextSegment = { text: string; changed: boolean };\n\n/** The two texts cut into segments, and how many words differ on each side. */\nexport type TextDifference = { a: TextSegment[]; b: TextSegment[]; changedA: number; changedB: number };\n\n/** The most words in A times the most in B that are compared; a bigger pair is not. */\nexport const MAX_CELLS = 2_500_000;\n\nconst tokens = (text: string) => text.split(/(\\s+)/).filter((t) => t !== \"\");\nconst isSpace = (t: string) => /^\\s+$/.test(t);\n\n/** Marks the words that differ between two texts, or returns null when the pair is too long to compare. */\nexport function diffWords(a: string, b: string): TextDifference | null {\n const ta = tokens(a);\n const tb = tokens(b);\n const wa = ta.filter((t) => !isSpace(t));\n const wb = tb.filter((t) => !isSpace(t));\n if ((wa.length + 1) * (wb.length + 1) > MAX_CELLS) return null;\n const w = wb.length + 1;\n const table = new Uint32Array((wa.length + 1) * w);\n for (let i = wa.length - 1; i >= 0; i--)\n for (let j = wb.length - 1; j >= 0; j--)\n table[i * w + j] = wa[i] === wb[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);\n const sameA = new Set<number>();\n const sameB = new Set<number>();\n for (let i = 0, j = 0; i < wa.length && j < wb.length; ) {\n if (wa[i] === wb[j]) {\n sameA.add(i++);\n sameB.add(j++);\n } else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) i++;\n else j++;\n }\n const cut = (all: string[], same: Set<number>) => {\n let word = 0;\n const out: TextSegment[] = [];\n let changed = 0;\n for (const t of all) {\n if (isSpace(t)) {\n out.push({ text: t, changed: false });\n continue;\n }\n const diff = !same.has(word++);\n if (diff) changed++;\n out.push({ text: t, changed: diff });\n }\n return { out, changed };\n };\n const ra = cut(ta, sameA);\n const rb = cut(tb, sameB);\n return { a: ra.out, b: rb.out, changedA: ra.changed, changedB: rb.changed };\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { diffWords, type TextSegment } from \"../lib/text-diff\";\nimport type { Candidate, TextMedia } from \"./compare\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Switch } from \"./switch\";\n\n// Two texts side by side to be read and judged: the transcripts of one recording from two models,\n// or two answers to one question. A person reading both wants the same line next to the same line,\n// so the two panes scroll together, and wants the words that differ shown without having to find\n// them, so there is a word diff behind a switch (off by default: a diff is an answer, and a judge\n// who is reading for quality should read first).\n//\n// The diff is our own and simple (`lib/text-diff.ts`: words, longest common subsequence). A changed\n// word is marked with a background AND an underline, so it survives a colour-blind reading and a\n// print, and is a `<mark>`, which a screen reader announces as highlighted. A pair too long to\n// compare is refused in words and both texts are still shown.\n//\n// `reference` is a third text, a ground truth (the transcript a person wrote). It is shown above\n// the two, labelled, and the diff can be taken against it instead of against the other candidate:\n// \"which is closer to what was said\" is the question a transcription judge asks, so with a reference\n// the diff starts against it.\n//\n// Keys: `d` marks the differences; a screen's own keys (a `PairJudge`'s answers) join the same legend\n// through `extraShortcuts`, and its vote bar goes in `footer`.\n//\n// Blind: only the label names a text; the id and note are never written, and `reference` is a\n// separate, labelled thing the caller chooses to show. Text is data, never markup: it is rendered as\n// text with whitespace kept (`whitespace-pre-wrap`), so a model's output cannot inject HTML.\n//\n// Checked: React Aria has no text-diff or synchronised-scroll part. Scrolling is a plain scroll\n// listener on two native scroll boxes; each is a focusable region (`tabIndex=0`, labelled) so a\n// keyboard user can scroll it, which a scrollable `div` otherwise denies them.\n\n/** Props for `CompareText`. */\nexport type CompareTextProps = {\n /** Names the comparison for screen readers. Required. */\n label: string;\n a: Candidate<TextMedia>;\n b: Candidate<TextMedia>;\n /** Whether the person must not learn which text is which. Required, no default. */\n blind: boolean;\n /** A ground-truth text, shown above both; the diff starts against it, and can be switched to the other candidate. */\n reference?: { label: string; text: string };\n /** Start with the word differences marked. Default false. */\n defaultDiff?: boolean;\n /** Said when the pair is too long to compare word by word. Default says so plainly. */\n tooLong?: string;\n /** Scroll the two panes together. Default true. */\n linkedScroll?: boolean;\n /** Bind the keys (`d` marks the differences) on the window. Default true. */\n keys?: boolean;\n /** Shortcuts of the surrounding screen (a `PairJudge`'s answer keys), bound with these and listed first in the same legend. */\n extraShortcuts?: Shortcut[];\n /** Drawn under the texts, above the legend: where a vote bar goes. */\n footer?: React.ReactNode;\n className?: string;\n};\n\nfunction Words({ segments, changed }: { segments: TextSegment[]; changed: boolean }) {\n return (\n <>\n {segments.map((s, i) =>\n changed && s.changed ? (\n <mark key={i} className=\"rounded-control bg-warning-subtle text-foreground underline decoration-2 underline-offset-2\">\n {s.text}\n </mark>\n ) : (\n <React.Fragment key={i}>{s.text}</React.Fragment>\n ),\n )}\n </>\n );\n}\n\n/** Two texts side by side with scrolling together, an optional reference, and a word diff on request. */\nexport function CompareText({ label, a, b, blind, reference, defaultDiff = false, tooLong = \"These texts are too long to compare word by word.\", linkedScroll = true, keys = true, extraShortcuts = [], footer, className }: CompareTextProps) {\n const [diff, setDiff] = React.useState(defaultDiff);\n const [against, setAgainst] = React.useState<\"other\" | \"reference\">(reference ? \"reference\" : \"other\");\n const boxA = React.useRef<HTMLDivElement>(null);\n const boxB = React.useRef<HTMLDivElement>(null);\n const syncing = React.useRef(false);\n\n const result = React.useMemo(() => {\n if (!diff) return null;\n if (against === \"reference\" && reference) {\n const ra = diffWords(a.media.text, reference.text);\n const rb = diffWords(b.media.text, reference.text);\n // `changedB` of each is the reference's words the candidate lacks: a model that drops words must not score as a match.\n return ra && rb ? { a: ra.a, b: rb.a, changedA: ra.changedA, changedB: rb.changedA, missingA: ra.changedB, missingB: rb.changedB } : \"long\";\n }\n const r = diffWords(a.media.text, b.media.text);\n return r ? { ...r, missingA: 0, missingB: 0 } : \"long\";\n }, [diff, against, reference, a.media.text, b.media.text]);\n\n // Keep the two panes at the same share of their scroll range: texts differ in length, so the\n // same pixel is not the same line, but the same share is close.\n const follow = (from: HTMLDivElement | null, to: HTMLDivElement | null) => {\n if (!linkedScroll || !from || !to || syncing.current) return;\n const range = from.scrollHeight - from.clientHeight;\n syncing.current = true;\n to.scrollTop = range > 0 ? (from.scrollTop / range) * (to.scrollHeight - to.clientHeight) : 0;\n requestAnimationFrame(() => (syncing.current = false));\n };\n\n const pane = (c: Candidate<TextMedia>, ref: React.RefObject<HTMLDivElement | null>, other: React.RefObject<HTMLDivElement | null>, segments: TextSegment[] | null) => (\n <figure className=\"grid min-w-0 gap-1.5\">\n <figcaption className=\"flex items-baseline gap-2\">\n <span className=\"type-label\">{c.label}</span>\n {!blind && c.note && <span className=\"type-caption text-muted-foreground\">{c.note}</span>}\n </figcaption>\n <div\n ref={ref}\n tabIndex={0}\n role=\"region\"\n aria-label={`Text ${c.label}`}\n onScroll={() => follow(ref.current, other.current)}\n className=\"max-h-96 overflow-auto whitespace-pre-wrap rounded-surface border border-border bg-muted p-3 type-body focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\"\n >\n {segments ? <Words segments={segments} changed /> : c.media.text}\n </div>\n </figure>\n );\n\n const counts = result && result !== \"long\" ? result : null;\n const words = (n: number) => `${n} ${n === 1 ? \"word\" : \"words\"}`;\n const ref = against === \"reference\" && reference;\n const say = (who: string, differ: number, missing: number) => (ref ? `${who}: ${words(differ)} ${differ === 1 ? \"differs\" : \"differ\"}, ${missing} missing.` : `${who}: ${words(differ)} ${differ === 1 ? \"differs\" : \"differ\"}.`);\n const shortcuts: Shortcut[] = [...extraShortcuts, { keys: [\"d\"], label: diff ? \"Hide the differences\" : \"Mark the differences\", run: () => setDiff((d) => !d) }];\n useHotkeys(shortcuts, { enabled: keys });\n return (\n <section aria-label={label} className={cn(\"grid gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-3\">\n <Switch label=\"Mark the words that differ\" on={diff} onChange={setDiff} />\n {diff && reference && (\n <ToggleGroup\n label=\"Differences against\"\n options={[\n { value: \"other\", label: \"The other text\" },\n { value: \"reference\", label: reference.label },\n ]}\n value={against}\n onChange={(v) => setAgainst(v as \"other\" | \"reference\")}\n size=\"sm\"\n />\n )}\n </div>\n {reference && (\n <figure className=\"grid gap-1.5\">\n <figcaption className=\"type-label\">{reference.label}</figcaption>\n <p className=\"whitespace-pre-wrap rounded-surface border border-border p-3 type-body\">{reference.text}</p>\n </figure>\n )}\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {pane(a, boxA, boxB, counts ? counts.a : null)}\n {pane(b, boxB, boxA, counts ? counts.b : null)}\n </div>\n {diff && (\n <p role=\"status\" className=\"type-body-sm text-muted-foreground\">\n {result === \"long\"\n ? tooLong\n : counts && counts.changedA + counts.missingA + counts.changedB + counts.missingB === 0\n ? ref && reference\n ? `Both match ${reference.label} word for word.`\n : \"The texts are the same word for word.\"\n : counts\n ? `${say(a.label, counts.changedA, counts.missingA)} ${say(b.label, counts.changedB, counts.missingB)}`\n : null}\n </p>\n )}\n {footer}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { Caption, FullscreenButton, Picture, ZoomControls, useZoom, zoomShortcuts } from \"./compare-parts\";\nimport type { Candidate } from \"./compare\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys } from \"./hotkeys\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\nimport { RegionChips, useRegions } from \"./compare-regions\";\nimport type { Region } from \"../lib/viewport\";\n\n// Every candidate's picture for one item at once, with one zoom for all of them (the models app's\n// \"Outputs\" tab, which lists each candidate's output, and Bright Horizons' pick-which-to-keep).\n// Looking at the same detail in every tile is the point, so the viewport is shared exactly as it is\n// in `Compare`; the rest of `Compare` (blind, `missing`, the keys from one list, full screen) is\n// the same too, and shares its parts. What each tile offers beyond looking (open it in a\n// comparison, choose it, flag it) is the caller's: `actions` draws it under the caption, so the grid\n// does not decide that a tile is a button.\n\n/** Props for `CompareGrid`. */\nexport type CompareGridProps = {\n /** Names the grid for screen readers: \"Four versions of this photo\". Required. */\n label: string;\n items: readonly Candidate[];\n /** Whether the person must not learn which variant is which: tiles are named by label only. Required, no default. */\n blind: boolean;\n /** The words shown where a picture could not be loaded. Required. */\n missing: string;\n /** What goes under a tile's caption: a button to compare it, a choice, a flag. */\n actions?: (item: Candidate) => React.ReactNode;\n /** Tiles per row at full width. Default 3. A narrow screen uses fewer. */\n columns?: 2 | 3 | 4;\n /** Named boxes to look at enlarged in every tile at once, as in `Compare`: chips, keys `q` `w` `e` `r` `y` `u`, nearest-neighbour while one is shown, Shift-drag to make another. */\n regions?: readonly Region[];\n /** Bind the zoom and full-screen keys on the window. Default true. */\n keys?: boolean;\n className?: string;\n};\n\nconst COLUMNS = { 2: \"sm:grid-cols-2\", 3: \"sm:grid-cols-2 lg:grid-cols-3\", 4: \"sm:grid-cols-2 lg:grid-cols-4\" } as const;\n\n/** Many pictures in a grid, zoomed and panned together, and full screen. */\nexport function CompareGrid({ label, items, blind, missing, actions, columns = 3, regions, keys = true, className }: CompareGridProps) {\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n const key = items.map((i) => i.media.src).join(\"|\");\n const [learned, setLearned] = React.useState<{ key: string; size: readonly [number, number] } | null>(null);\n const natural = items[0]?.media.size ?? (learned?.key === key ? learned.size : null);\n const aspect = natural ? natural[0] / natural[1] : 3 / 2;\n const first = React.useRef<HTMLDivElement>(null);\n const rg = useRegions({ regions, viewport, setViewport, frame: first, reset: key });\n const zoom = useZoom({ viewport, setViewport: rg.setViewport, frame: first, natural });\n const shortcuts = [...rg.shortcuts, ...zoomShortcuts(zoom, full, setFull)];\n useHotkeys(shortcuts, { enabled: keys });\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Zoom\" className=\"items-center gap-2\">\n <ZoomControls viewport={viewport} zoom={zoom} natural={natural} />\n <ToolbarSeparator />\n <FullscreenButton full={full} setFull={setFull} />\n </Toolbar>\n <RegionChips state={rg} />\n <div className={cn(\"grid gap-3\", COLUMNS[columns])}>\n {items.map((c, i) => (\n <figure key={c.id} className=\"grid content-start gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame viewport={viewport} setViewport={rg.setViewport} onBox={rg.add} outline={rg.peek} aspect={aspect} label={blind ? `Picture ${c.label}` : c.label} ref={i === 0 ? first : undefined}>\n <Picture c={c} blind={blind} missing={missing} pixelated={rg.active !== null} onNatural={i === 0 ? (w, h) => setLearned({ key, size: [w, h] }) : undefined} />\n </ViewportFrame>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions(c)}</div>}\n </figure>\n ))}\n </div>\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n","import * as React from \"react\";\nimport { useMove, mergeProps } from \"react-aria\";\nimport {\n PanelBottomClose,\n PanelBottomOpen,\n PanelLeftClose,\n PanelLeftOpen,\n PanelRightClose,\n PanelRightOpen,\n PanelTopClose,\n PanelTopOpen,\n} from \"lucide-react\";\nimport { IconButton } from \"./button\";\nimport { cn } from \"../lib/utils\";\n\n// A screen that is a workspace of panes: a stage in the middle, side panels, a bottom panel, a bar\n// across the top (strata-react issue #68, from strata-vid; ux-research components.md §3.20). It is\n// for tools (editors, IDE-style screens, mail with a reading pane), where the person sizes the\n// screen to the job and the same screen stays on view together. `AppShell` is for moving between\n// screens; this is for one screen with many regions.\n//\n// Shape: `<Workspace label state>` holds `<Split direction>`s, which hold `<Pane>`s and other\n// `<Split>`s. A pane with `grow` takes what is left; any other pane has a size the person sets.\n// Between a fixed pane and its neighbour sits a separator that controls the fixed one.\n//\n// - Panes are regions. Each is a `section` named by its own header, so a screen-reader user can\n// move between them by landmark, and every pane in an app has the same header: its name, the\n// few `actions` it owns, and a collapse button. A pane is a region, never a card (patterns.md §2).\n// - The separator is the window-splitter pattern: `role=\"separator\"` with `aria-valuenow`, `-min`\n// and `-max`, in the tab order. Arrow keys move it by 10px (Shift: 50), Home and End go to the\n// limits, Enter or a double-click restores the default size. Pointer drag, touch and the arrow\n// keys are React Aria's `useMove`.\n// - Limits: a pane never goes under its `min` or over its `max`, and the window shrinking takes\n// from the panes only down to their `min` (flex shrink with `min-width`), while the central pane\n// keeps its own minimum, so the stage never disappears. A drag stops where the central pane would\n// fall under its minimum.\n// - Collapse. A collapsible pane folds to a rail one control wide (beside the stage) or to its\n// header bar (above or below it), with a visible \"Show Library\" button, so there is always a way\n// back. `state.toggle(id)` does it from outside (a View menu, a shortcut). A collapsed pane's\n// body stays mounted but hidden, so what is in it (a timeline's scroll, a form) is kept.\n// - Remembered: `useWorkspaceState(\"editor\")` keeps sizes and collapsed panes in localStorage, in\n// try/catch (storage throws in private windows and with blocked site data), so the app writes no\n// storage code and a failure falls back to the defaults.\n// - Narrow: below `narrowBelow` (720px of the workspace's own width) side-by-side splits stack, and\n// their collapsible panes start folded to their header bars, one tap to open. That is a rule of the\n// component so every app does the same thing; it is not remembered, since it is the width and not\n// a choice.\n// - Density comes from the tokens: header and rail sizes are `--control-h`.\n// Motion: none. Resizing and folding are done many times a session (character.md §3).\n//\n// Checked for React Aria first: react-aria-components 1.22 has no splitter or panel part (its\n// `Separator` is a static rule, and `useSeparator` is for a non-focusable one), and the table's column\n// resizing is its own. So the layout is ours, on `useMove` for the interaction.\n\ntype Persisted = { sizes: Record<string, number>; collapsed: Record<string, boolean> };\n\nconst readPersisted = (key: string | undefined): Persisted => {\n const empty: Persisted = { sizes: {}, collapsed: {} };\n if (!key) return empty;\n try {\n const raw = JSON.parse(window.localStorage.getItem(`strata:workspace:${key}`) ?? \"null\") as Partial<Persisted> | null;\n if (!raw || typeof raw !== \"object\") return empty;\n const sizes: Record<string, number> = {};\n for (const [k, v] of Object.entries(raw.sizes ?? {})) if (typeof v === \"number\" && Number.isFinite(v)) sizes[k] = v;\n const collapsed: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(raw.collapsed ?? {})) if (typeof v === \"boolean\") collapsed[k] = v;\n return { sizes, collapsed };\n } catch {\n return empty;\n }\n};\n\n/** What `useWorkspaceState` returns: pass it to `Workspace`, and use it from outside (a menu, a shortcut) to fold or reset panes. */\nexport type WorkspaceState = {\n /** Whether a pane is folded now. `fallback` is the pane's `defaultCollapsed`. */\n isCollapsed: (id: string, fallback?: boolean) => boolean;\n setCollapsed: (id: string, collapsed: boolean) => void;\n /** Folds an open pane, opens a folded one. */\n toggle: (id: string) => void;\n /** Forgets every size and fold, back to the defaults. */\n reset: () => void;\n /** @internal */\n sizeOf: (id: string) => number | undefined;\n /** @internal */\n setSize: (id: string, size: number | null) => void;\n /** @internal */\n register: (id: string, defaultCollapsed: boolean) => void;\n /** @internal */\n narrow: boolean;\n /** @internal */\n setNarrow: (narrow: boolean) => void;\n};\n\n/** The sizes and folded panes of a `Workspace`; with `persist`, remembered in localStorage under that name. */\nexport function useWorkspaceState(persist?: string): WorkspaceState {\n const [saved, setSaved] = React.useState<Persisted>(() => readPersisted(persist));\n const [narrow, setNarrow] = React.useState(false);\n const [narrowOpen, setNarrowOpen] = React.useState<Record<string, boolean>>({});\n // Each pane's `defaultCollapsed`, so a toggle from outside (a View menu) acts on what is on screen.\n const defaults = React.useRef(new Map<string, boolean>());\n\n React.useEffect(() => {\n if (!persist) return;\n try {\n window.localStorage.setItem(`strata:workspace:${persist}`, JSON.stringify(saved));\n } catch {\n // Storage is a convenience; a workspace that cannot remember still works.\n }\n }, [persist, saved]);\n\n return React.useMemo<WorkspaceState>(() => {\n const isCollapsed = (id: string, fallback = defaults.current.get(id) ?? false) => (narrow ? !narrowOpen[id] : (saved.collapsed[id] ?? fallback));\n const setCollapsed = (id: string, collapsed: boolean) => {\n if (narrow) setNarrowOpen((o) => ({ ...o, [id]: !collapsed }));\n else setSaved((s) => ({ ...s, collapsed: { ...s.collapsed, [id]: collapsed } }));\n };\n return {\n isCollapsed,\n setCollapsed,\n toggle: (id) => setCollapsed(id, !isCollapsed(id)),\n reset: () => setSaved({ sizes: {}, collapsed: {} }),\n sizeOf: (id) => saved.sizes[id],\n setSize: (id, size) =>\n setSaved((s) => {\n const sizes = { ...s.sizes };\n if (size === null) delete sizes[id];\n else sizes[id] = Math.round(size);\n return { ...s, sizes };\n }),\n register: (id, defaultCollapsed) => void defaults.current.set(id, defaultCollapsed),\n narrow,\n setNarrow,\n };\n }, [saved, narrow, narrowOpen]);\n}\n\nconst StateContext = React.createContext<WorkspaceState | null>(null);\nconst useState_ = () => {\n const state = React.useContext(StateContext);\n if (!state) throw new Error(\"strata-react: a Pane or Split must be inside a Workspace.\");\n return state;\n};\n\ntype Slot = { direction: \"row\" | \"column\"; edge: \"start\" | \"end\" | \"only\"; stacked: boolean };\nconst SlotContext = React.createContext<Slot>({ direction: \"row\", edge: \"only\", stacked: false });\n\n/** The workspace: a labelled region that holds the splits and panes, and stacks them when narrow. */\nexport function Workspace({\n label,\n state,\n narrowBelow = 720,\n className,\n children,\n}: {\n label: string;\n state: WorkspaceState;\n /** Stack side-by-side splits when the workspace is narrower than this many pixels. Default 720. */\n narrowBelow?: number;\n className?: string;\n children: React.ReactNode;\n}) {\n const ref = React.useRef<HTMLDivElement>(null);\n const { setNarrow } = state;\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n const measure = () => {\n const width = el.getBoundingClientRect().width;\n setNarrow(width > 0 && width < narrowBelow);\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(el);\n return () => observer.disconnect();\n }, [narrowBelow, setNarrow]);\n\n return (\n <StateContext.Provider value={state}>\n <div ref={ref} role=\"group\" aria-label={label} className={cn(\"flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background\", className)}>\n {children}\n </div>\n </StateContext.Provider>\n );\n}\n\n/** What a `Pane` is, for the split that lays it out. */\nexport type PaneProps = {\n /** Identifies the pane in the remembered state: unique in the workspace. */\n id: string;\n /** The pane's name, in its header and as its landmark: \"Library\", \"Inspector\". */\n name: string;\n /** Takes the space the fixed panes leave. One per split (a nested `Split` always does). */\n grow?: boolean;\n /** Starting size in pixels (width beside the stage, height above or below it). Default 280. */\n size?: number;\n /** Smallest size in pixels. Default 160; for a growing pane, the least it keeps (default 240 wide, 120 high). */\n min?: number;\n /** Largest size in pixels. Default none. */\n max?: number;\n /** Shows a collapse button in the header and lets the pane fold to a rail or its header. */\n collapsible?: boolean;\n /** Starts folded until the person opens it. */\n defaultCollapsed?: boolean;\n /** The pane's few actions, drawn in its header before the collapse button. */\n actions?: React.ReactNode;\n className?: string;\n children?: React.ReactNode;\n};\n\nconst iconsFor = (direction: \"row\" | \"column\", edge: Slot[\"edge\"], stacked: boolean) => {\n if (stacked || direction === \"column\") return edge === \"start\" ? [PanelTopClose, PanelTopOpen] : [PanelBottomClose, PanelBottomOpen];\n return edge === \"end\" ? [PanelRightClose, PanelRightOpen] : [PanelLeftClose, PanelLeftOpen];\n};\n\n/** A region of a workspace with a consistent header (name, actions, fold button) and a body that scrolls. */\nexport function Pane({ id, name, grow, size = 280, min, max, collapsible, defaultCollapsed, actions, className, children }: PaneProps) {\n const state = useState_();\n const { direction, edge, stacked } = React.useContext(SlotContext);\n const headingId = React.useId();\n const { register } = state;\n React.useLayoutEffect(() => register(id, Boolean(defaultCollapsed)), [register, id, defaultCollapsed]);\n const folded = Boolean(collapsible) && state.isCollapsed(id, Boolean(defaultCollapsed));\n const rail = folded && direction === \"row\" && !stacked;\n const least = min ?? (grow ? (direction === \"row\" ? 240 : 120) : 160);\n const current = state.sizeOf(id) ?? size;\n const [closeIcon, openIcon] = iconsFor(direction, edge, stacked);\n\n const style: React.CSSProperties = grow\n ? { flex: \"1 1 0%\", [direction === \"row\" ? \"minWidth\" : \"minHeight\"]: least }\n : folded\n ? { flex: \"0 0 auto\" }\n : stacked\n ? { flex: \"0 1 auto\", maxHeight: \"50%\" }\n : {\n flex: `0 1 ${Math.max(least, Math.min(current, max ?? Infinity))}px`,\n [direction === \"row\" ? \"minWidth\" : \"minHeight\"]: least,\n ...(max ? { [direction === \"row\" ? \"maxWidth\" : \"maxHeight\"]: max } : {}),\n };\n\n return (\n <section\n id={`pane-${id}`}\n aria-labelledby={headingId}\n data-pane={id}\n data-collapsed={folded || undefined}\n data-grow={grow || undefined}\n data-min={grow ? least : undefined}\n data-size={grow || folded ? undefined : current}\n style={style}\n className={cn(\"flex min-h-0 min-w-0 flex-col overflow-hidden bg-background\", rail && cn(\"w-(--control-h) items-center\", edge === \"end\" ? \"border-l border-border\" : \"border-r border-border\"), className)}\n >\n <header className={cn(\"flex shrink-0 items-center gap-1 pl-3 pr-1\", rail ? \"h-auto flex-col py-1 pl-1\" : \"h-(--control-h) border-b border-border\")}>\n <h2 id={headingId} className={cn(\"type-label min-w-0 flex-1 truncate\", rail && \"sr-only\")}>\n {name}\n </h2>\n {!folded && actions}\n {collapsible && (\n <IconButton\n size=\"sm\"\n icon={folded ? openIcon : closeIcon}\n label={folded ? `Show ${name}` : `Hide ${name}`}\n aria-expanded={!folded}\n aria-controls={`pane-body-${id}`}\n onPress={() => state.toggle(id)}\n />\n )}\n </header>\n <div id={`pane-body-${id}`} hidden={folded} className=\"min-h-0 min-w-0 flex-1 overflow-auto\">\n {children}\n </div>\n </section>\n );\n}\n\ntype PaneElement = React.ReactElement<PaneProps>;\nconst isPane = (c: React.ReactNode): c is PaneElement => React.isValidElement(c) && c.type === Pane;\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(n, lo), hi);\n\nfunction Separator({\n pane,\n direction,\n sign,\n container,\n}: {\n pane: PaneProps;\n direction: \"row\" | \"column\";\n /** +1 when the controlled pane is before the separator, -1 when after. */\n sign: 1 | -1;\n container: React.RefObject<HTMLDivElement | null>;\n}) {\n const state = useState_();\n const [moving, setMoving] = React.useState(false);\n const min = pane.min ?? 160;\n const start = pane.size ?? 280;\n const size = state.sizeOf(pane.id) ?? start;\n const latest = React.useRef(size);\n latest.current = size;\n\n // A window smaller than the layout squeezes a pane under its saved size (flex shrink). Resizing and\n // the value reported start from what is drawn, or the next step would jump. Only where the layout\n // has been measured (jsdom has none).\n const measure = () => {\n const kids = Array.from(container.current?.children ?? []) as HTMLElement[];\n const own = kids.find((el) => el.dataset.pane === pane.id);\n return own ? Math.round(own.getBoundingClientRect()[direction === \"row\" ? \"width\" : \"height\"]) : 0;\n };\n const current = () => {\n const drawn = measure();\n return drawn > 0 && drawn < latest.current ? drawn : latest.current;\n };\n const [drawn, setDrawn] = React.useState(0);\n // A passive effect: the split's ref is attached after its children's layout effects have run.\n React.useEffect(() => {\n const root = container.current;\n if (!root || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => setDrawn(measure()));\n observer.observe(root);\n setDrawn(measure());\n return () => observer.disconnect();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [size, direction]);\n const shown = drawn > 0 && drawn < size ? drawn : size;\n\n // How far the controlled pane can grow before the stage falls under its own minimum. Only when the\n // layout has been measured (jsdom has none), and never under `min`.\n const room = () => {\n const root = container.current;\n const kids = Array.from(root?.children ?? []) as HTMLElement[];\n const own = kids.find((el) => el.dataset.pane === pane.id);\n const stage = kids.find((el) => el.dataset.grow !== undefined || el.dataset.split !== undefined);\n if (!own || !stage) return Infinity;\n const dim = direction === \"row\" ? \"width\" : \"height\";\n const stageSize = stage.getBoundingClientRect()[dim];\n if (stageSize <= 0) return Infinity;\n const stageMin = Number(stage.dataset.min ?? 0);\n return own.getBoundingClientRect()[dim] + stageSize - stageMin;\n };\n const upper = () => Math.max(min, Math.min(pane.max ?? Infinity, room()));\n const apply = (next: number) => state.setSize(pane.id, clamp(next, min, upper()));\n\n const { moveProps } = useMove({\n onMoveStart: () => setMoving(true),\n onMove: ({ deltaX, deltaY, pointerType, shiftKey }) => {\n const delta = (direction === \"row\" ? deltaX : deltaY) * (pointerType === \"keyboard\" ? (shiftKey ? 50 : 10) : 1);\n if (!delta) return;\n const next = clamp(current() + sign * delta, min, upper());\n latest.current = next;\n apply(next);\n },\n onMoveEnd: () => setMoving(false),\n });\n\n const restore = () => state.setSize(pane.id, null);\n const keys = {\n onKeyDown: (e: React.KeyboardEvent) => {\n if (e.key === \"Home\") apply(min);\n else if (e.key === \"End\") apply(upper());\n else if (e.key === \"Enter\") restore();\n else return;\n e.preventDefault();\n },\n onDoubleClick: restore,\n };\n\n const vertical = direction === \"row\";\n return (\n <div\n role=\"separator\"\n tabIndex={0}\n aria-orientation={vertical ? \"vertical\" : \"horizontal\"}\n aria-label={`Resize ${pane.name}`}\n aria-controls={`pane-${pane.id}`}\n aria-valuenow={Math.round(shown)}\n aria-valuemin={min}\n aria-valuemax={Number.isFinite(pane.max ?? Infinity) ? pane.max : undefined}\n data-moving={moving || undefined}\n {...mergeProps(moveProps, keys)}\n className={cn(\n \"relative shrink-0 touch-none bg-border transition-state hover:bg-primary focus-visible:bg-primary data-[moving]:bg-primary\",\n vertical ? \"w-px cursor-col-resize before:absolute before:inset-y-0 before:-inset-x-1\" : \"h-px cursor-row-resize before:absolute before:inset-x-0 before:-inset-y-1\",\n \"pointer-coarse:before:-inset-x-2\",\n )}\n />\n );\n}\n\n/** Lays its children out in a row or a column, with a separator between a fixed pane and its neighbour. A nested split takes the space the fixed panes leave. */\nexport function Split({ direction, className, children }: { direction: \"row\" | \"column\"; className?: string; children: React.ReactNode }) {\n const state = useState_();\n const ref = React.useRef<HTMLDivElement>(null);\n const stacked = direction === \"row\" && state.narrow;\n const effective = stacked ? \"column\" : direction;\n const items = React.Children.toArray(children);\n const slotted = (c: React.ReactNode) => isPane(c) || (React.isValidElement(c) && c.type === Split);\n const grows = (c: React.ReactNode) => (isPane(c) ? Boolean(c.props.grow) : true);\n\n const out: React.ReactNode[] = [];\n items.forEach((child, i) => {\n const growIndex = items.findIndex((c) => slotted(c) && grows(c));\n const edge: Slot[\"edge\"] = growIndex < 0 ? \"only\" : i < growIndex ? \"start\" : i > growIndex ? \"end\" : \"only\";\n out.push(\n <SlotContext.Provider key={React.isValidElement(child) && child.key != null ? child.key : i} value={{ direction: effective, edge, stacked }}>\n {child}\n </SlotContext.Provider>,\n );\n const next = items[i + 1];\n if (next === undefined || !slotted(child) || !slotted(next)) return;\n const fixed = (c: React.ReactNode) => isPane(c) && !c.props.grow && !(c.props.collapsible && state.isCollapsed(c.props.id, c.props.defaultCollapsed));\n const before = fixed(child);\n const after = fixed(next);\n if (stacked || (!before && !after)) return;\n const controlled = (before ? child : next) as PaneElement;\n out.push(<Separator key={`sep-${i}`} pane={controlled.props} direction={effective} sign={before ? 1 : -1} container={ref} />);\n });\n\n const growPane = items.find((c): c is PaneElement => isPane(c) && Boolean(c.props.grow));\n return (\n <div\n ref={ref}\n data-split={direction}\n data-min={growPane ? (growPane.props.min ?? (direction === \"row\" ? 240 : 120)) : undefined}\n className={cn(\"flex min-h-0 min-w-0 flex-1\", effective === \"row\" ? \"flex-row\" : \"flex-col\", className)}\n >\n {out}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Redo2, Undo2 } from \"lucide-react\";\nimport type { Command } from \"./commands\";\n\n// Undo and redo across a whole editing session (components.md §3.17; strata-react issue #81, from\n// strata-vid). `useUndoable` is the other half: one removal, a few seconds to take it back, then\n// it commits to a server. Use that for a row or an item that leaves a list; use this for a\n// document the person keeps editing, where every change can be walked back for as long as the\n// session lasts. A removal inside a document is a step here, not an `UndoBar` message.\n//\n// The model is the smallest one that does not care what the app's store is: a step is a name and\n// two functions, `undo` and `redo`. An app on a patch store pushes patches, one on snapshots pushes\n// the old and new value (`useHistoryState` does exactly that for plain React state), one on a\n// command pattern pushes its commands. The history never reads or holds the document.\n//\n// - A step is named by the phrase that follows the verb: \"move clip\" gives \"Undo move clip\" and\n// \"Redo move clip\". A person can tell what Undo will do before pressing it (Photoshop and Figma\n// say it; a bare \"Undo\" does not).\n// - A continuous change is one step. `begin(label)` returns `end`: every step pushed in between\n// becomes one, so a drag undoes in one press. For a change that arrives as many events (a slider)\n// pass the same `key` on each push: consecutive pushes with one key, with no undo between them,\n// merge into one step.\n// - A new step after an undo drops what could have been redone (the usual rule); `limit` drops the\n// oldest steps, and `atLimit` says it is happening so the app can say so.\n// - `commands` is Undo and Redo as `Command`s, with their label, shortcut and disabled reason, so a\n// menu, a toolbar button and the key handler (`useCommands`) all read the same object. Chords are\n// Mod+Z, and Mod+Shift+Z or Mod+Y for Redo. They do not fire in a text field, which keeps its own\n// undo: this history is the document's.\n// Motion: none. Undo is used 100+ times a day, so nothing moves.\n//\n// Checked: React Aria has no history part and no hook for one (react-stately's `useUndo` does not\n// exist; its `useControlledState` is for controlled values only), so this is our own.\n\n/** One undoable step. `label` is the phrase after the verb (\"move clip\"); `undo` and `redo` must be inverses. */\nexport type HistoryStep = {\n label: string;\n undo: () => void;\n redo: () => void;\n /** Consecutive pushes with the same key merge into one step (a slider, a text drag). */\n key?: string;\n};\n\n/** Options for `useHistory`. */\nexport type HistoryOptions = {\n /** The most steps kept; the oldest is dropped past it. Default 100. */\n limit?: number;\n};\n\n/** What `useHistory` returns. */\nexport type History = {\n /** Records a step the app has just done. Clears what could have been redone. Inside `begin`/`end` it joins the group. */\n push: (step: HistoryStep) => void;\n /** Starts a group named `label`; every push until the returned `end()` is one step. Nested groups join the outer one. An empty group records nothing. */\n begin: (label: string) => () => void;\n /** `begin`, run a function, `end`. */\n group: <T>(label: string, run: () => T) => T;\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n /** The name of the step Undo would take back, or undefined. */\n undoLabel: string | undefined;\n /** The name of the step Redo would repeat, or undefined. */\n redoLabel: string | undefined;\n /** Names of the steps that can be undone, oldest first. */\n past: string[];\n /** Names of the steps that can be redone, next first. */\n future: string[];\n /** The history holds `limit` steps, so the next push drops the oldest. */\n atLimit: boolean;\n /** Forgets every step (a document was opened or saved to a new place). */\n clear: () => void;\n /** Undo then Redo as commands: \"Undo move clip\", disabled with \"Nothing to undo\". Pass to `useCommands` and a `Menu`. */\n commands: [undo: Command, redo: Command];\n};\n\nconst compose = (older: HistoryStep, newer: HistoryStep): HistoryStep => ({\n label: older.label,\n key: older.key,\n undo: () => {\n newer.undo();\n older.undo();\n },\n redo: () => {\n older.redo();\n newer.redo();\n },\n});\n\n/** A history of named, undoable steps with grouping, a limit, and Undo and Redo as commands. */\nexport function useHistory({ limit = 100 }: HistoryOptions = {}): History {\n const store = React.useRef({ past: [] as HistoryStep[], future: [] as HistoryStep[], open: [] as HistoryStep[][], merge: false });\n const [version, bump] = React.useReducer((n: number) => n + 1, 0);\n const max = Math.max(1, limit);\n\n const api = React.useMemo(() => {\n const s = store.current;\n const record = (step: HistoryStep) => {\n const last = s.past[s.past.length - 1];\n if (s.merge && step.key && last && last.key === step.key) s.past[s.past.length - 1] = compose(last, step);\n else {\n s.past.push(step);\n if (s.past.length > max) s.past.splice(0, s.past.length - max);\n }\n s.future = [];\n s.merge = Boolean(step.key);\n bump();\n };\n const push = (step: HistoryStep) => {\n const group = s.open[s.open.length - 1];\n if (group) group.push(step);\n else record(step);\n };\n const begin = (label: string) => {\n const steps: HistoryStep[] = [];\n s.open.push(steps);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n s.open.pop();\n if (!steps.length) return;\n const grouped: HistoryStep = {\n label,\n undo: () => [...steps].reverse().forEach((x) => x.undo()),\n redo: () => steps.forEach((x) => x.redo()),\n };\n push(grouped);\n };\n };\n return {\n push,\n begin,\n group: <T,>(label: string, run: () => T): T => {\n const end = begin(label);\n try {\n return run();\n } finally {\n end();\n }\n },\n undo: () => {\n if (s.open.length) return;\n const step = s.past.pop();\n if (!step) return;\n step.undo();\n s.future.unshift(step);\n s.merge = false;\n bump();\n },\n redo: () => {\n if (s.open.length) return;\n const step = s.future.shift();\n if (!step) return;\n step.redo();\n s.past.push(step);\n s.merge = false;\n bump();\n },\n clear: () => {\n s.past = [];\n s.future = [];\n s.merge = false;\n bump();\n },\n };\n }, [max]);\n\n return React.useMemo(() => {\n const { past, future } = store.current;\n const undoLabel = past[past.length - 1]?.label;\n const redoLabel = future[0]?.label;\n const commands: [Command, Command] = [\n {\n id: \"history.undo\",\n label: undoLabel ? `Undo ${undoLabel}` : \"Undo\",\n icon: Undo2,\n keys: [\"Mod+Z\"],\n disabled: undoLabel ? false : \"Nothing to undo\",\n run: api.undo,\n },\n {\n id: \"history.redo\",\n label: redoLabel ? `Redo ${redoLabel}` : \"Redo\",\n icon: Redo2,\n keys: [\"Mod+Shift+Z\", \"Mod+Y\"],\n disabled: redoLabel ? false : \"Nothing to redo\",\n run: api.redo,\n },\n ];\n return {\n ...api,\n canUndo: past.length > 0,\n canRedo: future.length > 0,\n undoLabel,\n redoLabel,\n past: past.map((x) => x.label),\n future: future.map((x) => x.label),\n atLimit: past.length >= max,\n commands,\n };\n // `version` is the change signal: the stacks live in a ref so a step can be pushed from an event handler or a store subscription.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [api, version, max]);\n}\n\n/** Options for `useHistoryState`. */\nexport type HistoryStateOptions = HistoryOptions;\n\n/** What `setValue` takes besides the new value. */\nexport type SetOptions = {\n /** Merges consecutive changes with this key into one step (a slider, a drag). */\n key?: string;\n};\n\n/**\n * React state with a history: `set(next, \"move clip\")` changes the value and records the step; Undo\n * and Redo put the old and new values back. For an app whose document is a plain value. An app on its\n * own store uses `useHistory` and pushes steps from its actions.\n */\nexport function useHistoryState<S>(initial: S | (() => S), options?: HistoryStateOptions) {\n const [value, setValue] = React.useState(initial);\n const latest = React.useRef(value);\n const history = useHistory(options);\n const { push } = history;\n\n const write = React.useCallback((next: S) => {\n latest.current = next;\n setValue(next);\n }, []);\n\n const set = React.useCallback(\n (next: S | ((previous: S) => S), label: string, { key }: SetOptions = {}) => {\n const before = latest.current;\n const after = typeof next === \"function\" ? (next as (previous: S) => S)(before) : next;\n if (Object.is(before, after)) return;\n write(after);\n push({ label, key, undo: () => write(before), redo: () => write(after) });\n },\n [push, write],\n );\n\n /** Replaces the value without a step and forgets the history (a document was opened). */\n const reset = React.useCallback(\n (next: S) => {\n write(next);\n history.clear();\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [write, history.clear],\n );\n\n return { value, set, reset, history };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\n\n// Whether a document's work is safe (components.md §3.17; strata-react issue #81, from strata-vid,\n// whose project saved itself with no sign on screen that it had, or had not).\n//\n// `useAutoSave` is the state machine and `SaveStatus` the sign. The states are the four a person\n// asks about: saved (and when), saving, unsaved changes, and not saved (and why, with a retry).\n// - The same verb through every state (\"Saving…\", \"Saved\", \"Not saved\", \"Try again\"), in place,\n// with the labels stacked in one grid cell so the sign is as wide as its longest and nothing\n// beside it moves (the `AsyncButton` technique). The `failed` reason is cut to that width and\n// shown whole in the announcement and as a tooltip title.\n// - A routine save is quiet: no toast, no tick animation, no announcement. A failed save is the bad\n// day, so it is announced politely, once per failure, saying what happened and what is still\n// safe (\"Not saved: the connection dropped. Your changes are still here.\"). The recovery after\n// it is announced too, so a person who heard the failure hears that it is over.\n// - The time is a clock time (`format.clock`), which does not go stale on screen the way \"2 minutes\n// ago\" does; nothing here ticks.\n// - Saves are debounced (`delayMs`, default 1500) and never overlap: edits made while a save runs\n// are saved after it, so the last write is always the latest value. `delayMs: null` is a document\n// with an explicit Save command: the state is `dirty` until `saveNow()`.\n// - A document that saves itself needs no `beforeunload` prompt except while a save is pending or\n// failed; `useLeaveGuard(state.status !== \"saved\")` is that, on only while there is something to\n// lose (patterns.md §6). A router blocker is the app's: it needs a data router.\n// Motion: none; the spinner turns only under `motion-safe`.\n//\n// Checked: React Aria has no save indicator or autosave part; its `ProgressBar` and live regions\n// are what a sign like this would sit on, and a plain status text is the right element.\n\n/** The state of a document's saving. */\nexport type SaveState =\n | { status: \"saved\"; /** When it last saved here; null for a document just opened. */ at: Date | null }\n | { status: \"dirty\" }\n | { status: \"saving\" }\n | { status: \"failed\"; /** What happened, in the product's words. */ reason?: string };\n\n/** Options for `useAutoSave`. */\nexport type AutoSaveOptions<V> = {\n /** The document's current value. Compared with what was last saved by `equals`. */\n value: V;\n /** Saves a value. Throw (or reject) to fail. */\n save: (value: V) => void | Promise<unknown>;\n /** Wait this long after the last change before saving. `null`: never on its own, only `saveNow()`. Default 1500. */\n delayMs?: number | null;\n /** Whether two values are the same document. Default `Object.is`. */\n equals?: (a: V, b: V) => boolean;\n /** Turns a thrown error into the sentence shown. Default `describeActionError`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useAutoSave` returns. */\nexport type AutoSave = {\n state: SaveState;\n /** Saves now (and is \"Try again\" after a failure). Resolves when the save has finished, failed or not. */\n saveNow: () => Promise<void>;\n};\n\n/** Saves `value` after changes settle, never two at once, and says where it stands. The document's first `value` counts as saved. */\nexport function useAutoSave<V>({ value, save, delayMs = 1500, equals = Object.is, describeError = describeActionError }: AutoSaveOptions<V>): AutoSave {\n const [state, setState] = React.useState<SaveState>({ status: \"saved\", at: null });\n const latest = React.useRef({ value, save, equals, describeError, delayMs });\n latest.current = { value, save, equals, describeError, delayMs };\n const saved = React.useRef(value);\n const savedAt = React.useRef<Date | null>(null);\n const running = React.useRef<Promise<void> | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n window.clearTimeout(timer.current);\n };\n }, []);\n\n const schedule = React.useCallback(() => {\n window.clearTimeout(timer.current);\n if (latest.current.delayMs === null) return;\n timer.current = window.setTimeout(() => void run(), latest.current.delayMs);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const run = React.useCallback((): Promise<void> => {\n window.clearTimeout(timer.current);\n if (running.current) return running.current;\n const current = latest.current.value;\n if (latest.current.equals(current, saved.current)) {\n setState((s) => (s.status === \"saved\" ? s : { status: \"saved\", at: new Date() }));\n return Promise.resolve();\n }\n setState({ status: \"saving\" });\n // `settled` covers a saver that throws before its first await: the catch and finally then run\n // inside this call, before `attempt` exists, and the lock must not be taken after that.\n let settled = false;\n const attempt = (async () => {\n try {\n await latest.current.save(current);\n saved.current = current;\n savedAt.current = new Date();\n if (!mounted.current) return;\n if (latest.current.equals(latest.current.value, current)) setState({ status: \"saved\", at: savedAt.current });\n else {\n setState({ status: \"dirty\" });\n schedule();\n }\n } catch (error) {\n if (mounted.current) setState({ status: \"failed\", reason: latest.current.describeError(error) });\n } finally {\n settled = true;\n running.current = null;\n }\n })();\n if (!settled) running.current = attempt;\n return attempt;\n }, [schedule]);\n\n // A change: unsaved until it is saved. A failed state stays failed (the person has not been\n // told it is fine), and a save already running picks the change up when it ends.\n React.useEffect(() => {\n if (latest.current.equals(value, saved.current)) {\n // Edited back to what is saved: nothing to lose, so the sign says so (and the leave guard goes off).\n if (!running.current) {\n window.clearTimeout(timer.current);\n setState((s) => (s.status === \"dirty\" || s.status === \"failed\" ? { status: \"saved\", at: savedAt.current } : s));\n }\n return;\n }\n if (!running.current) setState((s) => (s.status === \"failed\" ? s : { status: \"dirty\" }));\n if (!running.current) schedule();\n }, [value, schedule]);\n\n return { state, saveNow: run };\n}\n\n/** Asks the browser to confirm before the page is closed or reloaded, while `active`. Off when there is nothing to lose. */\nexport function useLeaveGuard(active: boolean) {\n React.useEffect(() => {\n if (!active) return;\n const onBeforeUnload = (e: BeforeUnloadEvent) => {\n e.preventDefault();\n e.returnValue = \"\";\n };\n window.addEventListener(\"beforeunload\", onBeforeUnload);\n return () => window.removeEventListener(\"beforeunload\", onBeforeUnload);\n }, [active]);\n}\n\nconst labelOf = (s: SaveState) =>\n s.status === \"saved\" ? (s.at ? `Saved ${format.clock(s.at)}` : \"Saved\") : s.status === \"saving\" ? \"Saving…\" : s.status === \"dirty\" ? \"Unsaved changes\" : \"Not saved\";\n\n/**\n * The sign of whether the work is safe: \"Saved 10:42\", \"Saving…\", \"Unsaved changes\", or \"Not saved\"\n * with the reason and \"Try again\". Fixed width, so it never moves what is beside it. Announces a\n * failure, and the recovery from one, politely; a routine save is silent.\n */\nexport function SaveStatus({ state, onRetry, className }: { state: SaveState; onRetry: () => void; className?: string }) {\n const lastFailure = React.useRef(false);\n const failed = state.status === \"failed\";\n let announcement = \"\";\n if (failed) announcement = `Not saved${state.reason ? `: ${state.reason}` : \".\"} Your changes are still here.`;\n else if (lastFailure.current && state.status === \"saved\") announcement = \"Saved.\";\n React.useEffect(() => {\n if (failed) lastFailure.current = true;\n else if (state.status === \"saved\") lastFailure.current = false;\n }, [failed, state.status]);\n\n const Icon = { saved: Check, saving: LoaderCircle, dirty: null, failed: CircleAlert }[state.status];\n const current = labelOf(state);\n const all = [\"Saved 00:00\", \"Saving…\", \"Unsaved changes\", \"Not saved\"];\n const shown = failed && state.reason ? `Not saved: ${state.reason}` : current;\n\n return (\n <span\n data-status={state.status}\n title={failed ? shown : undefined}\n className={cn(\n \"inline-flex w-72 items-center justify-end gap-2 type-body-sm\",\n failed ? \"text-danger\" : \"text-muted-foreground\",\n className,\n )}\n >\n {Icon && <Icon aria-hidden className={cn(\"size-4 shrink-0\", state.status === \"saving\" && \"motion-safe:animate-spin\")} />}\n {failed ? (\n <span className=\"min-w-0 truncate\">{shown}</span>\n ) : (\n <span className=\"grid\">\n {all.map((l) => {\n const active = l === current || (l === \"Saved 00:00\" && state.status === \"saved\");\n return (\n <span key={l} aria-hidden={!active} className={active ? \"[grid-area:1/1] text-end tabular-nums\" : \"invisible [grid-area:1/1] text-end\"}>\n {active ? current : l}\n </span>\n );\n })}\n </span>\n )}\n {failed && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onRetry} className=\"shrink-0\">\n Try again\n </Button>\n )}\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </span>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,UAAU,EAAE,SAAS,MAAM,aAAa,OAAO,OAAO,OAAO,cAAc,UAAyB,CAAC,GAAG;CACtH,MAAM,CAAC,QAAQ,aAAa,MAAM,SAAS,KAAK;CAChD,MAAM,CAAC,IAAI,SAAS,MAAM,SAAyB,IAAI;CACvD,MAAM,OAAO,QAAQ;CACrB,MAAM,gBAAgB;EACpB,IAAI,MAAM;EACV,IAAI,CAAC,UAAU,CAAC,IAAI;GAClB,UAAU,KAAK;GACf;EACF;EACA,IAAI,OAAO,yBAAyB,aAAa;GAC/C,UAAU,WAAW;GACrB;EACF;EACA,MAAM,OAAO,GAAG,eAAe,QAAqB,sBAAsB,KAAK;EAC/E,MAAM,WAAW,IAAI,sBAAsB,YAAY,UAAU,QAAQ,QAAQ,SAAS,EAAE,CAAC,cAAc,GAAG;GAAE;GAAM;EAAW,CAAC;EAClI,SAAS,QAAQ,EAAE;EACnB,aAAa,SAAS,WAAW;CACnC,GAAG;EAAC;EAAQ;EAAI;EAAY;EAAM;CAAW,CAAC;CAC9C,OAAO;EAAE,KAAK;EAAO;CAAO;AAC9B;;;ACvCA,SAAgB,iBAA2B;CACz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