Skip to content

Write HTML. Render video. Built for agents.

feat(studio): dock engine for a movable Studio layout, not yet wired in (#4165)

Miguel Ángeldc94692441d6
diff --git a/bun.lock b/bun.lock
index feae4a4433..e668339a15 100644
--- a/bun.lock
+++ b/bun.lock
@@ -336,6 +336,7 @@
"@phosphor-icons/react": "^2.1.10",
"@tanstack/react-virtual": "^3.14.6",
"bpm-detective": "^2.0.5",
+ "dockview-react": "8.3.1",
"gsap": "^3.13.0",
"mediabunny": "^1.45.3",
},
@@ -1434,6 +1435,14 @@
"dfa": ["[email protected]", "", {}, "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q=="],
+
+
+ "dockview": ["[email protected]", "", { "dependencies": { "dockview-core": "^8.3.1" } }, "sha512-2odBC9cDKcVCVx8Db86vq9s9JZKzbgvdkxDzcfsrD9nORLc5UqhLgLvVcJguorBv7CyEpKDzFO1JVLYWJCYrJA=="],
+
+ "dockview-core": ["[email protected]", "", {}, "sha512-6Loais9hlIRo25sTQSWGWlgbPr22ddoLBzpGDFaTnocawnC45twp5f2S2WxUz5/HPa/a65I4yxKUqZa8xrcc5Q=="],
+
+ "dockview-react": ["[email protected]", "", { "dependencies": { "dockview": "^8.3.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-siezdOZ5izcdEn7TSYeWc+mC3hPgyW6rK6QHd6+L6PCRUKdB0WkGABtLtHmLn4Dr3VCm6C2+cv1qSCqJBeiFyA=="],
+
"dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
"domelementtype": ["[email protected]", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 204ca053c4..2e93f8610f 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -78,6 +78,7 @@
"@phosphor-icons/react": "^2.1.10",
"@tanstack/react-virtual": "^3.14.6",
"bpm-detective": "^2.0.5",
+ "dockview-react": "8.3.1",
"gsap": "^3.13.0",
"mediabunny": "^1.45.3"
},
diff --git a/packages/studio/src/components/dock/Dock.test.tsx b/packages/studio/src/components/dock/Dock.test.tsx
new file mode 100644
index 0000000000..3c48e26acb
--- /dev/null
+++ b/packages/studio/src/components/dock/Dock.test.tsx
@@ -0,0 +1,192 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Dock } from "./Dock";
+import { parseDockLayout } from "./dockLayoutSchema";
+import { useDockLayoutStore } from "./dockLayoutStore";
+import { PANEL_IDS } from "./panelRegistry";
+import { readStudioUiPreferences } from "../../utils/studioUiPreferences";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = ResizeObserverStub;
+
+let root: Root | null = null;
+
+function mount(projectId: string | null) {
+ const host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ act(() => {
+ root?.render(
+ <Dock.Root projectId={projectId}>
+ {PANEL_IDS.map((id) => (
+ <Dock.Panel key={id} id={id}>
+ <div data-testid={`content-${id}`}>{id}</div>
+ </Dock.Panel>
+ ))}
+ </Dock.Root>,
+ );
+ });
+ return host;
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ document.body.innerHTML = "";
+ vi.useRealTimers();
+});
+
+// The default Edit layout tabs [compositions|assets|code|catalog] into one
+// group and [design|layers|renders|variables] into another; dockview shows
+// only the active tab's content per group. `slideshow` is never part of the
+// default build — StudioRightPanels opens it itself when the file is one.
+const DEFAULT_OPEN = PANEL_IDS.filter((id) => id !== "slideshow");
+const DEFAULT_VISIBLE = ["preview", "timeline", "compositions", "design"];
+
+describe("Dock on React 19", () => {
+ it("mounts the default layout's ten panels, showing only each group's active tab", () => {
+ const host = mount("p1");
+ for (const id of DEFAULT_VISIBLE) {
+ expect(host.querySelector(`[data-testid="content-${id}"]`)).not.toBeNull();
+ }
+ for (const id of DEFAULT_OPEN.filter((id) => !DEFAULT_VISIBLE.includes(id))) {
+ expect(host.querySelector(`[data-testid="content-${id}"]`)).toBeNull();
+ }
+ expect(host.querySelector('[data-testid="content-slideshow"]')).toBeNull();
+ expect(useDockLayoutStore.getState().openPanels).toEqual(new Set(DEFAULT_OPEN));
+ });
+
+ it("persists a layout change per project and reads it back through the schema", () => {
+ mount("p1");
+ act(() => useDockLayoutStore.getState().closePanel("renders"));
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+ const stored = readStudioUiPreferences(undefined, "p1").dockLayout;
+ const expected = DEFAULT_OPEN.filter((id) => id !== "renders");
+ expect(Object.keys(stored?.panels ?? {}).sort()).toEqual([...expected].sort());
+ expect(readStudioUiPreferences(undefined, "p2").dockLayout).toBeUndefined();
+ });
+
+ it("closes a panel and reopens it from the store, becoming its group's visible tab", async () => {
+ const host = mount("p1");
+ act(() => useDockLayoutStore.getState().closePanel("renders"));
+ expect(useDockLayoutStore.getState().openPanels.has("renders")).toBe(false);
+ expect(host.querySelector('[data-testid="content-renders"]')).toBeNull();
+ // dockview's own panel-active event dispatch resolves on a microtask, one
+ // tick after the synchronous store call returns; `act(async ...)` is what
+ // actually waits for it instead of asserting against pre-flush DOM.
+ await act(async () => {
+ useDockLayoutStore.getState().togglePanel("renders");
+ await Promise.resolve();
+ });
+ expect(useDockLayoutStore.getState().openPanels.has("renders")).toBe(true);
+ expect(host.querySelector('[data-testid="content-renders"]')).not.toBeNull();
+ });
+
+ it("reopens a closed panel as a tab of its zone's group, not a new group", () => {
+ mount("p1");
+ act(() => useDockLayoutStore.getState().closePanel("compositions"));
+ act(() => useDockLayoutStore.getState().togglePanel("compositions"));
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ const grid = JSON.stringify(readStudioUiPreferences(undefined, "p1").dockLayout?.grid);
+ const groups = [...grid.matchAll(/"views":\[([^\]]*)\]/g)].map((m) => m[1]);
+ const home = groups.find((views) => views.includes('"compositions"'));
+ expect(home).toContain('"assets"');
+ });
+
+ it("reopens a side panel next to the preview when its whole column was closed", () => {
+ mount("p1");
+ const { closePanel, togglePanel } = useDockLayoutStore.getState();
+ for (const id of ["compositions", "assets", "code", "catalog"] as const)
+ act(() => closePanel(id));
+ act(() => togglePanel("compositions"));
+ expect(useDockLayoutStore.getState().openPanels.has("compositions")).toBe(true);
+ expect(useDockLayoutStore.getState().visiblePanels.has("compositions")).toBe(true);
+ });
+
+ it("reopens the timeline as its own group, never as a tab of the preview", () => {
+ mount("p1");
+ act(() => useDockLayoutStore.getState().closePanel("timeline"));
+ act(() => useDockLayoutStore.getState().togglePanel("timeline"));
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ const grid = JSON.stringify(readStudioUiPreferences(undefined, "p1").dockLayout?.grid);
+ const groups = [...grid.matchAll(/"views":\[([^\]]*)\]/g)].map((m) => m[1]);
+ expect(groups.find((views) => views.includes('"timeline"'))).not.toContain('"preview"');
+ });
+
+ it("restores the stored layout on the next mount instead of rebuilding the default", () => {
+ mount("p1");
+ act(() => useDockLayoutStore.getState().closePanel("renders"));
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ act(() => root?.unmount());
+ root = null;
+ document.body.innerHTML = "";
+
+ mount("p1");
+ expect(useDockLayoutStore.getState().openPanels.has("renders")).toBe(false);
+ });
+
+ it("falls back to the default layout when the stored one names an unknown panel", () => {
+ localStorage.setItem(
+ "hf-studio-ui-preferences:p1",
+ JSON.stringify({ dockLayout: { grid: {}, panels: { nope: {} } } }),
+ );
+ const host = mount("p1");
+ expect(host.querySelector('[data-testid="content-preview"]')).not.toBeNull();
+ });
+});
+
+describe("parseDockLayout", () => {
+ it("rejects shapes that are not a dock layout", () => {
+ expect(parseDockLayout(null)).toBeNull();
+ expect(parseDockLayout({ grid: {}, panels: {} })).toBeNull();
+ expect(
+ parseDockLayout({
+ grid: {
+ width: 1,
+ height: 1,
+ orientation: "HORIZONTAL",
+ root: { type: "leaf", data: { views: ["ghost"] } },
+ },
+ panels: { ghost: { id: "ghost", contentComponent: "panel" } },
+ }),
+ ).toBeNull();
+ });
+
+ const placed = (views: string[], panelIds: string[]) => ({
+ grid: {
+ width: 1,
+ height: 1,
+ orientation: "HORIZONTAL",
+ root: { type: "leaf", data: { views } },
+ },
+ panels: Object.fromEntries(panelIds.map((id) => [id, { id, contentComponent: "panel" }])),
+ });
+
+ it("rejects a view that has no panel entry and a panel that no view places", () => {
+ expect(parseDockLayout(placed(["preview", "design"], ["preview"]))).toBeNull();
+ expect(parseDockLayout(placed(["preview"], ["preview", "design"]))).toBeNull();
+ expect(parseDockLayout(placed(["preview", "design"], ["preview", "design"]))).not.toBeNull();
+ });
+});
diff --git a/packages/studio/src/components/dock/Dock.tsx b/packages/studio/src/components/dock/Dock.tsx
new file mode 100644
index 0000000000..e00d9fd42d
--- /dev/null
+++ b/packages/studio/src/components/dock/Dock.tsx
@@ -0,0 +1,264 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { createPortal } from "react-dom";
+import {
+ DockviewReact,
+ type DockviewApi,
+ type DockviewReadyEvent,
+ type IDockviewPanelProps,
+} from "dockview-react";
+import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
+import { addRegisteredPanel, buildEditLayout } from "./dockLayout";
+import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
+import { useDockLayoutStore, type DockController, type DockSnapshot } from "./dockLayoutStore";
+import {
+ PANEL_DEFINITIONS,
+ PANEL_IDS,
+ isPanelId,
+ panelsInZone,
+ type PanelDefinition,
+ type PanelId,
+} from "./panelRegistry";
+import "./dock.css";
+
+const PERSIST_DEBOUNCE_MS = 250;
+
+type Slots = Partial<Record<PanelId, HTMLElement>>;
+
+interface SlotsContextValue {
+ slots: Slots;
+ registerSlot: (id: PanelId, element: HTMLElement | null) => void;
+}
+
+const SlotsContext = createContext<SlotsContextValue | null>(null);
+
+function useSlots(): SlotsContextValue {
+ const value = useContext(SlotsContext);
+ if (!value) throw new Error("Dock.Panel must be rendered inside Dock.Root");
+ return value;
+}
+
+/** The element dockview mounts for a panel; Dock.Panel portals the real content into it. */
+function PanelSlot({ api }: IDockviewPanelProps) {
+ const { registerSlot } = useSlots();
+ const id = api.id;
+ const ref = useCallback(
+ (element: HTMLDivElement | null) => {
+ if (isPanelId(id)) registerSlot(id, element);
+ },
+ [id, registerSlot],
+ );
+ return <div ref={ref} className="h-full w-full min-h-0 min-w-0 overflow-hidden" />;
+}
+
+const COMPONENTS = { [DOCK_PANEL_COMPONENT]: PanelSlot };
+
+function snapshot(api: DockviewApi): DockSnapshot {
+ const openPanels = new Set<PanelId>();
+ const visiblePanels = new Set<PanelId>();
+ for (const panel of api.panels) {
+ if (!isPanelId(panel.id)) continue;
+ openPanels.add(panel.id);
+ if (panel.api.isVisible && panel.group.api.isVisible) visiblePanels.add(panel.id);
+ }
+ const active = api.activePanel?.id;
+ return { openPanels, visiblePanels, activePanel: isPanelId(active) ? active : null };
+}
+
+function createController(api: DockviewApi): DockController {
+ const open = (id: PanelId) => {
+ if (api.getPanel(id)) return;
+ const { zone, reopen } = PANEL_DEFINITIONS[id];
+ // Side columns are tab groups; preview and timeline are separate groups in the centre.
+ const sibling =
+ zone === "center"
+ ? undefined
+ : panelsInZone(zone).find((other) => other !== id && api.getPanel(other));
+ if (sibling) {
+ addRegisteredPanel(api, id, { referencePanel: sibling, direction: "within" });
+ return;
+ }
+ const hasAnchor = api.getPanel(reopen.near) !== undefined;
+ const position = { referencePanel: reopen.near, direction: reopen.direction };
+ addRegisteredPanel(api, id, hasAnchor ? position : undefined);
+ };
+ return {
+ open,
+ activate: (id) => {
+ open(id);
+ api.getPanel(id)?.api.setActive();
+ },
+ close: (id) => {
+ const panel = api.getPanel(id);
+ if (panel) api.removePanel(panel);
+ },
+ setTitle: (id, title) => api.getPanel(id)?.api.setTitle(title),
+ setGroupVisible: (id, visible) => api.getPanel(id)?.group.api.setVisible(visible),
+ reset: () => buildEditLayout(api, window.innerWidth),
+ };
+}
+
+function restoreOrBuild(api: DockviewApi, projectId: string | null) {
+ const stored = readStudioUiPreferences(undefined, projectId).dockLayout;
+ if (stored) {
+ try {
+ api.fromJSON(stored);
+ return;
+ } catch {
+ /* a layout the schema accepted but dockview cannot load: start over */
+ }
+ }
+ buildEditLayout(api, window.innerWidth);
+}
+
+function Root({ projectId, children }: { projectId: string | null; children: ReactNode }) {
+ const [slots, setSlots] = useState<Slots>({});
+ const registerSlot = useCallback((id: PanelId, element: HTMLElement | null) => {
+ setSlots((prev) => {
+ if (prev[id] === (element ?? undefined)) return prev;
+ const next = { ...prev };
+ if (element) next[id] = element;
+ else delete next[id];
+ return next;
+ });
+ }, []);
+
+ const disposeRef = useRef<() => void>(() => {});
+ useEffect(() => () => disposeRef.current(), []);
+
+ const onReady = useCallback(
+ ({ api }: DockviewReadyEvent) => {
+ restoreOrBuild(api, projectId);
+ const store = useDockLayoutStore.getState();
+ store.attach(createController(api));
+ store.sync(snapshot(api));
+ const pending = store.takePendingActivation();
+ if (pending) api.getPanel(pending)?.api.setActive();
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const persist = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ writeStudioUiPreferences({ dockLayout: api.toJSON() }, undefined, projectId);
+ }, PERSIST_DEBOUNCE_MS);
+ };
+ // dockview does not fire onDidLayoutChange for add/remove/activate,
+ // so every event class is wired to the same sync+persist pair.
+ const onDockChange = () => {
+ useDockLayoutStore.getState().sync(snapshot(api));
+ persist();
+ };
+ const subscriptions = [
+ api.onDidAddPanel(onDockChange),
+ api.onDidRemovePanel(onDockChange),
+ api.onDidActivePanelChange(onDockChange),
+ api.onDidLayoutChange(onDockChange),
+ ];
+ disposeRef.current = () => {
+ clearTimeout(timer);
+ for (const subscription of subscriptions) subscription.dispose();
+ useDockLayoutStore.getState().detach();
+ };
+ },
+ [projectId],
+ );
+
+ return (
+ <SlotsContext.Provider value={{ slots, registerSlot }}>
+ <DockviewReact
+ key={projectId ?? ""}
+ className="hf-dock flex-1 min-h-0"
+ components={COMPONENTS}
+ defaultRenderer="always"
+ disableFloatingGroups
+ onReady={onReady}
+ />
+ {children}
+ </SlotsContext.Provider>
+ );
+}
+
+function Panel({ id, title, children }: { id: PanelId; title?: string; children: ReactNode }) {
+ const element = useSlots().slots[id];
+ const visible = useDockLayoutStore((state) => state.visiblePanels.has(id));
+ const controller = useDockLayoutStore((state) => state.controller);
+ const label = title ?? PANEL_DEFINITIONS[id].title;
+ useEffect(() => {
+ controller?.setTitle(id, label);
+ }, [controller, id, label]);
+ const definition: PanelDefinition = PANEL_DEFINITIONS[id];
+ const shown = visible || definition.keepMounted;
+ return element && shown ? createPortal(children, element) : null;
+}
+
+function WindowMenu() {
+ const openPanels = useDockLayoutStore((state) => state.openPanels);
+ const togglePanel = useDockLayoutStore((state) => state.togglePanel);
+ const resetLayout = useDockLayoutStore((state) => state.resetLayout);
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const close = (event: PointerEvent) => {
+ if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
+ };
+ document.addEventListener("pointerdown", close);
+ return () => document.removeEventListener("pointerdown", close);
+ }, [open]);
+
+ return (
+ <div ref={rootRef} className="relative">
+ <button
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded={open}
+ onClick={() => setOpen((value) => !value)}
+ className="h-7 px-2.5 rounded-md text-[11px] font-medium text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800 transition-colors"
+ >
+ Window
+ </button>
+ {open && (
+ <div
+ role="menu"
+ className="absolute right-0 top-8 z-50 w-44 rounded-md border border-neutral-800 bg-neutral-900 py-1 shadow-lg"
+ >
+ {PANEL_IDS.map((id) => (
+ <button
+ key={id}
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={openPanels.has(id)}
+ onClick={() => togglePanel(id)}
+ className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-neutral-300 hover:bg-neutral-800"
+ >
+ <span className="w-3 text-panel-accent">{openPanels.has(id) ? "✓" : ""}</span>
+ {PANEL_DEFINITIONS[id].title}
+ </button>
+ ))}
+ <div className="my-1 border-t border-neutral-800" />
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ resetLayout();
+ setOpen(false);
+ }}
+ className="w-full px-3 py-1.5 text-left text-[11px] text-neutral-300 hover:bg-neutral-800"
+ >
+ Reset layout
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export const Dock = { Root, Panel, WindowMenu };
diff --git a/packages/studio/src/components/dock/dock.css b/packages/studio/src/components/dock/dock.css
new file mode 100644
index 0000000000..8eb8f2bf3a
--- /dev/null
+++ b/packages/studio/src/components/dock/dock.css
@@ -0,0 +1,23 @@
+@import "dockview-react/dist/styles/dockview.css";
+
+.hf-dock {
+ --dv-group-view-background-color: var(--color-panel-bg);
+ --dv-tabs-and-actions-container-background-color: var(--color-panel-surface);
+ --dv-activegroup-visiblepanel-tab-background-color: var(--color-panel-bg);
+ --dv-activegroup-hiddenpanel-tab-background-color: var(--color-panel-surface);
+ --dv-inactivegroup-visiblepanel-tab-background-color: var(--color-panel-bg);
+ --dv-inactivegroup-hiddenpanel-tab-background-color: var(--color-panel-surface);
+ --dv-activegroup-visiblepanel-tab-color: var(--color-panel-text-1);
+ --dv-activegroup-hiddenpanel-tab-color: var(--color-panel-text-3);
+ --dv-inactivegroup-visiblepanel-tab-color: var(--color-panel-text-2);
+ --dv-inactivegroup-hiddenpanel-tab-color: var(--color-panel-text-4);
+ --dv-tab-divider-color: var(--color-panel-border);
+ --dv-separator-border: var(--color-panel-border);
+ --dv-paneview-header-border-color: var(--color-panel-border);
+ --dv-sash-color: var(--color-panel-hover);
+ --dv-active-sash-color: var(--color-panel-accent);
+ --dv-drag-over-background-color: color-mix(in srgb, var(--color-panel-accent) 12%, transparent);
+ --dv-drag-over-border-color: var(--color-panel-accent);
+ --dv-tab-font-size: 11px;
+ --dv-tabs-and-actions-container-font-size: 11px;
+}
diff --git a/packages/studio/src/components/dock/dockLayout.ts b/packages/studio/src/components/dock/dockLayout.ts
new file mode 100644
index 0000000000..8b98c76ecf
--- /dev/null
+++ b/packages/studio/src/components/dock/dockLayout.ts
@@ -0,0 +1,58 @@
+import type { Direction, DockviewApi } from "dockview-react";
+import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
+import { PANEL_DEFINITIONS, type PanelId } from "./panelRegistry";
+
+const MIN_PREVIEW_W = 360;
+const MIN_PREVIEW_H = 200;
+const MIN_TIMELINE_H = 100;
+const MIN_SIDE_W = 200;
+const DEFAULT_TIMELINE_H = 360;
+
+function defaultSideWidths(viewportWidth: number) {
+ return {
+ left: Math.max(MIN_SIDE_W, Math.min(384, Math.round(viewportWidth * 0.257))),
+ right: Math.max(280, Math.min(424, Math.round(viewportWidth * 0.284))),
+ };
+}
+
+function minimumSize(id: PanelId) {
+ if (id === "preview") return { minimumWidth: MIN_PREVIEW_W, minimumHeight: MIN_PREVIEW_H };
+ if (id === "timeline") return { minimumHeight: MIN_TIMELINE_H };
+ return { minimumWidth: MIN_SIDE_W };
+}
+
+export function addRegisteredPanel(
+ api: DockviewApi,
+ id: PanelId,
+ position?: { referencePanel: PanelId; direction: Direction },
+) {
+ return api.addPanel({
+ id,
+ component: DOCK_PANEL_COMPONENT,
+ title: PANEL_DEFINITIONS[id].title,
+ renderer: "always",
+ ...minimumSize(id),
+ ...(position ? { position } : {}),
+ });
+}
+
+/** The default Edit layout: [library | preview | inspector] over a full-width timeline. */
+export function buildEditLayout(api: DockviewApi, viewportWidth: number) {
+ api.clear();
+ const widths = defaultSideWidths(viewportWidth);
+ addRegisteredPanel(api, "preview");
+ addRegisteredPanel(api, "timeline", { referencePanel: "preview", direction: "below" });
+ addRegisteredPanel(api, "compositions", { referencePanel: "preview", direction: "left" });
+ for (const id of ["assets", "code", "catalog"] as const) {
+ addRegisteredPanel(api, id, { referencePanel: "compositions", direction: "within" });
+ }
+ addRegisteredPanel(api, "design", { referencePanel: "preview", direction: "right" });
+ for (const id of ["layers", "renders", "variables"] as const) {
+ addRegisteredPanel(api, id, { referencePanel: "design", direction: "within" });
+ }
+ api.getPanel("compositions")?.api.setActive();
+ api.getPanel("design")?.api.setActive();
+ api.getPanel("compositions")?.group.api.setSize({ width: widths.left });
+ api.getPanel("design")?.group.api.setSize({ width: widths.right });
+ api.getPanel("timeline")?.group.api.setSize({ height: DEFAULT_TIMELINE_H });
+}
diff --git a/packages/studio/src/components/dock/dockLayoutSchema.ts b/packages/studio/src/components/dock/dockLayoutSchema.ts
new file mode 100644
index 0000000000..f9db12baad
--- /dev/null
+++ b/packages/studio/src/components/dock/dockLayoutSchema.ts
@@ -0,0 +1,66 @@
+import type { SerializedDockview } from "dockview-react";
+import { isPanelId } from "./panelRegistry";
+
+export const DOCK_PANEL_COMPONENT = "panel";
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function collectLeafViews(node: unknown, into: unknown[]): boolean {
+ if (!isRecord(node)) return false;
+ if (node.type === "leaf") {
+ if (!isRecord(node.data) || !Array.isArray(node.data.views)) return false;
+ into.push(...node.data.views);
+ return true;
+ }
+ if (node.type === "branch") {
+ return Array.isArray(node.data) && node.data.every((child) => collectLeafViews(child, into));
+ }
+ return false;
+}
+
+function hasGridShape(grid: Record<string, unknown>): boolean {
+ const oriented = grid.orientation === "HORIZONTAL" || grid.orientation === "VERTICAL";
+ return oriented && typeof grid.width === "number" && typeof grid.height === "number";
+}
+
+function panelsAreRegistered(panels: Record<string, unknown>): boolean {
+ const ids = Object.keys(panels);
+ return (
+ ids.length > 0 &&
+ ids.every((id) => {
+ const state = panels[id];
+ return (
+ isPanelId(id) &&
+ isRecord(state) &&
+ state.id === id &&
+ state.contentComponent === DOCK_PANEL_COMPONENT
+ );
+ })
+ );
+}
+
+function collectFloatingViews(floating: unknown, into: unknown[]): boolean {
+ if (floating === undefined) return true;
+ if (!Array.isArray(floating)) return false;
+ return floating.every((group) => {
+ if (!isRecord(group) || !isRecord(group.data) || !Array.isArray(group.data.views)) return false;
+ into.push(...group.data.views);
+ return true;
+ });
+}
+
+/** Parses a stored layout at the trust boundary; null (stale or foreign shape) means use the default preset. */
+export function parseDockLayout(value: unknown): SerializedDockview | null {
+ if (!isRecord(value) || !isRecord(value.grid) || !isRecord(value.panels)) return null;
+ const { grid, panels } = value;
+ if (!hasGridShape(grid) || !panelsAreRegistered(panels)) return null;
+
+ const views: unknown[] = [];
+ if (!collectLeafViews(grid.root, views)) return null;
+ if (!collectFloatingViews(value.floatingGroups, views)) return null;
+ const everyViewIsAPanel = views.every((id) => typeof id === "string" && id in panels);
+ const everyPanelIsPlaced = Object.keys(panels).every((id) => views.includes(id));
+ return everyViewIsAPanel && everyPanelIsPlaced ? (value as unknown as SerializedDockview) : null;
+}
diff --git a/packages/studio/src/components/dock/dockLayoutStore.ts b/packages/studio/src/components/dock/dockLayoutStore.ts
new file mode 100644
index 0000000000..cffa0ad1dd
--- /dev/null
+++ b/packages/studio/src/components/dock/dockLayoutStore.ts
@@ -0,0 +1,91 @@
+import { create } from "zustand";
+import {
+ PANEL_DEFINITIONS,
+ PANEL_IDS,
+ panelsInZone,
+ type PanelId,
+ type PanelZone,
+} from "./panelRegistry";
+
+/** The narrow surface Dock.Root exposes; dockview types never leave the dock folder. */
+export interface DockController {
+ /** Adds the panel at its default place if it is closed; never moves focus. */
+ open: (id: PanelId) => void;
+ /** Focuses the panel, reopening it at its default place if it was closed. */
+ activate: (id: PanelId) => void;
+ setTitle: (id: PanelId, title: string) => void;
+ close: (id: PanelId) => void;
+ /** Hides or shows the panel's whole tab group without closing it. */
+ setGroupVisible: (id: PanelId, visible: boolean) => void;
+ reset: () => void;
+}
+
+export interface DockSnapshot {
+ openPanels: ReadonlySet<PanelId>;
+ /** Open panels whose tab is showing and whose group is not hidden. */
+ visiblePanels: ReadonlySet<PanelId>;
+ activePanel: PanelId | null;
+}
+
+type LastActive = Partial<Record<PanelZone, PanelId>>;
+
+interface DockLayoutState extends DockSnapshot {
+ controller: DockController | null;
+ lastActive: LastActive;
+ /** An activation requested before the dock mounted; Dock.Root applies it on ready. */
+ pendingActivation: PanelId | null;
+ attach: (controller: DockController) => void;
+ detach: () => void;
+ sync: (snapshot: DockSnapshot) => void;
+ takePendingActivation: () => PanelId | null;
+ activatePanel: (id: PanelId) => void;
+ closePanel: (id: PanelId) => void;
+ togglePanel: (id: PanelId) => void;
+ setZoneVisible: (zone: PanelZone, visible: boolean) => void;
+ resetLayout: () => void;
+}
+
+export const useDockLayoutStore = create<DockLayoutState>((set, get) => ({
+ controller: null,
+ openPanels: new Set(PANEL_IDS),
+ visiblePanels: new Set(PANEL_IDS),
+ activePanel: null,
+ lastActive: {},
+ pendingActivation: null,
+ attach: (controller) => set({ controller }),
+ detach: () => set({ controller: null }),
+ sync: (snapshot) =>
+ set((state) => {
+ const { activePanel } = snapshot;
+ if (!activePanel) return snapshot;
+ const zone = PANEL_DEFINITIONS[activePanel].zone;
+ return { ...snapshot, lastActive: { ...state.lastActive, [zone]: activePanel } };
+ }),
+ takePendingActivation: () => {
+ const { pendingActivation } = get();
+ set({ pendingActivation: null });
+ return pendingActivation;
+ },
+ activatePanel: (id) => {
+ const { controller } = get();
+ if (!controller) {
+ set({ pendingActivation: id });
+ return;
+ }
+ controller.setGroupVisible(id, true);
+ controller.activate(id);
+ },
+ closePanel: (id) => get().controller?.close(id),
+ togglePanel: (id) => {
+ const { openPanels, activatePanel, closePanel } = get();
+ if (openPanels.has(id)) closePanel(id);
+ else activatePanel(id);
+ },
+ setZoneVisible: (zone, visible) => {
+ const { controller, openPanels } = get();
+ for (const id of panelsInZone(zone)) {
+ if (openPanels.has(id)) controller?.setGroupVisible(id, visible);
+ }
+ },
+ resetLayout: () => get().controller?.reset(),
+}));
diff --git a/packages/studio/src/components/dock/panelRegistry.ts b/packages/studio/src/components/dock/panelRegistry.ts
new file mode 100644
index 0000000000..303f31eede
--- /dev/null
+++ b/packages/studio/src/components/dock/panelRegistry.ts
@@ -0,0 +1,67 @@
+import type { Direction } from "dockview-react";
+
+export const PANEL_IDS = [
+ "preview",
+ "timeline",
+ "compositions",
+ "assets",
+ "code",
+ "catalog",
+ "design",
+ "layers",
+ "renders",
+ "variables",
+ "slideshow",
+] as const;
+
+export type PanelId = (typeof PANEL_IDS)[number];
+export type PanelZone = "left" | "center" | "right";
+
+export interface PanelDefinition {
+ title: string;
+ zone: PanelZone;
+ /** Where Window > <panel> puts it when it has no saved place: next to `near`. */
+ reopen: { near: PanelId; direction: Direction };
+ /** Content stays mounted while its tab is hidden (the preview iframe must not reload). */
+ keepMounted?: true;
+}
+
+export const PANEL_DEFINITIONS = {
+ preview: {
+ title: "Preview",
+ zone: "center",
+ reopen: { near: "timeline", direction: "above" },
+ keepMounted: true,
+ },
+ timeline: {
+ title: "Timeline",
+ zone: "center",
+ reopen: { near: "preview", direction: "below" },
+ keepMounted: true,
+ },
+ compositions: {
+ title: "Compositions",
+ zone: "left",
+ reopen: { near: "preview", direction: "left" },
+ },
+ assets: { title: "Assets", zone: "left", reopen: { near: "compositions", direction: "within" } },
+ code: { title: "Code", zone: "left", reopen: { near: "compositions", direction: "within" } },
+ catalog: {
+ title: "Catalog",
+ zone: "left",
+ reopen: { near: "compositions", direction: "within" },
+ },
+ design: { title: "Design", zone: "right", reopen: { near: "preview", direction: "right" } },
+ layers: { title: "Layers", zone: "right", reopen: { near: "design", direction: "within" } },
+ renders: { title: "Renders", zone: "right", reopen: { near: "design", direction: "within" } },
+ variables: { title: "Variables", zone: "right", reopen: { near: "design", direction: "within" } },
+ slideshow: { title: "Slideshow", zone: "right", reopen: { near: "design", direction: "within" } },
+} as const satisfies Record<PanelId, PanelDefinition>;
+
+export function isPanelId(value: unknown): value is PanelId {
+ return typeof value === "string" && (PANEL_IDS as readonly string[]).includes(value);
+}
+
+export function panelsInZone(zone: PanelZone): PanelId[] {
+ return PANEL_IDS.filter((id) => PANEL_DEFINITIONS[id].zone === zone);
+}
diff --git a/packages/studio/src/utils/studioUiPreferences.ts b/packages/studio/src/utils/studioUiPreferences.ts
index 53a73fc064..c1eb6bf7c9 100644
--- a/packages/studio/src/utils/studioUiPreferences.ts
+++ b/packages/studio/src/utils/studioUiPreferences.ts
@@ -1,3 +1,6 @@
+import type { SerializedDockview } from "dockview-react";
+import { parseDockLayout } from "../components/dock/dockLayoutSchema";
+
export interface StoredPreviewZoomState {
zoomPercent: number;
panX: number;
@@ -47,6 +50,8 @@ export interface StudioUiPreferences {
* intentionally scoped to one mount.
*/
agentToolsEnabled?: boolean;
+ /** The dock's serialized panel tree; parsed by `parseDockLayout` on read. */
+ dockLayout?: SerializedDockview;
}
const STUDIO_UI_PREFERENCES_KEY = "hf-studio-ui-preferences";
@@ -169,6 +174,8 @@ function readStorage(storage: Storage | null, key: string): StudioUiPreferences
if (typeof parsed.agentToolsEnabled === "boolean") {
preferences.agentToolsEnabled = parsed.agentToolsEnabled;
}
+ const dockLayout = parseDockLayout(parsed.dockLayout);
+ if (dockLayout) preferences.dockLayout = dockLayout;
return preferences;
} catch {
return {};