Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

ui: option data-value, cascading menus, editable ComboBox; use them for Move to and zoom

Bitti45388b70161b
diff --git a/src/components/ui/ComboBox.test.tsx b/src/components/ui/ComboBox.test.tsx
index eb06b02..06ed6a1 100644
--- a/src/components/ui/ComboBox.test.tsx
+++ b/src/components/ui/ComboBox.test.tsx
@@ -147,4 +147,105 @@ describe("ComboBox", () => {
fireEvent.keyDown(screen.getByRole("combobox"), { key: "ArrowUp" });
expect(onChange).toHaveBeenCalledWith(10);
});
+
+ it("puts each option's value on it as data-value", () => {
+ render(<ComboBox<number> aria-label="Steps" value={20} onChange={vi.fn()} options={[{ value: 10, label: "Ten" }, { value: 20, label: "Twenty" }]} />);
+ fireEvent.click(screen.getByRole("combobox"));
+ expect(screen.getAllByRole("option").map((option) => option.getAttribute("data-value"))).toEqual(["10", "20"]);
+ });
+
+ describe("editable", () => {
+ const presets: ComboItems = [{ value: "fit", label: "Fit" }, { value: "0.5", label: "50%" }, { value: "1", label: "100%" }];
+ const parsePercent = (text: string) => {
+ if (/^\s*fit\s*$/i.test(text)) return "fit";
+ const match = /^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(text);
+ if (!match) return null;
+ const percent = Number(match[1]);
+ return percent >= 10 && percent <= 800 ? String(percent / 100) : null;
+ };
+ function Zoom({ onChange }: { onChange?: (value: string) => void }) {
+ const [value, setValue] = useState("fit");
+ const text = value === "fit" ? "Fit" : `${Math.round(Number(value) * 100)}%`;
+ return <>
+ <ComboBox editable aria-label="Zoom" value={value} displayText={text} parseText={parsePercent} options={presets}
+ onChange={(next) => { setValue(next); onChange?.(next); }} />
+ <button>After</button>
+ </>;
+ }
+ const field = () => screen.getByRole("combobox", { name: "Zoom" }) as HTMLInputElement;
+
+ it("is a text field showing the display text, with the list on its button", () => {
+ const { container } = render(<Zoom />);
+ expect(field().tagName).toBe("INPUT");
+ expect(field()).toHaveValue("Fit");
+ fireEvent.click(container.querySelector(".ui-combo__button")!);
+ expect(screen.getByRole("listbox", { name: "Zoom" })).toBeInTheDocument();
+ expect(field()).toHaveFocus();
+ fireEvent.click(screen.getByRole("option", { name: "50%" }));
+ expect(field()).toHaveValue("50%");
+ expect(screen.queryByRole("listbox")).toBeNull();
+ });
+
+ it("commits typed text on Enter and on blur, through the validation callback", () => {
+ const onChange = vi.fn();
+ render(<Zoom onChange={onChange} />);
+ field().focus();
+ fireEvent.change(field(), { target: { value: "137" } });
+ fireEvent.keyDown(field(), { key: "Enter" });
+ expect(onChange).toHaveBeenLastCalledWith("1.37");
+ expect(field()).toHaveValue("137%");
+ fireEvent.change(field(), { target: { value: "250 %" } });
+ fireEvent.blur(field());
+ expect(onChange).toHaveBeenLastCalledWith("2.5");
+ expect(field()).toHaveValue("250%");
+ });
+
+ it("rejects invalid text and reverts, and Esc drops what was typed", () => {
+ const onChange = vi.fn();
+ render(<Zoom onChange={onChange} />);
+ field().focus();
+ fireEvent.change(field(), { target: { value: "huge" } });
+ fireEvent.keyDown(field(), { key: "Enter" });
+ expect(onChange).not.toHaveBeenCalled();
+ expect(field()).toHaveValue("Fit");
+ fireEvent.change(field(), { target: { value: "5000" } });
+ fireEvent.blur(field());
+ expect(onChange).not.toHaveBeenCalled();
+ expect(field()).toHaveValue("Fit");
+ fireEvent.change(field(), { target: { value: "75" } });
+ fireEvent.keyDown(field(), { key: "Escape" });
+ expect(field()).toHaveValue("Fit");
+ fireEvent.blur(field());
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("opens with Alt+Down, moves with the arrows and picks with Enter", () => {
+ const onChange = vi.fn();
+ render(<Zoom onChange={onChange} />);
+ field().focus();
+ fireEvent.keyDown(field(), { key: "ArrowDown", altKey: true });
+ expect(field()).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByRole("option", { name: "Fit" })).toHaveAttribute("aria-selected", "true");
+ fireEvent.keyDown(field(), { key: "ArrowDown" });
+ fireEvent.keyDown(field(), { key: "ArrowDown" });
+ expect(field().getAttribute("aria-activedescendant")).toBe(screen.getByRole("option", { name: "100%" }).id);
+ fireEvent.keyDown(field(), { key: "Enter" });
+ expect(onChange).toHaveBeenLastCalledWith("1");
+ expect(field()).toHaveAttribute("aria-expanded", "false");
+ expect(field()).toHaveValue("100%");
+ });
+
+ it("matches option labels by default when there is no parseText", () => {
+ const onChange = vi.fn();
+ render(<ComboBox editable aria-label="Fruit" value="apple" onChange={onChange} options={fruit} />);
+ const input = screen.getByRole("combobox", { name: "Fruit" });
+ expect(input).toHaveValue("Apple");
+ fireEvent.change(input, { target: { value: "lemon" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onChange).toHaveBeenCalledWith("lemon");
+ fireEvent.change(input, { target: { value: "durian" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/src/components/ui/ComboBox.tsx b/src/components/ui/ComboBox.tsx
index 22e73bc..f118a85 100644
--- a/src/components/ui/ComboBox.tsx
+++ b/src/components/ui/ComboBox.tsx
@@ -22,6 +22,15 @@
<ComboBox aria-label="Generator" value={id} onChange={setId}
options={[{ value: "a", label: "Alpha" }, { label: "More", options: [...] }]} />
+
+ Editable mode (`editable`) is the WinUI IsEditable ComboBox: a text field
+ with the drop-down button at its end. The list works as above; typed text
+ is committed on Enter or when focus leaves, through `parseText`, which
+ returns the value the text means or null to refuse it (the field then goes
+ back to `displayText`). Esc drops what was typed. Focus stays in the field:
+
+ <ComboBox editable aria-label="Zoom" value={preset} displayText="137%"
+ parseText={(text) => parsePercent(text)} options={presets} onChange={zoomTo} />
*/
import { ChevronDown } from "lucide-react";
@@ -75,6 +84,14 @@ export interface ComboBoxProps<V extends ComboValue = string> {
width?: number | string;
onBlur?: () => void;
onFocus?: () => void;
+ /** A text field with a drop-down button instead of a select-only button. */
+ editable?: boolean;
+ /** Editable mode: the value typed text stands for, or null to reject it.
+ * Default: the option whose label or value matches, ignoring case. */
+ parseText?: (text: string) => V | null;
+ /** Editable mode: the field's text while nothing is being typed. Default:
+ * the selected option's text (or empty). */
+ displayText?: string;
}
const isGroup = <V extends ComboValue>(item: ComboOption<V> | ComboGroup<V>): item is ComboGroup<V> =>
@@ -120,6 +137,10 @@ function flatten<V extends ComboValue>(items: ComboItems<V>): FlatOption<V>[] {
const ITEM_HEIGHT = 32;
export function ComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>) {
+ return props.editable ? <EditableComboBox {...props} /> : <SelectComboBox {...props} />;
+}
+
+function SelectComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>) {
const {
value, onChange, options, children, id, name, disabled, placeholder, className, width, onBlur, onFocus,
} = props;
@@ -299,6 +320,7 @@ export function ComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>)
<div
id={optionId(index)}
role="option"
+ data-value={String(option.value)}
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")}
@@ -319,3 +341,203 @@ export function ComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>)
</>
);
}
+
+/* --- Editable mode ------------------------------------------------------------ */
+
+function EditableComboBox<V extends ComboValue = string>(props: ComboBoxProps<V>) {
+ const {
+ value, onChange, options, children, id, name, disabled, placeholder, className, width, onBlur, onFocus, parseText, displayText,
+ } = 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 shown = displayText ?? (selectedIndex >= 0 ? flat[selectedIndex].text : "");
+
+ const [draft, setDraft] = useState<string | null>(null);
+ const [open, setOpen] = useState(false);
+ const [active, setActive] = useState(-1);
+ const [position, setPosition] = useState<CSSProperties>({ visibility: "hidden" });
+ const box = useRef<HTMLSpanElement>(null);
+ const input = useRef<HTMLInputElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+ 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 parse = (text: string): V | null => {
+ if (parseText) return parseText(text);
+ const needle = text.trim().toLowerCase();
+ const match = flat.find((option) => !option.disabled && (option.text.toLowerCase() === needle || String(option.value).toLowerCase() === needle));
+ return match ? match.value : null;
+ };
+
+ /** Commits typed text (if any). Returns true when something was typed. */
+ const commitDraft = () => {
+ if (draft === null) return false;
+ const next = draft.trim() === shown.trim() ? null : parse(draft);
+ setDraft(null);
+ if (next !== null) onChange(next);
+ return true;
+ };
+ const choose = (index: number) => {
+ const option = flat[index];
+ if (!option || option.disabled) return;
+ setDraft(null);
+ onChange(option.value);
+ };
+ const openList = () => {
+ if (disabled || !flat.length) return;
+ setActive(selectedIndex >= 0 && !flat[selectedIndex].disabled ? selectedIndex : -1);
+ setPosition({ visibility: "hidden" });
+ setOpen(true);
+ };
+ const close = () => setOpen(false);
+
+ useLightDismiss(list, open, () => close(), { ignore: [box] });
+
+ useLayoutEffect(() => {
+ if (!open || !list.current || !box.current) return;
+ const anchor = box.current.getBoundingClientRect();
+ const view = viewport();
+ const listRect = list.current.getBoundingClientRect();
+ const height = listRect.height || flat.length * ITEM_HEIGHT + 8;
+ const listWidth = Math.max(anchor.width, listRect.width);
+ const placed = placeAnchored(anchor, { width: listWidth, height }, "bottom", 4, view);
+ const left = Math.max(VIEWPORT_MARGIN, Math.min(placed.left, view.width - listWidth - VIEWPORT_MARGIN));
+ setPosition({ top: placed.top, left, minWidth: anchor.width });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ useLayoutEffect(() => {
+ if (!open || active < 0) return;
+ document.getElementById(optionId(active))?.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<HTMLInputElement>) => {
+ if (disabled) return;
+ const { key, altKey } = event;
+ if ((altKey && key === "ArrowDown") || key === "F4") {
+ event.preventDefault();
+ if (open) close(); else openList();
+ return;
+ }
+ if (key === "ArrowDown" || key === "ArrowUp") {
+ event.preventDefault();
+ if (altKey) { close(); return; }
+ if (!open) { openList(); return; }
+ // Moving through the list drops what was typed: Enter takes the item.
+ setDraft(null);
+ setActive(step(active, key === "ArrowDown" ? 1 : -1));
+ return;
+ }
+ if (key === "Enter") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!commitDraft() && open && active >= 0) choose(active);
+ close();
+ input.current?.select();
+ return;
+ }
+ if (key === "Escape") {
+ if (!open && draft === null) return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (open) close();
+ else setDraft(null);
+ return;
+ }
+ if (key === "Tab" && open) close();
+ };
+
+ const style: CSSProperties | undefined = width !== undefined ? { width: typeof width === "number" ? `${width}px` : width } : undefined;
+
+ return (
+ <>
+ <span ref={box} className={cx("ui-combo", "ui-combo--editable", disabled && "ui-combo--disabled", className)} style={style} data-tooltip={props["data-tooltip"]}>
+ <input
+ ref={input}
+ id={id}
+ type="text"
+ role="combobox"
+ className="ui-combo__input"
+ disabled={disabled}
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ aria-describedby={props["aria-describedby"]}
+ aria-autocomplete="none"
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={open ? listId : undefined}
+ aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
+ data-value={value ?? ""}
+ spellCheck={false}
+ autoComplete="off"
+ placeholder={typeof placeholder === "string" ? placeholder : undefined}
+ value={draft ?? shown}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={onKeyDown}
+ onFocus={(event) => { event.currentTarget.select(); onFocus?.(); }}
+ onBlur={() => { commitDraft(); close(); onBlur?.(); }}
+ />
+ <button
+ type="button"
+ className="ui-combo__button"
+ tabIndex={-1}
+ aria-hidden="true"
+ disabled={disabled}
+ // Keep focus (and any typing) in the field.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => { input.current?.focus(); if (open) close(); else openList(); }}
+ >
+ <ChevronDown className="ui-combo__chevron" size={12} aria-hidden="true" />
+ </button>
+ </span>
+ {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" }}
+ 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"
+ data-value={String(option.value)}
+ 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; choose(index); close(); input.current?.select(); }}
+ >
+ {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/ContextMenu.test.tsx b/src/components/ui/ContextMenu.test.tsx
index 6bb84c6..4eab79c 100644
--- a/src/components/ui/ContextMenu.test.tsx
+++ b/src/components/ui/ContextMenu.test.tsx
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { useContextMenu, type MenuEntry } from "./ContextMenu";
+import { SUBMENU_HOVER_DELAY, useContextMenu, type MenuEntry } from "./ContextMenu";
afterEach(cleanup);
@@ -129,4 +129,101 @@ describe("ContextMenu", () => {
fireEvent.keyDown(screen.getByRole("menu"), { key: "ArrowDown" });
expect(behind).not.toHaveBeenCalled();
});
+
+ describe("submenus", () => {
+ const cascade = () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const top = vi.fn();
+ const items: MenuEntry[] = [
+ { id: "top", label: "Duplicate", onSelect: top },
+ { id: "move", label: "Move to", items: [
+ { id: "a", label: "Opening", onSelect: first },
+ { id: "b", label: "Finale", onSelect: second },
+ ] },
+ ];
+ return { items, first, second, top };
+ };
+
+ it("marks the item with a chevron and opens on Right, with focus on the first entry", () => {
+ const { items, second } = cascade();
+ render(<Surface items={items} />);
+ const surface = screen.getByTestId("surface");
+ surface.focus();
+ fireEvent.keyDown(surface, { key: "F10", shiftKey: true });
+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });
+ const move = screen.getByRole("menuitem", { name: "Move to" });
+ expect(move).toHaveFocus();
+ expect(move).toHaveAttribute("aria-haspopup", "menu");
+ expect(move).toHaveAttribute("aria-expanded", "false");
+ expect(move.querySelector(".ui-menu__chevron")).not.toBeNull();
+ fireEvent.keyDown(move, { key: "ArrowRight" });
+ const sub = screen.getByRole("menu", { name: "Move to" });
+ expect(move).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByRole("menuitem", { name: "Opening" })).toHaveFocus();
+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });
+ fireEvent.keyDown(document.activeElement!, { key: "Enter" });
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(sub).not.toBeInTheDocument();
+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();
+ expect(surface).toHaveFocus();
+ });
+
+ it("closes one level with Left or Esc and puts focus back on its item", () => {
+ const { items, first } = cascade();
+ render(<Surface items={items} />);
+ const surface = screen.getByTestId("surface");
+ surface.focus();
+ fireEvent.keyDown(surface, { key: "F10", shiftKey: true });
+ fireEvent.keyDown(document.activeElement!, { key: "End" });
+ const move = screen.getByRole("menuitem", { name: "Move to" });
+ fireEvent.keyDown(move, { key: "Enter" });
+ expect(screen.getByRole("menu", { name: "Move to" })).toBeInTheDocument();
+ fireEvent.keyDown(document.activeElement!, { key: "ArrowLeft" });
+ expect(screen.queryByRole("menu", { name: "Move to" })).toBeNull();
+ expect(screen.getByRole("menu", { name: "Clip actions" })).toBeInTheDocument();
+ expect(move).toHaveFocus();
+ fireEvent.keyDown(move, { key: "ArrowRight" });
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(screen.queryByRole("menu", { name: "Move to" })).toBeNull();
+ expect(screen.getByRole("menu", { name: "Clip actions" })).toBeInTheDocument();
+ expect(move).toHaveFocus();
+ expect(first).not.toHaveBeenCalled();
+ });
+
+ it("opens on hover after a pause, closes when another item is hovered, and runs a click", () => {
+ vi.useFakeTimers();
+ try {
+ const { items, first } = cascade();
+ render(<Surface items={items} />);
+ fireEvent.contextMenu(screen.getByTestId("surface"), { clientX: 5, clientY: 5 });
+ const move = screen.getByRole("menuitem", { name: "Move to" });
+ fireEvent.mouseEnter(move);
+ expect(screen.queryByRole("menu", { name: "Move to" })).toBeNull();
+ act(() => { vi.advanceTimersByTime(SUBMENU_HOVER_DELAY); });
+ expect(screen.getByRole("menu", { name: "Move to" })).toBeInTheDocument();
+ // Hovered, not keyed: focus stays on the parent item.
+ expect(move).toHaveFocus();
+ fireEvent.mouseEnter(screen.getByRole("menuitem", { name: "Duplicate" }));
+ act(() => { vi.advanceTimersByTime(SUBMENU_HOVER_DELAY); });
+ expect(screen.queryByRole("menu", { name: "Move to" })).toBeNull();
+ fireEvent.click(move);
+ fireEvent.click(screen.getByRole("menuitem", { name: "Opening" }));
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();
+ } finally { vi.useRealTimers(); }
+ });
+
+ it("flips to the left of its item when there is no room on the right", () => {
+ const { items } = cascade();
+ render(<Surface items={items} />);
+ fireEvent.contextMenu(screen.getByTestId("surface"), { clientX: 5, clientY: 5 });
+ const move = screen.getByRole("menuitem", { name: "Move to" });
+ const width = window.innerWidth;
+ vi.spyOn(move, "getBoundingClientRect").mockReturnValue({ left: width - 180, right: width - 20, top: 100, bottom: 132, width: 160, height: 32, x: width - 180, y: 100, toJSON: () => ({}) });
+ fireEvent.click(move);
+ const sub = screen.getByRole("menu", { name: "Move to" });
+ expect(parseFloat(sub.style.left)).toBeLessThan(width - 180);
+ });
+ });
});
diff --git a/src/components/ui/ContextMenu.tsx b/src/components/ui/ContextMenu.tsx
index 000cf15..0e8cbb0 100644
--- a/src/components/ui/ContextMenu.tsx
+++ b/src/components/ui/ContextMenu.tsx
@@ -24,11 +24,20 @@
{menu.element}
`open` also takes a KeyboardEvent (anchors to its target and focuses the
- first item) or an element / DOMRect (anchors below it). */
+ first item) or an element / DOMRect (anchors below it).
-import { Check } from "lucide-react";
+ Submenus: an item with `items` instead of `onSelect` opens a cascading
+ menu beside it: on hover after a short pause, or on click, Enter, Space or
+ Right. Left or Esc closes just that level and puts focus back on its item;
+ a command anywhere in the cascade closes all of it. The item shows a
+ chevron, and the submenu flips to the left when there is no room on the
+ right:
+
+ { id: "move", label: "Move to", items: scenes.map((scene) => ({ label: scene.title, onSelect: … })) } */
+
+import { Check, ChevronRight } from "lucide-react";
import {
- useCallback, useLayoutEffect, useRef, useState,
+ useCallback, useEffect, useLayoutEffect, useRef, useState,
type CSSProperties, type KeyboardEvent, type ReactNode, type SyntheticEvent,
} from "react";
import { createPortal } from "react-dom";
@@ -49,7 +58,10 @@ export interface MenuItem {
danger?: boolean;
/** Renders a check column and role="menuitemcheckbox". */
checked?: boolean;
- onSelect: () => void;
+ /** Runs the command. Optional only for a submenu item (one with `items`). */
+ onSelect?: () => void;
+ /** Makes this a submenu item: these entries open in a cascading menu. */
+ items?: MenuEntry[];
}
export interface MenuSeparator { separator: true; id?: string }
@@ -75,13 +87,25 @@ export interface ContextMenuProps {
className?: string;
/** Minimum width in px (default 160 — Fluent's 120 is too tight for accelerators). */
minWidth?: number;
+ /** Internal, for submenus: a command ran somewhere below, close everything. */
+ onChosen?: () => void;
+ /** Internal, for submenus: Left closes this level. */
+ closeOnLeft?: boolean;
+ /** Internal, for submenus opened by hovering: leave focus on the parent item. */
+ keepFocus?: boolean;
+ /** Internal, for submenus: the pointer reached it (cancels a pending close). */
+ onPointerEnter?: () => void;
}
+/** How long the pointer rests on a submenu item before it opens. WinUI waits
+ * about this long, so a diagonal move towards the submenu does not flicker. */
+export const SUBMENU_HOVER_DELAY = 250;
+
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
+ items, position, onClose, focusFirst, restoreFocus = true, className, minWidth = 160, onChosen, closeOnLeft = false, onPointerEnter, keepFocus = false, ...aria
}: ContextMenuProps) {
const menu = useRef<HTMLDivElement>(null);
const opener = useRef<HTMLElement | null>(null);
@@ -89,6 +113,11 @@ export function ContextMenu({
const typeahead = useRef(createTypeahead());
const closeRef = useRef(onClose);
closeRef.current = onClose;
+ const [sub, setSub] = useState<{ index: number; anchor: HTMLElement; keyboard: boolean; hover: boolean; key: number } | null>(null);
+ const subCounter = useRef(0);
+ const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const clearHover = () => { if (hoverTimer.current !== undefined) { clearTimeout(hoverTimer.current); hoverTimer.current = undefined; } };
+ useEffect(() => clearHover, []);
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)") ?? [])];
@@ -106,7 +135,7 @@ export function ContextMenu({
setStyle({ left: placed.left, top: placed.top, minWidth });
const keyboard = focusFirst ?? lastInputWasKeyboard();
if (keyboard) focusSafely(buttons()[0] ?? element);
- else focusSafely(element);
+ else if (!keepFocus) focusSafely(element);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [positionKey]);
@@ -117,17 +146,40 @@ export function ContextMenu({
useLightDismiss(menu, true, (reason) => close(reason === "escape"));
- const run = (item: MenuItem) => {
+ /* A command closes the whole cascade: a submenu hands it up to the root,
+ which restores focus to whatever had it before the menu opened. */
+ const chosen = useCallback(() => {
+ if (onChosen) onChosen();
+ else close(true);
+ }, [onChosen, close]);
+
+ const openSub = (index: number, anchor: HTMLElement, keyboard: boolean, hover = false) => {
+ clearHover();
+ subCounter.current += 1;
+ setSub({ index, anchor, keyboard, hover, key: subCounter.current });
+ };
+
+ const cascadeAt = (button: HTMLElement | null) => {
+ const entry = button ? items[Number(button.dataset.index)] : undefined;
+ return entry && !isSeparator(entry) && entry.items ? Number(button!.dataset.index) : -1;
+ };
+
+ const run = (item: MenuItem, button?: HTMLElement | null) => {
if (item.disabled) return;
- close(true);
- item.onSelect();
+ if (item.items) {
+ const index = items.indexOf(item);
+ if (button && sub?.index !== index) openSub(index, button, lastInputWasKeyboard());
+ return;
+ }
+ chosen();
+ 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));
+ const accelerated = entries.find((item) => item.shortcut && !item.disabled && !item.items && matchesCombo(event.nativeEvent, item.shortcut));
if (accelerated && (event.ctrlKey || event.altKey || event.metaKey || event.key.length > 1)) {
event.preventDefault();
run(accelerated);
@@ -135,8 +187,17 @@ export function ContextMenu({
}
const list = buttons();
const index = list.indexOf(document.activeElement as HTMLButtonElement);
+ const focused = index >= 0 ? list[index] : null;
let next = -1;
switch (event.key) {
+ case "ArrowRight": {
+ const at = cascadeAt(focused);
+ if (focused && at >= 0) { event.preventDefault(); openSub(at, focused, true); }
+ return;
+ }
+ case "ArrowLeft":
+ if (closeOnLeft) { event.preventDefault(); close(true); }
+ return;
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;
@@ -145,7 +206,12 @@ export function ContextMenu({
case "Escape": event.preventDefault(); close(true); return;
case "Enter":
case " ":
- if (index >= 0) { event.preventDefault(); list[index].click(); }
+ if (focused) {
+ event.preventDefault();
+ const at = cascadeAt(focused);
+ if (at >= 0) openSub(at, focused, true);
+ else focused.click();
+ }
return;
default:
if (isPrintableKey(event)) {
@@ -157,6 +223,23 @@ export function ContextMenu({
focusSafely(list[next]);
};
+ const subItem = sub ? items[sub.index] : undefined;
+ const submenu = sub && subItem && !isSeparator(subItem) && subItem.items ? (
+ <ContextMenu
+ key={sub.key}
+ items={subItem.items}
+ position={{ anchor: sub.anchor, placement: "right" }}
+ focusFirst={sub.keyboard}
+ keepFocus={sub.hover}
+ aria-label={subItem.label}
+ minWidth={minWidth}
+ closeOnLeft
+ onChosen={chosen}
+ onPointerEnter={clearHover}
+ onClose={() => setSub(null)}
+ />
+ ) : null;
+
return createPortal(
<div
ref={menu}
@@ -167,25 +250,40 @@ export function ContextMenu({
style={style}
{...{ [LAYER_ATTR]: "menu" }}
onContextMenu={(event: SyntheticEvent) => event.preventDefault()}
+ onMouseEnter={onPointerEnter}
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;
+ const cascade = Boolean(entry.items);
return (
<button
key={entry.id ?? entry.label}
type="button"
role={checkable ? "menuitemcheckbox" : "menuitem"}
aria-checked={checkable ? entry.checked : undefined}
- aria-keyshortcuts={ariaKeyShortcuts(entry.shortcut)}
+ aria-keyshortcuts={cascade ? undefined : ariaKeyShortcuts(entry.shortcut)}
+ aria-haspopup={cascade ? "menu" : undefined}
+ aria-expanded={cascade ? sub?.index === index : undefined}
tabIndex={-1}
disabled={entry.disabled}
data-menu-item=""
+ data-index={index}
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); }}
+ className={cx("ui-menu__item", entry.danger && "ui-menu__item--danger", cascade && "ui-menu__item--cascade")}
+ onClick={(event) => run(entry, event.currentTarget)}
+ onMouseEnter={(event) => {
+ clearHover();
+ if (entry.disabled) return;
+ const button = event.currentTarget;
+ focusSafely(button);
+ if (cascade) {
+ if (sub?.index !== index) hoverTimer.current = setTimeout(() => openSub(index, button, false, true), SUBMENU_HOVER_DELAY);
+ } else if (sub) {
+ hoverTimer.current = setTimeout(() => setSub(null), SUBMENU_HOVER_DELAY);
+ }
+ }}
>
{hasGlyphColumn && (
<span className="ui-menu__glyph" aria-hidden="true">
@@ -193,10 +291,12 @@ export function ContextMenu({
</span>
)}
<span className="ui-menu__label">{entry.label}</span>
- {entry.shortcut && <kbd className="ui-menu__shortcut">{formatShortcut(entry.shortcut)}</kbd>}
+ {entry.shortcut && !cascade && <kbd className="ui-menu__shortcut">{formatShortcut(entry.shortcut)}</kbd>}
+ {cascade && <ChevronRight className="ui-menu__chevron" size={16} aria-hidden="true" />}
</button>
);
})}
+ {submenu}
</div>,
document.body,
);
diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts
index bb764b6..0e63b20 100644
--- a/src/components/ui/index.ts
+++ b/src/components/ui/index.ts
@@ -17,6 +17,9 @@
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.
+ `editable` + parseText(text) → value | null + displayText: a text field with the list
+ on a drop-down button; typed text commits on Enter / blur (the image editor's zoom).
+ Every option carries data-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.
@@ -28,7 +31,8 @@
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 }.
+ items: { id?, label, icon?, shortcut?, disabled?, checked?, onSelect } | { separator: true };
+ an item with `items: MenuEntry[]` (and no onSelect) is a cascading submenu.
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}? />
diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsx
index be57c8c..81de31d 100644
--- a/src/components/workspace/GeneratorView.test.tsx
+++ b/src/components/workspace/GeneratorView.test.tsx
@@ -884,7 +884,14 @@ describe("Generator board as a native list", () => {
const shot = screen.getByRole("button", { name: "Shot 2 of First scene" });
fireEvent.keyDown(shot, { key: "F10", shiftKey: true });
- fireEvent.click(within(screen.getByRole("menu", { name: "Shot 2 actions" })).getByRole("menuitem", { name: /Move to Second scene/ }));
+ const shotMenu = screen.getByRole("menu", { name: "Shot 2 actions" });
+ // One "Move to" item with the other scenes in a cascade, not one item per scene.
+ const moveTo = within(shotMenu).getByRole("menuitem", { name: "Move to" });
+ expect(moveTo).toHaveAttribute("aria-haspopup", "menu");
+ moveTo.focus();
+ fireEvent.keyDown(moveTo, { key: "ArrowRight" });
+ fireEvent.click(within(screen.getByRole("menu", { name: "Move to" })).getByRole("menuitem", { name: "Second scene" }));
+ expect(screen.queryByRole("menu")).toBeNull();
expect(sceneShots(state.latest().generationJobs.find((job) => job.id === "scene-second")!).map((item) => item.id)).toEqual(["shot-second-a", "shot-first-b"]);
});
diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsx
index 811094c..6a6744a 100644
--- a/src/components/workspace/ImageEditor.test.tsx
+++ b/src/components/workspace/ImageEditor.test.tsx
@@ -369,15 +369,27 @@ it("picks canvas tools from a radio group or their letter keys and zooms from th
const zoom = screen.getByRole("combobox", { name: "Image zoom" });
const frame = canvas.parentElement!;
- expect(zoom).toHaveTextContent("Fit");
+ expect(zoom).toHaveValue("Fit");
fireEvent.keyDown(canvas, { key: "=", ctrlKey: true });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.5");
- expect(zoom).toHaveTextContent("150%");
+ expect(zoom).toHaveValue("150%");
fireEvent.keyDown(canvas, { key: "-", ctrlKey: true });
fireEvent.keyDown(canvas, { key: "-", ctrlKey: true });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("0.75");
- choose("Image zoom", "200%");
+ // Presets from the drop-down button beside the field.
+ fireEvent.click(zoom.parentElement!.querySelector(".ui-combo__button")!);
+ fireEvent.click(screen.getByRole("option", { name: "200%" }));
expect(frame.style.getPropertyValue("--image-zoom")).toBe("2");
+ // Or any percentage, typed.
+ zoom.focus();
+ fireEvent.change(zoom, { target: { value: "137" } });
+ fireEvent.keyDown(zoom, { key: "Enter" });
+ expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.37");
+ expect(zoom).toHaveValue("137%");
+ fireEvent.change(zoom, { target: { value: "9000%" } });
+ fireEvent.keyDown(zoom, { key: "Enter" });
+ expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.37");
+ expect(zoom).toHaveValue("137%");
fireEvent.keyDown(canvas, { key: "0", ctrlKey: true });
- expect(zoom).toHaveTextContent("Fit");
+ expect(zoom).toHaveValue("Fit");
});
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index 8cd5fcb..d1079a8 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -381,9 +381,19 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
const zoomValue = fitted ? "fit" : zoomPresets.find((step) => Math.abs(step - view.zoom) < 1e-6)?.toString() ?? "custom";
const zoomOptions = [
{ value: "fit", label: "Fit" },
- ...(zoomValue === "custom" ? [{ value: "custom", label: `${Math.round(view.zoom * 100)}%`, disabled: true }] : []),
...zoomPresets.map((step) => ({ value: String(step), label: `${step * 100}%` })),
];
+ /* The field is editable: any percentage between the zoom limits can be
+ typed ("137", "137%", "fit"). Anything else is refused and the field
+ goes back to the current zoom. */
+ const zoomText = fitted ? "Fit" : `${Math.round(view.zoom * 100)}%`;
+ const parseZoom = (text: string): string | null => {
+ if (/^\s*fit\s*$/i.test(text)) return "fit";
+ const match = /^\s*(\d+(?:[.,]\d+)?)\s*%?\s*$/.exec(text);
+ if (!match) return null;
+ const zoom = Number(match[1].replace(",", ".")) / 100;
+ return zoom >= MIN_IMAGE_ZOOM - 1e-9 && zoom <= MAX_IMAGE_ZOOM + 1e-9 ? String(zoom) : null;
+ };
const tree = (node: ImageNode, depth: number) => {
const children = scene.nodes.filter((child) => child.parentId === node.id);
@@ -498,12 +508,15 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
</div>
<span className="image-tools__separator" role="separator" aria-orientation="vertical" />
<ComboBox
+ editable
className="image-zoom"
aria-label="Image zoom"
data-tooltip="Zoom (Ctrl+0 fit, Ctrl+1 100%, Ctrl+= in, Ctrl+- out)"
value={zoomValue}
+ displayText={zoomText}
+ parseText={parseZoom}
options={zoomOptions}
- onChange={(value) => { if (value === "fit") fit(); else if (value !== "custom") zoomTo(Number(value)); }}
+ onChange={(value) => { if (value === "fit") fit(); else zoomTo(Number(value)); }}
/>
</div>
<div ref={viewport} tabIndex={-1} className={`image-viewport${panning ? " panning" : ""}`} data-tooltip="Scroll to zoom · drag with the middle button to pan"
diff --git a/src/components/workspace/SceneBoard.tsx b/src/components/workspace/SceneBoard.tsx
index b9ebab6..508e10b 100644
--- a/src/components/workspace/SceneBoard.tsx
+++ b/src/components/workspace/SceneBoard.tsx
@@ -151,14 +151,17 @@ export function SceneBoard({
return [
{ id: "open", label: "Open", icon: <ExternalLink size={16} />, onSelect: () => onSelect({ jobId: job.id, shotId: shot.id }) },
{ id: "rename", label: "Rename", icon: <Pencil size={16} />, shortcut: "F2", disabled: !onRename, onSelect: () => onRename?.({ jobId: job.id, shotId: shot.id }) },
- ...(others.length ? [{ separator: true } as const] : []),
- ...others.map((target): MenuEntry => ({
- id: `move-${target.id}`,
- label: `Move to ${target.title}`,
+ ...(others.length ? [{ separator: true } as const, {
+ id: "move-to",
+ label: "Move to",
icon: <FolderInput size={16} />,
disabled: alone,
- onSelect: () => onMoveShot(job.id, shot.id, target.id, null),
- })),
+ items: others.map((target): MenuEntry => ({
+ id: `move-${target.id}`,
+ label: target.title,
+ onSelect: () => onMoveShot(job.id, shot.id, target.id, null),
+ })),
+ }] : []),
{ separator: true },
{ id: "delete", label: "Delete", icon: <Trash2 size={16} />, shortcut: "Delete", danger: true, disabled: alone || !onRemoveShot, onSelect: () => onRemoveShot?.(job, shot.id) },
];
diff --git a/src/styles/ui.css b/src/styles/ui.css
index 6d71c77..ee9e93d 100644
--- a/src/styles/ui.css
+++ b/src/styles/ui.css
@@ -262,6 +262,62 @@
color: var(--text-disabled);
}
+/* Editable: a text field with the drop-down button at its end. The frame is
+ the field's (hover fill, the accent underline while typing); the input and
+ the button inside it are bare. */
+.ui-combo--editable {
+ gap: 0;
+ padding: 0;
+ overflow: hidden;
+}
+
+.ui-combo--editable:focus-within,
+.ui-combo--editable:focus-within:hover {
+ border-bottom-color: var(--field-focus-line);
+ box-shadow: inset 0 -1px 0 var(--field-focus-line);
+ background: var(--fill-input-focus);
+}
+
+.ui-combo--editable.ui-combo--disabled {
+ color: var(--text-disabled);
+ background: var(--fill-control-disabled);
+}
+
+.ui-combo__input {
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ padding: 0 var(--space-2) 0 var(--space-3);
+ border: 0;
+ color: inherit;
+ background: transparent;
+}
+
+.ui-combo__input:focus,
+.ui-combo__input:focus-visible {
+ outline: none;
+ border: 0;
+ box-shadow: none;
+}
+
+.ui-combo__button {
+ width: var(--control-md);
+ height: 100%;
+ flex: none;
+ display: inline-grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ transition: var(--transition-control);
+}
+
+.ui-combo__button:hover:not(:disabled) { background: var(--fill-subtle-hover); }
+.ui-combo__button:active:not(:disabled) { background: var(--fill-subtle-pressed); }
+
+.ui-combo__button .ui-combo__chevron { margin: 0; }
+
.ui-combo__list {
position: fixed;
z-index: 950;
@@ -832,6 +888,19 @@
line-height: var(--leading-snug);
}
+/* A submenu item: a chevron where the accelerator would be, and the item
+ stays lit while its cascade is open (focus may already be in it). */
+.ui-menu__chevron {
+ flex: none;
+ margin-left: var(--space-5);
+ margin-right: calc(-1 * var(--space-1));
+ color: var(--text-secondary);
+}
+
+.ui-menu__item[aria-expanded="true"]:not(:disabled) {
+ background: var(--fill-subtle-hover);
+}
+
.ui-menu__separator {
height: 1px;
flex: none;