mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-24 16:06:34 +00:00
feat(studio): shared Menu, ContextMenu and Popover primitives
One menu chrome and one popover chrome, on Base UI, wearing the theme tokens. Dismissal is plain Base UI with no capture-phase wrapper: its outside-press listeners are registered on document with capture set, so the canvas overlay's bubble-phase stopPropagation cannot starve them. Menu items carry an optional mono shortcut hint, a disabled state and a danger tone. ContextMenu opens at the pointer. Popover shares the surface, radius and open motion but owns no item semantics, so a text field inside it keeps its own keys. Also adds [role='menuitemradio'] to the playback-shortcut ignore list. The hand-rolled speed menu spelled its rows as buttons, which that list already matched; the shared radio item is a div with the same role, and nothing else in the list matched it, so an open speed menu would have leaked arrow keys and Space to the player.
This commit is contained in:
@@ -0,0 +1,410 @@
|
||||
// @vitest-environment happy-dom
|
||||
/**
|
||||
* Menu, ContextMenu and Popover.
|
||||
*
|
||||
* Two kinds of check live here, and they fail for different reasons.
|
||||
*
|
||||
* The behaviour tests pin what the primitives owe their callers: arrow keys
|
||||
* skip a disabled item, a radio group reports exactly one `aria-checked`, a
|
||||
* text field inside a Popover keeps its own keys, and an outside press that a
|
||||
* parent swallows in the bubble phase still dismisses. That last one is U3's
|
||||
* finding re-asserted on the shipped component rather than on a spike fixture.
|
||||
*
|
||||
* The class test is the same shape as `Button.test.tsx`: Tailwind has no strict
|
||||
* mode for markup, so a class nobody defines styles nothing in silence. Every
|
||||
* class these components emit is compiled against Studio's real stylesheet and
|
||||
* a class that produces no selector fails, naming itself.
|
||||
*
|
||||
* happy-dom has no layout, so nothing here asserts a pixel or a position.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* `HTMLElement.click()` looks like the obvious way to open a menu and is the
|
||||
* wrong one here: it dispatches a bare `click` with no pointer event before it,
|
||||
* which Base UI reads as a KEYBOARD activation. A keyboard-opened menu
|
||||
* pre-highlights its first item, per the ARIA menu pattern, so every arrow-key
|
||||
* assertion written on top of `.click()` would be off by one against what a
|
||||
* user with a mouse actually sees. Spelling the sequence out keeps these tests
|
||||
* describing the pointer case, which is how every menu in Studio is opened.
|
||||
*/
|
||||
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"]')];
|
||||
|
||||
/**
|
||||
* The shape a Studio element menu has: actions, a hairline, a destructive one.
|
||||
* `disabled` marks whichever label is passed, so one component serves both the
|
||||
* plain arrow-key test and the disabled-item test.
|
||||
*/
|
||||
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 () => {
|
||||
// KTD13. `typingTarget` and `playbackShortcuts` gate every global hotkey on
|
||||
// exact role strings. Today's menus render `<button role="menuitem">` and
|
||||
// `<button role="menuitemradio">`, which both selector lists already match
|
||||
// through `button`. Base UI renders a `<div>` with the same roles, so the
|
||||
// roles have to carry the classification on their own.
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Nothing here re-checks that these components' classes resolve: the token gate
|
||||
* (`styles/tokenGate.test.ts`) already compiles Studio's stylesheet against
|
||||
* every class its non-test sources claim, `Menu.tsx` and `Popover.tsx`
|
||||
* included. A second copy of that check would be one more thing to keep in step
|
||||
* for no extra coverage.
|
||||
*
|
||||
* What the gate cannot see is what the compiled rule DOES, which is 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/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* Menu and ContextMenu — Base UI's menus wearing Studio's tokens.
|
||||
*
|
||||
* Studio has six hand-rolled menus today. Each one re-decides the same things:
|
||||
* a surface colour, a radius, a shadow, which key moves the highlight, whether
|
||||
* a right-click opens at the pointer, and how an outside press dismisses it.
|
||||
* This file decides them once.
|
||||
*
|
||||
* Three things are worth knowing before reading the code:
|
||||
*
|
||||
* - **Dismissal is plain Base UI, with no wrapper.** Studio's canvas overlay
|
||||
* calls `stopPropagation()` on its own bubble-phase pointer handlers, which
|
||||
* is why `useContextMenuDismiss` had to listen in the capture phase. Base UI
|
||||
* registers its outside-press listeners on `document` with capture set, so
|
||||
* an upstream bubble-phase stop cannot starve them. U3 proved that over the
|
||||
* real overlay; `Menu.test.tsx` re-asserts it on this component.
|
||||
*
|
||||
* - **`trigger` is rendered, not wrapped.** Both menus take the caller's own
|
||||
* element through Base UI's `render` prop, the way `Tooltip` does. A wrapper
|
||||
* would need a box of its own to position against, and a `display: contents`
|
||||
* wrapper has none.
|
||||
*
|
||||
* - **`container` exists for shadow roots.** Studio mounts surfaces inside
|
||||
* shadow roots; a portal that always lands on `<body>` would drop the popup
|
||||
* out of the host's stylesheet.
|
||||
*
|
||||
* The open motion names `duration-open`, the token that zeroes itself under
|
||||
* `prefers-reduced-motion` (see `theme.css`), so a menu cannot use the token
|
||||
* and forget the reduced-motion case.
|
||||
*/
|
||||
|
||||
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, so a screenshot cannot catch
|
||||
* the popup mid-transition. CSS-only: the open state itself stays controlled by
|
||||
* the caller or by Base UI.
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* The chrome every floating panel in Studio shares: surface, radius, hairline
|
||||
* ring, and the open motion. `Popover` wears this too, which is what makes a
|
||||
* context menu and a settings panel read as the same system. Each caller adds
|
||||
* its own shadow token (`shadow-menu` or `shadow-popover`).
|
||||
*
|
||||
* `data-starting-style` and `data-ending-style` are Base UI's transition
|
||||
* attributes; the popup is mounted with them set, so a plain CSS transition is
|
||||
* enough and no animation library is involved.
|
||||
*/
|
||||
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. The highlight hangs off `data-highlighted`, which Base UI sets from
|
||||
* keyboard and pointer alike, so the row the eye sees and the row Enter
|
||||
* activates cannot disagree.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A menu opened by right click or long press, at the pointer. `side` and
|
||||
* `align` are not offered: the anchor is the pointer, so there is nothing to
|
||||
* sit beside.
|
||||
*/
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A keyboard shortcut hint. Mono and tabular so a column of them lines up, and
|
||||
* dimmer than the label because it is a reminder, not an action.
|
||||
*
|
||||
* `MenuItem`'s `shortcut` prop renders this, and it is exported for the one
|
||||
* case the prop cannot cover: an item whose hint is 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 = "default",
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A single-choice group (SpeedMenu's playback rates). Selection is reported as
|
||||
* `aria-checked` on each item, which is the state assistive tech reads and the
|
||||
* one the dot indicator is drawn 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} />;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Popover — the same floating chrome as `Menu`, with no item semantics.
|
||||
*
|
||||
* The split is deliberate (KTD5). A flat list of actions is a menu: it owns the
|
||||
* arrow keys, typeahead and Enter, and every child has to be an item. A surface
|
||||
* with modes, a text field or a form is not: the arrow keys belong to whatever
|
||||
* is focused inside it. AssetContextMenu has rename and delete-confirm modes
|
||||
* with an embedded input, and the SnapToolbar's grid-spacing panel is a small
|
||||
* form; both are popovers, and putting them in a menu would take their keys
|
||||
* away.
|
||||
*
|
||||
* What they share is the look: `popupSurface` from `Menu.tsx` carries the
|
||||
* radius, the surface colour, the hairline ring and the open motion, so a
|
||||
* settings panel and a context menu cannot drift apart. Only the shadow differs
|
||||
* (`--shadow-popover` sits a step further off the page than `--shadow-menu`).
|
||||
*/
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -8,3 +8,15 @@ 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";
|
||||
|
||||
@@ -17,6 +17,12 @@ const PLAYBACK_SHORTCUT_IGNORED_SELECTOR = [
|
||||
"[role='checkbox']",
|
||||
"[role='combobox']",
|
||||
"[role='menuitem']",
|
||||
// A radio row inside a menu. The hand-rolled SpeedMenu spelled it as a
|
||||
// `<button role="menuitemradio">`, so `button` above happened to catch it;
|
||||
// the shared Menu's radio item is a `<div>` with the same role, and nothing
|
||||
// else here matches it. Without this line the playback shortcuts would claim
|
||||
// arrow keys and Space out of an open speed menu.
|
||||
"[role='menuitemradio']",
|
||||
"[role='radio']",
|
||||
"[role='slider']",
|
||||
"[role='spinbutton']",
|
||||
|
||||
Reference in New Issue
Block a user