Skip to content

Commit fa9f170

Browse files
feat(lint): warn when a 3D-transformed element is far larger than the stage (#8945)
1 parent d8a2f50 commit fa9f170

4 files changed

Lines changed: 161 additions & 0 deletions

File tree

‎docs/reference/lint-rules.mdx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,12 @@ stylesheet links in `<head>`, so those styles never apply in preview, snapshot o
224224

225225
**Fix:** Use hardcoded string selectors instead of interpolated ones.
226226

227+
### `three_d_layer_far_larger_than_stage`
228+
229+
**Warning.** An element with a 3D transform (`rotateX`, `rotateY`, `translateZ`, `perspective()` and similar) is more than 4 times the stage area. A 3D-transformed layer is drawn nearly whole, not only the part on stage, so it holds GPU memory for pixels nobody sees, and in an editor's preview it can blank the editor's own panels.
230+
231+
**Fix:** Size the element to what the camera can see, or use a repeating background on a stage-sized element.
232+
227233
### `timed_element_missing_clip_class`
228234

229235
**Warning.** An element has timing attributes but no `class="clip"`. The runtime still times it, but the browser editor and the clip-ownership rules use `.clip` to recognise it, so it is harder to edit and to lint.

‎packages/lint/src/hyperframeLinter.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { slideshowRules } from "./rules/slideshow";
2222
import { structureRules } from "./rules/structure";
2323
import { shaderRules } from "./rules/shaders";
2424
import { rootPathRules } from "./rules/rootPaths";
25+
import { layerRules } from "./rules/layers";
2526

2627
// Rules are grouped by source module so a timing can be attributed to
2728
// something a human can act on. Individual rules stay anonymous: an
@@ -51,6 +52,7 @@ const RULE_GROUPS: ReadonlyArray<{
5152
{ group: "structure", rules: structureRules },
5253
{ group: "shaders", rules: shaderRules },
5354
{ group: "rootPaths", rules: rootPathRules },
55+
{ group: "layers", rules: layerRules },
5456
];
5557

5658
/**
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { describe, expect, it } from "vitest";
2+
import { lintHyperframeHtml } from "../hyperframeLinter.js";
3+
4+
const CODE = "three_d_layer_far_larger_than_stage";
5+
6+
function html(body: string, style = ""): string {
7+
return `<html><body>
8+
<div data-composition-id="main" data-width="1920" data-height="1080">
9+
${body}
10+
</div>
11+
<style>${style}</style>
12+
<script>window.__timelines = window.__timelines || {}; window.__timelines["main"] = gsap.timeline({ paused: true });</script>
13+
</body></html>`;
14+
}
15+
16+
const floor = (w: number, h: number) =>
17+
`#floor{position:absolute;width:${w}px;height:${h}px;transform:translateZ(-1800px) rotateX(90deg)}`;
18+
19+
async function hits(source: string) {
20+
return (await lintHyperframeHtml(source)).findings.filter((f) => f.code === CODE);
21+
}
22+
23+
describe("three_d_layer_far_larger_than_stage", () => {
24+
it("warns on an 11000x5200 rotateX floor in a 1920x1080 composition", async () => {
25+
const found = await hits(html('<div id="floor"></div>', floor(11000, 5200)));
26+
expect(found).toHaveLength(1);
27+
expect(found[0]).toMatchObject({ severity: "warning", selector: "#floor" });
28+
expect(found[0]!.message).toContain("11000x5200px");
29+
expect(found[0]!.message).toContain("28x the 1920x1080 stage");
30+
});
31+
32+
it("is quiet for the same floor at stage size", async () => {
33+
expect(await hits(html('<div id="floor"></div>', floor(1920, 1080)))).toEqual([]);
34+
});
35+
36+
it("is quiet for a large element without a 3D transform", async () => {
37+
const css = "#bg{width:11000px;height:5200px;transform:translateX(-50%) rotate(10deg)}";
38+
expect(await hits(html('<div id="bg"></div>', css))).toEqual([]);
39+
});
40+
41+
it("warns on an inline style", async () => {
42+
const tag = '<div id="wall" style="width:9000px;height:9000px;transform:rotateY(40deg)"></div>';
43+
const found = await hits(html(tag));
44+
expect(found).toHaveLength(1);
45+
expect(found[0]).toMatchObject({ elementId: "wall" });
46+
});
47+
});

‎packages/lint/src/rules/layers.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import postcss from "postcss";
2+
import { styleRoot } from "../styleRoots";
3+
import type { LintContext, HyperframeLintFinding } from "../context";
4+
import { readAttr, readJsonAttr, truncateSnippet } from "../utils";
5+
6+
// A 3D-transformed layer is rasterized close to whole, not clipped to the stage. Measured in a 1920x1080 preview: an
7+
// 11000x5200 rotateX floor took layer area from 32 to 87 Mpx and the host app's own panels went blank.
8+
const MAX_STAGE_MULTIPLE = 4;
9+
// translate3d is left out: flat 3D translates are the usual promote-to-layer hack and keep 2D clipping.
10+
const THREE_D_TRANSFORM =
11+
/\b(?:rotate[XY]|rotate3d|translateZ|scaleZ|scale3d|matrix3d|perspective)\s*\(/i;
12+
13+
type Box = { width?: number; height?: number; transform?: string };
14+
type Stage = { width: number; height: number };
15+
16+
function pixels(value: string): number | undefined {
17+
const match = /^\s*(\d+(?:\.\d+)?)px\s*$/i.exec(value);
18+
return match ? Number(match[1]) : undefined;
19+
}
20+
21+
function boxOf(container: postcss.Container): Box {
22+
const box: Box = {};
23+
container.each((node) => {
24+
if (node.type !== "decl") return;
25+
const prop = node.prop.toLowerCase();
26+
if (prop === "width") box.width = pixels(node.value);
27+
else if (prop === "height") box.height = pixels(node.value);
28+
else if (prop === "transform") box.transform = node.value;
29+
});
30+
return box;
31+
}
32+
33+
function oversizedArea(box: Box, stage: Stage): boolean {
34+
if (!box.width || !box.height || !box.transform || !THREE_D_TRANSFORM.test(box.transform))
35+
return false;
36+
return box.width * box.height > stage.width * stage.height * MAX_STAGE_MULTIPLE;
37+
}
38+
39+
function finding(
40+
box: Box,
41+
stage: Stage,
42+
where: Partial<HyperframeLintFinding>,
43+
): HyperframeLintFinding {
44+
const ratio = Math.round(((box.width ?? 0) * (box.height ?? 0)) / (stage.width * stage.height));
45+
return {
46+
code: "three_d_layer_far_larger_than_stage",
47+
severity: "warning",
48+
message:
49+
`A ${box.width}x${box.height}px element with a 3D transform is ${ratio}x the ${stage.width}x${stage.height} stage. ` +
50+
`A 3D-transformed layer is drawn nearly whole, not just the part on stage, so it holds GPU memory for pixels ` +
51+
`nobody sees. In an editor's preview that can blank the editor's own panels.`,
52+
fixHint: `Size it to what the camera can see (at most ${MAX_STAGE_MULTIPLE}x the stage), or use a repeating background on a stage-sized element.`,
53+
...where,
54+
};
55+
}
56+
57+
function stageOf(rootTag: LintContext["rootTag"]): Stage | undefined {
58+
const width = Number.parseInt(readAttr(rootTag?.raw ?? "", "data-width") ?? "", 10);
59+
const height = Number.parseInt(readAttr(rootTag?.raw ?? "", "data-height") ?? "", 10);
60+
return width > 0 && height > 0 ? { width, height } : undefined;
61+
}
62+
63+
function parsed(read: () => postcss.Root): postcss.Root | undefined {
64+
try {
65+
return read();
66+
} catch {
67+
return undefined;
68+
}
69+
}
70+
71+
function styleBlockFindings(styles: LintContext["styles"], stage: Stage): HyperframeLintFinding[] {
72+
const findings: HyperframeLintFinding[] = [];
73+
for (const style of styles) {
74+
parsed(() => styleRoot(style))?.walkRules((rule) => {
75+
const box = boxOf(rule);
76+
if (oversizedArea(box, stage))
77+
findings.push(finding(box, stage, { selector: rule.selector }));
78+
});
79+
}
80+
return findings;
81+
}
82+
83+
function inlineStyleFindings(tags: LintContext["tags"], stage: Stage): HyperframeLintFinding[] {
84+
const findings: HyperframeLintFinding[] = [];
85+
for (const tag of tags) {
86+
const inline = readJsonAttr(tag.raw, "style");
87+
if (!inline || !THREE_D_TRANSFORM.test(inline)) continue;
88+
const root = parsed(() => postcss.parse(inline));
89+
const box = root ? boxOf(root) : {};
90+
if (!oversizedArea(box, stage)) continue;
91+
const where = {
92+
elementId: readAttr(tag.raw, "id") || undefined,
93+
snippet: truncateSnippet(tag.raw),
94+
};
95+
findings.push(finding(box, stage, where));
96+
}
97+
return findings;
98+
}
99+
100+
export const layerRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
101+
({ rootTag, tags, styles }) => {
102+
const stage = stageOf(rootTag);
103+
if (!stage) return [];
104+
return [...styleBlockFindings(styles, stage), ...inlineStyleFindings(tags, stage)];
105+
},
106+
];

0 commit comments

Comments
 (0)