perf(studio): commit a group drag in one request

Dragging N elements cost N writes and 9 reads for a three-element group: each
member fetched the composition's parse to preflight, fetched it again to
resolve its tween, then wrote the file on its own round trip. Every one of
those writes re-read, re-parsed and re-serialized the whole composition.

Three changes, same behaviour:

- The parse endpoint shares an in-flight request per file, so callers asking
  for the same composition at the same moment get one request. Only
  overlapping calls share — the entry is dropped as soon as it settles, so a
  read after a write still gets a fresh parse.
- The group preflight runs its members together instead of one at a time. A
  preflight writes nothing, so there is nothing to order.
- Members' mutations are queued and sent as one batch write. Anything that
  re-reads the file flushes the queue first, so a member resolving a shared or
  stale tween never reads a composition missing writes it is about to build
  on. The batch carries each member's runtime patch, and only the last one
  re-renders.

A three-element group drag now issues 2 reads and 1 write, down from 9 and 3.
This commit is contained in:
Miguel Angel Simon Sierra
2026-08-08 16:03:14 -07:00
parent 2329bd581f
commit 8a56c79897
6 changed files with 276 additions and 47 deletions
@@ -49,6 +49,14 @@ export interface CommitMutationOptions {
* existing soft/full reload path. Structural edits omit this and reload as before.
*/
instantPatch?: { selector: string; change: RuntimeTweenChange };
/**
* The same fast path for a batched commit: one patch per element the batch
* wrote, applied in order. All of them must land for the reload to be skipped
* — one that can't be applied leaves the preview half-patched, so the whole
* batch falls back to the reload. Only the last patch re-renders (see
* `deferSeek`), so a ten-element batch repaints once.
*/
instantPatches?: Array<{ selector: string; change: RuntimeTweenChange }>;
}
export interface CommitMutationCall {
@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fetchParsedAnimations } from "./keyframeCacheAstLoad";
/**
* Parsing a composition is a whole-file read + parse on the server, and a
* multi-element action asks for the same file once per element. Callers that
* overlap in time share one request; a caller that comes after the last one
* settled does not, so a parse issued after a write is never served a
* pre-write answer.
*/
describe("fetchParsedAnimations — in-flight sharing", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
function stubFetch(): { calls: () => number; settle: () => void } {
let calls = 0;
const pending: Array<() => void> = [];
vi.stubGlobal("fetch", () => {
calls++;
return new Promise((resolve) => {
pending.push(() =>
resolve({
ok: true,
json: () => Promise.resolve({ animations: [{ id: "a", targetSelector: "#a" }] }),
} as Response),
);
});
});
return {
calls: () => calls,
settle: () => {
for (const release of pending.splice(0, pending.length)) release();
},
};
}
it("serves overlapping reads of one file from a single request", async () => {
const fetchStub = stubFetch();
const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
];
fetchStub.settle();
const results = await Promise.all(pending);
expect(fetchStub.calls()).toBe(1);
expect(results.map((parsed) => parsed?.animations.length)).toEqual([1, 1, 1]);
});
it("does not share across files", async () => {
const fetchStub = stubFetch();
const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "other.html"),
];
fetchStub.settle();
await Promise.all(pending);
expect(fetchStub.calls()).toBe(2);
});
it("re-requests once the previous read has settled", async () => {
const fetchStub = stubFetch();
const first = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await first;
const second = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await second;
expect(fetchStub.calls()).toBe(2);
});
});
@@ -42,7 +42,32 @@ function hasAnimations(value: unknown): value is ParsedGsapAnimations {
);
}
export async function fetchParsedAnimations(
/**
* Requests for the same file that overlap in time, keyed `projectId|sourceFile`.
*
* Every parse re-reads and re-parses the whole composition server-side, and a
* multi-element action asks for the same file once per element. Sharing the
* in-flight promise makes that one request. Only OVERLAPPING calls share: the
* entry is dropped the moment it settles, so a call made after a write still
* gets a fresh parse.
*/
const inFlightParses = new Map<string, Promise<ParsedGsapAnimations | null>>();
export function fetchParsedAnimations(
projectId: string,
sourceFile: string,
): Promise<ParsedGsapAnimations | null> {
const key = `${projectId}|${sourceFile}`;
const inFlight = inFlightParses.get(key);
if (inFlight) return inFlight;
const request = requestParsedAnimations(projectId, sourceFile).finally(() => {
inFlightParses.delete(key);
});
inFlightParses.set(key, request);
return request;
}
async function requestParsedAnimations(
projectId: string,
sourceFile: string,
): Promise<ParsedGsapAnimations | null> {
@@ -24,7 +24,11 @@ import {
useGsapSaveFailureTelemetry,
useSafeGsapCommitMutation,
} from "./useSafeGsapCommitMutation";
import type { CommitMutation } from "./gsapScriptCommitTypes";
import type {
CommitMutation,
CommitMutationCall,
CommitMutationOptions,
} from "./gsapScriptCommitTypes";
import { setElementGsapPosition } from "../utils/elementGsap";
import { logResize, logResizeSettle } from "../utils/resizeDebug";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
@@ -163,37 +167,63 @@ export function useGsapAwareEditing({
// positions are already on screen, so holding the render until the last
// member has been written costs nothing and never shows a half-moved group.
let renderOnCommit = false;
const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) =>
gsapCommitMutation(selection, mutation, {
...options,
coalesceKey,
coalesceMs: Number.POSITIVE_INFINITY,
deferPreviewSync: !renderOnCommit,
const withGroupOptions = (options: CommitMutationOptions): CommitMutationOptions => ({
...options,
coalesceKey,
coalesceMs: Number.POSITIVE_INFINITY,
deferPreviewSync: !renderOnCommit,
});
// Every member writes the same file. Queue their mutations and send them as
// ONE request instead of one round trip per member: the server reads, parses
// and writes the composition once, and the preview patches once.
const queued: CommitMutationCall[] = [];
const flushQueued = async () => {
if (queued.length === 0) return;
const calls = queued.splice(0, queued.length);
if (!gsapCommitMutation.batch) {
for (const call of calls) {
await gsapCommitMutation(call.selection, call.mutation, call.options);
}
return;
}
await gsapCommitMutation.batch(calls, {
...(calls.at(-1)?.options ?? { label: "Move animated layer (group)" }),
label: "Move animated layer (group)",
});
};
const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) => {
queued.push({ selection, mutation, options: withGroupOptions(options) });
return Promise.resolve();
};
const preflightAnimations = new Map<DomEditSelection, GsapAnimation[]>();
// Editability is user-atomic: prove every member can be written before
// the first source mutation. Network failures after this point retain the
// existing multi-request semantics, but a blocked member can never leave
// earlier siblings partially moved.
for (const { selection } of updates) {
try {
const animations = await makeFetchFallback(selection, { failOnFetchError: true })();
preflightAnimations.set(selection, animations);
const outcome = await tryGsapDragIntercept(
selection,
{ x: 0, y: 0 },
animations,
previewIframeRef.current,
coalescedCommit,
undefined,
{ preflightOnly: true },
);
assertGsapEditPersisted(outcome);
} catch (error) {
trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)");
throw error;
}
}
// Every member reads the same file, and a preflight writes nothing — so run
// them together. The parse layer shares one in-flight request per file, which
// turns N sequential round trips into one.
await Promise.all(
updates.map(async ({ selection }) => {
try {
const animations = await makeFetchFallback(selection, { failOnFetchError: true })();
preflightAnimations.set(selection, animations);
const outcome = await tryGsapDragIntercept(
selection,
{ x: 0, y: 0 },
animations,
previewIframeRef.current,
coalescedCommit,
undefined,
{ preflightOnly: true },
);
assertGsapEditPersisted(outcome);
} catch (error) {
trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)");
throw error;
}
}),
);
for (const [index, { selection, next }] of updates.entries()) {
renderOnCommit = index === updates.length - 1;
try {
@@ -203,7 +233,13 @@ export function useGsapAwareEditing({
preflightAnimations.get(selection) ?? [],
previewIframeRef.current,
coalescedCommit,
makeFetchFallback(selection),
// The intercept re-reads the file to resolve a stale or shared tween.
// Anything already queued has to be on disk before that read, or it
// resolves against a file missing writes it is about to build on.
async () => {
await flushQueued();
return makeFetchFallback(selection)();
},
{ preflightPassed: true },
);
assertGsapEditPersisted(outcome);
@@ -212,6 +248,15 @@ export function useGsapAwareEditing({
throw error;
}
}
try {
await flushQueued();
} catch (error) {
const selection = updates.at(-1)?.selection;
if (selection) {
trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)");
}
throw error;
}
},
[gsapCommitMutation, previewIframeRef, makeFetchFallback, trackGsapInteractionFailure],
);
@@ -73,10 +73,13 @@ describe("applyPreviewSync", () => {
syncDragPreview(result(), reloadPreview);
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(FAKE_IFRAME, "#a", {
kind: "set",
props: { x: 10 },
},
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(
FAKE_IFRAME,
"#a",
{
kind: "set",
props: { x: 10 },
},
undefined,
false,
);
@@ -84,6 +87,63 @@ describe("applyPreviewSync", () => {
expect(reloadPreview).not.toHaveBeenCalled();
});
it("instantPatches: patches every element the batch wrote, rendering once at the end", () => {
patchRuntimeTweenInPlace.mockReturnValue(true);
const reloadPreview = vi.fn();
applyPreviewSync(
FAKE_IFRAME,
result(),
{
label: "Move animated layer (group)",
softReload: true,
instantPatches: [
{ selector: "#a", change: { kind: "set" as const, props: { x: 1 } } },
{ selector: "#b", change: { kind: "set" as const, props: { x: 2 } } },
{ selector: "#c", change: { kind: "set" as const, props: { x: 3 } } },
],
},
reloadPreview,
);
// Only the last patch re-renders — the earlier two defer their seek, so the
// group repaints once instead of once per member.
expect(patchRuntimeTweenInPlace.mock.calls.map((call) => [call[1], call[4]])).toEqual([
["#a", true],
["#b", true],
["#c", false],
]);
expect(applySoftReload).not.toHaveBeenCalled();
expect(reloadPreview).not.toHaveBeenCalled();
});
it("instantPatches: one patch that misses falls the whole batch back to the reload", () => {
patchRuntimeTweenInPlace.mockImplementation((_iframe, selector) => selector !== "#b");
applySoftReload.mockReturnValue("applied");
const reloadPreview = vi.fn();
applyPreviewSync(
FAKE_IFRAME,
result({ scriptText: "SCRIPT" }),
{
label: "Move animated layer (group)",
softReload: true,
instantPatches: [
{ selector: "#a", change: { kind: "set" as const, props: { x: 1 } } },
{ selector: "#b", change: { kind: "set" as const, props: { x: 2 } } },
],
},
reloadPreview,
);
// A half-patched preview is worse than a reloaded one: "#a" landed, "#b" did
// not, so the reload repaints both from the written source.
expect(applySoftReload).toHaveBeenCalled();
expect(trackStudioEvent).toHaveBeenCalledWith("gsap_instant_patch_fallback", {
selector: "#b",
});
});
it("instantPatch + patch fails: falls back to the soft reload, passing onAsyncFailure", () => {
patchRuntimeTweenInPlace.mockReturnValue(false);
applySoftReload.mockReturnValue("applied");
@@ -341,10 +401,13 @@ describe("runCommit — instantPatch wiring", () => {
// The file already matched (changed:false) but the runtime patch deferred
// from the paired first commit must still land.
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(FAKE_IFRAME, "#a", {
kind: "set",
props: { x: 485, y: 311 },
},
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(
FAKE_IFRAME,
"#a",
{
kind: "set",
props: { x: 485, y: 311 },
},
undefined,
false,
);
@@ -249,19 +249,24 @@ export function applyPreviewSync(
options: CommitMutationOptions,
reloadPreview: () => void,
): void {
if (options.instantPatch) {
const patched = patchRuntimeTweenInPlace(
iframe,
options.instantPatch.selector,
options.instantPatch.change,
undefined,
options.deferPreviewSync === true,
const patches = options.instantPatches ?? (options.instantPatch ? [options.instantPatch] : []);
if (patches.length > 0) {
const deferSeek = options.deferPreviewSync === true;
const missed = patches.find(
(patch, index) =>
!patchRuntimeTweenInPlace(
iframe,
patch.selector,
patch.change,
undefined,
deferSeek || index < patches.length - 1,
),
);
// Patched in place — element is already correct on screen; no reload needed.
if (patched) return;
// Patched in place — elements are already correct on screen; no reload needed.
if (!missed) return;
// The instant path couldn't patch in place — record the fallback so we can
// track how often the fast path misses before the soft/full reload below.
trackStudioEvent("gsap_instant_patch_fallback", { selector: options.instantPatch.selector });
trackStudioEvent("gsap_instant_patch_fallback", { selector: missed.selector });
// Fall through to the soft/full reload path below.
}
// Written, but the caller has more writes to make and will render after the last.
@@ -360,7 +365,12 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
);
if (!result) return;
options.onResult?.(result);
await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, options);
// Each call brings its own fast-path patch; the batch wrote them all, so the
// preview sync applies them all rather than just the last call's.
const instantPatches = calls
.map(({ options: callOptions }) => callOptions.instantPatch)
.filter((patch) => patch !== undefined);
await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, instantPatches.length > 0 ? { ...options, instantPatches } : options);
}, [showToast, finalizeSuccessfulMutation]);
// Every GSAP-script commit is a read-modify-write of one file. Overlapping