Skip to content

Write HTML. Render video. Built for agents.

refactor(studio): move playback adapter resolution into its own module (#4199)

Miguel Ángelfa699b7d9bad
diff --git a/packages/studio/src/player/hooks/playbackAdapterResolution.ts b/packages/studio/src/player/hooks/playbackAdapterResolution.ts
new file mode 100644
index 0000000000..a816b74181
--- /dev/null
+++ b/packages/studio/src/player/hooks/playbackAdapterResolution.ts
@@ -0,0 +1,98 @@
+// Picks the PlaybackAdapter an iframe's runtime exposes, wrapping it for static seek when needed.
+import type { MutableRefObject } from "react";
+import { usePlayerStore } from "../store/playerStore";
+import type { PlaybackAdapter, IframeWindow } from "../lib/playbackTypes";
+import {
+ getAdapterDuration,
+ wrapTimeline,
+ getDefaultStaticSeekPlaybackClock,
+ releaseStaticSeekCache,
+ resolveStaticSeekFallback,
+ type StaticSeekCacheEntry,
+} from "../lib/playbackAdapter";
+import { readTimelineDurationFromDocument } from "../lib/timelineDOM";
+
+/**
+ * Timeline-based adapters (`__timeline`, then `__timelines`): `match` is the first that covers
+ * the document duration; otherwise `fallback` is the first with any duration.
+ */
+function pickTimelineAdapter(
+ iframe: HTMLIFrameElement,
+ win: IframeWindow,
+ docDuration: number,
+): { match: PlaybackAdapter | null; fallback: PlaybackAdapter | null } {
+ let fallback: PlaybackAdapter | null = null;
+ for (const adapter of timelineCandidates(iframe, win)) {
+ const dur = getAdapterDuration(adapter);
+ if (dur > 0 && docDuration <= dur) return { match: adapter, fallback };
+ if (dur > 0) fallback ??= adapter;
+ }
+ return { match: null, fallback };
+}
+
+function* timelineCandidates(
+ iframe: HTMLIFrameElement,
+ win: IframeWindow,
+): Generator<PlaybackAdapter> {
+ if (win.__timeline) yield wrapTimeline(win.__timeline);
+ const keys = win.__timelines ? Object.keys(win.__timelines) : [];
+ if (!win.__timelines || keys.length === 0) return;
+ // The outermost [data-composition-id] is the master; Object.keys() order would let a
+ // sub-composition hijack transport.
+ const rootId = iframe.contentDocument
+ ?.querySelector("[data-composition-id]")
+ ?.getAttribute("data-composition-id");
+ const key = rootId && rootId in win.__timelines ? rootId : keys[keys.length - 1];
+ yield wrapTimeline(win.__timelines[key]);
+}
+
+interface StaticSeekRefs {
+ cache: MutableRefObject<StaticSeekCacheEntry | null>;
+ warned: MutableRefObject<boolean>;
+}
+
+export function resolvePlaybackAdapter(
+ iframe: HTMLIFrameElement,
+ win: IframeWindow,
+ refs: StaticSeekRefs,
+): PlaybackAdapter | null {
+ const playerAdapter =
+ win.__player && typeof win.__player.play === "function" ? win.__player : null;
+ const docDuration = readTimelineDurationFromDocument(iframe.contentDocument);
+ const adapterDur = getAdapterDuration(playerAdapter);
+
+ if (adapterDur > 0 && docDuration <= adapterDur) {
+ releaseStaticSeekCache(refs.cache, refs.warned);
+ return playerAdapter;
+ }
+
+ const timelines = pickTimelineAdapter(iframe, win, docDuration);
+ if (timelines.match) {
+ releaseStaticSeekCache(refs.cache, refs.warned);
+ return timelines.match;
+ }
+ const timelineAdapter = timelines.fallback;
+
+ // The document timeline extends past every native adapter's duration.
+ // Wrap the best available adapter with the effective duration so the
+ // seek slider, seek clamping, and duration display cover the full range.
+ const bestAdapter = playerAdapter ?? timelineAdapter;
+ const effectiveDuration = Math.max(usePlayerStore.getState().duration, docDuration, adapterDur);
+ if (
+ bestAdapter &&
+ effectiveDuration > 0 &&
+ ("renderSeek" in bestAdapter || typeof bestAdapter.seek === "function")
+ ) {
+ return resolveStaticSeekFallback({
+ cache: refs.cache,
+ warned: refs.warned,
+ bestAdapter,
+ effectiveDuration,
+ docDuration,
+ clock: getDefaultStaticSeekPlaybackClock(win),
+ getPlaybackRate: () => usePlayerStore.getState().playbackRate,
+ });
+ }
+
+ return bestAdapter;
+}
diff --git a/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts b/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts
new file mode 100644
index 0000000000..7083b588cc
--- /dev/null
+++ b/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts
@@ -0,0 +1,97 @@
+// Shared test harness: mounts the real useTimelinePlayer and fakes an iframe
+// whose window exposes a playback adapter.
+import React, { act, useEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { vi } from "vitest";
+import { useTimelinePlayer } from "./useTimelinePlayer";
+import { usePlayerStore } from "../store/playerStore";
+
+export type TimelinePlayerApi = ReturnType<typeof useTimelinePlayer>;
+
+export function resetPlayerStore() {
+ usePlayerStore.getState().reset();
+ usePlayerStore.setState({ requestedSeekTime: null });
+}
+
+function TimelinePlayerHarness({ onValue }: { onValue: (value: TimelinePlayerApi) => void }) {
+ const value = useTimelinePlayer();
+ useEffect(() => {
+ onValue(value);
+ }, [onValue, value]);
+ return null;
+}
+
+export function renderTimelinePlayerHarness() {
+ let api: TimelinePlayerApi | null = null;
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ act(() => {
+ root.render(React.createElement(TimelinePlayerHarness, { onValue: (value) => (api = value) }));
+ });
+
+ if (!api) throw new Error("useTimelinePlayer did not mount");
+ return { api: api as TimelinePlayerApi, root };
+}
+
+function makeFakeIframe(iframeWindow: Record<string, unknown>): HTMLIFrameElement {
+ const iframe = document.createElement("iframe");
+ Object.defineProperty(iframe, "contentWindow", { value: iframeWindow, configurable: true });
+ Object.defineProperty(iframe, "contentDocument", {
+ value: document.implementation.createHTMLDocument("preview"),
+ configurable: true,
+ });
+ return iframe;
+}
+
+export function attachIframeWindow(api: TimelinePlayerApi, iframeWindow: Record<string, unknown>) {
+ const iframe = makeFakeIframe(iframeWindow);
+ act(() => {
+ api.iframeRef.current = iframe;
+ api.onIframeLoad();
+ });
+}
+
+function makeAdapterWindow(
+ options: {
+ postMessage?: (message: unknown, targetOrigin: string) => void;
+ timelines?: Record<string, unknown>;
+ duration?: number;
+ } = {},
+) {
+ let currentTime = 0;
+ let playing = false;
+ const adapter = {
+ play: vi.fn(() => {
+ playing = true;
+ }),
+ pause: vi.fn(() => {
+ playing = false;
+ }),
+ seek: (time: number) => {
+ currentTime = time;
+ },
+ getTime: () => currentTime,
+ getDuration: () => options.duration ?? 30,
+ isPlaying: () => playing,
+ };
+ const win = {
+ __player: adapter,
+ __timelines: options.timelines,
+ postMessage: options.postMessage ?? (() => {}),
+ scrollTo: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ };
+ return { adapter, win };
+}
+
+export function attachIframeAdapter(
+ api: TimelinePlayerApi,
+ options: Parameters<typeof makeAdapterWindow>[0] = {},
+) {
+ const { adapter, win } = makeAdapterWindow(options);
+ attachIframeWindow(api, win);
+ return adapter;
+}
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.seek.test.ts b/packages/studio/src/player/hooks/useTimelinePlayer.seek.test.ts
index babeaa75ee..5d0fa43899 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.seek.test.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.seek.test.ts
@@ -1,105 +1,25 @@
// @vitest-environment happy-dom
-import React, { act, useEffect } from "react";
-import { createRoot } from "react-dom/client";
+import { act } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { useTimelinePlayer } from "./useTimelinePlayer";
+import type { useTimelinePlayer } from "./useTimelinePlayer";
+import {
+ attachIframeAdapter,
+ attachIframeWindow,
+ renderTimelinePlayerHarness,
+ resetPlayerStore,
+} from "./timelinePlayerTestHarness";
import { liveTime, usePlayerStore } from "../store/playerStore";
import { setTimelinePerformanceFixtureLease } from "../lib/timelinePerformanceFixture";
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
-function resetPlayerStore() {
- usePlayerStore.getState().reset();
- usePlayerStore.setState({ requestedSeekTime: null });
-}
-
-function TimelinePlayerHarness({
- onValue,
-}: {
- onValue: (value: ReturnType<typeof useTimelinePlayer>) => void;
-}) {
- const value = useTimelinePlayer();
- useEffect(() => {
- onValue(value);
- }, [onValue, value]);
- return null;
-}
-
-function renderTimelinePlayerHarness() {
- let api: ReturnType<typeof useTimelinePlayer> | null = null;
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
-
- act(() => {
- root.render(React.createElement(TimelinePlayerHarness, { onValue: (value) => (api = value) }));
- });
-
- if (!api) throw new Error("useTimelinePlayer did not mount");
- return { api, root };
-}
-
afterEach(() => {
setTimelinePerformanceFixtureLease(false);
document.body.innerHTML = "";
resetPlayerStore();
});
-function attachIframeWindow(
- api: ReturnType<typeof useTimelinePlayer>,
- iframeWindow: Record<string, unknown>,
-): void {
- const iframe = document.createElement("iframe");
- Object.defineProperty(iframe, "contentWindow", {
- value: iframeWindow,
- configurable: true,
- });
- Object.defineProperty(iframe, "contentDocument", {
- value: document.implementation.createHTMLDocument("preview"),
- configurable: true,
- });
- act(() => {
- api.iframeRef.current = iframe;
- api.onIframeLoad();
- });
-}
-
-function attachIframeAdapter(
- api: ReturnType<typeof useTimelinePlayer>,
- options: {
- postMessage?: (message: unknown, targetOrigin: string) => void;
- timelines?: Record<string, unknown>;
- duration?: number;
- } = {},
-) {
- let currentTime = 0;
- let playing = false;
- const adapter = {
- play: vi.fn(() => {
- playing = true;
- }),
- pause: vi.fn(() => {
- playing = false;
- }),
- seek: (time: number) => {
- currentTime = time;
- },
- getTime: () => currentTime,
- getDuration: () => options.duration ?? 30,
- isPlaying: () => playing,
- };
- attachIframeWindow(api, {
- __player: adapter,
- __timelines: options.timelines,
- postMessage: options.postMessage ?? (() => {}),
- scrollTo: () => {},
- addEventListener: () => {},
- removeEventListener: () => {},
- });
- return adapter;
-}
-
function renderAttachedTimelinePlayer() {
const { api, root } = renderTimelinePlayerHarness();
const adapter = attachIframeAdapter(api);
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.ts b/packages/studio/src/player/hooks/useTimelinePlayer.ts
index 7794be1b04..0e0fd99b2e 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.ts
@@ -3,6 +3,7 @@ import { usePlayerStore, liveTime, type TimelineElement } from "../store/playerS
import { useMountEffect } from "../../hooks/useMountEffect";
import { usePlaybackKeyboard } from "./usePlaybackKeyboard";
import { useTimelineSyncCallbacks } from "./useTimelineSyncCallbacks";
+import { resolvePlaybackAdapter } from "./playbackAdapterResolution";
import { useTimelinePlayerLoop } from "./useTimelinePlayerLoop";
import { logReload } from "../../utils/reloadDebug";
@@ -24,18 +25,8 @@ export {
} from "../lib/playbackShortcuts";
import type { PlaybackAdapter, IframeWindow } from "../lib/playbackTypes";
-import {
- getAdapterDuration,
- wrapTimeline,
- getDefaultStaticSeekPlaybackClock,
- releaseStaticSeekCache,
- resolveStaticSeekFallback,
- type StaticSeekCacheEntry,
-} from "../lib/playbackAdapter";
-import {
- readTimelineDurationFromDocument,
- mergeTimelineElementsPreservingDowngrades,
-} from "../lib/timelineDOM";
+import { releaseStaticSeekCache, type StaticSeekCacheEntry } from "../lib/playbackAdapter";
+import { mergeTimelineElementsPreservingDowngrades } from "../lib/timelineDOM";
import { normalizeToZones } from "../components/timelineZones";
import { applyPreviewAudioFlags, setPreviewPlaybackRate } from "../lib/timelineIframeHelpers";
import { scrubMusicAtSeek, stopScrubPreviewAudio } from "../lib/playbackScrub";
@@ -128,80 +119,15 @@ export function useTimelinePlayer() {
[setElements, requestTimelineReady, setDuration],
);
- // Pre-existing dispatcher complexity — surfaced by this PR's line shifts, not new logic.
- // fallow-ignore-next-line complexity
const getAdapter = useCallback((): PlaybackAdapter | null => {
try {
const iframe = iframeRef.current;
const win = iframe?.contentWindow as IframeWindow | null;
if (!iframe || !win) return null;
-
- const playerAdapter =
- win.__player && typeof win.__player.play === "function" ? win.__player : null;
- const docDuration = readTimelineDurationFromDocument(iframe.contentDocument);
- const adapterDur = getAdapterDuration(playerAdapter);
-
- if (adapterDur > 0 && docDuration <= adapterDur) {
- releaseStaticSeekCache(staticSeekAdapterRef, staticSeekWarnedRef);
- return playerAdapter;
- }
-
- let timelineAdapter: PlaybackAdapter | null = null;
- if (win.__timeline) {
- const adapter = wrapTimeline(win.__timeline);
- const dur = getAdapterDuration(adapter);
- if (dur > 0 && docDuration <= dur) {
- releaseStaticSeekCache(staticSeekAdapterRef, staticSeekWarnedRef);
- return adapter;
- }
- if (dur > 0) timelineAdapter ??= adapter;
- }
-
- if (win.__timelines) {
- const keys = Object.keys(win.__timelines);
- if (keys.length > 0) {
- // Resolve the root composition id from the DOM — the outermost [data-composition-id]
- // is the master; otherwise Object.keys() order lets a sub-composition hijack transport.
- const rootId = iframe?.contentDocument
- ?.querySelector("[data-composition-id]")
- ?.getAttribute("data-composition-id");
- const key = rootId && rootId in win.__timelines ? rootId : keys[keys.length - 1];
- const adapter = wrapTimeline(win.__timelines[key]);
- const dur = getAdapterDuration(adapter);
- if (dur > 0 && docDuration <= dur) {
- releaseStaticSeekCache(staticSeekAdapterRef, staticSeekWarnedRef);
- return adapter;
- }
- if (dur > 0) timelineAdapter ??= adapter;
- }
- }
-
- // The document timeline extends past every native adapter's duration.
- // Wrap the best available adapter with the effective duration so the
- // seek slider, seek clamping, and duration display cover the full range.
- const bestAdapter = playerAdapter ?? timelineAdapter;
- const effectiveDuration = Math.max(
- usePlayerStore.getState().duration,
- docDuration,
- adapterDur,
- );
- if (
- bestAdapter &&
- effectiveDuration > 0 &&
- ("renderSeek" in bestAdapter || typeof bestAdapter.seek === "function")
- ) {
- return resolveStaticSeekFallback({
- cache: staticSeekAdapterRef,
- warned: staticSeekWarnedRef,
- bestAdapter,
- effectiveDuration,
- docDuration,
- clock: getDefaultStaticSeekPlaybackClock(win),
- getPlaybackRate: () => usePlayerStore.getState().playbackRate,
- });
- }
-
- return bestAdapter;
+ return resolvePlaybackAdapter(iframe, win, {
+ cache: staticSeekAdapterRef,
+ warned: staticSeekWarnedRef,
+ });
} catch {
return null;
}