Files
hyperframes/packages/studio/src/hooks/gsapScriptCommitHelpers.ts
T
Miguel Ángel bea32b8aae fix(studio): stop a Studio edit from reloading the preview (#3137)
* fix(studio): stop a Studio edit from reloading the preview as if it were external

Every mutation route wrote the file without leaving a write receipt, so the
watcher's broadcast of Studio's own edit arrived with no identity on it. The
external-change coordinator could not tell that echo from an agent or an editor
writing the file behind Studio's back, so it took the safe branch and did a full
iframe reload. That reload hides the stage for the length of the reload, which is
what the flash after a text edit was.

Every mutation write now goes through one helper that records the receipt, and
the client claims the write before the request goes out rather than after it: the
server writes and the watcher fires while the request is still in flight, so a
token marked from the response can arrive after the echo it was meant to match.

Reproduced in the browser before and after, with the reload path traced end to
end. Before, a patch-element write logged `token: null` then a reload from the
coordinator; after, the same write logs the token and `suppressed: own write
token`, with no reload.

Adds `hf-reload-debug` (localStorage, off by default) alongside the existing
`hf-resize-debug`: it records each file-change decision and its reason, plus the
stack of whoever asked for a full reload.

* fix(studio): claim the timeline and caption writes too, not just the DOM ones

The receipt only helps when the client marked the token it sent, and the GSAP
mutation writers never sent one. A drag commits through gsap-mutations, so the
server minted a token the client had never seen, the change came back looking
like someone else's, and the preview did the full reload the receipt was meant
to prevent.

Same one-line claim on both GSAP mutation writers, the timing sync's mutation
call, and the caption auto-save PUT.

The rollback call stays deliberately unclaimed and says why: it runs because a
mutation did not converge, so the preview is on bytes nobody can vouch for and
the reload is the point.

Verified live: a drag-shaped update-properties on the timeline now logs
`suppressed: own write token` with no reload, where it logged a coordinator
reload before.

* refactor(studio): keep timelineTimingSync under the size cap

Claiming the timeline writes pushed this file one line past the 600-line
gate. Same change as the branch made later, landed with the commit that
caused it.

* fix(studio): cover remaining write receipt paths

* fix(studio): preserve batch write receipts

* fix(cli): emit every file in a watcher burst
2026-08-09 19:10:02 -04:00

139 lines
4.5 KiB
TypeScript

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";
/**
* 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.
*/
export function ensureElementAddressable(selection: DomEditSelection): {
selector: string;
autoId?: string;
} {
if (selection.id) return { selector: idSelector(selection.id) };
const el = selection.element;
const doc = el.ownerDocument;
if (selection.selector && matchesExactlyOne(doc, selection.selector, el)) {
return { selector: selection.selector };
}
const tag = el.tagName.toLowerCase();
let id = tag;
let n = 1;
while (doc.getElementById(id)) {
n += 1;
id = `${tag}-${n}`;
}
el.setAttribute("id", id);
return { selector: idSelector(id), autoId: id };
}
export class GsapMutationHttpError extends Error {
constructor(
readonly statusCode: number,
readonly responseBody: unknown,
) {
super(formatGsapMutationHttpErrorMessage(statusCode, responseBody));
this.name = "GsapMutationHttpError";
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
export function formatFieldsSuffix(rawFields: unknown): string {
const fields = Array.isArray(rawFields)
? rawFields.filter((f): f is string => typeof f === "string")
: [];
return fields.length > 0 ? ` (${fields.join(", ")})` : "";
}
export async function readJsonResponseBody(res: Response): Promise<unknown> {
const contentType = res.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
return await res.text().catch(() => null);
}
return await res.json().catch(() => null);
}
function formatGsapMutationHttpErrorMessage(statusCode: number, body: unknown): string {
if (isRecord(body) && typeof body.error === "string") {
return body.error;
}
return `GSAP mutation failed with status ${statusCode}`;
}
export function formatGsapMutationRejectionToast(error: GsapMutationHttpError): string {
const body = error.responseBody;
if (isRecord(body)) {
return `Couldn't save animation: ${formatGsapMutationHttpErrorMessage(
error.statusCode,
body,
)}${formatFieldsSuffix(body.fields)}`;
}
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 fetch(
`/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;
}