Skip to content

Write HTML. Render video. Built for agents.

feat(studio): shared menu, popover and value-control primitives (#4191)

Miguel Ángel3ec26b5e27d0
diff --git a/packages/studio/src/components/ui/Input.tsx b/packages/studio/src/components/ui/Input.tsx
new file mode 100644
index 0000000000..e3927c8d53
--- /dev/null
+++ b/packages/studio/src/components/ui/Input.tsx
@@ -0,0 +1,115 @@
+/**
+ * Input: a boxed text field. Typing edits a local draft; Enter and blur commit it,
+ * Escape abandons it. `onTrack` fires once per commit, never per keystroke.
+ */
+
+import { Input as BaseInput } from "@base-ui/react/input";
+import { useEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
+import { cn } from "./cn";
+import type { PreviewState } from "./Button";
+
+/**
+ * Shared field look (also used by NumberField and Select). Each interactive state is written
+ * twice, real and `data-[preview-state=...]`; `valueControls.test.tsx` asserts the lists match.
+ */
+export const fieldBase = cn(
+ "flex min-w-0 items-center gap-1.5 h-ctl px-2 rounded-md",
+ "bg-input border border-border-input text-step-11 font-medium text-text-1",
+ "transition-[border-color,background-color] ease-standard duration-focus",
+ "hover:border-border-strong data-[preview-state=hover]:border-border-strong",
+ "outline-hidden",
+ "focus-within:outline-solid focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-accent",
+ "data-[preview-state=focus]:outline-solid data-[preview-state=focus]:outline-2 data-[preview-state=focus]:outline-offset-1 data-[preview-state=focus]:outline-accent",
+ // `aria-invalid` is not one of Tailwind's built-in aria variants, so the
+ // arbitrary form is the one that compiles. The token gate would have caught
+ // the bare `aria-invalid:` spelling as a class that resolves to nothing.
+ "aria-[invalid]:border-danger",
+ "has-[:disabled]:opacity-40 has-[:disabled]:cursor-not-allowed",
+);
+
+/** The text itself, inside the box. The box owns the border and the ring. */
+export const fieldText = cn(
+ "min-w-0 w-full bg-transparent text-inherit outline-hidden",
+ "placeholder:text-text-5 disabled:cursor-not-allowed",
+);
+
+export interface InputProps extends Omit<
+ ComponentPropsWithoutRef<"input">,
+ "value" | "onChange" | "className"
+> {
+ /** The committed value. A draft lives inside until Enter or blur. */
+ value: string;
+ /** Called with the draft on Enter and on blur, only when it really changed. */
+ onCommit: (next: string) => void;
+ /** Called once per committed change, for design-input telemetry. */
+ onTrack?: () => void;
+ /** Marks the field invalid: red boundary and `aria-invalid`. */
+ invalid?: boolean;
+ className?: string;
+ "data-preview-state"?: PreviewState;
+}
+
+export function Input({
+ value,
+ onCommit,
+ onTrack,
+ invalid,
+ disabled,
+ className,
+ "data-preview-state": previewState,
+ ...props
+}: InputProps) {
+ const [draft, setDraft] = useState(value);
+ const valueRef = useRef(value);
+ valueRef.current = value;
+ const dirtyRef = useRef(false);
+
+ // An external write (a seek, an undo, another panel) is authoritative, but it
+ // must not eat what the user is halfway through typing.
+ useEffect(() => {
+ if (!dirtyRef.current) setDraft(value);
+ }, [value]);
+
+ const commit = (next: string) => {
+ dirtyRef.current = false;
+ if (next === valueRef.current) return;
+ onCommit(next);
+ onTrack?.();
+ };
+
+ return (
+ <div
+ className={cn(fieldBase, className)}
+ aria-invalid={invalid || undefined}
+ data-preview-state={previewState}
+ >
+ <BaseInput
+ value={draft}
+ disabled={disabled}
+ aria-invalid={invalid || undefined}
+ className={fieldText}
+ onValueChange={(next) => {
+ dirtyRef.current = true;
+ setDraft(next);
+ }}
+ onBlur={() => commit(draft)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit(draft);
+ return;
+ }
+ if (event.key === "Escape") {
+ // Abandon the draft rather than leave it for the blur commit.
+ event.preventDefault();
+ event.stopPropagation();
+ dirtyRef.current = false;
+ setDraft(valueRef.current);
+ event.currentTarget.blur();
+ }
+ }}
+ {...props}
+ />
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/ui/Menu.test.tsx b/packages/studio/src/components/ui/Menu.test.tsx
new file mode 100644
index 0000000000..261ce83edf
--- /dev/null
+++ b/packages/studio/src/components/ui/Menu.test.tsx
@@ -0,0 +1,374 @@
+// @vitest-environment happy-dom
+/** Menu, ContextMenu and Popover: key/aria behaviour, dismissal, and that emitted classes resolve. */
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import React, { act, useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { compile } from "tailwindcss";
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+import { loadStylesheet, STYLES_DIR } from "../../styles/styleSources";
+import { ContextMenu, Menu, MenuItem, MenuRadioGroup, MenuRadioItem, MenuSeparator } from "./Menu";
+import { Popover } from "./Popover";
+import { isTypingTarget } from "../../utils/typingTarget";
+import { shouldIgnorePlaybackShortcutTarget } from "../../player/lib/playbackShortcuts";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let mounted: { root: Root; host: HTMLElement } | null = null;
+
+function render(element: React.ReactElement): HTMLElement {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ mounted = { root, host };
+ act(() => root.render(element));
+ return host;
+}
+
+afterEach(() => {
+ if (!mounted) return;
+ const { root, host } = mounted;
+ mounted = null;
+ act(() => root.unmount());
+ host.remove();
+});
+
+/** Base UI moves focus into the popup one task after open, not synchronously. */
+async function settle(): Promise<void> {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+function press(target: Element): void {
+ // `composed` is what a real browser sets: without it the event never crosses
+ // a shadow boundary and Base UI's document listener never sees it.
+ const init = { bubbles: true, cancelable: true, composed: true };
+ act(() => {
+ target.dispatchEvent(new PointerEvent("pointerdown", init));
+ target.dispatchEvent(new MouseEvent("mousedown", init));
+ });
+}
+
+/**
+ * A mouse click, spelled out: bare `.click()` reads as keyboard activation to Base UI,
+ * which pre-highlights the first item and shifts every arrow-key assertion by one.
+ */
+function clickWithMouse(target: Element): void {
+ const init = { bubbles: true, cancelable: true, composed: true, detail: 1 };
+ act(() => {
+ target.dispatchEvent(new PointerEvent("pointerdown", { ...init, pointerType: "mouse" }));
+ target.dispatchEvent(new MouseEvent("mousedown", init));
+ target.dispatchEvent(new PointerEvent("pointerup", { ...init, pointerType: "mouse" }));
+ target.dispatchEvent(new MouseEvent("mouseup", init));
+ target.dispatchEvent(new MouseEvent("click", init));
+ });
+}
+
+function key(k: string, target: Element | null = document.activeElement): void {
+ const init = { key: k, bubbles: true, cancelable: true, composed: true };
+ act(() => {
+ (target ?? document.body).dispatchEvent(new KeyboardEvent("keydown", init));
+ (target ?? document.body).dispatchEvent(new KeyboardEvent("keyup", init));
+ });
+}
+
+function one<T extends Element>(selector: string, what: string): T {
+ const el = document.querySelector<T>(selector);
+ if (!el) throw new Error(`${what} not rendered`);
+ return el;
+}
+
+const trigger = () => one<HTMLElement>('[data-testid="trigger"]', "trigger");
+const popup = () => document.querySelector<HTMLElement>('[role="menu"]');
+const items = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+
+/** A Studio element menu: actions, a hairline, a destructive item; `disabled` marks the passed label. */
+function ActionMenu({
+ activated,
+ disable,
+}: {
+ activated: string[];
+ disable?: string;
+}): React.JSX.Element {
+ return (
+ <Menu trigger={<button data-testid="trigger">Actions</button>} aria-label="Element actions">
+ <MenuItem shortcut="⌘]" onClick={() => activated.push("front")}>
+ Bring to front
+ </MenuItem>
+ <MenuItem disabled={disable === "group"} onClick={() => activated.push("group")}>
+ Group
+ </MenuItem>
+ <MenuSeparator />
+ <MenuItem tone="danger" shortcut="⌫" onClick={() => activated.push("delete")}>
+ Delete
+ </MenuItem>
+ </Menu>
+ );
+}
+
+async function openActionMenu(activated: string[] = [], disable?: string): Promise<void> {
+ render(<ActionMenu activated={activated} disable={disable} />);
+ clickWithMouse(trigger());
+ await settle();
+ expect(popup()).not.toBeNull();
+}
+
+describe("Menu behaviour", () => {
+ // AE5.
+ it("activates the second item with ArrowDown twice then Enter, and closes", async () => {
+ const activated: string[] = [];
+ await openActionMenu(activated);
+
+ key("ArrowDown");
+ key("ArrowDown");
+ key("Enter");
+ await settle();
+
+ expect(activated).toEqual(["group"]);
+ expect(popup()).toBeNull();
+ });
+
+ it("does not activate a disabled item, and the arrow keys reach past it", async () => {
+ const activated: string[] = [];
+ await openActionMenu(activated, "group");
+
+ const [, disabled, last] = items();
+ expect(disabled.getAttribute("data-disabled")).not.toBeNull();
+ expect(disabled.getAttribute("aria-disabled")).toBe("true");
+
+ // Base UI keeps a disabled item in the roving sequence (the ARIA menu
+ // pattern: a disabled command stays discoverable). So the guarantee is not
+ // that the highlight skips it, it is that nothing runs when it is aimed at
+ // directly, by key or by pointer.
+ key("ArrowDown");
+ key("ArrowDown");
+ expect(disabled.getAttribute("data-highlighted")).not.toBeNull();
+ key("Enter", disabled);
+ act(() => disabled.click());
+ await settle();
+
+ expect(activated).toEqual([]);
+ expect(popup()).not.toBeNull();
+
+ // And the item after it is still reachable, so a disabled row is not a wall.
+ key("ArrowDown");
+ key("Enter");
+ await settle();
+
+ expect(activated).toEqual(["delete"]);
+ expect(last.isConnected).toBe(false);
+ });
+
+ it("renders a shortcut hint that assistive tech does not read as a label", async () => {
+ await openActionMenu();
+
+ const hint = one<HTMLElement>('[role="menuitem"] span[aria-hidden="true"]', "shortcut hint");
+
+ expect(hint.textContent).toBe("⌘]");
+ expect(items()[0].textContent).toContain("Bring to front");
+ });
+
+ it("closes on an outside press that a parent stops in the bubble phase", async () => {
+ // U3's finding, on the shipped component: the canvas overlay swallows
+ // bubble-phase pointer events, and Base UI's dismissal listens in capture.
+ const swallow = (event: React.SyntheticEvent) => event.stopPropagation();
+ render(
+ <div onPointerDown={swallow} onMouseDown={swallow}>
+ <div data-testid="overlay" aria-label="Composition canvas">
+ overlay
+ </div>
+ <Menu trigger={<button data-testid="trigger">Actions</button>} aria-label="Actions">
+ <MenuItem>Bring to front</MenuItem>
+ </Menu>
+ </div>,
+ );
+ act(() => trigger().click());
+ await settle();
+ expect(popup()).not.toBeNull();
+
+ // Witness: a bubble-phase document listener is the thing the overlay
+ // starves. If it starts firing, the press stopped being swallowed and this
+ // test would pass for a reason that says nothing about capture-phase
+ // dismissal.
+ let sawBubblePress = false;
+ const witness = () => {
+ sawBubblePress = true;
+ };
+ document.addEventListener("pointerdown", witness);
+ press(one('[data-testid="overlay"]', "overlay"));
+ document.removeEventListener("pointerdown", witness);
+
+ expect(sawBubblePress).toBe(false);
+ expect(popup()).toBeNull();
+ });
+});
+
+describe("MenuRadioGroup", () => {
+ it("selects one item and unselects the rest, and reports aria-checked", async () => {
+ function SpeedMenu(): React.JSX.Element {
+ const [rate, setRate] = useState(1);
+ return (
+ <Menu trigger={<button data-testid="trigger">{rate}x</button>} aria-label="Playback speed">
+ <MenuRadioGroup value={rate} onValueChange={(next) => setRate(next as number)}>
+ {[0.5, 1, 2].map((speed) => (
+ <MenuRadioItem key={speed} value={speed}>
+ {speed}x
+ </MenuRadioItem>
+ ))}
+ </MenuRadioGroup>
+ </Menu>
+ );
+ }
+ render(<SpeedMenu />);
+ act(() => trigger().click());
+ await settle();
+
+ const radios = () => [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
+ const checked = () => radios().filter((el) => el.getAttribute("aria-checked") === "true");
+
+ expect(radios()).toHaveLength(3);
+ expect(checked().map((el) => el.textContent)).toEqual(["1x"]);
+
+ act(() => radios()[2].click());
+ await settle();
+
+ expect(checked().map((el) => el.textContent)).toEqual(["2x"]);
+ expect(trigger().textContent).toBe("2x");
+ });
+});
+
+describe("ContextMenu", () => {
+ it("opens on a right click over its area and closes when an item runs", async () => {
+ const activated: string[] = [];
+ render(
+ <ContextMenu
+ aria-label="Clip actions"
+ trigger={
+ <div data-testid="trigger">
+ <span>clip</span>
+ </div>
+ }
+ >
+ <MenuItem onClick={() => activated.push("split")}>Split</MenuItem>
+ </ContextMenu>,
+ );
+
+ // The trigger renders the caller's element and keeps its children.
+ expect(trigger().textContent).toBe("clip");
+ expect(popup()).toBeNull();
+
+ act(() => {
+ trigger().dispatchEvent(
+ new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true }),
+ );
+ });
+ await settle();
+ expect(popup()).not.toBeNull();
+
+ act(() => items()[0].click());
+ await settle();
+
+ expect(activated).toEqual(["split"]);
+ expect(popup()).toBeNull();
+ });
+});
+
+describe("Popover", () => {
+ it("leaves the keys of a text field inside it alone", async () => {
+ // The Menu owns ArrowDown and typeahead; a Popover must not, or the rename
+ // field in AssetContextMenu would lose its own caret keys.
+ render(
+ <Popover trigger={<button data-testid="trigger">Rename</button>} aria-label="Rename asset">
+ <input data-testid="rename" defaultValue="scene1" />
+ </Popover>,
+ );
+ act(() => trigger().click());
+ await settle();
+
+ const input = one<HTMLInputElement>('[data-testid="rename"]', "rename field");
+ act(() => input.focus());
+ expect(document.activeElement).toBe(input);
+
+ key("ArrowDown");
+ key("ArrowUp");
+ key("s");
+ await settle();
+
+ expect(document.activeElement).toBe(input);
+ expect(document.querySelector('[role="menu"]')).toBeNull();
+ });
+});
+
+describe("hotkey classification", () => {
+ it("classifies menu rows and popover contents the way the menus they replace were", async () => {
+ // `typingTarget` and `playbackShortcuts` match exact role strings; Base UI renders
+ // a `<div>` with those roles, so the roles alone must carry the classification.
+ render(
+ <>
+ <Menu trigger={<button data-testid="trigger">Actions</button>} aria-label="Actions">
+ <MenuItem>Split</MenuItem>
+ <MenuRadioGroup value={1}>
+ <MenuRadioItem value={1}>1x</MenuRadioItem>
+ </MenuRadioGroup>
+ </Menu>
+ </>,
+ );
+ act(() => trigger().click());
+ await settle();
+
+ const row = one('[role="menuitem"]', "menu item");
+ const radio = one('[role="menuitemradio"]', "radio item");
+
+ for (const el of [row, radio]) {
+ expect(isTypingTarget(el)).toBe(false);
+ expect(shouldIgnorePlaybackShortcutTarget(el)).toBe(true);
+ }
+ });
+
+ it("treats a field inside a Popover as somewhere the user is typing", async () => {
+ render(
+ <Popover trigger={<button data-testid="trigger">Rename</button>} aria-label="Rename asset">
+ <input data-testid="rename" defaultValue="scene1" />
+ </Popover>,
+ );
+ act(() => trigger().click());
+ await settle();
+
+ const input = one('[data-testid="rename"]', "rename field");
+
+ expect(isTypingTarget(input)).toBe(true);
+ expect(shouldIgnorePlaybackShortcutTarget(input)).toBe(true);
+ });
+});
+
+/**
+ * Class resolution is covered by `styles/tokenGate.test.ts`; this checks what the compiled rule
+ * does (AE4).
+ */
+describe("open motion", () => {
+ let compileStudioCss: (candidates: string[]) => string;
+
+ beforeAll(async () => {
+ const compiled = await compile(readFileSync(path.join(STYLES_DIR, "studio.css"), "utf8"), {
+ base: STYLES_DIR,
+ // Tailwind's signature wants a promise; the shared resolver is sync.
+ loadStylesheet: async (id, base) => loadStylesheet(id, base),
+ });
+ compileStudioCss = (candidates) => compiled.build(candidates);
+ });
+
+ // AE4.
+ it("names a motion token that zeroes itself under reduced motion", async () => {
+ // The zero-duration case lives in the `duration-open` utility itself
+ // (theme.css), not in a `motion-reduce:` class beside it, so a caller
+ // cannot use the token and forget the reduced-motion half. The menu's job
+ // is to name the token; the stylesheet's job is the media query.
+ await openActionMenu();
+
+ expect([...popup()!.classList]).toContain("duration-open");
+ expect(compileStudioCss(["duration-open"])).toMatch(
+ /\.duration-open \{[\s\S]*?prefers-reduced-motion: reduce[\s\S]*?transition-duration: 0ms/,
+ );
+ });
+});
diff --git a/packages/studio/src/components/ui/Menu.tsx b/packages/studio/src/components/ui/Menu.tsx
new file mode 100644
index 0000000000..c3daf04153
--- /dev/null
+++ b/packages/studio/src/components/ui/Menu.tsx
@@ -0,0 +1,213 @@
+/**
+ * Menu and ContextMenu on Base UI. Dismissal is plain Base UI (capture-phase listeners survive the overlay's
+ * `stopPropagation`); `trigger` is rendered, not wrapped; `container` exists for shadow roots.
+ */
+
+import { ContextMenu as BaseContextMenu } from "@base-ui/react/context-menu";
+import { Menu as BaseMenu } from "@base-ui/react/menu";
+import type { ComponentPropsWithoutRef, ElementType, ReactElement, ReactNode } from "react";
+import { cn } from "./cn";
+
+/**
+ * Base UI lets `className` be a function of the part's state. Studio's parts
+ * merge a string with `cn`, so the string form is the one they accept.
+ */
+type StyledProps<T extends ElementType> = Omit<ComponentPropsWithoutRef<T>, "className"> & {
+ className?: string;
+};
+
+/** Forces the settled open look for a gallery shot; CSS-only, open state stays controlled. */
+export type PopupPreviewState = "open";
+
+/** Where the portal puts the popup. `null` keeps it inline, next to its trigger. */
+type PortalContainer = ComponentPropsWithoutRef<typeof BaseMenu.Portal>["container"];
+
+/** Matches Tooltip's gap from its trigger, and its viewport margin. */
+const SIDE_OFFSET = 6;
+const VIEWPORT_MARGIN = 8;
+
+/**
+ * Chrome shared by every floating panel (`Popover` too); callers add their own shadow token.
+ * `data-starting-style`/`data-ending-style` are Base UI's transition attributes.
+ */
+export const popupSurface = cn(
+ "rounded-lg border border-border-input bg-surface",
+ "origin-[var(--transform-origin)] outline-hidden",
+ "transition-[opacity,transform] ease-out-quint duration-open",
+ "data-[starting-style]:opacity-0 data-[starting-style]:scale-95",
+ "data-[ending-style]:opacity-0 data-[ending-style]:scale-95",
+ "data-[preview-state=open]:opacity-100 data-[preview-state=open]:scale-100",
+);
+
+/** The popup's own layer: menus sit above panel chrome and below a modal. */
+const POPUP_LAYER = "z-200";
+
+const menuPopup = cn(popupSurface, "min-w-36 p-1 shadow-menu");
+
+/** One row. `data-highlighted` is set by keyboard and pointer alike, so the seen row is the Enter row. */
+const itemBase = cn(
+ "flex cursor-default select-none items-center justify-between gap-6 rounded-sm px-2 py-1.5",
+ "text-step-11 whitespace-nowrap text-text-1",
+ "outline-hidden transition-colors ease-out-quint duration-hover",
+ "data-[highlighted]:bg-hover data-[highlighted]:text-text-0",
+ "data-[preview-state=hover]:bg-hover data-[preview-state=hover]:text-text-0",
+ "data-[disabled]:pointer-events-none data-[disabled]:opacity-40",
+);
+
+const itemDanger = cn("text-danger data-[highlighted]:bg-danger/15 data-[highlighted]:text-danger");
+
+export type MenuItemTone = "default" | "danger";
+
+interface PositionedProps {
+ side?: "top" | "bottom" | "left" | "right";
+ align?: "start" | "center" | "end";
+ sideOffset?: number;
+ /** Portal target. Pass the shadow root when the trigger lives in one. */
+ container?: PortalContainer;
+ /** Names the popup for assistive tech. A menu with no name is unlabelled. */
+ "aria-label"?: string;
+ className?: string;
+ "data-preview-state"?: PopupPreviewState;
+}
+
+interface MenuProps
+ extends PositionedProps, Omit<ComponentPropsWithoutRef<typeof BaseMenu.Root>, "children"> {
+ /** A single element. It becomes the trigger; no wrapper is added around it. */
+ trigger: ReactElement;
+ /** The items: `MenuItem`, `MenuRadioGroup`, `MenuSeparator`. */
+ children: ReactNode;
+}
+
+/**
+ * A menu opened by its trigger. Uncontrolled by default; pass `open` and
+ * `onOpenChange` for a menu whose state lives in a store.
+ */
+export function Menu({
+ trigger,
+ children,
+ side = "bottom",
+ align = "start",
+ sideOffset = SIDE_OFFSET,
+ container,
+ className,
+ "aria-label": ariaLabel,
+ "data-preview-state": previewState,
+ ...root
+}: MenuProps) {
+ return (
+ <BaseMenu.Root {...root}>
+ <BaseMenu.Trigger render={trigger} />
+ <BaseMenu.Portal container={container}>
+ <BaseMenu.Positioner
+ side={side}
+ align={align}
+ sideOffset={sideOffset}
+ collisionPadding={VIEWPORT_MARGIN}
+ className={POPUP_LAYER}
+ >
+ <BaseMenu.Popup
+ aria-label={ariaLabel}
+ data-preview-state={previewState}
+ className={cn(menuPopup, className)}
+ >
+ {children}
+ </BaseMenu.Popup>
+ </BaseMenu.Positioner>
+ </BaseMenu.Portal>
+ </BaseMenu.Root>
+ );
+}
+
+interface ContextMenuProps
+ extends PositionedProps, Omit<ComponentPropsWithoutRef<typeof BaseContextMenu.Root>, "children"> {
+ /**
+ * The right-clickable area, as the caller's own element. Its children are
+ * kept: the trigger renders that element rather than wrapping it.
+ */
+ trigger: ReactElement;
+ children: ReactNode;
+}
+
+/** Opened by right click or long press at the pointer, so `side` and `align` are not offered. */
+export function ContextMenu({
+ trigger,
+ children,
+ container,
+ className,
+ "aria-label": ariaLabel,
+ "data-preview-state": previewState,
+ ...root
+}: Omit<ContextMenuProps, "side" | "align" | "sideOffset">) {
+ return (
+ <BaseContextMenu.Root {...root}>
+ <BaseContextMenu.Trigger render={trigger} />
+ <BaseContextMenu.Portal container={container}>
+ <BaseContextMenu.Positioner collisionPadding={VIEWPORT_MARGIN} className={POPUP_LAYER}>
+ <BaseContextMenu.Popup
+ aria-label={ariaLabel}
+ data-preview-state={previewState}
+ className={cn(menuPopup, className)}
+ >
+ {children}
+ </BaseContextMenu.Popup>
+ </BaseContextMenu.Positioner>
+ </BaseContextMenu.Portal>
+ </BaseContextMenu.Root>
+ );
+}
+
+/** Keyboard shortcut hint, mono and tabular; exported for hints that are not a plain string. */
+export function MenuShortcut({ className, ...props }: StyledProps<"span">) {
+ return (
+ <span
+ className={cn("shrink-0 font-mono text-step-10 tabular-nums text-text-4", className)}
+ aria-hidden="true"
+ {...props}
+ />
+ );
+}
+
+interface MenuItemProps extends StyledProps<typeof BaseMenu.Item> {
+ /** Rendered as a dim mono hint on the trailing edge. Decorative. */
+ shortcut?: string;
+ /** `danger` for a destructive action (Delete, Remove). */
+ tone?: MenuItemTone;
+ "data-preview-state"?: "hover";
+}
+
+/** One action. `disabled` items are skipped by the arrow keys, not just dimmed. */
+export function MenuItem({ shortcut, tone, className, children, ...props }: MenuItemProps) {
+ return (
+ <BaseMenu.Item className={cn(itemBase, tone === "danger" && itemDanger, className)} {...props}>
+ <span className="truncate">{children}</span>
+ {shortcut ? <MenuShortcut>{shortcut}</MenuShortcut> : null}
+ </BaseMenu.Item>
+ );
+}
+
+/** Single-choice group; selection is `aria-checked` on each item, which the dot indicator draws from. */
+export function MenuRadioGroup(props: ComponentPropsWithoutRef<typeof BaseMenu.RadioGroup>) {
+ return <BaseMenu.RadioGroup {...props} />;
+}
+
+interface MenuRadioItemProps extends StyledProps<typeof BaseMenu.RadioItem> {
+ "data-preview-state"?: "hover";
+}
+
+/** One choice in a `MenuRadioGroup`. The dot renders only while it is checked. */
+export function MenuRadioItem({ className, children, ...props }: MenuRadioItemProps) {
+ return (
+ <BaseMenu.RadioItem className={cn(itemBase, className)} {...props}>
+ <span className="truncate">{children}</span>
+ {/* Fixed box so a checked and an unchecked row keep the same width. */}
+ <span className="flex size-3 shrink-0 items-center justify-center">
+ <BaseMenu.RadioItemIndicator className="size-1.5 rounded-full bg-accent" />
+ </span>
+ </BaseMenu.RadioItem>
+ );
+}
+
+/** A hairline between two groups of items. */
+export function MenuSeparator({ className, ...props }: StyledProps<typeof BaseMenu.Separator>) {
+ return <BaseMenu.Separator className={cn("my-1 h-px bg-hairline", className)} {...props} />;
+}
diff --git a/packages/studio/src/components/ui/NumberField.tsx b/packages/studio/src/components/ui/NumberField.tsx
new file mode 100644
index 0000000000..bfbfb281de
--- /dev/null
+++ b/packages/studio/src/components/ui/NumberField.tsx
@@ -0,0 +1,122 @@
+/**
+ * NumberField: the inspector's metric control. Commits only on blur, Enter, or a settled step (KTD11),
+ * never per keystroke. The unit is a sibling of the input; unparseable text shows a red boundary and commits nothing.
+ */
+
+import { NumberField as BaseNumberField } from "@base-ui/react/number-field";
+import { useEffect, useRef, useState } from "react";
+import { cn } from "./cn";
+import { fieldBase, fieldText } from "./Input";
+import type { PreviewState } from "./Button";
+
+export interface NumberFieldProps {
+ /** Accessible name. The inspector's row label is the usual one. */
+ label: string;
+ /** The committed value. */
+ value: number;
+ /** Called when a commit boundary produces a value different from `value`. */
+ onCommit: (next: number) => void;
+ /** Called once per committed change, for design-input telemetry. */
+ onTrack?: () => void;
+ /** Rendered beside the number: "px", "%", "deg". Never part of the text. */
+ unit?: string;
+ min?: number;
+ max?: number;
+ step?: number;
+ disabled?: boolean;
+ className?: string;
+ "data-preview-state"?: PreviewState;
+}
+
+export function NumberField({
+ label,
+ value,
+ onCommit,
+ onTrack,
+ unit,
+ min,
+ max,
+ step,
+ disabled,
+ className,
+ "data-preview-state": previewState,
+}: NumberFieldProps) {
+ const [draft, setDraft] = useState<number | null>(value);
+ const [invalid, setInvalid] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+ // What was last handed to `onCommit`, which is not the same as `value`: a
+ // blur can fire both Base UI's commit and ours in one turn, before the parent
+ // has re-rendered with the new prop, and the second must be a no-op.
+ const committedRef = useRef(value);
+ const valueRef = useRef(value);
+ valueRef.current = value;
+
+ useEffect(() => {
+ committedRef.current = value;
+ setDraft(value);
+ setInvalid(false);
+ }, [value]);
+
+ const commit = (next: number | null) => {
+ if (next === null || !Number.isFinite(next)) {
+ setInvalid(true);
+ return;
+ }
+ setInvalid(false);
+ if (next === committedRef.current) return;
+ committedRef.current = next;
+ onCommit(next);
+ onTrack?.();
+ };
+
+ /** Enter commits what is on screen, which Base UI has not parsed for us yet. */
+ const commitFromText = () => {
+ const text = inputRef.current?.value.trim() ?? "";
+ commit(text === "" ? null : Number(text));
+ };
+
+ return (
+ <BaseNumberField.Root
+ value={draft}
+ min={min}
+ max={max}
+ step={step}
+ disabled={disabled}
+ onValueChange={(next) => {
+ setDraft(next);
+ if (next !== null) setInvalid(false);
+ }}
+ onValueCommitted={(next) => commit(next)}
+ >
+ <BaseNumberField.Group
+ className={cn(fieldBase, className)}
+ aria-invalid={invalid || undefined}
+ data-preview-state={previewState}
+ >
+ <BaseNumberField.Input
+ ref={inputRef}
+ aria-label={label}
+ aria-invalid={invalid || undefined}
+ className={cn(fieldText, "tabular-nums")}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ commitFromText();
+ }}
+ onBlur={() => {
+ // Base UI's own blur handler returns without committing when the
+ // text does not parse. That is the only case left for us: a valid
+ // blur has already arrived through `onValueCommitted`.
+ const text = inputRef.current?.value.trim() ?? "";
+ if (text === "" || !Number.isFinite(Number(text))) setInvalid(true);
+ }}
+ />
+ {unit && (
+ <span className="shrink-0 select-none text-step-10 text-text-4" aria-hidden="true">
+ {unit}
+ </span>
+ )}
+ </BaseNumberField.Group>
+ </BaseNumberField.Root>
+ );
+}
diff --git a/packages/studio/src/components/ui/Popover.tsx b/packages/studio/src/components/ui/Popover.tsx
new file mode 100644
index 0000000000..43409e4e26
--- /dev/null
+++ b/packages/studio/src/components/ui/Popover.tsx
@@ -0,0 +1,74 @@
+/**
+ * Popover: `Menu`'s floating chrome (`popupSurface`) without item semantics, so arrow keys
+ * stay with whatever is focused inside (rename inputs, forms). Only the shadow differs.
+ */
+
+import { Popover as BasePopover } from "@base-ui/react/popover";
+import type { ComponentPropsWithoutRef, ReactElement, ReactNode } from "react";
+import { cn } from "./cn";
+import { popupSurface, type PopupPreviewState } from "./Menu";
+
+type PortalContainer = ComponentPropsWithoutRef<typeof BasePopover.Portal>["container"];
+
+/** Matches Menu's gap from its trigger, and its viewport margin. */
+const SIDE_OFFSET = 6;
+const VIEWPORT_MARGIN = 8;
+
+interface PopoverProps extends Omit<ComponentPropsWithoutRef<typeof BasePopover.Root>, "children"> {
+ /** A single element. It becomes the trigger; no wrapper is added around it. */
+ trigger: ReactElement;
+ /** Arbitrary content. The popover owns none of its keys. */
+ children: ReactNode;
+ side?: "top" | "bottom" | "left" | "right";
+ align?: "start" | "center" | "end";
+ sideOffset?: number;
+ /** Portal target. Pass the shadow root when the trigger lives in one. */
+ container?: PortalContainer;
+ /** Names the popup for assistive tech. */
+ "aria-label"?: string;
+ /**
+ * What to focus on open. Defaults to Base UI's behaviour (the first tabbable
+ * element), which is what a rename field wants.
+ */
+ initialFocus?: ComponentPropsWithoutRef<typeof BasePopover.Popup>["initialFocus"];
+ className?: string;
+ "data-preview-state"?: PopupPreviewState;
+}
+
+export function Popover({
+ trigger,
+ children,
+ side = "bottom",
+ align = "center",
+ sideOffset = SIDE_OFFSET,
+ container,
+ className,
+ initialFocus,
+ "aria-label": ariaLabel,
+ "data-preview-state": previewState,
+ ...root
+}: PopoverProps) {
+ return (
+ <BasePopover.Root {...root}>
+ <BasePopover.Trigger render={trigger} />
+ <BasePopover.Portal container={container}>
+ <BasePopover.Positioner
+ side={side}
+ align={align}
+ sideOffset={sideOffset}
+ collisionPadding={VIEWPORT_MARGIN}
+ className="z-200"
+ >
+ <BasePopover.Popup
+ aria-label={ariaLabel}
+ initialFocus={initialFocus}
+ data-preview-state={previewState}
+ className={cn(popupSurface, "p-3 text-step-11 text-text-1 shadow-popover", className)}
+ >
+ {children}
+ </BasePopover.Popup>
+ </BasePopover.Positioner>
+ </BasePopover.Portal>
+ </BasePopover.Root>
+ );
+}
diff --git a/packages/studio/src/components/ui/Select.tsx b/packages/studio/src/components/ui/Select.tsx
new file mode 100644
index 0000000000..d6510cd6c2
--- /dev/null
+++ b/packages/studio/src/components/ui/Select.tsx
@@ -0,0 +1,100 @@
+/**
+ * Select: Base UI select in Input's box. The trigger keeps `role="combobox"`, which both hotkey selector
+ * lists match. Options are data, not children, so typeahead and the value display can read labels.
+ */
+
+import { Select as BaseSelect } from "@base-ui/react/select";
+import { cn } from "./cn";
+import { fieldBase } from "./Input";
+import type { PreviewState } from "./Button";
+
+export interface SelectOption {
+ label: string;
+ value: string;
+}
+
+export interface SelectProps {
+ /** Accessible name for the trigger. */
+ label: string;
+ value: string;
+ options: SelectOption[];
+ /** Called when a different option is chosen. */
+ onCommit: (next: string) => void;
+ /** Called once per committed change, for design-input telemetry. */
+ onTrack?: () => void;
+ disabled?: boolean;
+ className?: string;
+ "data-preview-state"?: PreviewState;
+}
+
+export function Select({
+ label,
+ value,
+ options,
+ onCommit,
+ onTrack,
+ disabled,
+ className,
+ "data-preview-state": previewState,
+}: SelectProps) {
+ return (
+ <BaseSelect.Root
+ value={value}
+ disabled={disabled}
+ items={options}
+ onValueChange={(next) => {
+ const chosen = String(next);
+ if (chosen === value) return;
+ onCommit(chosen);
+ onTrack?.();
+ }}
+ >
+ <BaseSelect.Trigger
+ aria-label={label}
+ className={cn(
+ fieldBase,
+ "w-full cursor-pointer justify-between text-left",
+ "data-[popup-open]:border-border-strong",
+ className,
+ )}
+ data-preview-state={previewState}
+ >
+ <BaseSelect.Value className="truncate" />
+ <BaseSelect.Icon className="shrink-0 text-text-4" aria-hidden="true">
+ <svg width="8" height="5" viewBox="0 0 8 5" fill="none">
+ <path
+ d="M1 1L4 4L7 1"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ </BaseSelect.Icon>
+ </BaseSelect.Trigger>
+
+ <BaseSelect.Portal>
+ <BaseSelect.Positioner sideOffset={4} alignItemWithTrigger={false}>
+ <BaseSelect.Popup className="min-w-[var(--anchor-width)] rounded-md border border-border bg-surface py-1 shadow-menu outline-hidden">
+ <BaseSelect.List>
+ {options.map((option) => (
+ <BaseSelect.Item
+ key={option.value}
+ value={option.value}
+ className={cn(
+ "flex h-ctl-sm cursor-pointer select-none items-center gap-2 px-2.5",
+ "text-step-11 text-text-2 outline-hidden",
+ "data-[highlighted]:bg-hover data-[highlighted]:text-text-0",
+ "data-[selected]:text-text-0",
+ )}
+ >
+ <BaseSelect.ItemText className="truncate">{option.label}</BaseSelect.ItemText>
+ </BaseSelect.Item>
+ ))}
+ </BaseSelect.List>
+ </BaseSelect.Popup>
+ </BaseSelect.Positioner>
+ </BaseSelect.Portal>
+ </BaseSelect.Root>
+ );
+}
diff --git a/packages/studio/src/components/ui/Slider.tsx b/packages/studio/src/components/ui/Slider.tsx
new file mode 100644
index 0000000000..32a5814c49
--- /dev/null
+++ b/packages/studio/src/components/ui/Slider.tsx
@@ -0,0 +1,153 @@
+/**
+ * Slider: `onPreview` fires while the thumb moves and writes nothing durable; `onCommit` (with `onTrack`, once)
+ * fires at a boundary. Right-click or Escape aborts a drag via `eventDetails.cancel()` and restores the start value.
+ */
+
+import { Slider as BaseSlider } from "@base-ui/react/slider";
+import { useEffect, useRef, useState } from "react";
+import { cn } from "./cn";
+import type { PreviewState } from "./Button";
+
+export interface SliderProps {
+ /** Accessible name for the thumb. The inspector's row label is the usual one. */
+ label: string;
+ /** The committed value. */
+ value: number;
+ min: number;
+ max: number;
+ step?: number;
+ /** Every intermediate value while dragging or stepping. Not a commit. */
+ onPreview?: (next: number) => void;
+ /** Called at a commit boundary when the value really changed. */
+ onCommit: (next: number) => void;
+ /** Called once per commit boundary, for design-input telemetry. */
+ onTrack?: () => void;
+ disabled?: boolean;
+ className?: string;
+ "data-preview-state"?: PreviewState;
+}
+
+const first = (next: number | number[]): number => (Array.isArray(next) ? next[0] : next);
+
+export function Slider({
+ label,
+ value,
+ min,
+ max,
+ step,
+ onPreview,
+ onCommit,
+ onTrack,
+ disabled,
+ className,
+ "data-preview-state": previewState,
+}: SliderProps) {
+ const [draft, setDraft] = useState(value);
+ const draggingRef = useRef(false);
+ const abortedRef = useRef(false);
+ // The committed value the current gesture started from, so an abort has
+ // something to put back.
+ const dragStartRef = useRef(value);
+ // What was last handed to `onCommit`. A gesture's own commit lands before the
+ // parent re-renders, so deduping against the `value` prop would double-fire.
+ const committedRef = useRef(value);
+ const valueRef = useRef(value);
+ valueRef.current = value;
+
+ // An external write wins, except mid-drag: the echo is a frame behind, and
+ // applying it would snap the thumb backwards under the pointer.
+ useEffect(() => {
+ if (draggingRef.current) return;
+ committedRef.current = value;
+ setDraft(value);
+ }, [value]);
+
+ const commit = (next: number) => {
+ if (next === committedRef.current) return;
+ committedRef.current = next;
+ onCommit(next);
+ };
+
+ const abort = () => {
+ if (!draggingRef.current) return;
+ abortedRef.current = true;
+ const start = dragStartRef.current;
+ setDraft(start);
+ onPreview?.(start);
+ commit(start);
+ };
+
+ return (
+ <BaseSlider.Root
+ value={draft}
+ min={min}
+ max={max}
+ step={step}
+ disabled={disabled}
+ onValueChange={(next, details) => {
+ if (abortedRef.current) {
+ // The pointer is still down after a right-click abort. Base UI would
+ // otherwise keep applying moves to a gesture the user cancelled.
+ details.cancel();
+ return;
+ }
+ const n = first(next);
+ setDraft(n);
+ onPreview?.(n);
+ }}
+ onValueCommitted={(next) => {
+ draggingRef.current = false;
+ if (abortedRef.current) {
+ abortedRef.current = false;
+ return;
+ }
+ commit(first(next));
+ onTrack?.();
+ }}
+ className={cn("flex min-w-0 items-center", className)}
+ data-preview-state={previewState}
+ >
+ <BaseSlider.Control
+ // A stable hook for the drag tests and for the screenshot script. Base
+ // UI's own marker on this part only exists before hydration.
+ data-slider-control="true"
+ // h-6 is the 24x24 WCAG 2.2 (2.5.8) target: the visible track stays
+ // 2px, only the pointer box grows.
+ className="flex h-6 w-full min-w-0 touch-none select-none items-center"
+ onPointerDown={() => {
+ draggingRef.current = true;
+ abortedRef.current = false;
+ dragStartRef.current = valueRef.current;
+ }}
+ onContextMenu={(event) => {
+ if (!draggingRef.current) return;
+ event.preventDefault();
+ abort();
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || !draggingRef.current) return;
+ event.preventDefault();
+ abort();
+ }}
+ >
+ <BaseSlider.Track className="h-0.5 w-full rounded-full bg-hover">
+ <BaseSlider.Indicator className="rounded-full bg-text-5" />
+ <BaseSlider.Thumb
+ aria-label={label}
+ className={cn(
+ // The ring separates the thumb from the track behind it. A drop
+ // shadow would need a raw colour literal, which R5 does not allow
+ // outside the token file, and no shadow token fits a 10px dot.
+ "size-2.5 rounded-full bg-text-0 ring-2 ring-bg-1",
+ "cursor-grab active:cursor-grabbing data-[preview-state=active]:cursor-grabbing",
+ "hover:scale-110 data-[preview-state=hover]:scale-110",
+ "transition-transform ease-standard duration-hover",
+ "has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-accent",
+ "data-[preview-state=focus]:outline-solid data-[preview-state=focus]:outline-2 data-[preview-state=focus]:outline-offset-2 data-[preview-state=focus]:outline-accent",
+ )}
+ />
+ </BaseSlider.Track>
+ </BaseSlider.Control>
+ </BaseSlider.Root>
+ );
+}
diff --git a/packages/studio/src/components/ui/Toggle.tsx b/packages/studio/src/components/ui/Toggle.tsx
new file mode 100644
index 0000000000..187d1149ab
--- /dev/null
+++ b/packages/studio/src/components/ui/Toggle.tsx
@@ -0,0 +1,63 @@
+/**
+ * Toggle: a switch, not a checkbox (immediate effect). `role="switch"` needed an entry in
+ * `typingTarget.ts` so Space is not leaked to the global playback shortcut.
+ */
+
+import { Switch } from "@base-ui/react/switch";
+import { cn } from "./cn";
+import type { PreviewState } from "./Button";
+
+export interface ToggleProps {
+ /** Accessible name. */
+ label: string;
+ checked: boolean;
+ /** Called on every flip. */
+ onCommit: (next: boolean) => void;
+ /** Called once per flip, for design-input telemetry. */
+ onTrack?: () => void;
+ disabled?: boolean;
+ className?: string;
+ "data-preview-state"?: PreviewState;
+}
+
+export function Toggle({
+ label,
+ checked,
+ onCommit,
+ onTrack,
+ disabled,
+ className,
+ "data-preview-state": previewState,
+}: ToggleProps) {
+ return (
+ <Switch.Root
+ aria-label={label}
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={(next) => {
+ onCommit(next);
+ onTrack?.();
+ }}
+ data-preview-state={previewState}
+ className={cn(
+ "relative inline-flex h-4 w-7 shrink-0 cursor-pointer items-center rounded-full p-0.5",
+ "border border-border-input bg-input",
+ "transition-[background-color,border-color] ease-standard duration-press",
+ "hover:border-border-strong data-[preview-state=hover]:border-border-strong",
+ "data-[checked]:border-accent data-[checked]:bg-accent",
+ "outline-hidden focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
+ "data-[preview-state=focus]:outline-solid data-[preview-state=focus]:outline-2 data-[preview-state=focus]:outline-offset-1 data-[preview-state=focus]:outline-accent",
+ "disabled:cursor-not-allowed disabled:opacity-40",
+ className,
+ )}
+ >
+ <Switch.Thumb
+ className={cn(
+ "size-3 rounded-full bg-text-3",
+ "transition-[transform,background-color] ease-standard duration-press",
+ "data-[checked]:translate-x-3 data-[checked]:bg-bg-0",
+ )}
+ />
+ </Switch.Root>
+ );
+}
diff --git a/packages/studio/src/components/ui/index.ts b/packages/studio/src/components/ui/index.ts
index 1055707d7e..ccf50ff43a 100644
--- a/packages/studio/src/components/ui/index.ts
+++ b/packages/studio/src/components/ui/index.ts
@@ -8,3 +8,25 @@ export { Tab, TabPanel, Tabs, TabsList } from "./Tabs";
export { HyperframesLoader, StatusFrame } from "./HyperframesLoader";
export type { HyperframesLoaderProps } from "./HyperframesLoader";
export { Tooltip } from "./Tooltip";
+export {
+ ContextMenu,
+ Menu,
+ MenuItem,
+ MenuRadioGroup,
+ MenuRadioItem,
+ MenuSeparator,
+ MenuShortcut,
+ popupSurface,
+} from "./Menu";
+export type { MenuItemTone, PopupPreviewState } from "./Menu";
+export { Popover } from "./Popover";
+export { Input, fieldBase, fieldText } from "./Input";
+export type { InputProps } from "./Input";
+export { NumberField } from "./NumberField";
+export type { NumberFieldProps } from "./NumberField";
+export { Select } from "./Select";
+export type { SelectOption, SelectProps } from "./Select";
+export { Slider } from "./Slider";
+export type { SliderProps } from "./Slider";
+export { Toggle } from "./Toggle";
+export type { ToggleProps } from "./Toggle";
diff --git a/packages/studio/src/components/ui/valueControls.test.tsx b/packages/studio/src/components/ui/valueControls.test.tsx
new file mode 100644
index 0000000000..a15b040a78
--- /dev/null
+++ b/packages/studio/src/components/ui/valueControls.test.tsx
@@ -0,0 +1,524 @@
+// @vitest-environment happy-dom
+/** Value controls: one drag is one commit and one telemetry event; classes resolve; hotkey roles match. */
+import { createRequire } from "node:module";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { compile } from "tailwindcss";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const trackStudioEvent = vi.fn();
+vi.mock("../../utils/studioTelemetry", () => ({
+ trackStudioEvent: (...args: unknown[]) => trackStudioEvent(...args),
+}));
+
+import { Input } from "./Input";
+import { NumberField } from "./NumberField";
+import { Select } from "./Select";
+import { Slider } from "./Slider";
+import { Toggle } from "./Toggle";
+import { isTypingTarget } from "../../utils/typingTarget";
+import { shouldIgnorePlaybackShortcutTarget } from "../../player/lib/playbackShortcuts";
+import { __resetDesignInputThrottle, trackDesignInput } from "../../utils/designInputTracking";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let mounted: { root: Root; host: HTMLElement } | null = null;
+
+function render(element: React.ReactElement): HTMLElement {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ mounted = { root, host };
+ act(() => root.render(element));
+ return host;
+}
+
+function unmount() {
+ if (!mounted) return;
+ const { root, host } = mounted;
+ mounted = null;
+ act(() => root.unmount());
+ host.remove();
+}
+
+beforeEach(() => {
+ trackStudioEvent.mockReset();
+ __resetDesignInputThrottle();
+});
+afterEach(unmount);
+
+/** Base UI moves focus a task later than React renders; happy-dom is no faster. */
+const settle = () => act(async () => void (await new Promise((r) => setTimeout(r, 0))));
+
+function fire(el: Element, type: string, init: MouseEventInit & { key?: string } = {}) {
+ const event =
+ init.key === undefined
+ ? new MouseEvent(type, { bubbles: true, ...init })
+ : new KeyboardEvent(type, { bubbles: true, key: init.key });
+ act(() => void el.dispatchEvent(event));
+}
+
+/** Types into a React-controlled input the way the browser does. */
+function type(input: HTMLInputElement, text: string) {
+ act(() => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.bind(
+ input,
+ );
+ setter(text);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+/** One design-input telemetry call, through the real coalescing sink. */
+const track = (control: string) => () =>
+ trackDesignInput({ ui: "flat", section: "style", control, name: "Opacity" });
+
+const designInputCalls = () =>
+ trackStudioEvent.mock.calls.filter(([event]) => event === "design_input");
+
+// -- the compiled stylesheet, built once for the whole file --
+
+const STYLES_DIR = path.resolve(__dirname, "../../styles");
+const require = createRequire(import.meta.url);
+const TAILWIND_DIR = path.dirname(require.resolve("tailwindcss/package.json"));
+
+async function loadStylesheet(id: string, base: string) {
+ const file = id === "tailwindcss" ? path.join(TAILWIND_DIR, "index.css") : path.resolve(base, id);
+ return { path: file, base: path.dirname(file), content: readFileSync(file, "utf8") };
+}
+
+/** How Tailwind escapes a candidate into a selector: `\` before each symbol. */
+function asSelector(candidate: string): string {
+ return candidate.replace(/[^a-zA-Z0-9-]/g, (char) => `\\${char}`);
+}
+
+let compileStudioCss: (candidates: string[]) => string;
+
+beforeAll(async () => {
+ const compiled = await compile(readFileSync(path.join(STYLES_DIR, "studio.css"), "utf8"), {
+ base: STYLES_DIR,
+ loadStylesheet,
+ });
+ compileStudioCss = (candidates) => compiled.build(candidates);
+});
+
+function unresolved(candidates: string[]): string[] {
+ const css = compileStudioCss(candidates);
+ return candidates.filter((candidate) => !css.includes(asSelector(candidate)));
+}
+
+/** All five, rendered together, so one sweep covers the set. */
+function allFive(previewState?: "hover" | "active" | "focus") {
+ const noop = () => {};
+ return (
+ <>
+ <Input value="hello" onCommit={noop} aria-label="Name" data-preview-state={previewState} />
+ <NumberField
+ label="Size"
+ value={24}
+ unit="px"
+ onCommit={noop}
+ data-preview-state={previewState}
+ />
+ <Select
+ label="Weight"
+ value="400"
+ options={[
+ { label: "Regular", value: "400" },
+ { label: "Semibold", value: "600" },
+ ]}
+ onCommit={noop}
+ data-preview-state={previewState}
+ />
+ <Slider
+ label="Opacity"
+ value={10}
+ min={0}
+ max={100}
+ onCommit={noop}
+ data-preview-state={previewState}
+ />
+ <Toggle label="Visible" checked onCommit={noop} data-preview-state={previewState} />
+ </>
+ );
+}
+
+describe("value control classes", () => {
+ it("emits only classes Studio's stylesheet defines", () => {
+ const host = render(allFive());
+ const emitted = new Set<string>();
+ for (const el of host.querySelectorAll("*")) {
+ for (const cls of el.classList) emitted.add(cls);
+ }
+
+ expect(emitted.size).toBeGreaterThan(20);
+ expect(unresolved([...emitted])).toEqual([]);
+ });
+
+ it("fails an undefined class, so the check above is not vacuous", () => {
+ expect(unresolved(["bg-not-a-token", "text-step-999"])).toEqual([
+ "bg-not-a-token",
+ "text-step-999",
+ ]);
+ });
+
+ it("keeps every interactive look reachable without a pointer", () => {
+ // Same contract as Button: the `data-preview-state` half of each recipe
+ // repeats the real state's half exactly, so a gallery shot cannot drift
+ // away from what a pointer actually produces.
+ const realPrefix: Record<string, string[]> = {
+ hover: ["hover:"],
+ active: ["active:"],
+ focus: ["focus-visible:", "focus-within:", "has-[:focus-visible]:"],
+ };
+ const host = render(allFive());
+ const classes = [...host.querySelectorAll("*")].flatMap((el) => [...el.classList]);
+
+ for (const [state, prefixes] of Object.entries(realPrefix)) {
+ const previewPrefix = `data-[preview-state=${state}]:`;
+ const preview = classes
+ .filter((cls) => cls.startsWith(previewPrefix))
+ .map((cls) => cls.slice(previewPrefix.length));
+ const real = classes
+ .filter((cls) => prefixes.some((prefix) => cls.startsWith(prefix)))
+ .map((cls) => cls.slice(cls.lastIndexOf(":") + 1));
+
+ expect([...new Set(preview)].sort(), state).toEqual([...new Set(real)].sort());
+ expect(preview.length, state).toBeGreaterThan(0);
+ }
+ });
+
+ it("boxes every value control, so an input reads as an input", () => {
+ // R10. The three text-shaped controls carry a real border and a background
+ // that differs from the panel behind them.
+ const host = render(allFive());
+ const boxes = [...host.querySelectorAll(".border-border-input")];
+
+ expect(boxes.length).toBe(4); // Input, NumberField, Select trigger, Toggle
+ for (const box of boxes) {
+ expect([...box.classList]).toContain("bg-input");
+ }
+ });
+});
+
+describe("Slider", () => {
+ /** Gives the control a width so Base UI's pointer maths has a rect to use. */
+ function stubRect(el: Element, width = 100) {
+ el.getBoundingClientRect = () =>
+ ({ x: 0, y: 0, top: 0, left: 0, right: width, bottom: 10, width, height: 10 }) as DOMRect;
+ }
+
+ it("commits once and tracks once for a drag across five moves", () => {
+ const commits: number[] = [];
+ const previews: number[] = [];
+ // Counted at the wrapper as well as at the sink. The sink's 600 ms window
+ // would collapse a per-move `track()` into one event on its own, so
+ // asserting only the event count would pass even if the call moved to
+ // `onValueChange`. The raw count is what pins KTD11.
+ let trackCalls = 0;
+ const trackOnce = track("slider");
+ const host = render(
+ <Slider
+ label="Opacity"
+ value={10}
+ min={0}
+ max={100}
+ onPreview={(n) => previews.push(n)}
+ onCommit={(n) => commits.push(n)}
+ onTrack={() => {
+ trackCalls += 1;
+ trackOnce();
+ }}
+ />,
+ );
+ const control = host.querySelector("[data-slider-control]")!;
+ stubRect(control);
+
+ fire(control, "pointerdown", { clientX: 10, button: 0 });
+ // 10 to 40 over five moves. The release commits the last value a move
+ // delivered, not the pointerup coordinate, which is why the last move and
+ // the release sit at the same x.
+ for (const x of [15, 20, 25, 30, 40]) {
+ // `buttons: 1` is not decoration: Base UI reads it to tell a real drag
+ // from a move whose pointerup another element swallowed, and treats
+ // `buttons: 0` as the end of the gesture.
+ act(
+ () =>
+ void document.dispatchEvent(new MouseEvent("pointermove", { clientX: x, buttons: 1 })),
+ );
+ }
+ act(
+ () => void document.dispatchEvent(new MouseEvent("pointerup", { clientX: 40, buttons: 0 })),
+ );
+
+ expect(previews.length).toBeGreaterThan(1);
+ expect(commits).toEqual([40]);
+ expect(trackCalls).toBe(1);
+ expect(designInputCalls()).toHaveLength(1);
+ });
+
+ it("puts the value back when a drag is aborted with the right button", () => {
+ // KTD8. The pointer is still down: the abort has to stop Base UI applying
+ // any further move, not merely reset the number once.
+ const commits: number[] = [];
+ const host = render(
+ <Slider
+ label="Opacity"
+ value={10}
+ min={0}
+ max={100}
+ onCommit={(n) => commits.push(n)}
+ onTrack={track("slider")}
+ />,
+ );
+ const control = host.querySelector("[data-slider-control]")!;
+ stubRect(control);
+
+ fire(control, "pointerdown", { clientX: 10, button: 0 });
+ act(
+ () => void document.dispatchEvent(new MouseEvent("pointermove", { clientX: 60, buttons: 1 })),
+ );
+ fire(control, "contextmenu", { clientX: 60, button: 2 });
+ act(
+ () => void document.dispatchEvent(new MouseEvent("pointermove", { clientX: 90, buttons: 1 })),
+ );
+ act(
+ () => void document.dispatchEvent(new MouseEvent("pointerup", { clientX: 90, buttons: 0 })),
+ );
+
+ const input = host.querySelector<HTMLInputElement>('input[type="range"]')!;
+ expect(input.value).toBe("10");
+ expect(commits.at(-1) ?? 10).toBe(10);
+ expect(designInputCalls()).toHaveLength(0);
+ });
+
+ it("steps by one on ArrowRight and coalesces three fast presses into one event", () => {
+ const commits: number[] = [];
+ const host = render(
+ <Slider
+ label="Opacity"
+ value={10}
+ min={0}
+ max={100}
+ onCommit={(n) => commits.push(n)}
+ onTrack={track("slider")}
+ />,
+ );
+ const input = host.querySelector<HTMLInputElement>('input[type="range"]')!;
+
+ fire(input, "keydown", { key: "ArrowRight" });
+ fire(input, "keydown", { key: "ArrowRight" });
+ fire(input, "keydown", { key: "ArrowRight" });
+
+ expect(commits).toEqual([11, 12, 13]);
+ // Three commits, one event: the sink's 600 ms window is what turns a burst
+ // of keyboard steps into one "the user worked this control".
+ expect(designInputCalls()).toHaveLength(1);
+ });
+});
+
+describe("NumberField", () => {
+ it("commits a typed number on Enter and keeps the unit", () => {
+ const commits: number[] = [];
+ const host = render(
+ <NumberField
+ label="Size"
+ value={24}
+ unit="px"
+ onCommit={(n) => commits.push(n)}
+ onTrack={track("metric")}
+ />,
+ );
+ const input = host.querySelector("input")!;
+
+ type(input, "48");
+ expect(commits).toEqual([]); // a keystroke is not a commit
+
+ fire(input, "keydown", { key: "Enter" });
+
+ expect(commits).toEqual([48]);
+ expect(designInputCalls()).toHaveLength(1);
+ expect(host.textContent).toContain("px");
+ });
+
+ it("shows the error state for text it cannot parse, and commits nothing", () => {
+ // Not "abc": Base UI filters a non-numeral character out of the input
+ // before the text ever reaches this component, so that case is unreachable
+ // rather than untested. A lone minus sign is the reachable one. It is a
+ // legal character, it survives into the field, and it is not a number.
+ const commits: number[] = [];
+ const host = render(
+ <NumberField label="Size" value={24} unit="px" onCommit={(n) => commits.push(n)} />,
+ );
+ const input = host.querySelector("input")!;
+
+ type(input, "abc");
+ expect(input.value).toBe("24"); // rejected at the keystroke, nothing to commit
+
+ type(input, "-");
+ fire(input, "keydown", { key: "Enter" });
+
+ expect(commits).toEqual([]);
+ expect(input.getAttribute("aria-invalid")).toBe("true");
+ expect(host.textContent).toContain("px");
+ });
+
+ it("treats an emptied field as an error rather than as zero", () => {
+ const commits: number[] = [];
+ const host = render(
+ <NumberField label="Size" value={24} unit="px" onCommit={(n) => commits.push(n)} />,
+ );
+ const input = host.querySelector("input")!;
+
+ type(input, "");
+ fire(input, "keydown", { key: "Enter" });
+
+ expect(commits).toEqual([]);
+ expect(input.getAttribute("aria-invalid")).toBe("true");
+ });
+});
+
+describe("Input", () => {
+ it("commits a typed value on Enter, once, and not per keystroke", () => {
+ const commits: string[] = [];
+ const host = render(
+ <Input
+ value="hello"
+ aria-label="Name"
+ onCommit={(v) => commits.push(v)}
+ onTrack={track("text")}
+ />,
+ );
+ const input = host.querySelector("input")!;
+
+ type(input, "world");
+ expect(commits).toEqual([]);
+
+ fire(input, "keydown", { key: "Enter" });
+
+ expect(commits).toEqual(["world"]);
+ expect(designInputCalls()).toHaveLength(1);
+ });
+
+ it("abandons the draft on Escape", () => {
+ const commits: string[] = [];
+ const host = render(
+ <Input value="hello" aria-label="Name" onCommit={(v) => commits.push(v)} />,
+ );
+ const input = host.querySelector("input")!;
+
+ type(input, "world");
+ fire(input, "keydown", { key: "Escape" });
+
+ expect(input.value).toBe("hello");
+ expect(commits).toEqual([]);
+ });
+});
+
+describe("Select", () => {
+ it("opens with Space, moves the highlight, and commits on Enter", async () => {
+ const commits: string[] = [];
+ const host = render(
+ <Select
+ label="Weight"
+ value="400"
+ options={[
+ { label: "Regular", value: "400" },
+ { label: "Semibold", value: "600" },
+ ]}
+ onCommit={(v) => commits.push(v)}
+ onTrack={track("select")}
+ />,
+ );
+ const trigger = host.querySelector('[role="combobox"]')!;
+
+ // The trigger is a real `<button>`, so Space reaches it as keydown, keyup
+ // and then a click the browser synthesises. happy-dom does not synthesise
+ // that click, so the test dispatches the sequence a browser produces.
+ fire(trigger, "keydown", { key: " " });
+ fire(trigger, "keyup", { key: " " });
+ act(() => (trigger as HTMLElement).click());
+ await settle();
+ const options = [...document.querySelectorAll('[role="option"]')];
+ expect(options).toHaveLength(2);
+
+ fire(document.activeElement ?? document.body, "keydown", { key: "ArrowDown" });
+ await settle();
+ expect(document.querySelector("[data-highlighted]")?.textContent).toBe("Semibold");
+
+ fire(document.activeElement ?? document.body, "keydown", { key: "Enter" });
+ await settle();
+
+ expect(commits).toEqual(["600"]);
+ expect(designInputCalls()).toHaveLength(1);
+ expect(trigger.getAttribute("aria-expanded")).toBe("false");
+ });
+});
+
+describe("Toggle", () => {
+ it("flips on click and on Space, and reports aria-checked", () => {
+ const flips: boolean[] = [];
+ const host = render(
+ <Toggle
+ label="Visible"
+ checked={false}
+ onCommit={(v) => flips.push(v)}
+ onTrack={track("toggle")}
+ />,
+ );
+ const control = host.querySelector('[role="switch"]') as HTMLElement;
+
+ expect(control.getAttribute("aria-checked")).toBe("false");
+
+ act(() => control.click());
+ fire(control, "keydown", { key: " " });
+ fire(control, "keyup", { key: " " });
+
+ expect(flips).toEqual([true, true]);
+ expect(designInputCalls()).toHaveLength(1); // coalesced, same control
+ });
+});
+
+describe("hotkey classification (KTD13)", () => {
+ it("classifies each control the way the native input it replaces was", async () => {
+ // Native reference on the left, primitive on the right. Both selector lists
+ // have to agree on each pair, or a global shortcut starts behaving
+ // differently after a consumer migrates.
+ const host = render(
+ <>
+ <input type="text" data-testid="native-text" />
+ <input type="range" data-testid="native-range" />
+ <select data-testid="native-select">
+ <option>a</option>
+ </select>
+ <input type="checkbox" data-testid="native-checkbox" />
+ {allFive()}
+ </>,
+ );
+ await settle();
+
+ const native = (id: string) => host.querySelector(`[data-testid="${id}"]`)!;
+ const pairs: Array<[string, Element]> = [
+ ["native-text", host.querySelectorAll("input[type='text']")[1]!],
+ ["native-range", host.querySelector("input[type='range']")!],
+ ["native-select", host.querySelector('[role="combobox"]')!],
+ ["native-checkbox", host.querySelector('[role="switch"]')!],
+ ];
+
+ for (const [nativeId, primitive] of pairs) {
+ expect(isTypingTarget(primitive), `${nativeId}: typing target`).toBe(
+ isTypingTarget(native(nativeId)),
+ );
+ expect(shouldIgnorePlaybackShortcutTarget(primitive), `${nativeId}: playback`).toBe(
+ shouldIgnorePlaybackShortcutTarget(native(nativeId)),
+ );
+ }
+
+ // The slider thumb in particular: arrow keys must step the slider rather
+ // than nudge the canvas selection, which only holds while its input counts
+ // as a typing target.
+ expect(isTypingTarget(host.querySelector("input[type='range']"))).toBe(true);
+ });
+});
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index ac46b86920..ac661bb322 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -4,6 +4,29 @@ export type { ButtonSize, ButtonVariant, PreviewState } from "./components/ui/Bu
export { IconButton } from "./components/ui/IconButton";
export { Tab, TabPanel, Tabs, TabsList } from "./components/ui/Tabs";
export { Tooltip } from "./components/ui/Tooltip";
+export { cn } from "./components/ui/cn";
+export {
+ ContextMenu,
+ Menu,
+ MenuItem,
+ MenuRadioGroup,
+ MenuRadioItem,
+ MenuSeparator,
+ MenuShortcut,
+ popupSurface,
+} from "./components/ui/Menu";
+export type { MenuItemTone, PopupPreviewState } from "./components/ui/Menu";
+export { Popover } from "./components/ui/Popover";
+export { Input, fieldBase, fieldText } from "./components/ui/Input";
+export type { InputProps } from "./components/ui/Input";
+export { NumberField } from "./components/ui/NumberField";
+export type { NumberFieldProps } from "./components/ui/NumberField";
+export { Select } from "./components/ui/Select";
+export type { SelectOption, SelectProps } from "./components/ui/Select";
+export { Slider } from "./components/ui/Slider";
+export type { SliderProps } from "./components/ui/Slider";
+export { Toggle } from "./components/ui/Toggle";
+export type { ToggleProps } from "./components/ui/Toggle";
// NLE Layout
export { EditorShell } from "./components/EditorShell";
diff --git a/packages/studio/src/player/lib/playbackShortcuts.ts b/packages/studio/src/player/lib/playbackShortcuts.ts
index da312899d6..4fb5b1853a 100644
--- a/packages/studio/src/player/lib/playbackShortcuts.ts
+++ b/packages/studio/src/player/lib/playbackShortcuts.ts
@@ -17,6 +17,8 @@ const PLAYBACK_SHORTCUT_IGNORED_SELECTOR = [
"[role='checkbox']",
"[role='combobox']",
"[role='menuitem']",
+ // Base UI's menu radio item is a `<div>`, so `button` above no longer catches it.
+ "[role='menuitemradio']",
"[role='radio']",
"[role='slider']",
"[role='spinbutton']",
diff --git a/packages/studio/src/utils/typingTarget.ts b/packages/studio/src/utils/typingTarget.ts
index 9d86e032d9..c22b314c47 100644
--- a/packages/studio/src/utils/typingTarget.ts
+++ b/packages/studio/src/utils/typingTarget.ts
@@ -33,6 +33,10 @@ const TYPING_SELECTOR = [
"[role='textbox']",
"[role='searchbox']",
"[role='combobox']",
+ // A switch is a button in the DOM, but the native checkbox it replaces was an
+ // `input` and matched above. Without this row the shared Toggle would let a
+ // global shortcut claim Space instead of flipping the control (KTD13).
+ "[role='switch']",
".cm-editor",
].join(",");