Skip to content

Write HTML. Render video. Built for agents.

fix(studio): the server picks an added effect's element id; one client for patch and gsap writes (#4962)

Miguel Ángel48308e370826
diff --git a/packages/studio-server/src/helpers/duplicateElement.ts b/packages/studio-server/src/helpers/duplicateElement.ts
index e0734d943b..11bfeeb4e7 100644
--- a/packages/studio-server/src/helpers/duplicateElement.ts
+++ b/packages/studio-server/src/helpers/duplicateElement.ts
@@ -4,6 +4,7 @@ import {
findTargetElement,
dedupeClonedCompositionId,
isHTMLElement,
+ nextUniqueId,
parseSourceDocument,
type SourceMutationTarget,
} from "./sourceMutation.js";
@@ -41,13 +42,6 @@ export function duplicateElementInHtml(
return { html: ensureHfIds(html), matched: true, newId: uniqueId };
}
-function nextUniqueId(document: Document, newId: string): string {
- let uniqueId = newId;
- let suffix = 2;
- while (document.getElementById(uniqueId)) uniqueId = `${newId}-${suffix++}`;
- return uniqueId;
-}
-
function rippleElements(
document: Document,
element: Element,
diff --git a/packages/studio-server/src/helpers/freezeFrame.ts b/packages/studio-server/src/helpers/freezeFrame.ts
index 8a3983b26f..4bd8af25f2 100644
--- a/packages/studio-server/src/helpers/freezeFrame.ts
+++ b/packages/studio-server/src/helpers/freezeFrame.ts
@@ -6,6 +6,7 @@ import { MEDIA_LINK_ATTR as LINK_ATTR, relinkSplitHalves } from "@hyperframes/co
import {
findTargetElement,
isHTMLElement,
+ nextUniqueId,
parseSourceDocument,
splitElementInHtml,
type SourceMutationTarget,
@@ -115,12 +116,6 @@ function spans(el: Element, time: number): boolean {
return time > start + EPSILON && time < start + duration - EPSILON;
}
-function uniqueId(document: Document, base: string): string {
- let id = base;
- for (let n = 2; document.getElementById(id); n++) id = `${base}-${n}`;
- return id;
-}
-
function shiftTracks(document: Document, tracks: Set<number>, from: number, by: number): void {
for (const el of document.querySelectorAll("[data-start]")) {
if (el.hasAttribute("data-composition-id") || !tracks.has(trackOf(el))) continue;
@@ -241,7 +236,7 @@ export function applyFreezeFrameToHtml(
shiftTracks(document, tracks, input.playhead, hold);
const leftHalf = findTargetElement(document, input.target);
if (!leftHalf?.parentElement) return null;
- const freezeId = uniqueId(document, `${video.getAttribute("id") || "clip"}-freeze`);
+ const freezeId = nextUniqueId(document, `${video.getAttribute("id") || "clip"}-freeze`);
const still = buildStill(document, leftHalf, {
id: freezeId,
imageSrc: input.imageSrc,
diff --git a/packages/studio-server/src/helpers/sourceMutation.test.ts b/packages/studio-server/src/helpers/sourceMutation.test.ts
index d5bbecd55d..e1134f7224 100644
--- a/packages/studio-server/src/helpers/sourceMutation.test.ts
+++ b/packages/studio-server/src/helpers/sourceMutation.test.ts
@@ -686,3 +686,38 @@ describe("patchElementInHtml stamps the ids a rich-text patch introduces", () =>
expect(introducedId).not.toBe("hf-3x72");
});
});
+
+describe("patchElementInHtml ensure-id", () => {
+ const cards = (a = "", b = "") =>
+ `<div data-composition-id="main"><div data-hf-id="hf-a" class="card"${a}></div><div data-hf-id="hf-b" class="card"${b}></div></div>`;
+ const ensureId = (source: string, hfId: string, value = "div") =>
+ patchElementInHtml(source, { hfId }, [{ type: "ensure-id", property: "id", value }]);
+
+ it("writes the proposed id and reports it", () => {
+ const result = ensureId(cards(), "hf-a");
+
+ expect(result.elementId).toBe("div");
+ expect(parseHTML(result.html).document.getElementById("div")?.getAttribute("data-hf-id")).toBe(
+ "hf-a",
+ );
+ });
+
+ it("makes the proposed id unique against the file, not the caller's view", () => {
+ const result = ensureId(cards(' id="div"'), "hf-b");
+
+ expect(result.elementId).toBe("div-2");
+ expect(result.html).toContain('id="div"');
+ expect(result.html).toContain('id="div-2"');
+ });
+
+ it("keeps an id the element already holds and changes nothing", () => {
+ const source = cards(' id="div-7"');
+ const result = ensureId(source, "hf-a");
+
+ expect(result).toEqual({ html: source, matched: true, elementId: "div-7" });
+ });
+
+ it("reports no id when the target is not in the file", () => {
+ expect(ensureId(cards(), "hf-missing").elementId).toBeUndefined();
+ });
+});
diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts
index a5b90e1188..e6425233a3 100644
--- a/packages/studio-server/src/helpers/sourceMutation.ts
+++ b/packages/studio-server/src/helpers/sourceMutation.ts
@@ -182,7 +182,14 @@ export function dedupeClonedCompositionId(document: Document, clone: Element): v
}
export interface PatchOperation {
- type: "inline-style" | "attribute" | "html-attribute" | "text-content" | "rich-text";
+ /** `ensure-id` keeps the element's id, else writes `value` made unique in this file and `takenIds`. */
+ type:
+ | "inline-style"
+ | "attribute"
+ | "html-attribute"
+ | "text-content"
+ | "rich-text"
+ | "ensure-id";
property: string;
value: string | null;
childSelector?: string;
@@ -239,7 +246,8 @@ export function patchElementInHtml(
source: string,
target: SourceMutationTarget,
operations: PatchOperation[],
-): { html: string; matched: boolean } {
+ takenIds?: ReadonlySet<string>,
+): { html: string; matched: boolean; elementId?: string | null } {
const { document, wrappedFragment } = parseSourceDocument(source);
const el = findTargetElement(document, target);
if (!el || !isHTMLElement(el)) return { html: source, matched: false };
@@ -285,6 +293,10 @@ export function patchElementInHtml(
opTarget.removeAttribute(op.property);
}
break;
+ case "ensure-id":
+ if (opTarget.getAttribute("id") || !op.value) break;
+ opTarget.setAttribute("id", nextUniqueId(document, op.value, takenIds));
+ break;
case "text-content":
if (op.value != null) {
const inner = opTarget.children.length === 1 ? opTarget.firstElementChild : null;
@@ -307,8 +319,20 @@ export function patchElementInHtml(
}
const html = wrappedFragment ? document.body.innerHTML || "" : document.toString();
- if (html === originalHtml) return { html: source, matched: true };
- return { html: ensureHfIds(html), matched: true };
+ const elementId = htmlEl.getAttribute("id");
+ if (html === originalHtml) return { html: source, matched: true, elementId };
+ return { html: ensureHfIds(html), matched: true, elementId };
+}
+
+export function nextUniqueId(
+ document: Document,
+ base: string,
+ takenIds?: ReadonlySet<string>,
+): string {
+ let id = base;
+ let suffix = 2;
+ while (document.getElementById(id) || takenIds?.has(id)) id = `${base}-${suffix++}`;
+ return id;
}
/** Whether each target exists in `source`; the document is parsed once however many targets ask. */
@@ -392,13 +416,7 @@ export function splitElementInHtml(
return { html: source, matched: false, newId: null };
}
- if (document.getElementById(newId)) {
- let suffix = 2;
- const base = newId;
- while (document.getElementById(newId)) {
- newId = `${base}-${suffix++}`;
- }
- }
+ newId = nextUniqueId(document, newId);
const firstDuration = splitTime - start;
const secondDuration = duration - firstDuration;
@@ -535,13 +553,7 @@ function uniqueGroupDomId(document: Document, groupId: string): string {
.replace(/[^a-z0-9]+/g, "-")
// Normalization above leaves at most one hyphen at either edge.
.replace(/^-|-$/g, "") || "group";
- let id = base;
- let n = 2;
- while (document.getElementById(id)) {
- id = `${base}-${n}`;
- n += 1;
- }
- return id;
+ return nextUniqueId(document, base);
}
// fallow-ignore-next-line complexity
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index c8e02c8718..f6b33b1b11 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -643,6 +643,94 @@ describe("registerFileRoutes", () => {
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain("After");
});
+ it("reports the id ensure-id leaves on the element, saved or already there", async () => {
+ const projectDir = createProjectDir();
+ writeFileSync(
+ join(projectDir, "index.html"),
+ '<div data-hf-id="hf-a" id="div"></div><div data-hf-id="hf-b"></div>',
+ );
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const ensureId = async (hfId: string) => {
+ const response = await app.request(
+ "http://localhost/projects/demo/file-mutations/patch-element/index.html",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ target: { hfId },
+ operations: [{ type: "ensure-id", property: "id", value: "div" }],
+ }),
+ },
+ );
+ const { changed, elementId } = (await response.json()) as Record<string, unknown>;
+ return { changed, elementId };
+ };
+
+ expect(await ensureId("hf-b")).toEqual({ changed: true, elementId: "div-2" });
+ expect(await ensureId("hf-a")).toEqual({ changed: false, elementId: "div" });
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain('id="div-2"');
+ });
+
+ it("never lets ensure-id save an id another composition file in the preview holds", async () => {
+ const projectDir = createProjectDir();
+ writeFileSync(join(projectDir, "index.html"), '<div data-hf-id="hf-a"></div>');
+ mkdirSync(join(projectDir, "compositions"));
+ writeFileSync(join(projectDir, "compositions/b.html"), '<div data-hf-id="hf-b"></div>');
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ // Both adds proposed "div": neither preview knew of the other's write.
+ const ensureId = async (file: string, hfId: string) => {
+ const response = await app.request(
+ `http://localhost/projects/demo/file-mutations/patch-element/${file}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ target: { hfId },
+ operations: [{ type: "ensure-id", property: "id", value: "div" }],
+ }),
+ },
+ );
+ return ((await response.json()) as Record<string, unknown>).elementId;
+ };
+
+ expect(await ensureId("compositions/b.html", "hf-b")).toBe("div");
+ expect(await ensureId("index.html", "hf-a")).toBe("div-2");
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain('id="div-2"');
+ });
+
+ it("counts another file's ids after a quote-ended string and with no space before id", async () => {
+ const projectDir = createProjectDir();
+ writeFileSync(
+ join(projectDir, "index.html"),
+ '<div data-hf-id="hf-a"></div><p data-hf-id="hf-b"></p>',
+ );
+ writeFileSync(
+ join(projectDir, "b.html"),
+ '<script>var u = "/id=" + x;</script><div id="div"></div><p class="c"id="p"></p>',
+ );
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const ensureId = async (hfId: string, value: string) => {
+ const response = await app.request(
+ "http://localhost/projects/demo/file-mutations/patch-element/index.html",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ target: { hfId },
+ operations: [{ type: "ensure-id", property: "id", value }],
+ }),
+ },
+ );
+ return ((await response.json()) as Record<string, unknown>).elementId;
+ };
+
+ expect(await ensureId("hf-a", "div")).toBe("div-2");
+ expect(await ensureId("hf-b", "p")).toBe("p-2");
+ });
+
it("writes the font an edit uses in the same write as the edit", async () => {
const projectDir = createProjectDir();
const original = '<html><head></head><body><div id="title">Before</div></body></html>';
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 4f0321d70e..afc7f2e03a 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -28,10 +28,12 @@ import { generateWaveformCache } from "../helpers/waveform.js";
import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";
import {
folderGone,
+ isInHiddenOrVendorDir,
isSafePath,
mkdirWithinProject,
pinWithinProject,
resolveWithinProject,
+ walkDir,
} from "../helpers/safePath.js";
import { backupPathForResponse, snapshotBeforeWrite } from "../helpers/backupJournal.js";
import { projectDirMissing } from "../helpers/projectDirMissing.js";
@@ -374,6 +376,24 @@ function foldElementPatches(
const PATCH_CONFLICT_ATTEMPTS = 3;
+const ID_ATTRIBUTE = /[\s"'/]id\s*=\s*(?=(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))/gi;
+
+/** Every id in the project's HTML files: sub-compositions share one preview document. */
+function projectHtmlIds(projectDir: string): Set<string> {
+ const ids = new Set<string>();
+ for (const rel of walkDir(projectDir)) {
+ if (!rel.endsWith(".html") || isInHiddenOrVendorDir(rel)) continue;
+ let html: string;
+ try {
+ html = readFileSync(join(projectDir, rel), "utf-8");
+ } catch {
+ continue;
+ }
+ for (const m of html.matchAll(ID_ATTRIBUTE)) ids.add(m[1] ?? m[2] ?? m[3] ?? "");
+ }
+ return ids;
+}
+
type ElementPatchCommitResult =
| { error: "duplicate" | "forbidden" | "not-found" | "conflict"; sourceFile: string }
| { durable: boolean; files: ElementPatchBatchFileResult[] };
@@ -3062,7 +3082,15 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
} catch {
return c.json({ error: "not found" }, 404);
}
- const element = patchElementInHtml(originalContent, parsed.target, parsed.body.operations);
+ const takenIds = parsed.body.operations.some((op) => op.type === "ensure-id")
+ ? projectHtmlIds(ctx.project.dir)
+ : undefined;
+ const element = patchElementInHtml(
+ originalContent,
+ parsed.target,
+ parsed.body.operations,
+ takenIds,
+ );
const { matched } = element;
const patched =
matched && isStudioFontFaceCss(fontFaceCss)
@@ -3075,6 +3103,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
ok: true,
changed: false,
matched,
+ elementId: element.elementId,
content: originalContent,
path: ctx.filePath,
version,
@@ -3098,6 +3127,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
ok: true,
changed: true,
matched,
+ elementId: element.elementId,
content: patched,
path: ctx.filePath,
version,
diff --git a/packages/studio/src/hooks/fetchStubTestUtils.ts b/packages/studio/src/hooks/fetchStubTestUtils.ts
index 1cd61d13e3..f2385d46a3 100644
--- a/packages/studio/src/hooks/fetchStubTestUtils.ts
+++ b/packages/studio/src/hooks/fetchStubTestUtils.ts
@@ -1,10 +1,8 @@
-// Shared helpers for test-side `fetch` stubs (timelineTimingSync.test.ts,
-// useTimelineEditing.test.tsx): a JSON Response factory and a Request → URL
-// normalizer. Test-only module — imported exclusively from *.test.* files.
+// Test-only helpers for `fetch` stubs: a JSON Response factory and a Request → URL normalizer.
-export function jsonResponse(body: unknown): Response {
+export function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
- status: 200,
+ status,
headers: { "content-type": "application/json" },
});
}
diff --git a/packages/studio/src/hooks/gsapMutationClient.ts b/packages/studio/src/hooks/gsapMutationClient.ts
index 6ea38ad026..393c9aa995 100644
--- a/packages/studio/src/hooks/gsapMutationClient.ts
+++ b/packages/studio/src/hooks/gsapMutationClient.ts
@@ -88,6 +88,22 @@ function readMutationError(value: unknown, fallback: string): string {
return fallback;
}
+export function requestGsapMutation(
+ projectId: string,
+ route: "gsap-mutations" | "gsap-mutations-batch",
+ filePath: string,
+ body: unknown,
+): Promise<Response> {
+ return studioApiFetch(
+ `/api/projects/${encodeURIComponent(projectId)}/${route}/${encodeURIComponent(filePath)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
+ body: JSON.stringify(body),
+ },
+ );
+}
+
export async function postGsapMutation(
projectId: string,
filePath: string,
@@ -96,14 +112,7 @@ export async function postGsapMutation(
): Promise<GsapMutationStatus> {
let response: Response;
try {
- response = await studioApiFetch(
- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
- body: JSON.stringify(mutation),
- },
- );
+ response = await requestGsapMutation(projectId, "gsap-mutations", filePath, mutation);
} catch (error) {
throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, {
cause: error,
diff --git a/packages/studio/src/hooks/gsapScriptCommitHelpers.ts b/packages/studio/src/hooks/gsapScriptCommitHelpers.ts
index 8986de034e..5c9caa2b4c 100644
--- a/packages/studio/src/hooks/gsapScriptCommitHelpers.ts
+++ b/packages/studio/src/hooks/gsapScriptCommitHelpers.ts
@@ -1,22 +1,11 @@
-import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
export { PROPERTY_DEFAULTS } from "./gsapShared";
import { idSelector, matchesExactlyOne } from "./gsapShared";
-import { studioWriteHeaders } from "../utils/studioFileVersion";
-import { studioApiFetch } from "../utils/studioApiFetch";
/**
- * The selector to author a NEW tween against, minting an id on the element when
- * it has no address of its own.
- *
- * `selection.selector` is only usable when it addresses ONE element:
- * `buildStableSelector` hands back a bare class for an id-less element, so
- * returning it unconditionally aimed "add animation" at every sibling sharing
- * the class (the attribution blow-up that collapsed the timeline to one row,
- * see writeTargetSelector). A non-unique selector falls through to the id mint
- * below, which is the stronger fix here than a structural path: the id it writes
- * back to the source also makes every later lookup for this element exact.
+ * The selector for a NEW tween; a shared-class selector would hit every sibling, so an
+ * element without a unique one gets an `autoId` proposal the server makes unique (`ensure-id`).
*/
export function ensureElementAddressable(selection: DomEditSelection): {
selector: string;
@@ -37,7 +26,6 @@ export function ensureElementAddressable(selection: DomEditSelection): {
n += 1;
id = `${tag}-${n}`;
}
- el.setAttribute("id", id);
return { selector: idSelector(id), autoId: id };
}
@@ -87,53 +75,3 @@ export function formatGsapMutationRejectionToast(error: GsapMutationHttpError):
}
return `Couldn't save animation: ${error.message}`;
}
-
-interface AssignAutoIdParams {
- projectId: string;
- targetPath: string;
- selection: DomEditSelection;
- autoId: string;
- showToast?: (message: string, tone?: "error" | "info") => void;
-}
-
-export async function assignGsapTargetAutoIdIfNeeded({
- projectId,
- targetPath,
- selection,
- autoId,
- showToast,
-}: AssignAutoIdParams): Promise<boolean> {
- const patchBody = {
- target: {
- id: selection.id,
- hfId: selection.hfId,
- selector: selection.selector,
- selectorIndex: selection.selectorIndex,
- },
- operations: [{ type: "html-attribute", property: "id", value: autoId }],
- };
- const unsafePatchFields = findUnsafeDomPatchValues(patchBody);
- if (unsafePatchFields.length > 0) {
- showToast?.("Couldn't assign element id because the patch contains invalid values", "error");
- return false;
- }
- const res = await studioApiFetch(
- `/api/projects/${encodeURIComponent(projectId)}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
- body: JSON.stringify(patchBody),
- },
- );
- if (!res.ok) {
- showToast?.(
- formatGsapMutationRejectionToast(
- new GsapMutationHttpError(res.status, await readJsonResponseBody(res)),
- ),
- "error",
- );
- return false;
- }
- const data = (await res.json()) as { changed?: boolean };
- return data.changed === true;
-}
diff --git a/packages/studio/src/hooks/newTweenTarget.test.ts b/packages/studio/src/hooks/newTweenTarget.test.ts
index 50f54d6ed9..b097937f3c 100644
--- a/packages/studio/src/hooks/newTweenTarget.test.ts
+++ b/packages/studio/src/hooks/newTweenTarget.test.ts
@@ -73,6 +73,9 @@ describe("ensureElementAddressable — add-animation button", () => {
const { selector, autoId } = ensureElementAddressable(selection);
expect(autoId).toBeTruthy();
+ expect(el.hasAttribute("id")).toBe(false);
+ // addGsapAnimation sets the id the server confirms; the proposal is free in the preview.
+ el.setAttribute("id", autoId!);
expect(document.querySelectorAll(selector)).toHaveLength(1);
expect(document.querySelector(selector)).toBe(el);
expect(attributedTo(selector)).toEqual([autoId]);
diff --git a/packages/studio/src/hooks/useDomEditCommitsHelpers.test.ts b/packages/studio/src/hooks/useDomEditCommitsHelpers.test.ts
new file mode 100644
index 0000000000..f0242c2d6f
--- /dev/null
+++ b/packages/studio/src/hooks/useDomEditCommitsHelpers.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import { jsonResponse, requestUrl } from "./fetchStubTestUtils";
+import { assignGsapTargetAutoIdIfNeeded } from "./useDomEditCommitsHelpers";
+
+const selection = {
+ hfId: "hf-card",
+ selector: '[data-hf-id="hf-card"]',
+ selectorIndex: 0,
+} as DomEditSelection;
+
+function stubPatch(response: Response) {
+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0], _init?: RequestInit) => {
+ const url = requestUrl(input);
+ if (url.includes("/api/projects/p1/file-mutations/patch-element/index.html")) return response;
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function assign(over: Partial<Parameters<typeof assignGsapTargetAutoIdIfNeeded>[0]> = {}) {
+ const showToast = vi.fn();
+ const result = assignGsapTargetAutoIdIfNeeded({
+ projectId: "p1",
+ targetPath: "index.html",
+ selection,
+ autoId: "hf-auto-1",
+ showToast,
+ ...over,
+ });
+ return { result, showToast };
+}
+
+describe("assignGsapTargetAutoIdIfNeeded", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("asks the patch-element client to ensure the id and returns the one the file holds", async () => {
+ const fetchMock = stubPatch(jsonResponse({ changed: true, elementId: "hf-auto-1-2" }));
+ const { result } = assign();
+
+ await expect(result).resolves.toBe("hf-auto-1-2");
+ const [, init] = fetchMock.mock.calls[0]!;
+ expect(init?.method).toBe("POST");
+ expect(new Headers(init?.headers).get("X-Hyperframes-Write-Token")).toBeTruthy();
+ expect(JSON.parse(String(init?.body))).toEqual({
+ target: { hfId: "hf-card", selector: '[data-hf-id="hf-card"]', selectorIndex: 0 },
+ operations: [{ type: "ensure-id", property: "id", value: "hf-auto-1" }],
+ });
+ });
+
+ it("returns the id the element already holds in the file", async () => {
+ stubPatch(jsonResponse({ changed: false, matched: true, elementId: "div" }));
+ await expect(assign().result).resolves.toBe("div");
+ });
+
+ it.each([
+ ["the target is not in the file", { changed: false, matched: false }],
+ ["the reply names no id", {}],
+ ])("is null with a toast when %s", async (_name, body) => {
+ stubPatch(jsonResponse(body));
+ const { result, showToast } = assign();
+
+ await expect(result).resolves.toBeNull();
+ expect(showToast).toHaveBeenCalledWith(
+ "Couldn't assign element id: element not found in index.html",
+ "error",
+ );
+ });
+
+ it("is null with the server's reason in a toast when the patch is refused", async () => {
+ stubPatch(
+ new Response(JSON.stringify({ error: "target not found" }), {
+ status: 409,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const { result, showToast } = assign();
+
+ await expect(result).resolves.toBeNull();
+ expect(showToast).toHaveBeenCalledWith("Couldn't save edit: target not found", "error");
+ });
+
+ it("is null with a plain toast when the refusal has no JSON reason", async () => {
+ stubPatch(new Response("boom", { status: 500, headers: { "content-type": "text/plain" } }));
+ const { result, showToast } = assign();
+
+ await expect(result).resolves.toBeNull();
+ expect(showToast).toHaveBeenCalledWith("Couldn't save edit", "error");
+ });
+
+ it("refuses a non-finite target before any request", async () => {
+ const fetchMock = stubPatch(jsonResponse({ changed: true }));
+ const { result, showToast } = assign({
+ selection: { ...selection, selectorIndex: Number.NaN },
+ });
+
+ await expect(result).resolves.toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showToast).toHaveBeenCalledWith(
+ "Couldn't assign element id because the patch contains invalid values",
+ "error",
+ );
+ });
+
+ it("lets a network failure through", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new TypeError("offline");
+ }),
+ );
+ await expect(assign().result).rejects.toThrow("offline");
+ });
+});
diff --git a/packages/studio/src/hooks/useDomEditCommitsHelpers.ts b/packages/studio/src/hooks/useDomEditCommitsHelpers.ts
index 9d4af820dc..f2dfa12b34 100644
--- a/packages/studio/src/hooks/useDomEditCommitsHelpers.ts
+++ b/packages/studio/src/hooks/useDomEditCommitsHelpers.ts
@@ -8,6 +8,8 @@ import type { DomEditPatchBatch } from "./domEditCommitTypes";
import { formatFieldsSuffix } from "./gsapScriptCommitHelpers";
import { studioWriteHeaders } from "../utils/studioFileVersion";
import { studioApiFetch } from "../utils/studioApiFetch";
+import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
export function formatUnsafeFieldList(fields: Array<{ path: string }>): string {
return fields.map((field) => field.path).join(", ");
@@ -169,6 +171,8 @@ export interface PatchElementResponse {
content?: string;
path?: string;
version?: string;
+ /** The patched element's id after the patch; absent when the target was not found. */
+ elementId?: string | null;
}
type ShowToast = (message: string, tone?: "error" | "info") => void;
@@ -199,6 +203,46 @@ export async function postPatchElement(
return (await response.json()) as PatchElementResponse;
}
+interface AssignAutoIdParams {
+ projectId: string;
+ targetPath: string;
+ selection: DomEditSelection;
+ autoId: string;
+ showToast: ShowToast;
+}
+
+/** The id the file holds for the element after proposing `autoId` (the server keeps or dedupes it); null if none. */
+export async function assignGsapTargetAutoIdIfNeeded({
+ projectId,
+ targetPath,
+ selection,
+ autoId,
+ showToast,
+}: AssignAutoIdParams): Promise<string | null> {
+ const patchBody = {
+ target: {
+ id: selection.id,
+ hfId: selection.hfId,
+ selector: selection.selector,
+ selectorIndex: selection.selectorIndex,
+ },
+ operations: [{ type: "ensure-id", property: "id", value: autoId }],
+ };
+ if (findUnsafeDomPatchValues(patchBody).length > 0) {
+ showToast("Couldn't assign element id because the patch contains invalid values", "error");
+ return null;
+ }
+ try {
+ const { elementId } = await postPatchElement(projectId, targetPath, patchBody, showToast);
+ if (elementId) return elementId;
+ showToast(`Couldn't assign element id: element not found in ${targetPath}`, "error");
+ return null;
+ } catch (error) {
+ if (error instanceof StudioSaveHttpError && error.alreadyToasted) return null;
+ throw error;
+ }
+}
+
export async function writePreparedContent(
targetPath: string,
patchedContent: string,
diff --git a/packages/studio/src/hooks/useGsapAnimationOps.test.tsx b/packages/studio/src/hooks/useGsapAnimationOps.test.tsx
index 06e2055e69..070e27dd2f 100644
--- a/packages/studio/src/hooks/useGsapAnimationOps.test.tsx
+++ b/packages/studio/src/hooks/useGsapAnimationOps.test.tsx
@@ -3,6 +3,8 @@ import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import { patchElementInHtml } from "../../../studio-server/src/helpers/sourceMutation.js";
+import { jsonResponse } from "./fetchStubTestUtils";
import { useGsapAnimationOps } from "./useGsapAnimationOps";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -13,6 +15,8 @@ let cleanup: (() => void) | null = null;
afterEach(() => {
cleanup?.();
cleanup = null;
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
});
const selection = { id: "box", selector: "#box" } as DomEditSelection;
@@ -20,11 +24,12 @@ const selection = { id: "box", selector: "#box" } as DomEditSelection;
function renderOps(
commitMutationSafely: (...args: unknown[]) => Promise<void>,
commitMutation: (...args: unknown[]) => Promise<void> = vi.fn(async () => undefined),
+ projectId: string | null = "project",
): HookApi {
const captured: { api: HookApi | null } = { api: null };
function Probe() {
captured.api = useGsapAnimationOps({
- projectIdRef: { current: "project" },
+ projectIdRef: { current: projectId },
activeCompPath: "index.html",
commitMutation,
commitMutationSafely,
@@ -42,6 +47,52 @@ function renderOps(
return captured.api;
}
+const CARDS = `<div data-hf-id="hf-a" class="card"></div><div data-hf-id="hf-b" class="card"></div>`;
+
+function mountCards(): HTMLElement[] {
+ document.body.innerHTML = CARDS;
+ return [...document.body.querySelectorAll<HTMLElement>(".card")];
+}
+
+function addTo(api: HookApi, element: HTMLElement, hfId: string): Promise<void> {
+ return api.addGsapAnimation({ element, hfId } as unknown as DomEditSelection, "from");
+}
+
+/** The patch-element route over an in-memory copy of CARDS, patched by the server's own code. */
+function serveCards() {
+ let html = CARDS;
+ return {
+ handle(init?: RequestInit): Response {
+ const { target, operations } = JSON.parse(String(init?.body));
+ const result = patchElementInHtml(html, target, operations);
+ const changed = result.html !== html;
+ html = result.html;
+ return jsonResponse({
+ ok: true,
+ changed,
+ matched: result.matched,
+ elementId: result.elementId,
+ });
+ },
+ stub(route: (init: RequestInit | undefined, call: number) => Promise<Response>) {
+ let calls = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_input: unknown, init?: RequestInit) => route(init, ++calls)),
+ );
+ },
+ ids(): Record<string, string | null> {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ return Object.fromEntries(
+ [...doc.querySelectorAll("[data-hf-id]")].map((el) => [
+ el.getAttribute("data-hf-id"),
+ el.getAttribute("id"),
+ ]),
+ );
+ },
+ };
+}
+
function deferredCommit() {
let release!: () => void;
const promise = new Promise<void>((resolve) => {
@@ -86,6 +137,135 @@ describe("useGsapAnimationOps settlement", () => {
);
});
+ it.each([
+ ["saved", true, "div"],
+ ["refused", false, null],
+ ])(
+ "an id-less element takes the file's id only when the id write is %s",
+ async (_name, saved, id) => {
+ const server = serveCards();
+ const [element] = mountCards();
+ server.stub(async (init) =>
+ saved ? server.handle(init) : jsonResponse({ error: "file changed" }, 409),
+ );
+ const commitMutation = vi.fn(async () => undefined);
+ const api = renderOps(
+ vi.fn(async () => undefined),
+ commitMutation,
+ );
+
+ await addTo(api, element!, "hf-a");
+
+ expect(element!.getAttribute("id")).toBe(id);
+ expect(server.ids()).toEqual({ "hf-a": id, "hf-b": null });
+ expect(commitMutation).toHaveBeenCalledTimes(id ? 1 : 0);
+ },
+ );
+
+ it("a reply lost after the id is saved never lets a sibling reuse that id", async () => {
+ const server = serveCards();
+ const [first, second] = mountCards();
+ server.stub(async (init, call) => {
+ const reply = server.handle(init);
+ if (call === 1) throw new TypeError("connection reset");
+ return reply;
+ });
+ const commitMutation = vi.fn(async () => undefined);
+ const api = renderOps(
+ vi.fn(async () => undefined),
+ commitMutation,
+ );
+
+ await expect(addTo(api, first!, "hf-a")).rejects.toThrow("connection reset");
+ await addTo(api, second!, "hf-b");
+
+ expect(server.ids()).toEqual({ "hf-a": "div", "hf-b": "div-2" });
+ expect(second!.id).toBe("div-2");
+ expect(commitMutation).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ targetSelector: "#div-2" }),
+ expect.anything(),
+ );
+
+ await addTo(api, first!, "hf-a");
+
+ expect(server.ids()).toEqual({ "hf-a": "div", "hf-b": "div-2" });
+ expect(first!.id).toBe("div");
+ });
+
+ it("a refused add never strips the id an overlapping saved add gave the same element", async () => {
+ const server = serveCards();
+ const [element] = mountCards();
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ server.stub(async (init, call) => {
+ if (call !== 1) return server.handle(init);
+ await held;
+ return jsonResponse({ error: "file changed" }, 409);
+ });
+ const api = renderOps(vi.fn(async () => undefined));
+
+ const refused = addTo(api, element!, "hf-a");
+ await addTo(api, element!, "hf-a");
+ release();
+ await refused;
+
+ expect(server.ids()["hf-a"]).toBeTruthy();
+ expect(element!.id).toBe(server.ids()["hf-a"]);
+ });
+
+ it("overlapping adds on siblings take the ids the file holds, never one id twice", async () => {
+ const server = serveCards();
+ const [first, second] = mountCards();
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ server.stub(async (init, call) => {
+ if (call === 1) await held;
+ return server.handle(init);
+ });
+ const api = renderOps(vi.fn(async () => undefined));
+
+ const adding = addTo(api, first!, "hf-a");
+ await addTo(api, second!, "hf-b");
+ release();
+ await adding;
+
+ const ids = server.ids();
+ expect(new Set([ids["hf-a"], ids["hf-b"]])).toEqual(new Set(["div", "div-2"]));
+ expect([first!.id, second!.id]).toEqual([ids["hf-a"], ids["hf-b"]]);
+ });
+
+ it("leaves no id when the id write never reaches the file", async () => {
+ const [element] = mountCards();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new TypeError("offline");
+ }),
+ );
+ const api = renderOps(vi.fn(async () => undefined));
+
+ await expect(addTo(api, element!, "hf-a")).rejects.toThrow("offline");
+ expect(element!.hasAttribute("id")).toBe(false);
+ });
+
+ it("leaves no id when there is no project to save it to", async () => {
+ const [element] = mountCards();
+ const api = renderOps(
+ vi.fn(async () => undefined),
+ undefined,
+ null,
+ );
+
+ await addTo(api, element!, "hf-a");
+
+ expect(element!.hasAttribute("id")).toBe(false);
+ });
+
it("soft-reloads the preview when deleting an animation", async () => {
const commitMutationSafely = vi.fn(async () => undefined);
const api = renderOps(commitMutationSafely);
diff --git a/packages/studio/src/hooks/useGsapAnimationOps.ts b/packages/studio/src/hooks/useGsapAnimationOps.ts
index fafaa9fb79..e0e73d43c2 100644
--- a/packages/studio/src/hooks/useGsapAnimationOps.ts
+++ b/packages/studio/src/hooks/useGsapAnimationOps.ts
@@ -14,10 +14,9 @@ import {
cutoverCommittedOrThrow,
type CutoverDeps,
} from "../utils/sdkCutover";
-import {
- assignGsapTargetAutoIdIfNeeded,
- ensureElementAddressable,
-} from "./gsapScriptCommitHelpers";
+import { ensureElementAddressable } from "./gsapScriptCommitHelpers";
+import { idSelector } from "./gsapShared";
+import { assignGsapTargetAutoIdIfNeeded } from "./useDomEditCommitsHelpers";
import type { CommitMutation, SafeGsapCommitMutation } from "./gsapScriptCommitTypes";
interface SdkAnimationDeps {
@@ -122,12 +121,14 @@ export function useGsapAnimationOps({
method: "to" | "from" | "set" | "fromTo",
_currentTime?: number,
) => {
- const { selector, autoId } = ensureElementAddressable(selection);
+ const address = ensureElementAddressable(selection);
+ const { autoId } = address;
+ let selector = address.selector;
if (autoId) {
const pid = projectIdRef.current;
- const targetPath = selection.sourceFile || activeCompPath || "index.html";
if (!pid) return;
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
const assign = () =>
assignGsapTargetAutoIdIfNeeded({
projectId: pid,
@@ -136,10 +137,12 @@ export function useGsapAnimationOps({
autoId,
showToast,
});
- const assigned = await (writeProjectFile
+ const savedId = await (writeProjectFile
? serializeStudioFileMutation(writeProjectFile, targetPath, assign)
: assign());
- if (!assigned) return;
+ if (!savedId) return;
+ selection.element.setAttribute("id", savedId);
+ selector = idSelector(savedId);
}
const elStart = Number.parseFloat(selection.dataAttributes?.start ?? "0") || 0;
@@ -153,10 +156,8 @@ export function useGsapAnimationOps({
fromTo: { x: 0, y: 0, opacity: 1 },
};
- // Skip SDK path when an id was just assigned server-side (autoId): the
- // SDK session hasn't reloaded that write yet, so persisting its
- // serialization would clobber the new id — let the server add the tween
- // atomically with the id it wrote.
+ // After an id write (autoId) the SDK session has not reloaded the file yet,
+ // so persisting its serialization would drop the new id.
if (!autoId && selection.hfId && sdkSession && sdkDeps) {
const targetPath = selection.sourceFile || activeCompPath || "index.html";
const spec = {
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
index 5bff506acb..a10969e7cf 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
+++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
@@ -36,6 +36,7 @@ import type {
MutationResult,
} from "./gsapScriptCommitTypes";
import { persistSdkSerialize } from "../utils/sdkCutover";
+import { jsonResponse } from "./fetchStubTestUtils";
import { applyPreviewSync, useGsapScriptCommits } from "./useGsapScriptCommits";
import { hasStudioPendingEdits } from "../utils/studioPendingEdits";
@@ -715,6 +716,22 @@ describe("runCommit — instantPatch wiring", () => {
expect(trackStudioEvent.mock.calls.filter(([event]) => event === "keyframe")).toEqual([]);
});
+ it("rejects a refused write with the server's reason in a toast", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse({ error: "file changed on disk" }, 409)),
+ );
+ const deps = renderCommitHook();
+
+ await expect(
+ deps.api.commitMutation(selection, { type: "add-keyframe" }, { label: "Add" }),
+ ).rejects.toThrow();
+ expect(deps.showToast).toHaveBeenCalledWith(
+ expect.stringContaining("file changed on disk"),
+ "error",
+ );
+ });
+
const NESTED_SCRIPT = 'window.__timelines["root"] = tl;';
const SUB = `<template><div data-composition-id="sub"><div id="nwid" style="left: 40px"></div></div></template>`;
@@ -867,6 +884,8 @@ describe("runCommit — instantPatch wiring", () => {
body: JSON.stringify({ mutations: [firstMutation, lastMutation] }),
}),
);
+ const [, init] = vi.mocked(fetch).mock.calls[0]!;
+ expect(new Headers(init?.headers).get("X-Hyperframes-Write-Token")).toBeTruthy();
expect(deps.recordEdit).toHaveBeenCalledTimes(1);
expect(deps.recordEdit).toHaveBeenCalledWith(
expect.objectContaining({ label: "Resize", coalesceKey: "tx:resize:1" }),
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts
index cbe5d21dd2..53e62f7624 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.ts
+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts
@@ -44,41 +44,15 @@ import {
useGsapSaveFailureTelemetry,
useSafeGsapCommitMutation,
} from "./useSafeGsapCommitMutation";
-import { studioWriteHeaders } from "../utils/studioFileVersion";
-import { studioApiFetch } from "../utils/studioApiFetch";
+import { requestGsapMutation } from "./gsapMutationClient";
async function mutateGsapScript(
projectId: string,
+ route: "gsap-mutations" | "gsap-mutations-batch",
sourceFile: string,
- mutation: Record<string, unknown>,
+ body: unknown,
): Promise<MutationResult> {
- const res = await studioApiFetch(
- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(sourceFile)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
- body: JSON.stringify(mutation),
- },
- );
- if (!res.ok) throw new GsapMutationHttpError(res.status, await readJsonResponseBody(res));
- const result = (await res.json()) as MutationResult;
- if (!result.ok) throw new Error(`Failed to update GSAP in ${sourceFile}`);
- return result;
-}
-
-async function mutateGsapScriptBatch(
- projectId: string,
- sourceFile: string,
- mutations: Record<string, unknown>[],
-): Promise<MutationResult> {
- const res = await studioApiFetch(
- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations-batch/${encodeURIComponent(sourceFile)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
- body: JSON.stringify({ mutations }),
- },
- );
+ const res = await requestGsapMutation(projectId, route, sourceFile, body);
if (!res.ok) throw new GsapMutationHttpError(res.status, await readJsonResponseBody(res));
const result = (await res.json()) as MutationResult;
if (!result.ok) throw new Error(`Failed to update GSAP in ${sourceFile}`);
@@ -392,7 +366,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
const runCommit = useCallback(async (pid: string, compositionPath: string | null, targetPath: string, selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
const result = await runMutationRequest([mutation], options, showToast, () =>
- mutateGsapScript(pid, targetPath, mutation),
+ mutateGsapScript(pid, "gsap-mutations", targetPath, mutation),
);
if (!result) return;
trackKeyframeCommit([mutation], result, options);
@@ -406,7 +380,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
if (!first || !last) return;
const mutations = calls.map(({ mutation }) => mutation);
const result = await runMutationRequest(mutations, options, showToast, () =>
- mutateGsapScriptBatch(pid, targetPath, mutations),
+ mutateGsapScript(pid, "gsap-mutations-batch", targetPath, { mutations }),
);
if (!result) return;
trackKeyframeCommit(mutations, result, options, calls.map((call) => call.options));