Skip to content

Write HTML. Render video. Built for agents.

feat(studio): a host app can mount the dock with its own panels, storage key and width (#4812)

Miguel Ángel7719f973c059
diff --git a/packages/studio/src/components/dock/Dock.test.tsx b/packages/studio/src/components/dock/Dock.test.tsx
index f036d2fce5..fb1fd53467 100644
--- a/packages/studio/src/components/dock/Dock.test.tsx
+++ b/packages/studio/src/components/dock/Dock.test.tsx
@@ -48,23 +48,30 @@ class ResizeObserverStub {
vi.mock("./dockLayout", async (importOriginal) => {
const actual = await importOriginal<typeof import("./dockLayout")>();
- return { ...actual, applySideMinimums: vi.fn(actual.applySideMinimums) };
+ return {
+ ...actual,
+ applySideMinimums: vi.fn(actual.applySideMinimums),
+ addRegisteredPanel: vi.fn(actual.addRegisteredPanel),
+ };
});
const applySideMinimums = vi.mocked(dockLayout.applySideMinimums);
+const addRegisteredPanel = vi.mocked(dockLayout.addRegisteredPanel);
let root: Root | null = null;
function mount(
projectId: string | null,
titles: Partial<Record<(typeof PANEL_IDS)[number], string>> = {},
+ options: Omit<ComponentProps<typeof Dock.Root>, "projectId" | "children"> = {},
) {
const host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
act(() => {
root?.render(
- <Dock.Root projectId={projectId}>
- {PANEL_IDS.map((id) => (
+ <Dock.Root projectId={projectId} {...options}>
+ <Dock.WindowMenu />
+ {(options.panels ?? PANEL_IDS).map((id) => (
<Dock.Panel key={id} id={id} title={titles[id]}>
<div data-testid={`content-${id}`}>{id}</div>
</Dock.Panel>
@@ -173,6 +180,16 @@ describe("Dock on React 19", () => {
expect(useDockLayoutStore.getState().visiblePanels.has("compositions")).toBe(true);
});
+ it("reopens a panel whose usual neighbour is only closed exactly as before: no new position", () => {
+ mount("p1");
+ const { closePanel, togglePanel } = useDockLayoutStore.getState();
+ for (const id of ["compositions", "assets", "code", "catalog"] as const)
+ act(() => closePanel(id));
+ addRegisteredPanel.mockClear();
+ act(() => togglePanel("assets"));
+ expect(addRegisteredPanel).toHaveBeenCalledWith(expect.anything(), "assets", undefined);
+ });
+
it("reopens the timeline as its own group, never as a tab of the preview", () => {
mount("p1");
act(() => useDockLayoutStore.getState().closePanel("timeline"));
@@ -239,6 +256,64 @@ describe("Dock wiring", () => {
});
});
+// A host app mounts a subset of Studio's panels under its own storage key and width.
+describe("a host's dock", () => {
+ const panels = ["preview", "timeline", "assets", "renders"] as const;
+ const hostDock = { panels, storageKey: "host-dock" };
+
+ it("builds only its panels, a side column each, and its Window menu lists only them", () => {
+ const host = mount("p1", {}, hostDock);
+ expect(useDockLayoutStore.getState().openPanels).toEqual(new Set(panels));
+ expect(useDockLayoutStore.getState().visiblePanels).toEqual(new Set(panels));
+ expect(dockApi?.getPanel("assets")?.group.id).not.toBe(dockApi?.getPanel("renders")?.group.id);
+ const menu = [...host.querySelectorAll("button")].find((b) => b.textContent === "Window");
+ act(() => menu?.click());
+ const items = [...host.querySelectorAll('[role="menuitemcheckbox"]')].map((i) => i.textContent);
+ expect(items).toEqual(["✓Preview", "✓Timeline", "✓Assets", "✓Renders"]);
+ });
+
+ it("keeps its layout alone under its own key, never in Studio's preferences", () => {
+ mount("p1", {}, hostDock);
+ act(() => useDockLayoutStore.getState().closePanel("renders"));
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+ const stored = readStudioUiPreferences(undefined, "p1", "host-dock").dockLayout;
+ expect(Object.keys(stored?.panels ?? {}).sort()).toEqual(["assets", "preview", "timeline"]);
+ expect(readStudioUiPreferences(undefined, "p1").dockLayout).toBeUndefined();
+ });
+
+ it("falls back to its default when a stored layout names a panel it lacks", () => {
+ mount("p1");
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+ const studio = readStudioUiPreferences(undefined, "p1").dockLayout;
+ act(() => root?.unmount());
+ root = null;
+ localStorage.setItem("host-dock:p1", JSON.stringify({ dockLayout: studio }));
+ mount("p1", {}, hostDock);
+ expect(useDockLayoutStore.getState().openPanels).toEqual(new Set(panels));
+ });
+
+ it("reopens a panel beside the preview when the panel it reopens near is not in the dock", () => {
+ mount("p1", {}, hostDock);
+ act(() => useDockLayoutStore.getState().closePanel("assets"));
+ act(() => useDockLayoutStore.getState().togglePanel("assets"));
+ expect(useDockLayoutStore.getState().visiblePanels.has("assets")).toBe(true);
+ });
+
+ it("sizes its sides against its own width, not the window's", () => {
+ mount(null, {}, { ...hostDock, dockWidth: () => 700 });
+ applySideMinimums.mockClear();
+ const dockObservers = [...liveObservers].filter(({ target }) =>
+ target?.classList.contains("hf-dock"),
+ );
+ act(() => dockObservers.forEach(({ callback }) => callback()));
+ expect(applySideMinimums).toHaveBeenCalledWith(expect.anything(), 700);
+ });
+});
+
describe("parseDockLayout", () => {
it("rejects shapes that are not a dock layout", () => {
expect(parseDockLayout(null)).toBeNull();
diff --git a/packages/studio/src/components/dock/Dock.tsx b/packages/studio/src/components/dock/Dock.tsx
index 842045a62e..9ba5ab14b6 100644
--- a/packages/studio/src/components/dock/Dock.tsx
+++ b/packages/studio/src/components/dock/Dock.tsx
@@ -20,7 +20,7 @@ import { DockStripActions } from "./DockStripActions";
import { DockTab } from "./DockTab";
import { installTabFill } from "./dockTabFill";
import { addRegisteredPanel, applySideMinimums, buildEditLayout } from "./dockLayout";
-import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
+import { DOCK_PANEL_COMPONENT, parseDockLayout } from "./dockLayoutSchema";
import { useDockLayoutStore, type DockController, type DockSnapshot } from "./dockLayoutStore";
import {
PANEL_DEFINITIONS,
@@ -85,10 +85,20 @@ function snapshot(api: DockviewApi): DockSnapshot {
};
}
-function createController(api: DockviewApi): DockController {
+interface DockOptions {
+ panels: readonly PanelId[];
+ storageKey?: string | undefined;
+ dockWidth: () => number;
+}
+
+function createController(api: DockviewApi, options: DockOptions): DockController {
const open = (id: PanelId) => {
if (api.getPanel(id)) return;
- const { zone, reopen } = PANEL_DEFINITIONS[id];
+ const { zone, reopen: preferred } = PANEL_DEFINITIONS[id];
+ const reopen: PanelDefinition["reopen"] =
+ zone === "center" || options.panels.includes(preferred.near)
+ ? preferred
+ : { near: "preview", direction: zone };
// Side columns are tab groups; preview and timeline are separate groups in the centre.
const sibling =
zone === "center"
@@ -114,12 +124,13 @@ function createController(api: DockviewApi): DockController {
},
setTitle: (id, title) => api.getPanel(id)?.api.setTitle(title),
setGroupVisible: (id, visible) => api.getPanel(id)?.group.api.setVisible(visible),
- reset: () => buildEditLayout(api, window.innerWidth),
+ reset: () => buildEditLayout(api, options.dockWidth(), options.panels),
};
}
-function restoreOrBuild(api: DockviewApi, projectId: string | null) {
- const stored = readStudioUiPreferences(undefined, projectId).dockLayout;
+function restoreOrBuild(api: DockviewApi, projectId: string | null, options: DockOptions) {
+ const { dockLayout } = readStudioUiPreferences(undefined, projectId, options.storageKey);
+ const stored = parseDockLayout(dockLayout, options.panels);
if (stored) {
try {
api.fromJSON(stored);
@@ -128,10 +139,24 @@ function restoreOrBuild(api: DockviewApi, projectId: string | null) {
/* a layout the schema accepted but dockview cannot load: start over */
}
}
- buildEditLayout(api, window.innerWidth);
+ buildEditLayout(api, options.dockWidth(), options.panels);
}
-function Root({ projectId, children }: { projectId: string | null; children: ReactNode }) {
+const windowWidth = () => window.innerWidth;
+
+function Root({
+ projectId,
+ panels = PANEL_IDS,
+ storageKey,
+ dockWidth = windowWidth,
+ children,
+}: {
+ projectId: string | null;
+ panels?: readonly PanelId[];
+ storageKey?: string;
+ dockWidth?: () => number;
+ children: ReactNode;
+}) {
const [slots, setSlots] = useState<Slots>({});
const registerSlot = useCallback((id: PanelId, element: HTMLElement | null) => {
setSlots((prev) => {
@@ -149,16 +174,17 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
const onReady = useCallback(
({ api }: DockviewReadyEvent) => {
disposeRef.current();
- restoreOrBuild(api, projectId);
- applySideMinimums(api);
+ const options = { panels, storageKey, dockWidth };
+ restoreOrBuild(api, projectId, options);
+ applySideMinimums(api, dockWidth());
const root = api.groups[0]?.element.closest<HTMLElement>(".hf-dock");
const disposeAccessibility = root ? installDockAccessibility(api, root) : () => {};
const disposeTabFill = root ? installTabFill(api, root) : () => {};
- // The dock spans the window (buildEditLayout sizes against it too); its own box lags a resize.
- const resizeObserver = new ResizeObserver(() => applySideMinimums(api, window.innerWidth));
+ // Sides size against dockWidth, the window by default; the dock's own box lags a resize.
+ const resizeObserver = new ResizeObserver(() => applySideMinimums(api, dockWidth()));
if (root) resizeObserver.observe(root);
const store = useDockLayoutStore.getState();
- store.attach(createController(api));
+ store.attach(createController(api, options), panels);
store.sync(snapshot(api));
const pending = store.takePendingActivation();
if (pending) api.getPanel(pending)?.api.setActive();
@@ -167,7 +193,7 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
const persist = () => {
clearTimeout(timer);
timer = setTimeout(() => {
- writeStudioUiPreferences({ dockLayout: api.toJSON() }, undefined, projectId);
+ writeStudioUiPreferences({ dockLayout: api.toJSON() }, undefined, projectId, storageKey);
}, PERSIST_DEBOUNCE_MS);
};
// dockview does not fire onDidLayoutChange for add/remove/activate,
@@ -178,11 +204,11 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
};
const subscriptions = [
api.onDidAddPanel(() => {
- applySideMinimums(api);
+ applySideMinimums(api, dockWidth());
onDockChange();
}),
api.onDidMovePanel(() => {
- applySideMinimums(api);
+ applySideMinimums(api, dockWidth());
onDockChange();
}),
api.onDidRemovePanel(onDockChange),
@@ -198,7 +224,7 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
useDockLayoutStore.getState().detach();
};
},
- [projectId],
+ [projectId, panels, storageKey, dockWidth],
);
return (
@@ -235,6 +261,7 @@ function Panel({ id, title, children }: { id: PanelId; title?: string; children:
function WindowMenu() {
const openPanels = useDockLayoutStore((state) => state.openPanels);
+ const panels = useDockLayoutStore((state) => state.panels);
const togglePanel = useDockLayoutStore((state) => state.togglePanel);
const resetLayout = useDockLayoutStore((state) => state.resetLayout);
const [open, setOpen] = useState(false);
@@ -265,7 +292,7 @@ function WindowMenu() {
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) => (
+ {panels.map((id) => (
<button
key={id}
type="button"
diff --git a/packages/studio/src/components/dock/dockLayout.ts b/packages/studio/src/components/dock/dockLayout.ts
index 6374d09f56..883b342563 100644
--- a/packages/studio/src/components/dock/dockLayout.ts
+++ b/packages/studio/src/components/dock/dockLayout.ts
@@ -1,6 +1,6 @@
import type { Direction, DockviewApi } from "dockview-react";
import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
-import { PANEL_DEFINITIONS, isPanelId, type PanelId } from "./panelRegistry";
+import { PANEL_DEFINITIONS, PANEL_IDS, isPanelId, type PanelId } from "./panelRegistry";
const MIN_PREVIEW_W = 360;
const MIN_PREVIEW_H = 200;
@@ -8,6 +8,8 @@ const MIN_TIMELINE_H = 100;
const MIN_SIDE_W = 200;
const MIN_SIDE_W_FLOOR = 120;
const DEFAULT_TIMELINE_H = 360;
+const DEFAULT_LEFT = ["compositions", "assets", "code", "catalog"] as const;
+const DEFAULT_RIGHT = ["design", "layers", "renders", "variables"] as const;
/** Preferred side widths; when they overflow the preview's floor the right yields first, then the left. */
export function defaultSideWidths(viewportWidth: number) {
@@ -82,24 +84,35 @@ export function addRegisteredPanel(
});
}
+function addSideColumn(
+ api: DockviewApi,
+ ids: readonly PanelId[],
+ panels: readonly PanelId[],
+ direction: "left" | "right",
+) {
+ const [first, ...rest] = ids.filter((id) => panels.includes(id));
+ if (!first) return undefined;
+ addRegisteredPanel(api, first, { referencePanel: "preview", direction });
+ for (const id of rest)
+ addRegisteredPanel(api, id, { referencePanel: first, direction: "within" });
+ api.getPanel(first)?.api.setActive();
+ return first;
+}
+
/** The default Edit layout: [library | preview | inspector] over a full-width timeline. */
-export function buildEditLayout(api: DockviewApi, viewportWidth: number) {
+export function buildEditLayout(
+ api: DockviewApi,
+ viewportWidth: number,
+ panels: readonly PanelId[] = PANEL_IDS,
+) {
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();
+ const left = addSideColumn(api, DEFAULT_LEFT, panels, "left");
+ const right = addSideColumn(api, DEFAULT_RIGHT, panels, "right");
applySideMinimums(api, viewportWidth);
- api.getPanel("compositions")?.group.api.setSize({ width: widths.left });
- api.getPanel("design")?.group.api.setSize({ width: widths.right });
+ if (left) api.getPanel(left)?.group.api.setSize({ width: widths.left });
+ if (right) api.getPanel(right)?.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
index f9db12baad..7bf6648406 100644
--- a/packages/studio/src/components/dock/dockLayoutSchema.ts
+++ b/packages/studio/src/components/dock/dockLayoutSchema.ts
@@ -1,5 +1,5 @@
import type { SerializedDockview } from "dockview-react";
-import { isPanelId } from "./panelRegistry";
+import { PANEL_IDS, isPanelId, type PanelId } from "./panelRegistry";
export const DOCK_PANEL_COMPONENT = "panel";
@@ -25,7 +25,10 @@ function hasGridShape(grid: Record<string, unknown>): boolean {
return oriented && typeof grid.width === "number" && typeof grid.height === "number";
}
-function panelsAreRegistered(panels: Record<string, unknown>): boolean {
+function panelsAreRegistered(
+ panels: Record<string, unknown>,
+ allowed: readonly PanelId[],
+): boolean {
const ids = Object.keys(panels);
return (
ids.length > 0 &&
@@ -33,6 +36,7 @@ function panelsAreRegistered(panels: Record<string, unknown>): boolean {
const state = panels[id];
return (
isPanelId(id) &&
+ allowed.includes(id) &&
isRecord(state) &&
state.id === id &&
state.contentComponent === DOCK_PANEL_COMPONENT
@@ -52,10 +56,13 @@ function collectFloatingViews(floating: unknown, into: unknown[]): boolean {
}
/** 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 {
+export function parseDockLayout(
+ value: unknown,
+ allowed: readonly PanelId[] = PANEL_IDS,
+): SerializedDockview | null {
if (!isRecord(value) || !isRecord(value.grid) || !isRecord(value.panels)) return null;
const { grid, panels } = value;
- if (!hasGridShape(grid) || !panelsAreRegistered(panels)) return null;
+ if (!hasGridShape(grid) || !panelsAreRegistered(panels, allowed)) return null;
const views: unknown[] = [];
if (!collectLeafViews(grid.root, views)) return null;
diff --git a/packages/studio/src/components/dock/dockLayoutStore.ts b/packages/studio/src/components/dock/dockLayoutStore.ts
index e5439f4437..3887734d09 100644
--- a/packages/studio/src/components/dock/dockLayoutStore.ts
+++ b/packages/studio/src/components/dock/dockLayoutStore.ts
@@ -33,10 +33,11 @@ type LastActive = Partial<Record<PanelZone, PanelId>>;
interface DockLayoutState extends DockSnapshot {
controller: DockController | null;
+ panels: readonly PanelId[];
lastActive: LastActive;
/** An activation requested before the dock mounted; Dock.Root applies it on ready. */
pendingActivation: PanelId | null;
- attach: (controller: DockController) => void;
+ attach: (controller: DockController, panels?: readonly PanelId[]) => void;
detach: () => void;
sync: (snapshot: DockSnapshot) => void;
takePendingActivation: () => PanelId | null;
@@ -49,12 +50,13 @@ interface DockLayoutState extends DockSnapshot {
export const useDockLayoutStore = create<DockLayoutState>((set, get) => ({
controller: null,
+ panels: PANEL_IDS,
openPanels: new Set(PANEL_IDS),
visiblePanels: new Set(PANEL_IDS),
activePanel: null,
lastActive: {},
pendingActivation: null,
- attach: (controller) => set({ controller }),
+ attach: (controller, panels = PANEL_IDS) => set({ controller, panels }),
detach: () => set({ controller: null, lastActive: {} }),
sync: (snapshot) =>
set((state) => {
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index b3955fd388..9a3434ce97 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -12,6 +12,10 @@ export type { ShortcutHint, ShortcutSection } from "./player/components/studioSh
export { CompositionBreadcrumb } from "./components/nle/CompositionBreadcrumb";
export type { CompositionLevel } from "./components/nle/CompositionBreadcrumb";
export { useCompositionStack } from "./components/nle/useCompositionStack";
+export { Dock } from "./components/dock/Dock";
+export { useDockLayoutStore } from "./components/dock/dockLayoutStore";
+export type { DockController } from "./components/dock/dockLayoutStore";
+export type { PanelId } from "./components/dock/panelRegistry";
// Player (preview, timeline, playback controls)
export {
diff --git a/packages/studio/src/utils/studioUiPreferences.ts b/packages/studio/src/utils/studioUiPreferences.ts
index 826760722f..44a49faf6c 100644
--- a/packages/studio/src/utils/studioUiPreferences.ts
+++ b/packages/studio/src/utils/studioUiPreferences.ts
@@ -60,8 +60,8 @@ function getBrowserStorage(): Storage | null {
}
}
-function storageKeyFor(projectId: string | null): string {
- return projectId ? `${STUDIO_UI_PREFERENCES_KEY}:${projectId}` : STUDIO_UI_PREFERENCES_KEY;
+function storageKeyFor(projectId: string | null, key: string): string {
+ return projectId ? `${key}:${projectId}` : key;
}
// fallow-ignore-next-line complexity
@@ -157,24 +157,26 @@ function readStorage(storage: Storage | null, key: string): StudioUiPreferences
export function readStudioUiPreferences(
storage: Storage | null = getBrowserStorage(),
projectId: string | null = null,
+ key: string = STUDIO_UI_PREFERENCES_KEY,
): StudioUiPreferences {
- const scoped = readStorage(storage, storageKeyFor(projectId));
+ const scoped = readStorage(storage, storageKeyFor(projectId, key));
if (!projectId || Object.keys(scoped).length > 0) return scoped;
- return readStorage(storage, STUDIO_UI_PREFERENCES_KEY);
+ return readStorage(storage, key);
}
export function writeStudioUiPreferences(
patch: StudioUiPreferences,
storage: Storage | null = getBrowserStorage(),
projectId: string | null = null,
+ key: string = STUDIO_UI_PREFERENCES_KEY,
) {
if (!storage) return;
try {
const next = {
- ...readStudioUiPreferences(storage, projectId),
+ ...readStudioUiPreferences(storage, projectId, key),
...patch,
};
- storage.setItem(storageKeyFor(projectId), JSON.stringify(next));
+ storage.setItem(storageKeyFor(projectId, key), JSON.stringify(next));
} catch {
/* localStorage may be unavailable or full */
}