Skip to content

Commit d4756f5

Browse files
fix(studio): edits on GSAP-animated layers keep their keyframes and file positions (#4869)
* fix(studio): resizing an element GSAP only positions saves its CSS width and height * fix(studio): a resize never saves GSAP's scale mask as the element's CSS * fix(studio): keep the resize size writer inside the file and comment budgets * fix(studio): a GSAP-positioned resize saves its CSS size before the GSAP write renders * fix(studio): undoing a crop leaves a GSAP-animated layer where its file puts it * test(studio): an undo on a GSAP-parsed layer in a two-script file reloads the preview * fix(studio): a move keeps an authored xPercent centring set in the saved file * fix(studio): a drag on a centred element no longer flashes off-centre on release * fix(studio): a font pick saves the edit and its @font-face in one write * fix(studio): a focused combobox, switch or plain-text editor counts as an unsaved edit * test(scripts): pin that a slash after i-- before a quoted slash is division * fix(studio): an inspector edit saved while a preview reload loads stays on screen * fix(studio-server): a font save accepts exactly one @font-face rule and nothing after it * fix(studio-server): a font name or path with braces in quotes still saves its @font-face * fix(studio-server): a CR or form feed in a quoted font name cannot end the @font-face rule * test(studio): bank the 99 edit accuracy cases the GSAP fixes now pass
1 parent 37f30b1 commit d4756f5

43 files changed

Lines changed: 1746 additions & 1228 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/parsers/src/gsapConstants.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
* without pulling in gsapParser (which depends on recast / @babel/parser).
66
*/
77

8+
import type { GsapAnimation } from "./gsapSerialize.js";
9+
810
export const SUPPORTED_PROPS = [
911
// 2D Transforms
1012
"x",
@@ -69,6 +71,22 @@ for (const [group, props] of Object.entries(PROPERTY_GROUPS) as [
6971
for (const p of props) PROP_TO_GROUP.set(p, group);
7072
}
7173

74+
type PositionWrite = Pick<
75+
GsapAnimation,
76+
"propertyGroup" | "properties" | "fromProperties" | "keyframes"
77+
>;
78+
79+
/** A position write that sets x or y. An xPercent/yPercent centring set never duplicates one. */
80+
export function isXYPositionWrite(a: PositionWrite): boolean {
81+
const xy = (props?: Record<string, unknown>) => !!props && ("x" in props || "y" in props);
82+
return (
83+
a.propertyGroup === "position" &&
84+
(xy(a.properties) ||
85+
xy(a.fromProperties) ||
86+
!!a.keyframes?.keyframes.some((k) => xy(k.properties)))
87+
);
88+
}
89+
7290
export function classifyPropertyGroup(prop: string): PropertyGroupName {
7391
return PROP_TO_GROUP.get(prop) ?? "other";
7492
}

‎packages/parsers/src/gsapParser.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ export {
4949
classifyPropertyGroup,
5050
classifyTweenPropertyGroup,
5151
} from "./gsapConstants";
52-
import { classifyPropertyGroup, classifyTweenPropertyGroup } from "./gsapConstants";
52+
import {
53+
classifyPropertyGroup,
54+
classifyTweenPropertyGroup,
55+
isXYPositionWrite,
56+
} from "./gsapConstants";
5357
import type { PropertyGroupName } from "./gsapConstants";
5458
import { clipTweenMatcher, hasExplicitTime } from "./clipTweens";
5559
import {
@@ -1790,8 +1794,8 @@ function removeCallFromAst(call: TweenCallInfo): void {
17901794
/**
17911795
* Recast twin of {@link dedupePositionWritesInScript} (acorn). Enforce "exactly
17921796
* one position write per element": keep `keepId` (or the LAST position write in
1793-
* source order if stale), remove every OTHER pure-position write
1794-
* (`propertyGroup === "position"` — tl.to/from/fromTo flat-or-keyframed, tl.set,
1797+
* source order if stale), remove every OTHER x/y position write
1798+
* (`isXYPositionWrite` — tl.to/from/fromTo flat-or-keyframed, tl.set,
17951799
* standalone gsap.set, incl. degenerate duration:0 tweens). Non-position writes
17961800
* for the selector are left untouched.
17971801
*/
@@ -1807,7 +1811,7 @@ export function dedupePositionWritesInScript(
18071811
return script;
18081812
}
18091813
const posWrites = parsed.located.filter(
1810-
(l) => l.animation.targetSelector === selector && l.animation.propertyGroup === "position",
1814+
(l) => l.animation.targetSelector === selector && isXYPositionWrite(l.animation),
18111815
);
18121816
if (posWrites.length <= 1) return script;
18131817
const keeper = posWrites.find((l) => l.id === keepId) ?? posWrites[posWrites.length - 1]!;

‎packages/parsers/src/gsapWriter.parity.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,17 @@ describe("parity: dedupePositionWritesInScript (recast vs acorn)", () => {
198198
expect(modelOf(acornOut)).toEqual(modelOf(recastOut));
199199
});
200200

201+
it("keeps an xPercent/yPercent centring set beside an x/y tween in both writers", () => {
202+
const centred = `
203+
const tl = gsap.timeline({ paused: true });
204+
gsap.set("#box", { xPercent: -50, yPercent: -50 });
205+
tl.to("#box", { x: 120, y: 60, duration: 4, ease: "none" }, 0);
206+
`;
207+
const keepId = parseGsapScriptAcorn(centred).animations.find((a) => a.method === "to")!.id;
208+
expect(dedupePosAcorn(centred, "#box", keepId)).toBe(centred);
209+
expect(dedupePosRecast(centred, "#box", keepId)).toBe(centred);
210+
});
211+
201212
it("no-op when 0 or 1 position writes — both writers", () => {
202213
const single = `
203214
const tl = gsap.timeline({ paused: true });

‎packages/parsers/src/gsapWriterAcorn.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
type ParsedGsapAcornForWrite,
2525
type TweenCallInfo,
2626
} from "./gsapParserAcorn.js";
27-
import { classifyPropertyGroup } from "./gsapConstants.js";
27+
import { classifyPropertyGroup, isXYPositionWrite } from "./gsapConstants.js";
2828
import type { PropertyGroupName } from "./gsapConstants.js";
2929
import {
3030
findObjectArrayKeyframeIndex,
@@ -686,7 +686,7 @@ export function removeAnimationFromScript(script: string, animationId: string):
686686
*
687687
* Keeps `keepId` (the write the commit just edited); falls back to the LAST
688688
* position write in source order (the runtime-effective one) if `keepId` is stale.
689-
* Removes every OTHER pure-position write (`propertyGroup === "position"`, which
689+
* Removes every OTHER x/y position write (`isXYPositionWrite`, which
690690
* covers tl.to/from/fromTo flat-or-keyframed, tl.set, and standalone gsap.set,
691691
* including degenerate duration:0 tweens). Non-position writes for the same
692692
* selector (rotation / opacity / size / mixed) are left untouched.
@@ -699,7 +699,7 @@ export function dedupePositionWritesInScript(
699699
const parsed = parseGsapScriptAcornForWrite(script);
700700
if (!parsed) return script;
701701
const posWrites = parsed.located.filter(
702-
(l) => l.animation.targetSelector === selector && l.animation.propertyGroup === "position",
702+
(l) => l.animation.targetSelector === selector && isXYPositionWrite(l.animation),
703703
);
704704
if (posWrites.length <= 1) return script;
705705
const keeper = posWrites.find((l) => l.id === keepId) ?? posWrites[posWrites.length - 1]!;
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { describe, expect, it } from "vitest";
2+
import { ensureStudioFontFaceCss, isStudioFontFaceCss } from "./studioFontFace.js";
3+
4+
const bold =
5+
'@font-face { font-family: "Poppins"; src: url("assets/Bold.ttf"); font-weight: 700; font-display: swap; }';
6+
const regular =
7+
'@font-face { font-family: "Poppins"; src: url("assets/Regular.ttf"); font-weight: 400; font-display: swap; }';
8+
9+
describe("ensureStudioFontFaceCss", () => {
10+
it("keeps two weights of one family in one block, and adds each once", () => {
11+
const html = "<html><head></head><body></body></html>";
12+
const saved = ensureStudioFontFaceCss(ensureStudioFontFaceCss(html, bold), regular);
13+
expect(saved.match(/<style data-hf-studio-fonts="true">/g)).toHaveLength(1);
14+
expect(saved).toContain(bold);
15+
expect(saved).toContain(regular);
16+
expect(ensureStudioFontFaceCss(saved, bold)).toBe(saved);
17+
});
18+
19+
it("puts the block in the head, or first when the file has none", () => {
20+
expect(ensureStudioFontFaceCss("<html><head></head><body></body></html>", bold)).toMatch(
21+
/<style data-hf-studio-fonts="true">[\s\S]*<\/style>\s*<\/head>/,
22+
);
23+
expect(ensureStudioFontFaceCss("<div>x</div>", bold).startsWith("<style")).toBe(true);
24+
});
25+
26+
it("saves a file name with a replacement pattern as written", () => {
27+
const html = "<html><head></head><body>rest</body></html>";
28+
const odd =
29+
'@font-face { font-family: "Cash"; src: url("assets/Cash$\'Font.ttf"); font-display: swap; }';
30+
const saved = ensureStudioFontFaceCss(html, odd);
31+
expect(saved).toContain("Cash$'Font.ttf");
32+
expect(saved.match(/<body>/g)).toHaveLength(1);
33+
const again = ensureStudioFontFaceCss(saved, odd.split("Cash$'Font").join("Cash$&"));
34+
expect(again).toContain("Cash$&.ttf");
35+
expect(again.match(/<body>/g)).toHaveLength(1);
36+
});
37+
});
38+
39+
describe("isStudioFontFaceCss", () => {
40+
it("takes one @font-face rule and nothing that could leave the style block", () => {
41+
expect(isStudioFontFaceCss(bold)).toBe(true);
42+
expect(isStudioFontFaceCss("body { color: red }")).toBe(false);
43+
expect(isStudioFontFaceCss(`${bold} body{display:none}`)).toBe(false);
44+
expect(isStudioFontFaceCss(`${bold}\n${regular}`)).toBe(false);
45+
expect(isStudioFontFaceCss('@font-face { src: url("assets/Brand{1}.ttf"); }')).toBe(true);
46+
expect(isStudioFontFaceCss('@font-face { font-family: "x</style><script>"; }')).toBe(false);
47+
expect(isStudioFontFaceCss('@font-face { font-family: "x; } body{display:none}')).toBe(false);
48+
expect(isStudioFontFaceCss('@font-face { font-family: "x\\"; } body{}')).toBe(false);
49+
expect(isStudioFontFaceCss('@font-face { font-family: "x\\""; } body{}')).toBe(false);
50+
expect(isStudioFontFaceCss('@font-face { font-family: "x\r} body{} "; }')).toBe(false);
51+
expect(isStudioFontFaceCss("@font-face { font-family: 'x\\\f} body{} '; }")).toBe(false);
52+
expect(isStudioFontFaceCss('@font-face { src: url("x") } </style><script>')).toBe(false);
53+
expect(isStudioFontFaceCss(42)).toBe(false);
54+
});
55+
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const FONT_STYLE_RE = /<style\b[^>]*data-hf-studio-fonts=(["'])true\1[^>]*>([\s\S]*?)<\/style>/i;
2+
3+
// Braces only inside quoted strings; `<` nowhere: `</style` ends the block whatever the quoting.
4+
const ONE_FONT_FACE_RULE =
5+
/^@font-face \{(?:[^{}<"'\\]|"(?:[^"\\<\n\r\f]|\\[^<\n\r\f])*"|'(?:[^'\\<\n\r\f]|\\[^<\n\r\f])*')*\}$/;
6+
7+
export function isStudioFontFaceCss(css: unknown): css is string {
8+
return typeof css === "string" && ONE_FONT_FACE_RULE.test(css);
9+
}
10+
11+
export function ensureStudioFontFaceCss(html: string, css: string): string {
12+
if (html.includes(css)) return html;
13+
const block = FONT_STYLE_RE.exec(html);
14+
if (block) {
15+
const next = `${(block[2] ?? "").trim()}\n${css}`.trim();
16+
return html.replace(block[0], () => `<style data-hf-studio-fonts="true">\n${next}\n</style>`);
17+
}
18+
const styleTag = `<style data-hf-studio-fonts="true">\n${css}\n</style>`;
19+
if (/<\/head>/i.test(html)) return html.replace(/<\/head>/i, () => ` ${styleTag}\n </head>`);
20+
return `${styleTag}\n${html}`;
21+
}

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,49 @@ describe("registerFileRoutes", () => {
643643
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain("After");
644644
});
645645

646+
it("writes the font an edit uses in the same write as the edit", async () => {
647+
const projectDir = createProjectDir();
648+
const original = '<html><head></head><body><div id="title">Before</div></body></html>';
649+
writeFileSync(join(projectDir, "index.html"), original);
650+
const app = new Hono();
651+
registerFileRoutes(app, createAdapter(projectDir));
652+
const css =
653+
'@font-face { font-family: "Poppins"; src: url("assets/Poppins.ttf"); font-display: swap; }';
654+
const patch = (body: object, target = { id: "title" }) =>
655+
app.request("http://localhost/projects/demo/file-mutations/patch-element/index.html", {
656+
method: "POST",
657+
headers: { "Content-Type": "application/json" },
658+
body: JSON.stringify({
659+
target,
660+
operations: [{ type: "inline-style", property: "font-family", value: "Poppins" }],
661+
...body,
662+
}),
663+
});
664+
665+
expect((await patch({ fontFaceCss: "</style><script>x</script>" })).status).toBe(400);
666+
expect((await patch({ fontFaceCss: `${css} body{display:none}` })).status).toBe(400);
667+
const quotedBreakout = '@font-face { font-family: "x</style><script>"; }';
668+
expect((await patch({ fontFaceCss: quotedBreakout })).status).toBe(400);
669+
for (const newline of ["\r", "\f"]) {
670+
const smuggled = `@font-face { font-family: "x${newline}} body{background:red} "; }`;
671+
expect((await patch({ fontFaceCss: smuggled })).status).toBe(400);
672+
}
673+
expect((await patch({ fontFaceCss: css }, { id: "missing" })).status).toBe(200);
674+
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(original);
675+
676+
const response = await patch({ fontFaceCss: css });
677+
expect(response.status).toBe(200);
678+
const saved = readFileSync(join(projectDir, "index.html"), "utf-8");
679+
expect(saved).toContain("font-family: Poppins");
680+
expect(saved).toContain(css);
681+
expect(((await response.json()) as { content?: string }).content).toBe(saved);
682+
expect(readdirSync(join(projectDir, ".hyperframes", "backup"))).toHaveLength(1);
683+
684+
const braces = '@font-face { font-family: "Brand {1}"; src: url("assets/Brand{1}.ttf"); }';
685+
expect((await patch({ fontFaceCss: braces })).status).toBe(200);
686+
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain(braces);
687+
});
688+
646689
it("fails structured DOM mutations closed when the backup cannot be created", async () => {
647690
const projectDir = createProjectDir();
648691
const original = '<div id="title">Before</div>';

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

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ import {
8989
type PatchOperation,
9090
type ElementRebase,
9191
} from "../helpers/sourceMutation.js";
92+
import { ensureStudioFontFaceCss, isStudioFontFaceCss } from "../helpers/studioFontFace.js";
9293
import { parseHTML } from "linkedom";
9394
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
9495
import {
@@ -2934,11 +2935,16 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
29342935
const parsed = await parseMutationBody<{
29352936
target?: MutationTarget;
29362937
operations?: PatchOperation[];
2938+
fontFaceCss?: unknown;
29372939
}>(c);
29382940
if ("error" in parsed) return parsed.error;
29392941
if (!Array.isArray(parsed.body.operations) || parsed.body.operations.length === 0) {
29402942
return c.json({ error: "target and operations required" }, 400);
29412943
}
2944+
const { fontFaceCss } = parsed.body;
2945+
if (fontFaceCss !== undefined && !isStudioFontFaceCss(fontFaceCss)) {
2946+
return c.json({ error: "fontFaceCss must be one @font-face rule" }, 400);
2947+
}
29422948
const unsafeFields = findUnsafeDomPatchValues(parsed.body);
29432949
if (unsafeFields.length > 0) {
29442950
return rejectUnsafeMutationValues(c, unsafeFields);
@@ -2951,11 +2957,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
29512957
} catch {
29522958
return c.json({ error: "not found" }, 404);
29532959
}
2954-
const { html: patched, matched } = patchElementInHtml(
2955-
originalContent,
2956-
parsed.target,
2957-
parsed.body.operations,
2958-
);
2960+
const element = patchElementInHtml(originalContent, parsed.target, parsed.body.operations);
2961+
const { matched } = element;
2962+
const patched =
2963+
matched && isStudioFontFaceCss(fontFaceCss)
2964+
? ensureStudioFontFaceCss(element.html, fontFaceCss)
2965+
: element.html;
29592966
if (patched === originalContent) {
29602967
const version = fileContentVersion(originalContent);
29612968
c.header("ETag", version);

‎packages/studio/src/components/editor/fontAssets.test.ts‎

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// @vitest-environment jsdom
22
import { expect, it } from "vitest";
3-
import { ensureImportedFontFace, injectPreviewImportedFont } from "../../utils/studioFontHelpers";
3+
import { importedFontFaceCssFor, injectPreviewImportedFont } from "../../utils/studioFontHelpers";
44
import { importedFontFaceCss, type ImportedFontAsset } from "./fontAssets";
55

66
const face = (file: string, extra: Partial<ImportedFontAsset> = {}): ImportedFontAsset => ({
@@ -30,24 +30,25 @@ it("a face says which weight and style it draws, a variable file its weight rang
3030
);
3131
});
3232

33-
it("two weights of one family are both kept in the file and both drawn in the preview", () => {
33+
it("two weights of one family are both drawn in the preview", () => {
3434
const bold = face("Poppins-Bold.ttf", { weight: "700", style: "normal" });
3535
const regular = face("Poppins-Regular.ttf", { weight: "400", style: "normal" });
36-
const html = "<html><head></head><body></body></html>";
37-
const saved = ensureImportedFontFace(
38-
ensureImportedFontFace(html, bold, "index.html"),
39-
regular,
40-
"index.html",
41-
);
42-
expect(saved).toContain("font-weight: 700;");
43-
expect(saved).toContain("font-weight: 400;");
44-
expect(ensureImportedFontFace(saved, bold, "index.html")).toBe(saved);
4536
injectPreviewImportedFont(document, bold);
4637
injectPreviewImportedFont(document, regular);
4738
injectPreviewImportedFont(document, bold);
4839
expect(document.head.querySelectorAll("style")).toHaveLength(2);
4940
});
5041

42+
it("the saved rule points at the font from the file that uses it", () => {
43+
const bold = face("Poppins-Bold.ttf");
44+
expect(importedFontFaceCssFor(bold, "index.html")).toContain(
45+
'url("assets/fonts/Poppins/Poppins-Bold.ttf")',
46+
);
47+
expect(importedFontFaceCssFor(bold, "compositions/intro.html")).toContain(
48+
'url("../assets/fonts/Poppins/Poppins-Bold.ttf")',
49+
);
50+
});
51+
5152
it("a weight the browser would drop is left out, and a family cannot close the style block", () => {
5253
for (const weight of ["0", "5000", "bold", "700;}"])
5354
expect(importedFontFaceCss(face("x.ttf", { weight }))).not.toContain("font-weight");
@@ -56,14 +57,3 @@ it("a weight the browser would drop is left out, and a family cannot close the s
5657
"</style>",
5758
);
5859
});
59-
60-
it("a file name with a replacement pattern is saved as written, not expanded into the page", () => {
61-
const html = "<html><head></head><body>rest</body></html>";
62-
const odd = { family: "Cash", path: "assets/Cash$'Font.ttf", url: "/Cash$'Font.ttf" };
63-
const saved = ensureImportedFontFace(html, odd, "index.html");
64-
expect(saved).toContain("Cash$'Font.ttf");
65-
expect(saved.match(/<body>/g)).toHaveLength(1);
66-
const again = ensureImportedFontFace(saved, { ...odd, path: "assets/Cash$&.ttf" }, "index.html");
67-
expect(again).toContain("Cash$&.ttf");
68-
expect(again.match(/<body>/g)).toHaveLength(1);
69-
});

‎packages/studio/src/components/editor/gsapAnimatesProperty.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
export const gsapRendersTransform = (el: Element) =>
2+
!!(el as { _gsap?: { renderTransform?: unknown } })._gsap?.renderTransform;
3+
14
/**
25
* Checks whether GSAP actively animates one or more CSS/GSAP properties on
36
* the given element by inspecting all registered `__timelines`.

0 commit comments

Comments
 (0)