@hyperframes/studio 0.8.200 → 0.8.202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/assets/{hyperframes-player-LmRUJE8q.js → hyperframes-player-DnrkDR-_.js} +1 -1
  2. package/dist/assets/{index-BmTWk8xf.js → index-BhFxhBMA.js} +162 -162
  3. package/dist/assets/{index-CKNiEwbW.js → index-WFQeAouT.js} +1 -1
  4. package/dist/{chunk-ORLUDHTU.js → chunk-J6T4KD7Y.js} +33 -0
  5. package/dist/index.html +1 -1
  6. package/dist/index.js +202 -107
  7. package/dist/player.js +1 -1
  8. package/package.json +8 -8
  9. package/src/components/TimelineToolbar.test.tsx +117 -3
  10. package/src/components/TimelineToolbar.tsx +32 -1
  11. package/src/components/panels/VariablesBindElement.test.tsx +105 -0
  12. package/src/components/panels/VariablesBindElement.tsx +2 -2
  13. package/src/components/panels/VariablesDeclarationForm.test.ts +106 -0
  14. package/src/components/panels/VariablesDeclarationForm.tsx +21 -3
  15. package/src/components/panels/VariablesValueControls.tsx +6 -0
  16. package/src/components/ui/VideoFrameThumbnail.test.tsx +9 -0
  17. package/src/components/ui/VideoFrameThumbnail.tsx +1 -3
  18. package/src/hooks/appHotkeysDispatch.ts +7 -0
  19. package/src/hooks/useAppHotkeys.test.ts +75 -0
  20. package/src/player/components/EditModal.test.tsx +34 -0
  21. package/src/player/components/EditModal.tsx +4 -2
  22. package/src/player/components/studioShortcuts.ts +3 -0
  23. package/src/player/components/timelineMotion.test.ts +13 -0
  24. package/src/player/components/timelineMotion.ts +12 -6
  25. package/src/player/components/timelineZoom.test.ts +48 -0
  26. package/src/player/components/timelineZoom.ts +55 -0
  27. package/src/player/components/timelineZoomInput.test.ts +27 -0
  28. package/src/player/components/timelineZoomInput.ts +55 -8
  29. package/src/player/lib/timelineIframeHelpers.test.ts +41 -0
  30. package/src/player/lib/timelineIframeHelpers.ts +5 -2
@@ -7,6 +7,10 @@ import { clearAutomationClipboard, copyRange } from "../player/components/automa
7
7
  import { VOLUME_RANGE } from "@hyperframes/core/audio-automation";
8
8
  import type { TimelineElement } from "../player/store/timelineElement";
9
9
  import { useAudioGainDialogStore } from "../player/components/audioGainDialogStore";
10
+ import {
11
+ cancelTimelineZoom,
12
+ registerTimelineZoomViewport,
13
+ } from "../player/components/timelineZoomInput";
10
14
 
11
15
  /** Minimal valid fixture — TimelineElement only requires these five fields. */
12
16
  const bgmElement: TimelineElement = {
@@ -500,6 +504,77 @@ describe("dispatchPlainKey — G opens Audio Gain", () => {
500
504
  expect(event.defaultPrevented).toBe(true);
501
505
  });
502
506
 
507
+ it("Z zooms when a clip is selected and does not take the key otherwise", () => {
508
+ const scroll = document.createElement("div");
509
+ Object.defineProperties(scroll, {
510
+ clientWidth: { value: 1080 },
511
+ scrollWidth: { value: 1080 },
512
+ scrollLeft: { value: 0, writable: true },
513
+ });
514
+ const unregister = registerTimelineZoomViewport({
515
+ scroll,
516
+ contentOrigin: 32,
517
+ publishScroll: () => {},
518
+ });
519
+ usePlayerStore.setState({
520
+ elements: [bgmElement],
521
+ selectedElementId: "bgm",
522
+ selectedElementIds: new Set(["bgm"]),
523
+ });
524
+ const event = press("z");
525
+ dispatchPlainKey(event, "z", callbacks());
526
+ expect(event.defaultPrevented).toBe(true);
527
+ cancelTimelineZoom();
528
+ unregister();
529
+
530
+ const unmounted = press("z");
531
+ dispatchPlainKey(unmounted, "z", callbacks());
532
+ expect(unmounted.defaultPrevented).toBe(false);
533
+
534
+ const collapsedScroll = document.createElement("div");
535
+ Object.defineProperties(collapsedScroll, {
536
+ clientWidth: { value: 32 },
537
+ scrollWidth: { value: 32 },
538
+ scrollLeft: { value: 0, writable: true },
539
+ });
540
+ const unregisterCollapsed = registerTimelineZoomViewport({
541
+ scroll: collapsedScroll,
542
+ contentOrigin: 32,
543
+ publishScroll: () => {},
544
+ });
545
+ const collapsed = press("z");
546
+ dispatchPlainKey(collapsed, "z", callbacks());
547
+ expect(collapsed.defaultPrevented).toBe(false);
548
+ unregisterCollapsed();
549
+
550
+ usePlayerStore.setState({ selectedElementId: null, selectedElementIds: new Set() });
551
+ const idle = press("z");
552
+ dispatchPlainKey(idle, "z", callbacks());
553
+ expect(idle.defaultPrevented).toBe(false);
554
+
555
+ const shifted = new KeyboardEvent("keydown", { key: "z", shiftKey: true, bubbles: true });
556
+ dispatchPlainKey(shifted, "z", callbacks());
557
+ expect(shifted.defaultPrevented).toBe(false);
558
+
559
+ usePlayerStore.setState({
560
+ elements: [bgmElement],
561
+ selectedElementId: "scene.html#child",
562
+ selectedElementIds: new Set(["scene.html#child"]),
563
+ });
564
+ const child = press("z");
565
+ dispatchPlainKey(child, "z", callbacks());
566
+ expect(child.defaultPrevented).toBe(false);
567
+
568
+ usePlayerStore.setState({
569
+ elements: [{ ...bgmElement, duration: 0 }],
570
+ selectedElementId: "bgm",
571
+ selectedElementIds: new Set(["bgm"]),
572
+ });
573
+ const zero = press("z");
574
+ dispatchPlainKey(zero, "z", callbacks());
575
+ expect(zero.defaultPrevented).toBe(false);
576
+ });
577
+
503
578
  it("leaves G to the grid toggle when nothing selected has sound", () => {
504
579
  usePlayerStore.setState({ elements: [video], selectedElementId: "b-roll" });
505
580
  const event = press("g");
@@ -0,0 +1,34 @@
1
+ // @vitest-environment happy-dom
2
+ import { act } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import { EditPopover } from "./EditModal";
6
+
7
+ (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
8
+
9
+ afterEach(() => {
10
+ document.body.innerHTML = "";
11
+ });
12
+
13
+ describe("EditPopover", () => {
14
+ // The timeline panel's dockview overlay is transformed, which makes it the containing
15
+ // block for position: fixed. Rendered inside it, the popover's viewport coordinates are
16
+ // resolved against the panel, so a Shift+drag low on the page puts it out of view.
17
+ it("renders on document.body, outside a transformed panel", () => {
18
+ const panel = document.createElement("div");
19
+ panel.style.transform = "translateZ(0)";
20
+ document.body.appendChild(panel);
21
+ const root = createRoot(panel);
22
+ act(() =>
23
+ root.render(
24
+ <EditPopover rangeStart={1} rangeEnd={2} anchorX={400} anchorY={900} onClose={() => {}} />,
25
+ ),
26
+ );
27
+
28
+ const textarea = document.querySelector("textarea");
29
+ expect(textarea).not.toBeNull();
30
+ expect(panel.contains(textarea)).toBe(false);
31
+
32
+ act(() => root.unmount());
33
+ });
34
+ });
@@ -1,4 +1,5 @@
1
1
  import { useState, useCallback, useMemo, useRef } from "react";
2
+ import { createPortal } from "react-dom";
2
3
  import { useMountEffect } from "../../hooks/useMountEffect";
3
4
  import { usePlayerStore } from "../store/playerStore";
4
5
  import { formatTime } from "../lib/time";
@@ -126,7 +127,7 @@ export function EditPopover({ rangeStart, rangeEnd, anchorX, anchorY, onClose }:
126
127
  zIndex: 200,
127
128
  };
128
129
 
129
- return (
130
+ return createPortal(
130
131
  <div ref={popoverRef} style={style}>
131
132
  <div className="w-80 bg-neutral-900 border border-neutral-700/60 rounded-xl shadow-2xl shadow-black/40 overflow-hidden">
132
133
  {/* Header */}
@@ -205,6 +206,7 @@ export function EditPopover({ rangeStart, rangeEnd, anchorX, anchorY, onClose }:
205
206
  </button>
206
207
  </div>
207
208
  </div>
208
- </div>
209
+ </div>,
210
+ document.body,
209
211
  );
210
212
  }
@@ -5,6 +5,7 @@ export const STUDIO_PLAIN_KEYS = {
5
5
  record: "r",
6
6
  addKeyframe: "k",
7
7
  audioGain: "g",
8
+ zoomSelection: "z",
8
9
  } as const;
9
10
 
10
11
  export interface ShortcutHint {
@@ -20,6 +21,7 @@ export interface ShortcutSection {
20
21
  const hintKey = (key: string) => key.toUpperCase();
21
22
 
22
23
  export const SPLIT_SHORTCUT_HINT = hintKey(STUDIO_PLAIN_KEYS.split);
24
+ export const ZOOM_SELECTION_SHORTCUT_HINT = hintKey(STUDIO_PLAIN_KEYS.zoomSelection);
23
25
 
24
26
  /** What PlayerControls' shortcuts panel lists unless an embedder passes its own sections. */
25
27
  export const DEFAULT_SHORTCUT_SECTIONS: readonly ShortcutSection[] = [
@@ -54,6 +56,7 @@ export const DEFAULT_SHORTCUT_SECTIONS: readonly ShortcutSection[] = [
54
56
  { key: "⌘V", label: "Paste element" },
55
57
  { key: "⌘X", label: "Cut element" },
56
58
  { key: SPLIT_SHORTCUT_HINT, label: "Split clip at playhead" },
59
+ { key: ZOOM_SELECTION_SHORTCUT_HINT, label: "Zoom timeline to selected clips" },
57
60
  { key: hintKey(STUDIO_PLAIN_KEYS.audioGain), label: "Audio Gain for clips with sound" },
58
61
  { key: "⇧Click", label: "Razor tool: split all tracks" },
59
62
  { key: "[", label: "Select clips starting before the playhead" },
@@ -1,4 +1,5 @@
1
1
  import { afterEach, expect, it, vi } from "vitest";
2
+ import { usePlayerStore } from "../store/playerStore";
2
3
  import { markTimelineMotion, TIMELINE_REST_MS, whenTimelineIdle } from "./timelineMotion";
3
4
 
4
5
  afterEach(() => {
@@ -25,3 +26,15 @@ it("waits for a zoom to rest before resolving, and resolves at once when nothing
25
26
  await vi.advanceTimersByTimeAsync(1);
26
27
  expect(again).toBe(true);
27
28
  });
29
+
30
+ it("waits for the film to stop playing", async () => {
31
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "requestIdleCallback"] });
32
+ usePlayerStore.getState().setIsPlaying(true);
33
+ let idle = false;
34
+ void whenTimelineIdle().then(() => (idle = true));
35
+ await vi.advanceTimersByTimeAsync(5000);
36
+ expect(idle).toBe(false);
37
+ usePlayerStore.getState().setIsPlaying(false);
38
+ await vi.advanceTimersByTimeAsync(1000);
39
+ expect(idle).toBe(true);
40
+ });
@@ -1,4 +1,5 @@
1
1
  import { useState, useSyncExternalStore } from "react";
2
+ import { usePlayerStore } from "../store/playerStore";
2
3
 
3
4
  /** How long the timeline must go without a zoom step to count as at rest. */
4
5
  export const TIMELINE_REST_MS = 150;
@@ -28,16 +29,21 @@ const onIdle = (callback: () => void) => {
28
29
  else setTimeout(callback, 0);
29
30
  };
30
31
 
31
- /** Resolves at an idle moment with no zoom moving the timeline: long work waits there, not mid-zoom. */
32
+ const busy = () => moving || usePlayerStore.getState().isPlaying;
33
+
34
+ /** Resolves at an idle moment with the film stopped and no zoom moving the timeline: long work waits there. */
32
35
  export function whenTimelineIdle(): Promise<void> {
33
36
  return new Promise((resolve) => {
34
37
  const check = () => {
35
- if (!moving) return resolve();
36
- const stop = subscribeTimelineMotion(() => {
37
- if (moving) return;
38
- stop();
38
+ if (!busy()) return resolve();
39
+ const wake = () => {
40
+ if (busy()) return;
41
+ stopMotion();
42
+ stopPlayback();
39
43
  onIdle(check);
40
- });
44
+ };
45
+ const stopMotion = subscribeTimelineMotion(wake);
46
+ const stopPlayback = usePlayerStore.subscribe(wake);
41
47
  };
42
48
  onIdle(check);
43
49
  });
@@ -8,8 +8,10 @@ import {
8
8
  getTimelinePixelsPerSecond,
9
9
  getTimelineZoomPercent,
10
10
  MIN_TIMELINE_ZOOM_PERCENT,
11
+ TIMELINE_RANGE_MARGIN_PX,
11
12
  timelineZoomPercentToSlider,
12
13
  timelineSliderToZoomPercent,
14
+ zoomToSelectedClips,
13
15
  } from "./timelineZoom";
14
16
 
15
17
  const FIT_PPS = 12;
@@ -153,6 +155,52 @@ describe("computePinnedZoomPercent", () => {
153
155
  });
154
156
  });
155
157
 
158
+ const VIEW = { viewportWidth: 1080, contentOrigin: 32, fitPixelsPerSecond: 10 };
159
+
160
+ describe("zoomToSelectedClips", () => {
161
+ const usable = VIEW.viewportWidth - VIEW.contentOrigin - TIMELINE_RANGE_MARGIN_PX * 2;
162
+
163
+ it("returns the span and the percent that fits it between the margins", () => {
164
+ expect(zoomToSelectedClips({ ...VIEW, clips: [{ start: 10, end: 20 }] })).toEqual({
165
+ start: 10,
166
+ end: 20,
167
+ zoomPercent: (usable / 10 / VIEW.fitPixelsPerSecond) * 100,
168
+ });
169
+ });
170
+
171
+ it("unions several clips and skips a zero-length entry", () => {
172
+ expect(
173
+ zoomToSelectedClips({
174
+ ...VIEW,
175
+ clips: [
176
+ { start: 28, end: 30 },
177
+ { start: 10, end: 12 },
178
+ { start: 0, end: 0 },
179
+ ],
180
+ }),
181
+ ).toEqual({
182
+ start: 10,
183
+ end: 30,
184
+ zoomPercent: (usable / 20 / VIEW.fitPixelsPerSecond) * 100,
185
+ });
186
+ });
187
+
188
+ it("returns null when nothing selectable is passed or the timeline is collapsed", () => {
189
+ expect(zoomToSelectedClips({ ...VIEW, clips: [] })).toBeNull();
190
+ expect(zoomToSelectedClips({ ...VIEW, clips: [{ start: 4, end: 4 }] })).toBeNull();
191
+ expect(
192
+ zoomToSelectedClips({
193
+ ...VIEW,
194
+ viewportWidth: VIEW.contentOrigin,
195
+ clips: [{ start: 0, end: 1 }],
196
+ }),
197
+ ).toBeNull();
198
+ expect(
199
+ zoomToSelectedClips({ ...VIEW, viewportWidth: 0, clips: [{ start: 0, end: 1 }] }),
200
+ ).toBeNull();
201
+ });
202
+ });
203
+
156
204
  describe("timelineZoomPercentToSlider / timelineSliderToZoomPercent round-trip", () => {
157
205
  for (const percent of [10, 100, 500, 2000, MAX_ZOOM_PERCENT]) {
158
206
  it(`round-trips ${percent}% within ±1%`, () => {
@@ -2,6 +2,8 @@ import type { ZoomMode } from "../store/playerStore";
2
2
  import { STUDIO_PREVIEW_FPS } from "../lib/time";
3
3
 
4
4
  export const MIN_TIMELINE_ZOOM_PERCENT = 10;
5
+ /** Inset so a range zoom does not sit on the viewport edge. Shared with the range box. */
6
+ export const TIMELINE_RANGE_MARGIN_PX = 24;
5
7
  const MAX_TIMELINE_FRAME_WIDTH_PX = 48;
6
8
  // CapCut-strength steps: one button press / pinch gesture moves the zoom
7
9
  // meaningfully (user feedback, twice-doubled: 1.25×/0.8× + 0.0035 felt like
@@ -119,3 +121,56 @@ export function timelineSliderToZoomPercent(slider: number, fitPixelsPerSecond:
119
121
  const logValue = LOG_MIN + (clampedSlider / 100) * (logMax - LOG_MIN);
120
122
  return clampTimelineZoomPercent(Math.exp(logValue), fitPixelsPerSecond);
121
123
  }
124
+
125
+ export interface ClipTimeSpan {
126
+ start: number;
127
+ end: number;
128
+ }
129
+
130
+ export interface SelectedClipsZoom {
131
+ start: number;
132
+ end: number;
133
+ zoomPercent: number;
134
+ }
135
+
136
+ /** Union of clips with a positive duration. Zero-length entries are not a range. */
137
+ export function positiveClipSpan(
138
+ clips: readonly ClipTimeSpan[],
139
+ ): { start: number; end: number } | null {
140
+ let start = Number.POSITIVE_INFINITY;
141
+ let end = Number.NEGATIVE_INFINITY;
142
+ for (const clip of clips) {
143
+ if (!Number.isFinite(clip.start) || !Number.isFinite(clip.end) || !(clip.end > clip.start)) {
144
+ continue;
145
+ }
146
+ if (clip.start < start) start = clip.start;
147
+ if (clip.end > end) end = clip.end;
148
+ }
149
+ if (!Number.isFinite(start) || !(end > start)) return null;
150
+ return { start, end };
151
+ }
152
+
153
+ export function zoomToSelectedClips(input: {
154
+ clips: readonly ClipTimeSpan[];
155
+ viewportWidth: number;
156
+ contentOrigin: number;
157
+ fitPixelsPerSecond: number;
158
+ marginPx?: number;
159
+ }): SelectedClipsZoom | null {
160
+ const margin = input.marginPx ?? TIMELINE_RANGE_MARGIN_PX;
161
+ const span = positiveClipSpan(input.clips);
162
+ const fitPps = input.fitPixelsPerSecond;
163
+ const viewport = input.viewportWidth;
164
+ const origin = input.contentOrigin;
165
+ if (!span) return null;
166
+ if (!Number.isFinite(fitPps) || !(fitPps > 0)) return null;
167
+ // A collapsed timeline is no wider than its headers, so there is no track to fit.
168
+ if (!Number.isFinite(viewport) || !Number.isFinite(origin) || !(viewport > origin)) return null;
169
+
170
+ const usable = Math.max(1, viewport - origin - margin * 2);
171
+ const zoomPercent = clampTimelineZoomPercent(
172
+ (usable / (span.end - span.start) / fitPps) * 100,
173
+ fitPps,
174
+ );
175
+ return { start: span.start, end: span.end, zoomPercent };
176
+ }
@@ -346,6 +346,20 @@ describe("zoomTimelineToRange", () => {
346
346
  abort.abort();
347
347
  await expect(result).resolves.toBe("cancelled");
348
348
  });
349
+
350
+ it("resolves cancelled when the timeline is no wider than its headers", async () => {
351
+ const scroll = document.createElement("div");
352
+ Object.defineProperties(scroll, {
353
+ clientWidth: { value: 32 },
354
+ scrollWidth: { value: 32 },
355
+ scrollLeft: { value: 0, writable: true },
356
+ });
357
+ unregisterViewport = registerTimelineZoomViewport({ scroll, contentOrigin: 32, publishScroll });
358
+ const result = zoomTimelineToRange(10, 20, { smooth: false });
359
+ await expect(result).resolves.toBe("cancelled");
360
+ expect(usePlayerStore.getState().zoomMode).toBe("fit");
361
+ expect(usePlayerStore.getState().timelinePps).toBe(10);
362
+ });
349
363
  });
350
364
 
351
365
  describe("currentTimelineRange", () => {
@@ -456,4 +470,17 @@ describe("zoomTimelineStep", () => {
456
470
  // The range's middle, 56 + 1000 / 2, is the playhead.
457
471
  expect(laidOutX(60)).toBeCloseTo(556);
458
472
  });
473
+
474
+ it("still doubles the scale when the timeline is no wider than its headers", () => {
475
+ const scroll = document.createElement("div");
476
+ Object.defineProperties(scroll, {
477
+ clientWidth: { value: 32 },
478
+ scrollWidth: { value: 32 },
479
+ scrollLeft: { value: 0, writable: true },
480
+ });
481
+ unregisterViewport = registerTimelineZoomViewport({ scroll, contentOrigin: 32, publishScroll });
482
+ zoomTimelineStep("in");
483
+ vi.advanceTimersByTime(150);
484
+ expect(usePlayerStore.getState().timelinePps).toBeCloseTo(20);
485
+ });
459
486
  });
@@ -9,6 +9,10 @@ import {
9
9
  getNextTimelineZoomPercent,
10
10
  getTimelinePixelsPerSecond,
11
11
  getTimelineZoomPercent,
12
+ TIMELINE_RANGE_MARGIN_PX,
13
+ positiveClipSpan,
14
+ zoomToSelectedClips,
15
+ type ClipTimeSpan,
12
16
  } from "./timelineZoom";
13
17
 
14
18
  /** Where a zoom holds its place: `time` stays `x` px from the viewport's left edge. */
@@ -41,7 +45,6 @@ interface ZoomPreview {
41
45
  byPerson: boolean;
42
46
  }
43
47
 
44
- const RANGE_MARGIN_PX = 24;
45
48
  const SMOOTH_ZOOM_MS = 220;
46
49
  /** Past this the scaled-up preview turns soft. */
47
50
  const MAX_PREVIEW_SCALE = 4;
@@ -329,8 +332,8 @@ const reducedMotion = () =>
329
332
 
330
333
  /** The stretch a range zoom fills: from `x` px in, `width` px wide, inside the margins. */
331
334
  function rangeBox(view: TimelineZoomViewport): { x: number; width: number } {
332
- const x = view.contentOrigin + RANGE_MARGIN_PX;
333
- return { x, width: Math.max(1, view.scroll.clientWidth - x - RANGE_MARGIN_PX) };
335
+ const x = view.contentOrigin + TIMELINE_RANGE_MARGIN_PX;
336
+ return { x, width: Math.max(1, view.scroll.clientWidth - x - TIMELINE_RANGE_MARGIN_PX) };
334
337
  }
335
338
 
336
339
  /** The seconds the timeline shows between its margins: what zoomTimelineToRange would fill. */
@@ -364,16 +367,24 @@ function easeToRange(
364
367
  const view = viewport;
365
368
  const fitPps = usePlayerStore.getState().timelineFitPps;
366
369
  stopEase();
367
- if (!view || !(end > start) || !(fitPps > 0) || signal?.aborted)
368
- return Promise.resolve("cancelled");
370
+ const zoom =
371
+ view && !signal?.aborted
372
+ ? zoomToSelectedClips({
373
+ clips: [{ start, end }],
374
+ viewportWidth: view.scroll.clientWidth,
375
+ contentOrigin: view.contentOrigin,
376
+ fitPixelsPerSecond: fitPps,
377
+ })
378
+ : null;
379
+ if (!view || !zoom) return Promise.resolve("cancelled");
369
380
  let resolveThis: (result: TimelineZoomResult) => void = () => {};
370
381
  const result = new Promise<TimelineZoomResult>((resolve) => (resolveThis = resolve));
371
382
  resolveEase = resolveThis;
372
383
  signal?.addEventListener("abort", () => resolveEase === resolveThis && stopEase(), {
373
384
  once: true,
374
385
  });
375
- const { x, width } = rangeBox(view);
376
- const toPercent = clampTimelineZoomPercent((width / (end - start) / fitPps) * 100, fitPps);
386
+ const { x } = rangeBox(view);
387
+ const toPercent = zoom.zoomPercent;
377
388
  const finish = () => {
378
389
  commitPreview();
379
390
  stopEase("done");
@@ -447,7 +458,8 @@ export function zoomTimelineStep(direction: "in" | "out"): void {
447
458
  fitPps,
448
459
  );
449
460
  const view = viewport;
450
- if (!view || !(fitPps > 0)) {
461
+ // A collapsed timeline has no track to fit a range into, so the step still changes the percent.
462
+ if (!view || !(fitPps > 0) || !(view.scroll.clientWidth > view.contentOrigin)) {
451
463
  requestTimelineZoom(nextPercent);
452
464
  return;
453
465
  }
@@ -458,3 +470,38 @@ export function zoomTimelineStep(direction: "in" | "out"): void {
458
470
  const start = at.time - (at.x - x) / nextPps;
459
471
  void easeToRange(start, start + width / nextPps, {}, true);
460
472
  }
473
+
474
+ function selectedClipSpans(state: {
475
+ elements: readonly { key?: string | null; id: string; start: number; duration: number }[];
476
+ selectedElementId: string | null;
477
+ selectedElementIds: ReadonlySet<string>;
478
+ }): ClipTimeSpan[] {
479
+ const keys = new Set(state.selectedElementIds);
480
+ if (state.selectedElementId) keys.add(state.selectedElementId);
481
+ const clips: ClipTimeSpan[] = [];
482
+ for (const el of state.elements) {
483
+ if (!keys.has(el.key ?? el.id)) continue;
484
+ clips.push({ start: el.start, end: el.start + el.duration });
485
+ }
486
+ return clips;
487
+ }
488
+
489
+ /** Whether the selection matches a timeline clip the zoom can land on. */
490
+ export function canZoomToSelectedClips(state: {
491
+ elements: readonly { key?: string | null; id: string; start: number; duration: number }[];
492
+ selectedElementId: string | null;
493
+ selectedElementIds: ReadonlySet<string>;
494
+ }): boolean {
495
+ return positiveClipSpan(selectedClipSpans(state)) !== null;
496
+ }
497
+
498
+ export function zoomTimelineToSelectedClips(): boolean {
499
+ const view = viewport;
500
+ const state = usePlayerStore.getState();
501
+ if (!view || !(state.timelineFitPps > 0) || !(view.scroll.clientWidth > view.contentOrigin))
502
+ return false;
503
+ const span = positiveClipSpan(selectedClipSpans(state));
504
+ if (!span) return false;
505
+ void zoomTimelineToRange(span.start, span.end);
506
+ return true;
507
+ }
@@ -118,6 +118,47 @@ describe("buildMissingCompositionElements — hfId (R7)", () => {
118
118
  });
119
119
  });
120
120
 
121
+ describe("buildMissingCompositionElements — on a settled timeline", () => {
122
+ // Studio runs this on every runtime state tick, so a timeline with nothing to add must cost one host scan.
123
+ const settled = () =>
124
+ makeDoc(`
125
+ <div data-composition-id="root">
126
+ <div id="intro" data-composition-id="intro" data-start="0" data-duration="3"></div>
127
+ ${Array.from({ length: 40 }, (_, i) => `<video id="clip-${i}" data-start="${i}" data-duration="1"></video>`).join("")}
128
+ </div>
129
+ `);
130
+ const rows = ["intro", ...Array.from({ length: 40 }, (_, i) => `clip-${i}`)].map((id, i) => ({
131
+ id,
132
+ key: id,
133
+ tag: id === "intro" ? "div" : "video",
134
+ start: i,
135
+ duration: 1,
136
+ track: 0,
137
+ }));
138
+
139
+ it("walks no more of the document than the hosts when nothing is missing or patchable", () => {
140
+ const doc = settled();
141
+ const scans = vi.spyOn(doc, "querySelectorAll");
142
+ const result = buildMissingCompositionElements(doc, window as IframeWindow, rows, 40);
143
+ expect(scans.mock.calls.map(([selector]) => selector)).toEqual([
144
+ "[data-composition-id][data-start]",
145
+ ]);
146
+ expect([result.missing, result.patched, result.updatedEls]).toEqual([[], false, rows]);
147
+ });
148
+
149
+ it("still patches a row whose host carries its source", () => {
150
+ const doc = settled();
151
+ doc.getElementById("intro")!.setAttribute("data-composition-src", "compositions/intro.html");
152
+ const { patched, updatedEls } = buildMissingCompositionElements(
153
+ doc,
154
+ window as IframeWindow,
155
+ rows,
156
+ 40,
157
+ );
158
+ expect([patched, updatedEls[0]?.compositionSrc]).toEqual([true, "compositions/intro.html"]);
159
+ });
160
+ });
161
+
121
162
  describe("buildMissingCompositionElements — nested master time", () => {
122
163
  it("places hosts two and three levels deep at their master time", () => {
123
164
  const doc = makeDoc(`
@@ -493,7 +493,7 @@ export function buildMissingCompositionElements(
493
493
  const hosts = doc.querySelectorAll("[data-composition-id][data-start]");
494
494
  const missing: TimelineElement[] = [];
495
495
 
496
- const resolveEnd = createReferenceEndResolver(createTimedElementLookup(doc), iframeWin);
496
+ let resolveEnd: ReturnType<typeof createReferenceEndResolver> | undefined;
497
497
  const masterTime = createRuntimeStartTimeResolver({
498
498
  timelineRegistry: iframeWin.__timelines,
499
499
  includeAuthoredTimingAttrs: true,
@@ -505,6 +505,7 @@ export function buildMissingCompositionElements(
505
505
  const compId = el.getAttribute("data-composition-id");
506
506
  if (!compId || compId === rootCompId) continue;
507
507
  if (existingIds.has(el.id) || existingIds.has(compId)) continue;
508
+ resolveEnd ??= createReferenceEndResolver(createTimedElementLookup(doc), iframeWin);
508
509
  const entry = buildMissingCompositionEntry({
509
510
  doc,
510
511
  iframeWin,
@@ -518,7 +519,9 @@ export function buildMissingCompositionElements(
518
519
  if (entry) missing.push(entry);
519
520
  }
520
521
 
521
- // Patch existing elements that are missing compositionSrc
522
+ // Patch existing elements that are missing compositionSrc; only a host carrying its source can supply one.
523
+ if (!doc.querySelector("[data-composition-src], [data-composition-file]"))
524
+ return { missing, updatedEls: currentEls as TimelineElement[], patched: false };
522
525
  let patched = false;
523
526
  const findHost = previewElementFinder(doc);
524
527
  const updatedEls = (currentEls as TimelineElement[]).map((existing) => {