Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): all panels move onto the dockable, persisted layout (#4192)
Miguel Ángel98e8372a0aaa
diff --git a/.fallowrc.jsonc b/.fallowrc.jsoncindex 6c6ddea83a..51a2fb63b8 100644--- a/.fallowrc.jsonc+++ b/.fallowrc.jsonc@@ -226,7 +226,7 @@// collision.{ "file": "packages/cli/src/commands/*.ts", "exports": ["examples"] },// Options type for the render-queue hook's public startRender callback —- // consumed structurally by callers (StudioRightPanel), not by import.+ // consumed structurally by callers (StudioRightPanels), not by import.{"file": "packages/studio/src/components/renders/useRenderQueue.ts","exports": ["StartRenderOptions"],@@ -457,10 +457,6 @@// require intrusive middleware changes beyond this PR's scope."minLines": 6,"ignore": [- // FileTree.tsx / LeftSidebar.tsx: pre-existing 8-line structural clone- // (shared sidebar node shape); surfaced by the UX-sweep line shifts.- "packages/studio/src/components/editor/FileTree.tsx",- "packages/studio/src/components/sidebar/LeftSidebar.tsx",// AWS Lambda and GCP Cloud Run deliberately mirror the same distributed// rendering lifecycle while retaining provider-specific SDK, storage, and// retry semantics. The Plan v2 AWS adapter extends that existing symmetry;@@ -894,8 +890,7 @@"packages/studio/src/components/sidebar/AudioRow.tsx","packages/studio/src/components/sidebar/BlocksTab.tsx","packages/studio/src/components/sidebar/CompositionsTab.tsx",- "packages/studio/src/components/sidebar/LeftSidebar.tsx",- "packages/studio/src/components/StudioRightPanel.tsx",+ "packages/studio/src/components/StudioRightPanels.tsx","packages/studio/src/components/StudioToast.tsx","packages/studio/src/components/ui/Tooltip.tsx","packages/studio/src/components/ui/useDialogBehavior.ts",diff --git a/docs/studio/index.mdx b/docs/studio/index.mdxindex 20eb83f30b..b3dd2e905d 100644--- a/docs/studio/index.mdx+++ b/docs/studio/index.mdx@@ -32,8 +32,10 @@ npx hyperframes preview- **Preview** shows the built project. The live frame is in the middle, thetimeline is below, project tools are on the left, and the Inspector is on the- right.-- **Code**, **Comps**, **Assets**, and **Catalog** expose the project source,+ right. Drag any panel tab to move it, and use **Window** in the header to+ reopen a closed panel or reset the layout. Studio remembers your layout for+ each project.+- **Code**, **Compositions**, **Assets**, and **Catalog** expose the project source,compositions, media, and reusable visuals. **Design**, **Layers**,**Variables**, and **Renders** control the selected work.diff --git a/docs/studio/source.mdx b/docs/studio/source.mdxindex 6597ea38ca..3c031f25d8 100644--- a/docs/studio/source.mdx+++ b/docs/studio/source.mdx@@ -23,7 +23,7 @@ the surfaces without exporting or converting the project.## Make a focused source edit-1. Open **Code** in the left sidebar.+1. Open **Code** in the left panel column.2. Select the exact file in the project tree.3. Find the value responsible for the visible result.4. Make one focused change.@@ -68,7 +68,7 @@ must remain true.## Run Studio Lint-Choose **Lint** at the bottom of the left sidebar. Studio opens **HyperFrame+Choose **Lint** at the bottom of the left panel column. Studio opens **HyperFrameLint Results** with errors, warnings, file locations, and fix hints when theyare available.diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsxindex bdd6690d4b..9ba30cfc1c 100644--- a/packages/studio/src/App.tsx+++ b/packages/studio/src/App.tsx@@ -1,7 +1,7 @@import { useOwnPreviewIframe, usePreviewIframeStore } from "./player/store/previewIframeStore";import { buildProjectApiPath } from "./utils/projectRouting";import { useState, useCallback, useRef, useMemo, useLayoutEffect } from "react";-import type { LeftSidebarHandle, SidebarTab } from "./components/sidebar/LeftSidebar";+import { useDismissingTabSetter, useRightPanelIntent } from "./hooks/useRightPanelIntents";import { useRenderQueue } from "./components/renders/useRenderQueue";import { usePlayerStore } from "./player";import { StudioOverlays } from "./components/StudioOverlays";@@ -48,9 +48,9 @@ import type { DomEditSelection } from "./components/editor/domEditing";import { StudioHeader } from "./components/StudioHeader";import { useGestureCommit } from "./hooks/useGestureCommit";import { GestureTrailOverlay } from "./components/editor/GestureTrailOverlay";-import { StudioLeftSidebar } from "./components/StudioLeftSidebar";+import { StudioLeftPanels } from "./components/StudioLeftPanels";import { EditorShell } from "./components/EditorShell";-import { StudioRightPanel } from "./components/StudioRightPanel";+import { StudioRightPanels } from "./components/StudioRightPanels";import { TimelineToolbar } from "./components/TimelineToolbar";import { StudioPlaybackProvider, StudioShellProvider } from "./contexts/StudioContext";import { PanelLayoutProvider } from "./contexts/PanelLayoutContext";@@ -75,7 +75,6 @@ export function StudioApp() {const [previewDocumentVersion, refreshPreviewDocumentVersion] = usePreviewDocumentVersion();const [blockPreview, setBlockPreview] = useState<BlockPreviewInfo | null>(null);const previewIframeRef = useRef<HTMLIFrameElement | null>(null);- const leftSidebarRef = useRef<LeftSidebarHandle>(null);const captionEditMode = useCaptionStore((s) => s.isEditMode);const captionHasSelection = useCaptionStore((s) => s.selectedSegmentIds.size > 0);const captionSync = useCaptionSync(projectId);@@ -202,6 +201,13 @@ export function StudioApp() {setRightCollapsed: panelLayout.setRightCollapsed,setRightPanelTab: panelLayout.setRightPanelTab,});+ const dismissBlockParams = useCallback(() => setActiveBlockParams(null), [setActiveBlockParams]);+ const setRightPanelTab = useDismissingTabSetter(panelLayout.setRightPanelTab, dismissBlockParams);+ const layout = useMemo(+ () => ({ ...panelLayout, setRightPanelTab }),+ [panelLayout, setRightPanelTab],+ );+const clearDomSelectionRef = useRef<() => void>(() => {});const domEditSelectionBridgeRef = useRef<DomEditSelection | null>(null);type DomEditDelete = (s: DomEditSelection, o?: { expandGroup?: boolean }) => Promise<void>;@@ -234,7 +240,6 @@ export function StudioApp() {showToast,syncHistoryPreviewAfterApply: previewPersistence.syncHistoryPreviewAfterApply,waitForPendingDomEditSaves: previewPersistence.waitForPendingDomEditSaves,- leftSidebarRef,handleCopy,handlePaste,handleCut,@@ -248,10 +253,6 @@ export function StudioApp() {forceReloadSdkSession: sdkHandle.forceReload,onToggleRecording: () => handleToggleRecordingRef.current(),});- const sidebarTabRef = useRef({- select: (t: SidebarTab) => leftSidebarRef.current?.selectTab(t),- get: () => leftSidebarRef.current?.getTab() ?? "compositions",- });const domEditSession = useDomEditSession({projectId,activeCompPath,@@ -264,7 +265,7 @@ export function StudioApp() {setSelectedTimelineElementId,setTimelineSelectionSet,setRightCollapsed: panelLayout.setRightCollapsed,- setRightPanelTab: panelLayout.setRightPanelTab,+ setRightPanelTab,showToast,isRecordingRef: isGestureRecordingRef,refreshPreviewDocumentVersion,@@ -286,8 +287,6 @@ export function StudioApp() {reloadPreview,setRefreshKey,openSourceForSelection: fileManager.openSourceForSelection,- selectSidebarTab: sidebarTabRef.current.select,- getSidebarTab: sidebarTabRef.current.get,sdkSession: editFlowSdkSession,publishSdkSession: sdkHandle.publish,forceReloadSdkSession: sdkHandle.forceReload,@@ -367,20 +366,18 @@ export function StudioApp() {},[appHotkeys, resetConsoleErrors, refreshPreviewDocumentVersion],);- const {- designPanelActive,- inspectorPanelActive,- inspectorButtonActive,- shouldShowMotionPath,- shouldShowSelectedDomBounds,- } = useInspectorState(- panelLayout.rightPanelTab,- panelLayout.rightInspectorPanes,- panelLayout.effectiveRightCollapsed,- isPlaying,- domEditSession.domEditSelection,- gestureState === "recording",- );+ const rightPanel = useRightPanelIntent();+ const { inspectorPanelActive, shouldShowMotionPath, shouldShowSelectedDomBounds } =+ useInspectorState(+ rightPanel,+ isPlaying,+ domEditSession.domEditSelection,+ gestureState === "recording",+ );+ // The dock has no separate "railed by window width" state (it shrinks+ // panels, never auto-hides the group), so rightCollapsed is already the+ // value that decides whether the panel is actually showing.+ const inspectorButtonActive = !panelLayout.rightCollapsed && inspectorPanelActive;useStudioUrlState({projectId,activeCompPath,@@ -397,7 +394,7 @@ export function StudioApp() {applyMarqueeSelection: domEditSession.applyMarqueeSelection,buildDomSelectionFromTarget: domEditSession.buildDomSelectionFromTarget,applyDomSelection: domEditSession.applyDomSelection,- setRightPanelTab: panelLayout.setRightPanelTab,+ setRightPanelTab,initialState: initialUrlStateRef.current,});const studioCtxValue = buildStudioContextValue({@@ -437,7 +434,7 @@ export function StudioApp() {return (<StudioShellProvider value={studioCtxValue}><StudioPlaybackProvider value={studioCtxValue}>- <PanelLayoutProvider value={panelLayout}>+ <PanelLayoutProvider value={layout}><FileManagerProvider value={fileManager}><DomEditProvider value={domEditSession}><div@@ -468,26 +465,23 @@ export function StudioApp() {)}<ExternalFileConflictBanner coordinator={externalFileChanges} /><EditorShell- left={- <StudioLeftSidebar- leftSidebarRef={leftSidebarRef}- onSelectComposition={handleSelectComposition}- onAddBlock={handleAddBlock}- onPreviewBlock={setBlockPreview}- onLint={handleLint}- linting={linting}- lintFindingCount={lintModal?.length ?? findingsByFile.size}- lintFindingsByFile={findingsByFile}- lintHasError={hasLintError}- onAddAssetToTimeline={handleAddAssetAtPlayhead}- onAddCompositionToTimeline={handleAddCompositionAtPlayhead}- />- }- right={- panelLayout.effectiveRightCollapsed ? null : (- <StudioRightPanel- designPanelActive={designPanelActive}+ panels={+ <>+ <StudioLeftPanels+ onSelectComposition={handleSelectComposition}+ onAddBlock={handleAddBlock}+ onPreviewBlock={setBlockPreview}+ onLint={handleLint}+ linting={linting}+ lintFindingCount={lintModal?.length ?? findingsByFile.size}+ lintFindingsByFile={findingsByFile}+ lintHasError={hasLintError}+ onAddAssetToTimeline={handleAddAssetAtPlayhead}+ onAddCompositionToTimeline={handleAddCompositionAtPlayhead}+ />+ <StudioRightPanelsactiveBlockParams={activeBlockParams}+ onDismissBlockParams={dismissBlockParams}onCloseBlockParams={() => {setActiveBlockParams(null);panelLayout.setRightPanelTab("design");@@ -504,7 +498,7 @@ export function StudioApp() {onAutoGroupCarveSources={timelineEditing.handleAutoGroupCarveSources}onAddMediaOverlay={handleAddMediaOverlay}/>- )+ </>}timelineToolbar={timelineToolbar}renderClipContent={renderClipContent}diff --git a/packages/studio/src/components/EditorShell.selectionSync.test.tsx b/packages/studio/src/components/EditorShell.selectionSync.test.tsxindex 736c6ede69..5d818c8d95 100644--- a/packages/studio/src/components/EditorShell.selectionSync.test.tsx+++ b/packages/studio/src/components/EditorShell.selectionSync.test.tsx@@ -42,7 +42,6 @@ vi.mock("./nle/NLEContext", () => ({useNLEContext: () => ({compositionStack: [],updateCompositionStack: vi.fn(),- containerRef: { current: null },}),}));vi.mock("./nle/useTimelineEditCallbacks", () => ({@@ -53,7 +52,14 @@ vi.mock("./nle/PreviewOverlays", () => ({ PreviewOverlays: () => null }));vi.mock("./nle/TimelinePane", () => ({ TimelinePane: () => null }));vi.mock("../captions/components/CaptionTimeline", () => ({ CaptionTimeline: () => null }));-Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+Object.assign(globalThis, {+ IS_REACT_ACT_ENVIRONMENT: true,+ ResizeObserver: class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+});afterEach(() => {document.body.innerHTML = "";@@ -69,8 +75,7 @@ describe("EditorShell timeline selection sync", () => {act(() => {root.render(<EditorShell- left={null}- right={null}+ panels={null}timelineToolbar={null}renderClipContent={() => null}handleTimelineElementDelete={vi.fn()}diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsxindex b6ab689f28..ad0324dafd 100644--- a/packages/studio/src/components/EditorShell.tsx+++ b/packages/studio/src/components/EditorShell.tsx@@ -17,6 +17,7 @@ import type { GestureRecordingState } from "./editor/GestureRecordControl";import { useTimelineSelectionPreviewSync } from "../hooks/useTimelineSelectionPreviewSync";import { StudioAgentTools } from "../webmcp/StudioAgentTools";import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";+import { Dock } from "./dock/Dock";type RenderClipContent = (element: TimelineElement,@@ -26,10 +27,8 @@ type RenderClipContent = (// The seven move/resize/split/razor handlers come from TimelineEditCallbackDeps// (shared with useTimelineEditCallbacks); the rest are drop + wiring props.export interface EditorShellProps extends TimelineEditCallbackDeps {- /** Left sidebar (media/library), rendered in the top row. */- left: ReactNode;- /** Right panel (inspector/design) or null when collapsed, in the top row. */- right: ReactNode;+ /** Dock.Panel elements for every panel except the built-in preview and timeline. */+ panels: ReactNode;timelineToolbar: ReactNode;renderClipContent: RenderClipContent;handleTimelineElementDelete: (element: TimelineElement) => Promise<void> | void;@@ -72,12 +71,11 @@ export interface EditorShellProps extends TimelineEditCallbackDeps {gestureOverlay?: ReactNode;}-// The CapCut-style shell: [left | preview | right] in a top row, with a-// full-width timeline spanning the bottom. Owns the shared player +-// composition-stack state via NLEProvider so both rows share one player.+// The dockable shell: every panel lives in one Dock, arranged by the user's+// saved layout. Owns the shared player + composition-stack state via+// NLEProvider so every panel shares one player.export function EditorShell({- left,- right,+ panels,timelineToolbar,renderClipContent,handleTimelineElementDelete,@@ -178,8 +176,8 @@ export function EditorShell({}}><EditorShellBody- left={left}- right={right}+ projectId={projectId}+ panels={panels}captionEditMode={captionEditMode}onSelectTimelineElement={handleTimelineElementSelect}onPreviewBlockDrop={handlePreviewBlockDrop}@@ -213,8 +211,8 @@ export function EditorShell({}interface EditorShellBodyProps {- left: ReactNode;- right: ReactNode;+ panels: ReactNode;+ projectId: string;captionEditMode: boolean;previewOverlay: ReactNode;onSelectTimelineElement: (element: TimelineElement | null) => void;@@ -239,8 +237,8 @@ interface EditorShellBodyProps {}function EditorShellBody({- left,- right,+ panels,+ projectId,captionEditMode,previewOverlay,onSelectTimelineElement,@@ -257,7 +255,7 @@ function EditorShellBody({onDuplicateClip,canPasteClip,}: EditorShellBodyProps) {- const { compositionStack, updateCompositionStack, containerRef } = useNLEContext();+ const { compositionStack, updateCompositionStack } = useNLEContext();// The caption track's blocks are seek targets; CaptionTimeline took an onSeek// prop that nothing ever passed, so clicking a block did nothing.@@ -277,7 +275,6 @@ function EditorShellBody({return (<div- ref={containerRef}// Shell canvas is a step LIGHTER than the near-black panel cards so the// gaps between panels read as visible seams (CapCut-style).className="flex flex-col flex-1 min-h-0 bg-panel-surface"@@ -287,47 +284,46 @@ function EditorShellBody({{/* Renders nothing; exposes Studio's state to an agentic browser. Mountedhere rather than in App because it needs the DomEdit contexts. */}<StudioAgentTools />- {/* Top row: [left | preview | right] — outer padding + the 8px resize- seams give the panels CapCut-style separation on the dark canvas. */}- <div className="flex flex-row flex-1 min-h-0 px-px pt-px">- {left}- <div className="flex-1 min-w-0 flex flex-col relative">- <PreviewPane- previewOverlay={previewOverlay}+ <Dock.Root projectId={projectId}>+ <Dock.Panel id="preview">+ <div className="relative flex h-full w-full min-w-0 flex-col">+ <PreviewPane+ previewOverlay={previewOverlay}+ onSelectTimelineElement={onSelectTimelineElement}+ onPreviewBlockDrop={onPreviewBlockDrop}+ />+ </div>+ </Dock.Panel>+ <Dock.Panel id="timeline">+ <TimelinePane+ timelineToolbar={timelineToolbar}+ renderClipContent={renderClipContent}+ onFileDrop={onFileDrop}+ onAssetDrop={onAssetDrop}+ onBlockDrop={onBlockDrop}+ onCompositionDrop={onCompositionDrop}+ onDeleteElement={onDeleteElement}+ onCopyClip={onCopyClip}+ onPasteClip={onPasteClip}+ onDuplicateClip={onDuplicateClip}+ canPasteClip={canPasteClip}onSelectTimelineElement={onSelectTimelineElement}- onPreviewBlockDrop={onPreviewBlockDrop}+ timelineFooter={+ captionEditMode ? (+ <div className="border-t border-neutral-800/30 shrink-0" style={{ height: 60 }}>+ <div className="flex items-center gap-1.5 px-2 py-0.5">+ <span className="text-[9px] font-medium text-neutral-500 uppercase tracking-wider">+ Captions+ </span>+ </div>+ <CaptionTimeline pixelsPerSecond={100} onSeek={seekCaptionTime} />+ </div>+ ) : undefined+ }/>- </div>- {right}- </div>-- {/* Full-width timeline row */}- <TimelinePane- timelineToolbar={timelineToolbar}- renderClipContent={renderClipContent}- onFileDrop={onFileDrop}- onAssetDrop={onAssetDrop}- onBlockDrop={onBlockDrop}- onCompositionDrop={onCompositionDrop}- onDeleteElement={onDeleteElement}- onCopyClip={onCopyClip}- onPasteClip={onPasteClip}- onDuplicateClip={onDuplicateClip}- canPasteClip={canPasteClip}- onSelectTimelineElement={onSelectTimelineElement}- timelineFooter={- captionEditMode ? (- <div className="border-t border-neutral-800/30 shrink-0" style={{ height: 60 }}>- <div className="flex items-center gap-1.5 px-2 py-0.5">- <span className="text-[9px] font-medium text-neutral-500 uppercase tracking-wider">- Captions- </span>- </div>- <CaptionTimeline pixelsPerSecond={100} onSeek={seekCaptionTime} />- </div>- ) : undefined- }- />+ </Dock.Panel>+ {panels}+ </Dock.Root></div>);}diff --git a/packages/studio/src/components/StudioHeader.dom.test.tsx b/packages/studio/src/components/StudioHeader.dom.test.tsxindex b6d79f1939..45b926e910 100644--- a/packages/studio/src/components/StudioHeader.dom.test.tsx+++ b/packages/studio/src/components/StudioHeader.dom.test.tsx@@ -33,7 +33,7 @@ vi.mock("../contexts/StudioContext", () => ({vi.mock("../contexts/PanelLayoutContext", () => ({usePanelLayoutContext: () => ({- effectiveRightCollapsed: false,+ rightCollapsed: false,setRightCollapsed: vi.fn(),setRightPanelTab: vi.fn(),}),diff --git a/packages/studio/src/components/StudioHeader.test.ts b/packages/studio/src/components/StudioHeader.test.tsindex 4d897faa76..a68273c6e1 100644--- a/packages/studio/src/components/StudioHeader.test.ts+++ b/packages/studio/src/components/StudioHeader.test.ts@@ -13,16 +13,4 @@ describe("shouldOpenInspector", () => {it("closes when the inspector is genuinely on screen", () => {expect(shouldOpenInspector(false, true)).toBe(false);});-- it("opens when the window railed the panel away", () => {- // The regression this guards: the button used to branch on the raw- // rightCollapsed intent, which is still `false` while the window has the- // panel railed. That took the close branch, wrote rightCollapsed=true, and- // since that value is synced into the shareable Studio URL, a click that- // did nothing visible rewrote the link.- const userIntentIsOpen = false;- const windowRailedItAway = true;- expect(shouldOpenInspector(windowRailedItAway, true)).toBe(true);- expect(shouldOpenInspector(userIntentIsOpen, true)).toBe(false);- });});diff --git a/packages/studio/src/components/StudioHeader.tsx b/packages/studio/src/components/StudioHeader.tsxindex 7210df3845..7b88371373 100644--- a/packages/studio/src/components/StudioHeader.tsx+++ b/packages/studio/src/components/StudioHeader.tsx@@ -4,6 +4,7 @@ import { useStudioShellContext } from "../contexts/StudioContext";import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";import { trackStudioEvent } from "../utils/studioTelemetry";import { Button, buttonBase, buttonSizes, buttonVariants, cn, Tooltip } from "./ui";+import { Dock } from "./dock/Dock";export interface StudioHeaderProps {captureFrameHref: string;@@ -140,16 +141,15 @@ function HyperframesLogo() {/*** Does the header's Inspector button open the panel, or close it?*- * Takes the EFFECTIVE collapse state, so a panel the window has railed away- * counts as closed even though the user's stored intent still says open. The- * argument name is the guard: passing raw intent here is the bug this exists- * to keep out.+ * The dock has no separate "railed by window width" state (it shrinks panels,+ * never auto-hides the group), so `rightCollapsed` here is already the state+ * that decides whether the panel is actually showing.*/export function shouldOpenInspector(- effectiveRightCollapsed: boolean,+ rightCollapsed: boolean,inspectorPanelActive: boolean,): boolean {- return effectiveRightCollapsed || !inspectorPanelActive;+ return rightCollapsed || !inspectorPanelActive;}// fallow-ignore-next-line complexity@@ -164,11 +164,7 @@ export function StudioHeader({onExport,}: StudioHeaderProps) {const { projectId, renderQueue } = useStudioShellContext();- // effectiveRightCollapsed, not the raw intent: in the auto-railed state the- // intent is still "open" while the panel is hidden, so branching on intent- // made this button write rightCollapsed=true — and that value is synced into- // the shareable Studio URL, so a dead click would rewrite a link.- const { effectiveRightCollapsed, setRightCollapsed, setRightPanelTab } = usePanelLayoutContext();+ const { rightCollapsed, setRightCollapsed, setRightPanelTab } = usePanelLayoutContext();const isRendering = renderQueue.isRendering;const ffmpegMissing = renderQueue.ffmpegMissing;@@ -265,7 +261,7 @@ export function StudioHeader({</svg>}onClick={() => {- if (shouldOpenInspector(effectiveRightCollapsed, inspectorPanelActive)) {+ if (shouldOpenInspector(rightCollapsed, inspectorPanelActive)) {trackStudioEvent("panel_toggle", { panel: "inspector", collapsed: false });setRightPanelTab("design");setRightCollapsed(false);@@ -281,6 +277,7 @@ export function StudioHeader({</Button></Tooltip></div>+ <Dock.WindowMenu /><Tooltiplabel={ffmpegMissingdiff --git a/packages/studio/src/components/StudioLeftPanels.tsx b/packages/studio/src/components/StudioLeftPanels.tsxnew file mode 100644index 0000000000..96d80b356a--- /dev/null+++ b/packages/studio/src/components/StudioLeftPanels.tsx@@ -0,0 +1,202 @@+import { useCallback, type ReactNode } from "react";+import { SourceEditor } from "./editor/SourceEditor";+import { FileTree } from "./editor/FileTree";+import { MediaPreview } from "./MediaPreview";+import { AssetsTab } from "./sidebar/AssetsTab";+import { BlocksTab, type BlockPreviewInfo } from "./sidebar/BlocksTab";+import { CompositionsPanel } from "./sidebar/CompositionsPanel";+import { SidebarLintButton } from "./sidebar/SidebarLintButton";+import { Dock } from "./dock/Dock";+import { useDockLayoutStore } from "./dock/dockLayoutStore";+import { isMediaFile } from "../utils/mediaTypes";+import { useStudioShellContext } from "../contexts/StudioContext";+import { useFileManagerContext } from "../contexts/FileManagerContext";+import { getPersistedRenderSettings } from "./renders/renderSettings";++interface StudioLeftPanelsProps {+ onSelectComposition: (comp: string) => void;+ onAddBlock: (blockName: string) => void;+ onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;+ onLint: () => void;+ linting: boolean;+ lintFindingCount?: number;+ lintHasError?: boolean;+ lintFindingsByFile?: Map<string, { count: number; messages: string[] }>;+ onAddAssetToTimeline?: (path: string) => void;+ onAddCompositionToTimeline?: (path: string) => void;+}++function PanelColumn({ footer, children }: { footer: ReactNode; children: ReactNode }) {+ return (+ <div className="flex h-full min-h-0 flex-col overflow-hidden bg-neutral-950">+ <div className="flex min-h-0 flex-1 flex-col">{children}</div>+ {footer}+ </div>+ );+}++// fallow-ignore-next-line complexity+export function StudioLeftPanels({+ onSelectComposition,+ onAddBlock,+ onPreviewBlock,+ onLint,+ linting,+ lintFindingCount,+ lintHasError,+ lintFindingsByFile,+ onAddAssetToTimeline,+ onAddCompositionToTimeline,+}: StudioLeftPanelsProps) {+ const { projectId, renderQueue, waitForPendingDomEditSaves } = useStudioShellContext();+ const {+ compositions,+ assets,+ editingFile,+ fileTree,+ revealSourceOffset,+ handleFileSelect,+ handleCreateFile,+ handleCreateFolder,+ handleDeleteFile,+ handleRenameFile,+ handleDuplicateFile,+ handleMoveFile,+ handleImportFiles,+ handleContentChange,+ } = useFileManagerContext();++ const handleRenderComposition = useCallback(+ async (comp: string) => {+ // startRender refuses without an encoder and reports why as a row in the+ // Renders panel, which may be closed or behind another tab: bring it up.+ if (renderQueue.ffmpegMissing) {+ useDockLayoutStore.getState().activatePanel("renders");+ return;+ }+ await waitForPendingDomEditSaves();+ const { format, quality, fps } = getPersistedRenderSettings();+ await renderQueue.startRender({ composition: comp, format, quality, fps });+ },+ [renderQueue, waitForPendingDomEditSaves],+ );++ const importFiles = async (files: FileList, dir?: string) => {+ await handleImportFiles(files, dir);+ };+ const lintButton = (+ <SidebarLintButton+ onLint={onLint}+ linting={linting}+ findingCount={lintFindingCount}+ hasError={lintHasError}+ />+ );++ return (+ <>+ <Dock.Panel id="compositions">+ <PanelColumn footer={lintButton}>+ <CompositionsPanel+ projectId={projectId}+ compositions={compositions}+ activeComposition={editingFile?.path ?? null}+ onSelect={onSelectComposition}+ onAddToTimeline={onAddCompositionToTimeline}+ onRenderComposition={handleRenderComposition}+ isRendering={renderQueue.isRendering}+ lintFindingsByFile={lintFindingsByFile}+ />+ </PanelColumn>+ </Dock.Panel>+ <Dock.Panel id="assets">+ <PanelColumn footer={lintButton}>+ <AssetsTab+ projectId={projectId}+ assets={assets}+ onImport={importFiles}+ onDelete={handleDeleteFile}+ onRename={handleRenameFile}+ onAddAssetToTimeline={onAddAssetToTimeline}+ />+ </PanelColumn>+ </Dock.Panel>+ <Dock.Panel id="code">+ <PanelColumn footer={lintButton}>+ <div className="flex min-h-0 flex-1">+ {fileTree.length > 0 && (+ <div className="w-[160px] shrink-0 border-r border-neutral-800 overflow-y-auto">+ <FileTree+ files={fileTree}+ activeFile={editingFile?.path ?? null}+ onSelectFile={handleFileSelect}+ onCreateFile={handleCreateFile}+ onCreateFolder={handleCreateFolder}+ onDeleteFile={handleDeleteFile}+ onRenameFile={handleRenameFile}+ onDuplicateFile={handleDuplicateFile}+ onMoveFile={handleMoveFile}+ onImportFiles={importFiles}+ lintFindingsByFile={lintFindingsByFile}+ />+ </div>+ )}+ <div className="flex-1 overflow-hidden min-w-0">+ <CodeBody+ projectId={projectId}+ editingFile={editingFile}+ revealOffset={revealSourceOffset}+ onChange={handleContentChange}+ />+ </div>+ </div>+ </PanelColumn>+ </Dock.Panel>+ <Dock.Panel id="catalog">+ <PanelColumn footer={lintButton}>+ <BlocksTab onAddBlock={onAddBlock} onPreviewBlock={onPreviewBlock} />+ </PanelColumn>+ </Dock.Panel>+ </>+ );+}++function CodeBody({+ projectId,+ editingFile,+ revealOffset,+ onChange,+}: {+ projectId: string;+ editingFile: { path: string; content: string | null } | null;+ revealOffset: React.ComponentProps<typeof SourceEditor>["revealOffset"];+ onChange: (content: string) => void;+}) {+ if (!editingFile) {+ return (+ <div className="flex items-center justify-center h-full text-neutral-600 text-sm">+ Select a file to edit+ </div>+ );+ }+ if (isMediaFile(editingFile.path)) {+ return <MediaPreview projectId={projectId} filePath={editingFile.path} />;+ }+ // Never mount the editor on unloaded content: a keystroke would autosave an+ // empty document over the real file.+ if (editingFile.content == null) {+ return (+ <div className="flex h-full items-center justify-center text-[11px] text-neutral-600">+ Loading {editingFile.path}…+ </div>+ );+ }+ return (+ <SourceEditor+ content={editingFile.content}+ filePath={editingFile.path}+ onChange={onChange}+ revealOffset={revealOffset}+ />+ );+}diff --git a/packages/studio/src/components/StudioLeftSidebar.tsx b/packages/studio/src/components/StudioLeftSidebar.tsxdeleted file mode 100644index 26fc82fe94..0000000000--- a/packages/studio/src/components/StudioLeftSidebar.tsx+++ /dev/null@@ -1,207 +0,0 @@-import { useCallback, type RefObject } from "react";-import { SourceEditor } from "./editor/SourceEditor";-import { LeftSidebar, type LeftSidebarHandle } from "./sidebar/LeftSidebar";-import { MediaPreview } from "./MediaPreview";-import { isMediaFile } from "../utils/mediaTypes";-import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";-import { useStudioShellContext } from "../contexts/StudioContext";-import { useFileManagerContext } from "../contexts/FileManagerContext";-import { getPersistedRenderSettings } from "./renders/renderSettings";-import type { BlockPreviewInfo } from "./sidebar/BlocksTab";--export interface StudioLeftSidebarProps {- leftSidebarRef: RefObject<LeftSidebarHandle | null>;- onSelectComposition: (comp: string) => void;- onAddBlock: (blockName: string) => void;- onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;- onLint: () => void;- linting: boolean;- lintFindingCount?: number;- lintHasError?: boolean;- lintFindingsByFile?: Map<string, { count: number; messages: string[] }>;- onAddAssetToTimeline?: (path: string) => void;- onAddCompositionToTimeline?: (path: string) => void;-}--// fallow-ignore-next-line complexity-export function StudioLeftSidebar({- leftSidebarRef,- onSelectComposition,- onAddBlock,- onPreviewBlock,- onLint,- linting,- lintFindingCount,- lintHasError,- lintFindingsByFile,- onAddAssetToTimeline,- onAddCompositionToTimeline,-}: StudioLeftSidebarProps) {- const {- effectiveLeftCollapsed,- leftWidth,- adjustPanelWidth,- toggleLeftSidebar,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- setRightPanelTab,- setRightCollapsed,- } = usePanelLayoutContext();- const { projectId, renderQueue, waitForPendingDomEditSaves } = useStudioShellContext();- const {- compositions,- assets,- editingFile,- fileTree,- revealSourceOffset,- handleFileSelect,- handleCreateFile,- handleCreateFolder,- handleDeleteFile,- handleRenameFile,- handleDuplicateFile,- handleMoveFile,- handleImportFiles,- handleContentChange,- } = useFileManagerContext();-- const handleRenderComposition = useCallback(- async (comp: string) => {- // startRender refuses without an encoder, so nothing unfinishable gets- // queued either way. What it cannot do from here is show the reason:- // its refusal lands as a row in the Renders panel, which may be- // collapsed or on another tab, so the click would look like nothing- // happened. Same move the header makes: put the prompt in front of the- // user, then stop.- if (renderQueue.ffmpegMissing) {- setRightPanelTab("renders");- setRightCollapsed(false);- return;- }- await waitForPendingDomEditSaves();- const { format, quality, fps } = getPersistedRenderSettings();- await renderQueue.startRender({ composition: comp, format, quality, fps });- },- [renderQueue, waitForPendingDomEditSaves, setRightPanelTab, setRightCollapsed],- );-- if (effectiveLeftCollapsed) {- return (- <div className="mr-0.5 flex w-10 shrink-0 flex-col items-center rounded-lg border border-neutral-800/50 bg-neutral-950 pt-1">- <button- type="button"- onClick={toggleLeftSidebar}- className="flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-neutral-500 transition-colors hover:border-neutral-800 hover:bg-neutral-900 hover:text-neutral-300"- title="Show sidebar"- aria-label="Show sidebar"- >- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true"- >- <path d="M5 4v16" />- <path d="m10 7 5 5-5 5" />- </svg>- </button>- </div>- );- }-- return (- <>- <LeftSidebar- ref={leftSidebarRef}- width={leftWidth}- projectId={projectId}- compositions={compositions}- assets={assets}- activeComposition={editingFile?.path ?? null}- onSelectComposition={onSelectComposition}- fileTree={fileTree}- editingFile={editingFile}- onSelectFile={handleFileSelect}- onCreateFile={handleCreateFile}- onCreateFolder={handleCreateFolder}- onDeleteFile={handleDeleteFile}- onRenameFile={handleRenameFile}- onDuplicateFile={handleDuplicateFile}- onMoveFile={handleMoveFile}- onImportFiles={async (files, dir) => {- await handleImportFiles(files, dir);- }}- codeChildren={- editingFile ? (- isMediaFile(editingFile.path) ? (- <MediaPreview projectId={projectId} filePath={editingFile.path} />- ) : editingFile.content == null ? (- // Never mount the editor on unloaded content: a keystroke would- // autosave an empty document over the real file.- <div className="flex h-full items-center justify-center text-[11px] text-neutral-600">- Loading {editingFile.path}…- </div>- ) : (- <SourceEditor- content={editingFile.content}- filePath={editingFile.path}- onChange={handleContentChange}- revealOffset={revealSourceOffset}- />- )- ) : undefined- }- onRenderComposition={handleRenderComposition}- isRendering={renderQueue.isRendering}- onLint={onLint}- linting={linting}- lintFindingCount={lintFindingCount}- lintHasError={lintHasError}- lintFindingsByFile={lintFindingsByFile}- onToggleCollapse={toggleLeftSidebar}- onAddBlock={onAddBlock}- onPreviewBlock={onPreviewBlock}- onAddAssetToTimeline={onAddAssetToTimeline}- onAddCompositionToTimeline={onAddCompositionToTimeline}- />- {/* Vertical resize divider: 3px visible seam, 13px pointer-capture zone via- the absolutely-positioned inner hit area. The outer element is w-[3px] so- it contributes only 3px of gap in the flex row; the inner left-[-2px]- element widens the hit area without affecting layout. */}- <div- role="separator"- aria-label="Resize sidebar"- aria-orientation="vertical"- tabIndex={0}- className="group relative w-[3px] shrink-0 cursor-col-resize outline-hidden focus-visible:bg-studio-accent/20"- style={{ touchAction: "none" }}- onPointerDown={(e) => handlePanelResizeStart("left", e)}- onPointerMove={handlePanelResizeMove}- onPointerUp={handlePanelResizeEnd}- onPointerCancel={handlePanelResizeEnd}- onKeyDown={(e) => {- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;- e.preventDefault();- const delta = e.key === "ArrowLeft" ? -16 : 16;- adjustPanelWidth("left", delta);- }}- >- {/* Expanded hit zone, deliberately asymmetric: 2px into the sidebar card,- the 3px seam, then 8px into the preview pane's p-2 stage gutter — the- only dead space adjacent to this seam. It stops at 13px rather than the- 24px WCAG 2.2 (2.5.8) target because the next pixel on either side is- live: the sidebar's scrolling tab content on the left, the preview- stage on the right. Silently stealing their clicks is the worse bug. */}- <div className="absolute inset-y-0 left-[-2px] w-[13px]" />- {/* Visible hairline */}- <div className="absolute top-1/2 left-0 h-[52px] w-[3px] -translate-y-1/2 bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />- </div>- </>- );-}diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanels.tsxsimilarity index 54%rename from packages/studio/src/components/StudioRightPanel.tsxrename to packages/studio/src/components/StudioRightPanels.tsxindex 75c1cb5dad..16b574f792 100644--- a/packages/studio/src/components/StudioRightPanel.tsx+++ b/packages/studio/src/components/StudioRightPanels.tsx@@ -1,7 +1,6 @@import { useCallback } from "react";-import type { StudioRightPanelProps } from "./StudioRightPanel.types";+import type { StudioRightPanelsProps } from "./StudioRightPanels.types";-export type { StudioRightPanelProps };import { PropertyPanel } from "./editor/PropertyPanel";import { LayersPanel } from "./editor/LayersPanel";import { CaptionPropertyPanel } from "../captions/components/CaptionPropertyPanel";@@ -9,14 +8,18 @@ import { BlockParamsPanel } from "./editor/BlockParamsPanel";import { RenderQueuePanel } from "./renders/RenderQueuePanel";import { SlideshowPanel } from "./panels/SlideshowPanel";import { VariablesPanel } from "./panels/VariablesPanel";-import { RightPanelTabs, type RightPanelTabDescriptor } from "./RightPanelTabs";+import { Dock } from "./dock/Dock";+import { useDockLayoutStore } from "./dock/dockLayoutStore";import type { RenderJob } from "./renders/useRenderQueue";-import { STUDIO_FLAT_INSPECTOR_ENABLED } from "./editor/manualEditingAvailability";import { useSlideshowPersist } from "../hooks/useSlideshowPersist";import { useSlideshowTabState } from "../hooks/useSlideshowTabState";+import {+ useBlockParamsDismissal,+ useCaptionDesignFocus,+ useSlideshowDockPanel,+} from "../hooks/useRightPanelIntents";import { DesignPanelPromoteProvider } from "./DesignPanelPromoteProvider";import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";-import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";import { useFileManagerContext } from "../contexts/FileManagerContext";import { useDomEditContext } from "../contexts/DomEditContext";import { usePlayerStore } from "../player";@@ -27,14 +30,13 @@ import {} from "./studioColorGradingScope";import { timelineKeysForSelections } from "../utils/studioHelpers";import { canHideSelections } from "../utils/timelineInspector";-import { useInspectorSplitResize } from "../hooks/useInspectorSplitResize";import { useRemoveBackground } from "../hooks/useRemoveBackground";// fallow-ignore-next-line complexity-export function StudioRightPanel({- designPanelActive,+export function StudioRightPanels({activeBlockParams,onCloseBlockParams,+ onDismissBlockParams,recordingState,recordingDuration,onToggleRecording,@@ -46,20 +48,7 @@ export function StudioRightPanel({onToggleElementHidden,onAutoGroupCarveSources,onAddMediaOverlay,-}: StudioRightPanelProps) {- const {- rightWidth,- adjustPanelWidth,- rightPanelTab,- setRightPanelTab,- rightInspectorPanes,- toggleRightInspectorPane,- setExclusiveRightInspectorPane,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- } = usePanelLayoutContext();-+}: StudioRightPanelsProps) {const {previewIframeRef,projectId,@@ -154,41 +143,20 @@ export function StudioRightPanel({coalesceKey: activeCompPath ? `slideshow-notes:${activeCompPath}` : "slideshow-notes",});- const {- layersPanePercent,- splitContainerRef,- handleInspectorSplitResizeStart,- handleInspectorSplitResizeMove,- handleInspectorSplitResizeEnd,- } = useInspectorSplitResize();-const renderJobs = renderQueue.jobs as RenderJob[];- const inspectorTabActive = rightPanelTab === "design" || rightPanelTab === "layers";-+ const slideshowVisible = useDockLayoutStore((state) => state.visiblePanels.has("slideshow"));const { isSlideshowComposition, slideshowScenes } = useSlideshowTabState({editingFileContent: editingFile?.content,previewIframeRef,refreshKey,- rightPanelTab,- setRightPanelTab,+ slideshowVisible,});- const designPaneOpen = inspectorTabActive && rightInspectorPanes.design && designPanelActive;- const layersPaneOpen = inspectorTabActive && rightInspectorPanes.layers;-- const handleInspectorPaneButtonClick = (pane: "design" | "layers") => {- if (!inspectorTabActive) {- setRightPanelTab(pane);- return;- }- // Flat inspector: Layers always renders full-height by itself (see the- // render branch below), so the two panes are mutually exclusive here —- // otherwise both tabs could show "active" while only one actually shows.- if (STUDIO_FLAT_INSPECTOR_ENABLED) {- setExclusiveRightInspectorPane(pane);- return;- }- toggleRightInspectorPane(pane);- };+ useSlideshowDockPanel(isSlideshowComposition);+ useBlockParamsDismissal({+ hasBlockParams: activeBlockParams != null,+ onDismiss: onDismissBlockParams,+ });+ useCaptionDesignFocus(captionEditMode);const handleApplyColorGradingScope = useCallback(async (scope: ColorGradingScope, value: string | null) =>@@ -337,165 +305,48 @@ export function StudioRightPanel({</DesignPanelPromoteProvider>);- const renderQueuePanel = <RenderQueuePanel />;-- // Slideshow appears only for a slideshow composition, so the strip is built- // rather than written out: a tab that is not in this list is not reachable by- // an arrow key either.- const inspectorTabs: RightPanelTabDescriptor[] = [- {- id: "design",- label: "Design",- tooltip: "Element styles and properties",- active: designPaneOpen,- onSelect: () => handleInspectorPaneButtonClick("design"),- },- {- id: "layers",- label: "Layers",- tooltip: "Composition layer stack",- active: layersPaneOpen,- onSelect: () => handleInspectorPaneButtonClick("layers"),- },- {- id: "renders",- label: renderJobs.length > 0 ? `Renders (${renderJobs.length})` : "Renders",- tooltip: "Render queue and exports",- active: rightPanelTab === "renders",- onSelect: () => setRightPanelTab("renders"),- },- ...(isSlideshowComposition- ? [- {- id: "slideshow",- label: "Slideshow",- tooltip: "Slideshow branching editor",- active: rightPanelTab === "slideshow",- onSelect: () => setRightPanelTab("slideshow"),- },- ]- : []),- {- id: "variables",- label: "Variables",- tooltip: "Template variables — declare, preview with values",- active: rightPanelTab === "variables",- onSelect: () => setRightPanelTab("variables"),- },- ];+ let designBody = propertyPanel;+ if (captionEditMode) {+ designBody = <CaptionPropertyPanel iframeRef={previewIframeRef} />;+ } else if (activeBlockParams) {+ designBody = (+ <BlockParamsPanel+ blockName={activeBlockParams.blockName}+ blockTitle={activeBlockParams.blockTitle}+ params={activeBlockParams.params}+ compositionPath={activeBlockParams.compositionPath}+ onClose={onCloseBlockParams ?? (() => {})}+ />+ );+ }return (<>- {/* Vertical resize divider: 3px visible seam, 13px hit zone via the inner div. */}- <div- role="separator"- aria-label="Resize inspector panel"- aria-orientation="vertical"- tabIndex={0}- className="group relative w-[3px] shrink-0 cursor-col-resize outline-hidden focus-visible:bg-studio-accent/20"- style={{ touchAction: "none" }}- onPointerDown={(e) => handlePanelResizeStart("right", e)}- onPointerMove={handlePanelResizeMove}- onPointerUp={handlePanelResizeEnd}- onPointerCancel={handlePanelResizeEnd}- onKeyDown={(e) => {- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;- e.preventDefault();- // Panel is right-anchored: ArrowLeft grows it, ArrowRight shrinks it.- const delta = e.key === "ArrowLeft" ? 16 : -16;- adjustPanelWidth("right", delta);- }}- >- {/* Asymmetric hit zone: 8px into the preview's p-2 gutter (the only dead- space), the 3px seam, 2px into the card. Stops short of the 24px WCAG- 2.5.8 target because the next pixel each way is live. */}- <div className="absolute inset-y-0 left-[-8px] w-[13px]" />- {/* Visible hairline */}- <div className="absolute top-1/2 left-0 h-[52px] w-[3px] -translate-y-1/2 bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />- </div>- <div- className="flex min-w-0 shrink-0 flex-col overflow-hidden rounded-lg border border-neutral-800 bg-neutral-950"- style={{ width: rightWidth }}+ <Dock.Panel id="design">{designBody}</Dock.Panel>+ <Dock.Panel id="layers">+ <LayersPanel />+ </Dock.Panel>+ <Dock.Panel+ id="renders"+ title={renderJobs.length > 0 ? `Renders (${renderJobs.length})` : undefined}>- {captionEditMode ? (- <CaptionPropertyPanel iframeRef={previewIframeRef} />- ) : (- <>- <RightPanelTabs tabs={inspectorTabs} activateOnFocus={STUDIO_FLAT_INSPECTOR_ENABLED} />- <div className="min-h-0 min-w-0 flex-1 overflow-hidden">- {rightPanelTab === "block-params" && activeBlockParams ? (- <BlockParamsPanel- blockName={activeBlockParams.blockName}- blockTitle={activeBlockParams.blockTitle}- params={activeBlockParams.params}- compositionPath={activeBlockParams.compositionPath}- onClose={onCloseBlockParams ?? (() => {})}- />- ) : rightPanelTab === "slideshow" && isSlideshowComposition ? (- <SlideshowPanel- scenes={slideshowScenes}- onPersist={onPersistSlideshow}- onPersistNotes={onPersistSlideshowNotes}- />- ) : rightPanelTab === "variables" ? (- <VariablesPanel- sdkSession={sdkSession}- publishSdkSession={publishSdkSession}- reloadPreview={reloadPreview}- recordEdit={recordEdit}- />- ) : layersPaneOpen && designPaneOpen && !STUDIO_FLAT_INSPECTOR_ENABLED ? (- <div ref={splitContainerRef} className="flex h-full min-h-0 min-w-0 flex-col">- <div- className="min-h-[120px] overflow-hidden"- style={{ flexBasis: `${layersPanePercent}%`, flexShrink: 0 }}- >- <LayersPanel />- </div>- <div- role="separator"- aria-label="Resize Layers and Design panes"- aria-orientation="horizontal"- className="group flex h-2 shrink-0 cursor-row-resize items-center justify-center border-y border-neutral-800 bg-neutral-900"- style={{ touchAction: "none" }}- onPointerDown={handleInspectorSplitResizeStart}- onPointerMove={handleInspectorSplitResizeMove}- onPointerUp={handleInspectorSplitResizeEnd}- onPointerCancel={handleInspectorSplitResizeEnd}- >- <div className="h-px w-10 rounded-full bg-white/12 transition-colors group-hover:bg-white/24 group-active:bg-studio-accent/70" />- </div>- <div className="min-h-0 flex-1 overflow-hidden">{propertyPanel}</div>- </div>- ) : layersPaneOpen ? (- <LayersPanel />- ) : designPaneOpen ? (- propertyPanel- ) : inspectorTabActive ? (- // Inspector tab selected but no pane can render (panes toggled- // off, or inspector inactive during playback/recording): show an- // explanation instead of silently rendering the render queue- // under a highlighted inspector tab.- <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">- <p className="text-xs text-neutral-500">- Inspector is unavailable right now — select the Design or Layers pane above, or- pause playback/recording to inspect elements.- </p>- <button- type="button"- onClick={() => setRightPanelTab("renders")}- className="h-7 rounded-md border border-neutral-800 px-3 text-[11px] font-medium text-neutral-400 transition-colors hover:border-neutral-700 hover:text-neutral-200 active:scale-[0.98]"- >- Show Renders- </button>- </div>- ) : (- renderQueuePanel- )}- </div>- </>- )}- </div>+ <RenderQueuePanel />+ </Dock.Panel>+ <Dock.Panel id="variables">+ <VariablesPanel+ sdkSession={sdkSession}+ publishSdkSession={publishSdkSession}+ reloadPreview={reloadPreview}+ recordEdit={recordEdit}+ />+ </Dock.Panel>+ <Dock.Panel id="slideshow">+ <SlideshowPanel+ scenes={slideshowScenes}+ onPersist={onPersistSlideshow}+ onPersistNotes={onPersistSlideshowNotes}+ />+ </Dock.Panel></>);}diff --git a/packages/studio/src/components/StudioRightPanel.types.ts b/packages/studio/src/components/StudioRightPanels.types.tssimilarity index 90%rename from packages/studio/src/components/StudioRightPanel.types.tsrename to packages/studio/src/components/StudioRightPanels.types.tsindex d3bb185ac1..058f1b046e 100644--- a/packages/studio/src/components/StudioRightPanel.types.ts+++ b/packages/studio/src/components/StudioRightPanels.types.ts@@ -1,5 +1,5 @@/**- * Props for StudioRightPanel.+ * Props for StudioRightPanels.** Kept beside the component rather than inside it: the panel is at the file-size* cap, and this block is the part that changes least, so moving it keeps the@@ -14,8 +14,7 @@ import type { UseSlideshowPersistParams } from "../hooks/useSlideshowPersist";import type { AddMediaOverlayHandler } from "./editor/propertyPanelTypes";import type { ToggleHiddenHandler } from "../utils/studioHelpers";-export interface StudioRightPanelProps extends StudioEditPersistenceProps {- designPanelActive: boolean;+export interface StudioRightPanelsProps extends StudioEditPersistenceProps {activeBlockParams?: {blockName: string;blockTitle: string;@@ -23,6 +22,8 @@ export interface StudioRightPanelProps extends StudioEditPersistenceProps {compositionPath: string;} | null;onCloseBlockParams?: () => void;+ /** Drops the block-params view without touching the dock (selection or leaving Design). */+ onDismissBlockParams: () => void;recordingState?: "idle" | "recording" | "preview";recordingDuration?: number;onToggleRecording?: () => void;diff --git a/packages/studio/src/components/dock/Dock.test.tsx b/packages/studio/src/components/dock/Dock.test.tsxindex 1dbf5e209e..f036d2fce5 100644--- a/packages/studio/src/components/dock/Dock.test.tsx+++ b/packages/studio/src/components/dock/Dock.test.tsx@@ -54,7 +54,10 @@ const applySideMinimums = vi.mocked(dockLayout.applySideMinimums);let root: Root | null = null;-function mount(projectId: string | null) {+function mount(+ projectId: string | null,+ titles: Partial<Record<(typeof PANEL_IDS)[number], string>> = {},+) {const host = document.createElement("div");document.body.append(host);root = createRoot(host);@@ -62,7 +65,7 @@ function mount(projectId: string | null) {root?.render(<Dock.Root projectId={projectId}>{PANEL_IDS.map((id) => (- <Dock.Panel key={id} id={id}>+ <Dock.Panel key={id} id={id} title={titles[id]}><div data-testid={`content-${id}`}>{id}</div></Dock.Panel>))}@@ -142,6 +145,17 @@ describe("Dock on React 19", () => {expect(host.querySelector('[data-testid="content-renders"]')).not.toBeNull();});+ it("keeps a panel's custom title when it is closed and reopened", async () => {+ const host = mount("p1", { renders: "Renders (2)" });+ expect(host.textContent).toContain("Renders (2)");+ act(() => useDockLayoutStore.getState().closePanel("renders"));+ await act(async () => {+ useDockLayoutStore.getState().togglePanel("renders");+ await Promise.resolve();+ });+ expect(host.textContent).toContain("Renders (2)");+ });+it("reopens a closed panel as a tab of its zone's group, not a new group", () => {mount("p1");act(() => useDockLayoutStore.getState().closePanel("compositions"));diff --git a/packages/studio/src/components/dock/Dock.tsx b/packages/studio/src/components/dock/Dock.tsxindex 45a3c4cf72..022ae80af3 100644--- a/packages/studio/src/components/dock/Dock.tsx+++ b/packages/studio/src/components/dock/Dock.tsx@@ -69,8 +69,17 @@ function snapshot(api: DockviewApi): DockSnapshot {openPanels.add(panel.id);if (panel.api.isVisible && panel.group.api.isVisible) visiblePanels.add(panel.id);}+ const groupActivePanels = api.groups.flatMap((group) => {+ const id = group.activePanel?.id;+ return isPanelId(id) ? [id] : [];+ });const active = api.activePanel?.id;- return { openPanels, visiblePanels, activePanel: isPanelId(active) ? active : null };+ return {+ openPanels,+ visiblePanels,+ activePanel: isPanelId(active) ? active : null,+ groupActivePanels,+ };}function createController(api: DockviewApi): DockController {@@ -206,10 +215,11 @@ function Panel({ id, title, children }: { id: PanelId; title?: string; children:const element = useSlots().slots[id];const visible = useDockLayoutStore((state) => state.visiblePanels.has(id));const controller = useDockLayoutStore((state) => state.controller);+ const open = useDockLayoutStore((state) => state.openPanels.has(id));const label = title ?? PANEL_DEFINITIONS[id].title;useEffect(() => {- controller?.setTitle(id, label);- }, [controller, id, label]);+ if (open) controller?.setTitle(id, label);+ }, [controller, id, label, open]);const definition: PanelDefinition = PANEL_DEFINITIONS[id];const shown = visible || definition.keepMounted;return element && shown ? createPortal(children, element) : null;diff --git a/packages/studio/src/components/dock/dockLayoutStore.test.ts b/packages/studio/src/components/dock/dockLayoutStore.test.tsnew file mode 100644index 0000000000..90768d3c38--- /dev/null+++ b/packages/studio/src/components/dock/dockLayoutStore.test.ts@@ -0,0 +1,28 @@+import { beforeEach, describe, expect, it } from "vitest";+import { useDockLayoutStore } from "./dockLayoutStore";+import type { PanelId } from "./panelRegistry";++const snapshot = (groupActivePanels: PanelId[], activePanel: PanelId | null = null) => ({+ openPanels: new Set<PanelId>(["design", "renders", "compositions"]),+ visiblePanels: new Set<PanelId>(groupActivePanels),+ activePanel,+ groupActivePanels,+});++describe("dock store sync", () => {+ beforeEach(() => useDockLayoutStore.setState({ lastActive: {} }));++ it("records what every side group shows, not only the globally active panel", () => {+ useDockLayoutStore.getState().sync(snapshot(["compositions", "renders"], "compositions"));+ expect(useDockLayoutStore.getState().lastActive).toEqual({+ left: "compositions",+ right: "renders",+ });+ });++ it("forgets the previous dock's memory on detach", () => {+ useDockLayoutStore.getState().sync(snapshot(["renders"], "renders"));+ useDockLayoutStore.getState().detach();+ expect(useDockLayoutStore.getState().lastActive).toEqual({});+ });+});diff --git a/packages/studio/src/components/dock/dockLayoutStore.ts b/packages/studio/src/components/dock/dockLayoutStore.tsindex cffa0ad1dd..e5439f4437 100644--- a/packages/studio/src/components/dock/dockLayoutStore.ts+++ b/packages/studio/src/components/dock/dockLayoutStore.ts@@ -25,6 +25,8 @@ export interface DockSnapshot {/** Open panels whose tab is showing and whose group is not hidden. */visiblePanels: ReadonlySet<PanelId>;activePanel: PanelId | null;+ /** The tab each group shows, so a restored layout still records what every side column last showed. */+ groupActivePanels?: readonly PanelId[];}type LastActive = Partial<Record<PanelZone, PanelId>>;@@ -53,13 +55,17 @@ export const useDockLayoutStore = create<DockLayoutState>((set, get) => ({lastActive: {},pendingActivation: null,attach: (controller) => set({ controller }),- detach: () => set({ controller: null }),+ detach: () => set({ controller: null, lastActive: {} }),sync: (snapshot) =>set((state) => {+ const lastActive = { ...state.lastActive };+ for (const id of snapshot.groupActivePanels ?? []) {+ const zone = PANEL_DEFINITIONS[id].zone;+ if (zone !== "center") lastActive[zone] = id;+ }const { activePanel } = snapshot;- if (!activePanel) return snapshot;- const zone = PANEL_DEFINITIONS[activePanel].zone;- return { ...snapshot, lastActive: { ...state.lastActive, [zone]: activePanel } };+ if (activePanel) lastActive[PANEL_DEFINITIONS[activePanel].zone] = activePanel;+ return { ...snapshot, lastActive };}),takePendingActivation: () => {const { pendingActivation } = get();@@ -89,3 +95,14 @@ export const useDockLayoutStore = create<DockLayoutState>((set, get) => ({},resetLayout: () => get().controller?.reset(),}));++/** The panel of `zone` the user is looking at: the last one focused if still showing, else any showing. */+export function visiblePanelInZone(+ zone: PanelZone,+ lastActive: LastActive,+ visiblePanels: ReadonlySet<PanelId>,+): PanelId | null {+ const last = lastActive[zone];+ if (last && visiblePanels.has(last)) return last;+ return panelsInZone(zone).find((id) => visiblePanels.has(id)) ?? null;+}diff --git a/packages/studio/src/components/editor/SnapToolbar.test.tsx b/packages/studio/src/components/editor/SnapToolbar.test.tsxindex 92ce8da38e..2a3d060045 100644--- a/packages/studio/src/components/editor/SnapToolbar.test.tsx+++ b/packages/studio/src/components/editor/SnapToolbar.test.tsx@@ -5,7 +5,6 @@ import { createRoot } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import { useAppHotkeys } from "../../hooks/useAppHotkeys";import { usePlayerStore } from "../../player/store/playerStore";-import type { LeftSidebarHandle } from "../sidebar/LeftSidebar";import type { DomEditSelection } from "./domEditing";import { SnapToolbar } from "./SnapToolbar";import { usePreviewGuidesStore } from "./previewGuidesStore";@@ -31,7 +30,6 @@ function renderToolbar(onSnapChange = vi.fn()) {function AppHotkeyHarness() {const domEditSelectionRef = useRef<DomEditSelection | null>(null);const clearDomSelectionRef = useRef<() => void>(() => undefined);- const leftSidebarRef = useRef<LeftSidebarHandle | null>(null);useAppHotkeys({handleTimelineElementsDelete: vi.fn(async () => {}),@@ -50,7 +48,6 @@ function AppHotkeyHarness() {showToast: vi.fn(),syncHistoryPreviewAfterApply: vi.fn(async () => undefined),waitForPendingDomEditSaves: vi.fn(async () => undefined),- leftSidebarRef,handleCopy: vi.fn(() => false),handlePaste: vi.fn(async () => undefined),handleCut: vi.fn(async () => false),diff --git a/packages/studio/src/components/nle/NLEContext.tsx b/packages/studio/src/components/nle/NLEContext.tsxindex 6285e87c60..fb11dd2b6d 100644--- a/packages/studio/src/components/nle/NLEContext.tsx+++ b/packages/studio/src/components/nle/NLEContext.tsx@@ -4,17 +4,11 @@ import { useTimelinePlayer, usePlayerStore } from "../../player";import type { TimelineElement } from "../../player";import type { CompositionLevel } from "./CompositionBreadcrumb";import { useCompositionStack } from "./useCompositionStack";-import { MIN_TIMELINE_H, fitTimelineHeight } from "../../utils/fitPanels";import { setCompositionSourceMap } from "../editor/domEditingDom";import { ensureMotionPathPluginLoaded } from "../../utils/gsapSoftReload";-import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";import { useAssetPreviewStore } from "../../utils/assetPreviewStore";import { createStableContext } from "../../utils/hmrStableContext";-// Timeline gets a generous default height so the preview isn't oversized and the-// tracks have room to breathe (CapCut-style). Users can still drag the divider.-const DEFAULT_TIMELINE_H = 360;-export function shouldDisableTimelineWhileCompositionLoading(compositionLoading: boolean): boolean {return compositionLoading;}@@ -34,10 +28,6 @@ export interface NLEContextValue {handleDrillDown: (element: TimelineElement) => void;compIdToSrc: Map<string, string>;// layout state- timelineH: number;- setTimelineH: React.Dispatch<React.SetStateAction<number>>;- persistTimelineH: (height: number) => void;- containerRef: React.RefObject<HTMLDivElement | null>;// composition loadingcompositionLoading: boolean;setCompositionLoading: (loading: boolean) => void;@@ -256,35 +246,6 @@ export function NLEProvider({});}, [compIdToSrc]);- // Resizable timeline height — persisted alongside zoom/pan so the user's- // workspace layout survives reloads.- const [timelineH, setTimelineH] = useState(() => {- const stored = readStudioUiPreferences().timelineHeight;- return stored !== undefined && stored >= MIN_TIMELINE_H ? stored : DEFAULT_TIMELINE_H;- });- const persistTimelineH = useCallback((height: number) => {- writeStudioUiPreferences({ timelineHeight: Math.round(height) });- }, []);- const containerRef = useRef<HTMLDivElement>(null);- // A height persisted on a tall window can exceed this window's container and- // collapse the flex-1 preview to 0px. Observing the container rather than- // clamping once at mount is what makes a window RESIZED after load behave the- // same as one loaded at that size: dragging 760 -> 520 tall used to leave the- // timeline at its stored 429px and the preview at 47px.- useEffect(() => {- const element = containerRef.current;- if (!element || typeof ResizeObserver === "undefined") return;- const reconcile = () => {- const containerH = element.getBoundingClientRect().height;- if (!containerH) return;- setTimelineH((prev) => fitTimelineHeight(containerH, prev));- };- reconcile();- const observer = new ResizeObserver(reconcile);- observer.observe(element);- return () => observer.disconnect();- }, []);-const hasLoadedOnceRef = useRef(false);const [compositionLoading, setCompositionLoadingRaw] = useState(true);const setCompositionLoading = useCallback((loading: boolean) => {@@ -317,10 +278,6 @@ export function NLEProvider({handleNavigateComposition,handleDrillDown,compIdToSrc,- timelineH,- setTimelineH,- persistTimelineH,- containerRef,compositionLoading,setCompositionLoading,timelineDisabled,diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsxindex ed1dbf4e8d..063916a1ad 100644--- a/packages/studio/src/components/nle/TimelinePane.tsx+++ b/packages/studio/src/components/nle/TimelinePane.tsx@@ -2,7 +2,6 @@ import { useCallback, type ReactNode } from "react";import { Timeline } from "../../player";import type { TimelineElement } from "../../player";import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";-import { TimelineResizeDivider } from "./TimelineResizeDivider";import { useTimelineEditContext } from "../../contexts/TimelineEditContext";import { trackStudioExpandedClipEdit } from "../../telemetry/events";import { useNLEContext } from "./NLEContext";@@ -132,10 +131,6 @@ export function TimelinePane({handleDrillDown,compositionStack,updateCompositionStack,- timelineH,- setTimelineH,- persistTimelineH,- containerRef,timelineDisabled,timelineSessionEpoch,} = useNLEContext();@@ -254,72 +249,56 @@ export function TimelinePane({);return (- <>- <TimelineResizeDivider- timelineH={timelineH}- setTimelineH={setTimelineH}- persistTimelineH={persistTimelineH}- containerRef={containerRef}- disabled={timelineDisabled}- />-- {/* Timeline section — inner padding (not margin) keeps the divider's- height math exact while giving the panel a gap from the shell edges. */}+ <div className="relative flex h-full flex-col" aria-disabled={timelineDisabled || undefined}><div- className="relative flex flex-col shrink-0 px-px pb-px"- style={{ height: timelineH }}- aria-disabled={timelineDisabled || undefined}+ className="flex flex-col flex-1 min-h-0 overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"+ onDoubleClick={(e) => {+ if ((e.target as HTMLElement).closest("[data-clip]")) return;+ if (timelineDisabled) return;+ if (compositionStack.length > 1) {+ updateCompositionStack((prev) => prev.slice(0, -1));+ }+ }}>+ <div className="shrink-0">{timelineToolbar}</div>+ <Timeline+ sessionEpoch={timelineSessionEpoch}+ onSeek={seek}+ onDrillDown={handleDrillDown}+ renderClipContent={renderClipContent}+ onFileDrop={onFileDrop}+ onDeleteElement={handleDeleteElement}+ onAssetDrop={onAssetDrop}+ onBlockDrop={onBlockDrop}+ onCompositionDrop={onCompositionDrop}+ onMoveElement={handleMoveElement}+ onMoveElements={handleMoveElements}+ onResizeElement={handleResizeElement}+ onResizeElements={handleResizeElements}+ onBlockedEditAttempt={onBlockedEditAttempt}+ onSplitElement={handleSplitElement}+ onSelectElement={onSelectTimelineElement}+ onCopyClip={onCopyClip}+ onPasteClip={onPasteClip}+ onDuplicateClip={onDuplicateClip}+ canPasteClip={canPasteClip}+ />+ </div>+ {timelineFooter && <div className="shrink-0">{timelineFooter}</div>}+ {timelineDisabled && (<div- className="flex flex-col flex-1 min-h-0 overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"- onDoubleClick={(e) => {- if ((e.target as HTMLElement).closest("[data-clip]")) return;- if (timelineDisabled) return;- if (compositionStack.length > 1) {- updateCompositionStack((prev) => prev.slice(0, -1));- }- }}+ className="absolute inset-0 z-30 cursor-not-allowed bg-black/18 flex items-center justify-center"+ data-testid="timeline-loading-disabled-overlay"+ role="status"+ onPointerDown={(event) => event.preventDefault()}+ onDragOver={(event) => event.preventDefault()}+ onDrop={(event) => event.preventDefault()}>- <div className="shrink-0">{timelineToolbar}</div>- <Timeline- sessionEpoch={timelineSessionEpoch}- onSeek={seek}- onDrillDown={handleDrillDown}- renderClipContent={renderClipContent}- onFileDrop={onFileDrop}- onDeleteElement={handleDeleteElement}- onAssetDrop={onAssetDrop}- onBlockDrop={onBlockDrop}- onCompositionDrop={onCompositionDrop}- onMoveElement={handleMoveElement}- onMoveElements={handleMoveElements}- onResizeElement={handleResizeElement}- onResizeElements={handleResizeElements}- onBlockedEditAttempt={onBlockedEditAttempt}- onSplitElement={handleSplitElement}- onSelectElement={onSelectTimelineElement}- onCopyClip={onCopyClip}- onPasteClip={onPasteClip}- onDuplicateClip={onDuplicateClip}- canPasteClip={canPasteClip}- />+ <span className="rounded-md bg-neutral-900/90 px-2.5 py-1 text-[11px] text-neutral-400">+ Loading composition…+ </span></div>- {timelineFooter && <div className="shrink-0">{timelineFooter}</div>}- {timelineDisabled && (- <div- className="absolute inset-0 z-30 cursor-not-allowed bg-black/18 flex items-center justify-center"- data-testid="timeline-loading-disabled-overlay"- role="status"- onPointerDown={(event) => event.preventDefault()}- onDragOver={(event) => event.preventDefault()}- onDrop={(event) => event.preventDefault()}- >- <span className="rounded-md bg-neutral-900/90 px-2.5 py-1 text-[11px] text-neutral-400">- Loading composition…- </span>- </div>- )}- </div>- </>+ )}+ </div>);}diff --git a/packages/studio/src/components/nle/TimelineResizeDivider.tsx b/packages/studio/src/components/nle/TimelineResizeDivider.tsxdeleted file mode 100644index 8b407c633e..0000000000--- a/packages/studio/src/components/nle/TimelineResizeDivider.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { useCallback, useRef } from "react";-import { MIN_PREVIEW_H, MIN_TIMELINE_H, fitTimelineHeight } from "../../utils/fitPanels";--/**- * Horizontal drag/keyboard-resizable divider between the preview and the- * timeline. Implements the separator pattern: ArrowUp grows the timeline,- * ArrowDown shrinks it (mirrors the drag direction).- */-export function TimelineResizeDivider({- timelineH,- setTimelineH,- persistTimelineH,- containerRef,- disabled,-}: {- timelineH: number;- setTimelineH: React.Dispatch<React.SetStateAction<number>>;- persistTimelineH: (h: number) => void;- containerRef: React.RefObject<HTMLDivElement | null>;- disabled: boolean;-}) {- const isDragging = useRef(false);- const timelineHRef = useRef(timelineH);- timelineHRef.current = timelineH;-- const handlePointerDown = useCallback(- (e: React.PointerEvent) => {- if (disabled) return;- e.preventDefault();- isDragging.current = true;- (e.target as HTMLElement).setPointerCapture(e.pointerId);- },- [disabled],- );-- const handlePointerMove = useCallback(- (e: React.PointerEvent) => {- if (disabled) return;- if (!isDragging.current || !containerRef.current) return;- const rect = containerRef.current.getBoundingClientRect();- const mouseY = e.clientY - rect.top;- setTimelineH(fitTimelineHeight(rect.height, rect.height - mouseY));- },- [disabled, containerRef, setTimelineH],- );-- const handlePointerUp = useCallback(() => {- if (isDragging.current) persistTimelineH(timelineHRef.current);- isDragging.current = false;- }, [persistTimelineH]);-- const handleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- if (disabled) return;- if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;- e.preventDefault();- const containerH = containerRef.current?.getBoundingClientRect().height ?? 0;- const delta = e.key === "ArrowUp" ? 16 : -16;- setTimelineH((prev) => {- const next = fitTimelineHeight(containerH, prev + delta);- persistTimelineH(next);- return next;- });- },- [disabled, containerRef, setTimelineH, persistTimelineH],- );-- return (- // Horizontal resize divider: 3px visible seam (h-[3px]), 10px pointer-capture- // zone via the absolutely-positioned inner hit area so the layout gap stays- // at 3px while draggability is preserved over the full band.- <div- role="separator"- aria-orientation="horizontal"- aria-label="Resize timeline (arrow keys)"- aria-valuenow={Math.round(timelineH)}- aria-valuemin={MIN_TIMELINE_H}- aria-valuemax={Math.round(- (containerRef.current?.getBoundingClientRect().height ?? 600) - MIN_PREVIEW_H,- )}- tabIndex={0}- className="group relative h-[3px] shrink-0 cursor-row-resize z-10 outline-hidden focus-visible:bg-studio-accent/20"- style={{ touchAction: "none" }}- onPointerDown={handlePointerDown}- onPointerMove={handlePointerMove}- onPointerUp={handlePointerUp}- onPointerCancel={handlePointerUp}- onKeyDown={handleKeyDown}- >- {/* Expanded hit zone, deliberately asymmetric: 4px up into the transport- row's vertical centring slack, the 3px seam, then 3px down into the- timeline card's border + toolbar padding. It stops at 10px rather than- the 24px WCAG 2.2 (2.5.8) target because that is all the dead space- there is: 28px transport buttons sit above and 28px toolbar buttons- below, and silently stealing their clicks is the worse bug. */}- <div className="absolute inset-x-0 top-[-4px] h-[10px]" />- {/* Visible hairline — invisible at rest, subtle wash on hover/drag/focus */}- <div className="h-[3px] w-full bg-transparent transition-colors group-hover:bg-white/12 group-active:bg-white/18 group-focus-visible:bg-studio-accent/60" />- </div>- );-}diff --git a/packages/studio/src/components/panels/SlideshowPanel.tsx b/packages/studio/src/components/panels/SlideshowPanel.tsxindex e32a759640..42fbc86961 100644--- a/packages/studio/src/components/panels/SlideshowPanel.tsx+++ b/packages/studio/src/components/panels/SlideshowPanel.tsx@@ -156,7 +156,7 @@ export function makeSlideshowNotesController(): NotesController {// ── Component ─────────────────────────────────────────────────────────────export interface SlideshowPanelProps {- /** Scenes from the live clip manifest (passed from StudioRightPanel). */+ /** Scenes from the live clip manifest (passed from StudioRightPanels). */scenes: import("./slideshowPanelHelpers").SceneInfo[];/*** Called with the updated manifest after every discrete edit (toggle, add,diff --git a/packages/studio/src/components/panels/VariablesPanel.tsx b/packages/studio/src/components/panels/VariablesPanel.tsxindex b2dcad3e78..b52ace1d50 100644--- a/packages/studio/src/components/panels/VariablesPanel.tsx+++ b/packages/studio/src/components/panels/VariablesPanel.tsx@@ -246,7 +246,7 @@ const EMPTY_STATE = (</p>);-// Panel orchestrator — JSX conditionals per section, same shape as StudioRightPanel.+// Panel orchestrator — JSX conditionals per section, same shape as StudioRightPanels.// fallow-ignore-next-line complexityexport const VariablesPanel = memo(function VariablesPanel({sdkSession,diff --git a/packages/studio/src/components/renders/RenderQueuePanel.tsx b/packages/studio/src/components/renders/RenderQueuePanel.tsxindex e4a9df6512..8551de734b 100644--- a/packages/studio/src/components/renders/RenderQueuePanel.tsx+++ b/packages/studio/src/components/renders/RenderQueuePanel.tsx@@ -7,7 +7,7 @@ import { usePreviewVariablesStore } from "../../hooks/previewVariablesStore";/*** The Renders tab, wired to the shell context.*- * Split out of StudioRightPanel because every field it needs already lives in+ * Split out of StudioRightPanels because every field it needs already lives in* that context, so routing them through the panel only made the panel longer* without giving anything a second reader.*/diff --git a/packages/studio/src/components/sidebar/LeftSidebar.masterComposition.test.tsx b/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsxsimilarity index 73%rename from packages/studio/src/components/sidebar/LeftSidebar.masterComposition.test.tsxrename to packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsxindex 564bc719f0..6f6495d58f 100644--- a/packages/studio/src/components/sidebar/LeftSidebar.masterComposition.test.tsx+++ b/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsx@@ -4,7 +4,7 @@ import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import { usePlayerStore } from "../../player/store/playerStore";-import { LeftSidebar } from "./LeftSidebar";+import { CompositionsPanel } from "./CompositionsPanel";Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });(@@ -20,23 +20,20 @@ afterEach(() => {usePlayerStore.setState({ thumbnailContentRevision: 0 });});-describe("LeftSidebar root badge source", () => {+describe("CompositionsPanel root badge source", () => {it("derives the root badge from the filtered compositions list, not the raw file tree", () => {- // `fileTree` includes a non-composition index.html (a vendored preset) that the- // server's filtered `compositions` list excludes — the badge must source from- // `compositions`, not the raw file tree.+ // The project's raw file tree can hold a non-composition index.html (a vendored+ // preset); the badge must source from the server's filtered `compositions` list.const host = document.createElement("div");document.body.append(host);root = createRoot(host);act(() => {root?.render(- <LeftSidebar+ <CompositionsPanelprojectId="demo"compositions={["hero.html"]}- assets={[]}- fileTree={["index.html", "hero.html"]}activeComposition={null}- onSelectComposition={vi.fn()}+ onSelect={vi.fn()}/>,);});diff --git a/packages/studio/src/components/sidebar/CompositionsPanel.tsx b/packages/studio/src/components/sidebar/CompositionsPanel.tsxnew file mode 100644index 0000000000..456c6b395b--- /dev/null+++ b/packages/studio/src/components/sidebar/CompositionsPanel.tsx@@ -0,0 +1,15 @@+import type { ComponentProps } from "react";+import { resolveMasterCompositionPath } from "../../utils/studioUrlState";+import { CompositionsTab } from "./CompositionsTab";++type Props = Omit<ComponentProps<typeof CompositionsTab>, "masterCompositionPath">;++/** The Compositions dock panel body; the root badge comes from the filtered composition list. */+export function CompositionsPanel(props: Props) {+ return (+ <CompositionsTab+ {...props}+ masterCompositionPath={resolveMasterCompositionPath(props.compositions)}+ />+ );+}diff --git a/packages/studio/src/components/sidebar/LeftSidebar.storage.test.ts b/packages/studio/src/components/sidebar/LeftSidebar.storage.test.tsdeleted file mode 100644index 7e4cf8501b..0000000000--- a/packages/studio/src/components/sidebar/LeftSidebar.storage.test.ts+++ /dev/null@@ -1,28 +0,0 @@-// @vitest-environment happy-dom--import { afterEach, expect, it, vi } from "vitest";-import { getPersistedTab } from "./LeftSidebar";--vi.mock("../../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));--const originalDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");--afterEach(() => {- if (originalDescriptor) Object.defineProperty(globalThis, "localStorage", originalDescriptor);-});--it("falls back to the default tab when localStorage is blocked", () => {- // Chrome throws on the property read itself when site data is blocked for- // the document. This runs as a useState initializer, so throwing here takes- // Studio to the crash boundary.- Object.defineProperty(globalThis, "localStorage", {- configurable: true,- get() {- throw new Error(- "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",- );- },- });-- expect(getPersistedTab()).toBe("compositions");-});diff --git a/packages/studio/src/components/sidebar/LeftSidebar.tsx b/packages/studio/src/components/sidebar/LeftSidebar.tsxdeleted file mode 100644index 798dbe6e73..0000000000--- a/packages/studio/src/components/sidebar/LeftSidebar.tsx+++ /dev/null@@ -1,348 +0,0 @@-import {- memo,- useState,- useCallback,- useImperativeHandle,- useMemo,- useRef,- forwardRef,- type ReactNode,-} from "react";-import { CompositionsTab } from "./CompositionsTab";-import { AssetsTab } from "./AssetsTab";-import { trackStudioEvent } from "../../utils/studioTelemetry";-import { safeLocalStorage } from "../../utils/safeStorage";-import { resolveMasterCompositionPath } from "../../utils/studioUrlState";-import { BlocksTab, type BlockPreviewInfo } from "./BlocksTab";-import { FileTree } from "../editor/FileTree";-import { Tooltip } from "../ui";--export type SidebarTab = "compositions" | "assets" | "code" | "blocks";--export interface LeftSidebarHandle {- selectTab: (tab: SidebarTab) => void;- getTab: () => SidebarTab;-}--const STORAGE_KEY = "hf-studio-sidebar-tab";--const SIDEBAR_TABS: Array<{ id: SidebarTab; label: string; tooltip: string }> = [- { id: "code", label: "Code", tooltip: "Source code editor" },- { id: "compositions", label: "Comps", tooltip: "Compositions and sub-compositions" },- { id: "assets", label: "Assets", tooltip: "Videos, images, audio, fonts" },- { id: "blocks", label: "Catalog", tooltip: "Browse blocks and components" },-];--// Both the `localStorage` reference and `getItem` itself can throw when the-// browsing context is partitioned or site data is blocked — the same case-// telemetry/config.ts documents. This runs as a `useState` initializer, so an-// unguarded throw here takes the whole editor to the crash boundary rather-// than losing one remembered tab.-export function getPersistedTab(): SidebarTab {- let stored: string | null = null;- try {- stored = safeLocalStorage()?.getItem(STORAGE_KEY) ?? null;- } catch {- /* storage unavailable — fall back to the default tab */- }- if (stored === "assets") return "assets";- if (stored === "code") return "code";- if (stored === "blocks") return "blocks";- return "compositions";-}--interface LeftSidebarProps {- width?: number;- projectId: string;- compositions: string[];- assets: string[];- activeComposition: string | null;- onSelectComposition: (comp: string) => void;- onImportFiles?: (files: FileList, dir?: string) => void | Promise<void>;- fileTree?: string[];- editingFile?: { path: string; content: string | null } | null;- onSelectFile?: (path: string) => void;- onCreateFile?: (path: string) => void;- onCreateFolder?: (path: string) => void;- onDeleteFile?: (path: string) => void;- onRenameFile?: (oldPath: string, newPath: string) => void;- onDuplicateFile?: (path: string) => void;- onMoveFile?: (oldPath: string, newPath: string) => void;- codeChildren?: ReactNode;- onRenderComposition?: (comp: string) => void;- isRendering?: boolean;- onLint?: () => void;- linting?: boolean;- lintFindingCount?: number;- lintHasError?: boolean;- lintFindingsByFile?: Map<string, { count: number; messages: string[] }>;- onToggleCollapse?: () => void;- onAddBlock?: (blockName: string) => void | Promise<void>;- onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;- takeoverContent?: ReactNode;- onAddAssetToTimeline?: (path: string) => void;- onAddCompositionToTimeline?: (path: string) => void;-}--export const LeftSidebar = memo(- forwardRef<LeftSidebarHandle, LeftSidebarProps>(function LeftSidebar(- {- width = 240,- projectId,- compositions,- assets,- activeComposition,- onSelectComposition,- onImportFiles,- fileTree: fileProp,- editingFile,- onSelectFile,- onCreateFile,- onCreateFolder,- onDeleteFile,- onRenameFile,- onDuplicateFile,- onMoveFile,- codeChildren,- onRenderComposition,- isRendering,- onLint,- linting,- lintFindingCount,- lintHasError,- lintFindingsByFile,- onToggleCollapse,- onAddBlock,- onPreviewBlock,- takeoverContent,- onAddAssetToTimeline,- onAddCompositionToTimeline,- },- ref,- ) {- const [tab, setTab] = useState<SidebarTab>(getPersistedTab);- const tabRef = useRef(tab);- tabRef.current = tab;- const tablistRef = useRef<HTMLDivElement>(null);- const masterCompositionPath = useMemo(- () => resolveMasterCompositionPath(compositions),- [compositions],- );-- const selectTab = useCallback((t: SidebarTab) => {- setTab(t);- try {- safeLocalStorage()?.setItem(STORAGE_KEY, t);- } catch {- /* storage unavailable — the tab just won't be remembered */- }- trackStudioEvent("tab_switch", { panel: "left_sidebar", tab: t });- }, []);-- const getTab = useCallback(() => tabRef.current, []);-- useImperativeHandle(ref, () => ({ selectTab, getTab }), [selectTab, getTab]);-- // APG tabs pattern: Left/Right move focus AND selection between tabs.- const handleTablistKeyDown = useCallback(- (e: React.KeyboardEvent) => {- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;- e.preventDefault();- const ids = SIDEBAR_TABS.map((t) => t.id);- const idx = ids.indexOf(tabRef.current);- const next = ids[(idx + (e.key === "ArrowRight" ? 1 : -1) + ids.length) % ids.length];- selectTab(next);- tablistRef.current?.querySelector<HTMLButtonElement>(`[data-tab-id="${next}"]`)?.focus();- },- [selectTab],- );-- return (- <div- className="flex flex-col h-full overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"- style={{ width }}- >- {takeoverContent ? (- <div className="flex min-h-0 flex-1">{takeoverContent}</div>- ) : (- <>- {/* Tabs — Code first */}- <div className="border-b border-neutral-800/50 px-3 py-3 shrink-0">- <div className="flex items-center gap-2">- <div- ref={tablistRef}- role="tablist"- aria-label="Sidebar panels"- onKeyDown={handleTablistKeyDown}- className="grid min-w-0 flex-1 gap-0.5 rounded-[18px] bg-neutral-900 p-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"- style={{ gridTemplateColumns: "1fr 1fr 1fr 1fr" }}- >- {SIDEBAR_TABS.map((t) => (- <Tooltip key={t.id} label={t.tooltip} side="bottom">- <button- type="button"- role="tab"- data-tab-id={t.id}- aria-selected={tab === t.id}- aria-controls={`sidebar-panel-${t.id}`}- tabIndex={tab === t.id ? 0 : -1}- onClick={() => selectTab(t.id)}- className={`rounded-[14px] px-1.5 py-2 text-[10px] font-semibold truncate transition-all active:scale-[0.97] ${- tab === t.id- ? "bg-neutral-800 text-white"- : "text-neutral-500 hover:text-neutral-200"- }`}- >- {t.label}- </button>- </Tooltip>- ))}- </div>- {onToggleCollapse && (- <button- type="button"- onClick={onToggleCollapse}- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-transparent text-neutral-500 transition-colors hover:border-neutral-800 hover:bg-neutral-900 hover:text-neutral-300"- title="Hide sidebar"- aria-label="Hide sidebar"- >- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true"- >- <path d="m14 7-5 5 5 5" />- <path d="M19 4v16" />- </svg>- </button>- )}- </div>- </div>-- {/* Tab content */}- {tab === "compositions" && (- <div- id="sidebar-panel-compositions"- role="tabpanel"- className="flex flex-col flex-1 min-h-0"- >- <CompositionsTab- projectId={projectId}- compositions={compositions}- activeComposition={activeComposition}- masterCompositionPath={masterCompositionPath}- onSelect={onSelectComposition}- onAddToTimeline={onAddCompositionToTimeline}- onRenderComposition={onRenderComposition}- isRendering={isRendering}- lintFindingsByFile={lintFindingsByFile}- />- </div>- )}- {tab === "assets" && (- <div- id="sidebar-panel-assets"- role="tabpanel"- className="flex flex-col flex-1 min-h-0"- >- <AssetsTab- projectId={projectId}- assets={assets}- onImport={onImportFiles}- onDelete={onDeleteFile}- onRename={onRenameFile}- onAddAssetToTimeline={onAddAssetToTimeline}- />- </div>- )}- {tab === "code" && (- <div id="sidebar-panel-code" role="tabpanel" className="flex flex-1 min-h-0">- {(fileProp?.length ?? 0) > 0 && (- <div className="w-[160px] shrink-0 border-r border-neutral-800 overflow-y-auto">- <FileTree- files={fileProp ?? []}- activeFile={editingFile?.path ?? null}- onSelectFile={onSelectFile ?? (() => {})}- onCreateFile={onCreateFile}- onCreateFolder={onCreateFolder}- onDeleteFile={onDeleteFile}- onRenameFile={onRenameFile}- onDuplicateFile={onDuplicateFile}- onMoveFile={onMoveFile}- onImportFiles={onImportFiles}- lintFindingsByFile={lintFindingsByFile}- />- </div>- )}- <div className="flex-1 overflow-hidden min-w-0">- {codeChildren ?? (- <div className="flex items-center justify-center h-full text-neutral-600 text-sm">- Select a file to edit- </div>- )}- </div>- </div>- )}-- {tab === "blocks" && (- <div- id="sidebar-panel-blocks"- role="tabpanel"- className="flex flex-col flex-1 min-h-0"- >- <BlocksTab onAddBlock={onAddBlock} onPreviewBlock={onPreviewBlock} />- </div>- )}-- {/* Lint button pinned at the bottom */}- {onLint && (- <div className="border-t border-neutral-800 p-2 shrink-0">- <button- onClick={onLint}- disabled={linting}- className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[11px] font-medium text-neutral-500 enabled:hover:text-amber-300 enabled:hover:bg-neutral-800 enabled:active:scale-[0.98] transition-colors disabled:opacity-40"- >- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M9 11l3 3L22 4" />- <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" />- </svg>- {linting ? "Linting…" : "Lint"}- {!linting && lintFindingCount != null && lintFindingCount > 0 && (- <span- data-lint-badge={lintHasError ? "error" : "warning"}- className={- lintHasError- ? "ml-1 min-w-[16px] rounded-full bg-panel-danger/25 px-1 text-[9px] font-bold text-panel-danger animate-pulse motion-reduce:animate-none"- : "ml-1 min-w-[16px] rounded-full bg-amber-500/20 px-1 text-[9px] font-bold text-amber-400"- }- >- {lintFindingCount}- <span className="sr-only">- {lintHasError- ? " lint findings, including errors"- : " lint findings, warnings only"}- </span>- </span>- )}- </button>- </div>- )}- </>- )}- </div>- );- }),-);diff --git a/packages/studio/src/components/sidebar/LeftSidebar.lintBadge.test.tsx b/packages/studio/src/components/sidebar/SidebarLintButton.test.tsxsimilarity index 80%rename from packages/studio/src/components/sidebar/LeftSidebar.lintBadge.test.tsxrename to packages/studio/src/components/sidebar/SidebarLintButton.test.tsxindex 57a9913fe1..3df6a35cf9 100644--- a/packages/studio/src/components/sidebar/LeftSidebar.lintBadge.test.tsx+++ b/packages/studio/src/components/sidebar/SidebarLintButton.test.tsx@@ -3,7 +3,7 @@import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";-import { LeftSidebar } from "./LeftSidebar";+import { SidebarLintButton } from "./SidebarLintButton";Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });(@@ -24,23 +24,18 @@ function renderBadge(lintHasError: boolean): HTMLElement | null {root = createRoot(host);act(() => {root?.render(- <LeftSidebar- projectId="demo"- compositions={["index.html"]}- assets={[]}- fileTree={["index.html"]}- activeComposition={null}- onSelectComposition={vi.fn()}+ <SidebarLintButtononLint={vi.fn()}- lintFindingCount={2}- lintHasError={lintHasError}+ linting={false}+ findingCount={2}+ hasError={lintHasError}/>,);});return host.querySelector<HTMLElement>("[data-lint-badge]");}-describe("LeftSidebar lint badge", () => {+describe("SidebarLintButton badge", () => {it("pulses, and stops for reduced motion, while an error finding exists", () => {const badge = renderBadge(true);expect(badge?.dataset.lintBadge).toBe("error");diff --git a/packages/studio/src/components/sidebar/SidebarLintButton.tsx b/packages/studio/src/components/sidebar/SidebarLintButton.tsxnew file mode 100644index 0000000000..2e978deb06--- /dev/null+++ b/packages/studio/src/components/sidebar/SidebarLintButton.tsx@@ -0,0 +1,50 @@+export function SidebarLintButton({+ onLint,+ linting,+ findingCount,+ hasError,+}: {+ onLint: () => void;+ linting: boolean;+ findingCount?: number;+ hasError?: boolean;+}) {+ return (+ <div className="border-t border-neutral-800 p-2 shrink-0">+ <button+ type="button"+ onClick={onLint}+ disabled={linting}+ className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[11px] font-medium text-neutral-500 enabled:hover:text-amber-300 enabled:hover:bg-neutral-800 enabled:active:scale-[0.98] transition-colors disabled:opacity-40"+ >+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <path d="M9 11l3 3L22 4" />+ <path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" />+ </svg>+ {linting ? "Linting…" : "Lint"}+ {!linting && findingCount != null && findingCount > 0 && (+ <span+ data-lint-badge={hasError ? "error" : "warning"}+ className={+ hasError+ ? "ml-1 min-w-[16px] rounded-full bg-panel-danger/25 px-1 text-[9px] font-bold text-panel-danger animate-pulse motion-reduce:animate-none"+ : "ml-1 min-w-[16px] rounded-full bg-amber-500/20 px-1 text-[9px] font-bold text-amber-400"+ }+ >+ {findingCount}+ <span className="sr-only">+ {hasError ? " lint findings, including errors" : " lint findings, warnings only"}+ </span>+ </span>+ )}+ </button>+ </div>+ );+}diff --git a/packages/studio/src/contexts/PanelLayoutContext.tsx b/packages/studio/src/contexts/PanelLayoutContext.tsxindex c37ff8474e..5acf7fcbaa 100644--- a/packages/studio/src/contexts/PanelLayoutContext.tsx+++ b/packages/studio/src/contexts/PanelLayoutContext.tsx@@ -13,69 +13,15 @@ export function usePanelLayoutContext(): PanelLayoutValue {}export function PanelLayoutProvider({- value: {- leftWidth,- rightWidth,- adjustPanelWidth,- leftCollapsed,- rightCollapsed,- setRightCollapsed,- effectiveLeftCollapsed,- effectiveRightCollapsed,- rightPanelTab,- setRightPanelTab,- rightInspectorPanes,- toggleRightInspectorPane,- setExclusiveRightInspectorPane,- toggleLeftSidebar,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- },+ value: { rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab },children,}: {value: PanelLayoutValue;children: ReactNode;}) {const stable = useMemo<PanelLayoutValue>(- () => ({- leftWidth,- rightWidth,- adjustPanelWidth,- leftCollapsed,- rightCollapsed,- setRightCollapsed,- effectiveLeftCollapsed,- effectiveRightCollapsed,- rightPanelTab,- setRightPanelTab,- rightInspectorPanes,- toggleRightInspectorPane,- setExclusiveRightInspectorPane,- toggleLeftSidebar,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- }),- [- leftWidth,- rightWidth,- adjustPanelWidth,- leftCollapsed,- rightCollapsed,- setRightCollapsed,- effectiveLeftCollapsed,- effectiveRightCollapsed,- rightPanelTab,- setRightPanelTab,- rightInspectorPanes,- toggleRightInspectorPane,- setExclusiveRightInspectorPane,- toggleLeftSidebar,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- ],+ () => ({ rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab }),+ [rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab],);return <PanelLayoutContext value={stable}>{children}</PanelLayoutContext>;}diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.tsindex 6c4e62991e..f53da57a45 100644--- a/packages/studio/src/hooks/appHotkeysDispatch.ts+++ b/packages/studio/src/hooks/appHotkeysDispatch.ts@@ -2,7 +2,7 @@ import { automationOwnsKey } from "./useAutomationSelectionKeyboard";import { usePlayerStore } from "../player";import type { TimelineElement } from "../player";import type { DomEditSelection } from "../components/editor/domEditing";-import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";+import { useDockLayoutStore } from "../components/dock/dockLayoutStore";import { isTypingTarget } from "../utils/typingTarget";import { isEditableTarget } from "../utils/timelineDiscovery";import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";@@ -52,7 +52,6 @@ export interface HotkeyCallbacks {onToggleRecording?: () => void;onGroupSelection?: () => void;onUngroupSelection?: () => void;- leftSidebarRef: React.RefObject<LeftSidebarHandle | null>;domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;showToast: (message: string, tone?: "error" | "info") => void;}@@ -84,13 +83,13 @@ export function dispatchModifierKey(if (event.key === "1") {event.preventDefault();trackStudioEvent("keyboard_shortcut", { action: "tab_compositions" });- cb.leftSidebarRef.current?.selectTab("compositions");+ useDockLayoutStore.getState().activatePanel("compositions");return true;}if (event.key === "2") {event.preventDefault();trackStudioEvent("keyboard_shortcut", { action: "tab_assets" });- cb.leftSidebarRef.current?.selectTab("assets");+ useDockLayoutStore.getState().activatePanel("assets");return true;}diff --git a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsxindex 84aec62b84..d08ac78569 100644--- a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx+++ b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx@@ -4,7 +4,6 @@ import React, { act, useRef } from "react";import type { Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import type { DomEditSelection } from "../components/editor/domEditing";-import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";import { usePlayerStore } from "../player/store/playerStore";import { useAppHotkeys } from "./useAppHotkeys";import { mountReactHarness } from "./domSelectionTestHarness";@@ -46,7 +45,6 @@ function Harness() {showToast: vi.fn(),syncHistoryPreviewAfterApply: vi.fn(async () => undefined),waitForPendingDomEditSaves: vi.fn(async () => undefined),- leftSidebarRef: useRef<LeftSidebarHandle | null>(null),handleCopy: vi.fn(() => false),handlePaste: vi.fn(() => false),handleCut: vi.fn(() => false),diff --git a/packages/studio/src/hooks/useAppHotkeys.test.ts b/packages/studio/src/hooks/useAppHotkeys.test.tsindex dfbf8fc09b..bf9b93260c 100644--- a/packages/studio/src/hooks/useAppHotkeys.test.ts+++ b/packages/studio/src/hooks/useAppHotkeys.test.ts@@ -33,7 +33,6 @@ function callbacks() {onResetKeyframes: vi.fn(() => true),onDeleteSelectedKeyframes: vi.fn(),showToast: vi.fn(),- leftSidebarRef: { current: null },domEditSelectionRef: { current: null },};}diff --git a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsxindex fb9979c8b4..247780f892 100644--- a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx+++ b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx@@ -5,7 +5,6 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { TextAreaField } from "../components/editor/propertyPanelSections";import type { DomEditSelection } from "../components/editor/domEditing";-import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";import { usePlayerStore } from "../player/store/playerStore";import { useAppHotkeys } from "./useAppHotkeys";@@ -70,7 +69,6 @@ function Harness() {const [selectionRefreshed, setSelectionRefreshed] = useState(false);const selectionRef = useRef<DomEditSelection | null>(parentWithTextChild());const clearSelectionRef = useRef<() => void>(() => undefined);- const leftSidebarRef = useRef<LeftSidebarHandle | null>(null);useAppHotkeys({handleTimelineElementsDelete: timelineDeleteMany,@@ -89,7 +87,6 @@ function Harness() {showToast: vi.fn(),syncHistoryPreviewAfterApply: vi.fn(async () => undefined),waitForPendingDomEditSaves: vi.fn(async () => undefined),- leftSidebarRef,handleCopy: vi.fn(() => false),handlePaste: vi.fn(async () => undefined),handleCut: vi.fn(async () => false),diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.tsindex 8d1ab9fa68..d271533140 100644--- a/packages/studio/src/hooks/useAppHotkeys.ts+++ b/packages/studio/src/hooks/useAppHotkeys.ts@@ -2,7 +2,6 @@ import { useCallback, useEffect, useRef } from "react";import { usePlayerStore } from "../player";import type { TimelineElement } from "../player";import type { DomEditSelection } from "../components/editor/domEditing";-import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";import { isTypingTarget } from "../utils/typingTarget";import { useCaptionStore } from "../captions/store";import {@@ -88,7 +87,6 @@ interface UseAppHotkeysParams {showToast: (message: string, tone?: "error" | "info") => void;syncHistoryPreviewAfterApply: UseEditHistoryActionsOptions["syncHistoryPreviewAfterApply"];waitForPendingDomEditSaves: () => Promise<void>;- leftSidebarRef: React.RefObject<LeftSidebarHandle | null>;handleCopy: () => boolean;handlePaste: () => Promise<void>;handleCut: () => Promise<boolean>;@@ -125,7 +123,6 @@ export function useAppHotkeys({showToast,syncHistoryPreviewAfterApply,waitForPendingDomEditSaves,- leftSidebarRef,handleCopy,handlePaste,handleCut,@@ -204,7 +201,6 @@ export function useAppHotkeys({onToggleRecording,onGroupSelection,onUngroupSelection,- leftSidebarRef,domEditSelectionRef,showToast,};diff --git a/packages/studio/src/hooks/useDomEditPreviewSync.ts b/packages/studio/src/hooks/useDomEditPreviewSync.tsindex 383c136b50..c36e3b8b45 100644--- a/packages/studio/src/hooks/useDomEditPreviewSync.ts+++ b/packages/studio/src/hooks/useDomEditPreviewSync.ts@@ -6,7 +6,7 @@import { useEffect, useRef } from "react";import { findElementForSelection, type DomEditSelection } from "../components/editor/domEditing";import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";-import type { SidebarTab } from "../components/sidebar/LeftSidebar";+import { useDockLayoutStore } from "../components/dock/dockLayoutStore";import type { PatchTarget } from "../utils/sourcePatcher";import { logSelect } from "../utils/selectDebug";@@ -30,7 +30,6 @@ interface UseDomEditPreviewSyncParams {(iframe: HTMLIFrameElement) => Promise<void>>;openSourceForSelection?: (sourceFile: string, target: PatchTarget) => void;- getSidebarTab?: () => SidebarTab;gsapCacheVersion?: number;}@@ -48,7 +47,6 @@ export function useDomEditPreviewSync({syncPreviewHotkeys,applyStudioManualEditsToPreviewRef,openSourceForSelection,- getSidebarTab,gsapCacheVersion,}: UseDomEditPreviewSyncParams): void {// Sync selection from preview document on load / refresh@@ -142,15 +140,15 @@ export function useDomEditPreviewSync({useEffect(// fallow-ignore-next-line complexity() => {- if (!domEditSelection || !openSourceRef.current || !getSidebarTab) return;+ if (!domEditSelection || !openSourceRef.current) return;if (!domEditSelection.sourceFile) return;- if (getSidebarTab() !== "code") return;+ if (!useDockLayoutStore.getState().visiblePanels.has("code")) return;openSourceRef.current(domEditSelection.sourceFile, {id: domEditSelection.id,selector: domEditSelection.selector,selectorIndex: domEditSelection.selectorIndex,});},- [domEditSelection, getSidebarTab],+ [domEditSelection],);}diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.tsindex e9d4d819a5..a0e982100f 100644--- a/packages/studio/src/hooks/useDomEditSession.ts+++ b/packages/studio/src/hooks/useDomEditSession.ts@@ -5,7 +5,6 @@ import type { TimelineElement } from "../player";import type { ImportedFontAsset } from "../components/editor/fontAssets";import type { RightPanelTab } from "../utils/studioHelpers";import type { PatchTarget } from "../utils/sourcePatcher";-import type { SidebarTab } from "../components/sidebar/LeftSidebar";import type { Composition } from "@hyperframes/sdk";import { sdkCutoverPersist, sdkDeletePersist, type PublishSdkSession } from "../utils/sdkCutover";import { runResolverShadow, recordResolverParity } from "../utils/sdkResolverShadow";@@ -53,8 +52,6 @@ export interface UseDomEditSessionParams extends DomEditTimelineParams {reloadPreview: () => void;setRefreshKey: React.Dispatch<React.SetStateAction<number>>;openSourceForSelection?: (sourceFile: string, target: PatchTarget) => void;- selectSidebarTab?: (tab: SidebarTab) => void;- getSidebarTab?: () => SidebarTab;sdkSession?: Composition | null;publishSdkSession?: PublishSdkSession;forceReloadSdkSession?: () => void;@@ -97,8 +94,6 @@ export function useDomEditSession({reloadPreview,setRefreshKey: _setRefreshKey,openSourceForSelection,- selectSidebarTab,- getSidebarTab,sdkSession,publishSdkSession,forceReloadSdkSession,@@ -430,8 +425,6 @@ export function useDomEditSession({applyDomSelection,buildDomSelectionFromTarget,openSourceForSelection,- selectSidebarTab,- getSidebarTab,updateGsapProperty,updateGsapMeta,deleteGsapAnimation,diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.tsindex 7dc5261085..041634a890 100644--- a/packages/studio/src/hooks/useDomEditWiring.ts+++ b/packages/studio/src/hooks/useDomEditWiring.ts@@ -16,7 +16,7 @@ import { useGsapAnimationFetchFallback } from "./useGsapAnimationFetchFallback";import { useGsapInteractionFailureTelemetry } from "./useGsapInteractionFailureTelemetry";import { useGsapSelectionHandlers } from "./useGsapSelectionHandlers";import type { PatchTarget } from "../utils/sourcePatcher";-import type { SidebarTab } from "../components/sidebar/LeftSidebar";+import { useDockLayoutStore } from "../components/dock/dockLayoutStore";export interface UseDomEditWiringParams {projectId: string | null;@@ -43,8 +43,6 @@ export interface UseDomEditWiringParams {) => void;buildDomSelectionFromTarget: (element: HTMLElement) => Promise<DomEditSelection | null>;openSourceForSelection?: (sourceFile: string, target: PatchTarget) => void;- selectSidebarTab?: (tab: SidebarTab) => void;- getSidebarTab?: () => SidebarTab;// GSAP script commit ops (from useGsapScriptCommits)updateGsapProperty: (sel: DomEditSelection,@@ -132,8 +130,6 @@ export function useDomEditWiring({applyDomSelection,buildDomSelectionFromTarget,openSourceForSelection,- selectSidebarTab,- getSidebarTab,updateGsapProperty,updateGsapMeta,deleteGsapAnimation,@@ -157,16 +153,16 @@ export function useDomEditWiring({const onClickToSource = useCallback((selection: DomEditSelection) => {- if (!openSourceForSelection || !selectSidebarTab) return;+ if (!openSourceForSelection) return;if (!selection.sourceFile) return;- selectSidebarTab("code");+ useDockLayoutStore.getState().activatePanel("code");openSourceForSelection(selection.sourceFile, {id: selection.id,selector: selection.selector,selectorIndex: selection.selectorIndex,});},- [openSourceForSelection, selectSidebarTab],+ [openSourceForSelection],);// ── DOM selection -> timeline element sync ──@@ -267,7 +263,6 @@ export function useDomEditWiring({syncPreviewHotkeys,applyStudioManualEditsToPreviewRef,openSourceForSelection,- getSidebarTab,gsapCacheVersion,});diff --git a/packages/studio/src/hooks/useInspectorSplitResize.ts b/packages/studio/src/hooks/useInspectorSplitResize.tsdeleted file mode 100644index a286563886..0000000000--- a/packages/studio/src/hooks/useInspectorSplitResize.ts+++ /dev/null@@ -1,51 +0,0 @@-import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";--const MIN_INSPECTOR_SPLIT_PERCENT = 20;-const MAX_INSPECTOR_SPLIT_PERCENT = 75;--export function useInspectorSplitResize() {- const [layersPanePercent, setLayersPanePercent] = useState(40);- const splitContainerRef = useRef<HTMLDivElement>(null);- const splitDragRef = useRef<{- startY: number;- startPercent: number;- height: number;- } | null>(null);-- const handleInspectorSplitResizeStart = useCallback(- (event: ReactPointerEvent<HTMLDivElement>) => {- event.preventDefault();- event.currentTarget.setPointerCapture(event.pointerId);- const height = splitContainerRef.current?.getBoundingClientRect().height ?? 0;- splitDragRef.current = {- startY: event.clientY,- startPercent: layersPanePercent,- height,- };- },- [layersPanePercent],- );-- const handleInspectorSplitResizeMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {- const drag = splitDragRef.current;- if (!drag || drag.height <= 0) return;- const deltaPercent = ((event.clientY - drag.startY) / drag.height) * 100;- const next = Math.min(- MAX_INSPECTOR_SPLIT_PERCENT,- Math.max(MIN_INSPECTOR_SPLIT_PERCENT, drag.startPercent + deltaPercent),- );- setLayersPanePercent(next);- }, []);-- const handleInspectorSplitResizeEnd = useCallback(() => {- splitDragRef.current = null;- }, []);-- return {- layersPanePercent,- splitContainerRef,- handleInspectorSplitResizeStart,- handleInspectorSplitResizeMove,- handleInspectorSplitResizeEnd,- };-}diff --git a/packages/studio/src/hooks/usePanelLayout.test.ts b/packages/studio/src/hooks/usePanelLayout.test.tsindex 1a734184f6..1e26c0b6d0 100644--- a/packages/studio/src/hooks/usePanelLayout.test.ts+++ b/packages/studio/src/hooks/usePanelLayout.test.ts@@ -3,338 +3,150 @@import React, { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { readStudioUiPreferences } from "../utils/studioUiPreferences";+import { useDockLayoutStore, type DockController } from "../components/dock/dockLayoutStore";+import { PANEL_IDS, type PanelId } from "../components/dock/panelRegistry";import { trackStudioEvent } from "../utils/studioTelemetry";-import { usePanelLayout } from "./usePanelLayout";+import { usePanelLayout, type InitialPanelLayoutState } from "./usePanelLayout";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));-beforeEach(() => {- vi.mocked(trackStudioEvent).mockClear();- const entries = new Map<string, string>();- Object.defineProperty(window, "localStorage", {- configurable: true,- value: {- get length() {- return entries.size;- },- clear: () => entries.clear(),- getItem: (key: string) => entries.get(key) ?? null,- key: (index: number) => Array.from(entries.keys())[index] ?? null,- removeItem: (key: string) => entries.delete(key),- setItem: (key: string, value: string) => entries.set(key, value),- } satisfies Storage,- });- Object.defineProperty(window, "innerWidth", { configurable: true, value: 1496 });-});+function fakeController(): DockController {+ return {+ open: vi.fn(),+ activate: vi.fn(),+ close: vi.fn(),+ setTitle: vi.fn(),+ setGroupVisible: vi.fn(),+ reset: vi.fn(),+ };+}-afterEach(() => {- document.body.innerHTML = "";- vi.doUnmock("../components/editor/manualEditingAvailability");- vi.resetModules();-});+function showDock(visible: PanelId[], controller = fakeController()) {+ useDockLayoutStore.setState({+ controller,+ openPanels: new Set(PANEL_IDS),+ visiblePanels: new Set(visible),+ lastActive: {},+ activePanel: null,+ });+ return controller;+}-function renderPanelLayoutWith(hook: typeof usePanelLayout) {+function renderLayout(initial?: InitialPanelLayoutState) {const host = document.createElement("div");document.body.append(host);const root = createRoot(host);let current: ReturnType<typeof usePanelLayout> | null = null;-function Harness() {- current = hook();+ current = usePanelLayout(initial);return null;}-- act(() => {- root.render(React.createElement(Harness));- });-+ act(() => root.render(React.createElement(Harness)));return {- getState: (): ReturnType<typeof usePanelLayout> => {- if (!current) throw new Error("usePanelLayout did not render");+ get layout() {+ if (!current) throw new Error("layout not rendered");return current;},unmount: () => act(() => root.unmount()),};}-function renderPanelLayout() {- return renderPanelLayoutWith(usePanelLayout);-}--function resizeWindowTo(width: number) {- Object.defineProperty(window, "innerWidth", { configurable: true, value: width });- window.dispatchEvent(new Event("resize"));-}--describe("usePanelLayout — right inspector panes", () => {- it("opens Design with the intended viewport-scaled panel widths", () => {- const harness = renderPanelLayout();-- expect(harness.getState()).toMatchObject({- leftWidth: 384,- rightWidth: 424,- rightCollapsed: false,- rightPanelTab: "design",- });-- harness.unmount();- });-- it("persists the latest pointer width even before React rerenders", () => {- const harness = renderPanelLayout();- const state = harness.getState();- const target = { setPointerCapture: vi.fn() };-- act(() => {- state.handlePanelResizeStart("left", {- preventDefault: vi.fn(),- target,- pointerId: 1,- clientX: 100,- } as unknown as React.PointerEvent);- state.handlePanelResizeMove({ clientX: 140 } as React.PointerEvent);- state.handlePanelResizeEnd();- });-- expect(harness.getState().leftWidth).toBe(424);- expect(readStudioUiPreferences().leftWidth).toBe(424);- harness.unmount();- });-- it("accumulates and persists rapid keyboard resize steps", () => {- const harness = renderPanelLayout();- const state = harness.getState();-- act(() => {- state.adjustPanelWidth("right", 16);- state.adjustPanelWidth("right", 16);- });-- expect(harness.getState().rightWidth).toBe(456);- expect(readStudioUiPreferences().rightWidth).toBe(456);- harness.unmount();- });-- it("toggleRightInspectorPane independently flips one pane, allowing both open at once", () => {- const harness = renderPanelLayout();- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });-- act(() => harness.getState().toggleRightInspectorPane("layers"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: true, design: true });-- harness.unmount();- });+beforeEach(() => vi.mocked(trackStudioEvent).mockClear());+afterEach(() => {+ document.body.innerHTML = "";+ useDockLayoutStore.setState({ controller: null });+});- it("toggleRightInspectorPane refuses to turn off the last remaining pane", () => {- const harness = renderPanelLayout();- act(() => harness.getState().toggleRightInspectorPane("design"));- // Only "design" was on; toggling it off would leave both false — guarded.- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });- harness.unmount();+describe("usePanelLayout over the dock", () => {+ it("reads the tab of the right-zone panel that is showing", () => {+ showDock(["preview", "timeline", "compositions", "renders"]);+ const view = renderLayout();+ expect(view.layout.rightPanelTab).toBe("renders");+ expect(view.layout.rightCollapsed).toBe(false);});- it("setExclusiveRightInspectorPane is radio-style — selecting one turns the other off", () => {- const harness = renderPanelLayout();- act(() => harness.getState().toggleRightInspectorPane("layers"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: true, design: true });-- act(() => harness.getState().setExclusiveRightInspectorPane("layers"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: true, design: false });-- act(() => harness.getState().setExclusiveRightInspectorPane("design"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });-- harness.unmount();+ it("is collapsed when no right-zone panel is showing", () => {+ showDock(["preview", "timeline", "compositions"]);+ const view = renderLayout();+ expect(view.layout.rightCollapsed).toBe(true);+ expect(view.layout.rightPanelTab).toBe("design");});- it("setRightPanelTab additively opens a pane when the flat inspector is off (legacy behavior)", async () => {- vi.resetModules();- vi.doMock("../components/editor/manualEditingAvailability", async () => {- const actual = await vi.importActual<- typeof import("../components/editor/manualEditingAvailability")- >("../components/editor/manualEditingAvailability");- return { ...actual, STUDIO_FLAT_INSPECTOR_ENABLED: false };+ it("opens the Design panel for the legacy block-params tab and reports the tab switch", () => {+ const controller = showDock(["preview"]);+ const view = renderLayout();+ act(() => view.layout.setRightPanelTab("block-params"));+ expect(controller.setGroupVisible).toHaveBeenCalledWith("design", true);+ expect(controller.activate).toHaveBeenCalledWith("design");+ expect(trackStudioEvent).toHaveBeenCalledWith("tab_switch", {+ panel: "right_panel",+ tab: "block-params",});- const { usePanelLayout: usePanelLayoutFlatOff } = await import("./usePanelLayout");- const harness = renderPanelLayoutWith(usePanelLayoutFlatOff);- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });-- act(() => harness.getState().setRightPanelTab("layers"));- // Legacy (split-view) behavior: additive, both panes end up open.- expect(harness.getState().rightInspectorPanes).toEqual({ layers: true, design: true });-- harness.unmount();});- it("tracks only actual right-panel tab changes, including rapid repeated calls", () => {- const harness = renderPanelLayout();-- act(() => {- harness.getState().setRightPanelTab("design");- harness.getState().setRightPanelTab("design");- });+ it("reports a tab switch only when the tab actually changes", () => {+ showDock(["preview", "design"]);+ const view = renderLayout();+ vi.mocked(trackStudioEvent).mockClear();+ act(() => view.layout.setRightPanelTab("design"));expect(trackStudioEvent).not.toHaveBeenCalled();-- act(() => {- harness.getState().setRightPanelTab("layers");- harness.getState().setRightPanelTab("layers");- });- expect(trackStudioEvent).toHaveBeenCalledOnce();+ act(() => view.layout.setRightPanelTab("layers"));expect(trackStudioEvent).toHaveBeenCalledWith("tab_switch", {panel: "right_panel",tab: "layers",});- expect(harness.getState().rightPanelTab).toBe("layers");-- harness.unmount();- });-- it("caps a panel relative to the window instead of at a flat 600px", () => {- resizeWindowTo(700);- const harness = renderPanelLayout();- // The old flat cap let the inspector claim 600 of a 700px window.- expect(harness.getState().rightWidth).toBeLessThanOrEqual(280);- harness.unmount();- });-- it("rails both panels once the window cannot fit them", () => {- resizeWindowTo(560);- const harness = renderPanelLayout();- expect(harness.getState()).toMatchObject({- effectiveLeftCollapsed: true,- effectiveRightCollapsed: true,- leftCollapsed: false,- rightCollapsed: false,- });- harness.unmount();- });-- it("auto-collapse never writes the user's persisted or URL-synced intent", () => {- const harness = renderPanelLayout();- act(() => resizeWindowTo(560));-- expect(harness.getState().effectiveLeftCollapsed).toBe(true);- // localStorage carries leftCollapsed; the shareable URL carries rightCollapsed.- // A ten-second window drag must rewrite neither.- expect(readStudioUiPreferences().leftCollapsed).toBeUndefined();- expect(harness.getState().leftCollapsed).toBe(false);- expect(harness.getState().rightCollapsed).toBe(false);- harness.unmount();- });-- it("returns the user's own width when the window grows back", () => {- const harness = renderPanelLayout();- const wide = harness.getState().leftWidth;-- act(() => resizeWindowTo(560));- expect(harness.getState().leftWidth).toBeLessThan(wide);-- act(() => resizeWindowTo(1496));- expect(harness.getState().leftWidth).toBe(wide);- harness.unmount();- });-- it("keeps an explicitly collapsed sidebar collapsed after a narrow trip", () => {- const harness = renderPanelLayout();- act(() => harness.getState().toggleLeftSidebar());- expect(readStudioUiPreferences().leftCollapsed).toBe(true);-- act(() => resizeWindowTo(560));- act(() => resizeWindowTo(1496));-- expect(harness.getState().effectiveLeftCollapsed).toBe(true);- harness.unmount();- });-- it("lets the user reopen a panel the window auto-collapsed", () => {- const harness = renderPanelLayout();- act(() => resizeWindowTo(560));- expect(harness.getState().effectiveRightCollapsed).toBe(true);-- // Without this the header Inspector button would be dead below 700px.- act(() => harness.getState().setRightCollapsed(false));- expect(harness.getState().effectiveRightCollapsed).toBe(false);- harness.unmount();});- it("opens the sidebar when the rail's own button is clicked", () => {- const harness = renderPanelLayout();- act(() => resizeWindowTo(560));- expect(harness.getState().effectiveLeftCollapsed).toBe(true);-- // Regression: the toggle used to flip stored INTENT, which was already- // false here, so the click persisted leftCollapsed=true and the rail stayed- // railed — a dead button that silently saved a collapse nobody asked for.- act(() => harness.getState().toggleLeftSidebar());-- expect(harness.getState().effectiveLeftCollapsed).toBe(false);- expect(harness.getState().leftCollapsed).toBe(false);- expect(readStudioUiPreferences().leftCollapsed).toBe(false);- // And it gets a real width: rendering an expanded sidebar at the 42px rail- // width would squash its own content. Only a real-UI click caught this.- expect(harness.getState().leftWidth).toBeGreaterThanOrEqual(200);- harness.unmount();- });-- it("closes the sidebar again on the next click", () => {- const harness = renderPanelLayout();- act(() => resizeWindowTo(560));- act(() => harness.getState().toggleLeftSidebar());- act(() => harness.getState().toggleLeftSidebar());-- expect(harness.getState().effectiveLeftCollapsed).toBe(true);- expect(readStudioUiPreferences().leftCollapsed).toBe(true);- harness.unmount();- });-- it("forgets that reopen once the window is wide again", () => {- const harness = renderPanelLayout();- act(() => resizeWindowTo(560));- act(() => harness.getState().setRightCollapsed(false));- expect(harness.getState().effectiveRightCollapsed).toBe(false);-- // Widening past the threshold clears the override, so a later narrow trip- // rails again rather than staying open forever off one old click.- act(() => resizeWindowTo(1496));- act(() => resizeWindowTo(560));- expect(harness.getState().effectiveRightCollapsed).toBe(true);- harness.unmount();- });-- it("setRightPanelTab is flat-aware: exclusivity holds for callers other than a direct in-panel tab click", async () => {- vi.resetModules();- vi.doMock("../components/editor/manualEditingAvailability", async () => {- const actual = await vi.importActual<- typeof import("../components/editor/manualEditingAvailability")- >("../components/editor/manualEditingAvailability");- return { ...actual, STUDIO_FLAT_INSPECTOR_ENABLED: true };- });- const { usePanelLayout: usePanelLayoutFlatOn } = await import("./usePanelLayout");- const harness = renderPanelLayoutWith(usePanelLayoutFlatOn);- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });-- // The flat inspector can change its visible pane without changing the- // umbrella rightPanelTab value. A later element selection must still bring- // Design back even though rightPanelTab already says "design".- act(() => harness.getState().setExclusiveRightInspectorPane("layers"));- expect(harness.getState()).toMatchObject({- rightPanelTab: "design",- rightInspectorPanes: { layers: true, design: false },- });- act(() => harness.getState().setRightPanelTab("design"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: false, design: true });-- // Element-select / block-params-close / header Inspector-button callers- // all reach setRightPanelTab directly, not through the in-panel tab- // click's own setExclusiveRightInspectorPane call — this must still- // enforce exclusivity under the flat flag, or both tabs end up- // highlighted while only one pane actually renders.- act(() => harness.getState().setRightPanelTab("layers"));- expect(harness.getState().rightInspectorPanes).toEqual({ layers: true, design: false });-- harness.unmount();+ it("collapses every open right-zone panel group and leaves the other zones alone", () => {+ const controller = showDock(["preview", "design"]);+ const view = renderLayout();+ act(() => view.layout.setRightCollapsed(true));+ const hidden = vi.mocked(controller.setGroupVisible).mock.calls;+ expect(hidden.map(([id]) => id).sort()).toEqual(+ ["design", "layers", "renders", "slideshow", "variables"].sort(),+ );+ expect(hidden.every(([, visible]) => visible === false)).toBe(true);+ });++ it("expanding an already-showing right column does nothing to the tab", () => {+ const controller = showDock(["design"]);+ const view = renderLayout();+ act(() => view.layout.setRightCollapsed(false));+ expect(controller.activate).not.toHaveBeenCalled();+ });++ it("expanding a fully hidden right column brings Design back", () => {+ const controller = showDock(["preview"]);+ const view = renderLayout();+ act(() => view.layout.setRightCollapsed(false));+ expect(controller.activate).toHaveBeenCalledWith("design");+ });++ it("applies the URL's tab and collapse state once, when the dock attaches", () => {+ useDockLayoutStore.setState({ controller: null, openPanels: new Set(PANEL_IDS) });+ const view = renderLayout({ rightPanelTab: "variables", rightCollapsed: true });+ const controller = fakeController();+ act(() => useDockLayoutStore.getState().attach(controller));+ expect(controller.activate).toHaveBeenCalledWith("variables");+ expect(controller.setGroupVisible).toHaveBeenCalledWith("design", false);+ const later = fakeController();+ act(() => useDockLayoutStore.getState().attach(later));+ expect(later.activate).not.toHaveBeenCalled();+ expect(later.setGroupVisible).not.toHaveBeenCalled();+ view.unmount();+ });++ it("keeps a URL's slideshow tab until the panel opens, then activates it once", () => {+ const opened = new Set<PanelId>(PANEL_IDS.filter((id) => id !== "slideshow"));+ useDockLayoutStore.setState({ controller: null, openPanels: opened });+ const view = renderLayout({ rightPanelTab: "slideshow" });+ const controller = fakeController();+ act(() => useDockLayoutStore.getState().attach(controller));+ expect(controller.activate).not.toHaveBeenCalled();+ act(() => useDockLayoutStore.setState({ openPanels: new Set(PANEL_IDS) }));+ expect(controller.activate).toHaveBeenCalledWith("slideshow");+ view.unmount();});});diff --git a/packages/studio/src/hooks/usePanelLayout.ts b/packages/studio/src/hooks/usePanelLayout.tsindex 692775acae..ddeda8f120 100644--- a/packages/studio/src/hooks/usePanelLayout.ts+++ b/packages/studio/src/hooks/usePanelLayout.ts@@ -1,275 +1,70 @@-import { useState, useCallback, useRef, useEffect } from "react";-import type {- RightInspectorPane,- RightInspectorPanes,- RightPanelTab,-} from "../utils/studioHelpers";-import { readStudioUiPreferences, writeStudioUiPreferences } from "../utils/studioUiPreferences";+import { useCallback, useEffect, useRef } from "react";+import type { RightPanelTab } from "../utils/studioHelpers";import { trackStudioEvent } from "../utils/studioTelemetry";-import { STUDIO_FLAT_INSPECTOR_ENABLED } from "../components/editor/manualEditingAvailability";-import {- defaultPanelWidths,- fitPanelWidths,- railsEngaged,- type PanelWidths,-} from "../utils/fitPanels";--const NO_OVERRIDE = { left: false, right: false } as const;+import { useDockLayoutStore, visiblePanelInZone } from "../components/dock/dockLayoutStore";+import { PANEL_DEFINITIONS, type PanelId } from "../components/dock/panelRegistry";export interface InitialPanelLayoutState {rightCollapsed?: boolean | null;rightPanelTab?: RightPanelTab | null;}-type PanelSide = "left" | "right";--function getInitialRightInspectorPanes(tab?: RightPanelTab | null): RightInspectorPanes {- if (tab === "layers") return { layers: true, design: false };- return { layers: false, design: true };-}--function readViewportWidth(): number {- return typeof window === "undefined" ? 1496 : window.innerWidth;+/** The dock panel each legacy right-panel tab name opens; block params render inside Design. */+function panelForTab(tab: RightPanelTab): PanelId {+ return tab === "block-params" ? "design" : tab;}-/**- * What the user WANTS each panel to be, before the window gets a say. Stored- * preferences win over the width-derived defaults; neither is clamped here —- * `fitPanelWidths` owns every clamp so there is one place that decides.- */-function getPreferredPanelWidths(): PanelWidths {- const preferences = readStudioUiPreferences();- const defaults = defaultPanelWidths(readViewportWidth());- return {- left: preferences.leftWidth ?? defaults.left,- right: preferences.rightWidth ?? defaults.right,- };+function tabForPanel(id: PanelId | null): RightPanelTab {+ return id !== null && PANEL_DEFINITIONS[id].zone === "right" ? (id as RightPanelTab) : "design";}+/** The right column as the rest of Studio reads it, backed by the dock's panel state. */export function usePanelLayout(initialState?: InitialPanelLayoutState) {- const [preferredWidths, setPreferredWidths] = useState(getPreferredPanelWidths);- const [viewportWidth, setViewportWidth] = useState(readViewportWidth);- const [leftCollapsed, setLeftCollapsed] = useState(- () => readStudioUiPreferences().leftCollapsed ?? false,- );- const [rightCollapsed, setRightCollapsed] = useState(initialState?.rightCollapsed ?? false);- const [rightPanelTab, setRightPanelTab] = useState<RightPanelTab>(- initialState?.rightPanelTab ?? "design",- );- const rightPanelTabRef = useRef(rightPanelTab);- rightPanelTabRef.current = rightPanelTab;- const [rightInspectorPanes, setRightInspectorPanes] = useState<RightInspectorPanes>(() =>- getInitialRightInspectorPanes(initialState?.rightPanelTab),- );- const rightInspectorPanesRef = useRef(rightInspectorPanes);- rightInspectorPanesRef.current = rightInspectorPanes;- // Set when the user explicitly reopens a panel the window had auto-collapsed,- // so the rail cannot immediately swallow it again. Cleared once the window is- // wide enough that auto-collapse is no longer in play.- const [autoCollapseOverride, setAutoCollapseOverride] = useState<{- left: boolean;- right: boolean;- }>(NO_OVERRIDE);+ const controller = useDockLayoutStore((state) => state.controller);+ const lastActive = useDockLayoutStore((state) => state.lastActive);+ const visiblePanels = useDockLayoutStore((state) => state.visiblePanels);- // Reconciliation is a live window resize away, not a mount-time snapshot: a- // Studio loaded at 1440 and dragged to a half-screen used to keep its pixel- // widths and squeeze the preview to nothing.+ const initialRef = useRef(initialState);useEffect(() => {- if (typeof window === "undefined") return;- const handleResize = () => {- const width = window.innerWidth;- setViewportWidth(width);- // Cleared here rather than in an effect watching derived state: the rail- // flags depend only on width, and width only changes in this handler.- if (!railsEngaged(width)) {- setAutoCollapseOverride((prev) => (prev.left || prev.right ? NO_OVERRIDE : prev));- }- };- window.addEventListener("resize", handleResize);- return () => window.removeEventListener("resize", handleResize);- }, []);-- const fitted = fitPanelWidths(viewportWidth, preferredWidths, autoCollapseOverride);- const leftCollapsedByWidth = fitted.autoCollapseLeft;- const rightCollapsedByWidth = fitted.autoCollapseRight;-- // Rendered widths, which the drag handles measure from so the seam does not- // jump when a panel is currently narrower than its stored preference.- const fittedRef = useRef(fitted);- fittedRef.current = fitted;-- const panelDragRef = useRef<{- side: PanelSide;- startX: number;- startW: number;- } | null>(null);-- // Preferred widths are also held in a ref so a burst of pointer moves or- // keyboard nudges inside one React batch accumulates, instead of every call- // in the batch reading the same pre-render value.- const preferredRef = useRef(preferredWidths);-- const setPreferred = useCallback((side: PanelSide, width: number) => {- const next = Math.max(0, Math.round(width));- preferredRef.current = { ...preferredRef.current, [side]: next };- setPreferredWidths(preferredRef.current);- return next;- }, []);-- /** Transient: moves the panel without touching the stored preference. */- const updatePanelWidth = useCallback(- (side: PanelSide, width: number) => {- setPreferred(side, width);- },- [setPreferred],- );-- /**- * Durable: only an explicit drag or keyboard nudge writes a preference. A- * width the window forced on us is never persisted, so the user's real- * preference survives a temporary squeeze and returns when the window grows.- */- const commitPanelWidth = useCallback(- (side: PanelSide, width: number) => {- // Persist what the window will actually allow, not a raw pointer delta.- const candidate = { ...preferredRef.current, [side]: Math.max(0, Math.round(width)) };- const settled = fitPanelWidths(readViewportWidth(), candidate)[side];- setPreferred(side, settled);- writeStudioUiPreferences(side === "left" ? { leftWidth: settled } : { rightWidth: settled });- },- [setPreferred],- );-- const adjustPanelWidth = useCallback(- (side: PanelSide, delta: number) => {- commitPanelWidth(side, preferredRef.current[side] + delta);- },- [commitPanelWidth],- );-- // The toggle acts on what the user can SEE, not on stored intent. Toggling- // stored intent instead made the rail's "Show sidebar" button dead in the- // auto-collapsed state: intent was already false, so the click flipped it to- // true (persisting a collapse the user never asked for) while the rail stayed- // railed and nothing visibly happened.- const effectiveLeftCollapsedRef = useRef(false);- effectiveLeftCollapsedRef.current = leftCollapsed || leftCollapsedByWidth;-- const toggleLeftSidebar = useCallback(() => {- const next = !effectiveLeftCollapsedRef.current;- setLeftCollapsed(next);- writeStudioUiPreferences({ leftCollapsed: next });- trackStudioEvent("panel_toggle", { panel: "left_sidebar", collapsed: next });- if (!next) setAutoCollapseOverride((prev) => ({ ...prev, left: true }));- }, []);-- const setRightCollapsedWithOverride = useCallback((collapsed: boolean) => {- setRightCollapsed(collapsed);- if (!collapsed) {- setAutoCollapseOverride((prev) => (prev.right ? prev : { ...prev, right: true }));+ if (!controller) return;+ const { rightCollapsed, rightPanelTab } = initialRef.current ?? {};+ initialRef.current = undefined;+ const store = useDockLayoutStore.getState();+ const wanted = rightPanelTab ? panelForTab(rightPanelTab) : null;+ let unsubscribe = () => {};+ if (wanted && store.openPanels.has(wanted)) {+ store.activatePanel(wanted);+ } else if (wanted === "slideshow") {+ // The slideshow panel only opens once the composition loads and turns out to be one.+ unsubscribe = useDockLayoutStore.subscribe((state) => {+ if (!state.openPanels.has("slideshow")) return;+ unsubscribe();+ state.activatePanel("slideshow");+ });}+ if (rightCollapsed != null) store.setZoneVisible("right", !rightCollapsed);+ return () => unsubscribe();+ }, [controller]);++ const visibleRight = visiblePanelInZone("right", lastActive, visiblePanels);+ const rightPanelTab = tabForPanel(visibleRight);+ const rightCollapsed = visibleRight === null;++ const setRightPanelTab = useCallback((tab: RightPanelTab) => {+ const store = useDockLayoutStore.getState();+ const shown = visiblePanelInZone("right", store.lastActive, store.visiblePanels);+ store.activatePanel(panelForTab(tab));+ if (tabForPanel(shown) !== tab) trackStudioEvent("tab_switch", { panel: "right_panel", tab });}, []);- const handlePanelResizeStart = useCallback((side: PanelSide, e: React.PointerEvent) => {- e.preventDefault();- (e.target as HTMLElement).setPointerCapture(e.pointerId);- panelDragRef.current = {- side,- startX: e.clientX,- startW: fittedRef.current[side],- };- }, []);-- const handlePanelResizeMove = useCallback(- (e: React.PointerEvent) => {- const drag = panelDragRef.current;- if (!drag) return;- const delta = e.clientX - drag.startX;- updatePanelWidth(drag.side, drag.startW + (drag.side === "left" ? delta : -delta));- },- [updatePanelWidth],- );-- const handlePanelResizeEnd = useCallback(() => {- const side = panelDragRef.current?.side;- if (side) commitPanelWidth(side, preferredRef.current[side]);- panelDragRef.current = null;- }, [commitPanelWidth]);-- const trackedSetRightPanelTab = useCallback(- (tab: RightPanelTab) => {- const paneAlreadySelected =- tab !== "design" && tab !== "layers"- ? true- : STUDIO_FLAT_INSPECTOR_ENABLED- ? rightInspectorPanesRef.current[tab] &&- !rightInspectorPanesRef.current[tab === "design" ? "layers" : "design"]- : rightInspectorPanesRef.current[tab];- if (rightPanelTabRef.current === tab && paneAlreadySelected) return;- rightPanelTabRef.current = tab;- if (tab === "design" || tab === "layers") {- // Flat inspector: Layers always renders full-height by itself (see- // StudioRightPanel's render gate), so this MUST land on the same- // radio-style exclusivity setExclusiveRightInspectorPane enforces for- // the direct in-panel tab click — every OTHER path that reaches here- // (element select, closing block-params, the header Inspector- // button, and this function's own callers outside an active- // inspector tab) would otherwise additively leave both panes `true`- // and reproduce the "both tabs highlight, only one renders" bug this- // still-additive branch used to cause under the flat flag.- const nextPanes = STUDIO_FLAT_INSPECTOR_ENABLED- ? { design: tab === "design", layers: tab === "layers" }- : { ...rightInspectorPanesRef.current, [tab]: true };- rightInspectorPanesRef.current = nextPanes;- setRightInspectorPanes(nextPanes);- }- setRightPanelTab(tab);- trackStudioEvent("tab_switch", { panel: "right_panel", tab });- },- [setRightPanelTab],- );-- const toggleRightInspectorPane = useCallback((pane: RightInspectorPane) => {- setRightInspectorPanes((panes) => {- const next = { ...panes, [pane]: !panes[pane] };- if (!next.design && !next.layers) return panes;- return next;- });- }, []);-- // Radio-style variant for the flat inspector: Layers always renders full-- // height by itself there (never split-shared with Design), so leaving both- // panes independently toggleable would highlight both tabs as "active"- // while only one actually shows. Selecting one turns the other off.- const setExclusiveRightInspectorPane = useCallback((pane: RightInspectorPane) => {- setRightInspectorPanes({ design: pane === "design", layers: pane === "layers" });+ const setRightCollapsed = useCallback((collapsed: boolean) => {+ const store = useDockLayoutStore.getState();+ if (!collapsed && visiblePanelInZone("right", store.lastActive, store.visiblePanels) === null) {+ store.activatePanel("design");+ return;+ }+ store.setZoneVisible("right", !collapsed);}, []);- return {- leftWidth: fitted.left,- rightWidth: fitted.right,- adjustPanelWidth,- /**- * User intent. Persisted to localStorage; never written by auto-collapse.- * Deliberately read-only outside this hook: `toggleLeftSidebar` is the only- * writer, so it cannot be flipped without also clearing the rail override- * (which would open the sidebar and then immediately rail it again).- */- leftCollapsed,- /** User intent. Synced into the shareable URL; never written by auto-collapse. */- rightCollapsed,- setRightCollapsed: setRightCollapsedWithOverride,- /** What the shell actually renders: intent OR the window forcing a rail. */- effectiveLeftCollapsed: leftCollapsed || leftCollapsedByWidth,- effectiveRightCollapsed: rightCollapsed || rightCollapsedByWidth,- rightPanelTab,- setRightPanelTab: trackedSetRightPanelTab,- rightInspectorPanes,- toggleRightInspectorPane,- setExclusiveRightInspectorPane,- toggleLeftSidebar,- handlePanelResizeStart,- handlePanelResizeMove,- handlePanelResizeEnd,- };+ return { rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab };}diff --git a/packages/studio/src/hooks/useRightPanelIntents.test.ts b/packages/studio/src/hooks/useRightPanelIntents.test.tsnew file mode 100644index 0000000000..df0bb31a24--- /dev/null+++ b/packages/studio/src/hooks/useRightPanelIntents.test.ts@@ -0,0 +1,181 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useDockLayoutStore, type DockController } from "../components/dock/dockLayoutStore";+import { PANEL_IDS, type PanelId } from "../components/dock/panelRegistry";+import {+ useBlockParamsDismissal,+ useCaptionDesignFocus,+ useDismissingTabSetter,+ useRightPanelIntent,+ useSlideshowDockPanel,+} from "./useRightPanelIntents";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++function controllerMock(): DockController {+ return {+ open: vi.fn(),+ activate: vi.fn(),+ close: vi.fn(),+ setTitle: vi.fn(),+ setGroupVisible: vi.fn(),+ reset: vi.fn(),+ };+}++function seed(state: {+ open?: PanelId[];+ visible?: PanelId[];+ lastActive?: Partial<Record<"left" | "center" | "right", PanelId>>;+}) {+ const controller = controllerMock();+ useDockLayoutStore.setState({+ controller,+ openPanels: new Set(state.open ?? PANEL_IDS.filter((id) => id !== "slideshow")),+ visiblePanels: new Set(state.visible ?? []),+ lastActive: state.lastActive ?? {},+ activePanel: null,+ });+ return controller;+}++const mountedRoots: Array<() => void> = [];++function mountHook<P>(hook: (props: P) => unknown, initial: P) {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ mountedRoots.push(() => act(() => root.unmount()));+ let latest: unknown;+ function Harness({ props }: { props: P }) {+ latest = hook(props);+ return null;+ }+ const render = (props: P) => act(() => root.render(React.createElement(Harness, { props })));+ render(initial);+ return { render, value: () => latest, unmount: () => act(() => root.unmount()) };+}++afterEach(() => {+ for (const unmount of mountedRoots.splice(0)) unmount();+ vi.restoreAllMocks();+ document.body.innerHTML = "";+ useDockLayoutStore.setState({ controller: null });+});++describe("useSlideshowDockPanel", () => {+ it("opens the panel when the file becomes a slideshow and closes it when it stops", () => {+ const controller = seed({});+ const view = mountHook(useSlideshowDockPanel, false);+ expect(controller.open).not.toHaveBeenCalled();+ view.render(true);+ expect(controller.open).toHaveBeenCalledWith("slideshow");+ act(() =>+ useDockLayoutStore.setState({ openPanels: new Set<PanelId>(["design", "slideshow"]) }),+ );+ view.render(false);+ expect(controller.close).toHaveBeenCalledWith("slideshow");+ });++ it("keeps a restored slideshow placement while the file is still loading", () => {+ const controller = seed({ open: ["design", "slideshow"] });+ const view = mountHook(useSlideshowDockPanel, false);+ expect(controller.close).not.toHaveBeenCalled();+ view.render(true);+ expect(controller.open).not.toHaveBeenCalled();+ view.render(false);+ expect(controller.close).toHaveBeenCalledWith("slideshow");+ });++ it("leaves a slideshow panel that a restored layout already holds alone", () => {+ const controller = seed({ open: ["design", "slideshow"] });+ mountHook(useSlideshowDockPanel, true);+ expect(controller.open).not.toHaveBeenCalled();+ });++ it("waits for the dock to mount, then opens the panel once", () => {+ const controller = seed({});+ useDockLayoutStore.setState({ controller: null });+ mountHook(useSlideshowDockPanel, true);+ expect(controller.open).not.toHaveBeenCalled();+ act(() => useDockLayoutStore.setState({ controller }));+ expect(controller.open).toHaveBeenCalledWith("slideshow");+ });++ it("does not reopen a panel the user closed while the file is still a slideshow", () => {+ const controller = seed({});+ const view = mountHook(useSlideshowDockPanel, true);+ expect(controller.open).toHaveBeenCalledTimes(1);+ act(() => useDockLayoutStore.setState({ openPanels: new Set<PanelId>(["design"]) }));+ view.render(true);+ expect(controller.open).toHaveBeenCalledTimes(1);+ });+});++describe("useBlockParamsDismissal", () => {+ const props = { hasBlockParams: true, onDismiss: vi.fn() };++ it("keeps block params while the Design panel is showing", () => {+ seed({ visible: ["design"] });+ const onDismiss = vi.fn();+ mountHook(useBlockParamsDismissal, { ...props, onDismiss });+ expect(onDismiss).not.toHaveBeenCalled();+ });++ it("dismisses block params when the Design panel is no longer showing", () => {+ seed({ visible: ["design"] });+ const onDismiss = vi.fn();+ mountHook(useBlockParamsDismissal, { ...props, onDismiss });+ act(() => useDockLayoutStore.setState({ visiblePanels: new Set<PanelId>(["layers"]) }));+ expect(onDismiss).toHaveBeenCalled();+ });+});++describe("useDismissingTabSetter", () => {+ it("dismisses block params for any tab but block-params, then switches", () => {+ const setTab = vi.fn();+ const dismiss = vi.fn();+ const view = mountHook(+ ({ tab }: { tab: string }) => {+ const set = useDismissingTabSetter(setTab, dismiss);+ return () => set(tab);+ },+ { tab: "design" },+ );+ (view.value() as () => void)();+ expect(dismiss).toHaveBeenCalledTimes(1);+ expect(setTab).toHaveBeenCalledWith("design");+ view.render({ tab: "block-params" });+ (view.value() as () => void)();+ expect(dismiss).toHaveBeenCalledTimes(1);+ expect(setTab).toHaveBeenLastCalledWith("block-params");+ });+});++describe("useCaptionDesignFocus", () => {+ it("brings Design forward when caption editing starts over another right panel", () => {+ seed({ visible: ["layers"], lastActive: { right: "layers" } });+ const view = mountHook(useCaptionDesignFocus, false);+ const activate = vi.spyOn(useDockLayoutStore.getState(), "activatePanel");+ view.render(true);+ expect(activate).toHaveBeenCalledWith("design");+ });++ it("leaves a collapsed right column alone", () => {+ seed({ visible: [], lastActive: { right: "layers" } });+ const activate = vi.spyOn(useDockLayoutStore.getState(), "activatePanel");+ mountHook(useCaptionDesignFocus, true);+ expect(activate).not.toHaveBeenCalled();+ });+});++describe("useRightPanelIntent", () => {+ it("still names the inspector panel while the right column is collapsed", () => {+ seed({ visible: [], lastActive: { right: "design" } });+ const view = mountHook(useRightPanelIntent, undefined);+ expect(view.value()).toBe("design");+ });+});diff --git a/packages/studio/src/hooks/useRightPanelIntents.ts b/packages/studio/src/hooks/useRightPanelIntents.tsnew file mode 100644index 0000000000..5d1c8c4541--- /dev/null+++ b/packages/studio/src/hooks/useRightPanelIntents.ts@@ -0,0 +1,64 @@+import { useCallback, useEffect, useRef } from "react";+import { useDockLayoutStore, visiblePanelInZone } from "../components/dock/dockLayoutStore";++/** Opens the Slideshow panel when the file becomes a slideshow, closes it when it stops being one.+ * A user's own close, and a restored layout's placement, stick. */+export function useSlideshowDockPanel(isSlideshowComposition: boolean) {+ const controller = useDockLayoutStore((state) => state.controller);+ const wasSlideshow = useRef(false);+ useEffect(() => {+ if (!controller) return;+ const inDock = useDockLayoutStore.getState().openPanels.has("slideshow");+ if (isSlideshowComposition && !inDock) controller.open("slideshow");+ if (!isSlideshowComposition && wasSlideshow.current && inDock) controller.close("slideshow");+ wasSlideshow.current = isSlideshowComposition;+ }, [isSlideshowComposition, controller]);+}++/** Block params replace the Design body until Design stops showing; picking another tab dismisses them elsewhere. */+export function useBlockParamsDismissal({+ hasBlockParams,+ onDismiss,+}: {+ hasBlockParams: boolean;+ onDismiss: () => void;+}) {+ const designVisible = useDockLayoutStore((state) => state.visiblePanels.has("design"));+ useEffect(() => {+ if (hasBlockParams && !designVisible) onDismiss();+ }, [hasBlockParams, designVisible, onDismiss]);+}++/** Wraps a tab setter so any tab other than block-params first dismisses the block-params view. */+export function useDismissingTabSetter<Tab extends string>(+ setTab: (tab: Tab) => void,+ dismissBlockParams: () => void,+) {+ return useCallback(+ (tab: Tab) => {+ if (tab !== "block-params") dismissBlockParams();+ setTab(tab);+ },+ [setTab, dismissBlockParams],+ );+}++/** Caption edit mode owns the Design panel: whenever the right column shows something else, bring Design back. */+export function useCaptionDesignFocus(captionEditMode: boolean) {+ const designVisible = useDockLayoutStore((state) => state.visiblePanels.has("design"));+ const rightShown = useDockLayoutStore(+ (state) => visiblePanelInZone("right", state.lastActive, state.visiblePanels) !== null,+ );+ useEffect(() => {+ if (captionEditMode && rightShown && !designVisible) {+ useDockLayoutStore.getState().activatePanel("design");+ }+ }, [captionEditMode, rightShown, designVisible]);+}++/** The right-column panel the user last focused, whether or not the column is currently showing. */+export function useRightPanelIntent() {+ return useDockLayoutStore((state) =>+ visiblePanelInZone("right", state.lastActive, state.openPanels),+ );+}diff --git a/packages/studio/src/hooks/useSlideshowTabState.test.ts b/packages/studio/src/hooks/useSlideshowTabState.test.tsindex be45f448b2..8665f00e17 100644--- a/packages/studio/src/hooks/useSlideshowTabState.test.ts+++ b/packages/studio/src/hooks/useSlideshowTabState.test.ts@@ -4,7 +4,6 @@ import React, { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, describe, expect, it } from "vitest";import { useSlideshowTabState } from "./useSlideshowTabState";-import type { RightPanelTab } from "../utils/studioHelpers";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -15,14 +14,10 @@ afterEach(() => {document.body.innerHTML = "";});-function renderHook(params: {- editingFileContent: string | null | undefined;- rightPanelTab: RightPanelTab;-}) {+function renderHook(params: { editingFileContent: string | null | undefined }) {const host = document.createElement("div");document.body.append(host);const root = createRoot(host);- const setRightPanelTabCalls: RightPanelTab[] = [];let current: ReturnType<typeof useSlideshowTabState> | null = null;function Harness() {@@ -30,8 +25,7 @@ function renderHook(params: {editingFileContent: params.editingFileContent,previewIframeRef: { current: null },refreshKey: 0,- rightPanelTab: params.rightPanelTab,- setRightPanelTab: (tab) => setRightPanelTabCalls.push(tab),+ slideshowVisible: false,});return null;}@@ -45,52 +39,36 @@ function renderHook(params: {if (!current) throw new Error("useSlideshowTabState did not render");return current;},- setRightPanelTabCalls,unmount: () => act(() => root.unmount()),};}+// Whether "slideshow" stays the active dock tab across a file switch is+// StudioRightPanels' own effect now (it opens/closes the dock panel), not+// this hook's job — this only derives the two values that effect reads.describe("useSlideshowTabState", () => {it("detects a slideshow composition via the JSON island", () => {- const harness = renderHook({ editingFileContent: SLIDESHOW_HTML, rightPanelTab: "design" });+ const harness = renderHook({ editingFileContent: SLIDESHOW_HTML });expect(harness.getState().isSlideshowComposition).toBe(true);harness.unmount();});it("reports false for a plain (non-slideshow) composition", () => {- const harness = renderHook({ editingFileContent: PLAIN_HTML, rightPanelTab: "design" });+ const harness = renderHook({ editingFileContent: PLAIN_HTML });expect(harness.getState().isSlideshowComposition).toBe(false);harness.unmount();});it("reports false when there is no editing file yet", () => {- const harness = renderHook({ editingFileContent: undefined, rightPanelTab: "design" });+ const harness = renderHook({ editingFileContent: undefined });expect(harness.getState().isSlideshowComposition).toBe(false);harness.unmount();});it("still detects a malformed island — presence-only, not full manifest validation", () => {const malformed = `<html><body><script type="application/hyperframes-slideshow+json">{not valid json</script></body></html>`;- const harness = renderHook({ editingFileContent: malformed, rightPanelTab: "design" });+ const harness = renderHook({ editingFileContent: malformed });expect(harness.getState().isSlideshowComposition).toBe(true);harness.unmount();});-- it("bounces rightPanelTab off 'slideshow' to 'renders' on a non-slideshow composition", () => {- const harness = renderHook({ editingFileContent: PLAIN_HTML, rightPanelTab: "slideshow" });- expect(harness.setRightPanelTabCalls).toEqual(["renders"]);- harness.unmount();- });-- it("does not bounce when the composition is a slideshow", () => {- const harness = renderHook({ editingFileContent: SLIDESHOW_HTML, rightPanelTab: "slideshow" });- expect(harness.setRightPanelTabCalls).toEqual([]);- harness.unmount();- });-- it("does not bounce a tab other than 'slideshow'", () => {- const harness = renderHook({ editingFileContent: PLAIN_HTML, rightPanelTab: "renders" });- expect(harness.setRightPanelTabCalls).toEqual([]);- harness.unmount();- });});diff --git a/packages/studio/src/hooks/useSlideshowTabState.ts b/packages/studio/src/hooks/useSlideshowTabState.tsindex df7d49ea6e..6165f032bd 100644--- a/packages/studio/src/hooks/useSlideshowTabState.ts+++ b/packages/studio/src/hooks/useSlideshowTabState.ts@@ -1,29 +1,22 @@-import { useEffect, useMemo, type MutableRefObject } from "react";+import { useMemo, type MutableRefObject } from "react";import { SLIDESHOW_ISLAND_TYPE, slideshowIslandRegex } from "@hyperframes/core/slideshow";import type { SceneInfo } from "../components/panels/SlideshowPanel";import type { IframeWindow } from "../player/lib/playbackTypes";-import type { RightPanelTab } from "../utils/studioHelpers";/*** Derives whether the currently-edited composition is a slideshow (carries* the slideshow JSON island — the same definitive marker the CLI's `present`* command requires; it refuses to run without one) and the live scene list- * for the Slideshow panel, and bounces `rightPanelTab` off "slideshow" the- * moment it stops applying (e.g. the user switches to a non-slideshow file- * while that tab was open) so the panel never shows a dangling active tab- * whose button is no longer even rendered.- *- * Extracted from StudioRightPanel to keep that file under the 600-LOC gate.+ * for the Slideshow panel. Extracted from StudioRightPanels to keep that file+ * under the 600-LOC gate.*/export function useSlideshowTabState(params: {editingFileContent: string | null | undefined;previewIframeRef: MutableRefObject<HTMLIFrameElement | null>;refreshKey: number;- rightPanelTab: RightPanelTab;- setRightPanelTab: (tab: RightPanelTab) => void;+ slideshowVisible: boolean;}): { isSlideshowComposition: boolean; slideshowScenes: SceneInfo[] } {- const { editingFileContent, previewIframeRef, refreshKey, rightPanelTab, setRightPanelTab } =- params;+ const { editingFileContent, previewIframeRef, refreshKey, slideshowVisible } = params;// Presence-only (not full manifest validation): a malformed island should// still surface the Slideshow tab so the user can see/fix it, rather than@@ -49,13 +42,7 @@ export function useSlideshowTabState(params: {return [];}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [previewIframeRef, rightPanelTab, refreshKey]);-- useEffect(() => {- if (rightPanelTab === "slideshow" && !isSlideshowComposition) {- setRightPanelTab("renders");- }- }, [rightPanelTab, isSlideshowComposition, setRightPanelTab]);+ }, [previewIframeRef, slideshowVisible, refreshKey]);return { isSlideshowComposition, slideshowScenes };}diff --git a/packages/studio/src/hooks/useStudioContextValue.test.ts b/packages/studio/src/hooks/useStudioContextValue.test.tsindex 01228d92ed..557c7e7162 100644--- a/packages/studio/src/hooks/useStudioContextValue.test.ts+++ b/packages/studio/src/hooks/useStudioContextValue.test.ts@@ -4,14 +4,12 @@ import React from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";import type { DomEditSelection } from "../components/editor/domEditing";-import type { RightInspectorPanes } from "../utils/studioHelpers";+import type { PanelId } from "../components/dock/panelRegistry";import { makeSelection } from "./domSelectionTestHarness";import { useInspectorState, type InspectorState } from "./useStudioContextValue";interface HarnessProps {- rightPanelTab: string;- rightInspectorPanes: RightInspectorPanes;- rightCollapsed: boolean;+ rightPanel: PanelId | null;isPlaying: boolean;isGestureRecording: boolean;domEditSelection: DomEditSelection | null;@@ -22,9 +20,7 @@ function renderInspectorState(props: HarnessProps): InspectorState {function Harness() {state = useInspectorState(- props.rightPanelTab,- props.rightInspectorPanes,- props.rightCollapsed,+ props.rightPanel,props.isPlaying,props.domEditSelection,props.isGestureRecording,@@ -42,9 +38,7 @@ function selectedProps(): HarnessProps & { domEditSelection: DomEditSelection } {const element = document.createElement("div");return {- rightPanelTab: "renders",- rightInspectorPanes: { layers: false, design: false },- rightCollapsed: true,+ rightPanel: "renders",isPlaying: false,isGestureRecording: false,domEditSelection: makeSelection("Selected", element),@@ -78,16 +72,10 @@ describe("useInspectorState", () => {it("keeps selected DOM bounds coupled to the inspector or variables panel", () => {expect(renderInspectorState(selectedProps()).shouldShowSelectedDomBounds).toBe(false);expect(- renderInspectorState(- selectedProps({- rightPanelTab: "design",- rightInspectorPanes: { layers: false, design: true },- }),- ).shouldShowSelectedDomBounds,+ renderInspectorState(selectedProps({ rightPanel: "design" })).shouldShowSelectedDomBounds,).toBe(true);expect(- renderInspectorState(selectedProps({ rightPanelTab: "variables" }))- .shouldShowSelectedDomBounds,+ renderInspectorState(selectedProps({ rightPanel: "variables" })).shouldShowSelectedDomBounds,).toBe(true);});});diff --git a/packages/studio/src/hooks/useStudioContextValue.ts b/packages/studio/src/hooks/useStudioContextValue.tsindex b7f25982cb..783c51d22c 100644--- a/packages/studio/src/hooks/useStudioContextValue.ts+++ b/packages/studio/src/hooks/useStudioContextValue.ts@@ -1,7 +1,7 @@import { useCallback, useMemo, type DragEvent } from "react";import type { DomEditSelection } from "../components/editor/domEditing";import type { StudioContextValue } from "../contexts/StudioContext";-import type { RightInspectorPanes } from "../utils/studioHelpers";+import type { PanelId } from "../components/dock/panelRegistry";import type { TimelineFileDropHandler } from "./useTimelineEditingTypes";import { usePlayerStore } from "../player";@@ -66,33 +66,21 @@ export function buildStudioContextValue(input: StudioContextInput): StudioContex}export interface InspectorState {- layersPanelActive: boolean;- designPanelActive: boolean;inspectorPanelActive: boolean;- inspectorButtonActive: boolean;shouldShowMotionPath: boolean;shouldShowSelectedDomBounds: boolean;}export function useInspectorState(- rightPanelTab: string,- rightInspectorPanes: RightInspectorPanes,- rightCollapsed: boolean,+ rightPanel: PanelId | null,isPlaying: boolean,domEditSelection: DomEditSelection | null,isGestureRecording?: boolean,): InspectorState {- // fallow-ignore-next-line complexityreturn useMemo(() => {- const inspectorTabActive = rightPanelTab === "design" || rightPanelTab === "layers";- const layersPanelActive = inspectorTabActive && rightInspectorPanes.layers;- const designPanelActive = inspectorTabActive && rightInspectorPanes.design;- const inspectorPanelActive = layersPanelActive || designPanelActive;+ const inspectorPanelActive = rightPanel === "layers" || rightPanel === "design";return {- layersPanelActive,- designPanelActive,inspectorPanelActive,- inspectorButtonActive: !rightCollapsed && inspectorPanelActive,// Deliberately wider than shouldShowSelectedDomBounds: the on-canvas path// handles ARE the arc-drag affordance, so gating them on an open Inspector// would make keyframe path editing reachable only from a side panel.@@ -102,18 +90,9 @@ export function useInspectorState(// The Variables tab also works against the canvas selection (bind card),// so the selection outline stays visible there too.shouldShowSelectedDomBounds:- (inspectorPanelActive || rightPanelTab === "variables") &&- !isPlaying &&- !isGestureRecording,+ (inspectorPanelActive || rightPanel === "variables") && !isPlaying && !isGestureRecording,};- }, [- rightPanelTab,- rightInspectorPanes,- rightCollapsed,- isPlaying,- isGestureRecording,- domEditSelection,- ]);+ }, [rightPanel, isPlaying, isGestureRecording, domEditSelection]);}/** Lets an OS file drop reach `onDrop` anywhere in the shell; the timeline shows its own landing preview. */diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsxindex 2af548aca4..c50e8d362a 100644--- a/packages/studio/src/player/components/Timeline.tsx+++ b/packages/studio/src/player/components/Timeline.tsx@@ -448,7 +448,7 @@ export const Timeline = memo(function Timeline({return (<divref={setContainerRef}- aria-label="Timeline"+ aria-label="Timeline track view"data-timeline-element-count={expandedElements.length}className={`relative border-t select-none h-full overflow-hidden ${assetDrop.isDragOver ? "ring-1 ring-inset ring-studio-accent/60" : ""} ${activeTool === "razor" ? "cursor-crosshair" : shiftHeld ? "cursor-crosshair" : "cursor-default"}`}onMouseMove={updateRazorGuide}diff --git a/packages/studio/src/player/lib/timelinePerformanceDiagnostics.test.ts b/packages/studio/src/player/lib/timelinePerformanceDiagnostics.test.tsindex 30557fc85d..93eaff8cba 100644--- a/packages/studio/src/player/lib/timelinePerformanceDiagnostics.test.ts+++ b/packages/studio/src/player/lib/timelinePerformanceDiagnostics.test.ts@@ -14,7 +14,7 @@ describe("timeline performance diagnostics", () => {it("reads mounted resources without mutating the timeline", () => {document.body.innerHTML = `- <div aria-label="Timeline" data-timeline-scheduler-queued="3"+ <div aria-label="Timeline track view" data-timeline-scheduler-queued="3"data-timeline-scheduler-active="2" data-timeline-cache-bytes="4096"><div data-timeline-row><div data-clip="true"></div><div data-clip="true"></div></div><div data-timeline-row><div data-clip="true"></div></div>@@ -41,7 +41,8 @@ describe("timeline performance diagnostics", () => {});it("returns the zero baseline after unmount or reset removes the DOM", () => {- document.body.innerHTML = '<div aria-label="Timeline"><div data-clip="true"></div></div>';+ document.body.innerHTML =+ '<div aria-label="Timeline track view"><div data-clip="true"></div></div>';expect(readTimelinePerformanceDiagnostics().mountedClipRoots).toBe(1);document.body.replaceChildren();diff --git a/packages/studio/src/player/lib/timelinePerformanceDiagnostics.ts b/packages/studio/src/player/lib/timelinePerformanceDiagnostics.tsindex 2b30e615d4..6747477618 100644--- a/packages/studio/src/player/lib/timelinePerformanceDiagnostics.ts+++ b/packages/studio/src/player/lib/timelinePerformanceDiagnostics.ts@@ -69,7 +69,7 @@ function sumDataAttribute(root: ParentNode, selector: string, dataKey: string):export function readTimelinePerformanceDiagnostics(root: ParentNode = document,): Readonly<TimelinePerformanceDiagnostics> {- const timelineRoots = root.querySelectorAll<HTMLElement>('[aria-label="Timeline"]');+ const timelineRoots = root.querySelectorAll<HTMLElement>('[aria-label="Timeline track view"]');let mountedTimelineDescendants = 0;for (const timelineRoot of timelineRoots) {mountedTimelineDescendants += timelineRoot.querySelectorAll("*").length;diff --git a/packages/studio/src/utils/fitPanels.test.ts b/packages/studio/src/utils/fitPanels.test.tsdeleted file mode 100644index 39a0656169..0000000000--- a/packages/studio/src/utils/fitPanels.test.ts+++ /dev/null@@ -1,164 +0,0 @@-import { describe, expect, it } from "vitest";-import {- MIN_PREVIEW_H,- MIN_PREVIEW_W,- MIN_TIMELINE_H,- RAIL_W,- defaultPanelWidths,- fitPanelWidths,- fitTimelineHeight,-} from "./fitPanels";--function fitAt(viewportWidth: number) {- return fitPanelWidths(viewportWidth, defaultPanelWidths(viewportWidth));-}--describe("defaultPanelWidths", () => {- // Frozen literals, deliberately NOT compared against the live hook: the hook- // now delegates here, so asserting against it would be circular and would- // silently stop guarding the "wide windows are untouched" promise.- it.each([- [1680, 384, 424],- [1512, 384, 424],- [1280, 329, 364],- ])("keeps %ipx identical to the pre-change defaults", (vw, left, right) => {- expect(defaultPanelWidths(vw)).toEqual({ left, right });- });-});--describe("fitPanelWidths", () => {- it.each([1680, 1512, 1280])("leaves %ipx untouched by reconciliation", (vw) => {- const preferred = defaultPanelWidths(vw);- const fitted = fitPanelWidths(vw, preferred);- expect(fitted.left).toBe(preferred.left);- expect(fitted.right).toBe(preferred.right);- expect(fitted.autoCollapseLeft).toBe(false);- expect(fitted.autoCollapseRight).toBe(false);- });-- it.each([1680, 1512, 1280, 1100, 960, 860, 760, 640, 560, 480])(- "never starves the preview at %ipx",- (vw) => {- expect(fitAt(vw).preview).toBeGreaterThanOrEqual(MIN_PREVIEW_W);- },- );-- it("matches the projected preview widths from the plan", () => {- const projected: Array<[number, number]> = [- [1680, 866],- [1512, 698],- [1280, 581],- [1100, 499],- [960, 427],- [860, 360],- [760, 432],- [640, 592],- [560, 512],- [480, 432],- ];- for (const [vw, preview] of projected) {- expect({ vw, preview: fitAt(vw).preview }).toEqual({ vw, preview });- }- });-- it("fits everything at its minimum at exactly 860, the derived threshold", () => {- const fitted = fitAt(860);- expect(fitted).toMatchObject({- left: 214,- right: 280,- preview: MIN_PREVIEW_W,- autoCollapseLeft: false,- });- });-- it("rails the sidebar one pixel below the threshold", () => {- expect(fitAt(860).autoCollapseLeft).toBe(false);- expect(fitAt(859).autoCollapseLeft).toBe(true);- expect(fitAt(859).left).toBe(RAIL_W);- });-- it("hides the inspector one pixel below its own threshold", () => {- expect(fitAt(700).autoCollapseRight).toBe(false);- expect(fitAt(700).right).toBeGreaterThan(0);- expect(fitAt(699).autoCollapseRight).toBe(true);- expect(fitAt(699).right).toBe(0);- });-- it("never drives an EXPANDED sidebar below its usable minimum", () => {- // Guards the leftFloor/rightFloor split: the squeeze fallback may only reach- // the rail width when the panel is actually railed.- const fitted = fitPanelWidths(900, { left: 600, right: 600 });- expect(fitted.left).toBeGreaterThanOrEqual(200);- expect(fitted.right).toBeGreaterThanOrEqual(280);- });-- it("caps a single panel at 40% of the window", () => {- expect(fitPanelWidths(1600, { left: 900, right: 280 }).left).toBe(640);- });-- it("lets the preview floor win when the cap alone is not enough", () => {- // 40% of 1000 is 400, but 400 + 280 + 6 leaves the preview at 314.- const fitted = fitPanelWidths(1000, { left: 900, right: 280 });- expect(fitted.left).toBe(354);- expect(fitted.preview).toBe(MIN_PREVIEW_W);- });-- it("survives a viewport narrower than the preview floor alone", () => {- const fitted = fitAt(300);- expect(fitted.preview).toBeGreaterThanOrEqual(0);- expect(Number.isNaN(fitted.preview)).toBe(false);- expect(fitted.left).toBe(RAIL_W);- });-- it("returns preferences untouched before the shell is measured", () => {- const preferred = { left: 320, right: 400 };- expect(fitPanelWidths(0, preferred)).toMatchObject({ ...preferred, preview: 0 });- expect(fitPanelWidths(Number.NaN, preferred)).toMatchObject(preferred);- });-- it("is idempotent, so a resize loop cannot oscillate", () => {- for (const vw of [1512, 1100, 860, 760, 560]) {- const once = fitPanelWidths(vw, defaultPanelWidths(vw));- const twice = fitPanelWidths(vw, once);- expect(twice).toEqual(once);- }- });-});--describe("fitTimelineHeight", () => {- it("keeps a height that fits", () => {- expect(fitTimelineHeight(717, 429)).toBe(429);- });-- it("reclaims height for the preview when the shell shrinks", () => {- // The measured bug: mounted at 760 tall, dragged to 520. Preview was 47px.- expect(fitTimelineHeight(477, 429)).toBe(477 - MIN_PREVIEW_H);- expect(477 - fitTimelineHeight(477, 429)).toBeGreaterThanOrEqual(MIN_PREVIEW_H);- });-- it("raises a too-small preference to the timeline minimum", () => {- expect(fitTimelineHeight(717, 10)).toBe(MIN_TIMELINE_H);- });-- it("keeps the timeline usable when the shell is shorter than both minimums", () => {- expect(fitTimelineHeight(120, 429)).toBe(MIN_TIMELINE_H);- });-- it("returns the preference before the shell is measured", () => {- expect(fitTimelineHeight(0, 429)).toBe(429);- });-- it("is idempotent", () => {- const once = fitTimelineHeight(477, 429);- expect(fitTimelineHeight(477, once)).toBe(once);- });-- it("would return the preferred height if callers kept one", () => {- // The helper is preference-preserving; the vertical CALLER still stores the- // clamped value, so a shrink-then-grow does not restore the old height the- // way panel widths do. Tracked as a known asymmetry, not fixed here.- const preferred = 429;- expect(fitTimelineHeight(477, preferred)).toBe(277);- expect(fitTimelineHeight(717, preferred)).toBe(429);- });-});diff --git a/packages/studio/src/utils/fitPanels.ts b/packages/studio/src/utils/fitPanels.tsdeleted file mode 100644index f3d584cc10..0000000000--- a/packages/studio/src/utils/fitPanels.ts+++ /dev/null@@ -1,151 +0,0 @@-/**- * Panel reconciliation for the Studio shell.- *- * The shell is `[sidebar | preview | inspector]` over a full-width timeline.- * Only the preview is flexible (`flex-1 min-w-0`), so without an explicit floor- * it absorbs every squeeze: at a 560px window the old 240/320 panel floors alone- * overflowed the viewport and the preview rendered at 2px, on a *fresh* load.- * The same held vertically once the window was resized after mount.- *- * Every caller (mount, resize, drag, keyboard nudge, preference restore) routes- * through {@link fitPanelWidths} / {@link fitTimelineHeight} so exactly one place- * decides who yields. The rule is: the preview gets its floor first, panels- * shrink toward their minimums, then collapse to rails.- */--/** Smallest preview box worth editing in. Chosen, not derived — see the plan. */-export const MIN_PREVIEW_W = 360;-export const MIN_PREVIEW_H = 200;--const MIN_LEFT = 200;-const MIN_RIGHT = 280;-/**- * Collapsed sidebar rail, as a layout FOOTPRINT: the `w-10` box (40) plus the- * `mr-0.5` gap (2) it contributes to the flex row. Measured in the browser at a- * 760px window: rail box 40, margin-right 2, preview starts at x=43.- */-export const RAIL_W = 42;-export const MIN_TIMELINE_H = 100;--/** The two 3px resize seams between the three top-row panels. */-const PANEL_SEAM_W = 6;--/** No single panel may claim more than this share of the window. */-const PANEL_MAX_RATIO = 0.4;--/*- * Thresholds below are DERIVED from the minimums above, not chosen:- *- * MIN_LEFT 200 + MIN_RIGHT 280 + MIN_PREVIEW_W 360 + PANEL_SEAM_W 6 = 846- * -> below ~860 the sidebar can no longer fit at its minimum.- * RAIL_W 40 + MIN_RIGHT 280 + MIN_PREVIEW_W 360 + PANEL_SEAM_W 6 = 686- * -> below ~700 the inspector can no longer fit either.- *- * Change a minimum and move the matching threshold with it.- */-const RAIL_LEFT_BELOW = 860;-const RAIL_RIGHT_BELOW = 700;--/**- * True when the window is narrow enough to force at least one panel to a rail.- * The sidebar threshold is the wider of the two, so it is the whole condition.- */-export function railsEngaged(viewportWidth: number): boolean {- return viewportWidth < RAIL_LEFT_BELOW;-}--export interface PanelWidths {- left: number;- right: number;-}--export interface FittedPanelWidths extends PanelWidths {- preview: number;- /**- * Width-driven collapse. Derived per render; NEVER persisted and never written- * back to the user's own collapse preference — `leftCollapsed` lives in- * localStorage and `rightCollapsed` is synced into the shareable Studio URL,- * so a ten-second window drag must not rewrite either.- */- autoCollapseLeft: boolean;- autoCollapseRight: boolean;-}--function clamp(value: number, min: number, max: number): number {- return Math.max(min, Math.min(max, value));-}--/**- * The width each panel wants on a given viewport, before reconciliation.- * Upper bounds (384 / 424) are unchanged from the original implementation, which- * is what keeps windows at or above 1280px byte-identical to before.- */-export function defaultPanelWidths(viewportWidth: number): PanelWidths {- return {- left: Math.max(MIN_LEFT, Math.min(384, Math.round(viewportWidth * 0.257))),- right: Math.max(MIN_RIGHT, Math.min(424, Math.round(viewportWidth * 0.284))),- };-}--/**- * Resolve preferred panel widths against the viewport, reserving the preview.- *- * Order of yielding: window-relative cap, then the inspector shrinks toward its- * minimum, then the sidebar, then rails. A viewport of 0 (element not measured- * yet) returns the preferences untouched so a pre-measurement frame cannot- * clobber a real preference.- */-// fallow-ignore-next-line complexity-export function fitPanelWidths(- viewportWidth: number,- preferred: PanelWidths,- /**- * Sides the user explicitly reopened while the window was narrow. A side- * listed here keeps its real width instead of the rail: without this the- * panel would render expanded at 42px and squash its own content.- */- reopened: { left: boolean; right: boolean } = { left: false, right: false },-): FittedPanelWidths {- const vw = Number.isFinite(viewportWidth) ? Math.max(0, viewportWidth) : 0;- if (vw <= 0) {- return { ...preferred, preview: 0, autoCollapseLeft: false, autoCollapseRight: false };- }-- const autoCollapseLeft = vw < RAIL_LEFT_BELOW && !reopened.left;- const autoCollapseRight = vw < RAIL_RIGHT_BELOW && !reopened.right;- const cap = Math.floor(vw * PANEL_MAX_RATIO);-- // A railed panel's floor is its rail width; an open panel's floor is its- // minimum usable width. Without this split the squeeze fallback below would- // drive an *expanded* sidebar down to 40px and render its content unusable.- const leftFloor = autoCollapseLeft ? RAIL_W : MIN_LEFT;- const rightFloor = autoCollapseRight ? 0 : MIN_RIGHT;-- let left = autoCollapseLeft ? RAIL_W : clamp(preferred.left, MIN_LEFT, Math.max(MIN_LEFT, cap));- let right = autoCollapseRight ? 0 : clamp(preferred.right, MIN_RIGHT, Math.max(MIN_RIGHT, cap));-- const budget = vw - MIN_PREVIEW_W - PANEL_SEAM_W;- if (left + right > budget) right = Math.max(rightFloor, budget - left);- if (left + right > budget) left = Math.max(leftFloor, budget - right);-- return {- left,- right,- preview: Math.max(0, vw - left - right - PANEL_SEAM_W),- autoCollapseLeft,- autoCollapseRight,- };-}--/**- * Resolve a preferred timeline height against the shell's measured height.- *- * Subsumes the clamping that used to be inlined in TimelineResizeDivider's- * pointer and keyboard handlers and duplicated (mount-only) in NLEContext.- */-export function fitTimelineHeight(containerHeight: number, preferred: number): number {- const h = Number.isFinite(containerHeight) ? containerHeight : 0;- const wanted = Number.isFinite(preferred) ? preferred : MIN_TIMELINE_H;- if (h <= 0) return Math.max(MIN_TIMELINE_H, wanted);- return clamp(wanted, MIN_TIMELINE_H, Math.max(MIN_TIMELINE_H, h - MIN_PREVIEW_H));-}diff --git a/packages/studio/src/utils/studioHelpers.ts b/packages/studio/src/utils/studioHelpers.tsindex 28b027fa4b..26303d2217 100644--- a/packages/studio/src/utils/studioHelpers.ts+++ b/packages/studio/src/utils/studioHelpers.ts@@ -22,13 +22,6 @@ export type RightPanelTab =| "block-params"| "slideshow"| "variables";-export type RightInspectorPane = "layers" | "design";--export interface RightInspectorPanes {- layers: boolean;- design: boolean;-}-export interface AgentModalAnchorPoint {x: number;y: number;diff --git a/packages/studio/src/utils/studioUiPreferences.test.ts b/packages/studio/src/utils/studioUiPreferences.test.tsindex e2f31298db..5a702408cf 100644--- a/packages/studio/src/utils/studioUiPreferences.test.ts+++ b/packages/studio/src/utils/studioUiPreferences.test.ts@@ -20,7 +20,6 @@ describe("studio UI preferences", () => {const storage = createStorage();writeStudioUiPreferences({ timelineVisible: false }, storage);- writeStudioUiPreferences({ leftWidth: 384, rightWidth: 424 }, storage);writeStudioUiPreferences({ playbackRate: 1.5 }, storage);writeStudioUiPreferences({ audioMuted: true }, storage);writeStudioUiPreferences({ audioVolume: 0.4 }, storage);@@ -28,8 +27,6 @@ describe("studio UI preferences", () => {expect(readStudioUiPreferences(storage)).toEqual({timelineVisible: false,- leftWidth: 384,- rightWidth: 424,playbackRate: 1.5,audioMuted: true,audioVolume: 0.4,@@ -57,9 +54,6 @@ describe("studio UI preferences", () => {storage.setItem("hf-studio-ui-preferences",JSON.stringify({- leftCollapsed: "yes",- leftWidth: "wide",- rightWidth: Number.NaN,timelineVisible: true,playbackRate: Number.NaN,audioMuted: "false",@@ -119,28 +113,28 @@ describe("thumbnailMode preference", () => {describe("per-project scoping", () => {it("keeps two projects' preferences independent", () => {const storage = createStorage();- writeStudioUiPreferences({ leftWidth: 300 }, storage, "alpha");- writeStudioUiPreferences({ leftWidth: 500 }, storage, "beta");+ writeStudioUiPreferences({ playbackRate: 1.25 }, storage, "alpha");+ writeStudioUiPreferences({ playbackRate: 2 }, storage, "beta");- expect(readStudioUiPreferences(storage, "alpha").leftWidth).toBe(300);- expect(readStudioUiPreferences(storage, "beta").leftWidth).toBe(500);+ expect(readStudioUiPreferences(storage, "alpha").playbackRate).toBe(1.25);+ expect(readStudioUiPreferences(storage, "beta").playbackRate).toBe(2);});it("a project with nothing saved yet inherits the pre-scoping global entry once", () => {const storage = createStorage();- storage.setItem("hf-studio-ui-preferences", JSON.stringify({ leftWidth: 600 }));+ storage.setItem("hf-studio-ui-preferences", JSON.stringify({ playbackRate: 0.5 }));- expect(readStudioUiPreferences(storage, "gamma").leftWidth).toBe(600);+ expect(readStudioUiPreferences(storage, "gamma").playbackRate).toBe(0.5);});it("stops inheriting the global entry once the project has its own write", () => {const storage = createStorage();- storage.setItem("hf-studio-ui-preferences", JSON.stringify({ leftWidth: 600 }));+ storage.setItem("hf-studio-ui-preferences", JSON.stringify({ playbackRate: 0.5 }));- writeStudioUiPreferences({ leftWidth: 250 }, storage, "gamma");+ writeStudioUiPreferences({ playbackRate: 1.75 }, storage, "gamma");- expect(readStudioUiPreferences(storage, "gamma").leftWidth).toBe(250);- expect(readStudioUiPreferences(storage, null).leftWidth).toBe(600);+ expect(readStudioUiPreferences(storage, "gamma").playbackRate).toBe(1.75);+ expect(readStudioUiPreferences(storage, null).playbackRate).toBe(0.5);});});diff --git a/packages/studio/src/utils/studioUiPreferences.ts b/packages/studio/src/utils/studioUiPreferences.tsindex c1eb6bf7c9..c73b41ef30 100644--- a/packages/studio/src/utils/studioUiPreferences.ts+++ b/packages/studio/src/utils/studioUiPreferences.ts@@ -10,11 +10,7 @@ export interface StoredPreviewZoomState {export type TimelineTimeDisplayMode = "time" | "frame";export interface StudioUiPreferences {- leftCollapsed?: boolean;- leftWidth?: number;- rightWidth?: number;timelineVisible?: boolean;- timelineHeight?: number;playbackRate?: number;audioMuted?: boolean;audioVolume?: number;@@ -83,21 +79,9 @@ function readStorage(storage: Storage | null, key: string): StudioUiPreferencesif (!isRecord(parsed)) return {};const preferences: StudioUiPreferences = {};- if (typeof parsed.leftCollapsed === "boolean") {- preferences.leftCollapsed = parsed.leftCollapsed;- }- if (typeof parsed.leftWidth === "number" && Number.isFinite(parsed.leftWidth)) {- preferences.leftWidth = parsed.leftWidth;- }- if (typeof parsed.rightWidth === "number" && Number.isFinite(parsed.rightWidth)) {- preferences.rightWidth = parsed.rightWidth;- }if (typeof parsed.timelineVisible === "boolean") {preferences.timelineVisible = parsed.timelineVisible;}- if (typeof parsed.timelineHeight === "number" && Number.isFinite(parsed.timelineHeight)) {- preferences.timelineHeight = parsed.timelineHeight;- }if (typeof parsed.playbackRate === "number" && Number.isFinite(parsed.playbackRate)) {preferences.playbackRate = parsed.playbackRate;}diff --git a/packages/studio/tests/e2e/timeline-virtualization.mjs b/packages/studio/tests/e2e/timeline-virtualization.mjsindex 89e1ea803f..521da8ffee 100644--- a/packages/studio/tests/e2e/timeline-virtualization.mjs+++ b/packages/studio/tests/e2e/timeline-virtualization.mjs@@ -103,7 +103,7 @@ async function collectRun(page, injectedLongTaskMs = 0) {}function findTimelineScroller() {- const root = document.querySelector('[aria-label="Timeline"]');+ const root = document.querySelector('[aria-label="Timeline track view"]');if (!(root instanceof HTMLElement)) throw new Error("Timeline root not mounted");const scroller = root.querySelector("[data-timeline-scroll-viewport]");if (!(scroller instanceof HTMLElement)) throw new Error("Timeline scroller not mounted");@@ -172,7 +172,7 @@ async function assertLongTaskCapture(browser, longTaskLimitMs, scrollSamplesPerRconst injectedDurationMs = longTaskLimitMs + 25;try {await page.setContent(`- <div aria-label="Timeline">+ <div aria-label="Timeline track view"><div data-timeline-scroll-viewport style="width:100px;height:100px;overflow:auto"><div style="width:1000px;height:1000px"></div></div>@@ -334,7 +334,9 @@ try {}await page.evaluate(() => window.__studioTest.resetTimelinePerformanceFixture());- await page.waitForFunction(() => document.querySelector('[aria-label="Timeline"]') === null);+ await page.waitForFunction(+ () => document.querySelector('[aria-label="Timeline track view"]') === null,+ );await waitForStudioTestHookSettle(page);await loadFixtureAndWait(page, 1_000, PROFILE);await client.send("HeapProfiler.collectGarbage");@@ -418,7 +420,7 @@ async function waitForFixtureRender(page, elementCount) {modelCount: window.__playerStore?.getState().elements.length ?? null,renderedCount:document- .querySelector('[aria-label="Timeline"]')+ .querySelector('[aria-label="Timeline track view"]')?.getAttribute("data-timeline-element-count") ?? null,}));if (observed.renderedCount === String(elementCount)) {diff --git a/packages/studio/tests/e2e/webmcp-edit-loop.mjs b/packages/studio/tests/e2e/webmcp-edit-loop.mjsindex 3116ca5e73..e7d472855b 100644--- a/packages/studio/tests/e2e/webmcp-edit-loop.mjs+++ b/packages/studio/tests/e2e/webmcp-edit-loop.mjs@@ -344,16 +344,16 @@ async function fetchImage(url, evidenceName, expectedContentType = null) {async function findMountedThumbnailUrl(page, sourceFile, previous = null) {await page.waitForFunction(({ source, old }) =>- [...document.querySelectorAll('#sidebar-panel-compositions img[src*="/thumbnail/"]')].some(+ [...document.querySelectorAll('.hf-dock img[src*="/thumbnail/"]')].some((image) => image.src.includes(source) && (!old || image.src !== old),),{ timeout: RENDER_TIMEOUT_MS },{ source: sourceFile, old: previous },);return page.evaluate((source) => {- const image = [- ...document.querySelectorAll('#sidebar-panel-compositions img[src*="/thumbnail/"]'),- ].find((candidate) => candidate.src.includes(source));+ const image = [...document.querySelectorAll('.hf-dock img[src*="/thumbnail/"]')].find(+ (candidate) => candidate.src.includes(source),+ );return image?.src ?? null;}, sourceFile);}diff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjsindex 59c9741994..f5d4353b8a 100644--- a/scripts/check-no-main-deletions.mjs+++ b/scripts/check-no-main-deletions.mjs@@ -288,6 +288,31 @@ export const ALLOWED_DELETIONS = new Map(["docs/public/catalog/assets/e234267390ffd6ff.woff2","#4056 regenerated catalog font files are content-hashed, so a re-hashed file replaces the old one",],+ [+ "packages/studio/src/components/StudioLeftSidebar.tsx",+ "replaced by StudioLeftPanels.tsx, which mounts the left-zone panels as dock panels instead of a fixed sidebar",+ ],+ [+ "packages/studio/src/components/sidebar/LeftSidebar.tsx",+ "replaced by the dock-mounted CompositionsPanel/StudioLeftPanels; sidebar tab-switching is now the dock's own tab strip",+ ],+ [+ "packages/studio/src/components/sidebar/LeftSidebar.storage.test.ts",+ "tested the fixed-sidebar tab persistence removed with LeftSidebar.tsx; the dock persists its own layout",+ ],+ [+ "packages/studio/src/components/nle/TimelineResizeDivider.tsx",+ "the timeline's own resize divider; panel sizing is now the dock's sash",+ ],+ [+ "packages/studio/src/hooks/useInspectorSplitResize.ts",+ "resized the old fixed Layers/Design split pane, removed with the split-inspector layout",+ ],+ [+ "packages/studio/src/utils/fitPanels.ts",+ "computed fixed left/right panel widths for the old EditorShell layout; the dock sizes its own panels",+ ],+ ["packages/studio/src/utils/fitPanels.test.ts", "tests for fitPanels.ts, removed with it"],...["docs/studio/storyboard.mdx","packages/studio-server/src/routes/storyboard.test.ts",