Skip to content

Write HTML. Render video. Built for agents.

feat(cli): warn when canvas content touches the frame edge (#4427)

Miguel Ángel7556b95ac6ab
diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js
index b3683bcfd5..bb5d917453 100644
--- a/packages/cli/src/commands/layout-audit.browser.js
+++ b/packages/cli/src/commands/layout-audit.browser.js
@@ -1274,6 +1274,121 @@
return issues;
}
+ // Pixels drawn into a <canvas> have no DOM box, so text the frame edge cuts is invisible to
+ // canvas_overflow. Read a thin band just inside each covered frame edge and count sharp steps.
+ const CANVAS_EDGE_STEP = 96;
+ const CANVAS_EDGE_MIN_STEPS = 2;
+ // Monospace and bitmap glyph cells end in a gap, so the outermost column alone can read empty.
+ const CANVAS_EDGE_BAND_PX = 4;
+
+ function coveredFrameEdges(rect, rootRect, tolerance) {
+ const top = Math.max(rect.top, rootRect.top);
+ const bottom = Math.min(rect.bottom, rootRect.bottom);
+ const left = Math.max(rect.left, rootRect.left);
+ const right = Math.min(rect.right, rootRect.right);
+ if (bottom - top < CANVAS_EDGE_BAND_PX || right - left < CANVAS_EDGE_BAND_PX) return [];
+ const band = CANVAS_EDGE_BAND_PX;
+ const rows = { y: top, height: bottom - top, width: band, vertical: true };
+ const cols = { x: left, width: right - left, height: band, vertical: false };
+ const edges = [];
+ if (rect.left <= rootRect.left + tolerance) edges.push({ side: "left", x: left, ...rows });
+ if (rect.right >= rootRect.right - tolerance)
+ edges.push({ side: "right", x: right - band, ...rows });
+ if (rect.top <= rootRect.top + tolerance) edges.push({ side: "top", y: top, ...cols });
+ if (rect.bottom >= rootRect.bottom - tolerance)
+ edges.push({ side: "bottom", y: bottom - band, ...cols });
+ return edges;
+ }
+
+ // Draw the band into a scratch canvas (never getContext on the film's own canvas, which would
+ // claim it as 2D). A WebGL canvas without preserveDrawingBuffer reads blank: no finding.
+ function canvasEdgeBand(canvas, rect, edge) {
+ const scaleX = canvas.width / rect.width;
+ const scaleY = canvas.height / rect.height;
+ const off = document.createElement("canvas");
+ off.width = Math.max(1, Math.round(edge.width * scaleX));
+ off.height = Math.max(1, Math.round(edge.height * scaleY));
+ const ctx = off.getContext("2d");
+ if (!ctx) return null;
+ const sx = Math.max(0, Math.floor((edge.x - rect.left) * scaleX));
+ const sy = Math.max(0, Math.floor((edge.y - rect.top) * scaleY));
+ ctx.drawImage(canvas, sx, sy, off.width, off.height, 0, 0, off.width, off.height);
+ return {
+ data: ctx.getImageData(0, 0, off.width, off.height).data,
+ width: off.width,
+ height: off.height,
+ };
+ }
+
+ // Collapse the band across its thickness (brightest wins), then count steps along the edge:
+ // luma over black plus alpha, compared two pixels back so anti-aliased glyph edges still step.
+ function sharpSteps(band, vertical) {
+ const length = vertical ? band.height : band.width;
+ const thickness = vertical ? band.width : band.height;
+ const levels = [];
+ for (let along = 0; along < length; along++) {
+ let luma = 0;
+ let alpha = 0;
+ for (let across = 0; across < thickness; across++) {
+ const i = 4 * (vertical ? along * band.width + across : across * band.width + along);
+ const a = band.data[i + 3];
+ const l =
+ (0.299 * band.data[i] + 0.587 * band.data[i + 1] + 0.114 * band.data[i + 2]) * (a / 255);
+ luma = Math.max(luma, l);
+ alpha = Math.max(alpha, a);
+ }
+ levels.push([luma, alpha]);
+ }
+ let steps = 0;
+ for (let i = 2; i < levels.length; i++) {
+ const [luma, alpha] = levels[i];
+ const [backLuma, backAlpha] = levels[i - 2];
+ if (Math.max(Math.abs(luma - backLuma), Math.abs(alpha - backAlpha)) < CANVAS_EDGE_STEP)
+ continue;
+ steps++;
+ i += 2;
+ }
+ return steps;
+ }
+
+ function canvasEdgeHasContent(canvas, rect, edge) {
+ try {
+ const band = canvasEdgeBand(canvas, rect, edge);
+ return !!band && sharpSteps(band, edge.vertical) >= CANVAS_EDGE_MIN_STEPS;
+ } catch {
+ return false;
+ }
+ }
+
+ // ponytail: maps through the bounding box, exact for scale and translate; a rotated or skewed
+ // canvas reads the wrong pixels. Add a matrix inverse if that bites.
+ function canvasEdgeIssues(root, rootRect, time, tolerance) {
+ const issues = [];
+ for (const canvas of Array.from(root.querySelectorAll("canvas"))) {
+ if (!isVisibleElement(canvas) || hasAllowOverflowFlag(canvas)) continue;
+ if (!canvas.width || !canvas.height) continue;
+ const rect = toRect(canvas.getBoundingClientRect());
+ if (!rect.width || !rect.height) continue;
+ const sides = coveredFrameEdges(rect, rootRect, tolerance)
+ .filter((edge) => canvasEdgeHasContent(canvas, rect, edge))
+ .map((edge) => edge.side);
+ if (sides.length === 0) continue;
+ issues.push({
+ code: "canvas_content_at_edge",
+ severity: "warning",
+ time,
+ selector: selectorFor(canvas),
+ containerSelector: selectorFor(root),
+ message: `Canvas content touches the frame edge (${sides.join(", ")}).`,
+ rect,
+ containerRect: rootRect,
+ fixHint:
+ "Keep drawn text inside the visible part of the canvas, or mark intentional full-bleed art with data-layout-allow-overflow.",
+ });
+ }
+ return issues;
+ }
+
// Soft prior only — the counterfactual attach test (below) is what makes detachment a finding.
const CONNECTOR_NAME = /\b(conn(ector)?|arrow|edge|link|flow|wire)\b/i;
const CONNECTOR_SKIP_CONTAINERS = "defs, marker, clipPath, mask, symbol, pattern";
@@ -1646,6 +1761,7 @@
const escaped = escapedContainerIssues(root, time);
issues.push(...escaped.issues);
issues.push(...panelOutOfCanvasIssues(root, rootRect, time, tolerance, escaped.flagged));
+ issues.push(...canvasEdgeIssues(root, rootRect, time, tolerance));
issues.push(...connectorDetachmentIssues(root, rootRect, time));
issues.push(...connectorOrphanIssues(root, rootRect, time));
return issues;
diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts
index 0a11d2f7fa..2a0a2fd86e 100644
--- a/packages/cli/src/commands/layout-audit.browser.test.ts
+++ b/packages/cli/src/commands/layout-audit.browser.test.ts
@@ -1098,6 +1098,119 @@ describe("layout-audit.browser coordinate-frame findings", () => {
expect(issues.find((issue) => issue.selector === "#bleed")).toMatchObject({ severity: "info" });
});
+ describe("canvas_content_at_edge", () => {
+ // One grey RGBA pixel per entry: a 1px-thick band, read the same along every edge.
+ function edgeLine(levels: number[]): Uint8ClampedArray {
+ return new Uint8ClampedArray(levels.flatMap((level) => [level, level, level, 255]));
+ }
+
+ // Serves any requested band: the pattern runs along the edge (padded with its last pixel),
+ // painted into every column of the band's thickness, or only `inkAcross` when given.
+ // `inkAt(sx, sy)` limits the ink to the band drawn from that source origin.
+ function stubEdgeReads(
+ line: Uint8ClampedArray,
+ inkAcross?: number,
+ inkAt?: (sx: number, sy: number) => boolean,
+ ): ReturnType<typeof vi.fn> {
+ let origin: [number, number] = [0, 0];
+ const drawImage = vi.fn((_source: unknown, sx: number, sy: number) => {
+ origin = [sx, sy];
+ });
+ const pixels = line.length / 4;
+ const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
+ mockReturnValue(value: CanvasRenderingContext2D): void;
+ };
+ getContextSpy.mockReturnValue({
+ drawImage,
+ getImageData: (_x: number, _y: number, width: number, height: number) => {
+ const vertical = height >= width;
+ const data = new Uint8ClampedArray(width * height * 4);
+ if (inkAt && !inkAt(...origin)) return { data };
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const along = vertical ? y : x;
+ const across = vertical ? x : y;
+ if (inkAcross !== undefined && across !== inkAcross) continue;
+ const source = 4 * Math.min(along, pixels - 1);
+ data.set(line.subarray(source, source + 4), 4 * (y * width + x));
+ }
+ }
+ return { data };
+ },
+ } as unknown as CanvasRenderingContext2D);
+ return drawImage;
+ }
+
+ function mountCanvas(canvasRect: DOMRect, attributes = ""): void {
+ document.body.innerHTML = `
+ <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
+ <canvas id="art" width="1920" height="1080" ${attributes}></canvas>
+ </div>
+ `;
+ installGeometry({
+ root: rect({ left: 0, top: 0, width: 1920, height: 1080 }),
+ art: canvasRect,
+ });
+ installAuditScript();
+ }
+
+ const FULL_FRAME = rect({ left: 0, top: 0, width: 1920, height: 1080 });
+ // Dark ground crossed by two glyph strokes, as a headline cut by the frame edge reads.
+ const CUT_TEXT = edgeLine([0, 0, 0, 0, 200, 200, 200, 0, 0, 0, 220, 220, 0, 0, 0, 0]);
+
+ it("warns when drawn text crosses the frame edge", () => {
+ stubEdgeReads(CUT_TEXT);
+ mountCanvas(FULL_FRAME);
+
+ const issues = runAudit().filter((issue) => issue.code === "canvas_content_at_edge");
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ selector: "#art",
+ message: "Canvas content touches the frame edge (left, right, top, bottom).",
+ });
+ expect(issues[0]?.fixHint).toContain("data-layout-allow-overflow");
+ });
+
+ it("sees text whose glyph cell ends in a gap at the outermost pixel column", () => {
+ stubEdgeReads(CUT_TEXT, 1);
+ mountCanvas(FULL_FRAME);
+
+ expect(runAudit().some((issue) => issue.code === "canvas_content_at_edge")).toBe(true);
+ });
+
+ it("names only the edge whose band holds the content", () => {
+ stubEdgeReads(CUT_TEXT, undefined, (sx, sy) => sx === 1916 && sy === 0);
+ mountCanvas(FULL_FRAME);
+
+ const issues = runAudit().filter((issue) => issue.code === "canvas_content_at_edge");
+ expect(issues.map((issue) => issue.message)).toEqual([
+ "Canvas content touches the frame edge (right).",
+ ]);
+ });
+
+ it("stays silent on a full-bleed gradient", () => {
+ stubEdgeReads(edgeLine(Array.from({ length: 256 }, (_, index) => index)));
+ mountCanvas(FULL_FRAME);
+
+ expect(runAudit().some((issue) => issue.code === "canvas_content_at_edge")).toBe(false);
+ });
+
+ it("stays silent under data-layout-allow-overflow", () => {
+ stubEdgeReads(CUT_TEXT);
+ mountCanvas(FULL_FRAME, "data-layout-allow-overflow");
+
+ expect(runAudit().some((issue) => issue.code === "canvas_content_at_edge")).toBe(false);
+ });
+
+ it("never reads a canvas that sits inside the frame", () => {
+ const drawImage = stubEdgeReads(CUT_TEXT);
+ mountCanvas(rect({ left: 200, top: 200, width: 800, height: 450 }));
+
+ expect(runAudit().some((issue) => issue.code === "canvas_content_at_edge")).toBe(false);
+ expect(drawImage).not.toHaveBeenCalled();
+ });
+ });
+
it("flags a gradient-content hero but not an all-translucent gradient glow", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="1920" data-height="1080">
diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts
index f5c00ec52a..57f5402886 100644
--- a/packages/cli/src/utils/checkBrowser.ts
+++ b/packages/cli/src/utils/checkBrowser.ts
@@ -1225,6 +1225,7 @@ const LAYOUT_ISSUE_CODES: readonly LayoutIssueCode[] = [
"frame_out_of_frame",
"escaped_container",
"panel_out_of_canvas",
+ "canvas_content_at_edge",
"connector_detached",
"connector_orphan",
"rotation_pivot_drift",
diff --git a/packages/cli/src/utils/layoutAudit.ts b/packages/cli/src/utils/layoutAudit.ts
index cc498f09e7..10f4cfef94 100644
--- a/packages/cli/src/utils/layoutAudit.ts
+++ b/packages/cli/src/utils/layoutAudit.ts
@@ -22,6 +22,7 @@ export type LayoutIssueCode =
// Coordinate-frame findings — geometry computed in one frame, rendered in another.
| "escaped_container"
| "panel_out_of_canvas"
+ | "canvas_content_at_edge"
| "connector_detached"
| "connector_orphan"
// Cross-sample rotation finding — a spinning element whose bbox center drifts
@@ -203,6 +204,7 @@ const PERSISTENCE_TIERED_CODES: ReadonlySet<LayoutIssueCode> = new Set([
"text_occluded",
"escaped_container",
"panel_out_of_canvas",
+ "canvas_content_at_edge",
"connector_detached",
"connector_orphan",
]);
diff --git a/skills-manifest.json b/skills-manifest.json
index 4a233a2d18..b87d31b397 100644
--- a/skills-manifest.json
+++ b/skills-manifest.json
@@ -30,7 +30,7 @@
"files": 7
},
"hyperframes-cli": {
- "hash": "385f979b840b0eb9",
+ "hash": "d994bb25706982ee",
"files": 11
},
"hyperframes-core": {
diff --git a/skills/hyperframes-cli/references/lint-validate-inspect.md b/skills/hyperframes-cli/references/lint-validate-inspect.md
index 73308c6910..fb814d67f0 100644
--- a/skills/hyperframes-cli/references/lint-validate-inspect.md
+++ b/skills/hyperframes-cli/references/lint-validate-inspect.md
@@ -50,7 +50,7 @@ One command, one Chrome boot. `check` runs the linter first and skips the browse
Every finding carries a selector, the element's `data-*` identity, the composition source file, a bbox, and the sample time: jump straight from the JSON to the HTML you must edit and re-run.
-**Severity is persistence-aware.** A dynamic issue observed at a single grid sample (an entrance/exit transient) demotes to info and never gates. Issues held across samples gate the exit code, a held `content_overlap` is an error, and a held, partially-visible `canvas_overflow` breaching ≥5% of the canvas promotes to warning. Coordinate-frame findings (`escaped_container`, `panel_out_of_canvas`, `connector_detached`) flag geometry computed in one frame but rendered in another — an element far outside its offset parent, a painted panel stuck across the canvas edge, a connector line detached from every node. If a 3s+ composition shows zero geometry change across every sample, `check` fails with `sweep_static`: a frozen timeline makes every green verdict unreliable, so it refuses to pass. The fingerprint includes per-element opacity, so opacity-only reveals (code typing, staggered fades) count as motion — but only while they're still in flight at the sampled times. The classic trap is a reveal that completes early and then holds a static frame for the rest of the duration: every sample lands on the settled state and the run fails. Spread the reveal across the timeline or keep one continuously animated element alive (a blinking caret is idiomatic for code typing) — don't bolt on a slow position drift just to appease the check.
+**Severity is persistence-aware.** A dynamic issue observed at a single grid sample (an entrance/exit transient) demotes to info and never gates. Issues held across samples gate the exit code, a held `content_overlap` is an error, and a held, partially-visible `canvas_overflow` breaching ≥5% of the canvas promotes to warning. Coordinate-frame findings (`escaped_container`, `panel_out_of_canvas`, `connector_detached`) flag geometry computed in one frame but rendered in another — an element far outside its offset parent, a painted panel stuck across the canvas edge, a connector line detached from every node. Text drawn into a `<canvas>` has no DOM box, so `canvas_overflow` cannot see it; `canvas_content_at_edge` warns when a canvas's pixels show sharp content (drawn text, hard shapes) along the frame edge — mark intentional full-bleed art (particles, photos) with `data-layout-allow-overflow`. If a 3s+ composition shows zero geometry change across every sample, `check` fails with `sweep_static`: a frozen timeline makes every green verdict unreliable, so it refuses to pass. The fingerprint includes per-element opacity, so opacity-only reveals (code typing, staggered fades) count as motion — but only while they're still in flight at the sampled times. The classic trap is a reveal that completes early and then holds a static frame for the rest of the duration: every sample lands on the settled state and the run fails. Spread the reveal across the timeline or keep one continuously animated element alive (a blinking caret is idiomatic for code typing) — don't bolt on a slow position drift just to appease the check.
**Escape hatches** (mark intent in the HTML, then re-run):