Skip to content

Commit 70dde41

Browse files
perf(studio): keep timeline bulk actions under a second, hand-move at most 3 clips (#4932)
* perf(studio): keep timeline bulk actions under a second, hand-move at most 3 clips Dragging or keyboard-moving a selection of 4 or more clips is refused with a toast pointing at the prompt box; 1 to 3 clips move as before. Root causes of the multi-second waits on large projects: - every selected clip fired its own source-existence probe; they now leave as one request per file - a timeline delete sent one request per clip, each re-parsing the file; it is now one request that parses once - each click on a clip from another file re-fetched GSAP data for every composition; covered files are kept and unchanged files answer 304 - any root index.html write re-captured every composition thumbnail; only a root head edit does now, since a scene page borrows nothing else from it Adds timeline-bulk-actions.mjs, a browser benchmark of select-all, move 3 and delete-all on a real project. * chore(studio): trim the bulk benchmark header to the comment limit * refactor(studio): tidy the bulk-action fixes after review Root head memo is keyed by the root file's content so every subscriber of one write gets one answer, and a thumbnail request can no longer overwrite it. The GSAP read reuses the shared content version as its ETag. * fix(studio): keep a head edit's thumbnail refresh when a later write replaces it File changes coalesce to the newest while a drain is in flight, so the affected-composition lists are merged instead of replaced. A failed GSAP read stays unloaded and is retried, and the GSAP read's ETag is salted with the parser version. * feat(studio): cap hand-resizing a multi-selection at 3 clips like moving Dragging a resize edge with 4 or more clips selected is refused with the same toast as a move; the rule is one constant and one helper shared by pointer move, pointer resize and keyboard pickup. * fix(studio): keep a head edit's thumbnail refresh through a replaced conflict A newer blocked change replaces the held one, so it now inherits the thumbnails the held one owed. * fix(studio): keep a held head edit's thumbnail refresh when a later write saves cleanly The clean-save path and the failed-cleanup path now merge the held blocked change's affected compositions, and the blocked-state merge runs inside the state update so two conflicts in one tick cannot lose the first. * chore(studio): keep useTimelineClipDrag under the 600-line cap * feat(studio): cap by the clips an edit would change, and cut the added comments The 3-clip rule counts the clips a move or trim would write to: a locked clip swept into a move stays put, and a trim some member cannot take edits only the grabbed clip. Comment share is back at or under the base in every changed file. * fix(studio): clear fallow audit and comment length on the multi-select cap * fix(studio): keep bench script comments under the block limit * fix(studio): keep the failed file's payload when another file's snapshot delete fails
1 parent 835e0c1 commit 70dde41

29 files changed

Lines changed: 1134 additions & 145 deletions

‎packages/studio-server/src/helpers/compositionInputs.test.ts‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
22
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
5-
import { compositionsAffectedBy } from "./compositionInputs";
5+
import { compositionInputSignature, compositionsAffectedBy } from "./compositionInputs";
66

77
const dirs: string[] = [];
88
afterEach(() => {
@@ -44,8 +44,7 @@ describe("compositionsAffectedBy", () => {
4444
]);
4545
});
4646

47-
it("reaches every composition from the root, an asset, or a file the root does not mount", () => {
48-
expect(compositionsAffectedBy(dir(), "index.html")).toBeNull();
47+
it("reaches every composition from an asset or a file the root does not mount", () => {
4948
expect(compositionsAffectedBy(dir(), "assets/logo.svg")).toBeNull();
5049
expect(compositionsAffectedBy(dir(), "compositions/unmounted.html")).toBeNull();
5150
});
@@ -57,3 +56,57 @@ describe("compositionsAffectedBy", () => {
5756
]);
5857
});
5958
});
59+
60+
describe("a root write", () => {
61+
const html = (head: string, body: string) =>
62+
`<html><head>${head}</head><body>${body}${mount("compositions/a.html")}</body></html>`;
63+
const files = (head: string, body: string) => ({
64+
"index.html": html(head, body),
65+
"compositions/a.html": "<template>a</template>",
66+
});
67+
const rewrite = (dir: string, head: string, body: string) =>
68+
writeFileSync(join(dir, "index.html"), html(head, body));
69+
70+
it("moves every composition when the head changed, or when no head was seen yet", () => {
71+
const dir = project(files("<style>a{}</style>", "x"));
72+
expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
73+
74+
compositionInputSignature(dir, "compositions/a.html", "s1");
75+
rewrite(dir, "<style>b{}</style>", "x");
76+
expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
77+
});
78+
79+
it("moves only the root when the head is as it was", () => {
80+
const dir = project(files("<style>a{}</style>", "x"));
81+
compositionInputSignature(dir, "compositions/a.html", "s1");
82+
rewrite(dir, "<style>a{}</style>", "moved");
83+
expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]);
84+
rewrite(dir, "<style>a{}</style>", "moved again");
85+
expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]);
86+
});
87+
88+
it("tells every subscriber of one head edit the same thing, even after a thumbnail request", () => {
89+
const dir = project(files("<style>a{}</style>", "x"));
90+
compositionInputSignature(dir, "compositions/a.html", "s1");
91+
rewrite(dir, "<style>b{}</style>", "x");
92+
expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
93+
compositionInputSignature(dir, "compositions/a.html", "s2");
94+
expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
95+
});
96+
97+
it("leaves a scene's input signature alone for a body edit, not for a head edit", () => {
98+
const dir = project(files("<style>a{}</style>", "x"));
99+
const before = compositionInputSignature(dir, "compositions/a.html", "s1");
100+
rewrite(dir, "<style>a{}</style>", "moved");
101+
expect(compositionInputSignature(dir, "compositions/a.html", "s2")).toBe(before);
102+
rewrite(dir, "<style>b{}</style>", "moved");
103+
expect(compositionInputSignature(dir, "compositions/a.html", "s3")).not.toBe(before);
104+
});
105+
106+
it("changes the root's own input signature for a body edit", () => {
107+
const dir = project(files("<style>a{}</style>", "x"));
108+
const before = compositionInputSignature(dir, "index.html", "s1");
109+
rewrite(dir, "<style>a{}</style>", "moved");
110+
expect(compositionInputSignature(dir, "index.html", "s2")).not.toBe(before);
111+
});
112+
});

‎packages/studio-server/src/helpers/compositionInputs.ts‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { readFileSync } from "node:fs";
2+
import { createHash } from "node:crypto";
23
import { createProjectSignature } from "./projectSignature.js";
4+
import { rootHeadContent } from "./subComposition.js";
35
import { resolveWithinProject } from "./safePath.js";
46

57
const ROOT_COMPOSITION = "index.html";
@@ -51,8 +53,23 @@ function closureOf(read: SourceReader, compPath: string): Set<string> {
5153
// composition) ever thumbnailed, never evicted; LRU them if a server ever holds thousands.
5254
const inputSignatures = new Map<string, { projectSignature: string; inputSignature: string }>();
5355

56+
interface RootMemo {
57+
root: string;
58+
head: string;
59+
affected: string[] | null;
60+
}
61+
62+
const rootMemos = new Map<string, RootMemo>();
63+
64+
const sha1 = (text: string) => createHash("sha1").update(text).digest("hex");
65+
66+
function rootHashes(read: SourceReader) {
67+
const source = read(ROOT_COMPOSITION) ?? "";
68+
return { root: sha1(source), head: sha1(rootHeadContent(source)) };
69+
}
70+
5471
// What a thumbnail of `compPath` renders from: the project minus the compositions the root
55-
// mounts that `compPath` does not. The root always counts (previews use its head).
72+
// mounts that `compPath` does not; for a scene the root counts as its head alone.
5673
export function compositionInputSignature(
5774
projectDir: string,
5875
compPath: string,
@@ -62,21 +79,40 @@ export function compositionInputSignature(
6279
const known = inputSignatures.get(key);
6380
if (known?.projectSignature === projectSignature) return known.inputSignature;
6481
const read = projectReader(projectDir);
65-
const inputs = closureOf(read, normalizeSource(compPath) ?? compPath).add(ROOT_COMPOSITION);
66-
const siblings = [...closureOf(read, ROOT_COMPOSITION)].filter((path) => !inputs.has(path));
67-
const inputSignature = createProjectSignature(projectDir, new Set(siblings));
82+
const comp = normalizeSource(compPath) ?? compPath;
83+
const inputs = closureOf(read, comp).add(ROOT_COMPOSITION);
84+
const excluded = new Set(
85+
[...closureOf(read, ROOT_COMPOSITION)].filter((path) => !inputs.has(path)),
86+
);
87+
let inputSignature: string;
88+
if (comp === ROOT_COMPOSITION) {
89+
inputSignature = createProjectSignature(projectDir, excluded);
90+
} else {
91+
const hashes = rootHashes(read);
92+
if (!rootMemos.has(projectDir)) rootMemos.set(projectDir, { ...hashes, affected: null });
93+
inputSignature = `${createProjectSignature(projectDir, excluded.add(ROOT_COMPOSITION))}:${hashes.head}`;
94+
}
6895
inputSignatures.set(key, { projectSignature, inputSignature });
6996
return inputSignature;
7097
}
7198

7299
/**
73100
* Compositions whose rendered frames a write at `changedPath` can change, or `null` for all
74-
* of them: the root, assets and any file the root does not mount reach every composition.
101+
* of them: assets, a root head edit, and any file the root does not mount reach every
102+
* composition. A head-preserving root write changes only the root's own frames.
75103
*/
76104
export function compositionsAffectedBy(projectDir: string, changedPath: string): string[] | null {
77105
const changed = changedPath.replace(/\\/g, "/");
78106
const read = projectReader(projectDir);
107+
if (changed === ROOT_COMPOSITION) {
108+
const now = rootHashes(read);
109+
const memo = rootMemos.get(projectDir);
110+
if (memo?.root === now.root) return memo.affected;
111+
const affected = memo?.head === now.head ? [ROOT_COMPOSITION] : null;
112+
rootMemos.set(projectDir, { ...now, affected });
113+
return affected;
114+
}
79115
const mounted = closureOf(read, ROOT_COMPOSITION);
80-
if (changed === ROOT_COMPOSITION || !mounted.has(changed)) return null;
116+
if (!mounted.has(changed)) return null;
81117
return [...mounted].filter((path) => closureOf(read, path).has(changed));
82118
}

‎packages/studio-server/src/helpers/sourceMutation.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,33 @@ import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
44
import { describe, expect, it } from "vitest";
55
import {
66
removeElementFromHtml,
7+
removeElementsFromHtml,
78
patchElementInHtml,
89
probeElementInSource,
10+
probeElementsInSource,
911
} from "./sourceMutation.js";
1012

13+
describe("removeElementsFromHtml", () => {
14+
const html = `<!doctype html><html><body><div data-composition-id="main"><div id="parent"><span id="child"></span></div><div id="a"></div><div id="b"></div><div id="keep"></div></div></body></html>`;
15+
16+
it("matches removing the targets one at a time", () => {
17+
const targets = [{ id: "a" }, { id: "b" }];
18+
const oneByOne = targets.reduce(
19+
(source, target) => removeElementFromHtml(source, target),
20+
html,
21+
);
22+
expect(removeElementsFromHtml(html, targets)).toBe(oneByOne);
23+
expect(oneByOne).toContain(`id="keep"`);
24+
});
25+
26+
it("treats a target nested in an already removed one as done, and an unknown id as a no-op", () => {
27+
const updated = removeElementsFromHtml(html, [{ id: "parent" }, { id: "child" }, { id: "x" }]);
28+
expect(updated).not.toContain(`id="child"`);
29+
expect(updated).toContain(`id="keep"`);
30+
expect(removeElementsFromHtml(html, [{ id: "x" }])).toBe(html);
31+
});
32+
});
33+
1134
describe("removeElementFromHtml", () => {
1235
it("removes a self-closing element by id", () => {
1336
const html = `<!doctype html><html><body><div data-composition-id="main"><img id="photo" src="asset.png" /><div id="rest"></div></div></body></html>`;
@@ -460,6 +483,12 @@ describe("probeElementInSource", () => {
460483
expect(probeElementInSource(FIXTURE, { id: "hero" })).toBe(true);
461484
});
462485

486+
it("answers every target of a batch in order from one parse", () => {
487+
expect(
488+
probeElementsInSource(FIXTURE, [{ id: "hero" }, { id: "gone" }, { selector: ".brand" }, {}]),
489+
).toEqual([true, false, true, false]);
490+
});
491+
463492
it("returns true for an element found by class selector", () => {
464493
expect(probeElementInSource(FIXTURE, { selector: ".hero-heading" })).toBe(true);
465494
});

‎packages/studio-server/src/helpers/sourceMutation.ts‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -137,15 +137,30 @@ export function findTargetElement(
137137
}
138138
}
139139

140-
export function removeElementFromHtml(source: string, target: SourceMutationTarget): string {
140+
/**
141+
* Removes every target in one parse and one serialization. A target nested inside one already
142+
* removed no longer matches, which is a normal outcome rather than a failure.
143+
*/
144+
export function removeElementsFromHtml(
145+
source: string,
146+
targets: readonly SourceMutationTarget[],
147+
): string {
141148
const { document, wrappedFragment } = parseSourceDocument(source);
142-
const element = findTargetElement(document, target);
143-
if (!element) return source;
144-
145-
removeElementWithGsapCascade(document, element);
149+
let removed = false;
150+
for (const target of targets) {
151+
const element = findTargetElement(document, target);
152+
if (!element) continue;
153+
removeElementWithGsapCascade(document, element);
154+
removed = true;
155+
}
156+
if (!removed) return source;
146157
return wrappedFragment ? document.body.innerHTML || "" : document.toString();
147158
}
148159

160+
export function removeElementFromHtml(source: string, target: SourceMutationTarget): string {
161+
return removeElementsFromHtml(source, [target]);
162+
}
163+
149164
export function isHTMLElement(el: Node): el is HTMLElement {
150165
const HTMLEl = el.ownerDocument?.defaultView?.HTMLElement;
151166
return HTMLEl ? el instanceof HTMLEl : el.nodeType === 1 && "style" in el;
@@ -296,11 +311,21 @@ export function patchElementInHtml(
296311
return { html: ensureHfIds(html), matched: true };
297312
}
298313

299-
export function probeElementInSource(source: string, target: SourceMutationTarget): boolean {
300-
if (!target.id && !target.hfId && !target.selector) return false;
314+
/** Whether each target exists in `source`; the document is parsed once however many targets ask. */
315+
export function probeElementsInSource(
316+
source: string,
317+
targets: readonly SourceMutationTarget[],
318+
): boolean[] {
301319
const { document } = parseSourceDocument(source);
302-
const el = findTargetElement(document, target);
303-
return el != null && isHTMLElement(el);
320+
return targets.map((target) => {
321+
if (!target.id && !target.hfId && !target.selector) return false;
322+
const el = findTargetElement(document, target);
323+
return el != null && isHTMLElement(el);
324+
});
325+
}
326+
327+
export function probeElementInSource(source: string, target: SourceMutationTarget): boolean {
328+
return probeElementsInSource(source, [target])[0] ?? false;
304329
}
305330

306331
export interface SplitElementResult {

‎packages/studio-server/src/helpers/subComposition.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,10 @@ function tagRootCompositionFile(bodyHtml: string, compPath: string): string {
236236
);
237237
}
238238

239+
export function rootHeadContent(rootHtml: string): string {
240+
return rootHtml.match(/<head[^>]*>([\s\S]*?)<\/head>/i)?.[1] ?? "";
241+
}
242+
239243
/**
240244
* Build a standalone HTML page for a sub-composition.
241245
*
@@ -318,11 +322,7 @@ export function buildSubCompositionHtml(
318322
const indexPath = join(projectDir, "index.html");
319323
let headContent = "";
320324

321-
if (existsSync(indexPath)) {
322-
const indexHtml = readFileSync(indexPath, "utf-8");
323-
const headMatch = indexHtml.match(/<head[^>]*>([\s\S]*?)<\/head>/i);
324-
headContent = headMatch?.[1] ?? "";
325-
}
325+
if (existsSync(indexPath)) headContent = rootHeadContent(readFileSync(indexPath, "utf-8"));
326326

327327
// Inject <base> for relative asset resolution (before other tags)
328328
if (baseHref && !hasBaseElement(headContent)) {

‎packages/studio-server/src/routes/files.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,6 +1358,30 @@ describe("registerFileRoutes", () => {
13581358
expect(payload.animations[0].targetSelector).toBe(".kicker");
13591359
});
13601360

1361+
it("answers a revalidating read of an unchanged composition with a 304, and a changed one in full", async () => {
1362+
const projectDir = createProjectDir();
1363+
writeComp(projectDir, "scene.html", TEMPLATE_COMP);
1364+
const app = new Hono();
1365+
registerFileRoutes(app, createAdapter(projectDir));
1366+
const url = "http://localhost/projects/demo/gsap-animations/compositions/scene.html";
1367+
1368+
const first = await app.request(url);
1369+
const etag = first.headers.get("ETag");
1370+
expect(etag).toBeTruthy();
1371+
1372+
const unchanged = await app.request(url, { headers: { "If-None-Match": etag ?? "" } });
1373+
expect(unchanged.status).toBe(304);
1374+
1375+
writeComp(
1376+
projectDir,
1377+
"scene.html",
1378+
TEMPLATE_COMP.replace("</template>", "<!-- edited --></template>"),
1379+
);
1380+
const changed = await app.request(url, { headers: { "If-None-Match": etag ?? "" } });
1381+
expect(changed.status).toBe(200);
1382+
expect(changed.headers.get("ETag")).not.toBe(etag);
1383+
});
1384+
13611385
// A composition with a fromTo tween — used by the fromProperties mutation tests.
13621386
const FROMTO_COMP = `<!DOCTYPE html><html><body data-duration="3">
13631387
<div id="box" data-start="0" data-duration="3" style="opacity:0"></div>

0 commit comments

Comments
 (0)