Skip to content

Write HTML. Render video. Built for agents.

feat(studio): let a host hide timeline history, place the shortcuts button and set track padding (#4739)

Miguel Ángel26db3070161c
diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsx
index e309d5b977..61fefe2cd2 100644
--- a/packages/studio/src/components/TimelineToolbar.test.tsx
+++ b/packages/studio/src/components/TimelineToolbar.test.tsx
@@ -278,6 +278,23 @@ describe("TimelineToolbar audio meters", () => {
});
});
+describe("TimelineToolbar history", () => {
+ const historyButtons = (host: HTMLElement) =>
+ host.querySelectorAll('button[aria-label="Undo"], button[aria-label="Redo"]').length;
+
+ it("shows Undo and Redo by default", () => {
+ const { host, root } = renderToolbar();
+ expect(historyButtons(host)).toBe(2);
+ act(() => root.unmount());
+ });
+
+ it("renders neither when the host hides history", () => {
+ const { host, root } = renderToolbar(undefined, { showHistory: false });
+ expect(historyButtons(host)).toBe(0);
+ act(() => root.unmount());
+ });
+});
+
describe("TimelineToolbar add beat", () => {
it("shows Add beat by default, as Studio does", () => {
const { host, root } = renderToolbar();
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index cabaa123b8..1e3b71a70a 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -43,6 +43,7 @@ export interface TimelineToolbarProps {
domEditSession?: DomEditSessionSlice;
onSplitElement?: (element: TimelineElement, splitTime: number) => void;
history?: TimelineHistoryButtonsProps;
+ showHistory?: boolean;
showAddBeat?: boolean;
/** Hides Add keyframe and auto-record, and turns off auto-record and the K shortcut with them. */
showKeyframes?: boolean;
@@ -141,6 +142,7 @@ export function TimelineToolbar({
domEditSession,
onSplitElement,
history,
+ showHistory = true,
showAddBeat = true,
showKeyframes = true,
}: TimelineToolbarProps) {
@@ -213,7 +215,7 @@ export function TimelineToolbar({
<div className="border-b border-neutral-800/60">
<div className="flex items-center justify-between px-2 py-0.5">
<div className="flex items-center gap-0.5">
- <TimelineHistoryButtons {...history} />
+ {showHistory && <TimelineHistoryButtons {...history} />}
<TimelineToolPicker />
{/* Divider: tool-mode | editing-actions */}
<div aria-hidden="true" className="mx-1 h-4 w-px bg-neutral-800" />
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index aa6e012607..ade6c0c21c 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -6,6 +6,8 @@ export { EditorShell } from "./components/EditorShell";
export type { EditorShellProps } from "./components/EditorShell";
export { NLEPreview } from "./components/nle/NLEPreview";
export { DEFAULT_SHORTCUT_SECTIONS } from "./player/components/studioShortcuts";
+export { ShortcutsButton } from "./player/components/ShortcutsPanel";
+export type { ShortcutsButtonProps } from "./player/components/ShortcutsPanel";
export type { ShortcutHint, ShortcutSection } from "./player/components/studioShortcuts";
export { CompositionBreadcrumb } from "./components/nle/CompositionBreadcrumb";
export type { CompositionLevel } from "./components/nle/CompositionBreadcrumb";
@@ -49,6 +51,8 @@ export {
} from "./player/components/TimelineParts";
export { TimelineProvider, useTimelineContext } from "./player/components/TimelineProvider";
export type { TimelineTheme } from "./player/components/timelineTheme";
+export { TRACK_H } from "./player/components/timelineLayout";
+export type { TimelineTrackPadding } from "./player/components/timelineLayout";
// Clip content thumbnails: used by a host rendering its own timeline lane.
export { AudioWaveform } from "./player/components/AudioWaveform";
diff --git a/packages/studio/src/player/components/PlayerControls.tsx b/packages/studio/src/player/components/PlayerControls.tsx
index de6e01a94b..e3ed7dfa08 100644
--- a/packages/studio/src/player/components/PlayerControls.tsx
+++ b/packages/studio/src/player/components/PlayerControls.tsx
@@ -6,7 +6,7 @@ import { liveTime, usePlayerStore } from "../store/playerStore";
import { trackStudioEvent } from "../../utils/studioTelemetry";
import { Tooltip } from "../../components/ui";
import { useMountEffect } from "../../hooks/useMountEffect";
-import { ShortcutsPanel } from "./ShortcutsPanel";
+import { ShortcutsButton } from "./ShortcutsPanel";
import type { ShortcutSection } from "./studioShortcuts";
import { SpeedMenu } from "./SpeedMenu";
import { VolumeControl } from "./VolumeControl";
@@ -185,10 +185,6 @@ export const PlayerControls = memo(function PlayerControls({
const setAudioMuted = usePlayerStore.getState().setAudioMuted;
const setAudioVolume = usePlayerStore.getState().setAudioVolume;
const setLoopEnabled = usePlayerStore.getState().setLoopEnabled;
- const inPoint = usePlayerStore((s) => s.inPoint);
- const outPoint = usePlayerStore((s) => s.outPoint);
- const setInPoint = usePlayerStore.getState().setInPoint;
- const setOutPoint = usePlayerStore.getState().setOutPoint;
const timeDisplayMode = usePlayerStore((s) => s.timeDisplayMode);
const setTimeDisplayMode = usePlayerStore.getState().setTimeDisplayMode;
@@ -288,16 +284,7 @@ export const PlayerControls = memo(function PlayerControls({
{onToggleFullscreen && (
<FullscreenButton isFullscreen={isFullscreen} onToggleFullscreen={onToggleFullscreen} />
)}
- <ShortcutsPanel
- disabled={disabled}
- duration={duration}
- inPoint={inPoint}
- outPoint={outPoint}
- setInPoint={setInPoint}
- setOutPoint={setOutPoint}
- onSeek={onSeek}
- sections={shortcutSections}
- />
+ <ShortcutsButton disabled={disabled} onSeek={onSeek} sections={shortcutSections} />
</div>
</div>
</div>
diff --git a/packages/studio/src/player/components/ShortcutsPanel.test.tsx b/packages/studio/src/player/components/ShortcutsPanel.test.tsx
index dba9527c96..be4503e94c 100644
--- a/packages/studio/src/player/components/ShortcutsPanel.test.tsx
+++ b/packages/studio/src/player/components/ShortcutsPanel.test.tsx
@@ -2,10 +2,11 @@
import React, { act, Profiler } from "react";
import { describe, expect, it, vi } from "vitest";
-import { ShortcutsPanel } from "./ShortcutsPanel";
+import { ShortcutsButton, ShortcutsPanel } from "./ShortcutsPanel";
import { PlayerControls } from "./PlayerControls";
import { DEFAULT_SHORTCUT_SECTIONS, type ShortcutSection } from "./studioShortcuts";
import { createHappyDomRootHarness } from "./testRootHarness";
+import { usePlayerStore } from "../store/playerStore";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -200,4 +201,35 @@ describe("ShortcutsPanel", () => {
expect(errors.mock.calls.flat().join(" ")).not.toMatch(/same key/);
errors.mockRestore();
});
+
+ it("renders standalone for a host toolbar, reading the player store", () => {
+ const { duration, inPoint, requestSeek: storeSeek } = usePlayerStore.getState();
+ const requestSeek = vi.fn();
+ usePlayerStore.setState({ duration: 10, inPoint: 2, requestSeek });
+ try {
+ const host = document.createElement("div");
+ document.body.append(host);
+ act(() => {
+ mount(host).render(<ShortcutsButton sections={[{ title: "Host", hints: [] }]} />);
+ });
+ openPanel(host.querySelector<HTMLButtonElement>('button[aria-label="Shortcuts and tools"]')!);
+ expect(host.textContent).toContain("Host");
+ expect(host.textContent).toContain("00:02");
+
+ const input = host.querySelector<HTMLInputElement>('input[aria-label="Jump to frame"]')!;
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(
+ input,
+ "30",
+ );
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ act(() => {
+ input.form!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ expect(requestSeek).toHaveBeenCalledWith(1);
+ } finally {
+ usePlayerStore.setState({ duration, inPoint, requestSeek: storeSeek });
+ }
+ });
});
diff --git a/packages/studio/src/player/components/ShortcutsPanel.tsx b/packages/studio/src/player/components/ShortcutsPanel.tsx
index 8b8faa516a..bf6a28840e 100644
--- a/packages/studio/src/player/components/ShortcutsPanel.tsx
+++ b/packages/studio/src/player/components/ShortcutsPanel.tsx
@@ -2,6 +2,7 @@ import { useState, useCallback, useEffect, useId, useRef, memo } from "react";
import { formatTime, frameToSeconds } from "../lib/time";
import { Tooltip } from "../../components/ui";
import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss";
+import { usePlayerStore } from "../store/playerStore";
import { DEFAULT_SHORTCUT_SECTIONS, type ShortcutSection } from "./studioShortcuts";
interface ShortcutsPanelProps {
@@ -262,3 +263,28 @@ export const ShortcutsPanel = memo(function ShortcutsPanel({
</div>
);
});
+
+export interface ShortcutsButtonProps {
+ sections?: readonly ShortcutSection[];
+ disabled?: boolean;
+ onSeek?: (time: number) => void;
+}
+
+export function ShortcutsButton({ sections, disabled = false, onSeek }: ShortcutsButtonProps) {
+ const duration = usePlayerStore((s) => s.duration);
+ const inPoint = usePlayerStore((s) => s.inPoint);
+ const outPoint = usePlayerStore((s) => s.outPoint);
+ const { setInPoint, setOutPoint, requestSeek } = usePlayerStore.getState();
+ return (
+ <ShortcutsPanel
+ disabled={disabled}
+ duration={duration}
+ inPoint={inPoint}
+ outPoint={outPoint}
+ setInPoint={setInPoint}
+ setOutPoint={setOutPoint}
+ onSeek={onSeek ?? requestSeek}
+ sections={sections}
+ />
+ );
+}
diff --git a/packages/studio/src/player/components/Timeline.trackPadding.test.tsx b/packages/studio/src/player/components/Timeline.trackPadding.test.tsx
new file mode 100644
index 0000000000..83c422ea2b
--- /dev/null
+++ b/packages/studio/src/player/components/Timeline.trackPadding.test.tsx
@@ -0,0 +1,157 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Timeline } from "./Timeline";
+import { installTimelineMountEnv } from "./timelineMountTestEnv";
+import { usePlayerStore } from "../store/playerStore";
+import { CLIP_Y, RULER_H, TRACK_H, TRACKS_BOTTOM_PAD, TRACKS_TOP_PAD } from "./timelineLayout";
+import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+import type { TimelineProps } from "./TimelineTypes";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+installTimelineMountEnv();
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+async function mountCanvas(trackPadding?: TimelineProps["trackPadding"]) {
+ usePlayerStore.setState({
+ duration: 10,
+ currentTime: 0,
+ timelineReady: true,
+ gsapAnimations: new Map(),
+ elements: [{ id: "card", label: "Card", tag: "div", start: 0, duration: 4, track: 0 }],
+ });
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ await act(async () => root.render(<Timeline trackPadding={trackPadding} />));
+ const canvas = Array.from(host.querySelectorAll<HTMLElement>("div.relative")).find(
+ (el) => el.style.height && el.style.width,
+ );
+ const height = canvas?.style.height;
+ const firstRowTop = host.querySelector<HTMLElement>('[data-timeline-row="0"]')?.style.top;
+ act(() => root.unmount());
+ return { height, firstRowTop };
+}
+
+describe("Timeline trackPadding", () => {
+ it("keeps Studio's pads by default", async () => {
+ expect(await mountCanvas()).toEqual({
+ height: `${RULER_H + TRACKS_TOP_PAD + TRACK_H + TRACKS_BOTTOM_PAD}px`,
+ firstRowTop: `${RULER_H + TRACKS_TOP_PAD}px`,
+ });
+ });
+
+ it("places the first row and sizes the canvas from the host's pads", async () => {
+ expect(await mountCanvas({ top: 0, bottom: TRACK_H })).toEqual({
+ height: `${RULER_H + 2 * TRACK_H}px`,
+ firstRowTop: `${RULER_H}px`,
+ });
+ });
+
+ // With no top pad, y = 96 is the middle of row 1; any reader still on the default pad sees row 0.
+ const ROW1_MID = RULER_H + TRACK_H + TRACK_H / 2;
+ const hostPads = { top: 0, bottom: TRACK_H };
+
+ async function mountThreeTracks(props: TimelineProps = {}) {
+ usePlayerStore.setState({
+ duration: 10,
+ currentTime: 0,
+ timelineReady: true,
+ gsapAnimations: new Map(),
+ selectedElementId: null,
+ selectedElementIds: new Set(),
+ elements: [0, 1, 2].map((track) => ({
+ id: `c${track}`,
+ key: `c${track}`,
+ domId: `c${track}`,
+ tag: "div",
+ start: 0,
+ duration: 2,
+ track,
+ })),
+ });
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ await act(async () => root.render(<Timeline trackPadding={hostPads} {...props} />));
+ const viewport = host.querySelector<HTMLElement>("[data-timeline-scroll-viewport]")!;
+ return { host, root, viewport };
+ }
+
+ const top = (el: Element | null | undefined) => (el as HTMLElement | null)?.style.top;
+
+ it("draws the gap strip, drop preview and insert line, and drops, on the host's rows", async () => {
+ const onAssetDrop = vi.fn();
+ const { host, root, viewport } = await mountThreeTracks({ onAssetDrop });
+ act(() => usePlayerStore.getState().setSelectedElementId("c1"));
+ expect(top(host.querySelector('[style*="--timeline-accent-faint"]'))).toBe(
+ `${RULER_H + TRACK_H + CLIP_Y}px`,
+ );
+
+ const drag = (type: string, clientY: number) => {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperties(event, {
+ clientX: { value: 400 },
+ clientY: { value: clientY },
+ dataTransfer: {
+ value: {
+ types: [TIMELINE_ASSET_MIME],
+ files: [],
+ dropEffect: "none",
+ getData: (mime: string) => (mime === TIMELINE_ASSET_MIME ? '{"path":"a.png"}' : ""),
+ },
+ },
+ });
+ act(() => void viewport.dispatchEvent(event));
+ };
+ drag("dragover", ROW1_MID);
+ expect(top(host.querySelector('[data-testid="timeline-drop-preview"]'))).toBe(
+ `${RULER_H + TRACK_H + CLIP_Y}px`,
+ );
+ drag("dragover", RULER_H / 2);
+ expect(top(host.querySelector('[data-testid="timeline-insert-line"]'))).toBe(
+ `${RULER_H - 0.5}px`,
+ );
+ drag("drop", ROW1_MID);
+ expect(onAssetDrop).toHaveBeenCalledWith("a.png", expect.objectContaining({ track: 1 }));
+ act(() => root.unmount());
+ });
+
+ it("drags a clip onto the host's rows and opens a new track in the bottom pad", async () => {
+ const { host, root } = await mountThreeTracks({
+ onMoveElement: vi.fn(),
+ onResizeElement: vi.fn(),
+ });
+ const pointer = (target: EventTarget, type: string, clientY: number) =>
+ act(
+ () =>
+ void target.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button: 0,
+ pointerId: 1,
+ clientX: 400,
+ clientY,
+ }),
+ ),
+ );
+ const clip = host.querySelector('[data-clip][data-el-id="c0"]')!;
+ pointer(clip, "pointerdown", RULER_H + TRACK_H / 2);
+ pointer(window, "pointermove", ROW1_MID);
+ const ghost = Array.from(
+ host.querySelectorAll<HTMLElement>(".absolute.pointer-events-none"),
+ ).find((el) => el.style.zIndex === "30" && !el.dataset.testid);
+ expect(top(ghost)).toBe(`${RULER_H + TRACK_H + CLIP_Y}px`);
+ pointer(window, "pointermove", RULER_H + 3 * TRACK_H + TRACK_H / 2);
+ expect(top(host.querySelector('[data-testid="timeline-insert-line"]'))).toBe(
+ `${RULER_H + 3 * TRACK_H - 0.5}px`,
+ );
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx
index bae7783317..ec49a9b540 100644
--- a/packages/studio/src/player/components/TimelineCanvas.tsx
+++ b/packages/studio/src/player/components/TimelineCanvas.tsx
@@ -2,16 +2,7 @@ import { memo } from "react";
import { TimelineRulerPart } from "./TimelineRulerPart";
import { PlayheadIndicator } from "./PlayheadIndicator";
import { TimelinePlayheadLayer } from "./TimelinePlayheadLayer";
-import {
- RULER_H,
- CLIP_Y,
- TRACKS_TOP_PAD,
- TRACKS_BOTTOM_PAD,
- TRACK_H,
- PLAYHEAD_HEAD_W,
- getTimelineRowTop,
- getTimelineRowHeight,
-} from "./timelineLayout";
+import { RULER_H, CLIP_Y, TRACK_H, PLAYHEAD_HEAD_W, getTimelineRowHeight } from "./timelineLayout";
import { getTimelinePlayheadTransform } from "./timelinePlayheadTransform";
import { TimelineLanes } from "./TimelineLanes";
import { TimelineGestureOverlay } from "./TimelineGestureOverlay";
@@ -49,8 +40,11 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
<TimelineRulerPart />
{/* Breathing room between the sticky ruler and the first track lane — the
- top half of the CapCut-style padding (see TRACKS_TOP_PAD). */}
- <div aria-hidden="true" style={{ height: props.rowsVirtualized ? 0 : TRACKS_TOP_PAD }} />
+ top half of the CapCut-style padding (see TimelineRowGeometry.padding). */}
+ <div
+ aria-hidden="true"
+ style={{ height: props.rowsVirtualized ? 0 : props.rowGeometry.padding.top }}
+ />
<TimelineLanes
{...props}
@@ -67,10 +61,13 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
onRazorSplitAll={props.onRazorSplitAll}
/>
- {/* Breathing room below the last track lane (~1.5 track heights) — a real
+ {/* Breathing room below the last track lane (1.5 tracks by default) — a real
scrollable surface, so a clip can be dragged into the void to create a
- new bottom track comfortably (see TRACKS_BOTTOM_PAD / getTimelineCanvasHeight). */}
- <div aria-hidden="true" style={{ height: props.rowsVirtualized ? 0 : TRACKS_BOTTOM_PAD }} />
+ new bottom track comfortably (see TimelineRowGeometry.padding / canvasHeight). */}
+ <div
+ aria-hidden="true"
+ style={{ height: props.rowsVirtualized ? 0 : props.rowGeometry.padding.bottom }}
+ />
{/* Gap strips — loud dashed fill for the gap(s) a hovered "Close gap(s)"
menu row would collapse; a quiet tint for every gap on the selected
@@ -91,7 +88,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
key={`gap-${strip.kind}-${strip.track}-${gap.start}`}
className="pointer-events-none absolute"
style={{
- top: getTimelineRowTop(rowIndex, props.rowHeights) + CLIP_Y,
+ top: props.rowGeometry.getRowTop(rowIndex) + CLIP_Y,
left: props.contentOrigin + gap.start * props.pps,
width: Math.max((gap.end - gap.start) * props.pps, 2),
height: TRACK_H - CLIP_Y * 2,
@@ -109,7 +106,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
<div
className="absolute pointer-events-none"
style={{
- top: getTimelineRowTop(draggedRowIndex, props.rowHeights) + CLIP_Y,
+ top: props.rowGeometry.getRowTop(draggedRowIndex) + CLIP_Y,
left: props.contentOrigin + draggedClip.previewStart * props.pps,
width: Math.max(draggedClip.element.duration * props.pps, 4),
height: draggedClipHeight,
@@ -129,7 +126,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
data-testid="timeline-drop-preview"
className="absolute pointer-events-none"
style={{
- top: getTimelineRowTop(dropRowIndex, props.rowHeights) + CLIP_Y,
+ top: props.rowGeometry.getRowTop(dropRowIndex) + CLIP_Y,
left: props.contentOrigin + props.dropPreview.start * props.pps,
width: DROP_PREVIEW_SECONDS * props.pps,
height: TRACK_H - CLIP_Y * 2,
@@ -148,7 +145,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
data-testid="timeline-insert-line"
className="absolute pointer-events-none"
style={{
- top: getTimelineRowTop(insertLineRow, props.rowHeights) - 0.5,
+ top: props.rowGeometry.getRowTop(insertLineRow) - 0.5,
left: props.contentOrigin,
width: props.trackContentWidth,
height: 1,
diff --git a/packages/studio/src/player/components/TimelineTypes.ts b/packages/studio/src/player/components/TimelineTypes.ts
index 460fef28c9..c8abc30106 100644
--- a/packages/studio/src/player/components/TimelineTypes.ts
+++ b/packages/studio/src/player/components/TimelineTypes.ts
@@ -3,6 +3,7 @@ import type { TimelineElement } from "../store/playerStore";
import type { TimelineTimeRange } from "../store/rangeSelectionSlice";
import type { TimelineDropCallbacks } from "./timelineCallbacks";
import type { TimelineTheme } from "./timelineTheme";
+import type { TimelineTrackPadding } from "./timelineLayout";
import type { TimelineEditOverrides } from "./useResolvedTimelineEditCallbacks";
import type { TimelineStackingSyncProps } from "./useTimelineStackingSync";
@@ -35,4 +36,5 @@ export interface TimelineProps
theme?: Partial<TimelineTheme>;
showAudioEffects?: boolean;
showKeyframes?: boolean;
+ trackPadding?: TimelineTrackPadding;
}
diff --git a/packages/studio/src/player/components/timelineLayout.test.ts b/packages/studio/src/player/components/timelineLayout.test.ts
index efd90c92c7..097e222bbf 100644
--- a/packages/studio/src/player/components/timelineLayout.test.ts
+++ b/packages/studio/src/player/components/timelineLayout.test.ts
@@ -247,6 +247,53 @@ describe("track-area breathing pad y-math", () => {
});
});
+describe("host track padding", () => {
+ const geometry = createTimelineRowGeometry([0, 1, 2], baseRows(3), { top: 0, bottom: TRACK_H });
+ // Row 1 with no top pad, but still row 0 if any reader keeps the default pad.
+ const yInRow1 = RULER_H + TRACK_H + 10;
+
+ it("moves the first row up and sizes the canvas from the host pads", () => {
+ expect(geometry.getRowTop(0)).toBe(RULER_H);
+ expect(getTimelineRowTop(1, geometry.rowHeights)).toBe(RULER_H + TRACK_H);
+ expect(getTimelineCanvasHeight(geometry.rowHeights)).toBe(RULER_H + 4 * TRACK_H);
+ });
+
+ it("maps a drag pointer y to the row under it", () => {
+ expect(Math.floor(geometry.getRowFromY(yInRow1))).toBe(1);
+ expect(Math.floor(getTimelineRowFromY(yInRow1, geometry.rowHeights))).toBe(1);
+ });
+
+ it("drops onto the row under the pointer, and a new track in the bottom pad", () => {
+ const drop = {
+ rectLeft: 0,
+ rectTop: 0,
+ scrollLeft: 0,
+ scrollTop: 0,
+ contentOrigin: GUTTER,
+ pixelsPerSecond: 100,
+ rowHeights: geometry.rowHeights,
+ trackOrder: [0, 1, 2],
+ };
+ expect(resolveTimelineAssetDrop(drop, GUTTER, yInRow1).track).toBe(1);
+ const inBottomPad = RULER_H + 3 * TRACK_H + TRACK_H / 2;
+ expect(resolveTimelineAssetDrop(drop, GUTTER, inBottomPad).track).toBe(3);
+ });
+
+ it("clamps a negative pad to 0 and replaces a non-finite one with the default", () => {
+ const odd = createTimelineRowGeometry([0], baseRows(1), { top: -20, bottom: Number.NaN });
+ expect(odd.padding).toEqual({ top: 0, bottom: TRACKS_BOTTOM_PAD });
+ expect(odd.getRowTop(0)).toBe(RULER_H);
+ expect(odd.canvasHeight).toBe(RULER_H + TRACK_H + TRACKS_BOTTOM_PAD);
+ const infinite = createTimelineRowGeometry([0], baseRows(1), { top: Infinity });
+ expect(infinite.padding.top).toBe(TRACKS_TOP_PAD);
+ });
+
+ it("keeps the default pads when a host passes none", () => {
+ const defaults = createTimelineRowGeometry([0], baseRows(1));
+ expect(defaults.padding).toEqual({ top: TRACKS_TOP_PAD, bottom: TRACKS_BOTTOM_PAD });
+ });
+});
+
describe("getTimelineScrubTime", () => {
const at = (clientX: number, duration = 10) =>
getTimelineScrubTime({
diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts
index 7b8c55247c..4d1d8c9330 100644
--- a/packages/studio/src/player/components/timelineLayout.ts
+++ b/packages/studio/src/player/components/timelineLayout.ts
@@ -55,9 +55,8 @@ export function getTimelineLaneTop(laneIndex: number): number {
return TRACK_H + Math.max(0, Math.trunc(laneIndex)) * LANE_H;
}
/**
- * Breathing room INSIDE the scroll area (CapCut-style), threaded through every
- * track-row y computation via {@link getTimelineRowTop} — never inline a magic
- * offset; a track row's top is always ruler + top pad + cumulative row heights.
+ * Default breathing room INSIDE the scroll area (CapCut-style). A host overrides
+ * it per Timeline; rows always read TimelineRowGeometry.padding, never these.
*
* - TRACKS_TOP_PAD: empty space between the (sticky) ruler and the first track
* (~half a track height) so the first clip isn't jammed under the ruler.
@@ -66,6 +65,10 @@ export function getTimelineLaneTop(laneIndex: number): number {
*/
export const TRACKS_TOP_PAD = 50;
export const TRACKS_BOTTOM_PAD = Math.round(TRACK_H * 1.5);
+export interface TimelineTrackPadding {
+ top?: number;
+ bottom?: number;
+}
/**
* Breathing room LEFT of t=0 (CapCut-style), inside the scroll content — the
* horizontal sibling of TRACKS_TOP_PAD: empty lane surface between the sticky
@@ -115,12 +118,17 @@ function validRowHeight(height: number | undefined): number {
return height;
}
+function validPad(pad: number | undefined, fallback: number): number {
+ return pad !== undefined && Number.isFinite(pad) ? Math.max(0, pad) : fallback;
+}
+
export interface TimelineRowGeometry {
readonly rowKeys: readonly number[];
readonly rowHeights: readonly number[];
/** Cumulative row boundaries, including the final bottom boundary. */
readonly rowOffsets: readonly number[];
readonly rowsHeight: number;
+ readonly padding: Readonly<Required<TimelineTrackPadding>>;
readonly canvasHeight: number;
getRowIndex(rowKey: number): number;
getRowHeight(row: number): number;
@@ -141,7 +149,10 @@ const EMPTY_ROW_HEIGHTS: readonly number[] = Object.freeze([]);
export function createTimelineRowGeometry(
rowKeys: readonly number[],
rowHeights: readonly number[],
+ padding: TimelineTrackPadding = {},
): TimelineRowGeometry {
+ const topPad = validPad(padding.top, TRACKS_TOP_PAD);
+ const bottomPad = validPad(padding.bottom, TRACKS_BOTTOM_PAD);
const heights = Object.freeze(rowHeights.map(validRowHeight));
const keys = Object.freeze(
heights.map((_, row) => {
@@ -165,7 +176,7 @@ export function createTimelineRowGeometry(
return (offsets[wholeRow] ?? 0) + (row - wholeRow) * getRowHeight(wholeRow);
};
const getRowFromY = (contentY: number) => {
- const y = contentY - RULER_H - TRACKS_TOP_PAD;
+ const y = contentY - RULER_H - topPad;
if (heights.length === 0) return y / TRACK_H;
if (y < 0) return y / getRowHeight(0);
const rowsHeight = offsets[heights.length] ?? 0;
@@ -188,10 +199,11 @@ export function createTimelineRowGeometry(
rowHeights: heights,
rowOffsets: offsets,
rowsHeight: offsets.at(-1) ?? 0,
- canvasHeight: RULER_H + TRACKS_TOP_PAD + (offsets.at(-1) ?? 0) + TRACKS_BOTTOM_PAD,
+ padding: Object.freeze({ top: topPad, bottom: bottomPad }),
+ canvasHeight: RULER_H + topPad + (offsets.at(-1) ?? 0) + bottomPad,
getRowIndex: (rowKey) => rowIndexByKey.get(rowKey) ?? -1,
getRowHeight,
- getRowTop: (row) => RULER_H + TRACKS_TOP_PAD + getRowOffset(row),
+ getRowTop: (row) => RULER_H + topPad + getRowOffset(row),
getRowFromY,
getRowPositionFromY: (contentY) => {
const rowFloat = getRowFromY(contentY);
@@ -204,7 +216,7 @@ export function createTimelineRowGeometry(
return frozenGeometry;
}
-/** Compatibility accessor; repeated calls for one height-array reuse one snapshot. */
+/** Compatibility accessor: a geometry's own rowHeights resolves back to it, pads included. */
export function getTimelineRowGeometry(rowHeights: readonly number[]): TimelineRowGeometry {
const cached = rowGeometryCache.get(rowHeights);
if (cached) return cached;
@@ -228,10 +240,6 @@ export function getTimelineRowHeight(
return validRowHeight(rowHeights[row]);
}
-function getTimelineRowOffset(row: number, rowHeights: readonly number[]): number {
- return getTimelineRowGeometry(rowHeights).getRowTop(row) - RULER_H - TRACKS_TOP_PAD;
-}
-
/**
* The y (content-space) of the top edge of track ROW index `row` (0 = first
* displayed lane). The single source of truth for row->y: the ruler height plus
@@ -243,7 +251,7 @@ export function getTimelineRowTop(
row: number,
rowHeights: readonly number[] = EMPTY_ROW_HEIGHTS,
): number {
- return RULER_H + TRACKS_TOP_PAD + getTimelineRowOffset(row, rowHeights);
+ return getTimelineRowGeometry(rowHeights).getRowTop(row);
}
/**
@@ -484,9 +492,8 @@ export function getTimelinePlaybackFollowScrollLeft(input: {
}
export function getTimelineCanvasHeight(rowHeights: readonly number[]): number {
- // RULER_H + top pad + lanes + bottom pad. The old TIMELINE_SCROLL_BUFFER is
- // subsumed by TRACKS_BOTTOM_PAD (which is larger), so the drag-into-void space
- // below the last lane is real scrollable surface, not a hidden buffer.
+ // RULER_H + top pad + lanes + bottom pad, read from the geometry's padding.
+ // The drag-into-void space below the last lane is real scrollable surface.
return getTimelineRowGeometry(rowHeights).canvasHeight;
}
diff --git a/packages/studio/src/player/components/useTimelineProviderState.tsx b/packages/studio/src/player/components/useTimelineProviderState.tsx
index fb865d1636..ba19cf714a 100644
--- a/packages/studio/src/player/components/useTimelineProviderState.tsx
+++ b/packages/studio/src/player/components/useTimelineProviderState.tsx
@@ -65,6 +65,7 @@ export function useTimelineProviderState({
theme: themeOverrides,
showAudioEffects = true,
showKeyframes = true,
+ trackPadding,
sessionEpoch = 0,
previewIframeRef,
onZIndexReorder,
@@ -143,6 +144,7 @@ export function useTimelineProviderState({
gsapAnimations,
selectedElementId,
selectedElementIds,
+ trackPadding,
);
const timelineElementsRef = useRef(timelineElements);
timelineElementsRef.current = timelineElements; // oxlint-disable-line react/refs -- event handlers read the latest elements
diff --git a/packages/studio/src/player/components/useTimelineTrackLayout.ts b/packages/studio/src/player/components/useTimelineTrackLayout.ts
index 0f7b5c6585..29da97de6f 100644
--- a/packages/studio/src/player/components/useTimelineTrackLayout.ts
+++ b/packages/studio/src/player/components/useTimelineTrackLayout.ts
@@ -10,6 +10,7 @@ import {
TRACK_H,
createTimelineRowGeometry,
type TimelineRowGeometry,
+ type TimelineTrackPadding,
trackHeights,
type TimelineTrackHeightClip,
} from "./timelineLayout";
@@ -164,7 +165,10 @@ function useTimelineRowHeights(
selectedElementId: string | null,
selectedElementIds: ReadonlySet<string>,
groups: readonly TimelineTrackGroupInfo[],
+ trackPadding: TimelineTrackPadding | undefined,
) {
+ const padTop = trackPadding?.top;
+ const padBottom = trackPadding?.bottom;
const expandedClipIds = usePlayerStore((s) => s.expandedClipIds);
const expandedLaneOwnerIds = usePlayerStore((s) => s.expandedLaneOwnerIds);
const { laneCounts, rowGeometry } = useMemo(() => {
@@ -207,9 +211,12 @@ function useTimelineRowHeights(
rowGeometry: createTimelineRowGeometry(
tracks.map(([track]) => track),
rowHeights,
+ { top: padTop, bottom: padBottom },
),
};
}, [
+ padTop,
+ padBottom,
expandedClipIds,
expandedLaneOwnerIds,
gsapAnimations,
@@ -233,6 +240,7 @@ export function useTimelineTrackLayout(
gsapAnimations: Map<string, GsapAnimation[]>,
selectedElementId: string | null,
selectedElementIds: ReadonlySet<string>,
+ trackPadding?: TimelineTrackPadding,
) {
const { tracks, trackStyles, trackOrder, groups, trackGroupOf } =
useTimelineTrackDerivations(expandedElements);
@@ -244,6 +252,7 @@ export function useTimelineTrackLayout(
selectedElementId,
selectedElementIds,
groups,
+ trackPadding,
);
return {
@@ -305,8 +314,8 @@ export function useTimelineDisplayLayout(
const displayTrackOrder = useDisplayTrackOrder(draggedClip, trackOrder);
const displayRowHeights = useDisplayRowHeights(displayTrackOrder, rowGeometry);
const displayRowGeometry = useMemo(
- () => createTimelineRowGeometry(displayTrackOrder, displayRowHeights),
- [displayTrackOrder, displayRowHeights],
+ () => createTimelineRowGeometry(displayTrackOrder, displayRowHeights, rowGeometry.padding),
+ [displayTrackOrder, displayRowHeights, rowGeometry.padding],
);
return {
displayTrackOrder,
diff --git a/packages/studio/src/player/components/useTimelineVirtualRows.test.tsx b/packages/studio/src/player/components/useTimelineVirtualRows.test.tsx
index 582fbfeeb0..c0be0a8ea5 100644
--- a/packages/studio/src/player/components/useTimelineVirtualRows.test.tsx
+++ b/packages/studio/src/player/components/useTimelineVirtualRows.test.tsx
@@ -171,4 +171,36 @@ describe("useTimelineVirtualRows", () => {
act(() => root.unmount());
});
+
+ it("offsets the mounted range by the geometry's own top pad", () => {
+ const keys = Array.from({ length: 1_000 }, (_, index) => index);
+ const topPad = 200 * 48;
+ const geometry = createTimelineRowGeometry(
+ keys,
+ keys.map(() => 48),
+ { top: topPad },
+ );
+ const scroll = createScrollElement(RULER_H + topPad + 300 * 48);
+ const scrollRef = { current: scroll };
+ let rows: ReturnType<typeof useTimelineVirtualRows> = [];
+
+ function Probe() {
+ rows = useTimelineVirtualRows({
+ enabled: true,
+ scrollRef,
+ viewport: viewport(scroll),
+ rowGeometry: geometry,
+ sessionEpoch: 1,
+ pinnedRowKeys: [],
+ });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(React.createElement(Probe)));
+ act(() => {});
+ expect(rows.some((row) => row.index === 300)).toBe(true);
+ expect(rows.some((row) => row.index === 500)).toBe(false);
+ act(() => root.unmount());
+ });
});
diff --git a/packages/studio/src/player/components/useTimelineVirtualRows.ts b/packages/studio/src/player/components/useTimelineVirtualRows.ts
index 272be24c35..8830743e91 100644
--- a/packages/studio/src/player/components/useTimelineVirtualRows.ts
+++ b/packages/studio/src/player/components/useTimelineVirtualRows.ts
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, type RefObject } from "react";
import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual";
import { TIMELINE_VIEWPORT_BUDGETS } from "../lib/timelineViewportBudgets";
import type { TimelineScrollViewportSnapshot } from "./useTimelineScrollViewport";
-import { RULER_H, TRACKS_TOP_PAD, type TimelineRowGeometry } from "./timelineLayout";
+import { RULER_H, type TimelineRowGeometry } from "./timelineLayout";
export interface TimelineVirtualRow {
readonly index: number;
@@ -84,7 +84,7 @@ export function useTimelineVirtualRows({
getItemKey,
overscan: TIMELINE_VIEWPORT_BUDGETS.rowOverscanPerSide,
rangeExtractor,
- scrollMargin: RULER_H + TRACKS_TOP_PAD,
+ scrollMargin: RULER_H + rowGeometry.padding.top,
initialRect: { width: viewport.clientWidth, height: viewport.clientHeight },
initialOffset,
});