Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 0 additions & 31 deletions packages/studio/src/components/PanelTabButton.tsx

This file was deleted.

151 changes: 151 additions & 0 deletions packages/studio/src/components/RightPanelTabs.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// @vitest-environment happy-dom

/**
* The strip's keyboard behaviour, which tab reads as selected, and how the hotkey
* filters classify the elements (KTD13). The arrow-key tests are new behaviour, not a port.
*/
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
import { RightPanelTabs, type RightPanelTabDescriptor } from "./RightPanelTabs";
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;

const IDS = ["design", "layers", "renders", "variables"];

let mounted: { root: Root; host: HTMLElement } | null = null;

afterEach(() => {
if (!mounted) return;
const { root, host } = mounted;
mounted = null;
act(() => root.unmount());
host.remove();
});

/** The harness owns the active state too, so a selection moves as it does in the real panel. */
function mount(
initialActive: string[],
activateOnFocus = true,
): {
host: HTMLElement;
selections: ReturnType<typeof vi.fn>;
} {
const selections = vi.fn();

function Harness() {
const [active, setActive] = React.useState(initialActive);
const tabs: RightPanelTabDescriptor[] = IDS.map((id) => ({
id,
label: id,
tooltip: `${id} tooltip`,
active: active.includes(id),
onSelect: () => {
selections(id);
setActive([id]);
},
}));
return <RightPanelTabs tabs={tabs} activateOnFocus={activateOnFocus} />;
}

const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
mounted = { root, host };
act(() => root.render(<Harness />));
return { host, selections };
}

function tab(host: HTMLElement, id: string): HTMLElement {
const el = host.querySelector<HTMLElement>(`[data-tab-id="${id}"]`);
if (!el) throw new Error(`no tab for ${id}`);
return el;
}

function selected(host: HTMLElement): string | null {
return (
host.querySelector('[role="tab"][aria-selected="true"]')?.getAttribute("data-tab-id") ?? null
);
}

/** Base UI moves the roving tabindex synchronously and the focus one task later. */
async function arrow(key: string): Promise<void> {
const target = document.activeElement ?? document.body;
act(() => {
target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, composed: true }));
});
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}

it("moves from Design to Layers with ArrowRight and asks the panel to switch", async () => {
const { host, selections } = mount(["design"]);
act(() => tab(host, "design").focus());

await arrow("ArrowRight");

expect(document.activeElement).toBe(tab(host, "layers"));
expect(selections).toHaveBeenCalledWith("layers");
});

it("only moves focus on an arrow key when selection would toggle a pane", async () => {
const { host, selections } = mount(["design"], false);
act(() => tab(host, "design").focus());

await arrow("ArrowRight");

expect(document.activeElement).toBe(tab(host, "layers"));
expect(selections).not.toHaveBeenCalled();
});

it("jumps to the first and last tab with Home and End", async () => {
const { host, selections } = mount(["design"]);
act(() => tab(host, "design").focus());

await arrow("End");
expect(document.activeElement).toBe(tab(host, "variables"));
expect(selections).toHaveBeenLastCalledWith("variables");

await arrow("Home");
expect(document.activeElement).toBe(tab(host, "design"));
expect(selections).toHaveBeenLastCalledWith("design");
});

it("selects the tab whose content is on screen", () => {
const { host } = mount(["renders"]);

expect(selected(host)).toBe("renders");
});

it("leaves every tab unselected when the panel shows something the strip has no tab for", () => {
// Block params take over the panel body without a tab of their own. The old
// buttons all read unpressed in that state; nothing should read selected now.
const { host } = mount([]);

expect(selected(host)).toBe(null);
});

it("keeps a second open pane looking open in the legacy split inspector", () => {
// Design and Layers render together there. Only one tab can carry
// aria-selected, so the other has to keep the selected look or the strip
// would claim a pane is closed while it is on screen.
const { host } = mount(["design", "layers"]);

expect(selected(host)).toBe("design");
expect(tab(host, "layers").className).toContain("bg-hover");
});

it("classifies its tabs for the hotkey filters exactly as the old buttons did (KTD13)", () => {
// The old strip rendered plain <button>s: not a typing target, and claimed by
// the playback filter through its `button` selector. Base UI's tab is a
// <button> too, so both verdicts have to be unchanged.
const { host } = mount(["design"]);
const el = tab(host, "design");

expect(el.tagName).toBe("BUTTON");
expect(isTypingTarget(el)).toBe(false);
expect(shouldIgnorePlaybackShortcutTarget(el)).toBe(true);
});
59 changes: 59 additions & 0 deletions packages/studio/src/components/RightPanelTabs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* The inspector tab strip on the shared Tabs primitive. The selected tab is derived from the
* panel's state; in the legacy split inspector two can be open, only one holds `aria-selected`.
*/

import { Tab, Tabs, TabsList, Tooltip, cn } from "./ui";

export interface RightPanelTabDescriptor {
/** Stable id, also the `data-tab-id` attribute the strip is queried by. */
id: string;
label: string;
tooltip: string;
/** Whether this tab's content is on screen right now. */
active: boolean;
/** Run when the strip moves to this tab, by click or by arrow key. */
onSelect: () => void;
}

/** The look `aria-selected` gives the selected tab, for a second open pane. */
const SELECTED_LOOK = "bg-hover text-text-0";

export function RightPanelTabs({
tabs,
activateOnFocus = true,
}: {
tabs: readonly RightPanelTabDescriptor[];
/** False when `onSelect` toggles a pane, so an arrow key only moves focus. */
activateOnFocus?: boolean;
}) {
// `null` when the layout holds a tab this strip does not show (block params),
// which leaves every tab unselected, exactly as the old buttons did.
const value = tabs.find((tab) => tab.active)?.id ?? null;

return (
<Tabs
value={value}
onValueChange={(next) => {
tabs.find((tab) => tab.id === next)?.onSelect();
}}
>
<TabsList
aria-label="Inspector panels"
activateOnFocus={activateOnFocus}
className="flex min-w-0 items-center gap-1 overflow-hidden rounded-none border-b border-border-strong bg-transparent px-3 py-2"
>
{tabs.map((tab) => (
<Tooltip key={tab.id} label={tab.tooltip} side="bottom">
<Tab
value={tab.id}
className={cn("h-ctl-lg rounded-lg px-3 font-medium", tab.active && SELECTED_LOOK)}
>
{tab.label}
</Tab>
</Tooltip>
))}
</TabsList>
</Tabs>
);
}
153 changes: 153 additions & 0 deletions packages/studio/src/components/StudioHeader.dom.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// @vitest-environment happy-dom

/**
* The header on the shared primitives: same controls, disabled history still explained,
* hotkey filters unchanged (KTD13). Contexts are mocked, not provided.
*/
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { buttonSizes, buttonVariants } from "./ui";
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;

const editHistory = {
canUndo: false,
canRedo: false,
undoLabel: undefined as string | undefined,
redoLabel: undefined as string | undefined,
};
const renderQueue = { isRendering: false, ffmpegMissing: false };

vi.mock("../contexts/StudioContext", () => ({
useStudioShellContext: () => ({
projectId: "demo",
editHistory,
handleUndo: vi.fn(),
handleRedo: vi.fn(),
renderQueue,
}),
}));

vi.mock("../contexts/PanelLayoutContext", () => ({
usePanelLayoutContext: () => ({
effectiveRightCollapsed: false,
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
}),
}));

vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));

const { StudioHeader } = await import("./StudioHeader");

let mounted: { root: Root; host: HTMLElement } | null = null;

beforeEach(() => {
editHistory.canUndo = false;
editHistory.canRedo = false;
editHistory.undoLabel = undefined;
editHistory.redoLabel = undefined;
renderQueue.isRendering = false;
});

afterEach(() => {
if (!mounted) return;
const { root, host } = mounted;
mounted = null;
act(() => root.unmount());
host.remove();
});

function mount(): HTMLElement {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
mounted = { root, host };
act(() =>
root.render(
<StudioHeader
captureFrameHref="blob:frame"
captureFrameFilename="frame.png"
handleCaptureFrameClick={vi.fn()}
refreshCaptureFrameTime={vi.fn()}
inspectorButtonActive={false}
inspectorPanelActive={false}
/>,
),
);
return host;
}

function query(host: HTMLElement, selector: string): HTMLElement {
const el = host.querySelector<HTMLElement>(selector);
if (!el) throw new Error(`not rendered: ${selector}`);
return el;
}

/** Every class the recipe asks for, on the element the header rendered. */
function expectRecipe(el: HTMLElement, ...recipes: string[]): void {
const applied = new Set(el.className.split(/\s+/));
for (const recipe of recipes) {
for (const token of recipe.split(/\s+/)) {
expect(applied, `${token} missing from: ${el.className}`).toContain(token);
}
}
}

it("renders Export as the shared primary Button at the medium size", () => {
const host = mount();

expectRecipe(
query(host, '[data-testid="header-export"]'),
buttonVariants.primary,
buttonSizes.md,
);
});

it("disables Undo and Redo while the history is empty", () => {
const host = mount();

expect(query(host, '[aria-label="Undo"]').hasAttribute("disabled")).toBe(true);
expect(query(host, '[aria-label="Redo"]').hasAttribute("disabled")).toBe(true);
});

it("enables Undo once there is something to undo", () => {
editHistory.canUndo = true;
editHistory.undoLabel = "Move layer";
const host = mount();

expect(query(host, '[aria-label="Undo"]').hasAttribute("disabled")).toBe(false);
});

it("keeps Capture a real download link rather than a button", () => {
// `download` is what saves the frame. A Button here would render a <button>
// and the control would quietly stop downloading anything.
const host = mount();
const capture = query(host, '[aria-label="Capture current frame"]');

expect(capture.tagName).toBe("A");
expect(capture.getAttribute("download")).toBe("frame.png");
expectRecipe(capture, buttonSizes.md);
});

it("classifies the new header controls for the hotkey filters as the old ones were (KTD13)", () => {
// Every one of these was a <button> or an <a href> before the sweep: never a
// typing target, always claimed by the playback filter. A primitive that
// rendered a different element would leak or swallow hotkeys in silence.
const host = mount();
const controls = [
query(host, '[data-testid="header-export"]'),
query(host, '[aria-label="Undo"]'),
query(host, '[aria-label="Redo"]'),
query(host, '[aria-label="Inspector"]'),
query(host, '[aria-label="Capture current frame"]'),
];

for (const el of controls) {
expect(isTypingTarget(el), el.getAttribute("aria-label") ?? el.tagName).toBe(false);
expect(shouldIgnorePlaybackShortcutTarget(el), el.tagName).toBe(true);
}
});
Loading
Loading