Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): a picked element's edit writes only that element to source (#4508)
Miguel Ángelb66739820762
diff --git a/packages/studio/src/hooks/useElementPicker.test.ts b/packages/studio/src/hooks/useElementPicker.test.tsnew file mode 100644index 0000000000..1823215922--- /dev/null+++ b/packages/studio/src/hooks/useElementPicker.test.ts@@ -0,0 +1,172 @@+// @vitest-environment jsdom+import React, { act, useState } from "react";+import { createRoot, type Root } from "react-dom/client";+import { ensureHfIds } from "@hyperframes/parsers/hf-ids";+import { runtimeProtocolMetadata } from "@hyperframes/core/runtime/protocol";+import { afterEach, describe, expect, it } from "vitest";+import { useElementPicker } from "./useElementPicker";++// As the host leaves it on disk: hf-ids pinned, no element ids.+const SAVED = ensureHfIds(`<!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>`);++let root: Root | null = null;+afterEach(() => {+ act(() => root?.unmount());+ root = null;+ document.body.innerHTML = "";+});++// The preview page: the saved markup plus what the runtime adds to it.+function mountPreview(mounted = ""): HTMLIFrameElement {+ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ const doc = iframe.contentDocument as Document;+ doc.open();+ doc.write(SAVED);+ doc.close();+ (doc.querySelector("h1") as HTMLElement).style.cssText = "visibility: hidden; display: none";+ doc.body.append(Object.assign(doc.createElement("script"), { textContent: "/* runtime */" }));+ doc.body.insertAdjacentHTML("beforeend", mounted);+ return iframe;+}++function mountPicker(+ files: Record<string, string>,+ selector = "h1",+ mounted = "",+ hostAppliesWrites = true,+) {+ const iframe = mountPreview(mounted);+ const synced: Record<string, string>[] = [];+ let api: ReturnType<typeof useElementPicker> | null = null;+ let setHostFiles: (next: Record<string, string>) => void = () => {};+ // Like a Studio host: it holds the files in state and rerenders after each write.+ function Harness() {+ const [workspaceFiles, setFiles] = useState(files);+ setHostFiles = setFiles;+ api = useElementPicker(+ { current: iframe },+ {+ workspaceFiles,+ onSyncFiles: (changed) => {+ synced.push(changed);+ if (hostAppliesWrites) setFiles((prev) => ({ ...prev, ...changed }));+ },+ },+ );+ return null;+ }+ root = createRoot(document.createElement("div"));+ act(() => root?.render(React.createElement(Harness)));+ act(() => {+ window.dispatchEvent(+ new MessageEvent("message", {+ source: iframe.contentWindow,+ data: {+ source: "hf-preview",+ type: "element-picked",+ elementInfo: { selector, tagName: "h1" },+ ...runtimeProtocolMetadata(30),+ },+ }),+ );+ });+ const picker = () => api as ReturnType<typeof useElementPicker>;+ return {+ picker,+ synced,+ setHostFiles: (next: Record<string, string>) => act(() => setHostFiles(next)),+ };+}++describe("an edit to a picked element without an id", () => {+ it("writes only that edit into the saved file", () => {+ const { picker, synced } = mountPicker({ "index.html": SAVED });+ expect(picker().pickedElement?.selector).toBe("h1");+ act(() => picker().setStyle("color", "red"));+ expect(synced).toHaveLength(1);+ const written = synced[0]?.["index.html"] ?? "";+ expect(written).toMatch(/<h1 [^>]*style="color: red"[^>]*>Title<\/h1>/);+ expect(written).not.toContain("display: none");+ expect(written).not.toContain("/* runtime */");+ });++ it("persists a text edit", () => {+ const { picker, synced } = mountPicker({ "index.html": SAVED });+ act(() => picker().setTextContent("Hello"));+ expect(synced[0]?.["index.html"]).toMatch(/>Hello<\/h1>/);+ });++ // The same h1 in index.html and compositions/b.html, so both carry one hf-id.+ const SUB = ensureHfIds(`<template><div data-composition-id="b">+<h1 class="clip" data-start="2" data-duration="3" data-track-index="0">Title</h1>+</div></template>`);+ const subH1 = new DOMParser()+ .parseFromString(SUB, "text/html")+ .querySelector("template")+ ?.content.querySelector("h1");+ const host = `<div data-composition-file="compositions/b.html">${subH1?.outerHTML}</div>`;++ it.each([+ ["index.html first", { "index.html": SAVED, "compositions/b.html": SUB }],+ ["the sub-composition first", { "compositions/b.html": SUB, "index.html": SAVED }],+ ])("writes a twin element into its own file (%s)", (_order, files) => {+ expect(SAVED).toContain(`data-hf-id="${subH1?.getAttribute("data-hf-id")}"`);+ const inSub = mountPicker(files, "[data-composition-file] h1", host);+ act(() => inSub.picker().setStyle("color", "red"));+ expect(inSub.synced.map((changed) => Object.keys(changed))).toEqual([["compositions/b.html"]]);+ act(() => root?.unmount());+ const inRoot = mountPicker(files, "h1", host);+ act(() => inRoot.picker().setStyle("color", "red"));+ expect(inRoot.synced.map((changed) => Object.keys(changed))).toEqual([["index.html"]]);+ });++ it("keeps both of two edits made before the host rerenders", () => {+ const { picker, synced } = mountPicker({ "index.html": SAVED });+ act(() => {+ picker().setStyle("color", "red");+ picker().setStyle("background", "blue");+ });+ expect(synced.at(-1)?.["index.html"]).toMatch(/<h1 [^>]*style="color: red; background: blue"/);+ });++ it("builds the next edit on a file the host changed meanwhile", () => {+ const { picker, synced, setHostFiles } = mountPicker({ "index.html": SAVED });+ act(() => picker().setStyle("color", "red"));+ setHostFiles({ "index.html": SAVED.replace(">Title<", ">Renamed<") });+ act(() => picker().setStyle("background", "blue"));+ const written = synced.at(-1)?.["index.html"] ?? "";+ expect(written).toContain(">Renamed</h1>");+ expect(written).not.toContain("color: red");+ });++ it("builds the next edit on the host's undo", () => {+ const { picker, synced, setHostFiles } = mountPicker({ "index.html": SAVED });+ act(() => picker().setStyle("color", "red"));+ setHostFiles({ "index.html": SAVED });+ act(() => picker().setStyle("background", "blue"));+ expect(synced.at(-1)?.["index.html"]).not.toContain("color: red");+ });++ it("keeps later edits while the host has applied only the first", () => {+ const { picker, synced, setHostFiles } = mountPicker({ "index.html": SAVED }, "h1", "", false);+ act(() => {+ picker().setStyle("color", "red");+ picker().setStyle("background", "blue");+ });+ setHostFiles(synced[0] as Record<string, string>);+ act(() => picker().setStyle("border", "0"));+ expect(synced.at(-1)?.["index.html"]).toMatch(+ /style="color: red; background: blue; border: 0"/,+ );+ });++ it("writes nothing when no saved file holds the element", () => {+ const { picker, synced } = mountPicker({ "index.html": "<div>other</div>" });+ act(() => picker().setStyle("color", "red"));+ expect(synced).toEqual([]);+ });+});diff --git a/packages/studio/src/hooks/useElementPicker.ts b/packages/studio/src/hooks/useElementPicker.tsindex b04848377d..bfc33d4726 100644--- a/packages/studio/src/hooks/useElementPicker.ts+++ b/packages/studio/src/hooks/useElementPicker.ts@@ -1,10 +1,18 @@import { useState, useCallback, useRef } from "react";import { useMountEffect } from "./useMountEffect";-import { resolveSourceFile, applyPatch } from "../utils/sourcePatcher";+import {+ resolveSourceFile,+ applyPatch,+ applyPatchByTarget,+ findTagByTarget,+ type PatchOperation,+} from "../utils/sourcePatcher";import {acceptStudioRuntimeMessage,postRuntimeControlMessage,} from "../player/lib/runtimeProtocol";+import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail";+import { getSourceFileForElement } from "../components/editor/domEditingDom";export interface PickedElement {id: string | null;@@ -91,6 +99,8 @@ export function useElementPicker(// Listen for picker messages from the iframeuseMountEffect(() => {+ // One guard per message field, then one branch per message type.+ // fallow-ignore-next-line complexityconst handleMessage = (e: MessageEvent) => {const data = e.data;if (data?.source !== "hf-preview") return;@@ -101,40 +111,13 @@ export function useElementPicker(if (e.source !== activeIframe.contentWindow && e.source !== iframeRef.current?.contentWindow)return;- if (data.type === "element-picked") {- const el = data.elementInfo;- if (el) {- const styles = readComputedStyles(activeIframe, el.selector);- setPickedElement({- id: el.id ?? null,- tagName: el.tagName ?? "div",- selector: el.selector ?? "",- label: el.label ?? el.tagName ?? "Element",- boundingBox: el.boundingBox ?? { x: 0, y: 0, width: 0, height: 0 },- textContent: el.textContent ?? null,- src: el.src ?? null,- dataAttributes: el.dataAttributes ?? {},- computedStyles: styles,- });- setIsPickMode(false);- }+ if (data.type === "element-picked" && data.elementInfo) {+ setPickedElement(toPickedElement(data.elementInfo, activeIframe));+ setIsPickMode(false);} else if (data.type === "element-pick-candidates") {// Multiple candidates at click point — pick the first oneconst el = data.candidates?.[data.selectedIndex ?? 0];- if (el) {- const styles = readComputedStyles(activeIframe, el.selector);- setPickedElement({- id: el.id ?? null,- tagName: el.tagName ?? "div",- selector: el.selector ?? "",- label: el.label ?? el.tagName ?? "Element",- boundingBox: el.boundingBox ?? { x: 0, y: 0, width: 0, height: 0 },- textContent: el.textContent ?? null,- src: el.src ?? null,- dataAttributes: el.dataAttributes ?? {},- computedStyles: styles,- });- }+ if (el) setPickedElement(toPickedElement(el, activeIframe));}if (data.type === "pick-mode-cancelled") {@@ -149,29 +132,26 @@ export function useElementPicker(// Ref for options to avoid stale closures in debounced callbackconst optionsRef = useRef(options);optionsRef.current = options;+ const pendingWritesRef = useRef(new Map<string, PendingWrite>());+ settlePendingWrites(pendingWritesRef.current, options?.workspaceFiles);// Sync immediately (not debounced) — save on every change for reliabilityconst syncToSource = useCallback(- (- elementId: string,- selector: string,- op: {- type: "inline-style" | "attribute" | "text-content";- property: string;- value: string;- },- ) => {+ (picked: PickedElement, live: HTMLElement, iframe: HTMLIFrameElement, op: PatchOperation) => {const opts = optionsRef.current;- if (!opts?.workspaceFiles || !opts.onSyncFiles || !elementId) return;- const files = opts.workspaceFiles;- const sourceFile = resolveSourceFile(elementId, selector, files);- if (!sourceFile || !files[sourceFile]) {- return;- }- const patched = applyPatch(files[sourceFile], elementId, op);- if (patched !== files[sourceFile]) {- opts.onSyncFiles({ [sourceFile]: patched });- }+ if (!opts?.workspaceFiles || !opts.onSyncFiles) return;+ // No id: the preview's hf-id names the element, in the file it was served from.+ const hfId = live.getAttribute("data-hf-id");+ const pending = pendingWritesRef.current;+ const files = withPendingWrites(opts.workspaceFiles, pending);+ const patch = picked.id+ ? patchById(files, picked.id, picked.selector, op)+ : hfId+ ? patchByHfId(files, hfId, ownSourceFile(live, iframe), op)+ : null;+ if (!patch || patch.after === patch.before) return;+ recordPendingWrite(pending, patch.path, opts.workspaceFiles[patch.path], patch.after);+ opts.onSyncFiles({ [patch.path]: patch.after });},[],);@@ -193,32 +173,11 @@ export function useElementPicker(}: null,);- // Persist to source file- if (pickedElement.id) {- // ID-based patching — surgical edit of just the element's style- syncToSource(pickedElement.id, pickedElement.selector, {- type: "inline-style",- property: prop,- value,- });- } else {- // No ID — save the full composition HTML from the iframe- // This captures ALL inline style changes, not just the targeted one- try {- const fullHtml = activeIframe.contentDocument?.documentElement.outerHTML;- if (fullHtml && optionsRef.current?.onSyncFiles) {- // Determine which file this iframe represents- const src = activeIframe.getAttribute("src") ?? "";- const compMatch = src.match(/\/comp\/(.+?)(?:\?|$)/);- const filePath = compMatch ? compMatch[1] : "index.html";- optionsRef.current.onSyncFiles({- [filePath]: `<!DOCTYPE html>\n<html>${fullHtml.replace(/<html[^>]*>/, "")}`,- });- }- } catch {- /* cross-origin */- }- }+ syncToSource(pickedElement, el, activeIframe, {+ type: "inline-style",+ property: prop,+ value,+ });}} catch {/* cross-origin */@@ -244,14 +203,11 @@ export function useElementPicker(}: null,);- // Persist to source file immediately- if (pickedElement.id) {- syncToSource(pickedElement.id, pickedElement.selector, {- type: "attribute",- property: attr,- value,- });- }+ syncToSource(pickedElement, el as HTMLElement, activeIframe, {+ type: "attribute",+ property: attr,+ value,+ });}} catch {/* cross-origin */@@ -270,14 +226,11 @@ export function useElementPicker(if (el) {el.textContent = text;setPickedElement((prev) => (prev ? { ...prev, textContent: text } : null));- // Persist to source file- if (pickedElement.id) {- syncToSource(pickedElement.id, pickedElement.selector, {- type: "text-content",- property: "textContent",- value: text,- });- }+ syncToSource(pickedElement, el as HTMLElement, activeIframe, {+ type: "text-content",+ property: "textContent",+ value: text,+ });}} catch {/* cross-origin */@@ -305,6 +258,101 @@ export function useElementPicker(};}+type PickedElementInfo = Partial<Omit<PickedElement, "computedStyles">>;++// workspaceFiles lags this hook's own writes until the host rerenders.+interface PendingWrite {+ hostSource: string | undefined;+ writes: string[];+}++function settlePendingWrites(+ pending: Map<string, PendingWrite>,+ files: Record<string, string> | undefined,+): void {+ for (const [path, write] of pending) {+ const hostSource = files?.[path];+ if (hostSource === write.hostSource) continue;+ const caughtUpTo = hostSource === undefined ? -1 : write.writes.indexOf(hostSource);+ if (caughtUpTo < 0 || caughtUpTo === write.writes.length - 1) {+ pending.delete(path);+ } else {+ write.hostSource = hostSource;+ write.writes = write.writes.slice(caughtUpTo + 1);+ }+ }+}++function withPendingWrites(+ files: Record<string, string>,+ pending: Map<string, PendingWrite>,+): Record<string, string> {+ const merged = { ...files };+ for (const [path, write] of pending) merged[path] = write.writes.at(-1) ?? merged[path];+ return merged;+}++function recordPendingWrite(+ pending: Map<string, PendingWrite>,+ path: string,+ hostSource: string | undefined,+ after: string,+): void {+ const write = pending.get(path) ?? { hostSource, writes: [] };+ write.writes.push(after);+ pending.set(path, write);+}++// A default per field of the runtime's element info.+// fallow-ignore-next-line complexity+function toPickedElement(el: PickedElementInfo, iframe: HTMLIFrameElement): PickedElement {+ return {+ id: el.id ?? null,+ tagName: el.tagName ?? "div",+ selector: el.selector ?? "",+ label: el.label ?? el.tagName ?? "Element",+ boundingBox: el.boundingBox ?? { x: 0, y: 0, width: 0, height: 0 },+ textContent: el.textContent ?? null,+ src: el.src ?? null,+ dataAttributes: el.dataAttributes ?? {},+ computedStyles: readComputedStyles(iframe, el.selector ?? ""),+ };+}++interface SourcePatch {+ path: string;+ before: string;+ after: string;+}++function patchById(+ files: Record<string, string>,+ id: string,+ selector: string,+ op: PatchOperation,+): SourcePatch | null {+ const path = resolveSourceFile(id, selector, files);+ const before = path ? files[path] : undefined;+ return path && before ? { path, before, after: applyPatch(before, id, op) } : null;+}++function ownSourceFile(live: HTMLElement, iframe: HTMLIFrameElement): string {+ const previewed = compositionPathOfPreviewUrl(iframe.getAttribute("src") ?? "");+ return getSourceFileForElement(live, previewed).sourceFile;+}++function patchByHfId(+ files: Record<string, string>,+ hfId: string,+ ownFile: string,+ op: PatchOperation,+): SourcePatch | null {+ const matches = Object.keys(files).filter((file) => findTagByTarget(files[file] ?? "", { hfId }));+ const path = matches.includes(ownFile) ? ownFile : matches.length === 1 ? matches[0] : undefined;+ const before = path ? files[path] : undefined;+ return path && before ? { path, before, after: applyPatchByTarget(before, { hfId }, op) } : null;+}+/** Read a subset of computed styles from an element in the iframe */function readComputedStyles(iframe: HTMLIFrameElement, selector: string): Record<string, string> {const styles: Record<string, string> = {};