Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add shared Fluent component library and rebuild image menu on ContextMenu

Bittib9470b6534fe
diff --git a/src/components/ui/Chrome.tsx b/src/components/ui/Chrome.tsx
new file mode 100644
index 0000000..cebabfe
--- /dev/null
+++ b/src/components/ui/Chrome.tsx
@@ -0,0 +1,221 @@
+/* Window chrome pieces: CommandBar, PaneHeader, NavigationView (NavPane,
+ NavItem), TextField, StatusBar. */
+
+import {
+ forwardRef, useRef,
+ type ButtonHTMLAttributes, type ChangeEvent, type InputHTMLAttributes, type KeyboardEvent, type ReactNode, type Ref,
+} from "react";
+import { ariaKeyShortcuts, formatShortcut } from "../../lib/commands";
+import { InfoBadge, type InfoBadgeProps } from "./Controls";
+import { cx } from "./internal";
+
+/* --- CommandBar --------------------------------------------------------------------
+ A 40px row of 32px subtle buttons. role=toolbar; Left/Right move between
+ its buttons (every button stays in the Tab order too, which is what the
+ app's dense editors expect). No overflow menu. */
+
+export interface CommandBarProps {
+ children: ReactNode;
+ "aria-label"?: string;
+ className?: string;
+ /** Content pushed to the trailing edge. */
+ end?: ReactNode;
+}
+
+export function CommandBar({ children, end, className, ...aria }: CommandBarProps) {
+ const bar = useRef<HTMLDivElement>(null);
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
+ const target = event.target as HTMLElement;
+ if (target.closest("input, textarea, select, [role=combobox], [role=slider], [contenteditable=true]")) return;
+ const buttons = [...(bar.current?.querySelectorAll<HTMLButtonElement>(".ui-cmd:not(:disabled)") ?? [])];
+ const index = buttons.indexOf(target as HTMLButtonElement);
+ if (index < 0) return;
+ event.preventDefault();
+ buttons[(index + (event.key === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length]?.focus();
+ };
+ return (
+ <div ref={bar} role="toolbar" aria-label={aria["aria-label"]} className={cx("ui-command-bar", className)} onKeyDown={onKeyDown}>
+ <div className="ui-command-bar__primary">{children}</div>
+ {end && <div className="ui-command-bar__end">{end}</div>}
+ </div>
+ );
+}
+
+export interface CommandBarButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children"> {
+ icon?: ReactNode;
+ /** The accessible name and default tooltip. */
+ label: string;
+ /** Show the label as text next to the icon (default: icon only when there is an icon). */
+ showLabel?: boolean;
+ /** Tooltip text, when it should differ from the label. */
+ tooltip?: string;
+ /** A combo ("Ctrl+S"): shown in the tooltip and exposed as aria-keyshortcuts. It does not bind the key — use useShortcut. */
+ shortcut?: string;
+ /** Toggle buttons: sets aria-pressed and the checked look. */
+ pressed?: boolean;
+}
+
+export const CommandBarButton = forwardRef(function CommandBarButton(
+ { icon, label, showLabel, tooltip, shortcut, pressed, className, type = "button", ...rest }: CommandBarButtonProps,
+ ref: Ref<HTMLButtonElement>,
+) {
+ const withText = showLabel ?? !icon;
+ return (
+ <button
+ ref={ref}
+ type={type}
+ className={cx("ui-cmd", withText && "ui-cmd--labelled", pressed && "ui-cmd--pressed", className)}
+ aria-label={withText ? undefined : label}
+ aria-pressed={pressed}
+ aria-keyshortcuts={ariaKeyShortcuts(shortcut)}
+ data-tooltip={tooltip ?? (withText && !shortcut ? undefined : label)}
+ data-tooltip-shortcut={shortcut ? formatShortcut(shortcut) : undefined}
+ {...rest}
+ >
+ {icon && <span className="ui-cmd__icon" aria-hidden="true">{icon}</span>}
+ {withText && <span className="ui-cmd__label">{label}</span>}
+ </button>
+ );
+});
+
+export function CommandBarSeparator() {
+ return <span className="ui-command-bar__separator" role="separator" aria-orientation="vertical" />;
+}
+
+/* --- PaneHeader ------------------------------------------------------------------------
+ 32px, 12px semibold title, actions on the trailing edge. */
+
+export interface PaneHeaderProps {
+ title: ReactNode;
+ actions?: ReactNode;
+ /** Id for the title, so the pane can be aria-labelledby it. */
+ id?: string;
+ className?: string;
+ /** Heading level for the title (default 2). */
+ level?: 2 | 3 | 4;
+}
+
+export function PaneHeader({ title, actions, id, className, level = 2 }: PaneHeaderProps) {
+ const Heading = `h${level}` as "h2";
+ return (
+ <div className={cx("ui-pane-header", className)}>
+ <Heading id={id} className="ui-pane-header__title">{title}</Heading>
+ {actions && <div className="ui-pane-header__actions">{actions}</div>}
+ </div>
+ );
+}
+
+/* --- NavigationView ---------------------------------------------------------------------
+ NavPane is the left rail (a <nav>) with a footer slot for Settings; NavItem
+ is a 36px row with a 16px icon, a 3×16px accent pill when selected and an
+ optional InfoBadge. */
+
+export interface NavPaneProps {
+ children: ReactNode;
+ footer?: ReactNode;
+ header?: ReactNode;
+ "aria-label"?: string;
+ className?: string;
+ /** Icons only (48px rail). */
+ compact?: boolean;
+}
+
+export function NavPane({ children, footer, header, className, compact, ...aria }: NavPaneProps) {
+ return (
+ <nav aria-label={aria["aria-label"]} className={cx("ui-nav", compact && "ui-nav--compact", className)}>
+ {header && <div className="ui-nav__header">{header}</div>}
+ <div className="ui-nav__items">{children}</div>
+ {footer && <div className="ui-nav__footer">{footer}</div>}
+ </nav>
+ );
+}
+
+export interface NavItemProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children"> {
+ icon?: ReactNode;
+ label: ReactNode;
+ selected?: boolean;
+ /** A number, or `true` for a dot. */
+ badge?: number | boolean;
+ badgeSeverity?: InfoBadgeProps["severity"];
+ /** Accessible label for the badge ("3 running"). */
+ badgeLabel?: string;
+}
+
+export const NavItem = forwardRef(function NavItem(
+ { icon, label, selected, badge, badgeSeverity, badgeLabel, className, type = "button", ...rest }: NavItemProps,
+ ref: Ref<HTMLButtonElement>,
+) {
+ return (
+ <button
+ ref={ref}
+ type={type}
+ className={cx("ui-nav-item", selected && "ui-nav-item--selected", className)}
+ aria-current={selected ? "page" : undefined}
+ {...rest}
+ >
+ {icon && <span className="ui-nav-item__icon" aria-hidden="true">{icon}</span>}
+ <span className="ui-nav-item__label">{label}</span>
+ {badge !== undefined && badge !== false && (
+ <InfoBadge className="ui-nav-item__badge" value={typeof badge === "number" ? badge : undefined} severity={badgeSeverity} aria-label={badgeLabel} />
+ )}
+ </button>
+ );
+});
+
+/* --- TextField --------------------------------------------------------------------------
+ The Fluent TextBox as a composite: a 32px wrapper that draws the edge and
+ the 2px accent underline on focus, an optional 16px leading icon, the
+ borderless input, and optional trailing buttons (clear, reveal, browse). */
+
+export interface TextFieldProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "size"> {
+ value: string;
+ onChange: (value: string, event: ChangeEvent<HTMLInputElement>) => void;
+ icon?: ReactNode;
+ /** Buttons after the input; use className="ui-textfield__button". */
+ trailing?: ReactNode;
+ /** Wrapper class. */
+ className?: string;
+ inputClassName?: string;
+ inputRef?: Ref<HTMLInputElement>;
+ width?: number | string;
+}
+
+export function TextField({ value, onChange, icon, trailing, className, inputClassName, inputRef, width, disabled, ...rest }: TextFieldProps) {
+ return (
+ <div className={cx("ui-textfield", disabled && "ui-textfield--disabled", className)} style={width !== undefined ? { width } : undefined}>
+ {icon && <span className="ui-textfield__icon" aria-hidden="true">{icon}</span>}
+ <input
+ ref={inputRef}
+ className={cx("ui-textfield__input", inputClassName)}
+ value={value}
+ disabled={disabled}
+ onChange={(event) => onChange(event.target.value, event)}
+ {...rest}
+ />
+ {trailing && <span className="ui-textfield__trailing">{trailing}</span>}
+ </div>
+ );
+}
+
+/* --- StatusBar ----------------------------------------------------------------------------
+ A 24px bar along the bottom of a window or pane, 12px text. It is a
+ labelled region, not a live region: a playhead timecode would otherwise be
+ read out every frame. Put role="status" on the one item that should speak. */
+
+export interface StatusBarProps {
+ children: ReactNode;
+ /** Items pushed to the trailing edge. */
+ end?: ReactNode;
+ "aria-label"?: string;
+ className?: string;
+}
+
+export function StatusBar({ children, end, className, ...aria }: StatusBarProps) {
+ return (
+ <div role={aria["aria-label"] ? "region" : undefined} aria-label={aria["aria-label"]} className={cx("ui-statusbar", className)}>
+ <div className="ui-statusbar__items">{children}</div>
+ {end && <div className="ui-statusbar__items ui-statusbar__items--end">{end}</div>}
+ </div>
+ );
+}
diff --git a/src/components/ui/ComboBox.tsx b/src/components/ui/ComboBox.tsx
new file mode 100644
index 0000000..22e73bc
--- /dev/null
+++ b/src/components/ui/ComboBox.tsx
@@ -0,0 +1,321 @@
+/* ComboBox — the WinUI drop-down, a drop-in for <select>.
+
+ A 32px trigger styled as a standard button with a chevron. It opens an
+ acrylic listbox flyout (8px corners, 4px padding, 32px items, a 3×16px
+ accent pill beside the selected item) positioned so the selected item sits
+ right over the trigger when there is room, else below or above.
+
+ Focus never leaves the trigger: it is the ARIA 1.2 select-only combobox, so
+ the list is driven with aria-activedescendant and Tab simply moves on.
+
+ Keyboard, closed: Alt+Down / F4 / Enter / Space open; Up / Down / Home / End
+ and typing change the value directly, like a native select.
+ Keyboard, open: arrows / Home / End / PageUp / PageDown / typing move,
+ Enter or Space picks, Esc or Alt+Up closes, Tab picks-nothing and moves on.
+
+ Migrating from <select> is mechanical — keep the <option> children:
+
+ <select value={v} onChange={(e) => setV(e.target.value)}>…options…</select>
+ <ComboBox value={v} onChange={setV}>…same options…</ComboBox>
+
+ or pass data:
+
+ <ComboBox aria-label="Generator" value={id} onChange={setId}
+ options={[{ value: "a", label: "Alpha" }, { label: "More", options: [...] }]} />
+*/
+
+import { ChevronDown } from "lucide-react";
+import {
+ Children, Fragment, isValidElement, useId, useLayoutEffect, useMemo, useRef, useState,
+ type CSSProperties, type KeyboardEvent, type ReactElement, type ReactNode,
+} from "react";
+import { createPortal } from "react-dom";
+import {
+ LAYER_ATTR, VIEWPORT_MARGIN, createTypeahead, cx, isPrintableKey, placeAnchored, textOf, useLightDismiss, viewport,
+} from "./internal";
+
+export type ComboValue = string | number;
+
+export interface ComboOption<V extends ComboValue = string> {
+ value: V;
+ label: ReactNode;
+ disabled?: boolean;
+ /** A second, caption-sized line under the label (in the list only). */
+ description?: ReactNode;
+ /** 16px leading icon (list and trigger). */
+ icon?: ReactNode;
+ /** Plain text for typeahead / accessibility when `label` is not a string. */
+ textValue?: string;
+}
+
+export interface ComboGroup<V extends ComboValue = string> {
+ label: string;
+ options: ComboOption<V>[];
+}
+
+export type ComboItems<V extends ComboValue = string> = (ComboOption<V> | ComboGroup<V>)[];
+
+export interface ComboBoxProps<V extends ComboValue = string> {
+ value: V | null | undefined;
+ onChange: (value: V) => void;
+ /** Data form. When omitted, <option>/<optgroup> children are read instead. */
+ options?: ComboItems<V>;
+ children?: ReactNode;
+ id?: string;
+ name?: string;
+ "aria-label"?: string;
+ "aria-labelledby"?: string;
+ "aria-describedby"?: string;
+ "data-tooltip"?: string;
+ disabled?: boolean;
+ /** Shown when no option matches `value`. */
+ placeholder?: ReactNode;
+ className?: string;
+ /** CSS width of the trigger (number = px). Default: sized by the stylesheet (min 120px). */
+ width?: number | string;
+ onBlur?: () => void;
+ onFocus?: () => void;
+}
+
+const isGroup = <V extends ComboValue>(item: ComboOption<V> | ComboGroup<V>): item is ComboGroup<V> =>
+ "options" in item && Array.isArray((item as ComboGroup<V>).options);
+
+/** Read <option>/<optgroup> React children into ComboBox items. Values stay strings, like a select's. */
+export function optionsFromChildren(children: ReactNode): ComboItems<string> {
+ const items: ComboItems<string> = [];
+ const readOption = (element: ReactElement<{ value?: unknown; children?: ReactNode; disabled?: boolean; label?: string }>): ComboOption<string> => {
+ const { value, children: label, disabled } = element.props;
+ const text = textOf(label);
+ return { value: value === undefined ? text : String(value), label: label ?? element.props.label ?? "", disabled: Boolean(disabled), textValue: text };
+ };
+ Children.forEach(children, (child) => {
+ if (!isValidElement(child)) return;
+ if (child.type === "option") items.push(readOption(child as ReactElement<{ value?: unknown; children?: ReactNode }>));
+ else if (child.type === "optgroup") {
+ const props = child.props as { label?: string; children?: ReactNode };
+ const options: ComboOption<string>[] = [];
+ Children.forEach(props.children, (inner) => {
+ if (isValidElement(inner) && inner.type === "option") options.push(readOption(inner as ReactElement<{ value?: unknown; children?: ReactNode }>));
+ });
+ items.push({ label: props.label ?? "", options });
+ } else if (child.type === Fragment) {
+ // Fragments of options (e.g. {list.map(...)} inside <>…</>).
+ items.push(...optionsFromChildren((child.props as { children?: ReactNode }).children));
+ }
+ });
+ return items;
+}
+
+interface FlatOption<V extends ComboValue> extends ComboOption<V> { group?: string; firstInGroup?: boolean; text: string }
+
+function flatten<V extends ComboValue>(items: ComboItems<V>): FlatOption<V>[] {
+ const flat: FlatOption<V>[] = [];
+ for (const item of items) {
+ if (isGroup(item)) item.options.forEach((option, index) => flat.push({ ...option, group: item.label, firstInGroup: index === 0, text: option.textValue ?? textOf(option.label) }));
+ else flat.push({ ...item, text: item.textValue ?? textOf(item.label) });
+ }
+ return flat;
+}
+
+const ITEM_HEIGHT = 32;
+
+export function ComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>) {
+ const {
+ value, onChange, options, children, id, name, disabled, placeholder, className, width, onBlur, onFocus,
+ } = props;
+ const items = useMemo(() => (options ?? (optionsFromChildren(children) as unknown as ComboItems<V>)), [options, children]);
+ const flat = useMemo(() => flatten(items), [items]);
+ const selectedIndex = flat.findIndex((option) => option.value === value || String(option.value) === String(value ?? "\u0000"));
+ const selected = selectedIndex >= 0 ? flat[selectedIndex] : undefined;
+
+ const [open, setOpen] = useState(false);
+ const [active, setActive] = useState(-1);
+ const [position, setPosition] = useState<CSSProperties>({ visibility: "hidden" });
+ const trigger = useRef<HTMLButtonElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+ const typeahead = useRef(createTypeahead());
+ const autoId = useId();
+ const listId = `${autoId}-list`;
+ const optionId = (index: number) => `${autoId}-opt-${index}`;
+
+ const enabledIndexes = flat.map((option, index) => (option.disabled ? -1 : index)).filter((index) => index >= 0);
+
+ const commit = (index: number) => {
+ const option = flat[index];
+ if (!option || option.disabled) return;
+ if (option.value !== value) onChange(option.value);
+ };
+
+ const openList = () => {
+ if (disabled || !flat.length) return;
+ setActive(selectedIndex >= 0 && !flat[selectedIndex].disabled ? selectedIndex : enabledIndexes[0] ?? -1);
+ setPosition({ visibility: "hidden" });
+ setOpen(true);
+ };
+ const close = (focusTrigger = true) => {
+ setOpen(false);
+ if (focusTrigger) trigger.current?.focus({ preventScroll: true });
+ };
+
+ useLightDismiss(list, open, (reason) => close(reason === "escape"), { ignore: [trigger] });
+
+ /* Place the list: selected item over the trigger, else below, else above. */
+ useLayoutEffect(() => {
+ if (!open || !list.current || !trigger.current) return;
+ const anchor = trigger.current.getBoundingClientRect();
+ const view = viewport();
+ const listRect = list.current.getBoundingClientRect();
+ const height = listRect.height || flat.length * ITEM_HEIGHT + 8;
+ const width = Math.max(anchor.width, listRect.width);
+ const item = active >= 0 ? document.getElementById(optionId(selectedIndex >= 0 ? selectedIndex : active)) : null;
+ let top: number;
+ let left = anchor.left;
+ const overTop = item ? anchor.top + anchor.height / 2 - (item.offsetTop - list.current.scrollTop + item.offsetHeight / 2) : NaN;
+ if (item && overTop >= VIEWPORT_MARGIN && overTop + height <= view.height - VIEWPORT_MARGIN) {
+ top = overTop;
+ } else {
+ const placed = placeAnchored(anchor, { width, height }, "bottom", 4, view);
+ top = placed.top;
+ left = placed.left;
+ }
+ left = Math.max(VIEWPORT_MARGIN, Math.min(left, view.width - width - VIEWPORT_MARGIN));
+ setPosition({ top, left, minWidth: anchor.width });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ /* Keep the active option in view. */
+ useLayoutEffect(() => {
+ if (!open || active < 0) return;
+ const element = document.getElementById(optionId(active));
+ element?.scrollIntoView?.({ block: "nearest" });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, active]);
+
+ const step = (from: number, delta: number) => {
+ if (!enabledIndexes.length) return -1;
+ const at = enabledIndexes.indexOf(from);
+ if (at < 0) return delta > 0 ? enabledIndexes[0] : enabledIndexes[enabledIndexes.length - 1];
+ return enabledIndexes[Math.max(0, Math.min(enabledIndexes.length - 1, at + delta))];
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
+ if (disabled) return;
+ const { key, altKey } = event;
+ if (!open) {
+ if ((altKey && key === "ArrowDown") || key === "F4" || key === "Enter" || key === " ") {
+ event.preventDefault();
+ openList();
+ return;
+ }
+ let next = -1;
+ if (key === "ArrowDown" || key === "ArrowRight") next = step(selectedIndex, 1);
+ else if (key === "ArrowUp" || key === "ArrowLeft") next = step(selectedIndex, -1);
+ else if (key === "Home") next = enabledIndexes[0] ?? -1;
+ else if (key === "End") next = enabledIndexes.at(-1) ?? -1;
+ else if (isPrintableKey(event)) next = typeahead.current(key, flat.map((option) => (option.disabled ? "" : option.text)), selectedIndex);
+ else return;
+ event.preventDefault();
+ if (next >= 0) commit(next);
+ return;
+ }
+ // Open.
+ if (key === "Escape" || (altKey && key === "ArrowUp") || key === "F4") {
+ event.preventDefault();
+ event.stopPropagation();
+ close();
+ return;
+ }
+ if (key === "Enter" || key === " ") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (active >= 0) commit(active);
+ close();
+ return;
+ }
+ if (key === "Tab") { close(false); return; }
+ const page = Math.max(1, Math.floor((list.current?.clientHeight ?? 320) / ITEM_HEIGHT) - 1);
+ let next = active;
+ if (key === "ArrowDown") next = step(active, 1);
+ else if (key === "ArrowUp") next = step(active, -1);
+ else if (key === "Home") next = enabledIndexes[0] ?? -1;
+ else if (key === "End") next = enabledIndexes.at(-1) ?? -1;
+ else if (key === "PageDown") next = step(active, page);
+ else if (key === "PageUp") next = step(active, -page);
+ else if (isPrintableKey(event)) {
+ const found = typeahead.current(key, flat.map((option) => (option.disabled ? "" : option.text)), active);
+ if (found >= 0) next = found;
+ } else return;
+ event.preventDefault();
+ setActive(next);
+ };
+
+ const style: CSSProperties | undefined = width !== undefined ? { width: typeof width === "number" ? `${width}px` : width } : undefined;
+
+ return (
+ <>
+ <button
+ ref={trigger}
+ type="button"
+ id={id}
+ role="combobox"
+ className={cx("ui-combo", className)}
+ style={style}
+ disabled={disabled}
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ aria-describedby={props["aria-describedby"]}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={open ? listId : undefined}
+ aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
+ data-tooltip={props["data-tooltip"]}
+ data-value={value ?? ""}
+ onClick={() => (open ? close() : openList())}
+ onKeyDown={onKeyDown}
+ onBlur={onBlur}
+ onFocus={onFocus}
+ >
+ {selected?.icon && <span className="ui-combo__icon" aria-hidden="true">{selected.icon}</span>}
+ <span className={cx("ui-combo__value", !selected && "ui-combo__value--placeholder")}>{selected ? selected.label : placeholder ?? " "}</span>
+ <ChevronDown className="ui-combo__chevron" size={12} aria-hidden="true" />
+ </button>
+ {name !== undefined && <input type="hidden" name={name} value={value === null || value === undefined ? "" : String(value)} />}
+ {open && createPortal(
+ <div
+ ref={list}
+ id={listId}
+ role="listbox"
+ className="ui-combo__list"
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ style={position}
+ {...{ [LAYER_ATTR]: "listbox" }}
+ // Keep DOM focus on the trigger.
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ {flat.map((option, index) => (
+ <div key={`${String(option.value)}-${index}`} role="presentation">
+ {option.firstInGroup && <div className="ui-combo__group" role="presentation">{option.group}</div>}
+ <div
+ id={optionId(index)}
+ role="option"
+ aria-selected={index === selectedIndex}
+ aria-disabled={option.disabled || undefined}
+ className={cx("ui-combo__option", index === active && "ui-combo__option--active", index === selectedIndex && "ui-combo__option--selected")}
+ onMouseMove={() => { if (!option.disabled && active !== index) setActive(index); }}
+ onClick={() => { if (option.disabled) return; commit(index); close(); }}
+ >
+ {option.icon && <span className="ui-combo__icon" aria-hidden="true">{option.icon}</span>}
+ <span className="ui-combo__option-text">
+ <span className="ui-combo__option-label">{option.label}</span>
+ {option.description && <span className="ui-combo__option-description">{option.description}</span>}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
diff --git a/src/components/ui/ContentDialog.tsx b/src/components/ui/ContentDialog.tsx
new file mode 100644
index 0000000..410f3b2
--- /dev/null
+++ b/src/components/ui/ContentDialog.tsx
@@ -0,0 +1,159 @@
+/* ContentDialog — the WinUI modal dialog.
+
+ A flat --scrim, a 548px-max panel with 8px corners, a 20px semibold title,
+ 24px of body padding and a darker footer band holding equal-width buttons
+ in the Windows order [Primary][Secondary][Close]. There is no header ×, no
+ icon badge and no click-outside dismiss: Esc (and the Close button) close,
+ Enter runs the default button.
+
+ <ContentDialog
+ title="Save changes to “Lamp”?"
+ primaryText="Save" onPrimary={save}
+ secondaryText="Don't save" onSecondary={discard}
+ closeText="Cancel" onClose={cancel}
+ defaultButton="primary"
+ >
+ Your edits will be lost if you don't save them.
+ </ContentDialog>
+
+ Render it conditionally, or keep it mounted and drive `open`. */
+
+import { useId, useRef, type KeyboardEvent, type ReactNode, type RefObject } from "react";
+import { createPortal } from "react-dom";
+import { LAYER_ATTR, cx } from "./internal";
+import { useModalFocus } from "./useModalFocus";
+
+export type DialogButton = "primary" | "secondary" | "close";
+
+export interface ContentDialogProps {
+ /** Default true, so the dialog can simply be rendered conditionally. */
+ open?: boolean;
+ title: ReactNode;
+ children?: ReactNode;
+ primaryText?: ReactNode;
+ onPrimary?: () => void;
+ primaryDisabled?: boolean;
+ secondaryText?: ReactNode;
+ onSecondary?: () => void;
+ secondaryDisabled?: boolean;
+ /** The dismiss button's label. Omit for a dialog that must be answered with primary/secondary (Esc still calls onClose). */
+ closeText?: ReactNode;
+ /** Called by the Close button and by Esc. */
+ onClose: () => void;
+ /** Accent-styled, triggered by Enter (outside textareas and buttons). Default: none. */
+ defaultButton?: DialogButton | "none";
+ /** Marks the primary action as destructive for assistive text only; Fluent has no red buttons. */
+ destructive?: boolean;
+ /** Max width in px (default 548). */
+ width?: number;
+ className?: string;
+ /** Overrides the default description (the body). */
+ "aria-describedby"?: string;
+ /** Focus this element first instead of the first focusable in the body. */
+ initialFocus?: RefObject<HTMLElement | null>;
+ /** Disable Esc (e.g. while a save is in flight). */
+ disableEscape?: boolean;
+}
+
+export function ContentDialog({
+ open = true,
+ title,
+ children,
+ primaryText,
+ onPrimary,
+ primaryDisabled,
+ secondaryText,
+ onSecondary,
+ secondaryDisabled,
+ closeText,
+ onClose,
+ defaultButton = "none",
+ destructive,
+ width,
+ className,
+ initialFocus,
+ disableEscape,
+ ...rest
+}: ContentDialogProps) {
+ const panel = useRef<HTMLDivElement>(null);
+ const buttons = useRef<Partial<Record<DialogButton, HTMLButtonElement | null>>>({});
+ const id = useId();
+ const titleId = `${id}-title`;
+ const bodyId = `${id}-body`;
+
+ useModalFocus(panel, {
+ active: open,
+ initialFocus,
+ fallbackFocus: () => (defaultButton !== "none" ? buttons.current[defaultButton] : null) ?? buttons.current.primary ?? buttons.current.secondary ?? buttons.current.close,
+ });
+
+ if (!open) return null;
+
+ const run = (which: DialogButton) => {
+ if (which === "primary" && !primaryDisabled) onPrimary?.();
+ else if (which === "secondary" && !secondaryDisabled) onSecondary?.();
+ else if (which === "close") onClose();
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.defaultPrevented) return;
+ if (event.key === "Escape" && !disableEscape) {
+ event.preventDefault();
+ event.stopPropagation();
+ onClose();
+ return;
+ }
+ if (event.key === "Enter" && defaultButton !== "none" && !event.shiftKey && !event.ctrlKey && !event.altKey && !event.nativeEvent.isComposing) {
+ const target = event.target as HTMLElement;
+ if (target.closest("textarea, button, select, a[href], [role=combobox], [role=listbox], [role=menu], [contenteditable=true]")) return;
+ const button = buttons.current[defaultButton];
+ if (!button || button.disabled) return;
+ event.preventDefault();
+ event.stopPropagation();
+ run(defaultButton);
+ }
+ };
+
+ const specs: { which: DialogButton; text: ReactNode; disabled?: boolean }[] = [];
+ if (primaryText !== undefined) specs.push({ which: "primary", text: primaryText, disabled: primaryDisabled });
+ if (secondaryText !== undefined) specs.push({ which: "secondary", text: secondaryText, disabled: secondaryDisabled });
+ if (closeText !== undefined) specs.push({ which: "close", text: closeText });
+
+ return createPortal(
+ <div className="ui-dialog-scrim" {...{ [LAYER_ATTR]: "dialog" }}>
+ <div
+ ref={panel}
+ className={cx("ui-dialog", className)}
+ role={destructive ? "alertdialog" : "dialog"}
+ aria-modal="true"
+ aria-labelledby={titleId}
+ aria-describedby={rest["aria-describedby"] ?? (children ? bodyId : undefined)}
+ style={width ? { maxWidth: `min(${width}px, calc(100vw - 2 * var(--space-5)))` } : undefined}
+ onKeyDown={onKeyDown}
+ >
+ <div className="ui-dialog__body" data-modal-body>
+ <h2 id={titleId} className="ui-dialog__title">{title}</h2>
+ {children !== undefined && <div id={bodyId} className="ui-dialog__content">{children}</div>}
+ </div>
+ {specs.length > 0 && (
+ <div className="ui-dialog__footer" style={{ gridTemplateColumns: `repeat(${specs.length}, minmax(0, 1fr))` }}>
+ {specs.map(({ which, text, disabled }) => (
+ <button
+ key={which}
+ ref={(element) => { buttons.current[which] = element; }}
+ type="button"
+ className={cx(which === defaultButton ? "primary-button" : "secondary-button", "ui-dialog__button")}
+ data-dialog-button={which}
+ disabled={disabled}
+ onClick={() => run(which)}
+ >
+ {text}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/components/ui/ContextMenu.tsx b/src/components/ui/ContextMenu.tsx
new file mode 100644
index 0000000..000cf15
--- /dev/null
+++ b/src/components/ui/ContextMenu.tsx
@@ -0,0 +1,271 @@
+/* ContextMenu — the WinUI MenuFlyout.
+
+ Acrylic, 8px corners, 4px vertical padding; 32px items with 4px corners
+ inset 4px from the edge and 11px of text inset; 16px icons; accelerator
+ text right-aligned in secondary ink; disabled items dimmed by colour, not
+ opacity. Opens at a point (a contextmenu event) or anchored to an element,
+ flipping to stay inside the window.
+
+ Focus: opened by the keyboard (Shift+F10, the Menu key, a button's Enter)
+ the first item takes focus; opened by the mouse the menu itself takes it,
+ so arrows, Enter and Esc still work without painting a focus visual.
+ Arrows / Home / End move, Enter / Space run, Esc / Tab close, typing jumps
+ to the next item starting with that letter, and pressing an item's own
+ shortcut runs it.
+
+ Hook form, for most screens:
+
+ const menu = useContextMenu();
+ <div onContextMenu={(e) => menu.open(e, [
+ { id: "rename", label: "Rename", icon: <Pencil size={16} />, shortcut: "F2", onSelect: rename },
+ { separator: true },
+ { id: "delete", label: "Delete", icon: <Trash2 size={16} />, shortcut: "Delete", onSelect: remove },
+ ])} />
+ {menu.element}
+
+ `open` also takes a KeyboardEvent (anchors to its target and focuses the
+ first item) or an element / DOMRect (anchors below it). */
+
+import { Check } from "lucide-react";
+import {
+ useCallback, useLayoutEffect, useRef, useState,
+ type CSSProperties, type KeyboardEvent, type ReactNode, type SyntheticEvent,
+} from "react";
+import { createPortal } from "react-dom";
+import { ariaKeyShortcuts, formatShortcut, matchesCombo } from "../../lib/commands";
+import {
+ LAYER_ATTR, createTypeahead, cx, focusSafely, isPrintableKey, lastInputWasKeyboard, placeAnchored, placeAtPoint,
+ useLightDismiss, type RectLike,
+} from "./internal";
+
+export interface MenuItem {
+ id?: string;
+ label: string;
+ icon?: ReactNode;
+ /** A combo ("Ctrl+C", "Delete"); shown formatted and honoured while the menu is open. */
+ shortcut?: string;
+ disabled?: boolean;
+ /** Kept for callers; Fluent paints destructive items like any other. */
+ danger?: boolean;
+ /** Renders a check column and role="menuitemcheckbox". */
+ checked?: boolean;
+ onSelect: () => void;
+}
+
+export interface MenuSeparator { separator: true; id?: string }
+
+export type MenuEntry = MenuItem | MenuSeparator;
+
+export const isSeparator = (entry: MenuEntry): entry is MenuSeparator => "separator" in entry && entry.separator === true;
+
+export type MenuPosition =
+ | { x: number; y: number }
+ | { anchor: Element | RectLike; placement?: "bottom" | "top" | "right" | "bottom-end" };
+
+export interface ContextMenuProps {
+ items: MenuEntry[];
+ /** Where to open: a point, or an anchor element / rect. */
+ position: MenuPosition;
+ onClose: () => void;
+ "aria-label"?: string;
+ /** Focus the first item on open. Default: only when the last input was the keyboard. */
+ focusFirst?: boolean;
+ /** Return focus to the element that had it when the menu closes via Esc or a command. Default true. */
+ restoreFocus?: boolean;
+ className?: string;
+ /** Minimum width in px (default 160 — Fluent's 120 is too tight for accelerators). */
+ minWidth?: number;
+}
+
+const rectOf = (anchor: Element | RectLike): RectLike =>
+ anchor instanceof Element ? anchor.getBoundingClientRect() : anchor;
+
+export function ContextMenu({
+ items, position, onClose, focusFirst, restoreFocus = true, className, minWidth = 160, ...aria
+}: ContextMenuProps) {
+ const menu = useRef<HTMLDivElement>(null);
+ const opener = useRef<HTMLElement | null>(null);
+ const [style, setStyle] = useState<CSSProperties>({ visibility: "hidden", left: 0, top: 0 });
+ const typeahead = useRef(createTypeahead());
+ const closeRef = useRef(onClose);
+ closeRef.current = onClose;
+ const hasGlyphColumn = items.some((entry) => !isSeparator(entry) && (entry.icon !== undefined || entry.checked !== undefined));
+
+ const buttons = () => [...(menu.current?.querySelectorAll<HTMLButtonElement>("button[data-menu-item]:not(:disabled)") ?? [])];
+
+ const positionKey = "x" in position ? `${position.x},${position.y}` : position.anchor;
+
+ useLayoutEffect(() => {
+ if (!opener.current) opener.current = document.activeElement as HTMLElement | null;
+ const element = menu.current;
+ if (!element) return;
+ const size = { width: element.offsetWidth || minWidth, height: element.offsetHeight || 0 };
+ const placed = "x" in position
+ ? placeAtPoint(position.x, position.y, size)
+ : placeAnchored(rectOf(position.anchor), size, position.placement ?? "bottom", 4);
+ setStyle({ left: placed.left, top: placed.top, minWidth });
+ const keyboard = focusFirst ?? lastInputWasKeyboard();
+ if (keyboard) focusSafely(buttons()[0] ?? element);
+ else focusSafely(element);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [positionKey]);
+
+ const close = useCallback((restore: boolean) => {
+ if (restore && restoreFocus) focusSafely(opener.current);
+ closeRef.current();
+ }, [restoreFocus]);
+
+ useLightDismiss(menu, true, (reason) => close(reason === "escape"));
+
+ const run = (item: MenuItem) => {
+ if (item.disabled) return;
+ close(true);
+ item.onSelect();
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ // Keys pressed in a menu never reach the surface behind it.
+ event.stopPropagation();
+ const entries = items.filter((entry): entry is MenuItem => !isSeparator(entry));
+ const accelerated = entries.find((item) => item.shortcut && !item.disabled && matchesCombo(event.nativeEvent, item.shortcut));
+ if (accelerated && (event.ctrlKey || event.altKey || event.metaKey || event.key.length > 1)) {
+ event.preventDefault();
+ run(accelerated);
+ return;
+ }
+ const list = buttons();
+ const index = list.indexOf(document.activeElement as HTMLButtonElement);
+ let next = -1;
+ switch (event.key) {
+ case "ArrowDown": next = index < 0 ? 0 : (index + 1) % list.length; break;
+ case "ArrowUp": next = index < 0 ? list.length - 1 : (index - 1 + list.length) % list.length; break;
+ case "Home": next = 0; break;
+ case "End": next = list.length - 1; break;
+ case "Tab": event.preventDefault(); close(true); return;
+ case "Escape": event.preventDefault(); close(true); return;
+ case "Enter":
+ case " ":
+ if (index >= 0) { event.preventDefault(); list[index].click(); }
+ return;
+ default:
+ if (isPrintableKey(event)) {
+ next = typeahead.current(event.key, list.map((button) => button.dataset.label ?? ""), index);
+ if (next < 0) return;
+ } else return;
+ }
+ event.preventDefault();
+ focusSafely(list[next]);
+ };
+
+ return createPortal(
+ <div
+ ref={menu}
+ role="menu"
+ tabIndex={-1}
+ aria-label={aria["aria-label"]}
+ className={cx("ui-menu", hasGlyphColumn && "ui-menu--glyphs", className)}
+ style={style}
+ {...{ [LAYER_ATTR]: "menu" }}
+ onContextMenu={(event: SyntheticEvent) => event.preventDefault()}
+ onKeyDown={onKeyDown}
+ >
+ {items.map((entry, index) => {
+ if (isSeparator(entry)) return <div key={entry.id ?? `separator-${index}`} role="separator" className="ui-menu__separator" />;
+ const checkable = entry.checked !== undefined;
+ return (
+ <button
+ key={entry.id ?? entry.label}
+ type="button"
+ role={checkable ? "menuitemcheckbox" : "menuitem"}
+ aria-checked={checkable ? entry.checked : undefined}
+ aria-keyshortcuts={ariaKeyShortcuts(entry.shortcut)}
+ tabIndex={-1}
+ disabled={entry.disabled}
+ data-menu-item=""
+ data-label={entry.label}
+ className={cx("ui-menu__item", entry.danger && "ui-menu__item--danger")}
+ onClick={() => run(entry)}
+ onMouseEnter={(event) => { if (!entry.disabled) focusSafely(event.currentTarget); }}
+ >
+ {hasGlyphColumn && (
+ <span className="ui-menu__glyph" aria-hidden="true">
+ {checkable ? (entry.checked ? <Check size={16} /> : null) : entry.icon}
+ </span>
+ )}
+ <span className="ui-menu__label">{entry.label}</span>
+ {entry.shortcut && <kbd className="ui-menu__shortcut">{formatShortcut(entry.shortcut)}</kbd>}
+ </button>
+ );
+ })}
+ </div>,
+ document.body,
+ );
+}
+
+/* --- Hook ---------------------------------------------------------------------- */
+
+type OpenSource =
+ | { clientX: number; clientY: number; preventDefault?: () => void; stopPropagation?: () => void; type?: string; currentTarget?: EventTarget | null; target?: EventTarget | null; nativeEvent?: Event }
+ | { key: string; preventDefault?: () => void; stopPropagation?: () => void; currentTarget?: EventTarget | null; target?: EventTarget | null }
+ | Element
+ | RectLike;
+
+export interface OpenMenuOptions {
+ "aria-label"?: string;
+ focusFirst?: boolean;
+ placement?: "bottom" | "top" | "right" | "bottom-end";
+ onClose?: () => void;
+}
+
+export function useContextMenu() {
+ const [state, setState] = useState<{ items: MenuEntry[]; position: MenuPosition; options: OpenMenuOptions; focusFirst?: boolean; key: number } | null>(null);
+ const counter = useRef(0);
+
+ const current = useRef(state);
+ current.current = state;
+
+ const close = useCallback(() => {
+ const closing = current.current;
+ current.current = null;
+ setState(null);
+ closing?.options.onClose?.();
+ }, []);
+
+ const open = useCallback((source: OpenSource, items: MenuEntry[], options: OpenMenuOptions = {}) => {
+ let position: MenuPosition;
+ let focusFirst = options.focusFirst;
+ if (typeof Element !== "undefined" && source instanceof Element) {
+ position = { anchor: source, placement: options.placement };
+ } else if ("key" in source) {
+ source.preventDefault?.();
+ source.stopPropagation?.();
+ const target = (source.currentTarget ?? source.target) as Element | null;
+ position = target instanceof Element ? { anchor: target, placement: options.placement } : { x: 0, y: 0 };
+ focusFirst ??= true;
+ } else if ("clientX" in source) {
+ source.preventDefault?.();
+ source.stopPropagation?.();
+ // A contextmenu event raised by the keyboard has no coordinates.
+ const target = (source.currentTarget ?? source.target) as Element | null;
+ if (source.clientX === 0 && source.clientY === 0 && target instanceof Element) position = { anchor: target, placement: options.placement };
+ else position = { x: source.clientX, y: source.clientY };
+ } else {
+ position = { anchor: source, placement: options.placement };
+ }
+ counter.current += 1;
+ setState({ items, position, options, focusFirst, key: counter.current });
+ }, []);
+
+ const element = state ? (
+ <ContextMenu
+ key={state.key}
+ items={state.items}
+ position={state.position}
+ focusFirst={state.focusFirst}
+ aria-label={state.options["aria-label"]}
+ onClose={close}
+ />
+ ) : null;
+
+ return { open, close, element, isOpen: state !== null };
+}
diff --git a/src/components/ui/Controls.tsx b/src/components/ui/Controls.tsx
new file mode 100644
index 0000000..1d1531b
--- /dev/null
+++ b/src/components/ui/Controls.tsx
@@ -0,0 +1,387 @@
+/* The small WinUI controls: ToggleSwitch, Checkbox, RadioGroup / Radio,
+ Slider, ProgressBar, ProgressRing, InfoBadge, Expander, SelectorBar.
+
+ Check boxes, radios and sliders are native inputs underneath (controls.css
+ already paints them Fluent); these components add the label layout,
+ indeterminate state and the slider's filled track. */
+
+import { ChevronDown } from "lucide-react";
+import {
+ createContext, useContext, useEffect, useId, useRef,
+ type ChangeEvent, type CSSProperties, type InputHTMLAttributes, type KeyboardEvent, type ReactNode,
+} from "react";
+import { cx } from "./internal";
+import { useDisclosure } from "./Settings";
+
+/* --- ToggleSwitch --------------------------------------------------------------
+ 40×20 track, 12px knob, accent when on. WinUI shows "On"/"Off" to the LEFT
+ of the switch; pass `stateText={false}` to hide it. The optional `label` is
+ the accessible name (visible, left of the state text), or use aria-label. */
+
+export interface ToggleSwitchProps {
+ checked: boolean;
+ onChange: (checked: boolean) => void;
+ label?: ReactNode;
+ /** Default ["On", "Off"]; false hides it. */
+ stateText?: false | [ReactNode, ReactNode];
+ disabled?: boolean;
+ id?: string;
+ "aria-label"?: string;
+ "aria-labelledby"?: string;
+ "aria-describedby"?: string;
+ className?: string;
+}
+
+export function ToggleSwitch({ checked, onChange, label, stateText = ["On", "Off"], disabled, id, className, ...aria }: ToggleSwitchProps) {
+ const labelId = useId();
+ return (
+ <label className={cx("ui-toggle", checked && "ui-toggle--on", disabled && "ui-toggle--disabled", className)}>
+ {label && <span id={labelId} className="ui-toggle__label">{label}</span>}
+ {stateText && <span className="ui-toggle__state" aria-hidden="true">{checked ? stateText[0] : stateText[1]}</span>}
+ <button
+ id={id}
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ aria-label={aria["aria-label"]}
+ aria-labelledby={aria["aria-labelledby"] ?? (label ? labelId : undefined)}
+ aria-describedby={aria["aria-describedby"]}
+ disabled={disabled}
+ className="ui-toggle__track"
+ onClick={() => onChange(!checked)}
+ >
+ <span className="ui-toggle__knob" />
+ </button>
+ </label>
+ );
+}
+
+/* --- Checkbox --------------------------------------------------------------------- */
+
+export interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "onChange" | "checked"> {
+ checked: boolean;
+ onChange: (checked: boolean, event: ChangeEvent<HTMLInputElement>) => void;
+ indeterminate?: boolean;
+ label?: ReactNode;
+ /** A caption line under the label. */
+ description?: ReactNode;
+}
+
+export function Checkbox({ checked, onChange, indeterminate = false, label, description, className, disabled, ...rest }: CheckboxProps) {
+ const input = useRef<HTMLInputElement>(null);
+ useEffect(() => { if (input.current) input.current.indeterminate = indeterminate; }, [indeterminate]);
+ const descriptionId = useId();
+ return (
+ <label className={cx("ui-check", disabled && "ui-check--disabled", className)}>
+ <input
+ ref={input}
+ type="checkbox"
+ checked={checked}
+ disabled={disabled}
+ aria-checked={indeterminate ? "mixed" : undefined}
+ aria-describedby={description ? descriptionId : rest["aria-describedby"]}
+ onChange={(event) => onChange(event.target.checked, event)}
+ {...rest}
+ />
+ {(label || description) && (
+ <span className="ui-check__text">
+ {label && <span className="ui-check__label">{label}</span>}
+ {description && <span id={descriptionId} className="ui-check__description">{description}</span>}
+ </span>
+ )}
+ </label>
+ );
+}
+
+/* --- RadioGroup / Radio ----------------------------------------------------------- */
+
+interface RadioContextValue { name: string; value: string | undefined; onChange: (value: string) => void; disabled?: boolean }
+const RadioContext = createContext<RadioContextValue | null>(null);
+
+export interface RadioGroupProps<V extends string = string> {
+ value: V | undefined;
+ onChange: (value: V) => void;
+ /** Visible group heading (becomes the accessible name). */
+ label?: ReactNode;
+ "aria-label"?: string;
+ name?: string;
+ /** Data form; or pass <Radio> children. */
+ options?: { value: V; label: ReactNode; description?: ReactNode; disabled?: boolean }[];
+ children?: ReactNode;
+ orientation?: "vertical" | "horizontal";
+ disabled?: boolean;
+ className?: string;
+}
+
+export function RadioGroup<V extends string = string>({ value, onChange, label, name, options, children, orientation = "vertical", disabled, className, ...aria }: RadioGroupProps<V>) {
+ const autoName = useId();
+ const labelId = useId();
+ return (
+ <div
+ role="radiogroup"
+ aria-labelledby={label ? labelId : undefined}
+ aria-label={aria["aria-label"]}
+ aria-disabled={disabled || undefined}
+ className={cx("ui-radio-group", `ui-radio-group--${orientation}`, className)}
+ >
+ {label && <span id={labelId} className="ui-radio-group__label">{label}</span>}
+ <RadioContext.Provider value={{ name: name ?? autoName, value, onChange: onChange as (value: string) => void, disabled }}>
+ <div className="ui-radio-group__items">
+ {options?.map((option) => <Radio key={option.value} value={option.value} label={option.label} description={option.description} disabled={option.disabled} />)}
+ {children}
+ </div>
+ </RadioContext.Provider>
+ </div>
+ );
+}
+
+export interface RadioProps {
+ value: string;
+ label: ReactNode;
+ description?: ReactNode;
+ disabled?: boolean;
+ className?: string;
+}
+
+export function Radio({ value, label, description, disabled, className }: RadioProps) {
+ const group = useContext(RadioContext);
+ if (!group) throw new Error("<Radio> must be inside a <RadioGroup>");
+ const off = disabled || group.disabled;
+ return (
+ <label className={cx("ui-check", off && "ui-check--disabled", className)}>
+ <input type="radio" name={group.name} value={value} checked={group.value === value} disabled={off} onChange={() => group.onChange(value)} />
+ <span className="ui-check__text">
+ <span className="ui-check__label">{label}</span>
+ {description && <span className="ui-check__description">{description}</span>}
+ </span>
+ </label>
+ );
+}
+
+/* --- Slider -------------------------------------------------------------------------
+ input[type=range] with `--p` set from value/min/max, so the track fills up
+ to the thumb (controls.css). onChange gets a number. */
+
+export interface SliderProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange" | "min" | "max" | "step"> {
+ value: number;
+ onChange: (value: number, event: ChangeEvent<HTMLInputElement>) => void;
+ min?: number;
+ max?: number;
+ step?: number | "any";
+}
+
+export function sliderPercent(value: number, min: number, max: number) {
+ if (!(max > min)) return "0%";
+ return `${Math.round(Math.min(1, Math.max(0, (value - min) / (max - min))) * 10000) / 100}%`;
+}
+
+export function Slider({ value, onChange, min = 0, max = 100, step = 1, className, style, ...rest }: SliderProps) {
+ return (
+ <input
+ type="range"
+ className={cx("ui-slider", className)}
+ value={value}
+ min={min}
+ max={max}
+ step={step}
+ style={{ ...style, "--p": sliderPercent(value, min, max) } as CSSProperties}
+ onChange={(event) => onChange(Number(event.target.value), event)}
+ {...rest}
+ />
+ );
+}
+
+/* --- ProgressBar / ProgressRing --------------------------------------------------- */
+
+export interface ProgressBarProps {
+ /** 0–100. Omit for indeterminate. */
+ value?: number;
+ state?: "normal" | "paused" | "error";
+ "aria-label"?: string;
+ "aria-labelledby"?: string;
+ className?: string;
+}
+
+export function ProgressBar({ value, state = "normal", className, ...aria }: ProgressBarProps) {
+ const determinate = typeof value === "number" && Number.isFinite(value);
+ const clamped = determinate ? Math.min(100, Math.max(0, value)) : 0;
+ return (
+ <div
+ role="progressbar"
+ aria-valuemin={determinate ? 0 : undefined}
+ aria-valuemax={determinate ? 100 : undefined}
+ aria-valuenow={determinate ? Math.round(clamped) : undefined}
+ aria-label={aria["aria-label"]}
+ aria-labelledby={aria["aria-labelledby"]}
+ data-state={state}
+ className={cx("ui-progress", !determinate && "ui-progress--indeterminate", state !== "normal" && `ui-progress--${state}`, className)}
+ >
+ <span className="ui-progress__fill" style={determinate ? { width: `${clamped}%` } : undefined} />
+ </div>
+ );
+}
+
+export interface ProgressRingProps {
+ /** 0–100. Omit for indeterminate. */
+ value?: number;
+ size?: 16 | 20 | 32;
+ "aria-label"?: string;
+ className?: string;
+}
+
+export function ProgressRing({ value, size = 16, className, ...aria }: ProgressRingProps) {
+ const determinate = typeof value === "number" && Number.isFinite(value);
+ const clamped = determinate ? Math.min(100, Math.max(0, value)) : 0;
+ const stroke = size === 32 ? 3 : 2;
+ const radius = (size - stroke) / 2;
+ const circumference = 2 * Math.PI * radius;
+ return (
+ <span
+ role="progressbar"
+ aria-valuemin={determinate ? 0 : undefined}
+ aria-valuemax={determinate ? 100 : undefined}
+ aria-valuenow={determinate ? Math.round(clamped) : undefined}
+ aria-label={aria["aria-label"]}
+ className={cx("ui-ring", !determinate && "ui-ring--indeterminate", className)}
+ style={{ width: size, height: size }}
+ >
+ <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} aria-hidden="true">
+ {determinate && <circle className="ui-ring__track" cx={size / 2} cy={size / 2} r={radius} strokeWidth={stroke} fill="none" />}
+ <circle
+ className="ui-ring__arc"
+ cx={size / 2}
+ cy={size / 2}
+ r={radius}
+ strokeWidth={stroke}
+ fill="none"
+ strokeLinecap="round"
+ strokeDasharray={determinate ? `${(clamped / 100) * circumference} ${circumference}` : `${circumference * 0.3} ${circumference}`}
+ transform={`rotate(-90 ${size / 2} ${size / 2})`}
+ />
+ </svg>
+ </span>
+ );
+}
+
+/* --- InfoBadge ---------------------------------------------------------------------
+ A 16px pill with a number, or an 8px dot without one. */
+
+export interface InfoBadgeProps {
+ value?: number;
+ severity?: "attention" | "informational" | "success" | "caution" | "critical";
+ /** Numbers above this show as "max+" (default 99). */
+ max?: number;
+ "aria-label"?: string;
+ className?: string;
+}
+
+export function InfoBadge({ value, severity = "attention", max = 99, className, ...aria }: InfoBadgeProps) {
+ const dot = value === undefined;
+ return (
+ <span
+ className={cx("ui-badge", `ui-badge--${severity}`, dot && "ui-badge--dot", className)}
+ role={aria["aria-label"] ? "status" : undefined}
+ aria-label={aria["aria-label"]}
+ aria-hidden={aria["aria-label"] ? undefined : true}
+ >
+ {!dot && (value! > max ? `${max}+` : value)}
+ </span>
+ );
+}
+
+/* --- Expander ------------------------------------------------------------------------
+ The generic WinUI Expander: a 48px header button with a rotating chevron
+ and a content area with its own darker layer. */
+
+export interface ExpanderProps {
+ header: ReactNode;
+ description?: ReactNode;
+ icon?: ReactNode;
+ children?: ReactNode;
+ expanded?: boolean;
+ defaultExpanded?: boolean;
+ onExpandedChange?: (expanded: boolean) => void;
+ className?: string;
+ id?: string;
+}
+
+export function Expander({ header, description, icon, children, expanded, defaultExpanded, onExpandedChange, className, id }: ExpanderProps) {
+ const [isOpen, toggle] = useDisclosure(expanded, defaultExpanded, onExpandedChange);
+ const contentId = useId();
+ return (
+ <div id={id} className={cx("ui-expander", isOpen && "ui-expander--open", className)}>
+ <button type="button" className="ui-expander__header" aria-expanded={isOpen} aria-controls={contentId} onClick={toggle}>
+ {icon && <span className="ui-expander__icon" aria-hidden="true">{icon}</span>}
+ <span className="ui-expander__text">
+ <span className="ui-expander__title">{header}</span>
+ {description && <span className="ui-expander__description">{description}</span>}
+ </span>
+ <ChevronDown size={16} aria-hidden="true" className="ui-expander__chevron" />
+ </button>
+ <div id={contentId} className="ui-expander__content" hidden={!isOpen}>{children}</div>
+ </div>
+ );
+}
+
+/* --- SelectorBar -----------------------------------------------------------------------
+ Text tabs with a 3×16px accent pill under the selected one. role=tablist,
+ arrow keys / Home / End move and select (automatic activation). */
+
+export interface SelectorBarItem<V extends string = string> {
+ value: V;
+ label: ReactNode;
+ icon?: ReactNode;
+ disabled?: boolean;
+ /** Id of the tabpanel this tab controls. */
+ controls?: string;
+}
+
+export interface SelectorBarProps<V extends string = string> {
+ items: SelectorBarItem<V>[];
+ value: V;
+ onChange: (value: V) => void;
+ "aria-label"?: string;
+ className?: string;
+}
+
+export function SelectorBar<V extends string = string>({ items, value, onChange, className, ...aria }: SelectorBarProps<V>) {
+ const refs = useRef<(HTMLButtonElement | null)[]>([]);
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const enabled = items.map((item, index) => (item.disabled ? -1 : index)).filter((index) => index >= 0);
+ const at = enabled.indexOf(items.findIndex((item) => item.value === value));
+ let next: number | undefined;
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") next = enabled[(at + 1) % enabled.length];
+ else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = enabled[(at - 1 + enabled.length) % enabled.length];
+ else if (event.key === "Home") next = enabled[0];
+ else if (event.key === "End") next = enabled[enabled.length - 1];
+ if (next === undefined) return;
+ event.preventDefault();
+ onChange(items[next].value);
+ refs.current[next]?.focus();
+ };
+ return (
+ <div role="tablist" aria-label={aria["aria-label"]} className={cx("ui-selector-bar", className)} onKeyDown={onKeyDown}>
+ {items.map((item, index) => {
+ const selected = item.value === value;
+ return (
+ <button
+ key={item.value}
+ ref={(element) => { refs.current[index] = element; }}
+ type="button"
+ role="tab"
+ aria-selected={selected}
+ aria-controls={item.controls}
+ tabIndex={selected ? 0 : -1}
+ disabled={item.disabled}
+ className={cx("ui-selector-bar__item", selected && "ui-selector-bar__item--selected")}
+ onClick={() => onChange(item.value)}
+ >
+ {item.icon && <span className="ui-selector-bar__icon" aria-hidden="true">{item.icon}</span>}
+ <span>{item.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
diff --git a/src/components/ui/Flyout.tsx b/src/components/ui/Flyout.tsx
new file mode 100644
index 0000000..0357b45
--- /dev/null
+++ b/src/components/ui/Flyout.tsx
@@ -0,0 +1,81 @@
+/* Flyout — an anchored, light-dismiss popup on acrylic (WinUI Flyout).
+
+ For small tools that open from a button: the work queue, a colour picker,
+ a filter panel. It is non-modal: a press outside, Esc, a window resize or
+ the window losing focus closes it; focus moves into it on open and back to
+ the anchor on Esc.
+
+ const button = useRef<HTMLButtonElement>(null);
+ const [open, setOpen] = useState(false);
+ <button ref={button} aria-expanded={open} onClick={() => setOpen(!open)}>Queue</button>
+ <Flyout open={open} anchor={button} onClose={() => setOpen(false)} aria-label="Work queue">
+ …
+ </Flyout>
+*/
+
+import { useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react";
+import { createPortal } from "react-dom";
+import { LAYER_ATTR, cx, focusSafely, focusables, placeAnchored, useLightDismiss, type Placement, type RectLike } from "./internal";
+
+export interface FlyoutProps {
+ open: boolean;
+ /** The element it hangs from (a ref or the element), or a rect. */
+ anchor: RefObject<HTMLElement | null> | HTMLElement | RectLike | null;
+ onClose: () => void;
+ children?: ReactNode;
+ placement?: Placement;
+ "aria-label"?: string;
+ "aria-labelledby"?: string;
+ className?: string;
+ /** Focus this on open; default the first focusable inside, else the flyout. */
+ initialFocus?: RefObject<HTMLElement | null>;
+ /** Width in px (default: content). */
+ width?: number;
+ /** Default "dialog". */
+ role?: "dialog" | "region" | "group";
+}
+
+const resolveAnchor = (anchor: FlyoutProps["anchor"]): { element: HTMLElement | null; rect: RectLike | null } => {
+ if (!anchor) return { element: null, rect: null };
+ if (typeof HTMLElement !== "undefined" && anchor instanceof HTMLElement) return { element: anchor, rect: anchor.getBoundingClientRect() };
+ if ("current" in anchor) return { element: anchor.current, rect: anchor.current?.getBoundingClientRect() ?? null };
+ return { element: null, rect: anchor as RectLike };
+};
+
+export function Flyout({ open, anchor, onClose, children, placement = "bottom", className, initialFocus, width, role = "dialog", ...aria }: FlyoutProps) {
+ const panel = useRef<HTMLDivElement>(null);
+ const [style, setStyle] = useState<CSSProperties>({ visibility: "hidden" });
+ const anchorElement = resolveAnchor(anchor).element;
+
+ useLayoutEffect(() => {
+ if (!open || !panel.current) return;
+ const { rect } = resolveAnchor(anchor);
+ const size = { width: panel.current.offsetWidth, height: panel.current.offsetHeight };
+ const placed = rect ? placeAnchored(rect, size, placement, 4) : { left: 8, top: 8 };
+ setStyle({ left: placed.left, top: placed.top, width });
+ focusSafely(initialFocus?.current ?? focusables(panel.current)[0] ?? panel.current);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ useLightDismiss(panel, open, (reason) => {
+ if (reason === "escape") focusSafely(resolveAnchor(anchor).element);
+ onClose();
+ }, { ignore: [anchorElement] });
+
+ if (!open) return null;
+ return createPortal(
+ <div
+ ref={panel}
+ role={role}
+ tabIndex={-1}
+ aria-label={aria["aria-label"]}
+ aria-labelledby={aria["aria-labelledby"]}
+ className={cx("ui-flyout", className)}
+ style={style}
+ {...{ [LAYER_ATTR]: "flyout" }}
+ >
+ {children}
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/components/ui/InfoBar.tsx b/src/components/ui/InfoBar.tsx
new file mode 100644
index 0000000..608bc34
--- /dev/null
+++ b/src/components/ui/InfoBar.tsx
@@ -0,0 +1,63 @@
+/* InfoBar — an inline, full-width status message (WinUI InfoBar).
+
+ Sits in the flow of the page (under a command bar, at the top of a pane),
+ never floats in a corner. A severity tint and a 16px filled glyph, the
+ title in semibold followed by the message on the same line, an optional
+ action and an optional 32px close button.
+
+ <InfoBar severity="error" title="Export failed" message={error} onClose={dismiss} />
+ <InfoBar severity="success" title="Saved" message={path} action={<button className="secondary-button">Open folder</button>} />
+*/
+
+import { Check, X } from "lucide-react";
+import type { ReactNode } from "react";
+import { cx } from "./internal";
+
+export type InfoBarSeverity = "informational" | "success" | "warning" | "error";
+
+export interface InfoBarProps {
+ severity?: InfoBarSeverity;
+ title?: ReactNode;
+ /** The message; `children` works too. */
+ message?: ReactNode;
+ children?: ReactNode;
+ /** A button or link at the trailing end. */
+ action?: ReactNode;
+ /** Shows the close button when set. */
+ onClose?: () => void;
+ closeLabel?: string;
+ /** Hide the severity glyph. */
+ hideIcon?: boolean;
+ className?: string;
+ id?: string;
+}
+
+/** The 16px filled severity glyph, also used by InfoBadge-like spots. */
+export function SeverityGlyph({ severity }: { severity: InfoBarSeverity }) {
+ return (
+ <span className={cx("ui-severity-glyph", `ui-severity-glyph--${severity}`)} aria-hidden="true">
+ {severity === "success" ? <Check size={10} strokeWidth={3} />
+ : severity === "error" ? <X size={10} strokeWidth={3} />
+ : <span className="ui-severity-glyph__mark">{severity === "warning" ? "!" : "i"}</span>}
+ </span>
+ );
+}
+
+export function InfoBar({ severity = "informational", title, message, children, action, onClose, closeLabel = "Close", hideIcon, className, id }: InfoBarProps) {
+ const body = message ?? children;
+ return (
+ <div id={id} className={cx("ui-infobar", `ui-infobar--${severity}`, className)} role={severity === "error" ? "alert" : "status"}>
+ {!hideIcon && <SeverityGlyph severity={severity} />}
+ <div className="ui-infobar__text">
+ {title && <strong className="ui-infobar__title">{title}</strong>}
+ {body && <span className="ui-infobar__message">{body}</span>}
+ </div>
+ {action && <div className="ui-infobar__action">{action}</div>}
+ {onClose && (
+ <button type="button" className="icon-button ui-infobar__close" aria-label={closeLabel} data-tooltip={closeLabel} onClick={onClose}>
+ <X size={16} />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/ui/PropRow.tsx b/src/components/ui/PropRow.tsx
new file mode 100644
index 0000000..045277d
--- /dev/null
+++ b/src/components/ui/PropRow.tsx
@@ -0,0 +1,169 @@
+/* PropRow + PropSection — dense inspector rows.
+
+ A row is a grid: 104px label | value | 20px reset. 28px min height, the
+ label in 12px secondary ink. Give it `scrub` and dragging horizontally on
+ the label changes the number (ew-resize cursor, pointer capture, `step` per
+ pixel, Shift ×10) — the way every node editor does it. The reset button
+ appears only when the value differs from its default.
+
+ <PropSection title="Transform" persistKey="clip.transform">
+ <PropRow label="Opacity" htmlFor="opacity" value={opacity} defaultValue={100}
+ onReset={() => setOpacity(100)} scrub={{ value: opacity, onChange: setOpacity, min: 0, max: 100 }}>
+ <input id="opacity" className="text-field" … />
+ </PropRow>
+ </PropSection>
+*/
+
+import { ChevronDown, RotateCcw } from "lucide-react";
+import { useEffect, useId, useRef, useState, type PointerEvent, type ReactNode } from "react";
+import { cx } from "./internal";
+
+export interface ScrubOptions {
+ value: number;
+ onChange: (value: number) => void;
+ /** Per pixel of drag (default 1). Shift multiplies by 10. */
+ step?: number;
+ min?: number;
+ max?: number;
+ /** Called once when a drag ends (e.g. to seal an undo step). */
+ onCommit?: (value: number) => void;
+}
+
+export interface PropRowProps {
+ label: ReactNode;
+ /** Id of the control the label names. */
+ htmlFor?: string;
+ children?: ReactNode;
+ /** Current and default value, to decide whether the reset button shows. */
+ value?: unknown;
+ defaultValue?: unknown;
+ /** Force the modified state (overrides the value/defaultValue comparison). */
+ modified?: boolean;
+ onReset?: () => void;
+ resetLabel?: string;
+ scrub?: ScrubOptions;
+ className?: string;
+}
+
+const DRAG_THRESHOLD = 3;
+
+export function PropRow({ label, htmlFor, children, value, defaultValue, modified, onReset, resetLabel, scrub, className }: PropRowProps) {
+ const drag = useRef<{ x: number; start: number; accumulated: number; moved: boolean; pointer: number } | null>(null);
+ const [scrubbing, setScrubbing] = useState(false);
+ const suppressClick = useRef(false);
+ const isModified = modified ?? (defaultValue !== undefined && value !== undefined && !Object.is(value, defaultValue));
+
+ const clamp = (next: number) => Math.min(scrub?.max ?? Infinity, Math.max(scrub?.min ?? -Infinity, next));
+ const round = (next: number, step: number) => {
+ const decimals = (String(step).split(".")[1] ?? "").length;
+ return Number(next.toFixed(decimals));
+ };
+
+ const onPointerDown = (event: PointerEvent<HTMLLabelElement>) => {
+ if (!scrub || event.button !== 0) return;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ drag.current = { x: event.clientX, start: scrub.value, accumulated: 0, moved: false, pointer: event.pointerId };
+ };
+ const onPointerMove = (event: PointerEvent<HTMLLabelElement>) => {
+ const state = drag.current;
+ if (!state || !scrub) return;
+ const dx = event.clientX - state.x;
+ state.x = event.clientX;
+ state.accumulated += dx * (event.shiftKey ? 10 : 1);
+ if (!state.moved && Math.abs(state.accumulated) < DRAG_THRESHOLD) return;
+ if (!state.moved) { state.moved = true; setScrubbing(true); }
+ const step = scrub.step ?? 1;
+ const next = clamp(round(state.start + Math.round(state.accumulated) * step, step));
+ if (next !== scrub.value) scrub.onChange(next);
+ };
+ const end = (event: PointerEvent<HTMLLabelElement>) => {
+ const state = drag.current;
+ if (!state) return;
+ event.currentTarget.releasePointerCapture?.(state.pointer);
+ drag.current = null;
+ if (state.moved) {
+ suppressClick.current = true;
+ setScrubbing(false);
+ scrub?.onCommit?.(scrub.value);
+ }
+ };
+
+ return (
+ <div className={cx("ui-prop-row", scrubbing && "ui-prop-row--scrubbing", className)}>
+ <label
+ className={cx("ui-prop-row__label", scrub && "ui-prop-row__label--scrub")}
+ htmlFor={htmlFor}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={end}
+ onPointerCancel={end}
+ // A drag should not end by focusing (and selecting) the field.
+ onClick={(event) => { if (suppressClick.current) { suppressClick.current = false; event.preventDefault(); } }}
+ >
+ {label}
+ </label>
+ <div className="ui-prop-row__value">{children}</div>
+ {isModified && onReset ? (
+ <button
+ type="button"
+ className="ui-prop-row__reset"
+ aria-label={resetLabel ?? `Reset ${typeof label === "string" ? label : "value"}`}
+ data-tooltip={resetLabel ?? "Reset to default"}
+ onClick={onReset}
+ >
+ <RotateCcw size={12} aria-hidden="true" />
+ </button>
+ ) : <span className="ui-prop-row__reset-spacer" aria-hidden="true" />}
+ </div>
+ );
+}
+
+export interface PropSectionProps {
+ title: ReactNode;
+ children?: ReactNode;
+ /** Controlled open state. */
+ open?: boolean;
+ defaultOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ /** Remember the open state in localStorage under "slopus.section.<key>". */
+ persistKey?: string;
+ /** Buttons at the header's trailing edge (compact icon buttons). */
+ actions?: ReactNode;
+ className?: string;
+}
+
+function readOpen(key: string | undefined, fallback: boolean) {
+ if (!key) return fallback;
+ try {
+ const raw = localStorage.getItem(`slopus.section.${key}`);
+ return raw === null ? fallback : raw === "1";
+ } catch {
+ return fallback;
+ }
+}
+
+export function PropSection({ title, children, open, defaultOpen = true, onOpenChange, persistKey, actions, className }: PropSectionProps) {
+ const [inner, setInner] = useState(() => readOpen(persistKey, defaultOpen));
+ const isOpen = open ?? inner;
+ const contentId = useId();
+ useEffect(() => {
+ if (!persistKey || open !== undefined) return;
+ try { localStorage.setItem(`slopus.section.${persistKey}`, inner ? "1" : "0"); } catch { /* storage unavailable */ }
+ }, [persistKey, inner, open]);
+ const toggle = () => {
+ if (open === undefined) setInner(!isOpen);
+ onOpenChange?.(!isOpen);
+ };
+ return (
+ <section className={cx("ui-prop-section", isOpen && "ui-prop-section--open", className)}>
+ <div className="ui-prop-section__header">
+ <button type="button" className="ui-prop-section__toggle" aria-expanded={isOpen} aria-controls={contentId} onClick={toggle}>
+ <ChevronDown size={12} aria-hidden="true" className="ui-prop-section__chevron" />
+ <span>{title}</span>
+ </button>
+ {actions && <span className="ui-prop-section__actions">{actions}</span>}
+ </div>
+ <div id={contentId} className="ui-prop-section__content" hidden={!isOpen}>{children}</div>
+ </section>
+ );
+}
diff --git a/src/components/ui/Settings.tsx b/src/components/ui/Settings.tsx
new file mode 100644
index 0000000..bf5d4a5
--- /dev/null
+++ b/src/components/ui/Settings.tsx
@@ -0,0 +1,186 @@
+/* SettingsCard, SettingsGroup, SettingsExpander — the Windows Settings row.
+
+ A card is a grid: 20px icon | header + description | control. 68px min
+ height (48px without a description is fine too), 12px 16px padding, 4px
+ corners, the --card fill and a 1px --stroke-card edge. Stacked cards sit
+ 4px apart inside a SettingsGroup, which can carry a 14px semibold heading.
+
+ <SettingsGroup heading="Appearance">
+ <SettingsCard icon={<Palette size={20} />} header="Theme" description="Light, dark or follow Windows">
+ <ComboBox value={theme} onChange={setTheme} options={themes} />
+ </SettingsCard>
+ <SettingsCard header="About" description="Version 0.1.1" onClick={openAbout} /> // chevron
+ <SettingsCard header="Documentation" href="https://…" /> // external glyph
+ <SettingsExpander icon={<Cpu size={20} />} header="GPU" description="…" control={<ToggleSwitch …/>}>
+ <SettingsRow header="Device">…</SettingsRow>
+ <SettingsRow header="Memory limit">…</SettingsRow>
+ </SettingsExpander>
+ </SettingsGroup>
+*/
+
+import { ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
+import { useId, useState, type ReactNode } from "react";
+import { cx } from "./internal";
+
+export interface SettingsGroupProps {
+ heading?: ReactNode;
+ children: ReactNode;
+ className?: string;
+ id?: string;
+}
+
+export function SettingsGroup({ heading, children, className, id }: SettingsGroupProps) {
+ const headingId = useId();
+ return (
+ <section id={id} className={cx("ui-settings-group", className)} aria-labelledby={heading ? headingId : undefined}>
+ {heading && <h3 id={headingId} className="ui-settings-group__heading">{heading}</h3>}
+ <div className="ui-settings-group__cards">{children}</div>
+ </section>
+ );
+}
+
+export interface SettingsCardProps {
+ icon?: ReactNode;
+ header: ReactNode;
+ description?: ReactNode;
+ /** The control on the trailing edge (a toggle, a ComboBox, a button). */
+ children?: ReactNode;
+ /** Makes the whole card a button with a trailing chevron. */
+ onClick?: () => void;
+ /** Makes the whole card a link with a trailing external glyph. */
+ href?: string;
+ /** Override the trailing glyph of a clickable card. */
+ actionIcon?: "chevron" | "external" | "none";
+ disabled?: boolean;
+ className?: string;
+ id?: string;
+}
+
+export function SettingsCard({ icon, header, description, children, onClick, href, actionIcon, disabled, className, id }: SettingsCardProps) {
+ const headerId = useId();
+ const descriptionId = useId();
+ const content = (
+ <>
+ {icon !== undefined && <span className="ui-settings-card__icon" aria-hidden="true">{icon}</span>}
+ <span className="ui-settings-card__text">
+ <span id={headerId} className="ui-settings-card__header">{header}</span>
+ {description && <span id={descriptionId} className="ui-settings-card__description">{description}</span>}
+ </span>
+ </>
+ );
+ const glyph = actionIcon ?? (href ? "external" : "chevron");
+ const trailing = (children || glyph !== "none") && (
+ <span className="ui-settings-card__control">
+ {children}
+ {glyph === "chevron" && <ChevronRight size={16} aria-hidden="true" className="ui-settings-card__glyph" />}
+ {glyph === "external" && <ExternalLink size={16} aria-hidden="true" className="ui-settings-card__glyph" />}
+ </span>
+ );
+ const classes = cx("ui-settings-card", !icon && "ui-settings-card--no-icon", disabled && "ui-settings-card--disabled", className);
+
+ if (href) {
+ return (
+ <a id={id} className={cx(classes, "ui-settings-card--clickable")} href={disabled ? undefined : href} target="_blank" rel="noreferrer" aria-disabled={disabled || undefined}>
+ {content}{trailing}
+ </a>
+ );
+ }
+ if (onClick) {
+ return (
+ <button id={id} type="button" className={cx(classes, "ui-settings-card--clickable")} disabled={disabled} onClick={onClick} aria-describedby={description ? descriptionId : undefined}>
+ {content}{trailing}
+ </button>
+ );
+ }
+ return (
+ <div id={id} className={classes} role="group" aria-labelledby={headerId} aria-describedby={description ? descriptionId : undefined}>
+ {content}
+ {children !== undefined && <span className="ui-settings-card__control">{children}</span>}
+ </div>
+ );
+}
+
+/* --- Disclosure state shared by the expanders --------------------------------- */
+
+export function useDisclosure(expanded: boolean | undefined, defaultExpanded: boolean | undefined, onExpandedChange?: (expanded: boolean) => void) {
+ const [inner, setInner] = useState(Boolean(defaultExpanded));
+ const isOpen = expanded ?? inner;
+ const toggle = () => {
+ const next = !isOpen;
+ if (expanded === undefined) setInner(next);
+ onExpandedChange?.(next);
+ };
+ return [isOpen, toggle] as const;
+}
+
+export interface SettingsExpanderProps {
+ icon?: ReactNode;
+ header: ReactNode;
+ description?: ReactNode;
+ /** A control in the header row, left of the chevron (does not toggle). */
+ control?: ReactNode;
+ /** Rows shown when expanded; SettingsRow is the usual child. Dividers are drawn between them. */
+ children?: ReactNode;
+ expanded?: boolean;
+ defaultExpanded?: boolean;
+ onExpandedChange?: (expanded: boolean) => void;
+ className?: string;
+ id?: string;
+}
+
+export function SettingsExpander({ icon, header, description, control, children, expanded, defaultExpanded, onExpandedChange, className, id }: SettingsExpanderProps) {
+ const [isOpen, toggle] = useDisclosure(expanded, defaultExpanded, onExpandedChange);
+ const base = useId();
+ const headerId = `${base}-header`;
+ const descriptionId = `${base}-description`;
+ const contentId = `${base}-content`;
+ return (
+ <div id={id} className={cx("ui-settings-expander", isOpen && "ui-settings-expander--open", className)}>
+ <div className={cx("ui-settings-card", "ui-settings-expander__header", !icon && "ui-settings-card--no-icon")}>
+ {/* The whole row toggles; the control sits above this button. */}
+ <button
+ type="button"
+ className="ui-settings-expander__toggle"
+ aria-expanded={isOpen}
+ aria-controls={contentId}
+ aria-labelledby={headerId}
+ aria-describedby={description ? descriptionId : undefined}
+ onClick={toggle}
+ />
+ {icon !== undefined && <span className="ui-settings-card__icon" aria-hidden="true">{icon}</span>}
+ <span className="ui-settings-card__text">
+ <span id={headerId} className="ui-settings-card__header">{header}</span>
+ {description && <span id={descriptionId} className="ui-settings-card__description">{description}</span>}
+ </span>
+ <span className="ui-settings-card__control">
+ {control && <span className="ui-settings-expander__control">{control}</span>}
+ <ChevronDown size={16} aria-hidden="true" className="ui-settings-expander__chevron" />
+ </span>
+ </div>
+ <div id={contentId} className="ui-settings-expander__content" role="region" aria-labelledby={headerId} hidden={!isOpen}>
+ {children}
+ </div>
+ </div>
+ );
+}
+
+export interface SettingsRowProps {
+ header: ReactNode;
+ description?: ReactNode;
+ children?: ReactNode;
+ className?: string;
+}
+
+/** A row inside a SettingsExpander: header + description | control, indented past the icon column. */
+export function SettingsRow({ header, description, children, className }: SettingsRowProps) {
+ const headerId = useId();
+ return (
+ <div className={cx("ui-settings-row", className)} role="group" aria-labelledby={headerId}>
+ <span className="ui-settings-card__text">
+ <span id={headerId} className="ui-settings-card__header">{header}</span>
+ {description && <span className="ui-settings-card__description">{description}</span>}
+ </span>
+ {children !== undefined && <span className="ui-settings-card__control">{children}</span>}
+ </div>
+ );
+}
diff --git a/src/components/ui/Splitter.tsx b/src/components/ui/Splitter.tsx
new file mode 100644
index 0000000..4254077
--- /dev/null
+++ b/src/components/ui/Splitter.tsx
@@ -0,0 +1,175 @@
+/* Splitter + usePaneSize — resizable panes.
+
+ A 4px hit area centred on a 1px line that turns accent under the mouse and
+ while dragging. role="separator" with aria-valuenow/min/max; arrow keys
+ move it 8px (Shift: 32px), Home/End jump to the limits, double-click
+ resets. Sizes persist in localStorage under "slopus.pane.<key>".
+
+ const inspector = usePaneSize("generator.inspector", 340, { min: 260, max: 560 });
+ <div className="generator" style={inspector.style}> // sets --pane-generator-inspector
+ <main />
+ <Splitter {...inspector.splitterProps} reverse aria-label="Resize inspector" />
+ <aside />
+ </div>
+ .generator { grid-template-columns: 1fr auto var(--pane-generator-inspector); }
+
+ `reverse` is for a pane on the right (or bottom) of the splitter: dragging
+ towards it makes it smaller. Orientation "vertical" (default) is a vertical
+ line between columns; "horizontal" is a horizontal line between rows. */
+
+import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from "react";
+import { cx } from "./internal";
+
+export interface PaneSizeOptions {
+ min?: number;
+ max?: number;
+ /** CSS custom property name. Default `--pane-<key with dots → dashes>`. */
+ cssVar?: string;
+ /** Default true. */
+ persist?: boolean;
+}
+
+export interface SplitterValueProps {
+ value: number;
+ min: number;
+ max: number;
+ onChange: (size: number) => void;
+ onReset?: () => void;
+}
+
+export interface PaneSize {
+ size: number;
+ setSize: (size: number) => void;
+ reset: () => void;
+ min: number;
+ max: number;
+ cssVar: string;
+ /** Spread on the grid container. */
+ style: CSSProperties;
+ /** Spread on the <Splitter>. */
+ splitterProps: SplitterValueProps;
+}
+
+const STORAGE_PREFIX = "slopus.pane.";
+
+function readStored(key: string): number | undefined {
+ try {
+ const raw = localStorage.getItem(STORAGE_PREFIX + key);
+ if (raw === null) return undefined;
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function usePaneSize(key: string, defaultSize: number, options: PaneSizeOptions = {}): PaneSize {
+ const min = options.min ?? 0;
+ const max = options.max ?? Number.MAX_SAFE_INTEGER;
+ const persist = options.persist !== false;
+ const cssVar = options.cssVar ?? `--pane-${key.replace(/[^a-zA-Z0-9-]+/g, "-")}`;
+ const clampSize = useCallback((value: number) => Math.round(Math.min(max, Math.max(min, value))), [min, max]);
+ const [size, setRaw] = useState(() => clampSize((persist ? readStored(key) : undefined) ?? defaultSize));
+
+ useEffect(() => {
+ if (!persist) return;
+ try { localStorage.setItem(STORAGE_PREFIX + key, String(size)); } catch { /* storage unavailable */ }
+ }, [key, size, persist]);
+
+ const setSize = useCallback((value: number) => setRaw(clampSize(value)), [clampSize]);
+ const reset = useCallback(() => setRaw(clampSize(defaultSize)), [clampSize, defaultSize]);
+
+ return useMemo(() => ({
+ size,
+ setSize,
+ reset,
+ min,
+ max,
+ cssVar,
+ style: { [cssVar]: `${size}px` } as CSSProperties,
+ splitterProps: { value: size, min, max, onChange: setSize, onReset: reset },
+ }), [size, setSize, reset, min, max, cssVar]);
+}
+
+export interface SplitterProps extends SplitterValueProps {
+ /** "vertical" = a vertical line between columns (default); "horizontal" = between rows. */
+ orientation?: "vertical" | "horizontal";
+ /** The pane being sized is after the splitter (right / below). */
+ reverse?: boolean;
+ "aria-label"?: string;
+ /** Id of the pane being sized. */
+ "aria-controls"?: string;
+ className?: string;
+ disabled?: boolean;
+ /** Keyboard step in px (default 8; Shift ×4). */
+ step?: number;
+}
+
+export function Splitter({
+ value, min, max, onChange, onReset, orientation = "vertical", reverse, className, disabled, step = 8, ...aria
+}: SplitterProps) {
+ const drag = useRef<{ start: number; size: number; pointer: number } | null>(null);
+ const [dragging, setDragging] = useState(false);
+ const vertical = orientation === "vertical";
+ const clamp = (next: number) => Math.min(max, Math.max(min, next));
+
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (disabled || event.button !== 0) return;
+ event.preventDefault();
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ drag.current = { start: vertical ? event.clientX : event.clientY, size: value, pointer: event.pointerId };
+ setDragging(true);
+ };
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ if (!drag.current) return;
+ const delta = (vertical ? event.clientX : event.clientY) - drag.current.start;
+ const next = clamp(drag.current.size + (reverse ? -delta : delta));
+ if (next !== value) onChange(next);
+ };
+ const end = (event: PointerEvent<HTMLDivElement>) => {
+ if (!drag.current) return;
+ event.currentTarget.releasePointerCapture?.(drag.current.pointer);
+ drag.current = null;
+ setDragging(false);
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (disabled) return;
+ const amount = event.shiftKey ? step * 4 : step;
+ const grow = reverse ? -amount : amount;
+ let next: number | undefined;
+ if (vertical && event.key === "ArrowLeft") next = value - grow;
+ else if (vertical && event.key === "ArrowRight") next = value + grow;
+ else if (!vertical && event.key === "ArrowUp") next = value - grow;
+ else if (!vertical && event.key === "ArrowDown") next = value + grow;
+ else if (event.key === "Home") next = min;
+ else if (event.key === "End") next = max;
+ else if (event.key === "Enter" && onReset) { event.preventDefault(); onReset(); return; }
+ if (next === undefined) return;
+ event.preventDefault();
+ next = clamp(next);
+ if (next !== value) onChange(next);
+ };
+
+ return (
+ <div
+ role="separator"
+ tabIndex={disabled ? -1 : 0}
+ aria-orientation={orientation}
+ aria-valuenow={Math.round(value)}
+ aria-valuemin={min}
+ aria-valuemax={max === Number.MAX_SAFE_INTEGER ? undefined : max}
+ aria-label={aria["aria-label"]}
+ aria-controls={aria["aria-controls"]}
+ aria-disabled={disabled || undefined}
+ className={cx("ui-splitter", `ui-splitter--${orientation}`, dragging && "ui-splitter--dragging", className)}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={end}
+ onPointerCancel={end}
+ onLostPointerCapture={end}
+ onDoubleClick={() => { if (!disabled) onReset?.(); }}
+ onKeyDown={onKeyDown}
+ />
+ );
+}
diff --git a/src/components/ui/Tooltip.tsx b/src/components/ui/Tooltip.tsx
new file mode 100644
index 0000000..c1541f0
--- /dev/null
+++ b/src/components/ui/Tooltip.tsx
@@ -0,0 +1,204 @@
+/* Tooltip — one delegated layer for every [data-tooltip] in the app.
+
+ Mount <TooltipLayer /> once at the root (or <FluentRuntime />, which also
+ installs the slider fill). Then any element can ask for a tooltip:
+
+ <button className="icon-button" aria-label="Split clip" {...tooltipProps("Split clip", "S")}>
+
+ which is just data-tooltip="Split clip" data-tooltip-shortcut="S". The
+ shortcut is shown after the text in secondary ink.
+
+ Timing is WinUI's: shown after 500ms of hover or on keyboard focus, 100ms
+ when moving straight from one tooltip to another; hidden on pointer press,
+ scroll, Esc, blur and when the pointer leaves. Placed below the pointer
+ (below the element for keyboard focus), flipped above near the bottom of
+ the window and kept inside it horizontally.
+
+ Migrating from title="…": replace `title={x}` with `{...tooltipProps(x)}`.
+ An icon-only button still needs its aria-label; the tooltip is visual. */
+
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { formatShortcut } from "../../lib/commands";
+import { installRangeFill } from "../../lib/rangeFill";
+import { VIEWPORT_MARGIN, lastInputWasKeyboard, viewport } from "./internal";
+
+export const TOOLTIP_DELAY = 500;
+export const TOOLTIP_BETWEEN_DELAY = 100;
+/** How long after a tooltip hides the next one still counts as "moving between". */
+const BETWEEN_WINDOW = 400;
+
+/** Props that give an element a tooltip. Spread onto any element. */
+export function tooltipProps(text: string | undefined | null, shortcut?: string | null): { "data-tooltip"?: string; "data-tooltip-shortcut"?: string } {
+ if (!text) return {};
+ return shortcut ? { "data-tooltip": text, "data-tooltip-shortcut": formatShortcut(shortcut) } : { "data-tooltip": text };
+}
+
+interface Shown {
+ target: HTMLElement;
+ text: string;
+ shortcut?: string;
+ /** Pointer position for hover, undefined for focus (place under the element). */
+ point?: { x: number; y: number };
+}
+
+const findTarget = (node: EventTarget | null): HTMLElement | null =>
+ node instanceof Element ? (node.closest<HTMLElement>("[data-tooltip]")) : null;
+
+export function TooltipLayer() {
+ const [shown, setShown] = useState<Shown | null>(null);
+ const tip = useRef<HTMLDivElement>(null);
+ const timer = useRef<number>();
+ const lastHidden = useRef(-Infinity);
+ const current = useRef<Shown | null>(null);
+ const pending = useRef<HTMLElement | null>(null);
+ const pointer = useRef({ x: 0, y: 0 });
+
+ useEffect(() => {
+ const clear = () => { window.clearTimeout(timer.current); pending.current = null; };
+ const hide = () => {
+ clear();
+ if (current.current) lastHidden.current = Date.now();
+ current.current = null;
+ setShown(null);
+ };
+ const show = (target: HTMLElement, viaFocus: boolean) => {
+ const text = target.dataset.tooltip;
+ if (!text) return;
+ const next: Shown = { target, text, shortcut: target.dataset.tooltipShortcut || undefined, point: viaFocus ? undefined : { ...pointer.current } };
+ current.current = next;
+ setShown(next);
+ };
+ const schedule = (target: HTMLElement, viaFocus: boolean) => {
+ if (current.current?.target === target || pending.current === target) return;
+ const between = current.current !== null || Date.now() - lastHidden.current < BETWEEN_WINDOW;
+ clear();
+ if (current.current) { current.current = null; setShown(null); lastHidden.current = Date.now(); }
+ pending.current = target;
+ timer.current = window.setTimeout(() => { pending.current = null; if (target.isConnected) show(target, viaFocus); }, between ? TOOLTIP_BETWEEN_DELAY : TOOLTIP_DELAY);
+ };
+
+ const onOver = (event: MouseEvent) => {
+ pointer.current = { x: event.clientX, y: event.clientY };
+ const target = findTarget(event.target);
+ if (target) schedule(target, false);
+ else if (current.current || pending.current) hide();
+ };
+ const onMove = (event: MouseEvent) => { pointer.current = { x: event.clientX, y: event.clientY }; };
+ const onOut = (event: MouseEvent) => {
+ const from = findTarget(event.target);
+ const to = findTarget(event.relatedTarget);
+ if (from && from !== to && !to) hide();
+ };
+ const onFocusIn = (event: FocusEvent) => {
+ const target = findTarget(event.target);
+ if (target && lastInputWasKeyboard()) schedule(target, true);
+ };
+ const onFocusOut = (event: FocusEvent) => {
+ if (findTarget(event.target) && (current.current?.target === event.target || pending.current === event.target)) hide();
+ };
+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape" && (current.current || pending.current)) hide(); };
+
+ document.addEventListener("mouseover", onOver);
+ document.addEventListener("mousemove", onMove, { passive: true });
+ document.addEventListener("mouseout", onOut);
+ document.addEventListener("focusin", onFocusIn);
+ document.addEventListener("focusout", onFocusOut);
+ document.addEventListener("pointerdown", hide, true);
+ document.addEventListener("mousedown", hide, true);
+ document.addEventListener("scroll", hide, true);
+ document.addEventListener("wheel", hide, { capture: true, passive: true });
+ window.addEventListener("keydown", onKey, true);
+ window.addEventListener("blur", hide);
+ return () => {
+ clear();
+ document.removeEventListener("mouseover", onOver);
+ document.removeEventListener("mousemove", onMove);
+ document.removeEventListener("mouseout", onOut);
+ document.removeEventListener("focusin", onFocusIn);
+ document.removeEventListener("focusout", onFocusOut);
+ document.removeEventListener("pointerdown", hide, true);
+ document.removeEventListener("mousedown", hide, true);
+ document.removeEventListener("scroll", hide, true);
+ document.removeEventListener("wheel", hide, { capture: true });
+ window.removeEventListener("keydown", onKey, true);
+ window.removeEventListener("blur", hide);
+ };
+ }, []);
+
+ /* A shown tooltip whose element disappears (a re-render) or whose text changes follows it. */
+ useEffect(() => {
+ if (!shown) return;
+ const observer = new MutationObserver(() => {
+ if (!shown.target.isConnected || !shown.target.dataset.tooltip) { current.current = null; setShown(null); return; }
+ if (shown.target.dataset.tooltip !== shown.text || (shown.target.dataset.tooltipShortcut || undefined) !== shown.shortcut) {
+ const next = { ...shown, text: shown.target.dataset.tooltip, shortcut: shown.target.dataset.tooltipShortcut || undefined };
+ current.current = next;
+ setShown(next);
+ }
+ });
+ observer.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-tooltip", "data-tooltip-shortcut"] });
+ return () => observer.disconnect();
+ }, [shown]);
+
+ /* Describe the element while the tooltip is up, unless its name already says the same. */
+ useEffect(() => {
+ if (!shown || !tip.current) return;
+ const target = shown.target;
+ if (target.getAttribute("aria-label") === shown.text) return;
+ const before = target.getAttribute("aria-describedby");
+ const id = tip.current.id;
+ target.setAttribute("aria-describedby", before ? `${before} ${id}` : id);
+ return () => {
+ if (before === null) target.removeAttribute("aria-describedby");
+ else target.setAttribute("aria-describedby", before);
+ };
+ }, [shown]);
+
+ useLayoutEffect(() => {
+ if (!shown || !tip.current) return;
+ const view = viewport();
+ // Measure at the origin, so a tooltip last shown near the right edge is
+ // not measured wrapped against it.
+ const element = tip.current;
+ element.style.visibility = "hidden";
+ element.style.left = "0px";
+ element.style.top = "0px";
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+ let left: number;
+ let top: number;
+ if (shown.point) {
+ left = shown.point.x - width / 2;
+ top = shown.point.y + 20;
+ if (top + height > view.height - VIEWPORT_MARGIN) top = shown.point.y - height - 12;
+ } else {
+ const rect = shown.target.getBoundingClientRect();
+ left = rect.left + rect.width / 2 - width / 2;
+ top = rect.bottom + 8;
+ if (top + height > view.height - VIEWPORT_MARGIN) top = rect.top - height - 8;
+ }
+ left = Math.max(VIEWPORT_MARGIN, Math.min(left, view.width - width - VIEWPORT_MARGIN));
+ top = Math.max(VIEWPORT_MARGIN, top);
+ // Written straight to the element: React never owns these, so a tooltip
+ // that lands on the same spot as the last one is still repositioned.
+ element.style.left = `${left}px`;
+ element.style.top = `${top}px`;
+ element.style.visibility = "";
+ }, [shown]);
+
+ if (!shown) return null;
+ return createPortal(
+ <div ref={tip} id="ui-tooltip" role="tooltip" className="ui-tooltip">
+ <span className="ui-tooltip__text">{shown.text}</span>
+ {shown.shortcut && <span className="ui-tooltip__shortcut">{shown.shortcut}</span>}
+ </div>,
+ document.body,
+ );
+}
+
+/** Mount once at the app root: the tooltip layer plus the slider fill for every range input. */
+export function FluentRuntime() {
+ useEffect(() => installRangeFill(document), []);
+ return <TooltipLayer />;
+}
diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts
new file mode 100644
index 0000000..bb764b6
--- /dev/null
+++ b/src/components/ui/index.ts
@@ -0,0 +1,86 @@
+/* ============================================================================
+ Slopus Fluent UI — the shared WinUI-style component library.
+
+ Import everything from here: import { ComboBox, ContentDialog } from "../ui";
+ Styles live in src/styles/ui.css (already imported by index.css); classes
+ are `ui-*`. Every overlay renders into document.body through a portal.
+
+ App root (once):
+ <FluentRuntime /> tooltip layer + filled track on every <input type=range>
+ (or <TooltipLayer /> and installRangeFill() from lib/rangeFill separately)
+
+ Components — one line each; the source file has a fuller example:
+ ContentDialog modal; title, children, primaryText/onPrimary, secondaryText/onSecondary,
+ closeText + onClose (Esc), defaultButton ("primary"|"secondary"|"close"; Enter runs it),
+ primaryDisabled, width. Buttons render [Primary][Secondary][Close]. No click-outside.
+ useModalFocus useModalFocus(ref, { active, initialFocus, restoreFocus }) — trap + restore focus.
+ InfoBar <InfoBar severity="error" title="…" message="…" action={…} onClose={…} /> inline, full width.
+ ComboBox <ComboBox value onChange={(v) => …} options={[{value,label}]} aria-label /> or keep
+ <option>/<optgroup> children — a drop-in for <select> whose onChange gets the value.
+ optionsFromChildren(children) → ComboBox items from <option> elements.
+ Splitter <Splitter {...pane.splitterProps} orientation="vertical" reverse aria-label="Resize …" />
+ usePaneSize const pane = usePaneSize("screen.pane", 320, { min, max }); style={pane.style} sets --pane-screen-pane.
+ SettingsGroup <SettingsGroup heading="…">cards…</SettingsGroup> (4px gap).
+ SettingsCard <SettingsCard icon header description>{control}</SettingsCard>; onClick → chevron, href → external.
+ SettingsExpander <SettingsExpander icon header description control={…}>{<SettingsRow …/>}</SettingsExpander>
+ SettingsRow <SettingsRow header description>{control}</SettingsRow> (inside an expander).
+ PropSection <PropSection title="Transform" persistKey="clip.transform" actions={…}>rows…</PropSection>
+ PropRow <PropRow label htmlFor value defaultValue onReset scrub={{ value, onChange, step, min, max }}>{field}</PropRow>
+ ContextMenu <ContextMenu items position={{x,y}|{anchor}} onClose aria-label /> (controlled).
+ useContextMenu const menu = useContextMenu(); onContextMenu={(e) => menu.open(e, items)}; render {menu.element}.
+ items: { id?, label, icon?, shortcut?, disabled?, checked?, onSelect } | { separator: true }.
+ TooltipLayer mounted once; any element with data-tooltip="…" [data-tooltip-shortcut="Ctrl+S"] gets one.
+ tooltipProps {...tooltipProps("Split clip", "S")} — the codemod for title="…".
+ ToggleSwitch <ToggleSwitch checked onChange={(on) => …} label? aria-label? stateText={false}? />
+ Checkbox <Checkbox checked onChange={(on) => …} label description indeterminate />
+ RadioGroup/Radio <RadioGroup value onChange label options={[…]} /> or <Radio value label/> children.
+ Slider <Slider value onChange={(n) => …} min max step aria-label /> (sets --p).
+ ProgressBar <ProgressBar value={0..100 | undefined} state="normal"|"paused"|"error" aria-label />
+ ProgressRing <ProgressRing size={16|20|32} value? aria-label />
+ InfoBadge <InfoBadge value={3} severity="attention" /> or a dot without value.
+ Expander <Expander header description icon defaultExpanded>{content}</Expander>
+ SelectorBar <SelectorBar items={[{value,label}]} value onChange aria-label /> (tablist).
+ CommandBar <CommandBar aria-label end={…}><CommandBarButton icon label shortcut onClick /><CommandBarSeparator/></CommandBar>
+ PaneHeader <PaneHeader title="Inspector" actions={…} />
+ NavPane/NavItem <NavPane aria-label footer={…}><NavItem icon label selected badge onClick /></NavPane>
+ Flyout <Flyout open anchor={buttonRef} onClose aria-label>…</Flyout> (light dismiss, acrylic).
+ TextField <TextField value onChange={(v) => …} icon trailing={<button className="ui-textfield__button" …/>} />
+ StatusBar <StatusBar end={…}>items…</StatusBar> (24px).
+
+ Non-component helpers live in src/lib:
+ lib/commands.ts useShortcut("Ctrl+S", fn, { enabled, allowInInput, scope, preventDefault, allowInModal }),
+ registerShortcut, formatShortcut, matchesCombo, useCommand.
+ lib/undo.ts createUndoStack<T>() / useUndoStack(present, apply, { limit, mergeWindowMs }).
+ lib/rangeFill.ts installRangeFill(root) / uninstallRangeFill(root).
+ ========================================================================== */
+
+export { ContentDialog, type ContentDialogProps, type DialogButton } from "./ContentDialog";
+export { useModalFocus, type ModalFocusOptions } from "./useModalFocus";
+export { InfoBar, SeverityGlyph, type InfoBarProps, type InfoBarSeverity } from "./InfoBar";
+export {
+ ComboBox, optionsFromChildren,
+ type ComboBoxProps, type ComboGroup, type ComboItems, type ComboOption, type ComboValue,
+} from "./ComboBox";
+export { Splitter, usePaneSize, type PaneSize, type PaneSizeOptions, type SplitterProps } from "./Splitter";
+export {
+ SettingsCard, SettingsExpander, SettingsGroup, SettingsRow, useDisclosure,
+ type SettingsCardProps, type SettingsExpanderProps, type SettingsGroupProps, type SettingsRowProps,
+} from "./Settings";
+export { PropRow, PropSection, type PropRowProps, type PropSectionProps, type ScrubOptions } from "./PropRow";
+export {
+ ContextMenu, isSeparator, useContextMenu,
+ type ContextMenuProps, type MenuEntry, type MenuItem, type MenuPosition, type MenuSeparator, type OpenMenuOptions,
+} from "./ContextMenu";
+export { FluentRuntime, TooltipLayer, tooltipProps, TOOLTIP_BETWEEN_DELAY, TOOLTIP_DELAY } from "./Tooltip";
+export {
+ Checkbox, Expander, InfoBadge, ProgressBar, ProgressRing, Radio, RadioGroup, SelectorBar, Slider, ToggleSwitch, sliderPercent,
+ type CheckboxProps, type ExpanderProps, type InfoBadgeProps, type ProgressBarProps, type ProgressRingProps,
+ type RadioGroupProps, type RadioProps, type SelectorBarItem, type SelectorBarProps, type SliderProps, type ToggleSwitchProps,
+} from "./Controls";
+export { Flyout, type FlyoutProps } from "./Flyout";
+export {
+ CommandBar, CommandBarButton, CommandBarSeparator, NavItem, NavPane, PaneHeader, StatusBar, TextField,
+ type CommandBarButtonProps, type CommandBarProps, type NavItemProps, type NavPaneProps, type PaneHeaderProps,
+ type StatusBarProps, type TextFieldProps,
+} from "./Chrome";
+export { placeAnchored, placeAtPoint, type Placement } from "./internal";
diff --git a/src/components/ui/internal.ts b/src/components/ui/internal.ts
new file mode 100644
index 0000000..34da010
--- /dev/null
+++ b/src/components/ui/internal.ts
@@ -0,0 +1,216 @@
+/* Shared plumbing for the Fluent components: class joining, placement maths,
+ input-modality tracking, focus helpers and light dismiss. Not part of the
+ public API (index.ts re-exports only what screens need). */
+
+import { useEffect, useRef, type RefObject } from "react";
+
+export const cx = (...parts: (string | false | null | undefined)[]) => parts.filter(Boolean).join(" ");
+
+/* --- Layers ------------------------------------------------------------------
+ Everything that overlays renders into document.body through a portal. The
+ attribute marks a layer so focus traps and light dismiss can tell "inside a
+ popup that belongs to me" from "outside". */
+export const LAYER_ATTR = "data-ui-layer";
+
+/* --- Placement --------------------------------------------------------------- */
+
+export interface Size { width: number; height: number }
+export interface Point { left: number; top: number }
+export interface RectLike { left: number; top: number; right: number; bottom: number; width: number; height: number }
+
+export const VIEWPORT_MARGIN = 8;
+
+export function viewport(): Size {
+ return { width: window.innerWidth || document.documentElement.clientWidth || 0, height: window.innerHeight || document.documentElement.clientHeight || 0 };
+}
+
+const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(value, Math.max(min, max)));
+
+/** A menu opened at a point: down-right of it, flipped left/up when it would overflow. */
+export function placeAtPoint(x: number, y: number, size: Size, view: Size = viewport(), margin = VIEWPORT_MARGIN): Point {
+ let left = x;
+ let top = y;
+ if (left + size.width > view.width - margin && x - size.width >= margin) left = x - size.width;
+ if (top + size.height > view.height - margin && y - size.height >= margin) top = y - size.height;
+ return { left: clamp(left, margin, view.width - size.width - margin), top: clamp(top, margin, view.height - size.height - margin) };
+}
+
+export type Placement = "bottom" | "top" | "right" | "left" | "bottom-end" | "top-end";
+
+/** A popup anchored to an element: preferred side first, flipped when it does not fit. */
+export function placeAnchored(anchor: RectLike, size: Size, placement: Placement = "bottom", gap = 4, view: Size = viewport(), margin = VIEWPORT_MARGIN): Point & { placement: Placement } {
+ const below = anchor.bottom + gap;
+ const above = anchor.top - gap - size.height;
+ const fitsBelow = below + size.height <= view.height - margin;
+ const fitsAbove = above >= margin;
+ if (placement === "right" || placement === "left") {
+ const right = anchor.right + gap;
+ const left = anchor.left - gap - size.width;
+ const fitsRight = right + size.width <= view.width - margin;
+ const fitsLeft = left >= margin;
+ const useRight = placement === "right" ? fitsRight || !fitsLeft : !(fitsLeft || !fitsRight);
+ return {
+ left: clamp(useRight ? right : left, margin, view.width - size.width - margin),
+ top: clamp(anchor.top, margin, view.height - size.height - margin),
+ placement: useRight ? "right" : "left",
+ };
+ }
+ const end = placement.endsWith("-end");
+ const wantsBelow = !placement.startsWith("top");
+ const useBelow = wantsBelow ? fitsBelow || !fitsAbove : !(fitsAbove || !fitsBelow);
+ const rawLeft = end ? anchor.right - size.width : anchor.left;
+ return {
+ left: clamp(rawLeft, margin, view.width - size.width - margin),
+ top: clamp(useBelow ? below : above, margin, view.height - size.height - margin),
+ placement: (useBelow ? "bottom" : "top") + (end ? "-end" : "") as Placement,
+ };
+}
+
+/* --- Input modality -----------------------------------------------------------
+ Windows menus take keyboard focus onto their first item only when they were
+ opened with the keyboard. We remember what the user last did. */
+
+let lastKeyboard = false;
+let tracking = false;
+
+export function trackModality() {
+ if (tracking || typeof document === "undefined") return;
+ tracking = true;
+ document.addEventListener("keydown", (event) => {
+ if (!["Shift", "Control", "Alt", "Meta"].includes(event.key)) lastKeyboard = true;
+ }, true);
+ const pointer = () => { lastKeyboard = false; };
+ document.addEventListener("pointerdown", pointer, true);
+ document.addEventListener("mousedown", pointer, true);
+ document.addEventListener("contextmenu", (event) => {
+ // A contextmenu event from the keyboard arrives with no pointer position.
+ if ((event as MouseEvent).button === 0 && (event as MouseEvent).clientX === 0 && (event as MouseEvent).clientY === 0 && lastKeyboard) return;
+ lastKeyboard = false;
+ }, true);
+}
+trackModality();
+
+export const lastInputWasKeyboard = () => lastKeyboard;
+
+/* --- Focus ------------------------------------------------------------------- */
+
+const FOCUSABLE = [
+ "a[href]", "area[href]", "button:not([disabled])", "input:not([disabled]):not([type=hidden])",
+ "select:not([disabled])", "textarea:not([disabled])", "iframe", "[contenteditable=''],[contenteditable='true']",
+ "[tabindex]:not([tabindex='-1'])",
+].join(",");
+
+export function focusables(root: ParentNode): HTMLElement[] {
+ return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((element) =>
+ !element.hasAttribute("inert") && !element.closest("[inert]") && element.getAttribute("aria-hidden") !== "true" && !(element as HTMLElement & { hidden?: boolean }).hidden);
+}
+
+/** Focus without scrolling the page, when the element can still be focused. */
+export function focusSafely(element: HTMLElement | null | undefined) {
+ if (element && element.isConnected) element.focus({ preventScroll: true });
+}
+
+/* --- Light dismiss ------------------------------------------------------------
+ A flyout closes on a pointer press outside it (and outside the element that
+ opened it), on Esc, and when the window loses focus or resizes. Esc is
+ caught in the capture phase and stopped, so a dialog underneath does not
+ also close. */
+
+export interface DismissOptions {
+ /** Elements whose presses do NOT count as outside (the anchor, typically). */
+ ignore?: (RefObject<Element | null> | Element | null | undefined)[];
+ /** Default true. */
+ escape?: boolean;
+ /** Close on window resize / blur (default true). */
+ windowChanges?: boolean;
+}
+
+export function useLightDismiss(
+ ref: RefObject<HTMLElement | null>,
+ active: boolean,
+ onDismiss: (reason: "outside" | "escape" | "window") => void,
+ options: DismissOptions = {},
+) {
+ const dismiss = useRef(onDismiss);
+ dismiss.current = onDismiss;
+ const opts = useRef(options);
+ opts.current = options;
+
+ useEffect(() => {
+ if (!active) return;
+ const inside = (target: EventTarget | null) => {
+ if (!(target instanceof Node)) return false;
+ if (ref.current?.contains(target)) return true;
+ for (const entry of opts.current.ignore ?? []) {
+ const element = entry && "current" in (entry as object) ? (entry as RefObject<Element>).current : (entry as Element | null | undefined);
+ if (element?.contains(target)) return true;
+ }
+ // A nested popup (a ComboBox list inside a Flyout) is part of us.
+ const layer = target instanceof Element ? target.closest(`[${LAYER_ATTR}]`) : target.parentElement?.closest(`[${LAYER_ATTR}]`);
+ if (layer && ref.current && layer !== ref.current && layer.compareDocumentPosition(ref.current) & Node.DOCUMENT_POSITION_PRECEDING) return true;
+ return false;
+ };
+ const pointer = (event: Event) => { if (!inside(event.target)) dismiss.current("outside"); };
+ const key = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || opts.current.escape === false) return;
+ // Only the top-most layer answers Esc.
+ const layers = document.querySelectorAll(`[${LAYER_ATTR}]`);
+ if (layers.length && layers[layers.length - 1] !== ref.current && ref.current) {
+ const last = layers[layers.length - 1];
+ if (!ref.current.contains(last)) return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ dismiss.current("escape");
+ };
+ const windowChange = () => { if (opts.current.windowChanges !== false) dismiss.current("window"); };
+ document.addEventListener("pointerdown", pointer, true);
+ document.addEventListener("mousedown", pointer, true);
+ window.addEventListener("keydown", key, true);
+ window.addEventListener("resize", windowChange);
+ window.addEventListener("blur", windowChange);
+ return () => {
+ document.removeEventListener("pointerdown", pointer, true);
+ document.removeEventListener("mousedown", pointer, true);
+ window.removeEventListener("keydown", key, true);
+ window.removeEventListener("resize", windowChange);
+ window.removeEventListener("blur", windowChange);
+ };
+ }, [active, ref]);
+}
+
+/* --- Typeahead ---------------------------------------------------------------- */
+
+/** Accumulates printable keys for 700ms and finds the next label starting with them. */
+export function createTypeahead(timeout = 700) {
+ let buffer = "";
+ let last = 0;
+ return (key: string, labels: string[], from: number): number => {
+ const now = Date.now();
+ buffer = now - last > timeout ? key : buffer + key;
+ last = now;
+ const needle = buffer.toLowerCase();
+ const count = labels.length;
+ // A repeated single letter cycles through matches.
+ const repeat = needle.length > 1 && [...needle].every((ch) => ch === needle[0]);
+ const search = repeat ? needle[0] : needle;
+ const start = buffer.length === 1 || repeat ? from + 1 : from;
+ for (let i = 0; i < count; i += 1) {
+ const index = (start + i + count) % count;
+ if (labels[index]?.toLowerCase().startsWith(search)) return index;
+ }
+ return -1;
+ };
+}
+
+export const isPrintableKey = (event: { key: string; ctrlKey: boolean; altKey: boolean; metaKey: boolean }) =>
+ event.key.length === 1 && event.key !== " " && !event.ctrlKey && !event.altKey && !event.metaKey;
+
+/** Plain text of a React node (for typeahead and aria). */
+export function textOf(node: unknown): string {
+ if (node === null || node === undefined || typeof node === "boolean") return "";
+ if (typeof node === "string" || typeof node === "number") return String(node);
+ if (Array.isArray(node)) return node.map(textOf).join("");
+ if (typeof node === "object" && node && "props" in node) return textOf((node as { props: { children?: unknown } }).props.children);
+ return "";
+}
diff --git a/src/components/ui/useModalFocus.ts b/src/components/ui/useModalFocus.ts
new file mode 100644
index 0000000..39d75ff
--- /dev/null
+++ b/src/components/ui/useModalFocus.ts
@@ -0,0 +1,103 @@
+/* useModalFocus — the focus half of a modal surface.
+
+ While `active`:
+ - focus moves into `ref` (to `initialFocus`, else the first element marked
+ [data-autofocus], else the first focusable element in the container's
+ body region [data-modal-body], else the first focusable at all, else the
+ container itself);
+ - Tab and Shift+Tab wrap inside the container;
+ - focus that escapes (a click on the page behind, a script) is pulled back,
+ except into a popup layer opened from inside the modal (a ComboBox list,
+ a menu), which lives in its own portal;
+ - when it ends, focus returns to whatever had it before, if that is still
+ in the document.
+
+ ContentDialog uses it; any other modal surface (a full-screen editor, a
+ wizard) can too:
+
+ const panel = useRef<HTMLDivElement>(null);
+ useModalFocus(panel, { active: open });
+*/
+
+import { useLayoutEffect, useRef, type RefObject } from "react";
+import { LAYER_ATTR, focusSafely, focusables } from "./internal";
+
+export interface ModalFocusOptions {
+ /** Default true. */
+ active?: boolean;
+ /** Element to focus first. */
+ initialFocus?: RefObject<HTMLElement | null>;
+ /** Fallback when the body has nothing focusable (ContentDialog: its default button). */
+ fallbackFocus?: () => HTMLElement | null | undefined;
+ /** Default true. */
+ restoreFocus?: boolean;
+}
+
+export function useModalFocus(ref: RefObject<HTMLElement | null>, options: ModalFocusOptions = {}) {
+ const { active = true, restoreFocus = true } = options;
+ const opts = useRef(options);
+ opts.current = options;
+
+ useLayoutEffect(() => {
+ if (!active) return;
+ const container = ref.current;
+ if (!container) return;
+ const previous = document.activeElement as HTMLElement | null;
+
+ const initial =
+ opts.current.initialFocus?.current ??
+ container.querySelector<HTMLElement>("[data-autofocus]") ??
+ (() => {
+ const body = container.querySelector<HTMLElement>("[data-modal-body]");
+ return body ? focusables(body)[0] : undefined;
+ })() ??
+ opts.current.fallbackFocus?.() ??
+ focusables(container)[0] ??
+ container;
+ if (initial === container && !container.hasAttribute("tabindex")) container.setAttribute("tabindex", "-1");
+ focusSafely(initial);
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Tab" || event.defaultPrevented) return;
+ const items = focusables(container);
+ if (!items.length) { event.preventDefault(); return; }
+ const first = items[0];
+ const last = items[items.length - 1];
+ const current = document.activeElement;
+ if (event.shiftKey && (current === first || !container.contains(current))) {
+ event.preventDefault();
+ focusSafely(last);
+ } else if (!event.shiftKey && (current === last || !container.contains(current))) {
+ event.preventDefault();
+ focusSafely(first);
+ }
+ };
+ const onFocusIn = (event: FocusEvent) => {
+ const target = event.target as Node | null;
+ if (!target || container.contains(target)) return;
+ // A popup layer opened later than this modal belongs to it.
+ const layer = target instanceof Element ? target.closest(`[${LAYER_ATTR}]`) : null;
+ if (layer && layer !== container && container.compareDocumentPosition(layer) & Node.DOCUMENT_POSITION_FOLLOWING) return;
+ // Another modal stacked on top of this one owns focus.
+ const modals = document.querySelectorAll('[aria-modal="true"]');
+ const top = modals[modals.length - 1];
+ if (top && top !== container && !top.contains(container)) return;
+ focusSafely(focusables(container)[0] ?? container);
+ };
+ container.addEventListener("keydown", onKeyDown);
+ document.addEventListener("focusin", onFocusIn);
+ return () => {
+ container.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("focusin", onFocusIn);
+ // Synchronously: during unmount the dialog is still in the document,
+ // so focus moves straight from it to the opener with no stop at <body>.
+ // A modal opened on top of this one keeps the focus it took.
+ if (restoreFocus && previous && previous !== document.body && previous.isConnected) {
+ const now = document.activeElement;
+ const stolen = now && now !== document.body && !container.contains(now) && now.closest('[aria-modal="true"]');
+ if (!stolen) focusSafely(previous);
+ }
+ };
+ }, [active, ref, restoreFocus]);
+}
+
diff --git a/src/components/workspace/HierarchyContextMenu.tsx b/src/components/workspace/HierarchyContextMenu.tsx
index 9da841b..0253661 100644
--- a/src/components/workspace/HierarchyContextMenu.tsx
+++ b/src/components/workspace/HierarchyContextMenu.tsx
@@ -1,43 +1,24 @@
-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
-import { createPortal } from "react-dom";
+import type { ReactNode } from "react";
+import { ContextMenu, type MenuEntry } from "../ui/ContextMenu";
+
+/* The image editor's menus, kept as a thin adapter over the shared
+ ContextMenu (src/components/ui) so ImageEditor keeps its item shape:
+ `separator: true` on an item draws a divider ABOVE it, and `action` is the
+ command. New screens should use ContextMenu / useContextMenu directly. */
export interface HierarchyMenuItem {
label: string; icon: ReactNode; shortcut?: string; disabled?: boolean; danger?: boolean; separator?: boolean; action: () => void;
}
-export function HierarchyContextMenu({ x, y, items, onClose, label = "Image hierarchy actions" }: { x: number; y: number; items: HierarchyMenuItem[]; onClose: () => void; label?: string }) {
- const menu = useRef<HTMLDivElement>(null);
- const [position, setPosition] = useState({ left: x, top: y });
- useLayoutEffect(() => {
- const bounds = menu.current!.getBoundingClientRect();
- setPosition({ left: Math.max(8, Math.min(x, window.innerWidth - bounds.width - 8)), top: Math.max(8, Math.min(y, window.innerHeight - bounds.height - 8)) });
- menu.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus();
- }, [x, y]);
- useEffect(() => {
- const outside = (event: PointerEvent) => { if (event.target instanceof Node && !menu.current?.contains(event.target)) onClose(); };
- const escape = (event: KeyboardEvent) => {
- if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); onClose(); }
+
+export function toMenuEntries(items: HierarchyMenuItem[]): MenuEntry[] {
+ return items.flatMap((item, index): MenuEntry[] => {
+ const entry: MenuEntry = {
+ id: item.label, label: item.label, icon: item.icon, shortcut: item.shortcut, disabled: item.disabled, danger: item.danger, onSelect: item.action,
};
- document.addEventListener("pointerdown", outside);
- window.addEventListener("keydown", escape, true);
- window.addEventListener("resize", onClose);
- return () => { document.removeEventListener("pointerdown", outside); window.removeEventListener("keydown", escape, true); window.removeEventListener("resize", onClose); };
- }, [onClose]);
- return createPortal(<div ref={menu} className="image-hierarchy-menu" role="menu" aria-label={label} style={position} onContextMenu={(event) => event.preventDefault()} onKeyDown={(event) => {
- event.stopPropagation();
- const shortcut = (event.ctrlKey || event.metaKey) ? `Ctrl+${event.key.toUpperCase()}` : event.key;
- const command = items.find((item) => item.shortcut === shortcut && !item.disabled);
- if (command) { event.preventDefault(); onClose(); command.action(); return; }
- const buttons = [...menu.current!.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")];
- const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
- if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
- event.preventDefault();
- const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length;
- buttons[next]?.focus();
- } else if (event.key === "Tab") { event.preventDefault(); onClose(); }
- }}>
- {items.map((item) => <div key={item.label} role="none">
- {item.separator && <div role="separator" />}
- <button type="button" role="menuitem" disabled={item.disabled} className={item.danger ? "danger" : ""} onClick={() => { onClose(); item.action(); }}>{item.icon}<span>{item.label}</span>{item.shortcut && <kbd>{item.shortcut}</kbd>}</button>
- </div>)}
- </div>, document.body);
+ return item.separator && index > 0 ? [{ separator: true, id: `separator-${item.label}` }, entry] : [entry];
+ });
+}
+
+export function HierarchyContextMenu({ x, y, items, onClose, label = "Image hierarchy actions" }: { x: number; y: number; items: HierarchyMenuItem[]; onClose: () => void; label?: string }) {
+ return <ContextMenu position={{ x, y }} items={toMenuEntries(items)} onClose={onClose} aria-label={label} />;
}
diff --git a/src/styles/index.css b/src/styles/index.css
index dda43b9..8ab702c 100644
--- a/src/styles/index.css
+++ b/src/styles/index.css
@@ -13,6 +13,7 @@
@import "./base.css";
@import "./window.css";
@import "./controls.css";
+@import "./ui.css";
/* Application surfaces */
@import "./titlebar.css";
diff --git a/src/styles/ui.css b/src/styles/ui.css
new file mode 100644
index 0000000..6d71c77
--- /dev/null
+++ b/src/styles/ui.css
@@ -0,0 +1,1628 @@
+/* ============================================================================
+ ui.css — the shared Fluent component library (src/components/ui).
+
+ Every class here is prefixed `ui-` and belongs to one component in
+ src/components/ui; the component file is the documentation for its markup.
+ Nothing in this sheet is a screen's layout: a screen positions a component,
+ the component paints itself.
+
+ The same rules as the rest of the app apply, and are worth restating
+ because a component library is where they get broken first:
+ - colours come only from tokens.css, in both themes;
+ - the cursor is the arrow (the splitter and the scrub label use the resize
+ arrows, which mean "drag this");
+ - hover and press change a fill over --motion-fast and nothing else;
+ - blur (acrylic) only on the popups: menu, ComboBox list, flyout;
+ - cards have a stroke and no shadow; popups use --shadow-sm, the dialog
+ --shadow, the tooltip --shadow-tooltip.
+
+ Stacking, from the bottom: dialog scrim 900, flyout and ComboBox list 950,
+ menu 960, tooltip 1100. A ComboBox or menu opened from inside a dialog has
+ to sit above it, and a tooltip above everything.
+ ========================================================================== */
+
+/* --- Motion shared by the popups -------------------------------------------- */
+
+@keyframes ui-popup-in {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: none; }
+}
+
+@keyframes ui-dialog-in {
+ from { opacity: 0; transform: scale(1.05); }
+ to { opacity: 1; transform: none; }
+}
+
+@keyframes ui-fade-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
+/* ============================================================================
+ ContentDialog
+ ========================================================================== */
+
+.ui-dialog-scrim {
+ position: fixed;
+ inset: 0;
+ z-index: 900;
+ display: grid;
+ place-items: center;
+ padding: var(--space-5);
+ background: var(--scrim);
+ animation: ui-fade-in var(--motion-normal) linear;
+}
+
+.ui-dialog {
+ width: 100%;
+ max-width: min(548px, 100%);
+ min-width: min(320px, 100%);
+ max-height: calc(100vh - 2 * var(--space-5));
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid var(--stroke-surface);
+ border-radius: var(--radius-xl);
+ color: var(--text-primary);
+ background: var(--dialog-bg);
+ box-shadow: var(--shadow);
+ animation: ui-dialog-in var(--motion-panel) var(--ease-decelerate);
+}
+
+.ui-dialog:focus-visible {
+ outline: none;
+ box-shadow: var(--shadow);
+}
+
+.ui-dialog__body {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: var(--space-5);
+}
+
+/* Fluent Subtitle: 20/28 semibold, in the Display cut. */
+.ui-dialog__title {
+ margin: 0 0 var(--space-3);
+ font-family: var(--font-display);
+ font-size: var(--text-lg);
+ font-weight: var(--weight-semibold);
+ line-height: 1.4;
+}
+
+.ui-dialog__content {
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+.ui-dialog__content > p {
+ margin: 0 0 var(--space-3);
+}
+
+.ui-dialog__content > p:last-child {
+ margin-bottom: 0;
+}
+
+/* The button band: one layer darker, a hairline above it, and buttons that
+ share the width equally (the column count is set inline). */
+.ui-dialog__footer {
+ display: grid;
+ gap: var(--space-2);
+ padding: var(--space-5);
+ border-top: 1px solid var(--stroke-card);
+ background: var(--dialog-footer-bg);
+}
+
+.ui-dialog__button {
+ width: 100%;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* ============================================================================
+ InfoBar
+ ========================================================================== */
+
+.ui-infobar {
+ width: 100%;
+ min-height: var(--space-8);
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ padding: 0 var(--space-2) 0 var(--space-4);
+ border: 1px solid var(--stroke-card);
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: var(--card);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+.ui-infobar--success { background: var(--success-soft); }
+.ui-infobar--warning { background: var(--warning-soft); }
+.ui-infobar--error { background: var(--danger-soft); }
+
+.ui-infobar__text {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-wrap: wrap;
+ column-gap: var(--space-3);
+ padding-block: var(--space-3);
+ overflow-wrap: anywhere;
+}
+
+.ui-infobar__title {
+ font-weight: var(--weight-semibold);
+}
+
+.ui-infobar__action {
+ flex: none;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.ui-infobar__close {
+ flex: none;
+}
+
+/* The 16px filled severity disc. The glyph is cut in the panel colour, which
+ is dark on the pastel dark-theme hues and white on the deeper light ones. */
+.ui-severity-glyph {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+ border-radius: 50%;
+ color: var(--panel);
+ background: var(--text-secondary);
+}
+
+.ui-severity-glyph--informational {
+ color: var(--on-accent);
+ background: var(--accent-fill);
+}
+
+.ui-severity-glyph--success { background: var(--success); }
+.ui-severity-glyph--warning { background: var(--warning); }
+.ui-severity-glyph--error { background: var(--danger); }
+
+.ui-severity-glyph__mark {
+ font-family: var(--font-sans);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-bold);
+ line-height: 1;
+}
+
+/* ============================================================================
+ ComboBox
+ ========================================================================== */
+
+.ui-combo {
+ height: var(--control-md);
+ min-width: 120px;
+ max-width: 100%;
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: 0 var(--space-2) 0 var(--space-3);
+ border: 1px solid var(--stroke-control);
+ border-bottom-color: var(--stroke-control-bottom);
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: var(--fill-control);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ text-align: left;
+ transition: var(--transition-control);
+}
+
+.ui-combo:hover:not(:disabled) { background: var(--fill-control-hover); }
+
+.ui-combo:active:not(:disabled),
+.ui-combo[aria-expanded="true"] {
+ background: var(--fill-control-pressed);
+}
+
+.ui-combo:disabled {
+ color: var(--text-disabled);
+ background: var(--fill-control-disabled);
+}
+
+.ui-combo__value {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.ui-combo__value--placeholder {
+ color: var(--text-secondary);
+}
+
+.ui-combo__icon {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+}
+
+.ui-combo__chevron {
+ flex: none;
+ margin-left: auto;
+ color: var(--text-secondary);
+}
+
+.ui-combo:disabled .ui-combo__chevron {
+ color: var(--text-disabled);
+}
+
+.ui-combo__list {
+ position: fixed;
+ z-index: 950;
+ max-width: calc(100vw - 2 * var(--space-2));
+ max-height: min(360px, calc(100vh - 2 * var(--space-2)));
+ overflow-y: auto;
+ padding: var(--space-1);
+ border: 1px solid var(--stroke-surface);
+ border-radius: var(--radius-lg);
+ color: var(--text-primary);
+ background: var(--acrylic);
+ backdrop-filter: var(--acrylic-filter);
+ box-shadow: var(--shadow-sm);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ animation: ui-fade-in var(--motion-fast) linear;
+}
+
+.ui-combo__group {
+ padding: var(--space-2) calc(var(--space-3) - 1px) var(--space-1);
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-snug);
+}
+
+.ui-combo__group:not(:first-child) {
+ margin-top: var(--space-1);
+ border-top: 1px solid var(--line);
+}
+
+.ui-combo__option {
+ position: relative;
+ min-height: var(--control-md);
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin-block: 2px;
+ padding: 0 calc(var(--space-3) - 1px);
+ border-radius: var(--radius-sm);
+ white-space: nowrap;
+ transition: var(--transition-control);
+}
+
+.ui-combo__option--active,
+.ui-combo__option--selected {
+ background: var(--fill-subtle-hover);
+}
+
+.ui-combo__option--active.ui-combo__option--selected {
+ background: var(--fill-control-hover);
+}
+
+.ui-combo__option:active:not([aria-disabled="true"]) {
+ color: var(--text-secondary);
+ background: var(--fill-subtle-pressed);
+}
+
+/* The selected item's 3×16px accent pill, on the leading edge. */
+.ui-combo__option--selected::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 50%;
+ width: 3px;
+ height: 16px;
+ margin-top: -8px;
+ border-radius: var(--radius-pill);
+ background: var(--accent);
+}
+
+.ui-combo__option[aria-disabled="true"] {
+ color: var(--text-disabled);
+ background: transparent;
+}
+
+.ui-combo__option-text {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ padding-block: calc(var(--space-1) + 1px);
+}
+
+.ui-combo__option-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ui-combo__option-description {
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+ white-space: normal;
+}
+
+/* ============================================================================
+ Splitter
+ A 4px hit area centred on a 1px line. It lays out as a 4px track of its
+ own; a grid that wants the line flush with a pane border gives the track
+ `auto` and pulls it over the border with a negative margin.
+ ========================================================================== */
+
+.ui-splitter {
+ position: relative;
+ z-index: 2;
+ flex: none;
+ touch-action: none;
+ outline-offset: -2px;
+}
+
+.ui-splitter--vertical {
+ width: 4px;
+ align-self: stretch;
+ cursor: col-resize;
+}
+
+.ui-splitter--horizontal {
+ height: 4px;
+ justify-self: stretch;
+ cursor: row-resize;
+}
+
+.ui-splitter::before {
+ content: "";
+ position: absolute;
+ background: var(--line);
+ transition: background-color var(--motion-fast) linear;
+}
+
+.ui-splitter--vertical::before {
+ top: 0;
+ bottom: 0;
+ left: calc(50% - 0.5px);
+ width: 1px;
+}
+
+.ui-splitter--horizontal::before {
+ left: 0;
+ right: 0;
+ top: calc(50% - 0.5px);
+ height: 1px;
+}
+
+.ui-splitter:hover::before,
+.ui-splitter--dragging::before,
+.ui-splitter:focus-visible::before {
+ background: var(--accent);
+}
+
+.ui-splitter--vertical:hover::before,
+.ui-splitter--vertical.ui-splitter--dragging::before {
+ left: calc(50% - 1px);
+ width: 2px;
+}
+
+.ui-splitter--horizontal:hover::before,
+.ui-splitter--horizontal.ui-splitter--dragging::before {
+ top: calc(50% - 1px);
+ height: 2px;
+}
+
+.ui-splitter[aria-disabled="true"] {
+ cursor: default;
+}
+
+/* ============================================================================
+ SettingsCard, SettingsGroup, SettingsExpander, SettingsRow
+ ========================================================================== */
+
+.ui-settings-group {
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-settings-group__heading {
+ margin: 0 0 var(--space-2);
+ font-family: var(--font-sans);
+ font-size: var(--text-base);
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-normal);
+}
+
+.ui-settings-group__cards {
+ display: grid;
+ gap: var(--space-1);
+}
+
+.ui-settings-card {
+ width: 100%;
+ min-height: 68px;
+ display: grid;
+ grid-template-columns: 20px minmax(0, 1fr) auto;
+ align-items: center;
+ column-gap: var(--space-4);
+ padding: var(--space-3) var(--space-4);
+ border: 1px solid var(--stroke-card);
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: var(--card);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ text-align: left;
+ text-decoration: none;
+ transition: var(--transition-control);
+}
+
+.ui-settings-card--no-icon {
+ grid-template-columns: minmax(0, 1fr) auto;
+}
+
+.ui-settings-card--clickable:hover:not(:disabled, [aria-disabled="true"]) { background: var(--card-hover); }
+.ui-settings-card--clickable:active:not(:disabled, [aria-disabled="true"]) { background: var(--card-pressed); }
+
+.ui-settings-card--disabled,
+.ui-settings-card--disabled .ui-settings-card__description,
+.ui-settings-card--disabled .ui-settings-card__glyph {
+ color: var(--text-disabled);
+}
+
+.ui-settings-card__icon {
+ width: 20px;
+ height: 20px;
+ display: grid;
+ place-items: center;
+}
+
+.ui-settings-card__text {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-settings-card__description {
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+}
+
+.ui-settings-card__control {
+ justify-self: end;
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ color: var(--text-primary);
+}
+
+.ui-settings-card__glyph {
+ flex: none;
+ color: var(--text-secondary);
+}
+
+/* The expander's header is a card whose whole surface is one toggle button,
+ laid UNDER the content; the text passes presses through to it and the
+ control does not, so a switch in the header works on its own. */
+.ui-settings-expander {
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-settings-expander__header {
+ position: relative;
+ min-height: var(--space-8);
+}
+
+.ui-settings-expander--open .ui-settings-expander__header {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+.ui-settings-expander__toggle {
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+ padding: 0;
+ border: 0;
+ border-radius: inherit;
+ background: transparent;
+ transition: var(--transition-control);
+}
+
+.ui-settings-expander__toggle:hover { background: var(--fill-subtle-hover); }
+.ui-settings-expander__toggle:active { background: var(--fill-subtle-pressed); }
+
+.ui-settings-expander__header > :not(.ui-settings-expander__toggle) {
+ position: relative;
+ z-index: 1;
+ pointer-events: none;
+}
+
+.ui-settings-expander__control {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ pointer-events: auto;
+}
+
+.ui-settings-expander__chevron {
+ color: var(--text-primary);
+ transition: transform var(--motion-normal) var(--ease-decelerate);
+}
+
+.ui-settings-expander--open .ui-settings-expander__chevron {
+ transform: rotate(180deg);
+}
+
+.ui-settings-expander__content {
+ border: 1px solid var(--stroke-card);
+ border-top: 0;
+ border-radius: 0 0 var(--radius-md) var(--radius-md);
+ background: var(--card);
+}
+
+.ui-settings-expander__content > * + * {
+ border-top: 1px solid var(--stroke-card);
+}
+
+/* A row inside an expander, indented past the header's icon column
+ (16px padding + 20px icon + 16px gap). */
+.ui-settings-row {
+ min-height: var(--space-8);
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ column-gap: var(--space-4);
+ padding: var(--space-2) var(--space-4) var(--space-2) calc(2 * var(--space-4) + 20px);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+/* ============================================================================
+ PropRow + PropSection — dense inspector rows
+ ========================================================================== */
+
+.ui-prop-section__header {
+ height: 28px;
+ display: flex;
+ align-items: center;
+ border-bottom: 1px solid var(--line);
+}
+
+.ui-prop-section__toggle {
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ padding: 0 var(--space-2);
+ border: 0;
+ border-radius: var(--radius-sm);
+ color: var(--text-primary);
+ background: transparent;
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-snug);
+ text-align: left;
+ transition: var(--transition-control);
+}
+
+.ui-prop-section__toggle:hover { background: var(--fill-subtle-hover); }
+.ui-prop-section__toggle:active { background: var(--fill-subtle-pressed); }
+
+.ui-prop-section__chevron {
+ flex: none;
+ color: var(--text-secondary);
+ transform: rotate(-90deg);
+ transition: transform var(--motion-normal) var(--ease-decelerate);
+}
+
+.ui-prop-section--open .ui-prop-section__chevron {
+ transform: none;
+}
+
+.ui-prop-section__actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding-right: var(--space-1);
+}
+
+.ui-prop-section__content {
+ display: grid;
+ gap: 2px;
+ padding: var(--space-1) var(--space-2) var(--space-2) var(--space-3);
+}
+
+.ui-prop-row {
+ min-height: 28px;
+ display: grid;
+ grid-template-columns: 104px minmax(0, 1fr) 20px;
+ align-items: center;
+ column-gap: var(--space-2);
+}
+
+.ui-prop-row__label {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ transition: color var(--motion-fast) linear;
+}
+
+/* Drag-to-scrub: the resize arrows say "drag me sideways". */
+.ui-prop-row__label--scrub {
+ cursor: ew-resize;
+ touch-action: none;
+}
+
+.ui-prop-row__label--scrub:hover,
+.ui-prop-row--scrubbing .ui-prop-row__label {
+ color: var(--text-primary);
+}
+
+.ui-prop-row--scrubbing,
+.ui-prop-row--scrubbing * {
+ cursor: ew-resize;
+}
+
+.ui-prop-row__value {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+}
+
+.ui-prop-row__value > input:not([type="checkbox"], [type="radio"], [type="range"]),
+.ui-prop-row__value > .ui-combo,
+.ui-prop-row__value > .ui-textfield {
+ flex: 1;
+ min-width: 0;
+ height: var(--control-sm);
+}
+
+/* Numbers read right-aligned in tabular figures, without Chromium's spin
+ arrows; the label scrubs and the arrow keys still step. */
+.ui-prop-row__value input[type="number"] {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ appearance: textfield;
+}
+
+.ui-prop-row__value input[type="number"]::-webkit-inner-spin-button,
+.ui-prop-row__value input[type="number"]::-webkit-outer-spin-button {
+ appearance: none;
+ margin: 0;
+}
+
+.ui-prop-row__reset,
+.ui-prop-row__reset-spacer {
+ width: 20px;
+ height: 20px;
+}
+
+.ui-prop-row__reset {
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-sm);
+ color: var(--text-secondary);
+ background: transparent;
+ transition: var(--transition-control);
+}
+
+.ui-prop-row__reset:hover {
+ color: var(--text-primary);
+ background: var(--fill-subtle-hover);
+}
+
+.ui-prop-row__reset:active {
+ background: var(--fill-subtle-pressed);
+}
+
+/* ============================================================================
+ ContextMenu (MenuFlyout)
+ ========================================================================== */
+
+.ui-menu {
+ position: fixed;
+ z-index: 960;
+ display: flex;
+ flex-direction: column;
+ max-width: min(360px, calc(100vw - 2 * var(--space-2)));
+ max-height: calc(100vh - 2 * var(--space-2));
+ overflow-y: auto;
+ padding: var(--space-1) 0;
+ border: 1px solid var(--stroke-surface);
+ border-radius: var(--radius-lg);
+ color: var(--text-primary);
+ background: var(--acrylic);
+ backdrop-filter: var(--acrylic-filter);
+ box-shadow: var(--shadow-sm);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ animation: ui-popup-in var(--motion-normal) var(--ease-decelerate);
+}
+
+/* The menu itself takes focus when opened with the mouse; that is not a
+ keyboard focus and draws no ring. */
+.ui-menu:focus,
+.ui-menu:focus-visible {
+ outline: none;
+ box-shadow: var(--shadow-sm);
+}
+
+.ui-menu__item {
+ min-height: var(--control-md);
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ margin: 0 var(--space-1);
+ padding: 0 calc(var(--space-3) - 1px);
+ border: 0;
+ border-radius: var(--radius-sm);
+ color: var(--text-primary);
+ background: transparent;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ text-align: left;
+ white-space: nowrap;
+ transition: var(--transition-control);
+}
+
+.ui-menu__item:hover:not(:disabled),
+.ui-menu__item:focus:not(:disabled) {
+ background: var(--fill-subtle-hover);
+}
+
+.ui-menu__item:active:not(:disabled) {
+ color: var(--text-secondary);
+ background: var(--fill-subtle-pressed);
+}
+
+.ui-menu__item:focus-visible {
+ outline-offset: -2px;
+}
+
+/* Disabled by colour, never by opacity: a faded row reads as a rendering
+ fault on acrylic. */
+.ui-menu__item:disabled,
+.ui-menu__item:disabled .ui-menu__shortcut {
+ color: var(--text-disabled);
+}
+
+.ui-menu__glyph {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+}
+
+.ui-menu__label {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ui-menu__shortcut {
+ margin-left: var(--space-5);
+ color: var(--text-secondary);
+ font-family: var(--font-sans);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+}
+
+.ui-menu__separator {
+ height: 1px;
+ flex: none;
+ margin: var(--space-1) 0;
+ background: var(--line);
+}
+
+/* ============================================================================
+ Flyout
+ ========================================================================== */
+
+.ui-flyout {
+ position: fixed;
+ z-index: 950;
+ max-width: calc(100vw - 2 * var(--space-2));
+ max-height: calc(100vh - 2 * var(--space-2));
+ overflow: auto;
+ padding: var(--space-4);
+ border: 1px solid var(--stroke-surface);
+ border-radius: var(--radius-lg);
+ color: var(--text-primary);
+ background: var(--acrylic);
+ backdrop-filter: var(--acrylic-filter);
+ box-shadow: var(--shadow-sm);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ animation: ui-popup-in var(--motion-normal) var(--ease-decelerate);
+}
+
+.ui-flyout:focus,
+.ui-flyout:focus-visible {
+ outline: none;
+ box-shadow: var(--shadow-sm);
+}
+
+/* ============================================================================
+ Tooltip
+ ========================================================================== */
+
+.ui-tooltip {
+ position: fixed;
+ z-index: 1100;
+ max-width: 320px;
+ padding: calc(var(--space-1) + 1px) var(--space-2) calc(var(--space-2) - 1px);
+ border: 1px solid var(--tooltip-stroke);
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: var(--tooltip-bg);
+ box-shadow: var(--shadow-tooltip);
+ font-family: var(--font-sans);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+ overflow-wrap: anywhere;
+ pointer-events: none;
+ animation: ui-fade-in var(--motion-fast) linear;
+}
+
+.ui-tooltip__shortcut {
+ margin-left: var(--space-2);
+ color: var(--text-secondary);
+}
+
+/* ============================================================================
+ ToggleSwitch
+ ========================================================================== */
+
+.ui-toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-3);
+ min-height: var(--control-md);
+ color: var(--text-primary);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+.ui-toggle__state {
+ min-width: 24px;
+ text-align: right;
+}
+
+.ui-toggle__track {
+ position: relative;
+ width: 40px;
+ height: 20px;
+ flex: none;
+ padding: 0;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-pill);
+ background: var(--fill-control-alt);
+ transition: var(--transition-control);
+}
+
+.ui-toggle__track:hover:not(:disabled) { background: var(--fill-subtle-hover); }
+.ui-toggle__track:active:not(:disabled) { background: var(--fill-subtle-pressed); }
+
+.ui-toggle__knob {
+ position: absolute;
+ top: 50%;
+ left: 3px;
+ width: 12px;
+ height: 12px;
+ margin-top: -6px;
+ border-radius: 50%;
+ background: var(--text-secondary);
+ transition: transform var(--motion-normal) var(--ease-decelerate);
+}
+
+.ui-toggle--on .ui-toggle__track {
+ border-color: var(--accent-fill);
+ background: var(--accent-fill);
+}
+
+.ui-toggle--on .ui-toggle__track:hover:not(:disabled) {
+ border-color: var(--button-primary-hover);
+ background: var(--button-primary-hover);
+}
+
+.ui-toggle--on .ui-toggle__track:active:not(:disabled) {
+ border-color: var(--button-primary-active);
+ background: var(--button-primary-active);
+}
+
+.ui-toggle--on .ui-toggle__knob {
+ background: var(--on-accent);
+ transform: translateX(20px);
+}
+
+.ui-toggle--disabled {
+ color: var(--text-disabled);
+}
+
+.ui-toggle--disabled .ui-toggle__track {
+ border-color: var(--text-disabled);
+ background: transparent;
+}
+
+.ui-toggle--disabled .ui-toggle__knob {
+ background: var(--text-disabled);
+}
+
+.ui-toggle--disabled.ui-toggle--on .ui-toggle__track {
+ border-color: transparent;
+ background: var(--accent-disabled);
+}
+
+.ui-toggle--disabled.ui-toggle--on .ui-toggle__knob {
+ background: var(--on-accent-disabled);
+}
+
+/* ============================================================================
+ Checkbox and Radio (label layout; the box itself is controls.css)
+ ========================================================================== */
+
+.ui-check {
+ display: inline-grid;
+ grid-template-columns: var(--check-size) auto;
+ align-items: start;
+ column-gap: var(--space-2);
+ padding-block: calc((var(--control-md) - var(--check-size)) / 2);
+ color: var(--text-primary);
+ font-size: var(--text-base);
+ line-height: var(--check-size);
+}
+
+.ui-check__text {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.ui-check__description {
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+}
+
+.ui-check--disabled,
+.ui-check--disabled .ui-check__description {
+ color: var(--text-disabled);
+}
+
+.ui-radio-group {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.ui-radio-group__label {
+ color: var(--text-primary);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+.ui-radio-group__items {
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-radio-group--horizontal .ui-radio-group__items {
+ flex-direction: row;
+ flex-wrap: wrap;
+ column-gap: var(--space-5);
+}
+
+/* ============================================================================
+ Slider (the look is controls.css; this only sizes it)
+ ========================================================================== */
+
+.ui-slider {
+ min-width: 0;
+}
+
+/* ============================================================================
+ ProgressBar and ProgressRing
+ ========================================================================== */
+
+.ui-progress {
+ position: relative;
+ height: var(--progress-height);
+ overflow: hidden;
+ border-radius: var(--radius-progress);
+ background: var(--track);
+}
+
+.ui-progress__fill {
+ display: block;
+ height: 100%;
+ border-radius: var(--radius-progress);
+ background: var(--accent-fill);
+ transition: width var(--motion-normal) linear;
+}
+
+.ui-progress--paused .ui-progress__fill { background: var(--warning); }
+.ui-progress--error .ui-progress__fill { background: var(--danger); }
+
+.ui-progress--indeterminate .ui-progress__fill {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 40%;
+ animation: ui-progress-indeterminate 2s var(--ease-decelerate) infinite;
+}
+
+/* An indeterminate bar that is paused or failed stops and fills: there is no
+ progress to show, only the state. */
+.ui-progress--indeterminate.ui-progress--paused .ui-progress__fill,
+.ui-progress--indeterminate.ui-progress--error .ui-progress__fill {
+ width: 100%;
+ animation: none;
+}
+
+@keyframes ui-progress-indeterminate {
+ from { transform: translateX(-100%); }
+ to { transform: translateX(250%); }
+}
+
+.ui-ring {
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+ color: var(--accent);
+}
+
+.ui-ring svg {
+ display: block;
+}
+
+.ui-ring__track {
+ stroke: var(--track);
+}
+
+.ui-ring__arc {
+ stroke: currentColor;
+ transition: stroke-dasharray var(--motion-normal) linear;
+}
+
+.ui-ring--indeterminate svg {
+ animation: spin 0.9s linear infinite;
+}
+
+/* ============================================================================
+ InfoBadge
+ ========================================================================== */
+
+.ui-badge {
+ min-width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+ padding: 0 var(--space-1);
+ border-radius: var(--radius-pill);
+ color: var(--on-accent);
+ background: var(--accent-fill);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+}
+
+.ui-badge--informational { color: var(--panel); background: var(--text-secondary); }
+.ui-badge--success { color: var(--panel); background: var(--success); }
+.ui-badge--caution { color: var(--panel); background: var(--warning); }
+.ui-badge--critical { color: var(--panel); background: var(--danger); }
+
+.ui-badge--dot {
+ width: 8px;
+ min-width: 8px;
+ height: 8px;
+ padding: 0;
+}
+
+/* ============================================================================
+ Expander (generic)
+ ========================================================================== */
+
+.ui-expander {
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-expander__header {
+ width: 100%;
+ min-height: var(--space-8);
+ display: flex;
+ align-items: center;
+ gap: var(--space-4);
+ padding: var(--space-2) var(--space-4);
+ border: 1px solid var(--stroke-card);
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: var(--card);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ text-align: left;
+ transition: var(--transition-control);
+}
+
+.ui-expander__header:hover { background: var(--card-hover); }
+.ui-expander__header:active { background: var(--card-pressed); }
+
+.ui-expander--open .ui-expander__header {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+.ui-expander__icon {
+ width: 20px;
+ height: 20px;
+ flex: none;
+ display: grid;
+ place-items: center;
+}
+
+.ui-expander__text {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.ui-expander__description {
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+}
+
+.ui-expander__chevron {
+ flex: none;
+ transition: transform var(--motion-normal) var(--ease-decelerate);
+}
+
+.ui-expander--open .ui-expander__chevron {
+ transform: rotate(180deg);
+}
+
+.ui-expander__content {
+ padding: var(--space-4);
+ border: 1px solid var(--stroke-card);
+ border-top: 0;
+ border-radius: 0 0 var(--radius-md) var(--radius-md);
+ background: var(--card);
+}
+
+/* ============================================================================
+ SelectorBar
+ ========================================================================== */
+
+.ui-selector-bar {
+ display: flex;
+ align-items: stretch;
+ gap: var(--space-1);
+}
+
+.ui-selector-bar__item {
+ position: relative;
+ min-height: var(--space-7);
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: 0 var(--space-3);
+ border: 0;
+ border-radius: var(--radius-md);
+ color: var(--text-secondary);
+ background: transparent;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ white-space: nowrap;
+ transition: var(--transition-control);
+}
+
+.ui-selector-bar__item:hover:not(:disabled) {
+ color: var(--text-primary);
+ background: var(--fill-subtle-hover);
+}
+
+.ui-selector-bar__item:active:not(:disabled) {
+ background: var(--fill-subtle-pressed);
+}
+
+.ui-selector-bar__item--selected {
+ color: var(--text-primary);
+}
+
+.ui-selector-bar__item--selected::after {
+ content: "";
+ position: absolute;
+ left: 50%;
+ bottom: 2px;
+ width: 16px;
+ height: 3px;
+ margin-left: -8px;
+ border-radius: var(--radius-pill);
+ background: var(--accent);
+}
+
+.ui-selector-bar__item:disabled {
+ color: var(--text-disabled);
+}
+
+.ui-selector-bar__icon {
+ display: inline-grid;
+ place-items: center;
+}
+
+/* ============================================================================
+ CommandBar
+ ========================================================================== */
+
+.ui-command-bar {
+ min-height: var(--space-7);
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ padding: 0 var(--space-1);
+}
+
+.ui-command-bar__primary,
+.ui-command-bar__end {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.ui-command-bar__end {
+ margin-left: auto;
+}
+
+.ui-command-bar__separator {
+ width: 1px;
+ height: 20px;
+ flex: none;
+ margin: 0 var(--space-1);
+ background: var(--line);
+}
+
+.ui-cmd {
+ min-width: var(--icon-button);
+ height: var(--control-md);
+ flex: none;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ padding: 0;
+ border: 1px solid transparent;
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: transparent;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ white-space: nowrap;
+ transition: var(--transition-control);
+}
+
+.ui-cmd--labelled {
+ padding: 0 var(--space-3) 0 var(--space-2);
+}
+
+.ui-cmd:hover:not(:disabled) { background: var(--fill-subtle-hover); }
+
+.ui-cmd:active:not(:disabled) {
+ color: var(--text-secondary);
+ background: var(--fill-subtle-pressed);
+}
+
+.ui-cmd:disabled {
+ color: var(--text-disabled);
+}
+
+.ui-cmd--pressed {
+ border-color: var(--accent-line);
+ color: var(--accent-on-soft);
+ background: var(--accent-soft);
+}
+
+.ui-cmd--pressed:hover:not(:disabled) {
+ background: var(--accent-soft-strong);
+}
+
+.ui-cmd__icon {
+ width: 16px;
+ height: 16px;
+ display: inline-grid;
+ place-items: center;
+}
+
+/* ============================================================================
+ PaneHeader
+ ========================================================================== */
+
+.ui-pane-header {
+ min-height: var(--control-md);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ padding: 0 var(--space-1) 0 var(--space-3);
+}
+
+.ui-pane-header__title {
+ min-width: 0;
+ margin: 0;
+ overflow: hidden;
+ color: var(--text-primary);
+ font-family: var(--font-sans);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-snug);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.ui-pane-header__actions {
+ flex: none;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+/* ============================================================================
+ NavigationView: NavPane + NavItem
+ ========================================================================== */
+
+.ui-nav {
+ min-height: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ padding: var(--space-1);
+}
+
+.ui-nav__items {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ overflow-y: auto;
+}
+
+.ui-nav__footer,
+.ui-nav__header {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.ui-nav-item {
+ position: relative;
+ width: 100%;
+ min-height: 36px;
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ padding: 0 var(--space-3);
+ border: 0;
+ border-radius: var(--radius-md);
+ color: var(--text-primary);
+ background: transparent;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ text-align: left;
+ transition: var(--transition-control);
+}
+
+.ui-nav-item:hover:not(:disabled),
+.ui-nav-item--selected {
+ background: var(--fill-subtle-hover);
+}
+
+.ui-nav-item:active:not(:disabled) {
+ color: var(--text-secondary);
+ background: var(--fill-subtle-pressed);
+}
+
+.ui-nav-item:disabled {
+ color: var(--text-disabled);
+}
+
+.ui-nav-item--selected::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 50%;
+ width: 3px;
+ height: 16px;
+ margin-top: -8px;
+ border-radius: var(--radius-pill);
+ background: var(--accent);
+}
+
+.ui-nav-item__icon {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+}
+
+.ui-nav-item__label {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.ui-nav-item__badge {
+ margin-left: auto;
+}
+
+/* The 48px icon rail: labels stay in the accessibility tree, off screen. */
+.ui-nav--compact .ui-nav-item {
+ justify-content: center;
+ padding: 0;
+}
+
+.ui-nav--compact .ui-nav-item__label {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+}
+
+.ui-nav--compact .ui-nav-item__badge {
+ position: absolute;
+ top: var(--space-1);
+ right: var(--space-1);
+}
+
+/* ============================================================================
+ TextField — the TextBox as a composite (see .search-field in controls.css)
+ ========================================================================== */
+
+.ui-textfield {
+ height: var(--field-height);
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: 0 var(--space-1) 0 var(--space-3);
+ border: 1px solid var(--stroke-control);
+ border-bottom-color: var(--stroke-strong);
+ border-radius: var(--radius-sm);
+ color: var(--text-secondary);
+ background: var(--fill-control);
+ transition: var(--transition-control);
+}
+
+.ui-textfield:hover:not(:focus-within, .ui-textfield--disabled) {
+ background: var(--fill-control-hover);
+}
+
+.ui-textfield:focus-within {
+ border-bottom-color: var(--field-focus-line);
+ background: var(--fill-input-focus);
+ box-shadow: inset 0 -1px 0 var(--field-focus-line);
+}
+
+.ui-textfield--disabled {
+ border-bottom-color: var(--stroke-control);
+ color: var(--text-disabled);
+ background: var(--fill-control-disabled);
+}
+
+.ui-textfield__icon {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+}
+
+.ui-textfield__input {
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ padding: 0;
+ border: 0;
+ outline: none;
+ color: var(--text-primary);
+ background: transparent;
+ box-shadow: none; /* .ui-textfield:focus-within draws it */
+ font-size: var(--text-base);
+}
+
+.ui-textfield__input:disabled {
+ color: var(--text-disabled);
+}
+
+.ui-textfield__trailing {
+ flex: none;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.ui-textfield__button {
+ width: var(--control-sm);
+ height: var(--control-sm);
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-sm);
+ color: var(--text-secondary);
+ background: transparent;
+ transition: var(--transition-control);
+}
+
+.ui-textfield__button:hover:not(:disabled) {
+ color: var(--text-primary);
+ background: var(--fill-subtle-hover);
+}
+
+.ui-textfield__button:active:not(:disabled) {
+ background: var(--fill-subtle-pressed);
+}
+
+/* ============================================================================
+ StatusBar
+ ========================================================================== */
+
+.ui-statusbar {
+ min-height: var(--control-sm);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-4);
+ padding: 0 var(--space-3);
+ border-top: 1px solid var(--line);
+ color: var(--text-secondary);
+ background: var(--layer);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+}
+
+.ui-statusbar__items {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: var(--space-4);
+ white-space: nowrap;
+}
+
+.ui-statusbar__items--end {
+ margin-left: auto;
+}