Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): preview lookups use the right element when an id repeats across files (#4486)
Miguel Ángel4dc1bee9c239
diff --git a/packages/studio/src/components/editor/domEditingElement.ts b/packages/studio/src/components/editor/domEditingElement.tsindex d954e1d35f..045d20e85a 100644--- a/packages/studio/src/components/editor/domEditingElement.ts+++ b/packages/studio/src/components/editor/domEditingElement.ts@@ -314,6 +314,19 @@ export function findElementForSelection(return findAll(selection.selector)[selection.selectorIndex ?? 0] ?? null;}+// The selected node while mounted, else its copy in the selection's own file (ids repeat across files), else any copy.+export function findPreviewNode(+ doc: Document | null | undefined,+ el: DomEditSelection,+): Element | null {+ if (!doc) return null;+ if (el.element?.isConnected && el.element.ownerDocument === doc) return el.element;+ return (+ findElementForSelection(doc, el) ??+ findElementForSelection(doc, { ...el, sourceFile: undefined })+ );+}+// fallow-ignore-next-line complexityexport function findElementForTimelineElement(doc: Document,diff --git a/packages/studio/src/components/editor/gsapLivePreview.test.ts b/packages/studio/src/components/editor/gsapLivePreview.test.tsnew file mode 100644index 0000000000..60e6485d98--- /dev/null+++ b/packages/studio/src/components/editor/gsapLivePreview.test.ts@@ -0,0 +1,63 @@+// @vitest-environment happy-dom+import { expect, it, vi } from "vitest";+import { createGsapLivePreview } from "./gsapLivePreview";+import type { DomEditSelection } from "./domEditingTypes";+import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";+import { readGsapRuntimeValuesForPanel } from "./propertyPanelHelpers";++it("previews on the selected element, not an earlier same-id copy in a sub-composition", () => {+ document.body.innerHTML =+ '<div data-composition-id="strip"><div id="card" data-hf-id="hf-inner"></div></div>' ++ '<div id="card" data-hf-id="hf-root"></div>';+ const set = vi.fn();+ const iframe = { contentWindow: { gsap: { set } }, contentDocument: document };+ const preview = createGsapLivePreview({ current: iframe as unknown as HTMLIFrameElement });+ preview({ id: "card", hfId: "hf-root" } as DomEditSelection, { x: 10 });+ expect(set.mock.calls[0]?.[0]).toBe(document.querySelector('[data-hf-id="hf-root"]'));+});++it("previews on the copy in the selection's own file when a sub-composition repeats its hf-id", () => {+ document.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html">' ++ '<div id="card" data-hf-id="hf-card"></div></div><div id="card" data-hf-id="hf-card" class="root"></div>';+ const set = vi.fn();+ const iframe = { contentWindow: { gsap: { set } }, contentDocument: document };+ const preview = createGsapLivePreview({ current: iframe as unknown as HTMLIFrameElement });+ preview({ id: "card", hfId: "hf-card", sourceFile: "index.html" } as DomEditSelection, { x: 10 });+ expect(set.mock.calls[0]?.[0]).toBe(document.querySelector(".root"));+});++it("previews on the selected node while it is mounted, even in a second mount of the same sub-composition", () => {+ document.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html"><div id="card" data-hf-id="hf-card"></div></div>' ++ '<div data-composition-id="strip" data-composition-src="compositions/strip.html"><div id="card" data-hf-id="hf-card"></div></div>';+ const second = document.querySelectorAll<HTMLElement>("#card")[1];+ const selection = {+ id: "card",+ hfId: "hf-card",+ sourceFile: "compositions/strip.html",+ element: second,+ };+ const set = vi.fn();+ const iframe = { contentWindow: { gsap: { set } }, contentDocument: document };+ createGsapLivePreview({ current: iframe as unknown as HTMLIFrameElement })(+ selection as DomEditSelection,+ { x: 10 },+ );+ expect(set.mock.calls[0]?.[0]).toBe(second);+});++it("the panel reads GSAP values off the node the live preview moves", () => {+ document.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html"><div id="card"></div></div>' ++ '<div id="card" class="root"></div>';+ const root = document.querySelector<HTMLElement>(".root");+ const getProperty = vi.fn(() => 5);+ const iframe = { contentWindow: { gsap: { getProperty } }, contentDocument: document };+ const selection = { id: "card", sourceFile: "index.html", element: root } as DomEditSelection;+ const animations = [{ properties: { x: 5 } }] as unknown as GsapAnimation[];+ readGsapRuntimeValuesForPanel("anim", animations, selection, {+ current: iframe as unknown as HTMLIFrameElement,+ });+ expect(getProperty.mock.calls[0]?.[0]).toBe(root);+});diff --git a/packages/studio/src/components/editor/gsapLivePreview.ts b/packages/studio/src/components/editor/gsapLivePreview.tsindex ead64721a1..4f331a3f43 100644--- a/packages/studio/src/components/editor/gsapLivePreview.ts+++ b/packages/studio/src/components/editor/gsapLivePreview.ts@@ -1,4 +1,5 @@import type { DomEditSelection } from "./domEditingTypes";+import { findPreviewNode } from "./domEditingElement";/*** Build the "live preview" callback the 3D-transform sub-view fires while a@@ -8,19 +9,6 @@ import type { DomEditSelection } from "./domEditingTypes";* Extracted so the identical closure exists once — shared by the legacy* PropertyPanel Layout section and the flat Layout group (PropertyPanelFlat).*/-// Resolve by id when unique, otherwise by selector + selectorIndex — a bare-// querySelector(selector) always hits the FIRST match, so dragging on the-// second of two same-selector siblings would animate the wrong element.-function resolvePreviewNode(- doc: Document | null | undefined,- el: DomEditSelection,-): Element | null {- if (!doc) return null;- if (el.id) return doc.querySelector(`#${el.id}`);- if (!el.selector) return null;- return doc.querySelectorAll(el.selector)[el.selectorIndex ?? 0] ?? null;-}-export function createGsapLivePreview(iframeRef: { readonly current: HTMLIFrameElement | null }) {return (el: DomEditSelection, props: Record<string, number>) => {const iframe = iframeRef.current;@@ -28,7 +16,7 @@ export function createGsapLivePreview(iframeRef: { readonly current: HTMLIFrameE| { gsap?: { set: (t: Element, v: Record<string, number>) => void } }| null| undefined;- const node = resolvePreviewNode(iframe?.contentDocument, el);+ const node = findPreviewNode(iframe?.contentDocument, el);if (win?.gsap && node) win.gsap.set(node, props);};}diff --git a/packages/studio/src/components/editor/propertyPanelHelpers.ts b/packages/studio/src/components/editor/propertyPanelHelpers.tsindex 8fcb0ce988..3081106d46 100644--- a/packages/studio/src/components/editor/propertyPanelHelpers.ts+++ b/packages/studio/src/components/editor/propertyPanelHelpers.ts@@ -4,6 +4,7 @@ import type { DomEditSelection } from "./domEditing";import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";import type { TimelineElement } from "../../player";import { roundToCenti } from "../../utils/rounding";+import { findPreviewNode } from "./domEditingElement";export type {BackgroundRemovalProgress,@@ -470,8 +471,6 @@ export function readGsapRuntimeValuesForPanel(if (!gsapAnimId || gsapAnimations.length === 0) return null;const iframe = previewIframeRef?.current;if (!iframe?.contentWindow) return null;- const selector = element.id ? `#${element.id}` : element.selector;- if (!selector) return null;try {const gsap = (iframe.contentWindow as unknown as {@@ -479,7 +478,7 @@ export function readGsapRuntimeValuesForPanel(}).gsap;if (!gsap?.getProperty) return null;- const el = iframe.contentDocument?.querySelector(selector);+ const el = findPreviewNode(iframe.contentDocument, element);if (!el) return null;const propKeys = collectPanelPropKeys(gsapAnimations);const result: Record<string, number> = {};@@ -508,10 +507,9 @@ export function readGsapBorderRadiusForPanel(if (!hasBRProp) return null;}const iframe = previewIframeRef?.current;- const selector = element.id ? `#${element.id}` : element.selector;- if (!iframe?.contentDocument || !selector) return null;+ if (!iframe?.contentDocument) return null;try {- const el = iframe.contentDocument.querySelector(selector);+ const el = findPreviewNode(iframe.contentDocument, element);if (!el || !iframe.contentWindow) return null;const cs = iframe.contentWindow.getComputedStyle(el);const parse = (v: string) => Number.parseFloat(v) || 0;diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.tsindex c0b4dc0f5d..19178b24d3 100644--- a/packages/studio/src/hooks/useDomEditWiring.ts+++ b/packages/studio/src/hooks/useDomEditWiring.ts@@ -207,9 +207,7 @@ export function useDomEditWiring(params: UseDomEditWiringParams) {} = useGsapAnimationsForElement(projectId ?? null,gsapSourceFile,- domEditSelection- ? { id: domEditSelection.id ?? null, selector: domEditSelection.selector ?? null }- : null,+ domEditSelection,gsapCacheVersion,// Pass the preview iframe so class/selector tweens (e.g. `.dot`) resolve to// the live element and surface in the inspector — not just by #id match.diff --git a/packages/studio/src/hooks/useGestureRecording.test.tsx b/packages/studio/src/hooks/useGestureRecording.test.tsxindex abcd00e87d..5ce382c020 100644--- a/packages/studio/src/hooks/useGestureRecording.test.tsx+++ b/packages/studio/src/hooks/useGestureRecording.test.tsx@@ -109,7 +109,7 @@ describe("useGestureRecording", () => {act(() => root.unmount());expect(cancelAnimationFrame).toHaveBeenCalledWith(17);- expect(set).toHaveBeenCalledWith("#card", {+ expect(set).toHaveBeenCalledWith(element, {clearProps: "x,y,scale,scaleX,scaleY,rotation,rotationX,rotationY,opacity,z",});expect(element.style.visibility).toBe("hidden");diff --git a/packages/studio/src/hooks/useGestureRecording.ts b/packages/studio/src/hooks/useGestureRecording.tsindex 78c778b24c..1bba90974f 100644--- a/packages/studio/src/hooks/useGestureRecording.ts+++ b/packages/studio/src/hooks/useGestureRecording.ts@@ -30,8 +30,7 @@ interface BasePosition {interface GsapRuntime {timeline: { seek: (t: number) => void };- gsap: { set: (target: string, vars: Record<string, number | string>) => void };- selector: string;+ gsap: { set: (target: Element, vars: Record<string, number | string>) => void };element: HTMLElement;startTime: number;maxSeekTime: number;@@ -81,12 +80,11 @@ function readBasePosition(element: HTMLElement, iframeEl: HTMLIFrameElement): Bafunction connectGsapRuntime(element: HTMLElement,iframeEl: HTMLIFrameElement,- selector: string | null,elementEndTime: number | undefined,): GsapRuntime | null {try {const win = iframeEl.contentWindow as Window & {- gsap?: { set: (t: string, v: Record<string, number | string>) => void };+ gsap?: { set: (t: Element, v: Record<string, number | string>) => void };__timelines?: Record<string, { seek: (t: number) => void; duration: () => number }>;__player?: { getTime: () => number };};@@ -98,12 +96,11 @@ function connectGsapRuntime(([key, value]) => key !== "__proxied" && typeof value?.seek === "function",)?.[1] ?? null): null;- if (win?.gsap?.set && tl?.seek && selector) {+ if (win?.gsap?.set && tl?.seek && element.id) {const tlDuration = tl.duration();return {timeline: tl,gsap: win.gsap,- selector,element,startTime: win.__player?.getTime() ?? 0,maxSeekTime:@@ -126,7 +123,7 @@ function applyRuntimePreview(const seekTime = Math.min(runtime.startTime + time, runtime.maxSeekTime);runtime.timeline.seek(seekTime);runtime.element.style.setProperty("translate", "none");- runtime.gsap.set(runtime.selector, { ...properties });+ runtime.gsap.set(runtime.element, { ...properties });runtime.element.style.visibility = "visible";liveTime.notify(seekTime);usePlayerStore.getState().setCurrentTime(seekTime);@@ -256,7 +253,7 @@ function releaseRuntimePreview(r: RecordingRefs): void {element.style.visibility = savedVisibility;element.style.setProperty("translate", savedTranslate || "");try {- runtime.gsap.set(runtime.selector, {+ runtime.gsap.set(runtime.element, {clearProps: "x,y,scale,scaleX,scaleY,rotation,rotationX,rotationY,opacity,z",});} catch {@@ -324,8 +321,7 @@ export function useGestureRecording() {r.scale = computeIframeScale(iframeEl);// --- Phase 3: Connect to the iframe GSAP runtime ---- const selector = element.id ? `#${element.id}` : null;- r.runtime = connectGsapRuntime(element, iframeEl, selector, elementEndTime);+ r.runtime = connectGsapRuntime(element, iframeEl, elementEndTime);// Clear the optimistic path offset only while a live runtime owns the// preview. releaseRuntimePreview restores it on every exit path.if (r.runtime && (base.cssOffX || base.cssOffY)) {diff --git a/packages/studio/src/hooks/useGsapTweenCache.element.test.tsx b/packages/studio/src/hooks/useGsapTweenCache.element.test.tsxnew file mode 100644index 0000000000..67f05f49b6--- /dev/null+++ b/packages/studio/src/hooks/useGsapTweenCache.element.test.tsx@@ -0,0 +1,39 @@+// @vitest-environment happy-dom+import { act } from "react";+import { expect, it, vi } from "vitest";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";++installReactActEnvironment();++const dotTween = {+ id: "dots",+ targetSelector: ".dot",+ method: "from",+ position: 0,+ properties: { opacity: 0 },+} as GsapAnimation;+vi.mock("./keyframeCacheAstLoad", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./keyframeCacheAstLoad")>()),+ fetchParsedAnimations: async () => ({ animations: [dotTween] }),+}));+const { useGsapAnimationsForElement } = await import("./useGsapTweenCache");++it("attributes a class tween by the selected element, not an earlier same-id copy in a sub-composition", async () => {+ document.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html"><div id="card"></div></div>' ++ '<div id="card" class="dot"></div>';+ const element = document.querySelectorAll<HTMLElement>("#card")[1];+ const selection = { id: "card", sourceFile: "index.html", element } as DomEditSelection;+ const iframeRef = { current: { contentDocument: document } as unknown as HTMLIFrameElement };+ let animations: GsapAnimation[] = [];+ function Harness() {+ animations = useGsapAnimationsForElement("p", "index.html", selection, 0, iframeRef).animations;+ return null;+ }+ const root = mountReactHarness(<Harness />);+ await act(async () => {});+ expect(animations.map((animation) => animation.id)).toEqual(["dots"]);+ act(() => root.unmount());+});diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.tsindex 9b3a8aa22f..1551b9ddf5 100644--- a/packages/studio/src/hooks/useGsapTweenCache.ts+++ b/packages/studio/src/hooks/useGsapTweenCache.ts@@ -1,6 +1,8 @@import { useEffect, useMemo, useRef, useState, useCallback } from "react";import type { GsapAnimation, GsapKeyframesData } from "@hyperframes/core/gsap-parser";import { usePlayerStore } from "../player/store/playerStore";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { findPreviewNode } from "../components/editor/domEditingElement";import { readRuntimeKeyframes, scanAllRuntimeKeyframes } from "./gsapRuntimeBridge";import {clearKeyframeCacheForElement,@@ -73,7 +75,7 @@ export function getAnimationsForElement(export function useGsapAnimationsForElement(projectId: string | null,sourceFile: string,- target: GsapElementTarget | null,+ target: DomEditSelection | null,version: number,iframeRef?: React.RefObject<HTMLIFrameElement | null>,): {@@ -157,24 +159,14 @@ export function useGsapAnimationsForElement(// gsap.from(".dot", {stagger})) attribute to every matching element, not// just the one whose exact selector equals the tween's. `version` re-runs// this after composition reloads.- let element: Element | null = null;- const doc = iframeRef?.current?.contentDocument;- if (doc) {- try {- element =- (targetId ? doc.getElementById(targetId) : null) ??- (targetSelector ? doc.querySelector(targetSelector) : null);- } catch {- element = null;- }- }+ const element = target ? findPreviewNode(iframeRef?.current?.contentDocument, target) : null;return getAnimationsForElement(allAnimations,{ id: targetId, selector: targetSelector },element,);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [allAnimations, targetId, targetSelector, version, iframeRef]);+ }, [allAnimations, target, version, iframeRef]);// fallow-ignore-next-line complexityconst animations = useMemo(() => {diff --git a/packages/studio/src/player/lib/automationStoreSync.test.ts b/packages/studio/src/player/lib/automationStoreSync.test.tsindex 1786c3cd7a..a66b399141 100644--- a/packages/studio/src/player/lib/automationStoreSync.test.ts+++ b/packages/studio/src/player/lib/automationStoreSync.test.ts@@ -33,6 +33,30 @@ beforeEach(() => {});describe("syncStoredAutomationFromPreview", () => {+ it("reads the element the timeline bound, not an earlier same-id copy in a sub-composition", () => {+ usePlayerStore.setState({ elements: [el({ hfId: "hf-root" })] });+ const doc = document.implementation.createHTMLDocument("preview");+ doc.body.innerHTML =+ '<div data-composition-id="strip"><audio id="bgm" data-hf-id="hf-inner"></audio></div>' ++ '<audio id="bgm" data-hf-id="hf-root"></audio>';+ doc.querySelector('[data-hf-id="hf-inner"]')?.setAttribute("data-automation", TWO_POINTS);+ doc.querySelector('[data-hf-id="hf-root"]')?.setAttribute("data-automation", RESTORED);+ syncStoredAutomationFromPreview(doc);+ expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);+ });++ it("reads the copy in the element's own file when a sub-composition repeats its hf-id", () => {+ usePlayerStore.setState({ elements: [el({ hfId: "hf-bgm" })] });+ const doc = document.implementation.createHTMLDocument("preview");+ doc.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html">' ++ '<audio id="bgm" data-hf-id="hf-bgm"></audio></div><audio id="bgm" data-hf-id="hf-bgm"></audio>';+ doc.querySelectorAll("audio")[0]?.setAttribute("data-automation", TWO_POINTS);+ doc.querySelectorAll("audio")[1]?.setAttribute("data-automation", RESTORED);+ syncStoredAutomationFromPreview(doc);+ expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);+ });+it("reads back an envelope an undo restored on the preview", () => {// The bug: a soft undo patches the preview document and re-runs the timeline, but// the store keeps its own copy of the attributes and that copy is what a lanediff --git a/packages/studio/src/player/lib/automationStoreSync.ts b/packages/studio/src/player/lib/automationStoreSync.tsindex 2b7f79762b..61d742dc23 100644--- a/packages/studio/src/player/lib/automationStoreSync.ts+++ b/packages/studio/src/player/lib/automationStoreSync.ts@@ -17,14 +17,7 @@ import { HF_AUDIO_AUTOMATION_ATTR } from "@hyperframes/core/audio-automation";import { HF_AUDIO_FX_ATTR } from "@hyperframes/core/audio-fx";import { usePlayerStore, type TimelineElement } from "../store/playerStore";import { groupInfoFor } from "./timelineGroupInfo";--/** The preview node an element stands for, by dom id and then by `data-hf-id`. */-function previewNodeFor(doc: Document, element: TimelineElement): Element | null {- const domId = element.domId ?? element.id;- const byId = domId ? doc.getElementById(domId) : null;- if (byId) return byId;- return element.hfId ? doc.querySelector(`[data-hf-id="${element.hfId}"]`) : null;-}+import { previewElementFinder } from "./timelineElementHelpers";/*** Re-read every element's automation and FX-chain attributes from the preview@@ -62,10 +55,11 @@ function syncedFields(doc: Document, element: TimelineElement, node: Element) {export function syncStoredAutomationFromPreview(doc: Document | null | undefined): void {if (!doc) return;+ const findNode = previewElementFinder(doc);usePlayerStore.setState((state) => {let changed = false;const elements = state.elements.map((element) => {- const node = previewNodeFor(doc, element);+ const node = findNode(element);if (!node) return element;const fields = syncedFields(doc, element, node);// Same array back when nothing moved: `elements` keys memos all over thediff --git a/packages/studio/src/player/lib/playbackScrub.ts b/packages/studio/src/player/lib/playbackScrub.tsindex 5119f50d13..4bfbbd1e8d 100644--- a/packages/studio/src/player/lib/playbackScrub.ts+++ b/packages/studio/src/player/lib/playbackScrub.ts@@ -12,5 +12,5 @@ export function scrubMusicAtSeek(iframe: HTMLIFrameElement | null, nextTime: numif (!music || s.audioMuted) return;const rel = nextTime - music.start;const audioFileTime = rel >= 0 && rel <= music.duration ? (music.playbackStart ?? 0) + rel : null;- scrubPreviewAudio(iframe, audioFileTime, music.domId ?? music.id, s.audioVolume);+ scrubPreviewAudio(iframe, audioFileTime, music, s.audioVolume);}diff --git a/packages/studio/src/player/lib/timelineDOM.test.ts b/packages/studio/src/player/lib/timelineDOM.test.tsindex 3382fc784d..e0605037b4 100644--- a/packages/studio/src/player/lib/timelineDOM.test.ts+++ b/packages/studio/src/player/lib/timelineDOM.test.ts@@ -285,6 +285,34 @@ describe("createTimelineElementFromManifestClip — source-scoped selector ident});});+ it("keeps the host it was given when a sub-composition is mounted twice", () => {+ const doc = makeDoc(`+ <div data-composition-id="root" data-composition-file="index.html">+ <div id="a" data-hf-id="hf-a" data-composition-id="card" data-composition-src="card.html"></div>+ <div id="b" data-hf-id="hf-b" data-composition-id="card" data-composition-src="card.html"></div>+ </div>+ `);+ const element = createTimelineElementFromManifestClip({+ clip: {+ id: "b",+ label: "Card",+ kind: "composition",+ tagName: "div",+ start: 4,+ duration: 4,+ track: 0,+ compositionId: "card",+ parentCompositionId: "root",+ compositionSrc: null,+ assetUrl: null,+ },+ fallbackIndex: 1,+ doc,+ hostEl: doc.getElementById("b"),+ });+ expect(element).toMatchObject({ domId: "b", hfId: "hf-b", compositionSrc: "card.html" });+ });+it("ignores an index.html duplicate when indexing a scene.html selector", () => {const doc = makeDoc(`<div data-composition-id="root" data-composition-file="index.html">diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.tsindex 46d36d3c05..74bd053bd6 100644--- a/packages/studio/src/player/lib/timelineDOM.ts+++ b/packages/studio/src/player/lib/timelineDOM.ts@@ -171,8 +171,10 @@ export function createTimelineElementFromManifestClip(params: {entry.playbackRate ??= 1;let resolvedSrc = clip.compositionSrc;if (!resolvedSrc) {- hostEl =- doc?.querySelector(`[data-composition-id="${CSS.escape(clip.compositionId)}"]`) ?? hostEl;+ if (hostEl?.getAttribute("data-composition-id") !== clip.compositionId) {+ hostEl =+ doc?.querySelector(`[data-composition-id="${CSS.escape(clip.compositionId)}"]`) ?? hostEl;+ }resolvedSrc =hostEl?.getAttribute("data-composition-src") ??hostEl?.getAttribute("data-composition-file") ??diff --git a/packages/studio/src/player/lib/timelineElementHelpers.ts b/packages/studio/src/player/lib/timelineElementHelpers.tsindex e75eb060f3..2589b11768 100644--- a/packages/studio/src/player/lib/timelineElementHelpers.ts+++ b/packages/studio/src/player/lib/timelineElementHelpers.ts@@ -458,6 +458,39 @@ function findInClipScope(return lone;}+export type PreviewTarget = Pick<TimelineElement, "hfId" | "domId" | "id" | "sourceFile">;++/** Finds a row's preview element by `data-hf-id`, then id, preferring one in the row's own file: both repeat across+ * files. Indexes the document once, so a pass over every row costs one scan. */+export function previewElementFinder(+ doc: Document,+ selector = "[data-hf-id], [id]",+): (target: PreviewTarget) => Element | null {+ const byKey = new Map<string, Element[]>();+ const add = (key: string, node: Element) => {+ const nodes = byKey.get(key);+ if (nodes) nodes.push(node);+ else byKey.set(key, [node]);+ };+ for (const node of doc.querySelectorAll(selector)) {+ const hfId = node.getAttribute("data-hf-id");+ const id = node.getAttribute("id");+ if (hfId) add(`hf:${hfId}`, node);+ if (id) add(`id:${id}`, node);+ }+ return (target) => {+ const matches = [+ ...((target.hfId && byKey.get(`hf:${target.hfId}`)) || []),+ ...(byKey.get(`id:${target.domId ?? target.id}`) ?? []),+ ];+ return (+ matches.find((node) => getTimelineElementSourceFile(node) === target.sourceFile) ??+ matches[0] ??+ null+ );+ };+}+export function findClipElementById(doc: Document, clip: ClipManifestClip): Element | null {if (!clip.id) return null;const first = doc.getElementById(clip.id);diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.test.ts b/packages/studio/src/player/lib/timelineIframeHelpers.test.tsindex 143b58fb81..8fa3408097 100644--- a/packages/studio/src/player/lib/timelineIframeHelpers.test.ts+++ b/packages/studio/src/player/lib/timelineIframeHelpers.test.ts@@ -17,6 +17,31 @@ function makeDoc(html: string): Document {}describe("buildMissingCompositionElements — hfId (R7)", () => {+ it("labels a row from its own host when a sub-composition repeats the host's id", () => {+ const doc = makeDoc(`+ <div data-composition-id="main">+ <div data-composition-id="strip" data-composition-src="compositions/strip.html"><div id="scene"></div></div>+ <div id="scene" data-hf-id="hf-scene" data-composition-id="scene" data-composition-file="compositions/scene.html"></div>+ </div>+ `);+ const row = {+ id: "scene",+ key: "scene",+ tag: "div",+ start: 0,+ duration: 4,+ track: 0,+ hfId: "hf-scene",+ };+ const { updatedEls, patched } = buildMissingCompositionElements(+ doc,+ window as IframeWindow,+ [row],+ 10,+ );+ expect([patched, updatedEls[0]?.compositionSrc]).toEqual([true, "compositions/scene.html"]);+ });+it("harvests hfId from data-hf-id on composition host elements", () => {const doc = makeDoc(`<div data-composition-id="root">@@ -104,7 +129,7 @@ describe("scrubPreviewAudio", () => {audio.pause = vi.fn();iframe.contentDocument.body.append(audio);- scrubPreviewAudio(iframe, 0.5, "music", 0.4);+ scrubPreviewAudio(iframe, 0.5, { id: "music" }, 0.4);expect(audio.volume).toBeCloseTo(0.1);stopScrubPreviewAudio();@@ -112,13 +137,13 @@ describe("scrubPreviewAudio", () => {/*** The preview document is a different realm, so `instanceof HTMLAudioElement`- * is false for every node in it. That threw the `musicId` hint away and left+ * is false for every node in it. That threw the `music` hint away and left* the first `<audio>` in the document as the only route — and the first* `<audio>` is often the voiceover, so scrubbing previewed the wrong track.* Two elements, music second, is what tells the two paths apart: with one* element the fallback reaches the right node by accident.*/- it("previews the track named by musicId, not the first audio in the document", () => {+ it("previews the track named by the music row, not the first audio in the document", () => {const iframe = document.createElement("iframe");document.body.append(iframe);const previewDoc = iframe.contentDocument;@@ -139,13 +164,32 @@ describe("scrubPreviewAudio", () => {// The node really is cross-realm; this is the condition, not a contrivance.expect(music instanceof HTMLAudioElement).toBe(false);- scrubPreviewAudio(iframe, 0.5, "music-bed", 1);+ scrubPreviewAudio(iframe, 0.5, { id: "music-bed" }, 1);expect(music.play).toHaveBeenCalled();expect(voiceover.play).not.toHaveBeenCalled();stopScrubPreviewAudio();});+ it("previews the music row's own track when a sub-composition repeats its id", () => {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ const previewDoc = iframe.contentDocument;+ if (!previewDoc?.body) throw new Error("expected an iframe document");+ previewDoc.body.innerHTML =+ '<div data-composition-id="strip" data-composition-src="compositions/strip.html"><audio id="music"></audio></div>' ++ '<audio id="music" class="root"></audio>';+ const [inner, root] = Array.from(previewDoc.querySelectorAll("audio"));+ for (const audio of [inner, root])+ Object.assign(audio!, { play: vi.fn(async () => {}), pause: vi.fn() });++ scrubPreviewAudio(iframe, 0.5, { id: "music" }, 1);++ expect(root!.play).toHaveBeenCalled();+ expect(inner!.play).not.toHaveBeenCalled();+ stopScrubPreviewAudio();+ });+/** A scrub audition is media running under a paused clock, which the runtime now* stops on sight. So it borrows the element. That a leased element survives the* tick is asserted runtime-side in core's `transportPark.test.ts`; here the@@ -166,7 +210,7 @@ describe("scrubPreviewAudio", () => {const releasePausedMedia = vi.fn();(previewDoc.defaultView as IframeWindow).__hf = { leasePausedMedia, releasePausedMedia };- scrubPreviewAudio(iframe, 0.5, "music", 1);+ scrubPreviewAudio(iframe, 0.5, { id: "music" }, 1);expect(leasePausedMedia).toHaveBeenCalledWith(music);expect(releasePausedMedia).not.toHaveBeenCalled();diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.ts b/packages/studio/src/player/lib/timelineIframeHelpers.tsindex 777790d5d3..75fec43136 100644--- a/packages/studio/src/player/lib/timelineIframeHelpers.ts+++ b/packages/studio/src/player/lib/timelineIframeHelpers.ts@@ -20,6 +20,8 @@ import {getTimelineElementDisplayLabel,buildTimelineElementIdentity,readTimelineElementZIndex,+ previewElementFinder,+ type PreviewTarget,} from "./timelineElementHelpers";import { postRuntimeControlMessage } from "./runtimeProtocol";import { transitionLabelsForDocument } from "./timelineTransitionMetadata";@@ -216,14 +218,14 @@ let scrubStopTimer: ReturnType<typeof setTimeout> | null = null;let scrubPrevMuted: boolean | null = null;let scrubPrevVolume: number | null = null;-// Resolve the SAME element the store identified as music: prefer its id, then-// the role attribute, and only fall back to the first <audio> (which could be a-// voiceover, so the id hint matters).+// Resolve the SAME element the store identified as music: prefer that row's own+// element, then the role attribute, and only fall back to the first <audio>+// (which could be a voiceover, so the row hint matters)./*** `doc` is the preview iframe's document, so its `<audio>` nodes are instances of* the IFRAME's `HTMLAudioElement`, never this module's. `instanceof* HTMLAudioElement` here is false for every one of them, which silently threw the- * `musicId` hint away and fell through to "first `<audio>` in the document" — the+ * `music` hint away and fell through to "first `<audio>` in the document" — the* very thing the comment above warns can be a voiceover. Ask what the node IS.* Same rule and same reasoning as packages/core/src/runtime/domRealm.ts.*/@@ -235,9 +237,9 @@ function isAudioNode(node: Element | null): node is HTMLAudioElement {);}-function resolveScrubAudioEl(doc: Document, musicId?: string | null): HTMLAudioElement | null {- if (musicId) {- const byId = doc.getElementById(musicId);+function resolveScrubAudioEl(doc: Document, music?: PreviewTarget | null): HTMLAudioElement | null {+ if (music) {+ const byId = previewElementFinder(doc, "audio")(music);if (isAudioNode(byId)) return byId;}return (@@ -283,7 +285,7 @@ function applyScrub(el: HTMLAudioElement, audioFileTime: number, previewVolume:export function scrubPreviewAudio(iframe: HTMLIFrameElement | null,audioFileTime: number | null,- musicId?: string | null,+ music?: PreviewTarget | null,previewVolume = 1,): void {if (!iframe) return;@@ -298,7 +300,7 @@ export function scrubPreviewAudio(return;}if (!doc) return;- const el = resolveScrubAudioEl(doc, musicId);+ const el = resolveScrubAudioEl(doc, music);if (el) applyScrub(el, audioFileTime, previewVolume);}@@ -512,12 +514,11 @@ export function buildMissingCompositionElements(// Patch existing elements that are missing compositionSrclet patched = false;+ const findHost = previewElementFinder(doc);const updatedEls = (currentEls as TimelineElement[]).map((existing) => {if (existing.compositionSrc) return existing;- // Find the matching DOM host by element id or composition idconst host =- doc.getElementById(existing.id) ??- doc.querySelector(`[data-composition-id="${CSS.escape(existing.id)}"]`);+ findHost(existing) ?? doc.querySelector(`[data-composition-id="${CSS.escape(existing.id)}"]`);if (!host) return existing;const compSrc =host.getAttribute("data-composition-src") || host.getAttribute("data-composition-file");