Skip to content

Write HTML. Render video. Built for agents.

fix(studio): timeline Fit fills the width with the film, and a host can hide keyframe controls (#4680)

Miguel Ángela3b6eec97e7d
diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsx
index 87c1fa4403..bc6132cc43 100644
--- a/packages/studio/src/components/TimelineToolbar.test.tsx
+++ b/packages/studio/src/components/TimelineToolbar.test.tsx
@@ -24,17 +24,22 @@ vi.mock("../contexts/StudioContext", () => ({
afterEach(() => {
document.body.innerHTML = "";
- usePlayerStore.setState({ autoKeyframeEnabled: true, thumbnailMode: "adaptive" });
+ usePlayerStore.setState({
+ autoKeyframeEnabled: true,
+ thumbnailMode: "adaptive",
+ zoomMode: "fit",
+ });
});
function renderToolbar(
domEditSession?: React.ComponentProps<typeof TimelineToolbar>["domEditSession"],
+ props: Partial<React.ComponentProps<typeof TimelineToolbar>> = {},
) {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
act(() => {
- root.render(<TimelineToolbar domEditSession={domEditSession} />);
+ root.render(<TimelineToolbar domEditSession={domEditSession} {...props} />);
});
return { host, root };
}
@@ -175,6 +180,52 @@ describe("TimelineToolbar — keyframes on audio tracks", () => {
expect(button?.disabled).toBe(false);
act(() => root.unmount());
});
+
+ const keyframeControls = (host: HTMLElement) => [
+ host.querySelector('button[aria-label="Add keyframe at playhead"]'),
+ host.querySelector('button[aria-label="Auto-record manual edits as keyframes"]'),
+ ];
+ /** True when the keyframe shortcut claimed K, so playback never saw it. */
+ const pressK = () => {
+ const event = new KeyboardEvent("keydown", { key: "k", bubbles: true, cancelable: true });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+ return event.defaultPrevented;
+ };
+
+ it("shows Add keyframe and auto-record, and K adds a keyframe, by default", () => {
+ const { host, root } = renderToolbar(sessionFor("div"));
+ expect(keyframeControls(host).every(Boolean)).toBe(true);
+ expect(pressK()).toBe(true);
+ act(() => root.unmount());
+ });
+
+ it("hides both controls for a host without keyframes, turns auto-record off and leaves K alone", () => {
+ const { host, root } = renderToolbar(sessionFor("div"), { showKeyframes: false });
+ expect(keyframeControls(host)).toEqual([null, null]);
+ expect(usePlayerStore.getState().autoKeyframeEnabled).toBe(false);
+ expect(pressK()).toBe(false);
+ act(() => root.unmount());
+ });
+});
+
+describe("TimelineToolbar Fit", () => {
+ it("shows Fit as a named icon and says whether fit is on", () => {
+ const { host, root } = renderToolbar();
+ const fit = () => host.querySelector('button[aria-label="Fit timeline to width"]');
+ expect(fit()?.textContent).toBe("");
+ expect(fit()?.querySelector("svg")).not.toBeNull();
+ act(() => fit()?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
+ expect(fit()?.getAttribute("aria-pressed")).toBe("true");
+ act(() =>
+ host
+ .querySelector('button[aria-label="Zoom in"]')
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true })),
+ );
+ expect(fit()?.getAttribute("aria-pressed")).toBe("false");
+ act(() => root.unmount());
+ });
});
describe("TimelineToolbar audio meters", () => {
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index e9342a063d..a59fb077ce 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -1,5 +1,11 @@
import { useEffect, useRef } from "react";
-import { Image, Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
+import {
+ ArrowsOutLineHorizontal,
+ Image,
+ Magnet,
+ MagnifyingGlassMinus,
+ MagnifyingGlassPlus,
+} from "@phosphor-icons/react";
import {
useEnableKeyframes,
isPlayheadWithinTween,
@@ -38,6 +44,8 @@ export interface TimelineToolbarProps {
onSplitElement?: (element: TimelineElement, splitTime: number) => void;
history?: TimelineHistoryButtonsProps;
showAddBeat?: boolean;
+ /** Hides Add keyframe and auto-record, and turns off auto-record and the K shortcut with them. */
+ showKeyframes?: boolean;
}
interface KeyframeToggleState {
@@ -134,6 +142,7 @@ export function TimelineToolbar({
onSplitElement,
history,
showAddBeat = true,
+ showKeyframes = true,
}: TimelineToolbarProps) {
const activeTool = usePlayerStore((s) => s.activeTool);
const setActiveTool = usePlayerStore((s) => s.setActiveTool);
@@ -174,10 +183,14 @@ export function TimelineToolbar({
// Wire the "Add keyframe (K)" shortcut the toolbar advertises. Active only when
// there's a keyframeable selection; otherwise K stays JKL-pause in playback.
useKeyframeKeyboard({
- enabled: Boolean(onToggleKeyframe),
+ enabled: showKeyframes && Boolean(onToggleKeyframe),
onAddKeyframe: onToggleKeyframe,
});
+ useEffect(() => {
+ if (!showKeyframes) setAutoKeyframeEnabled(false);
+ }, [showKeyframes, setAutoKeyframeEnabled]);
+
// "N" toggles timeline snapping (industry convention: Resolve/FCP).
// Skip when typing in an input/contenteditable.
useEffect(() => {
@@ -270,107 +283,110 @@ export function TimelineToolbar({
</button>
</Tooltip>
)}
- {/* Always rendered (CapCut-style): with no keyframeable selection the
- button fades to a disabled state instead of unmounting, so the
- toolbar layout never shifts. */}
- <Tooltip
- label={
- keyframePathEndpoint
- ? "Motion path endpoints cannot be removed"
- : !onToggleKeyframe
- ? "Select an animated element to add keyframes"
- : keyframeIsMotionPath
- ? keyframeWillExtend
- ? "Extend motion path to playhead (K)"
- : keyframeState === "active"
- ? "Remove waypoint from motion path (K)"
- : "Add waypoint to motion path (K)"
- : keyframeState === "active"
- ? "Remove keyframe at playhead (K)"
- : keyframeState === "inactive"
+ {showKeyframes && (
+ <>
+ {/* With no keyframeable selection the button fades to disabled instead of
+ unmounting, so the toolbar layout never shifts (CapCut-style). */}
+ <Tooltip
+ label={
+ keyframePathEndpoint
+ ? "Motion path endpoints cannot be removed"
+ : !onToggleKeyframe
+ ? "Select an animated element to add keyframes"
+ : keyframeIsMotionPath
? keyframeWillExtend
- ? "Add keyframe at playhead, extends animation (K)"
- : "Add keyframe at playhead (K)"
- : "Add keyframe (K)"
- }
- >
- <button
- type="button"
- disabled={!onToggleKeyframe}
- onClick={onToggleKeyframe}
- aria-label={
- keyframePathEndpoint
- ? "Motion path endpoint"
- : keyframeIsMotionPath
- ? keyframeState === "active"
- ? "Remove motion path waypoint"
- : keyframeWillExtend
- ? "Extend motion path to playhead"
- : "Add motion path waypoint"
- : keyframeState === "active"
- ? "Remove keyframe at playhead"
- : "Add keyframe at playhead"
- }
- className={
- !onToggleKeyframe
- ? flatDisabled
- : `${flatBtn} active:scale-[0.98] hover:bg-white/6 ${
- keyframeState === "active"
- ? "text-studio-accent"
- : keyframeState === "inactive"
- ? "text-neutral-400 hover:text-studio-accent"
- : "text-neutral-600 hover:text-neutral-400"
- }`
- }
- >
- <svg width="16" height="16" viewBox="0 0 10 10" fill="currentColor">
- {keyframeState === "active" ? (
- <path d="M5 0.5L9.5 5L5 9.5L0.5 5Z" />
- ) : (
- <path
- d="M5 1.2L8.8 5L5 8.8L1.2 5Z"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.2"
- />
- )}
- </svg>
- </button>
- </Tooltip>
- <Tooltip
- label={
- autoKeyframeEnabled
- ? "Auto-record manual edits as keyframes (click to turn off)"
- : "Manual edits will not be recorded as keyframes (click to turn on)"
- }
- >
- <button
- type="button"
- onClick={() => setAutoKeyframeEnabled(!autoKeyframeEnabled)}
- aria-label="Auto-record manual edits as keyframes"
- aria-pressed={autoKeyframeEnabled}
- className={`${flatBtn} active:scale-[0.98] hover:bg-white/6 ${
- autoKeyframeEnabled
- ? "text-red-400 hover:text-red-300"
- : "text-neutral-600 hover:text-neutral-400"
- }`}
- >
- <svg width="16" height="16" viewBox="0 0 10 10" fill="none">
- {/* Same diamond outline as the Add-keyframe icon, with a
+ ? "Extend motion path to playhead (K)"
+ : keyframeState === "active"
+ ? "Remove waypoint from motion path (K)"
+ : "Add waypoint to motion path (K)"
+ : keyframeState === "active"
+ ? "Remove keyframe at playhead (K)"
+ : keyframeState === "inactive"
+ ? keyframeWillExtend
+ ? "Add keyframe at playhead, extends animation (K)"
+ : "Add keyframe at playhead (K)"
+ : "Add keyframe (K)"
+ }
+ >
+ <button
+ type="button"
+ disabled={!onToggleKeyframe}
+ onClick={onToggleKeyframe}
+ aria-label={
+ keyframePathEndpoint
+ ? "Motion path endpoint"
+ : keyframeIsMotionPath
+ ? keyframeState === "active"
+ ? "Remove motion path waypoint"
+ : keyframeWillExtend
+ ? "Extend motion path to playhead"
+ : "Add motion path waypoint"
+ : keyframeState === "active"
+ ? "Remove keyframe at playhead"
+ : "Add keyframe at playhead"
+ }
+ className={
+ !onToggleKeyframe
+ ? flatDisabled
+ : `${flatBtn} active:scale-[0.98] hover:bg-white/6 ${
+ keyframeState === "active"
+ ? "text-studio-accent"
+ : keyframeState === "inactive"
+ ? "text-neutral-400 hover:text-studio-accent"
+ : "text-neutral-600 hover:text-neutral-400"
+ }`
+ }
+ >
+ <svg width="16" height="16" viewBox="0 0 10 10" fill="currentColor">
+ {keyframeState === "active" ? (
+ <path d="M5 0.5L9.5 5L5 9.5L0.5 5Z" />
+ ) : (
+ <path
+ d="M5 1.2L8.8 5L5 8.8L1.2 5Z"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ />
+ )}
+ </svg>
+ </button>
+ </Tooltip>
+ <Tooltip
+ label={
+ autoKeyframeEnabled
+ ? "Auto-record manual edits as keyframes (click to turn off)"
+ : "Manual edits will not be recorded as keyframes (click to turn on)"
+ }
+ >
+ <button
+ type="button"
+ onClick={() => setAutoKeyframeEnabled(!autoKeyframeEnabled)}
+ aria-label="Auto-record manual edits as keyframes"
+ aria-pressed={autoKeyframeEnabled}
+ className={`${flatBtn} active:scale-[0.98] hover:bg-white/6 ${
+ autoKeyframeEnabled
+ ? "text-red-400 hover:text-red-300"
+ : "text-neutral-600 hover:text-neutral-400"
+ }`}
+ >
+ <svg width="16" height="16" viewBox="0 0 10 10" fill="none">
+ {/* Same diamond outline as the Add-keyframe icon, with a
record-style dot inside: filled = auto-recording,
hollow = manual edits won't be keyframed. */}
- <path d="M5 0.7L9.3 5L5 9.3L0.7 5Z" stroke="currentColor" strokeWidth="1" />
- <circle
- cx="5"
- cy="5"
- r="1.8"
- fill={autoKeyframeEnabled ? "currentColor" : "none"}
- stroke="currentColor"
- strokeWidth="1"
- />
- </svg>
- </button>
- </Tooltip>
+ <path d="M5 0.7L9.3 5L5 9.3L0.7 5Z" stroke="currentColor" strokeWidth="1" />
+ <circle
+ cx="5"
+ cy="5"
+ r="1.8"
+ fill={autoKeyframeEnabled ? "currentColor" : "none"}
+ stroke="currentColor"
+ strokeWidth="1"
+ />
+ </svg>
+ </button>
+ </Tooltip>
+ </>
+ )}
{onSplitElement &&
(() => {
// Render the button unconditionally (disabled when unusable):
@@ -495,13 +511,15 @@ export function TimelineToolbar({
<button
type="button"
onClick={() => setZoomMode("fit")}
+ aria-label="Fit timeline to width"
+ aria-pressed={zoomMode === "fit"}
className={`h-7 px-2 rounded-md text-[11px] font-medium transition-colors ${
zoomMode === "fit"
? "bg-studio-accent/10 text-studio-accent"
: "text-neutral-400 hover:bg-white/6 hover:text-neutral-200"
}`}
>
- Fit
+ <ArrowsOutLineHorizontal size={16} aria-hidden="true" />
</button>
</Tooltip>
<Tooltip label="Zoom out">
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index 3311b5b4db..16d75ff1da 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -213,7 +213,9 @@ describe("Timeline provider boundary", () => {
100,
).start,
).toBe(10);
- expect(getTimelineFitPps(640, 11, GUTTER)).toBe(10.1);
+ expect(getTimelineFitPps(640, 11, GUTTER)).toBeCloseTo(
+ (640 - GUTTER - 2) / (11 * FIT_ZOOM_HEADROOM),
+ );
act(() => root.unmount());
});
@@ -313,7 +315,7 @@ describe("Timeline provider boundary", () => {
expect(rulerX).toBe(LABEL_COL_W + GUTTER + 1000);
expect(collapsedHeader.textContent).toContain("Outro");
expect(getTimelineFitPps(640, 20, LABEL_COL_W + GUTTER)).toBeCloseTo(
- (640 - (LABEL_COL_W + GUTTER) - 2) / MIN_TIMELINE_EXTENT_S,
+ (640 - (LABEL_COL_W + GUTTER) - 2) / (20 * FIT_ZOOM_HEADROOM),
);
expect(
resolveTimelineAssetDrop(
@@ -948,15 +950,13 @@ describe("shouldAutoScrollTimeline", () => {
});
});
-describe("getTimelineFitPps (min 60s extent + fit headroom)", () => {
+describe("getTimelineFitPps (fit headroom, 60s floor only without a duration)", () => {
const viewport = 632; // usable width = 632 - GUTTER - TRACKS_LEFT_PAD - 2
- it("computes fit pps against the 60s floor for short compositions", () => {
- // A 10s comp maps 60s onto the viewport → the comp takes ~1/6 of the width.
- // (10 * 1.2 = 12s of headroom-padded content is still under the 60s floor.)
- const pps = getTimelineFitPps(viewport, 10, GUTTER + TRACKS_LEFT_PAD);
- expect(pps).toBeCloseTo((viewport - (GUTTER + TRACKS_LEFT_PAD) - 2) / MIN_TIMELINE_EXTENT_S);
- expect(10 * pps).toBeCloseTo((viewport - (GUTTER + TRACKS_LEFT_PAD) - 2) / 6);
+ it("fits a short film to the width, not to a 60s ruler", () => {
+ const usable = viewport - (GUTTER + TRACKS_LEFT_PAD) - 2;
+ const pps = getTimelineFitPps(viewport, 17, GUTTER + TRACKS_LEFT_PAD);
+ expect(17 * pps).toBeCloseTo(usable / FIT_ZOOM_HEADROOM);
});
it("fits duration * FIT_ZOOM_HEADROOM (not the bare duration) for long compositions", () => {
@@ -1000,11 +1000,10 @@ describe("getTimelineFitPps (min 60s extent + fit headroom)", () => {
});
describe("getTimelineDisplayContentWidth", () => {
- it("always spans at least MIN_TIMELINE_EXTENT_S seconds of content", () => {
- // 10s of content at 20 pps = 200px; the floor keeps 60s (1200px) rendered.
+ it("spans MIN_TIMELINE_EXTENT_S seconds while the duration is unknown", () => {
expect(
getTimelineDisplayContentWidth({
- trackContentWidth: 200,
+ effectiveDuration: 0,
viewportWidth: 400,
contentOrigin: GUTTER,
pps: 20,
@@ -1012,10 +1011,24 @@ describe("getTimelineDisplayContentWidth", () => {
).toBe(MIN_TIMELINE_EXTENT_S * 20);
});
- it("still fills the viewport when that is larger than the 60s floor", () => {
+ it("renders a short film at fit exactly as wide as the viewport, so fit never scrolls", () => {
+ const viewport = 632;
+ const origin = GUTTER + TRACKS_LEFT_PAD;
+ const pps = getTimelineFitPps(viewport, 17, origin);
+ expect(
+ getTimelineDisplayContentWidth({
+ effectiveDuration: 17,
+ viewportWidth: viewport,
+ contentOrigin: origin,
+ pps,
+ }),
+ ).toBeCloseTo(viewport - origin - 2);
+ });
+
+ it("still fills the viewport when that is larger than the fit span", () => {
expect(
getTimelineDisplayContentWidth({
- trackContentWidth: 200,
+ effectiveDuration: 40,
viewportWidth: 2000,
contentOrigin: GUTTER + TRACKS_LEFT_PAD,
pps: 5,
@@ -1026,7 +1039,7 @@ describe("getTimelineDisplayContentWidth", () => {
it("tracks a drag ghost past every other bound (drag-to-extend)", () => {
expect(
getTimelineDisplayContentWidth({
- trackContentWidth: 500,
+ effectiveDuration: 100,
viewportWidth: 400,
contentOrigin: GUTTER,
pps: 5,
@@ -1038,7 +1051,7 @@ describe("getTimelineDisplayContentWidth", () => {
it("tracks a resize (trim) ghost past every other bound (trim-to-extend)", () => {
expect(
getTimelineDisplayContentWidth({
- trackContentWidth: 500,
+ effectiveDuration: 100,
viewportWidth: 400,
contentOrigin: GUTTER,
pps: 5,
@@ -1047,15 +1060,15 @@ describe("getTimelineDisplayContentWidth", () => {
).toBe(4200);
});
- it("keeps long content authoritative", () => {
+ it("keeps the fit headroom past the end when zoomed in", () => {
expect(
getTimelineDisplayContentWidth({
- trackContentWidth: 9000,
+ effectiveDuration: 180,
viewportWidth: 400,
contentOrigin: GUTTER,
pps: 50,
}),
- ).toBe(9000);
+ ).toBeCloseTo(180 * FIT_ZOOM_HEADROOM * 50);
});
});
diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts
index 760e583c94..5b7f6f0f74 100644
--- a/packages/studio/src/player/components/timelineLayout.ts
+++ b/packages/studio/src/player/components/timelineLayout.ts
@@ -281,57 +281,51 @@ export function getTimelineInsertBoundaryBand(rowHeight: number): number {
* rendered width (see Timeline.tsx displayContentWidth).
*/
export const DRAG_EXTEND_MARGIN_PX = 160;
-/**
- * The rendered timeline always spans at least this many seconds of ruler +
- * track lanes, even when the composition is shorter — the empty space on the
- * right is a real, drag/drop-enabled surface (clips can be moved into it; the
- * composition grows on commit, content-driven). In fit mode the fit pps is
- * derived against this floor, so a 10s comp renders as ~1/6 of the viewport
- * with 60s of ruler after it.
- */
+/** The span the timeline maps while the composition's duration is unknown or 0. */
export const MIN_TIMELINE_EXTENT_S = 60;
/**
* Fit-mode headroom (CapCut-style): "fit" maps `duration * 1.2` — not the bare
* duration — onto the viewport, so the composition ends at ~83% of the width
* and the trailing ~17% stays empty ruler + droppable lane surface (room to
* drag clips past the current end without first zooming out). Applied ONLY
- * inside {@link getTimelineFitPps}, the single fit-pps source, so the ruler,
- * lanes, playhead, marquee, and drag math all inherit it consistently. Manual
+ * inside {@link getTimelineFitSpan}, which fit pps and the drawn width share, so
+ * the ruler, lanes, playhead, marquee, and drag math inherit it. Manual
* zoom percentages stay defined relative to this fit basis (100% == fit).
*/
export const FIT_ZOOM_HEADROOM = 1.2;
/* ── Tick generation ──────────────────────────────────────────────── */
/* ── Width / duration derivation ──────────────────────────────────── */
+/** Seconds the timeline maps: the composition plus FIT_ZOOM_HEADROOM, or the floor while its duration is unknown. */
+function getTimelineFitSpan(effectiveDuration: number): number {
+ return Number.isFinite(effectiveDuration) && effectiveDuration > 0
+ ? effectiveDuration * FIT_ZOOM_HEADROOM
+ : MIN_TIMELINE_EXTENT_S;
+}
+
/**
* Fit-mode pixels-per-second: fill the viewport with the composition plus
* FIT_ZOOM_HEADROOM trailing headroom (CapCut-style — the comp never slams
- * into the right edge), and never map fewer than MIN_TIMELINE_EXTENT_S
- * seconds onto it — a short comp takes a fraction of the width and the
- * remaining ruler runs to 1:00.
- * Manual zoom multiplies this base, so the floor only anchors the default.
+ * into the right edge). Manual zoom multiplies this base.
*/
export function getTimelineFitPps(
viewportWidth: number,
effectiveDuration: number,
contentOrigin: number,
): number {
- const safeDuration =
- Number.isFinite(effectiveDuration) && effectiveDuration > 0 ? effectiveDuration : 0;
- const span = Math.max(safeDuration * FIT_ZOOM_HEADROOM, MIN_TIMELINE_EXTENT_S);
if (!Number.isFinite(viewportWidth) || viewportWidth <= contentOrigin) return 100;
- return (viewportWidth - contentOrigin - 2) / span;
+ return (viewportWidth - contentOrigin - 2) / getTimelineFitSpan(effectiveDuration);
}
/**
* The rendered timeline extent in px. Always covers, whichever is largest:
- * the actual clip content, the visible viewport (no dead black after short
+ * the visible viewport (no dead black after short
* content — CapCut-style), a live drag or resize ghost plus the auto-scroll
- * margin (drag/trim-to-extend), and the MIN_TIMELINE_EXTENT_S floor. Only the
+ * margin (drag/trim-to-extend), and the fit span at this zoom. Only the
* RENDERED extent grows; clip positions/durations are untouched.
*/
export function getTimelineDisplayContentWidth(input: {
- trackContentWidth: number;
+ effectiveDuration: number;
viewportWidth: number;
contentOrigin: number;
pps: number;
@@ -340,11 +334,10 @@ export function getTimelineDisplayContentWidth(input: {
}): number {
const safePps = Number.isFinite(input.pps) ? Math.max(input.pps, 0) : 0;
return Math.max(
- input.trackContentWidth,
input.viewportWidth - input.contentOrigin - 2,
input.dragGhostEndPx ?? 0,
input.resizeGhostEndPx ?? 0,
- MIN_TIMELINE_EXTENT_S * safePps,
+ getTimelineFitSpan(input.effectiveDuration) * safePps,
);
}
diff --git a/packages/studio/src/player/components/useTimelineGeometry.test.tsx b/packages/studio/src/player/components/useTimelineGeometry.test.tsx
index 8d486f50ca..a32e3414be 100644
--- a/packages/studio/src/player/components/useTimelineGeometry.test.tsx
+++ b/packages/studio/src/player/components/useTimelineGeometry.test.tsx
@@ -115,3 +115,108 @@ describe("useTimelineGeometry restore-scroll effect", () => {
expect(scroll.scrollLeft).toBe(300);
});
});
+
+function ScaleProbe({
+ duration,
+ width = 1200,
+ clips = duration > 0,
+ seen,
+}: {
+ duration: number;
+ width?: number;
+ clips?: boolean;
+ seen: { pps: number; fitPps: number };
+}) {
+ const ppsRef = useRef(0);
+ const fitPpsRef = useRef(0);
+ const zoomMode = usePlayerStore((s) => s.zoomMode);
+ const manualZoomPercent = usePlayerStore((s) => s.manualZoomPercent);
+ const { pps, fitPps } = useTimelineGeometry({
+ viewportWidth: width,
+ effectiveDuration: duration,
+ zoomMode,
+ manualZoomPercent,
+ ppsRef,
+ fitPpsRef,
+ draggedClip: null,
+ resizingClip: null,
+ expandedElements: clips ? [{ ...element, start: 0, duration }] : [],
+ isDragging: useRef(false),
+ scrollRef: useRef<HTMLDivElement>(null),
+ lastScrollLeftRef: useRef(0),
+ contentOrigin: 32,
+ });
+ seen.pps = pps;
+ seen.fitPps = fitPps;
+ return null;
+}
+
+describe("useTimelineGeometry keeps the scale when only the length changes", () => {
+ const seen = { pps: 0, fitPps: 0 };
+ const renderAt = (duration: number, width?: number, clips?: boolean) =>
+ act(() =>
+ root.render(<ScaleProbe duration={duration} width={width} clips={clips} seen={seen} />),
+ );
+ const within = (pps: number) => Math.abs(seen.pps - pps) < seen.fitPps * 0.005;
+
+ it("keeps a short film's clips the same size when the first edit lengthens it", () => {
+ usePlayerStore.setState({ zoomMode: "fit", manualZoomPercent: 100 });
+ renderAt(17);
+ const before = seen.pps;
+ act(() => usePlayerStore.getState().pinTimelineZoom(seen.pps, seen.fitPps));
+ renderAt(25);
+ expect(seen.fitPps).toBeLessThan(before);
+ expect(within(before)).toBe(true);
+ });
+
+ it("keeps the scale in manual zoom when a later edit shortens the film", () => {
+ usePlayerStore.setState({ zoomMode: "manual", manualZoomPercent: 150 });
+ renderAt(17);
+ const before = seen.pps;
+ renderAt(12);
+ expect(seen.fitPps).toBeGreaterThan(before / 1.5);
+ expect(within(before)).toBe(true);
+ });
+
+ it("still scales with the fit width when the timeline is resized, and when the length first loads", () => {
+ usePlayerStore.setState({ zoomMode: "manual", manualZoomPercent: 150 });
+ renderAt(0);
+ renderAt(17);
+ expect(seen.pps).toBeCloseTo(seen.fitPps * 1.5);
+ renderAt(17, 900);
+ expect(seen.pps).toBeCloseTo(seen.fitPps * 1.5);
+ });
+
+ it("refits when another composition opens, which empties the clips first", () => {
+ usePlayerStore.setState({ zoomMode: "manual", manualZoomPercent: 150 });
+ renderAt(120);
+ renderAt(120, undefined, false);
+ renderAt(5);
+ expect(seen.pps).toBeCloseTo(seen.fitPps * 1.5);
+ });
+
+ it("refits after a project reset, which empties the clips and the length", () => {
+ usePlayerStore.setState({ zoomMode: "manual", manualZoomPercent: 150 });
+ renderAt(120);
+ renderAt(0);
+ renderAt(17);
+ expect(seen.pps).toBeCloseTo(seen.fitPps * 1.5);
+ });
+
+ it("keeps a lengthened film's scale near the maximum zoom", () => {
+ usePlayerStore.setState({ zoomMode: "manual", manualZoomPercent: 100_000 });
+ renderAt(17);
+ const before = seen.pps;
+ expect(before).toBeLessThan(seen.fitPps * 1000);
+ renderAt(25);
+ expect(within(before)).toBe(true);
+ });
+
+ it("leaves the manual zoom alone in fit mode", () => {
+ usePlayerStore.setState({ zoomMode: "fit", manualZoomPercent: 100 });
+ renderAt(17);
+ renderAt(25);
+ expect(seen.pps).toBe(seen.fitPps);
+ expect(usePlayerStore.getState().manualZoomPercent).toBe(100);
+ });
+});
diff --git a/packages/studio/src/player/components/useTimelineGeometry.ts b/packages/studio/src/player/components/useTimelineGeometry.ts
index 52d0a28647..19ed8d181e 100644
--- a/packages/studio/src/player/components/useTimelineGeometry.ts
+++ b/packages/studio/src/player/components/useTimelineGeometry.ts
@@ -1,6 +1,6 @@
-import { useEffect, useRef, type RefObject } from "react";
+import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import { usePlayerStore, type TimelineElement, type ZoomMode } from "../store/playerStore";
-import { getTimelinePixelsPerSecond } from "./timelineZoom";
+import { computePinnedZoomPercent, getTimelinePixelsPerSecond } from "./timelineZoom";
import {
DRAG_EXTEND_MARGIN_PX,
getTimelineDisplayContentWidth,
@@ -43,12 +43,9 @@ export function useTimelineGeometry({
lastScrollLeftRef,
contentOrigin,
}: UseTimelineGeometryInput) {
- // Fit pps maps at least MIN_TIMELINE_EXTENT_S onto the viewport, so short
- // comps show a 60s ruler with usable empty space (see getTimelineFitPps).
const fitPps = getTimelineFitPps(viewportWidth, effectiveDuration, contentOrigin);
const pps = getTimelinePixelsPerSecond(fitPps, zoomMode, manualZoomPercent);
ppsRef.current = pps;
- const trackContentWidth = Math.max(0, effectiveDuration * pps);
// Drag-to-extend: while a clip is dragged, keep the rendered extent a margin
// past the ghost's end. Holding the pointer in the right edge zone then keeps
// auto-scroll stepping (scrollWidth grows with the ghost), so the timeline
@@ -65,12 +62,12 @@ export function useTimelineGeometry({
const resizeGhostEndPx = resizingClip?.started
? (resizingClip.previewStart + resizingClip.previewDuration) * pps + DRAG_EXTEND_MARGIN_PX
: 0;
- // The timeline canvas always fills at least the viewport width AND the
- // MIN_TIMELINE_EXTENT_S floor: the ruler + empty track lanes keep going into
+ // The timeline canvas always fills at least the viewport width AND the fit
+ // span at this zoom: the ruler + empty track lanes keep going into
// the space instead of leaving dead black — CapCut-style. Only the RENDERED
// extent grows; clip positions/durations are untouched.
const displayContentWidth = getTimelineDisplayContentWidth({
- trackContentWidth,
+ effectiveDuration,
viewportWidth,
contentOrigin,
pps,
@@ -108,8 +105,7 @@ export function useTimelineGeometry({
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [expandedElements, zoomMode]);
- // Publish the live scale so edit handlers OUTSIDE <Timeline> (the keyboard-delete
- // path) can pin the zoom via pinTimelineZoomToCurrent without threading geometry.
+ // Publish the live scale for readers outside <Timeline> (the toolbar's zoom controls).
// In a useEffect (not the render body) so React-18 concurrent replay — Suspense
// retry, transitions, StrictMode double-invoke — can't double-publish. The write is
// idempotent (same pps/fitPps → same fields), so this is behavior-preserving; the
@@ -117,6 +113,18 @@ export function useTimelineGeometry({
useEffect(() => {
usePlayerStore.getState().setTimelineScale(pps, fitPps);
}, [pps, fitPps]);
+ // In manual zoom a length change keeps the on-screen scale instead of rescaling every
+ // clip, whichever edit caused it. A composition switch empties the clips first, so it refits.
+ const hasClips = expandedElements.length > 0;
+ const lastScale = useRef({ effectiveDuration, pps, hasClips });
+ useLayoutEffect(() => {
+ const last = lastScale.current;
+ lastScale.current = { effectiveDuration, pps, hasClips };
+ if (zoomMode !== "manual" || !last.hasClips || !hasClips) return;
+ if (last.effectiveDuration === effectiveDuration) return;
+ // Before paint; the percent is clamped against the new fit, not the store's last published one.
+ usePlayerStore.setState({ manualZoomPercent: computePinnedZoomPercent(last.pps, fitPps) });
+ });
return {
pps,