Skip to content

Commit 7719f97

Browse files
feat(studio): a host app can mount the dock with its own panels, storage key and width (#4812)
* feat(studio): a host app can mount the dock with its own panels, storage key and width * refactor(studio): the dock keeps a host layout through Studio's own preference storage * fix(studio): a dock reopens a panel beside the preview only when its usual neighbour is not in the dock
1 parent e29433c commit 7719f97

7 files changed

Lines changed: 177 additions & 47 deletions

File tree

‎packages/studio/src/components/dock/Dock.test.tsx‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,30 @@ class ResizeObserverStub {
4848

4949
vi.mock("./dockLayout", async (importOriginal) => {
5050
const actual = await importOriginal<typeof import("./dockLayout")>();
51-
return { ...actual, applySideMinimums: vi.fn(actual.applySideMinimums) };
51+
return {
52+
...actual,
53+
applySideMinimums: vi.fn(actual.applySideMinimums),
54+
addRegisteredPanel: vi.fn(actual.addRegisteredPanel),
55+
};
5256
});
5357
const applySideMinimums = vi.mocked(dockLayout.applySideMinimums);
58+
const addRegisteredPanel = vi.mocked(dockLayout.addRegisteredPanel);
5459

5560
let root: Root | null = null;
5661

5762
function mount(
5863
projectId: string | null,
5964
titles: Partial<Record<(typeof PANEL_IDS)[number], string>> = {},
65+
options: Omit<ComponentProps<typeof Dock.Root>, "projectId" | "children"> = {},
6066
) {
6167
const host = document.createElement("div");
6268
document.body.append(host);
6369
root = createRoot(host);
6470
act(() => {
6571
root?.render(
66-
<Dock.Root projectId={projectId}>
67-
{PANEL_IDS.map((id) => (
72+
<Dock.Root projectId={projectId} {...options}>
73+
<Dock.WindowMenu />
74+
{(options.panels ?? PANEL_IDS).map((id) => (
6875
<Dock.Panel key={id} id={id} title={titles[id]}>
6976
<div data-testid={`content-${id}`}>{id}</div>
7077
</Dock.Panel>
@@ -173,6 +180,16 @@ describe("Dock on React 19", () => {
173180
expect(useDockLayoutStore.getState().visiblePanels.has("compositions")).toBe(true);
174181
});
175182

183+
it("reopens a panel whose usual neighbour is only closed exactly as before: no new position", () => {
184+
mount("p1");
185+
const { closePanel, togglePanel } = useDockLayoutStore.getState();
186+
for (const id of ["compositions", "assets", "code", "catalog"] as const)
187+
act(() => closePanel(id));
188+
addRegisteredPanel.mockClear();
189+
act(() => togglePanel("assets"));
190+
expect(addRegisteredPanel).toHaveBeenCalledWith(expect.anything(), "assets", undefined);
191+
});
192+
176193
it("reopens the timeline as its own group, never as a tab of the preview", () => {
177194
mount("p1");
178195
act(() => useDockLayoutStore.getState().closePanel("timeline"));
@@ -239,6 +256,64 @@ describe("Dock wiring", () => {
239256
});
240257
});
241258

259+
// A host app mounts a subset of Studio's panels under its own storage key and width.
260+
describe("a host's dock", () => {
261+
const panels = ["preview", "timeline", "assets", "renders"] as const;
262+
const hostDock = { panels, storageKey: "host-dock" };
263+
264+
it("builds only its panels, a side column each, and its Window menu lists only them", () => {
265+
const host = mount("p1", {}, hostDock);
266+
expect(useDockLayoutStore.getState().openPanels).toEqual(new Set(panels));
267+
expect(useDockLayoutStore.getState().visiblePanels).toEqual(new Set(panels));
268+
expect(dockApi?.getPanel("assets")?.group.id).not.toBe(dockApi?.getPanel("renders")?.group.id);
269+
const menu = [...host.querySelectorAll("button")].find((b) => b.textContent === "Window");
270+
act(() => menu?.click());
271+
const items = [...host.querySelectorAll('[role="menuitemcheckbox"]')].map((i) => i.textContent);
272+
expect(items).toEqual(["✓Preview", "✓Timeline", "✓Assets", "✓Renders"]);
273+
});
274+
275+
it("keeps its layout alone under its own key, never in Studio's preferences", () => {
276+
mount("p1", {}, hostDock);
277+
act(() => useDockLayoutStore.getState().closePanel("renders"));
278+
act(() => {
279+
vi.advanceTimersByTime(400);
280+
});
281+
const stored = readStudioUiPreferences(undefined, "p1", "host-dock").dockLayout;
282+
expect(Object.keys(stored?.panels ?? {}).sort()).toEqual(["assets", "preview", "timeline"]);
283+
expect(readStudioUiPreferences(undefined, "p1").dockLayout).toBeUndefined();
284+
});
285+
286+
it("falls back to its default when a stored layout names a panel it lacks", () => {
287+
mount("p1");
288+
act(() => {
289+
vi.advanceTimersByTime(400);
290+
});
291+
const studio = readStudioUiPreferences(undefined, "p1").dockLayout;
292+
act(() => root?.unmount());
293+
root = null;
294+
localStorage.setItem("host-dock:p1", JSON.stringify({ dockLayout: studio }));
295+
mount("p1", {}, hostDock);
296+
expect(useDockLayoutStore.getState().openPanels).toEqual(new Set(panels));
297+
});
298+
299+
it("reopens a panel beside the preview when the panel it reopens near is not in the dock", () => {
300+
mount("p1", {}, hostDock);
301+
act(() => useDockLayoutStore.getState().closePanel("assets"));
302+
act(() => useDockLayoutStore.getState().togglePanel("assets"));
303+
expect(useDockLayoutStore.getState().visiblePanels.has("assets")).toBe(true);
304+
});
305+
306+
it("sizes its sides against its own width, not the window's", () => {
307+
mount(null, {}, { ...hostDock, dockWidth: () => 700 });
308+
applySideMinimums.mockClear();
309+
const dockObservers = [...liveObservers].filter(({ target }) =>
310+
target?.classList.contains("hf-dock"),
311+
);
312+
act(() => dockObservers.forEach(({ callback }) => callback()));
313+
expect(applySideMinimums).toHaveBeenCalledWith(expect.anything(), 700);
314+
});
315+
});
316+
242317
describe("parseDockLayout", () => {
243318
it("rejects shapes that are not a dock layout", () => {
244319
expect(parseDockLayout(null)).toBeNull();

‎packages/studio/src/components/dock/Dock.tsx‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { DockStripActions } from "./DockStripActions";
2020
import { DockTab } from "./DockTab";
2121
import { installTabFill } from "./dockTabFill";
2222
import { addRegisteredPanel, applySideMinimums, buildEditLayout } from "./dockLayout";
23-
import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
23+
import { DOCK_PANEL_COMPONENT, parseDockLayout } from "./dockLayoutSchema";
2424
import { useDockLayoutStore, type DockController, type DockSnapshot } from "./dockLayoutStore";
2525
import {
2626
PANEL_DEFINITIONS,
@@ -85,10 +85,20 @@ function snapshot(api: DockviewApi): DockSnapshot {
8585
};
8686
}
8787

88-
function createController(api: DockviewApi): DockController {
88+
interface DockOptions {
89+
panels: readonly PanelId[];
90+
storageKey?: string | undefined;
91+
dockWidth: () => number;
92+
}
93+
94+
function createController(api: DockviewApi, options: DockOptions): DockController {
8995
const open = (id: PanelId) => {
9096
if (api.getPanel(id)) return;
91-
const { zone, reopen } = PANEL_DEFINITIONS[id];
97+
const { zone, reopen: preferred } = PANEL_DEFINITIONS[id];
98+
const reopen: PanelDefinition["reopen"] =
99+
zone === "center" || options.panels.includes(preferred.near)
100+
? preferred
101+
: { near: "preview", direction: zone };
92102
// Side columns are tab groups; preview and timeline are separate groups in the centre.
93103
const sibling =
94104
zone === "center"
@@ -114,12 +124,13 @@ function createController(api: DockviewApi): DockController {
114124
},
115125
setTitle: (id, title) => api.getPanel(id)?.api.setTitle(title),
116126
setGroupVisible: (id, visible) => api.getPanel(id)?.group.api.setVisible(visible),
117-
reset: () => buildEditLayout(api, window.innerWidth),
127+
reset: () => buildEditLayout(api, options.dockWidth(), options.panels),
118128
};
119129
}
120130

121-
function restoreOrBuild(api: DockviewApi, projectId: string | null) {
122-
const stored = readStudioUiPreferences(undefined, projectId).dockLayout;
131+
function restoreOrBuild(api: DockviewApi, projectId: string | null, options: DockOptions) {
132+
const { dockLayout } = readStudioUiPreferences(undefined, projectId, options.storageKey);
133+
const stored = parseDockLayout(dockLayout, options.panels);
123134
if (stored) {
124135
try {
125136
api.fromJSON(stored);
@@ -128,10 +139,24 @@ function restoreOrBuild(api: DockviewApi, projectId: string | null) {
128139
/* a layout the schema accepted but dockview cannot load: start over */
129140
}
130141
}
131-
buildEditLayout(api, window.innerWidth);
142+
buildEditLayout(api, options.dockWidth(), options.panels);
132143
}
133144

134-
function Root({ projectId, children }: { projectId: string | null; children: ReactNode }) {
145+
const windowWidth = () => window.innerWidth;
146+
147+
function Root({
148+
projectId,
149+
panels = PANEL_IDS,
150+
storageKey,
151+
dockWidth = windowWidth,
152+
children,
153+
}: {
154+
projectId: string | null;
155+
panels?: readonly PanelId[];
156+
storageKey?: string;
157+
dockWidth?: () => number;
158+
children: ReactNode;
159+
}) {
135160
const [slots, setSlots] = useState<Slots>({});
136161
const registerSlot = useCallback((id: PanelId, element: HTMLElement | null) => {
137162
setSlots((prev) => {
@@ -149,16 +174,17 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
149174
const onReady = useCallback(
150175
({ api }: DockviewReadyEvent) => {
151176
disposeRef.current();
152-
restoreOrBuild(api, projectId);
153-
applySideMinimums(api);
177+
const options = { panels, storageKey, dockWidth };
178+
restoreOrBuild(api, projectId, options);
179+
applySideMinimums(api, dockWidth());
154180
const root = api.groups[0]?.element.closest<HTMLElement>(".hf-dock");
155181
const disposeAccessibility = root ? installDockAccessibility(api, root) : () => {};
156182
const disposeTabFill = root ? installTabFill(api, root) : () => {};
157-
// The dock spans the window (buildEditLayout sizes against it too); its own box lags a resize.
158-
const resizeObserver = new ResizeObserver(() => applySideMinimums(api, window.innerWidth));
183+
// Sides size against dockWidth, the window by default; the dock's own box lags a resize.
184+
const resizeObserver = new ResizeObserver(() => applySideMinimums(api, dockWidth()));
159185
if (root) resizeObserver.observe(root);
160186
const store = useDockLayoutStore.getState();
161-
store.attach(createController(api));
187+
store.attach(createController(api, options), panels);
162188
store.sync(snapshot(api));
163189
const pending = store.takePendingActivation();
164190
if (pending) api.getPanel(pending)?.api.setActive();
@@ -167,7 +193,7 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
167193
const persist = () => {
168194
clearTimeout(timer);
169195
timer = setTimeout(() => {
170-
writeStudioUiPreferences({ dockLayout: api.toJSON() }, undefined, projectId);
196+
writeStudioUiPreferences({ dockLayout: api.toJSON() }, undefined, projectId, storageKey);
171197
}, PERSIST_DEBOUNCE_MS);
172198
};
173199
// dockview does not fire onDidLayoutChange for add/remove/activate,
@@ -178,11 +204,11 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
178204
};
179205
const subscriptions = [
180206
api.onDidAddPanel(() => {
181-
applySideMinimums(api);
207+
applySideMinimums(api, dockWidth());
182208
onDockChange();
183209
}),
184210
api.onDidMovePanel(() => {
185-
applySideMinimums(api);
211+
applySideMinimums(api, dockWidth());
186212
onDockChange();
187213
}),
188214
api.onDidRemovePanel(onDockChange),
@@ -198,7 +224,7 @@ function Root({ projectId, children }: { projectId: string | null; children: Rea
198224
useDockLayoutStore.getState().detach();
199225
};
200226
},
201-
[projectId],
227+
[projectId, panels, storageKey, dockWidth],
202228
);
203229

204230
return (
@@ -235,6 +261,7 @@ function Panel({ id, title, children }: { id: PanelId; title?: string; children:
235261

236262
function WindowMenu() {
237263
const openPanels = useDockLayoutStore((state) => state.openPanels);
264+
const panels = useDockLayoutStore((state) => state.panels);
238265
const togglePanel = useDockLayoutStore((state) => state.togglePanel);
239266
const resetLayout = useDockLayoutStore((state) => state.resetLayout);
240267
const [open, setOpen] = useState(false);
@@ -265,7 +292,7 @@ function WindowMenu() {
265292
role="menu"
266293
className="absolute right-0 top-8 z-50 w-44 rounded-md border border-neutral-800 bg-neutral-900 py-1 shadow-lg"
267294
>
268-
{PANEL_IDS.map((id) => (
295+
{panels.map((id) => (
269296
<button
270297
key={id}
271298
type="button"

‎packages/studio/src/components/dock/dockLayout.ts‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import type { Direction, DockviewApi } from "dockview-react";
22
import { DOCK_PANEL_COMPONENT } from "./dockLayoutSchema";
3-
import { PANEL_DEFINITIONS, isPanelId, type PanelId } from "./panelRegistry";
3+
import { PANEL_DEFINITIONS, PANEL_IDS, isPanelId, type PanelId } from "./panelRegistry";
44

55
const MIN_PREVIEW_W = 360;
66
const MIN_PREVIEW_H = 200;
77
const MIN_TIMELINE_H = 100;
88
const MIN_SIDE_W = 200;
99
const MIN_SIDE_W_FLOOR = 120;
1010
const DEFAULT_TIMELINE_H = 360;
11+
const DEFAULT_LEFT = ["compositions", "assets", "code", "catalog"] as const;
12+
const DEFAULT_RIGHT = ["design", "layers", "renders", "variables"] as const;
1113

1214
/** Preferred side widths; when they overflow the preview's floor the right yields first, then the left. */
1315
export function defaultSideWidths(viewportWidth: number) {
@@ -82,24 +84,35 @@ export function addRegisteredPanel(
8284
});
8385
}
8486

87+
function addSideColumn(
88+
api: DockviewApi,
89+
ids: readonly PanelId[],
90+
panels: readonly PanelId[],
91+
direction: "left" | "right",
92+
) {
93+
const [first, ...rest] = ids.filter((id) => panels.includes(id));
94+
if (!first) return undefined;
95+
addRegisteredPanel(api, first, { referencePanel: "preview", direction });
96+
for (const id of rest)
97+
addRegisteredPanel(api, id, { referencePanel: first, direction: "within" });
98+
api.getPanel(first)?.api.setActive();
99+
return first;
100+
}
101+
85102
/** The default Edit layout: [library | preview | inspector] over a full-width timeline. */
86-
export function buildEditLayout(api: DockviewApi, viewportWidth: number) {
103+
export function buildEditLayout(
104+
api: DockviewApi,
105+
viewportWidth: number,
106+
panels: readonly PanelId[] = PANEL_IDS,
107+
) {
87108
api.clear();
88109
const widths = defaultSideWidths(viewportWidth);
89110
addRegisteredPanel(api, "preview");
90111
addRegisteredPanel(api, "timeline", { referencePanel: "preview", direction: "below" });
91-
addRegisteredPanel(api, "compositions", { referencePanel: "preview", direction: "left" });
92-
for (const id of ["assets", "code", "catalog"] as const) {
93-
addRegisteredPanel(api, id, { referencePanel: "compositions", direction: "within" });
94-
}
95-
addRegisteredPanel(api, "design", { referencePanel: "preview", direction: "right" });
96-
for (const id of ["layers", "renders", "variables"] as const) {
97-
addRegisteredPanel(api, id, { referencePanel: "design", direction: "within" });
98-
}
99-
api.getPanel("compositions")?.api.setActive();
100-
api.getPanel("design")?.api.setActive();
112+
const left = addSideColumn(api, DEFAULT_LEFT, panels, "left");
113+
const right = addSideColumn(api, DEFAULT_RIGHT, panels, "right");
101114
applySideMinimums(api, viewportWidth);
102-
api.getPanel("compositions")?.group.api.setSize({ width: widths.left });
103-
api.getPanel("design")?.group.api.setSize({ width: widths.right });
115+
if (left) api.getPanel(left)?.group.api.setSize({ width: widths.left });
116+
if (right) api.getPanel(right)?.group.api.setSize({ width: widths.right });
104117
api.getPanel("timeline")?.group.api.setSize({ height: DEFAULT_TIMELINE_H });
105118
}

‎packages/studio/src/components/dock/dockLayoutSchema.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { SerializedDockview } from "dockview-react";
2-
import { isPanelId } from "./panelRegistry";
2+
import { PANEL_IDS, isPanelId, type PanelId } from "./panelRegistry";
33

44
export const DOCK_PANEL_COMPONENT = "panel";
55

@@ -25,14 +25,18 @@ function hasGridShape(grid: Record<string, unknown>): boolean {
2525
return oriented && typeof grid.width === "number" && typeof grid.height === "number";
2626
}
2727

28-
function panelsAreRegistered(panels: Record<string, unknown>): boolean {
28+
function panelsAreRegistered(
29+
panels: Record<string, unknown>,
30+
allowed: readonly PanelId[],
31+
): boolean {
2932
const ids = Object.keys(panels);
3033
return (
3134
ids.length > 0 &&
3235
ids.every((id) => {
3336
const state = panels[id];
3437
return (
3538
isPanelId(id) &&
39+
allowed.includes(id) &&
3640
isRecord(state) &&
3741
state.id === id &&
3842
state.contentComponent === DOCK_PANEL_COMPONENT
@@ -52,10 +56,13 @@ function collectFloatingViews(floating: unknown, into: unknown[]): boolean {
5256
}
5357

5458
/** Parses a stored layout at the trust boundary; null (stale or foreign shape) means use the default preset. */
55-
export function parseDockLayout(value: unknown): SerializedDockview | null {
59+
export function parseDockLayout(
60+
value: unknown,
61+
allowed: readonly PanelId[] = PANEL_IDS,
62+
): SerializedDockview | null {
5663
if (!isRecord(value) || !isRecord(value.grid) || !isRecord(value.panels)) return null;
5764
const { grid, panels } = value;
58-
if (!hasGridShape(grid) || !panelsAreRegistered(panels)) return null;
65+
if (!hasGridShape(grid) || !panelsAreRegistered(panels, allowed)) return null;
5966

6067
const views: unknown[] = [];
6168
if (!collectLeafViews(grid.root, views)) return null;

0 commit comments

Comments
 (0)