Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): a copied clip pastes as saved, not with the preview's hidden styles (#4506)
Miguel Ángel516320c28d03
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsxindex dff32fe210..a70645f463 100644--- a/packages/studio/src/App.tsx+++ b/packages/studio/src/App.tsx@@ -239,6 +239,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: SthandleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,handleDomEditElementDelete: domEditDeleteBridge,previewIframeRef,+ waitForPendingDomEditSaves: previewPersistence.waitForPendingDomEditSaves,});const appHotkeys = useAppHotkeys({handleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,diff --git a/packages/studio/src/hooks/useClipboard.source.test.ts b/packages/studio/src/hooks/useClipboard.source.test.tsnew file mode 100644index 0000000000..715d7bf24a--- /dev/null+++ b/packages/studio/src/hooks/useClipboard.source.test.ts@@ -0,0 +1,340 @@+// @vitest-environment jsdom+import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { ensureHfIds } from "@hyperframes/parsers/hf-ids";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useClipboard } from "./useClipboard";+import { usePlayerStore, type TimelineElement } from "../player";+import type { DomEditSelection } from "../components/editor/domEditing";+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";++// Saved without hf-ids and with no element id: the preview stamps ids only in memory.+const SAVED = `<!doctype html><html><body>+<div data-composition-id="main" data-start="0" data-duration="10">+<h1 class="clip" data-start="2" data-duration="3" data-track-index="0">Title</h1>+</div></body></html>`;++const SUB = `<template id="sub-template"><div data-composition-id="sub" data-start="0" data-duration="4">+<h2 class="clip" data-start="1" data-duration="2" data-track-index="0">Sub</h2>+</div></template>`;++// What the runtime leaves on a clip while the playhead is before its start.+const RUNTIME_HIDE = "visibility: hidden; display: none; position: absolute";++function stampedHfId(source: string, selector: string): string {+ const doc = new DOMParser().parseFromString(ensureHfIds(source), "text/html");+ const roots = [doc, ...Array.from(doc.querySelectorAll("template"), (t) => t.content)];+ const el = roots.map((root) => root.querySelector(selector)).find(Boolean);+ return el?.getAttribute("data-hf-id") ?? "";+}++const TITLE_HF_ID = stampedHfId(SAVED, "h1");+const SUB_HF_ID = stampedHfId(SUB, "h2");++const TITLE: TimelineElement = {+ id: TITLE_HF_ID,+ hfId: TITLE_HF_ID,+ tag: "h1",+ start: 2,+ duration: 3,+ track: 0,+ authoredTrack: 0,+ sourceFile: "index.html",+};++let root: Root | null = null;+afterEach(() => {+ act(() => root?.unmount());+ root = null;+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+});++// The preview page: the saved markup with the preview's in-memory ids, a sub-composition+// mounted inline, and the runtime's hide on both clips.+function mountPreview(sub: string, bundle: (host: Element) => void): HTMLIFrameElement {+ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ const doc = iframe.contentDocument as Document;+ doc.open();+ doc.write(ensureHfIds(SAVED));+ doc.close();+ const parsed = new DOMParser().parseFromString(ensureHfIds(sub), "text/html");+ const subRoot = (parsed.querySelector("template") as HTMLTemplateElement).content+ .firstElementChild;+ const host = doc.createElement("div");+ host.setAttribute("data-composition-src", "compositions/sub.html");+ host.append(doc.importNode(subRoot as Element, true));+ bundle(host);+ doc.querySelector('[data-composition-id="main"]')?.append(host);+ for (const clip of doc.querySelectorAll(".clip"))+ (clip as HTMLElement).style.cssText = RUNTIME_HIDE;+ return iframe;+}++function stubFiles(+ files: Record<string, string>,+ fail: { on: boolean },+ delayMs: Record<string, number>,+) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ const path = decodeURIComponent(String(url).split("/files/")[1] ?? "");+ // The server answers later, so a write that lands first is what the read sees.+ await new Promise((resolve) => setTimeout(resolve, delayMs[path] ?? 0));+ if (fail.on) return new Response("", { status: 500 });+ return new Response(JSON.stringify({ content: files[path] }));+ }),+ );+}++function mountClipboard(+ domSelection: DomEditSelection | null = null,+ sub = SUB,+ bundle: (host: Element) => void = () => {},+) {+ const files: Record<string, string> = { "index.html": SAVED, "compositions/sub.html": sub };+ const fail = { on: false };+ const delayMs: Record<string, number> = {};+ const domEditSave = { pending: Promise.resolve() };+ const domSelectionRef = { current: domSelection };+ stubFiles(files, fail, delayMs);+ const iframe = mountPreview(sub, bundle);+ const writes: string[] = [];+ const deleted: string[] = [];+ const writeProjectFile = async (_path: string, content: string) => {+ writes.push(content);+ };+ let api: ReturnType<typeof useClipboard> | null = null;+ function Harness() {+ api = useClipboard({+ projectId: "p",+ activeCompPath: "index.html",+ domEditSelectionRef: domSelectionRef,+ showToast: () => {},+ writeProjectFile,+ recordEdit: async () => {},+ reloadPreview: () => {},+ handleTimelineElementsDelete: async (elements) => {+ deleted.push(...elements.map((el) => el.id));+ files["index.html"] = SAVED.replace(/<h1[\s\S]*<\/h1>/, "");+ },+ handleDomEditElementDelete: async () => {},+ previewIframeRef: { current: iframe },+ waitForPendingDomEditSaves: () => domEditSave.pending,+ });+ return null;+ }+ root = createRoot(document.createElement("div"));+ act(() => root?.render(React.createElement(Harness)));+ const clipboard = () => api as ReturnType<typeof useClipboard>;+ return {+ clipboard,+ writes,+ deleted,+ files,+ fail,+ writeProjectFile,+ iframe,+ delayMs,+ domEditSave,+ domSelectionRef,+ };+}++function selectTitle() {+ usePlayerStore.setState({+ elements: [TITLE],+ selectedElementId: TITLE.id,+ selectedElementIds: new Set([TITLE.id]),+ currentTime: 6,+ });+}++function clearSelection() {+ usePlayerStore.setState({ selectedElementId: null, selectedElementIds: new Set() });+}++describe("copy takes a clip's saved markup, not the runtime's live styling", () => {+ it("pastes a timeline clip copied while hidden, matched through the preview's hf-id", async () => {+ selectTitle();+ const { clipboard, writes } = mountClipboard();+ expect(clipboard().handleCopy()).toBe(true);+ await clipboard().handlePaste();+ expect(writes).toHaveLength(1);+ expect(writes[0]).toContain(">Title</h1>");+ expect(writes[0]).not.toContain("display: none");+ expect(writes[0]).not.toContain("visibility: hidden");+ });++ it("pastes a sub-composition clip copied while hidden, found inside its template", async () => {+ clearSelection();+ const selection = {+ hfId: SUB_HF_ID,+ selector: "h2",+ selectorIndex: 0,+ sourceFile: "compositions/sub.html",+ } as DomEditSelection;+ const { clipboard, writes } = mountClipboard(selection);+ expect(clipboard().handleCopy()).toBe(true);+ await clipboard().handlePaste();+ expect(writes).toHaveLength(1);+ expect(writes[0]).toContain(">Sub</h2>");+ expect(writes[0]).not.toContain("display: none");+ });++ it("cuts only once the saved markup is read, and pastes it", async () => {+ selectTitle();+ const { clipboard, writes, deleted } = mountClipboard();+ await clipboard().handleCut();+ expect(deleted).toEqual([TITLE.id]);+ await clipboard().handlePaste();+ expect(writes[0]).toContain(">Title</h1>");+ expect(writes[0]).not.toContain("display: none");+ });++ it("reads a save still in flight when the copy starts", async () => {+ selectTitle();+ const { clipboard, writes, files, writeProjectFile } = mountClipboard();+ void serializeStudioFileMutations(writeProjectFile, ["index.html"], async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ // The host pins hf-ids on disk, so a Studio save keeps the clip's id.+ files["index.html"] = ensureHfIds(SAVED).replace(">Title<", ">Title v2<");+ });+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]?.match(/>Title v2<\/h1>/g)).toHaveLength(2);+ expect(writes[0]).not.toContain(">Title</h1>");+ });++ it("finds a clip by its id once its saved markup no longer hashes to the preview's hf-id", async () => {+ selectTitle();+ const { clipboard, writes, files, iframe } = mountClipboard();+ iframe.contentDocument?.querySelector("h1")?.setAttribute("id", "title");+ files["index.html"] = SAVED.replace("<h1 ", '<h1 id="title" ').replace(">Title<", ">Title v2<");+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]?.match(/>Title v2<\/h1>/g)).toHaveLength(2);+ expect(writes[0]).not.toContain("display: none");+ });+});++const SUB_SELECTION = {+ hfId: SUB_HF_ID,+ selector: "h2",+ selectorIndex: 0,+ sourceFile: "compositions/sub.html",+} as DomEditSelection;++describe("copy of a sub-composition clip", () => {+ it("rebases its relative asset paths to the project root, as the preview does", async () => {+ clearSelection();+ const sub = SUB.replace(+ ">Sub<",+ '><img src="../assets/logo.png?v=2"><img src="logo.png"><img src="assets/shared.png">' ++ '<img src="../assets/100%.png"><span style="background: url(\'../fonts/My Font.woff2\')"></span>Sub<',+ );+ const selection = { ...SUB_SELECTION, hfId: stampedHfId(sub, "h2") };+ const { clipboard, writes } = mountClipboard(selection, sub, (host) => {+ const [up, sibling] = Array.from(host.querySelectorAll("img"));+ up?.setAttribute("src", "assets/logo.png?v=2");+ sibling?.setAttribute("src", "compositions/logo.png");+ });+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]).toContain('src="assets/logo.png?v=2"');+ expect(writes[0]).toContain('src="compositions/logo.png"');+ expect(writes[0]).toContain('src="assets/shared.png"');+ expect(writes[0]).toContain('src="assets/100%.png"');+ expect(writes[0]).toContain("url('fonts/My Font.woff2')");+ expect(writes[0]).not.toContain("../");+ expect(writes[0]).not.toContain("display: none");+ });+});++describe("copy order", () => {+ it("waits for a DOM edit save still in flight", async () => {+ selectTitle();+ const { clipboard, writes, files, domEditSave } = mountClipboard();+ domEditSave.pending = new Promise((resolve) =>+ setTimeout(() => {+ files["index.html"] = ensureHfIds(SAVED).replace(">Title<", ">Title v2<");+ resolve();+ }, 5),+ );+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]?.match(/>Title v2<\/h1>/g)).toHaveLength(2);+ });++ it("still copies after a DOM edit save failed", async () => {+ selectTitle();+ const { clipboard, writes, domEditSave } = mountClipboard();+ domEditSave.pending = Promise.reject(new Error("save conflict"));+ domEditSave.pending.catch(() => {});+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]?.match(/>Title<\/h1>/g)).toHaveLength(2);+ });++ it("pastes the second of two copies", async () => {+ selectTitle();+ const { clipboard, writes, domSelectionRef } = mountClipboard();+ clipboard().handleCopy();+ await new Promise((resolve) => setTimeout(resolve, 10));+ clearSelection();+ domSelectionRef.current = SUB_SELECTION;+ clipboard().handleCopy();+ await clipboard().handlePaste();+ expect(writes[0]).toContain(">Sub</h2>");+ expect(writes[0]?.match(/>Title<\/h1>/g)).toHaveLength(1);+ });++ it("pastes the later copy even when the earlier copy's read lands last", async () => {+ selectTitle();+ const { clipboard, writes, delayMs, domSelectionRef } = mountClipboard();+ delayMs["index.html"] = 20;+ clipboard().handleCopy();+ clearSelection();+ domSelectionRef.current = SUB_SELECTION;+ clipboard().handleCopy();+ await new Promise((resolve) => setTimeout(resolve, 40));+ delayMs["index.html"] = 0;+ await clipboard().handlePaste();+ expect(writes[0]).toContain(">Sub</h2>");+ expect(writes[0]?.match(/>Title<\/h1>/g)).toHaveLength(1);+ });++ it("duplicates a hidden clip with its saved markup", async () => {+ selectTitle();+ const { clipboard, writes } = mountClipboard();+ await clipboard().handleDuplicate();+ expect(writes[0]?.match(/>Title<\/h1>/g)).toHaveLength(2);+ expect(writes[0]).not.toContain("display: none");+ });+});++describe("a copy that fails", () => {+ it("leaves the previous copy on the clipboard", async () => {+ selectTitle();+ const { clipboard, writes, fail } = mountClipboard();+ clipboard().handleCopy();+ await new Promise((resolve) => setTimeout(resolve, 10));+ fail.on = true;+ clipboard().handleCopy();+ await new Promise((resolve) => setTimeout(resolve, 10));+ fail.on = false;+ await clipboard().handlePaste();+ expect(writes).toHaveLength(1);+ expect(writes[0]).toContain(">Title</h1>");+ });++ it("deletes nothing on a cut", async () => {+ selectTitle();+ const { clipboard, deleted, fail } = mountClipboard();+ fail.on = true;+ expect(await clipboard().handleCut()).toBe(false);+ expect(deleted).toEqual([]);+ });+});diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.tsindex f7505e2366..2bdeef8d5e 100644--- a/packages/studio/src/hooks/useClipboard.ts+++ b/packages/studio/src/hooks/useClipboard.ts@@ -19,6 +19,13 @@ import { findElementForSelection } from "../components/editor/domEditingElement"import { findTimelineElementInIframe, readFileContent } from "./timelineEditingHelpers";import { buildTimelineElementKey } from "../player/lib/timelineElementHelpers";import { timeRangesOverlap } from "../player/components/timelineCollision";+import {+ authoredMarkup,+ findAuthoredElement,+ findAuthoredElementById,+ parseSavedSource,+} from "../utils/authoredSource";+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";interface RecordEditInput {label: string;@@ -37,6 +44,7 @@ interface UseClipboardOptions {handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;handleDomEditElementDelete: (selection: DomEditSelection) => Promise<void>;previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;+ waitForPendingDomEditSaves: () => Promise<void>;}/** The timeline element(s) a copy/cut/duplicate acts on: the multi-selection@@ -62,11 +70,11 @@ function clipToast(verbPast: string, clipCount: number): string {return clipCount > 1 ? `${verbPast} ${clipCount} clips` : `${verbPast} clip`;}-function getElementOuterHtml(+function getSelectedDomElement(iframeRef: React.MutableRefObject<HTMLIFrameElement | null>,selection: DomEditSelection,activeCompositionPath: string | null,-): string | null {+): Element | null {let doc: Document | null = null;try {doc = iframeRef.current?.contentDocument ?? null;@@ -75,7 +83,27 @@ function getElementOuterHtml(}if (!doc) return null;- return findElementForSelection(doc, selection, activeCompositionPath)?.outerHTML ?? null;+ return findElementForSelection(doc, selection, activeCompositionPath);+}++function savedMarkupElseLive(saved: Document, live: Element, sourceFile: string): string {+ const authored = findAuthoredElement(saved, live) ?? findAuthoredElementById(saved, live);+ return authored ? authoredMarkup(authored, live, sourceFile) : live.outerHTML;+}++async function readSavedMarkup(+ readSaved: (path: string) => Promise<string>,+ paths: string[],+ lives: Element[],+): Promise<string[]> {+ const sources = new Map<string, Promise<Document>>();+ return Promise.all(+ paths.map(async (path, index) => {+ if (!sources.has(path)) sources.set(path, readSaved(path).then(parseSavedSource));+ const saved = await (sources.get(path) as Promise<Document>);+ return savedMarkupElseLive(saved, lives[index] as Element, path);+ }),+ );}export interface PlacedClip {@@ -195,86 +223,130 @@ export function useClipboard({handleTimelineElementsDelete,handleDomEditElementDelete,previewIframeRef,+ waitForPendingDomEditSaves,}: UseClipboardOptions) {- const clipboardRef = useRef<ClipboardPayload | null>(null);+ const clipboardRef = useRef<Promise<ClipboardPayload | null> | null>(null);const projectIdRef = useRef(projectId);projectIdRef.current = projectId;+ // After any save still in flight on the file, so a copy right after an edit takes the edit.+ const readSaved = useCallback(+ async (path: string): Promise<string> => {+ const pid = projectIdRef.current;+ if (!pid) throw new Error("No project is open.");+ // Only the order matters here; a failed save already shows its own banner.+ await waitForPendingDomEditSaves().catch(() => {});+ return serializeStudioFileMutations(writeProjectFile, [path], () =>+ readFileContent(pid, path),+ );+ },+ [waitForPendingDomEditSaves, writeProjectFile],+ );+// Resolved through findTimelineElementInIframe, the same composition-aware// lookup every other timeline editor uses — unlike findElementForSelection,// it can address a composition-instance clip's root.- const collectSelectedClips = useCallback((): {+ const findSelectedClips = useCallback((): {elements: TimelineElement[];- clips: TimelineClipboardClip[];+ lives: Element[];} | null => {const selected = getSelectedElements();if (selected.length === 0) return null;-- const clips: TimelineClipboardClip[] = [];+ const lives: Element[] = [];for (const element of selected) {- const html =- findTimelineElementInIframe(previewIframeRef.current, element, activeCompPath)?.outerHTML ??- null;- if (!html) {+ const live = findTimelineElementInIframe(previewIframeRef.current, element, activeCompPath);+ if (!live) {showToast(`Unable to copy "${element.label ?? element.id}".`, "info");return null;}- clips.push({- html,+ lives.push(live);+ }+ return { elements: selected, lives };+ }, [activeCompPath, previewIframeRef, showToast]);++ const readClips = useCallback(+ async (targets: {+ elements: TimelineElement[];+ lives: Element[];+ }): Promise<TimelineClipboardClip[]> => {+ const paths = targets.elements.map((el) => el.sourceFile || activeCompPath || "index.html");+ const markup = await readSavedMarkup(readSaved, paths, targets.lives);+ return targets.elements.map((element, index) => ({+ html: markup[index] as string,start: element.start,duration: element.duration,// authoredTrack, not track: `track` can be a display-lane number// remapped by normalizeToZones, and writing THAT into data-track-index// re-targets the wrong track in the sparse authored file.track: element.authoredTrack ?? element.track,- });- }- return { elements: selected, clips };- }, [activeCompPath, previewIframeRef, showToast]);-- // Two independent copy modes (timeline clip vs DOM element) in one handler.- // fallow-ignore-next-line complexity- const handleCopy = useCallback((): boolean => {- if (usePlayerStore.getState().selectedElementId) {- const result = collectSelectedClips();- if (!result) return false;- const targetPath = result.elements[0]?.sourceFile || activeCompPath || "index.html";- clipboardRef.current = { kind: "timeline-clip", clips: result.clips, sourceFile: targetPath };- showToast(- result.clips.length > 1 ? `Copied ${result.clips.length} clips` : "Copied clip",- "info",- );- return true;- }+ }));+ },+ [activeCompPath, readSaved],+ );- // DOM element copy- const domSelection = domEditSelectionRef.current;- if (domSelection) {- const html = getElementOuterHtml(previewIframeRef, domSelection, activeCompPath);- if (!html) {+ const copyTimelineSelection = useCallback((): Promise<ClipboardPayload> | null => {+ const targets = findSelectedClips();+ if (!targets) return null;+ const sourceFile = targets.elements[0]?.sourceFile || activeCompPath || "index.html";+ return readClips(targets).then((clips) => {+ showToast(clips.length > 1 ? `Copied ${clips.length} clips` : "Copied clip", "info");+ return { kind: "timeline-clip", clips, sourceFile };+ });+ }, [activeCompPath, findSelectedClips, readClips, showToast]);++ const copyDomSelection = useCallback(+ (domSelection: DomEditSelection): Promise<ClipboardPayload> | null => {+ const live = getSelectedDomElement(previewIframeRef, domSelection, activeCompPath);+ if (!live) {showToast("Unable to copy this element.", "info");- return false;+ return null;}- const targetPath = domSelection.sourceFile || activeCompPath || "index.html";- clipboardRef.current = {- kind: "dom-element",- html,- sourceFile: targetPath,- originSelector: domSelection.selector,- originSelectorIndex: domSelection.selectorIndex,- };- showToast("Copied element", "info");- return true;- }+ const sourceFile = domSelection.sourceFile || activeCompPath || "index.html";+ return readSaved(sourceFile).then((content) => {+ showToast("Copied element", "info");+ return {+ kind: "dom-element",+ html: savedMarkupElseLive(parseSavedSource(content), live, sourceFile),+ sourceFile,+ originSelector: domSelection.selector,+ originSelectorIndex: domSelection.selectorIndex,+ };+ });+ },+ [activeCompPath, previewIframeRef, readSaved, showToast],+ );- showToast("Nothing selected to copy.", "info");- return false;- }, [activeCompPath, collectSelectedClips, domEditSelectionRef, previewIframeRef, showToast]);+ // The key handler needs its answer now, so the targets are found here and only the file read+ // is pending. Returns this copy's own result; a failed copy leaves the clipboard as it was.+ const copyToClipboard = useCallback((): Promise<ClipboardPayload | null> | null => {+ const domSelection = domEditSelectionRef.current;+ let pending: Promise<ClipboardPayload> | null;+ if (usePlayerStore.getState().selectedElementId) pending = copyTimelineSelection();+ else if (domSelection) pending = copyDomSelection(domSelection);+ else {+ showToast("Nothing selected to copy.", "info");+ return null;+ }+ if (!pending) return null;+ const own = pending.catch((error: unknown) => {+ showToast(error instanceof Error ? error.message : "Failed to copy", "error");+ return null;+ });+ const previous = clipboardRef.current;+ const settled = own.then((payload) => payload ?? previous);+ clipboardRef.current = settled;+ void settled.then((payload) => {+ if (!payload && clipboardRef.current === settled) clipboardRef.current = null;+ });+ return own;+ }, [copyDomSelection, copyTimelineSelection, domEditSelectionRef, showToast]);++ const handleCopy = useCallback((): boolean => copyToClipboard() !== null, [copyToClipboard]);// Two independent paste modes (timeline clip vs DOM element) behind one guarded save.// fallow-ignore-next-line complexityconst handlePaste = useCallback(async () => {- const payload = clipboardRef.current;+ const payload = await clipboardRef.current;if (!payload) {showToast("Nothing to paste.", "info");return;@@ -339,16 +411,17 @@ export function useClipboard({// pasteTimelineClips with handlePaste; only the anchor and clip source// differ (the selection's own end here, the playhead there).const handleDuplicate = useCallback(async (): Promise<boolean> => {- const result = collectSelectedClips();- if (!result) return false;+ const targets = findSelectedClips();+ if (!targets) return false;const pid = projectIdRef.current;if (!pid) return false;- const { elements, clips } = result;+ const { elements } = targets;const targetPath = elements[0]?.sourceFile || activeCompPath || "index.html";const anchorTime = Math.max(...elements.map((el) => el.start + el.duration));try {+ const clips = await readClips(targets);const originalContent = await readFileContent(pid, targetPath);const liveElements = usePlayerStore.getState().elements;const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements);@@ -381,7 +454,8 @@ export function useClipboard({}}, [activeCompPath,- collectSelectedClips,+ findSelectedClips,+ readClips,recordEdit,reloadPreview,showToast,@@ -390,8 +464,9 @@ export function useClipboard({const handleCut = useCallback(async (): Promise<boolean> => {const selected = getSelectedElements();- const copied = handleCopy();- if (!copied) return false;+ const domSelection = domEditSelectionRef.current;+ const copied = copyToClipboard();+ if (!copied || !(await copied)) return false;if (selected.length > 0) {// One call for the whole selection, not one per element: the batched@@ -401,13 +476,17 @@ export function useClipboard({return true;}- const domSelection = domEditSelectionRef.current;if (domSelection) {await handleDomEditElementDelete(domSelection);return true;}return true;- }, [handleCopy, domEditSelectionRef, handleTimelineElementsDelete, handleDomEditElementDelete]);+ }, [+ copyToClipboard,+ domEditSelectionRef,+ handleTimelineElementsDelete,+ handleDomEditElementDelete,+ ]);const canPaste = useCallback(() => clipboardRef.current !== null, []);diff --git a/packages/studio/src/utils/authoredSource.ts b/packages/studio/src/utils/authoredSource.tsnew file mode 100644index 0000000000..19b69defa0--- /dev/null+++ b/packages/studio/src/utils/authoredSource.ts@@ -0,0 +1,92 @@+import { ensureHfIds, isCompositionTemplate } from "@hyperframes/parsers/hf-ids";++// Stamped as the preview stamps the files it serves, so a live element's hf-id finds its source.+export function parseSavedSource(html: string): Document {+ return new DOMParser().parseFromString(ensureHfIds(html), "text/html");+}++const rootsByDoc = new WeakMap<Document, ParentNode[]>();++// A plain template is a runtime clone source, so ids inside it repeat across clones.+function searchRoots(root: ParentNode): ParentNode[] {+ const templates = Array.from(root.querySelectorAll("template")).filter(isCompositionTemplate);+ return [root, ...templates.flatMap((template) => searchRoots(template.content))];+}++function findByAttribute(doc: Document, name: string, value: string): Element | null {+ let roots = rootsByDoc.get(doc);+ if (!roots) rootsByDoc.set(doc, (roots = searchRoots(doc)));+ const selector = `[${name}="${value.replace(/["\\]/g, "\\$&")}"]`;+ for (const root of roots) {+ const match = root.querySelector(selector);+ if (match) return match;+ }+ return null;+}++export function findAuthoredElement(doc: Document, live: Element): Element | null {+ const hfId = live.getAttribute("data-hf-id");+ if (hfId) return findByAttribute(doc, "data-hf-id", hfId);+ return live.id ? findByAttribute(doc, "id", live.id) : null;+}++export function findAuthoredElementById(doc: Document, live: Element): Element | null {+ return live.id ? findByAttribute(doc, "id", live.id) : null;+}++const PATH_ATTRS = ["src", "href"];+const CSS_URL = /\burl\(\s*(["']?)([^)"'\s](?:[^)"']*[^)"'\s])?)\1\s*\)/g;++function isRelative(path: string): boolean {+ return !!path && !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(path);+}++function toProjectPath(sourceFile: string, path: string): string {+ const parts = sourceFile.split("/").slice(0, -1);+ for (const part of path.split("/")) {+ if (part === "..") parts.pop();+ else if (part !== "." && part !== "") parts.push(part);+ }+ return parts.join("/");+}++function livePathsOf(live: Element): Set<string> {+ const paths = new Set<string>();+ for (const el of [live, ...Array.from(live.querySelectorAll("*"))]) {+ for (const attr of PATH_ATTRS) paths.add(el.getAttribute(attr) ?? "");+ for (const match of (el.getAttribute("style") ?? "").matchAll(CSS_URL)) paths.add(match[2]);+ }+ return paths;+}++// The preview inlines a sub-composition with its relative asset paths rebased to the project+// root (rewriteAssetPath in @hyperframes/parsers, which is not browser-safe); copy does the same.+export function authoredMarkup(authored: Element, live: Element, sourceFile: string): string {+ if (!sourceFile.includes("/")) return authored.outerHTML;+ const livePaths = livePathsOf(live);+ const rebase = (path: string): string => {+ if (!isRelative(path)) return path;+ const cut = path.search(/[?#]/);+ const suffix = cut < 0 ? "" : path.slice(cut);+ const rebased = toProjectPath(sourceFile, cut < 0 ? path : path.slice(0, cut)) + suffix;+ return path.startsWith("../") || livePaths.has(rebased) ? rebased : path;+ };+ const copy = authored.cloneNode(true) as Element;+ for (const el of [copy, ...Array.from(copy.querySelectorAll("*"))]) {+ for (const attr of PATH_ATTRS) {+ const value = el.getAttribute(attr);+ if (value) el.setAttribute(attr, rebase(value.trim()));+ }+ const style = el.getAttribute("style");+ if (style) {+ el.setAttribute(+ "style",+ style.replace(+ CSS_URL,+ (_, quote: string, url: string) => `url(${quote}${rebase(url)}${quote})`,+ ),+ );+ }+ }+ return copy.outerHTML;+}diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.tsindex c2178e5f85..c4e24a9110 100644--- a/packages/studio/src/utils/gsapSoftReload.test.ts+++ b/packages/studio/src/utils/gsapSoftReload.test.ts@@ -488,6 +488,35 @@ describe("applySoftReload authored-opacity restore", () => {expect(el.style.getPropertyPriority("opacity")).toBe("");});+ it("keeps the stamp for an element whose hf-id the written file lacks, even if it shares an id", () => {+ const el = document.createElement("img");+ el.id = "title-card";+ el.setAttribute("data-hf-id", "hf-from-another-file");+ el.setAttribute("data-hf-authored-opacity", "0.5");+ el.style.opacity = "0";++ const opacity = restoreOpacity(+ el,+ '<html><body><img id="title-card" style="opacity: 0.9"></body></html>',+ );++ expect(opacity).toBe("0.5");+ });++ it("does not take a runtime clone's opacity from its plain template", () => {+ const el = document.createElement("li");+ el.id = "item";+ el.setAttribute("data-hf-authored-opacity", "0.5");+ el.style.opacity = "0";++ const opacity = restoreOpacity(+ el,+ '<html><body><template><li id="item" style="opacity: 0.3"></li></template></body></html>',+ );++ expect(opacity).toBe("0.5");+ });+it("falls back to the parse-time stamp when no after-write HTML is given", () => {const el = document.createElement("img");el.setAttribute("data-hf-authored-opacity", "0.75");diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.tsindex 71b624276d..bbcbaa4f3d 100644--- a/packages/studio/src/utils/gsapSoftReload.ts+++ b/packages/studio/src/utils/gsapSoftReload.ts@@ -1,4 +1,5 @@import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading";+import { findAuthoredElement, parseSavedSource } from "./authoredSource";import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "./authoredOpacity";type IframeWindow = Window & {@@ -301,17 +302,12 @@ export function applySoftReload(const findAuthoredSource = (el: HTMLElement): Element | null => {if (authoredDoc === undefined) {try {- authoredDoc = authoredHtml- ? new DOMParser().parseFromString(authoredHtml, "text/html")- : null;+ authoredDoc = authoredHtml ? parseSavedSource(authoredHtml) : null;} catch {authoredDoc = null;}}- if (!authoredDoc) return null;- const hfId = el.getAttribute("data-hf-id");- if (hfId) return authoredDoc.querySelector(`[data-hf-id="${hfId}"]`);- return el.id ? authoredDoc.getElementById(el.id) : null;+ return authoredDoc ? findAuthoredElement(authoredDoc, el) : null;};const readAuthoredOpacity = (el: HTMLElement): string | null => {const source = findAuthoredSource(el);