AI media harness for planning, generating, and editing locally
TypeScript
Add shortcut dispatcher, undo stack and range fill helpers
Bitti74ca37e6a692
diff --git a/src/lib/commands.test.tsx b/src/lib/commands.test.tsxnew file mode 100644index 0000000..5dcd8f4--- /dev/null+++ b/src/lib/commands.test.tsx@@ -0,0 +1,191 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render } from "@testing-library/react";+import { useRef } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ ariaKeyShortcuts, formatShortcut, isTextEntry, matchesCombo, parseCombo, registerShortcut,+ resetShortcutsForTests, useCommand, useShortcut, type ShortcutOptions,+} from "./commands";++afterEach(() => { cleanup(); resetShortcutsForTests(); });++const press = (key: string, init: Partial<KeyboardEventInit> = {}, target: EventTarget = document.body) =>+ fireEvent.keyDown(target, { key, bubbles: true, cancelable: true, ...init });++describe("combo parsing and matching", () => {+ it("parses modifiers and normalises key names", () => {+ expect(parseCombo("Ctrl+Shift+Z")).toMatchObject({ ctrl: true, shift: true, alt: false, key: "z" });+ expect(parseCombo("Alt+Left").key).toBe("ArrowLeft");+ expect(parseCombo("Del").key).toBe("Delete");+ expect(parseCombo("f2").key).toBe("F2");+ expect(parseCombo("Ctrl++").key).toBe("+");+ expect(parseCombo("Space").key).toBe(" ");+ });++ it("matches letters case-insensitively and modifiers exactly", () => {+ const base = { ctrlKey: false, altKey: false, shiftKey: false, metaKey: false };+ expect(matchesCombo({ ...base, key: "s", ctrlKey: true }, "Ctrl+S")).toBe(true);+ expect(matchesCombo({ ...base, key: "S", ctrlKey: true, shiftKey: true }, "Ctrl+S")).toBe(false);+ expect(matchesCombo({ ...base, key: "Z", ctrlKey: true, shiftKey: true }, "Ctrl+Shift+Z")).toBe(true);+ expect(matchesCombo({ ...base, key: "j" }, "J")).toBe(true);+ expect(matchesCombo({ ...base, key: "F10", shiftKey: true }, "Shift+F10")).toBe(true);+ expect(matchesCombo({ ...base, key: "F10" }, "Shift+F10")).toBe(false);+ expect(matchesCombo({ ...base, key: "ArrowLeft", altKey: true }, "Alt+ArrowLeft")).toBe(true);+ // A shifted symbol does not need "Shift" spelled out.+ expect(matchesCombo({ ...base, key: "?", shiftKey: true }, "?")).toBe(true);+ // Non-Latin layout: the physical code still identifies the letter.+ expect(matchesCombo({ ...base, key: "ы", code: "KeyS", ctrlKey: true }, "Ctrl+S")).toBe(true);+ });++ it("formats for display the way Windows does", () => {+ expect(formatShortcut("ctrl+shift+z")).toBe("Ctrl+Shift+Z");+ expect(formatShortcut("Alt+ArrowLeft")).toBe("Alt+Left");+ expect(formatShortcut("Delete")).toBe("Delete");+ expect(formatShortcut("Escape")).toBe("Esc");+ expect(formatShortcut("space")).toBe("Space");+ expect(formatShortcut(["Ctrl+Y", "Ctrl+Shift+Z"])).toBe("Ctrl+Y, Ctrl+Shift+Z");+ expect(formatShortcut(undefined)).toBe("");+ expect(ariaKeyShortcuts("Ctrl+S")).toBe("Control+S");+ });++ it("knows which elements take typed text", () => {+ const text = document.createElement("input");+ const box = document.createElement("input");+ box.type = "checkbox";+ const editable = document.createElement("div");+ editable.setAttribute("contenteditable", "true");+ const inner = document.createElement("span");+ editable.append(inner);+ expect(isTextEntry(text)).toBe(true);+ expect(isTextEntry(box)).toBe(false);+ expect(isTextEntry(document.createElement("textarea"))).toBe(true);+ expect(isTextEntry(document.createElement("select"))).toBe(true);+ expect(isTextEntry(inner)).toBe(true);+ expect(isTextEntry(document.createElement("button"))).toBe(false);+ });+});++function Bind({ combo, handler, options, withScope }: { combo: string | string[]; handler: () => void | boolean; options?: ShortcutOptions; withScope?: boolean }) {+ const scope = useRef<HTMLDivElement>(null);+ useShortcut(combo, handler, withScope ? { ...options, scope } : options);+ return <div ref={scope} data-testid={`scope-${String(combo)}`}><button>inside</button></div>;+}++describe("useShortcut", () => {+ it("fires on the window and prevents the default", () => {+ const save = vi.fn();+ render(<Bind combo="Ctrl+S" handler={save} />);+ const event = new KeyboardEvent("keydown", { key: "s", ctrlKey: true, bubbles: true, cancelable: true });+ document.body.dispatchEvent(event);+ expect(save).toHaveBeenCalledTimes(1);+ expect(event.defaultPrevented).toBe(true);+ });++ it("ignores presses from text entry unless allowed", () => {+ const remove = vi.fn();+ const undo = vi.fn();+ const view = render(<>+ <Bind combo="Delete" handler={remove} />+ <Bind combo="Ctrl+Z" handler={undo} options={{ allowInInput: true }} />+ <input aria-label="name" />+ </>);+ const input = view.getByLabelText("name");+ press("Delete", {}, input);+ expect(remove).not.toHaveBeenCalled();+ press("z", { ctrlKey: true }, input);+ expect(undo).toHaveBeenCalledTimes(1);+ });++ it("respects enabled and an already-handled event", () => {+ const handler = vi.fn();+ const view = render(<Bind combo="F2" handler={handler} options={{ enabled: false }} />);+ press("F2");+ expect(handler).not.toHaveBeenCalled();+ view.rerender(<Bind combo="F2" handler={handler} options={{ enabled: true }} />);+ const event = new KeyboardEvent("keydown", { key: "F2", bubbles: true, cancelable: true });+ event.preventDefault();+ document.body.dispatchEvent(event);+ expect(handler).not.toHaveBeenCalled();+ press("F2");+ expect(handler).toHaveBeenCalledTimes(1);+ });++ it("lets the innermost scope win, then the latest registration", () => {+ const outer = vi.fn();+ const inner = vi.fn();+ const later = vi.fn();+ const view = render(<>+ <Bind combo="Delete" handler={outer} />+ <Bind combo={["Delete"]} handler={inner} withScope />+ </>);+ const button = view.getAllByText("inside")[1];+ press("Delete", {}, button);+ expect(inner).toHaveBeenCalledTimes(1);+ expect(outer).not.toHaveBeenCalled();+ // Outside the scope only the global one is eligible.+ press("Delete");+ expect(outer).toHaveBeenCalledTimes(1);++ const stop = registerShortcut("Delete", later);+ press("Delete");+ expect(later).toHaveBeenCalledTimes(1);+ expect(outer).toHaveBeenCalledTimes(1);+ stop();+ press("Delete");+ expect(outer).toHaveBeenCalledTimes(2);+ });++ it("falls through when a handler declines", () => {+ const first = vi.fn();+ const decline = vi.fn(() => false as const);+ render(<Bind combo="J" handler={first} />);+ registerShortcut("J", decline);+ press("j");+ expect(decline).toHaveBeenCalled();+ expect(first).toHaveBeenCalledTimes(1);+ });++ it("mutes unscoped shortcuts behind a modal dialog", () => {+ const handler = vi.fn();+ const modalOk = vi.fn();+ render(<>+ <Bind combo="Ctrl+S" handler={handler} />+ <Bind combo="Ctrl+E" handler={modalOk} options={{ allowInModal: true }} />+ <div role="dialog" aria-modal="true" />+ </>);+ press("s", { ctrlKey: true });+ press("e", { ctrlKey: true });+ expect(handler).not.toHaveBeenCalled();+ expect(modalOk).toHaveBeenCalledTimes(1);+ });++ it("stops listening when unmounted", () => {+ const handler = vi.fn();+ const view = render(<Bind combo="F5" handler={handler} />);+ view.unmount();+ press("F5");+ expect(handler).not.toHaveBeenCalled();+ });+});++describe("useCommand", () => {+ function Save({ run, disabled }: { run: () => void; disabled?: boolean }) {+ const command = useCommand({ id: "save", label: "Save", shortcut: "Ctrl+S", disabled, run });+ return <button {...command.buttonProps}>{command.label}</button>;+ }++ it("binds the key and describes the button", () => {+ const run = vi.fn();+ const view = render(<Save run={run} />);+ const button = view.getByRole("button", { name: "Save" });+ expect(button).toHaveProperty("dataset.tooltipShortcut", "Ctrl+S");+ expect(button.getAttribute("aria-keyshortcuts")).toBe("Control+S");+ press("s", { ctrlKey: true });+ fireEvent.click(button);+ expect(run).toHaveBeenCalledTimes(2);+ view.rerender(<Save run={run} disabled />);+ press("s", { ctrlKey: true });+ expect(run).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/lib/commands.ts b/src/lib/commands.tsnew file mode 100644index 0000000..4f45471--- /dev/null+++ b/src/lib/commands.ts@@ -0,0 +1,359 @@+/* ============================================================================+ Keyboard commands — one window-level dispatcher for every shortcut.++ Screens used to each hang their own `keydown` listener on window, check+ `event.target` for text fields in slightly different ways, and fight over+ keys like Delete and Space. This module owns ONE bubble-phase listener on+ window and routes each key press to the best registered handler:++ useShortcut("Ctrl+S", save);+ useShortcut(["Delete", "Backspace"], removeSelection, { scope: timelineRef });+ useShortcut("F2", rename, { enabled: Boolean(selected) });++ Rules, in the order the dispatcher applies them:+ 1. A press whose default was already prevented (a menu, a dialog, a field+ that handled it) is left alone.+ 2. Presses inside a text entry (text-like input, textarea, select,+ contenteditable) are ignored unless the handler says `allowInInput`.+ 3. While a modal dialog is open (`[aria-modal="true"]`) only handlers+ scoped INSIDE that dialog, or that pass `allowInModal`, can fire.+ 4. Of the handlers that remain, the one whose `scope` element is the+ innermost ancestor of the focused element wins; unscoped handlers are+ the outermost. Ties go to the most recently registered handler.+ 5. A handler may return `false` to decline, and the next candidate runs.++ Combos are written the way Windows displays them: "Ctrl+Shift+Z", "F2",+ "Delete", "Shift+F10", "Alt+ArrowLeft", "J". Letters are case-insensitive.+ `formatShortcut` turns a combo into its display form for tooltips and menus.+ ========================================================================== */++import { useEffect, useRef, type RefObject } from "react";++export interface ParsedCombo {+ ctrl: boolean;+ alt: boolean;+ shift: boolean;+ meta: boolean;+ /** Normalised key: a lowercase letter/digit/symbol, or a KeyboardEvent.key name. */+ key: string;+ /** True when "Shift" was spelled out; symbols ("?") otherwise ignore shift. */+ shiftExplicit: boolean;+}++const KEY_ALIASES: Record<string, string> = {+ del: "Delete",+ delete: "Delete",+ esc: "Escape",+ escape: "Escape",+ space: " ",+ spacebar: " ",+ left: "ArrowLeft",+ right: "ArrowRight",+ up: "ArrowUp",+ down: "ArrowDown",+ arrowleft: "ArrowLeft",+ arrowright: "ArrowRight",+ arrowup: "ArrowUp",+ arrowdown: "ArrowDown",+ enter: "Enter",+ return: "Enter",+ tab: "Tab",+ backspace: "Backspace",+ home: "Home",+ end: "End",+ pageup: "PageUp",+ pagedown: "PageDown",+ insert: "Insert",+ ins: "Insert",+ contextmenu: "ContextMenu",+ apps: "ContextMenu",+ plus: "+",+};++function normaliseKey(raw: string): string {+ if (raw.length === 1) return raw.toLowerCase();+ const alias = KEY_ALIASES[raw.toLowerCase()];+ if (alias) return alias;+ if (/^f\d{1,2}$/i.test(raw)) return raw.toUpperCase();+ return raw;+}++const parsedCache = new Map<string, ParsedCombo>();++/** "Ctrl+Shift+Z" → { ctrl, shift, key: "z" }. A trailing "+" is the plus key. */+export function parseCombo(combo: string): ParsedCombo {+ const cached = parsedCache.get(combo);+ if (cached) return cached;+ const parts = combo.trim().split(/\s*\+\s*/);+ // "Ctrl++" splits into ["Ctrl", "", ""]: the key is "+".+ if (parts.length > 1 && parts.at(-1) === "") { parts.splice(-2, 2, "+"); }+ const parsed: ParsedCombo = { ctrl: false, alt: false, shift: false, meta: false, key: "", shiftExplicit: false };+ parts.forEach((part, index) => {+ const lower = part.toLowerCase();+ const last = index === parts.length - 1;+ if (!last && (lower === "ctrl" || lower === "control" || lower === "mod" || lower === "cmdorctrl")) parsed.ctrl = true;+ else if (!last && (lower === "alt" || lower === "option")) parsed.alt = true;+ else if (!last && lower === "shift") { parsed.shift = true; parsed.shiftExplicit = true; }+ else if (!last && (lower === "meta" || lower === "win" || lower === "cmd")) parsed.meta = true;+ else parsed.key = normaliseKey(part);+ });+ parsedCache.set(combo, parsed);+ return parsed;+}++interface KeyLike {+ key: string;+ code?: string;+ ctrlKey: boolean;+ altKey: boolean;+ shiftKey: boolean;+ metaKey: boolean;+}++/** Does this key press spell `combo`? */+export function matchesCombo(event: KeyLike, combo: string): boolean {+ const want = parseCombo(combo);+ if (!want.key) return false;+ if (event.ctrlKey !== want.ctrl || event.altKey !== want.alt || event.metaKey !== want.meta) return false;+ const key = normaliseKey(event.key === "Spacebar" ? " " : event.key);+ const isSymbol = want.key.length === 1 && !/[a-z0-9 ]/.test(want.key);+ if (!isSymbol || want.shiftExplicit) {+ if (event.shiftKey !== want.shift) return false;+ }+ if (key === want.key) return true;+ // Ctrl+Alt / AltGr and non-Latin layouts report a different `key` for a+ // letter; the physical code still says which letter it is.+ if (want.key.length === 1 && /[a-z0-9]/.test(want.key) && event.code) {+ return event.code === `Key${want.key.toUpperCase()}` || event.code === `Digit${want.key}`;+ }+ return false;+}++const DISPLAY_KEYS: Record<string, string> = {+ " ": "Space",+ ArrowLeft: "Left",+ ArrowRight: "Right",+ ArrowUp: "Up",+ ArrowDown: "Down",+ Escape: "Esc",+ ContextMenu: "Menu",+ PageUp: "PgUp",+ PageDown: "PgDn",+};++/** The Windows display form: "ctrl+shift+z" → "Ctrl+Shift+Z", "Alt+ArrowLeft" → "Alt+Left". */+export function formatShortcut(combo: string | readonly string[] | undefined | null): string {+ if (!combo) return "";+ if (typeof combo !== "string") return combo.map((one) => formatShortcut(one)).join(", ");+ const parsed = parseCombo(combo);+ const parts: string[] = [];+ if (parsed.ctrl) parts.push("Ctrl");+ if (parsed.meta) parts.push("Win");+ if (parsed.alt) parts.push("Alt");+ if (parsed.shift) parts.push("Shift");+ const key = DISPLAY_KEYS[parsed.key] ?? (parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key);+ parts.push(key);+ return parts.join("+");+}++/** The `aria-keyshortcuts` spelling ("Control+Shift+Z"). */+export function ariaKeyShortcuts(combo: string | readonly string[] | undefined | null): string | undefined {+ if (!combo) return undefined;+ const list = typeof combo === "string" ? [combo] : combo;+ return list.map((one) => {+ const parsed = parseCombo(one);+ const parts: string[] = [];+ if (parsed.ctrl) parts.push("Control");+ if (parsed.meta) parts.push("Meta");+ if (parsed.alt) parts.push("Alt");+ if (parsed.shift) parts.push("Shift");+ parts.push(parsed.key === " " ? "Space" : parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key);+ return parts.join("+");+ }).join(" ");+}++const NON_TEXT_INPUTS = new Set(["checkbox", "radio", "range", "button", "submit", "reset", "color", "file", "image"]);++/** True for elements that take typed text: shortcuts should leave them alone. */+export function isTextEntry(target: EventTarget | null): boolean {+ if (!(target instanceof Element)) return false;+ if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type);+ if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;+ if (target instanceof HTMLElement && target.isContentEditable) return true;+ return Boolean(target.closest('[contenteditable=""], [contenteditable="true"]'));+}++export interface ShortcutOptions {+ /** Default true. */+ enabled?: boolean;+ /** Fire even while the focus is in a text input, textarea, select or contenteditable. */+ allowInInput?: boolean;+ /** Only fire while focus is inside this element; innermost scope wins. */+ scope?: RefObject<HTMLElement | null> | HTMLElement | null;+ /** Default true: the event's default action is prevented when a handler runs. */+ preventDefault?: boolean;+ /** Fire even while a modal dialog is open (unscoped handlers are otherwise muted). */+ allowInModal?: boolean;+}++/** Return `false` to decline; the next matching handler then runs. */+export type ShortcutHandler = (event: KeyboardEvent) => void | boolean;++interface Registration {+ combos: readonly string[];+ handler: { current: ShortcutHandler };+ options: { current: ShortcutOptions };+ order: number;+}++const registrations = new Set<Registration>();+let orderCounter = 0;+let listening = false;++function scopeElement(options: ShortcutOptions): HTMLElement | null | undefined {+ const scope = options.scope;+ if (scope === undefined) return undefined;+ if (scope === null) return null;+ if (typeof HTMLElement !== "undefined" && scope instanceof HTMLElement) return scope;+ return (scope as RefObject<HTMLElement | null>).current;+}++function depth(element: Element): number {+ let count = 0;+ for (let node: Element | null = element; node; node = node.parentElement) count += 1;+ return count;+}++function dispatch(event: KeyboardEvent) {+ if (event.defaultPrevented || event.isComposing || event.key === "Process") return;+ const target = (event.target instanceof Element ? event.target : document.activeElement) ?? document.body;+ const inInput = isTextEntry(target);+ const modals = [...document.querySelectorAll<HTMLElement>('[aria-modal="true"]')];+ const modal = modals.at(-1);++ const candidates: { registration: Registration; rank: number }[] = [];+ for (const registration of registrations) {+ const options = registration.options.current;+ if (options.enabled === false) continue;+ if (inInput && !options.allowInInput) continue;+ if (!registration.combos.some((combo) => matchesCombo(event, combo))) continue;+ const scope = scopeElement(options);+ if (scope === null) continue; // a scoped handler whose element is gone+ if (scope && !scope.contains(target)) continue;+ if (modal && !options.allowInModal && !(scope && modal.contains(scope))) continue;+ candidates.push({ registration, rank: scope ? depth(scope) : 0 });+ }+ candidates.sort((a, b) => b.rank - a.rank || b.registration.order - a.registration.order);+ for (const { registration } of candidates) {+ const result = registration.handler.current(event);+ if (result === false) continue;+ if (registration.options.current.preventDefault !== false) event.preventDefault();+ return;+ }+}++function sync() {+ if (typeof window === "undefined") return;+ if (registrations.size && !listening) {+ window.addEventListener("keydown", dispatch, false);+ listening = true;+ } else if (!registrations.size && listening) {+ window.removeEventListener("keydown", dispatch, false);+ listening = false;+ }+}++/** Imperative registration, for code outside React. Returns the unregister function. */+export function registerShortcut(+ combo: string | readonly string[],+ handler: ShortcutHandler,+ options: ShortcutOptions = {},+): () => void {+ const registration: Registration = {+ combos: typeof combo === "string" ? [combo] : combo,+ handler: { current: handler },+ options: { current: options },+ order: (orderCounter += 1),+ };+ registrations.add(registration);+ sync();+ return () => {+ registrations.delete(registration);+ sync();+ };+}++/**+ * Bind a shortcut for as long as the component is mounted.+ * The handler and options may change every render without re-registering.+ */+export function useShortcut(+ combo: string | readonly string[],+ handler: ShortcutHandler,+ options: ShortcutOptions = {},+): void {+ const handlerRef = useRef(handler);+ const optionsRef = useRef(options);+ handlerRef.current = handler;+ optionsRef.current = options;+ const key = typeof combo === "string" ? combo : combo.join("\u0000");+ useEffect(() => {+ const registration: Registration = {+ combos: key.split("\u0000"),+ handler: handlerRef,+ options: optionsRef,+ order: (orderCounter += 1),+ };+ registrations.add(registration);+ sync();+ return () => {+ registrations.delete(registration);+ sync();+ };+ }, [key]);+}++/* --- Optional command registry ------------------------------------------------+ For surfaces that want a command's label, shortcut and action in one place+ (a menu item, a command bar button and the key all running the same thing):++ const save = useCommand({ id: "save", label: "Save", shortcut: "Ctrl+S", run: onSave });+ <CommandBarButton {...save.buttonProps} icon={<Save size={16} />} />++ It is a thin layer over useShortcut and needs no provider. */++export interface CommandSpec extends Omit<ShortcutOptions, "enabled"> {+ id: string;+ label: string;+ shortcut?: string | readonly string[];+ disabled?: boolean;+ run: () => void;+}++export function useCommand(spec: CommandSpec) {+ const { shortcut, disabled, run, label, id, ...options } = spec;+ useShortcut(shortcut ?? [], () => { run(); }, { ...options, enabled: Boolean(shortcut) && !disabled });+ const primary = typeof shortcut === "string" ? shortcut : shortcut?.[0];+ return {+ id,+ label,+ shortcut: primary,+ shortcutText: formatShortcut(primary),+ disabled: Boolean(disabled),+ run,+ buttonProps: {+ "aria-label": label,+ "aria-keyshortcuts": ariaKeyShortcuts(shortcut),+ "data-tooltip": label,+ "data-tooltip-shortcut": primary ? formatShortcut(primary) : undefined,+ disabled: Boolean(disabled),+ onClick: () => run(),+ },+ };+}++/** Test hook: drop every registration. */+export function resetShortcutsForTests() {+ registrations.clear();+ sync();+}diff --git a/src/lib/rangeFill.test.ts b/src/lib/rangeFill.test.tsnew file mode 100644index 0000000..10247cb--- /dev/null+++ b/src/lib/rangeFill.test.ts@@ -0,0 +1,91 @@+// @vitest-environment jsdom++import { afterEach, describe, expect, it } from "vitest";+import { installRangeFill, rangePercent, uninstallRangeFill } from "./rangeFill";++const range = (value: string, min = "", max = "") => {+ const input = document.createElement("input");+ input.type = "range";+ if (min) input.min = min;+ if (max) input.max = max;+ input.value = value;+ return input;+};++/* MutationObserver callbacks are microtasks. */+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++afterEach(() => {+ uninstallRangeFill(document);+ document.body.innerHTML = "";+});++describe("rangePercent", () => {+ it("maps the value into [min, max] and clamps", () => {+ expect(rangePercent(range("50"))).toBe("50%");+ expect(rangePercent(range("5", "0", "20"))).toBe("25%");+ expect(rangePercent(range("-1", "-2", "2"))).toBe("25%");+ const degenerate = range("1", "1", "1");+ expect(rangePercent(degenerate)).toBe("0%");+ });+});++describe("installRangeFill", () => {+ it("fills existing ranges, follows input events and new ranges, and uninstalls", async () => {+ const first = range("30");+ document.body.append(first);+ const stop = installRangeFill();+ expect(first.style.getPropertyValue("--p")).toBe("30%");++ first.value = "80";+ first.dispatchEvent(new Event("input", { bubbles: true }));+ expect(first.style.getPropertyValue("--p")).toBe("80%");++ const wrapper = document.createElement("div");+ const added = range("10", "0", "40");+ wrapper.append(added);+ document.body.append(wrapper);+ await flush();+ expect(added.style.getPropertyValue("--p")).toBe("25%");++ // A programmatic change that reaches the attribute, the way React writes a+ // controlled value: property first (no event fires), then the attribute.+ added.value = "20";+ added.setAttribute("value", "20");+ await flush();+ expect(added.style.getPropertyValue("--p")).toBe("50%");+ added.max = "80";+ await flush();+ expect(added.style.getPropertyValue("--p")).toBe("25%");++ // Installing twice is harmless and returns the same uninstall.+ expect(installRangeFill()).toBe(stop);+ stop();+ first.value = "10";+ first.dispatchEvent(new Event("input", { bubbles: true }));+ expect(first.style.getPropertyValue("--p")).toBe("80%");+ });++ it("leaves opted-out ranges and other inputs alone", () => {+ const own = range("50");+ own.dataset.rangeFill = "off";+ const text = document.createElement("input");+ document.body.append(own, text);+ installRangeFill();+ text.dispatchEvent(new Event("input", { bubbles: true }));+ expect(own.style.getPropertyValue("--p")).toBe("");+ expect(text.style.getPropertyValue("--p")).toBe("");+ });++ it("can be scoped to an element", () => {+ const host = document.createElement("section");+ const inside = range("40");+ const outside = range("60");+ host.append(inside);+ document.body.append(host, outside);+ const stop = installRangeFill(host);+ expect(inside.style.getPropertyValue("--p")).toBe("40%");+ expect(outside.style.getPropertyValue("--p")).toBe("");+ stop();+ });+});diff --git a/src/lib/rangeFill.ts b/src/lib/rangeFill.tsnew file mode 100644index 0000000..c6f72df--- /dev/null+++ b/src/lib/rangeFill.ts@@ -0,0 +1,86 @@+/* ============================================================================+ Range fill — the Fluent slider's filled track, for every slider at once.++ controls.css paints input[type="range"] with the accent up to `--p`, a+ percentage, because CSS cannot read an input's value. Rather than have each+ screen compute and set it, `installRangeFill()` (called once at startup)+ keeps `--p` current on every range under `root`:++ - an initial pass over the ranges already in the document,+ - `input` / `change` listeners (captured at the root) for user drags,+ - a MutationObserver for ranges added later and for value/min/max+ attribute changes (React mirrors a controlled input's value into the+ attribute, so programmatic changes are seen too).++ A range can opt out with `data-range-fill="off"` (a scrubber with its own+ look). `<Slider>` in src/components/ui sets `--p` itself as well; the two+ agree, so either can run first.+ ========================================================================== */++/** The value's position in [min, max] as a CSS percentage string. */+export function rangePercent(input: HTMLInputElement): string {+ const min = input.min === "" ? 0 : Number(input.min);+ const max = input.max === "" ? 100 : Number(input.max);+ const value = Number(input.value);+ if (!Number.isFinite(min) || !Number.isFinite(max) || !Number.isFinite(value) || max <= min) return "0%";+ const ratio = Math.min(1, Math.max(0, (value - min) / (max - min)));+ return `${Math.round(ratio * 10000) / 100}%`;+}++const isRange = (node: unknown): node is HTMLInputElement =>+ typeof HTMLInputElement !== "undefined" && node instanceof HTMLInputElement && node.type === "range";++/** Set `--p` on one range input (no-op for anything else or an opted-out range). */+export function updateRangeFill(input: Element): void {+ if (!isRange(input) || input.dataset.rangeFill === "off") return;+ const next = rangePercent(input);+ if (input.style.getPropertyValue("--p") !== next) input.style.setProperty("--p", next);+}++function sweep(node: ParentNode | Node) {+ if (isRange(node)) updateRangeFill(node);+ if ("querySelectorAll" in node) {+ for (const range of (node as ParentNode).querySelectorAll('input[type="range"]')) updateRangeFill(range);+ }+}++const installed = new WeakMap<Node, () => void>();++/**+ * Keep `--p` updated on every range under `root`. Idempotent per root.+ * Returns the uninstall function (also reachable via `uninstallRangeFill(root)`).+ */+export function installRangeFill(root: Document | Element = document): () => void {+ const existing = installed.get(root);+ if (existing) return existing;++ const onInput = (event: Event) => updateRangeFill(event.target as Element);+ root.addEventListener("input", onInput, true);+ root.addEventListener("change", onInput, true);++ let observer: MutationObserver | undefined;+ if (typeof MutationObserver !== "undefined") {+ observer = new MutationObserver((records) => {+ for (const record of records) {+ if (record.type === "attributes") updateRangeFill(record.target as Element);+ else for (const added of record.addedNodes) sweep(added);+ }+ });+ observer.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: ["value", "min", "max", "type"] });+ }+ sweep(root);++ const uninstall = () => {+ root.removeEventListener("input", onInput, true);+ root.removeEventListener("change", onInput, true);+ observer?.disconnect();+ installed.delete(root);+ };+ installed.set(root, uninstall);+ return uninstall;+}++/** Undo `installRangeFill(root)`. */+export function uninstallRangeFill(root: Document | Element = document): void {+ installed.get(root)?.();+}diff --git a/src/lib/undo.test.tsx b/src/lib/undo.test.tsxnew file mode 100644index 0000000..9e01441--- /dev/null+++ b/src/lib/undo.test.tsx@@ -0,0 +1,99 @@+// @vitest-environment jsdom++import { act, cleanup, render } from "@testing-library/react";+import { useState } from "react";+import { afterEach, describe, expect, it } from "vitest";+import { createUndoStack, useUndoStack, type UndoController } from "./undo";++afterEach(cleanup);++describe("createUndoStack", () => {+ it("undoes and redoes snapshots in order", () => {+ const stack = createUndoStack<number>();+ let value = 0;+ const set = (next: number) => { stack.record(value); value = next; };+ set(1); set(2); set(3);+ expect(stack.canUndo).toBe(true);+ value = stack.undo(value)!; expect(value).toBe(2);+ value = stack.undo(value)!; expect(value).toBe(1);+ expect(stack.canRedo).toBe(true);+ value = stack.redo(value)!; expect(value).toBe(2);+ set(9);+ expect(stack.canRedo).toBe(false);+ value = stack.undo(value)!; expect(value).toBe(2);+ value = stack.undo(value)!; expect(value).toBe(1);+ value = stack.undo(value)!; expect(value).toBe(0);+ expect(stack.undo(value)).toBeUndefined();+ });++ it("coalesces rapid edits with the same key and splits on seal, key or time", () => {+ let time = 0;+ const stack = createUndoStack<number>({ mergeWindowMs: 500, now: () => time });+ stack.record(0, "opacity"); time += 100;+ stack.record(1, "opacity"); time += 100;+ stack.record(2, "opacity");+ expect(stack.undoDepth).toBe(1);+ stack.record(3, "scale");+ expect(stack.undoDepth).toBe(2);+ time += 1000;+ stack.record(4, "scale");+ expect(stack.undoDepth).toBe(3);+ stack.seal();+ stack.record(5, "scale");+ expect(stack.undoDepth).toBe(4);+ // Unkeyed edits never merge.+ stack.record(6); stack.record(7);+ expect(stack.undoDepth).toBe(6);+ expect(stack.undo(8)).toBe(7);+ });++ it("drops the oldest steps past the limit and clears", () => {+ const stack = createUndoStack<number>({ limit: 3 });+ for (let i = 0; i < 5; i += 1) stack.record(i);+ expect(stack.undoDepth).toBe(3);+ expect(stack.undo(5)).toBe(4);+ expect(stack.undo(4)).toBe(3);+ expect(stack.undo(3)).toBe(2);+ expect(stack.undo(2)).toBeUndefined();+ stack.clear();+ expect(stack.canUndo || stack.canRedo).toBe(false);+ });++ it("notifies subscribers", () => {+ const stack = createUndoStack<number>();+ let calls = 0;+ const stop = stack.subscribe(() => { calls += 1; });+ stack.record(1);+ stack.undo(2);+ stop();+ stack.redo(1);+ expect(calls).toBe(2);+ });+});++describe("useUndoStack", () => {+ it("drives React state and re-renders canUndo/canRedo", () => {+ let history!: UndoController<string>;+ let value = "";+ function Editor() {+ const [text, setText] = useState("a");+ value = text;+ history = useUndoStack(text, setText);+ return <span>{history.canUndo ? "can undo" : "clean"}{history.canRedo ? " can redo" : ""}</span>;+ }+ const view = render(<Editor />);+ expect(view.container.textContent).toBe("clean");+ act(() => history.commit("b"));+ act(() => history.commit("c"));+ expect(value).toBe("c");+ expect(view.container.textContent).toBe("can undo");+ act(() => { history.undo(); });+ expect(value).toBe("b");+ expect(view.container.textContent).toBe("can undo can redo");+ act(() => { history.redo(); });+ expect(value).toBe("c");+ act(() => { history.undo(); history.undo(); });+ expect(value).toBe("a");+ expect(history.undo()).toBe(false);+ });+});diff --git a/src/lib/undo.ts b/src/lib/undo.tsnew file mode 100644index 0000000..dd5d46f--- /dev/null+++ b/src/lib/undo.ts@@ -0,0 +1,184 @@+/* ============================================================================+ Undo / redo — snapshot history with coalescing.++ The history stores whole snapshots of a value (a scene, a clip's settings,+ a project config). Snapshots of immutable state are cheap: unchanged+ branches are shared. Before a change, the CURRENT value is recorded; undo+ swaps the present for the most recent record and pushes the present onto+ the redo side.++ Rapid edits that carry the same `key` within `mergeWindowMs` coalesce into+ one step — dragging a slider or typing into a field is one undo, not two+ hundred. `seal()` ends a coalescing run explicitly (call it on pointerup or+ blur) so the next edit with the same key starts a new step.++ const history = createUndoStack<Scene>({ limit: 100, mergeWindowMs: 600 });+ history.record(scene, "opacity"); // before applying a change+ const previous = history.undo(scene); // → the snapshot to restore, or undefined++ In React, `useUndoStack(present, apply)` wraps the same thing:++ const history = useUndoStack(scene, setScene);+ history.commit(next, "opacity"); // record + apply+ history.undo(); history.redo(); history.canUndo;+ ========================================================================== */++import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";++export interface UndoOptions {+ /** Maximum undo steps kept (default 100). The oldest are dropped. */+ limit?: number;+ /** Edits with the same key within this many ms merge into one step (default 500; 0 disables). */+ mergeWindowMs?: number;+ /** Clock, for tests. */+ now?: () => number;+}++export interface UndoStack<T> {+ /** Save `current` as an undo step before it is replaced. Clears redo. */+ record(current: T, key?: string): void;+ /** Return the snapshot to restore, moving `current` onto the redo side. */+ undo(current: T): T | undefined;+ /** Return the snapshot to restore, moving `current` onto the undo side. */+ redo(current: T): T | undefined;+ /** End the current coalescing run. */+ seal(): void;+ clear(): void;+ readonly canUndo: boolean;+ readonly canRedo: boolean;+ readonly undoDepth: number;+ readonly redoDepth: number;+ /** Change notifications (for React / UI state). Returns the unsubscribe. */+ subscribe(listener: () => void): () => void;+ /** Bumps on every change; a cheap snapshot for useSyncExternalStore. */+ readonly version: number;+}++export function createUndoStack<T>(options: UndoOptions = {}): UndoStack<T> {+ const limit = Math.max(1, options.limit ?? 100);+ const mergeWindow = options.mergeWindowMs ?? 500;+ const now = options.now ?? (() => Date.now());+ const past: T[] = [];+ const future: T[] = [];+ let lastKey: string | undefined;+ let lastTime = -Infinity;+ let version = 0;+ const listeners = new Set<() => void>();+ const changed = () => {+ version += 1;+ for (const listener of listeners) listener();+ };++ return {+ record(current, key) {+ const time = now();+ const merge = key !== undefined && key === lastKey && mergeWindow > 0 && time - lastTime <= mergeWindow && past.length > 0;+ lastKey = key;+ lastTime = time;+ const hadFuture = future.length > 0;+ future.length = 0;+ if (merge) {+ // The earliest snapshot of the run is already on the stack.+ if (hadFuture) changed();+ return;+ }+ past.push(current);+ if (past.length > limit) past.splice(0, past.length - limit);+ changed();+ },+ undo(current) {+ const previous = past.pop();+ if (previous === undefined) return undefined;+ future.push(current);+ lastKey = undefined;+ changed();+ return previous;+ },+ redo(current) {+ const next = future.pop();+ if (next === undefined) return undefined;+ past.push(current);+ lastKey = undefined;+ changed();+ return next;+ },+ seal() {+ lastKey = undefined;+ },+ clear() {+ if (!past.length && !future.length) return;+ past.length = 0;+ future.length = 0;+ lastKey = undefined;+ changed();+ },+ get canUndo() { return past.length > 0; },+ get canRedo() { return future.length > 0; },+ get undoDepth() { return past.length; },+ get redoDepth() { return future.length; },+ get version() { return version; },+ subscribe(listener) {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+ },+ };+}++export interface UndoController<T> {+ /** Record the present and apply `next`. Same key within the merge window = one step. */+ commit(next: T, key?: string): void;+ /** Record the present without applying anything (the caller applies the change). */+ record(key?: string): void;+ undo(): boolean;+ redo(): boolean;+ seal(): void;+ clear(): void;+ canUndo: boolean;+ canRedo: boolean;+ stack: UndoStack<T>;+}++/**+ * React binding. `present` is the current value; `apply` replaces it (a state+ * setter works). The stack lives as long as the component.+ */+export function useUndoStack<T>(present: T, apply: (value: T) => void, options: UndoOptions = {}): UndoController<T> {+ const stackRef = useRef<UndoStack<T>>();+ if (!stackRef.current) stackRef.current = createUndoStack<T>(options);+ const stack = stackRef.current;+ const presentRef = useRef(present);+ presentRef.current = present;+ const applyRef = useRef(apply);+ applyRef.current = apply;++ useSyncExternalStore(stack.subscribe, () => stack.version, () => stack.version);++ const commit = useCallback((next: T, key?: string) => {+ stack.record(presentRef.current, key);+ presentRef.current = next;+ applyRef.current(next);+ }, [stack]);+ const record = useCallback((key?: string) => stack.record(presentRef.current, key), [stack]);+ const undo = useCallback(() => {+ const previous = stack.undo(presentRef.current);+ if (previous === undefined) return false;+ presentRef.current = previous;+ applyRef.current(previous);+ return true;+ }, [stack]);+ const redo = useCallback(() => {+ const next = stack.redo(presentRef.current);+ if (next === undefined) return false;+ presentRef.current = next;+ applyRef.current(next);+ return true;+ }, [stack]);+ const seal = useCallback(() => stack.seal(), [stack]);+ const clear = useCallback(() => stack.clear(), [stack]);++ const { canUndo, canRedo } = stack;+ return useMemo(+ () => ({ commit, record, undo, redo, seal, clear, canUndo, canRedo, stack }),+ [commit, record, undo, redo, seal, clear, canUndo, canRedo, stack],+ );+}