framesheet 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +212 -2
  3. package/dist/analysis.d.ts +84 -0
  4. package/dist/analysis.d.ts.map +1 -0
  5. package/dist/analysis.js +335 -0
  6. package/dist/analysis.js.map +1 -0
  7. package/dist/checks.d.ts +44 -0
  8. package/dist/checks.d.ts.map +1 -0
  9. package/dist/checks.js +200 -0
  10. package/dist/checks.js.map +1 -0
  11. package/dist/compose.d.ts +117 -0
  12. package/dist/compose.d.ts.map +1 -0
  13. package/dist/compose.js +236 -0
  14. package/dist/compose.js.map +1 -0
  15. package/dist/driver.d.ts +56 -0
  16. package/dist/driver.d.ts.map +1 -0
  17. package/dist/driver.js +94 -0
  18. package/dist/driver.js.map +1 -0
  19. package/dist/generated/assets.d.ts +9 -0
  20. package/dist/generated/assets.d.ts.map +1 -0
  21. package/dist/generated/assets.js +11 -0
  22. package/dist/generated/assets.js.map +1 -0
  23. package/dist/index.d.ts +15 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +14 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/inspect.d.ts +150 -0
  28. package/dist/inspect.d.ts.map +1 -0
  29. package/dist/inspect.js +570 -0
  30. package/dist/inspect.js.map +1 -0
  31. package/dist/models.d.ts +117 -0
  32. package/dist/models.d.ts.map +1 -0
  33. package/dist/models.js +9 -0
  34. package/dist/models.js.map +1 -0
  35. package/dist/pixels.d.ts +46 -0
  36. package/dist/pixels.d.ts.map +1 -0
  37. package/dist/pixels.js +237 -0
  38. package/dist/pixels.js.map +1 -0
  39. package/dist/pyfmt.d.ts +16 -0
  40. package/dist/pyfmt.d.ts.map +1 -0
  41. package/dist/pyfmt.js +54 -0
  42. package/dist/pyfmt.js.map +1 -0
  43. package/dist/report.schema.json +754 -0
  44. package/dist/sources.d.ts +32 -0
  45. package/dist/sources.d.ts.map +1 -0
  46. package/dist/sources.js +123 -0
  47. package/dist/sources.js.map +1 -0
  48. package/dist/test.d.ts +46 -0
  49. package/dist/test.d.ts.map +1 -0
  50. package/dist/test.js +58 -0
  51. package/dist/test.js.map +1 -0
  52. package/dist/timing.d.ts +30 -0
  53. package/dist/timing.d.ts.map +1 -0
  54. package/dist/timing.js +128 -0
  55. package/dist/timing.js.map +1 -0
  56. package/package.json +78 -4
  57. package/src/analysis.ts +416 -0
  58. package/src/checks.ts +261 -0
  59. package/src/compose.ts +303 -0
  60. package/src/driver.ts +115 -0
  61. package/src/generated/assets.ts +14 -0
  62. package/src/index.ts +44 -0
  63. package/src/inspect.ts +690 -0
  64. package/src/models.ts +130 -0
  65. package/src/pixels.ts +248 -0
  66. package/src/pyfmt.ts +55 -0
  67. package/src/sources.ts +131 -0
  68. package/src/test.ts +100 -0
  69. package/src/timing.ts +133 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Philipp Temminghoff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md CHANGED
@@ -1,3 +1,213 @@
1
- # Temporary Holding Version
1
+ # framesheet (npm)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Frame-accurate contact sheets, motion heatmaps and checks for animated SVG/HTML, and for
4
+ animated components in a running web app. TypeScript port of the Python package
5
+ [`framesheet`](https://pypi.org/project/framesheet/): same in-page time control
6
+ (`runtime.js`, shared byte for byte), same report schema, same image layout. Use it in a
7
+ Playwright e2e suite for visual regression of animations, or in a Node server so an AI
8
+ agent can look at the SVG/HTML it generated.
9
+
10
+ An agent (or a reviewer) can only look at still images, and one screenshot shows one
11
+ moment. framesheet renders the whole cycle at exact virtual times and returns:
12
+
13
+ | Image | Use it for |
14
+ | --- | --- |
15
+ | `full` | One full-resolution frame (default `t=0`, `at`): layout, text, margins. |
16
+ | `sheet` | Contact sheet: N frames over one cycle, each labelled `t=0.50s`. The last tile is one 60 fps frame before the cycle end, so the loop seam is visible. |
17
+ | `heatmap` | Every pixel that changes at any time, coloured over a dimmed first frame. |
18
+ | `report` | Duration and how it was found, findings (stable codes), per-frame changed-pixel ratios, boxes of animated elements, loop seamlessness. Schema: `framesheet/schema/report.schema.json`. |
19
+
20
+ ![Contact sheet of the pipeline fixture](https://raw.githubusercontent.com/phil65/framesheet/main/docs/assets/pipeline_sheet.png)
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ npm install -D framesheet playwright-core # or: bun add -d framesheet playwright-core
26
+ npx playwright install chromium # once (Linux CI: --with-deps chromium)
27
+ ```
28
+
29
+ `playwright-core` (>= 1.45) is a peer dependency: framesheet uses your Playwright and its
30
+ browsers. A project that already has `@playwright/test` or `playwright` has it. ESM only,
31
+ Node >= 20 or Bun. No native dependencies (PNG decoding is pure JS; the sheet and heatmap
32
+ are drawn on a canvas in the same Chromium, with the font the Python images use).
33
+
34
+ ## `inspect()`: a file, markup string or URL
35
+
36
+ ```ts
37
+ import { inspect } from "framesheet";
38
+
39
+ const result = await inspect("banner.svg", { frames: 12 });
40
+ console.log(result.summary()); // same text as the Python CLI
41
+ result.images.sheet; // PNG Buffer (also full, heatmap)
42
+ result.report.loop.seamless; // report.json content (snake_case, shared schema)
43
+ for (const f of result.findings) console.log(f.severity, f.code, f.element, f.times);
44
+
45
+ await inspect('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">...</svg>');
46
+ await inspect("https://example.com/anim.html", { size: [1440, 900], scale: 2 });
47
+ await inspect("canvas.html", { duration: 4, out: "/tmp/check" }); // also writes the files
48
+ ```
49
+
50
+ Options: `frames` (2-100, default 12), `duration` (s; detected if omitted), `at` (s, time
51
+ of `full`), `size` (`[w, h]`), `scale`, `tile`, `columns`, `heatFrames` (default 48),
52
+ `keepFrames`, `colorScheme`, `out` (write `full.png`, `sheet.png`, `heatmap.png`,
53
+ `report.json`; without it nothing touches the disk), `timeout` (ms), `browser` (reuse a
54
+ launched `Browser`; a fresh context is used per call), `launchOptions`, `blockNetwork`
55
+ (abort every request except the input: use it for untrusted markup).
56
+
57
+ The result is an `Inspection`: `report`, `images` (`full`, `sheet`, `heatmap`,
58
+ `frames?`), `files` (paths, with `out`), `findings`, `errors`, `warnings`, `codes()`,
59
+ `summary()`. Output is deterministic: same input, same environment, same PNG bytes.
60
+
61
+ ## `inspectPage()`: a page or component you already have open
62
+
63
+ ```ts
64
+ import { inspectPage, prepare } from "framesheet";
65
+
66
+ const result = await inspectPage(page, {
67
+ locator: page.locator("#mindmap"), // optional: one component (also inside an iframe)
68
+ frames: 8,
69
+ trigger: () => page.getByRole("button", { name: "Open" }).click(),
70
+ });
71
+ ```
72
+
73
+ What works where:
74
+
75
+ | Motion | Works on any page, any time | Needs `prepare(page)` **before** `goto` |
76
+ | --- | --- | --- |
77
+ | SMIL (`<animate>`, `<animateMotion>`, ...) | yes: paused and seeked per frame | |
78
+ | CSS animations and transitions | yes: `document.getAnimations()` seeked | |
79
+ | Web Animations (`el.animate`) | yes, same | |
80
+ | `requestAnimationFrame`, timers, `Date`, `performance.now` (canvas, spring/rAF animation libraries) | runs on real time: frames are not exact | yes: Playwright's fake clock is stepped per frame |
81
+
82
+ - `prepare(page)` installs Playwright's fake clock before navigation. It follows real
83
+ time, so the app behaves normally, until `inspectPage` pauses it (on a 16 ms frame
84
+ boundary) and steps it frame by frame; afterwards it runs on.
85
+ - `prepare(page, { paused: true })` freezes time from navigation on, exactly like
86
+ `inspect()`: JS-driven motion that starts on load is captured from its first frame.
87
+ App timers stand still until an inspection (or `page.clock.runFor`) advances them;
88
+ good for component pages and stories, risky for whole apps that rely on timers.
89
+ - `trigger` runs after time is frozen and before `t=0` is captured: start an "open"
90
+ animation by clicking, and the sheet shows it from its first frame. Declarative
91
+ animations that already ran are rewound to their start either way (every animation is
92
+ timed from when the inspection first sees it).
93
+ - `locator` limits everything to the component: duration detection (animations of
94
+ other elements are ignored), geometry and checks, and the images (clipped to its box,
95
+ plus `padding`). Geometry is in the coordinates of the component's frame.
96
+ - Afterwards the page is handed back: SMIL and animations that were running play again
97
+ (from where the inspection left them) and the fake clock resumes.
98
+ - Static source checks are off for pages (`staticChecks: true` runs them on the
99
+ serialised markup of the page or component).
100
+ - A second inspection of the same page gives the same geometry and report, but Chromium
101
+ may antialias a few edge pixels differently on a page that already painted other
102
+ states; a fresh navigation (as in an e2e test) is byte-identical.
103
+
104
+ ## Visual regression in a Playwright suite: `framesheet/test`
105
+
106
+ ```ts
107
+ // e2e/mindmap.spec.ts
108
+ import { test } from "@playwright/test";
109
+ import { expectAnimation, prepare } from "framesheet/test";
110
+
111
+ test("mind map opens smoothly", async ({ page }) => {
112
+ await page.goto("/mindmap/demo");
113
+ await expectAnimation(page.locator("#mindmap"), "mindmap-open", {
114
+ frames: 8,
115
+ trigger: () => page.getByRole("button", { name: "Expand" }).click(),
116
+ maxDiffPixelRatio: 0.01,
117
+ });
118
+ });
119
+
120
+ test("drawing replays its strokes", async ({ page }) => {
121
+ await prepare(page, { paused: true }); // JS-driven: freeze the clock before goto
122
+ await page.goto("/drawings/demo");
123
+ await expectAnimation(page.locator("canvas"), "drawing-replay", { duration: 2 });
124
+ });
125
+ ```
126
+
127
+ `expectAnimation(target, name, options)` builds the contact sheet of a page or locator
128
+ and asserts it with Playwright's own `expect(buffer).toMatchSnapshot("<name>.png")`, so
129
+ `--update-snapshots`, per-platform baseline names (`<name>-chromium-linux.png`) and the
130
+ HTML report's diff view work as usual. Options: everything of `inspectPage`, plus
131
+ `maxDiffPixelRatio`, `maxDiffPixels`, `threshold`, `heatmap` (also compare
132
+ `<name>-heatmap.png`), `failOn` (`"error"` default, `"warning"`, or `false`), `ignore`
133
+ (codes), `snapshot` (`false`: findings only), `attach` (default: attach sheet, heatmap,
134
+ full frame and report.json to the test). It returns the `Inspection`. The sheet title is
135
+ `name`, so baselines do not depend on the dev server's URL.
136
+
137
+ For stable baselines launch Chromium like framesheet does:
138
+
139
+ ```ts
140
+ // playwright.config.ts
141
+ import { LAUNCH_ARGS } from "framesheet";
142
+ export default defineConfig({
143
+ use: { launchOptions: { args: LAUNCH_ARGS } }, // main-thread animations, sRGB, no LCD text
144
+ });
145
+ ```
146
+
147
+ Baselines differ between platforms and font setups (as with `toHaveScreenshot`): record
148
+ them where CI runs (e.g. the Playwright Docker image) and keep `maxDiffPixelRatio` small
149
+ but non-zero.
150
+
151
+ ## In a server (agent tools)
152
+
153
+ framesheet runs anywhere Node and Chromium run; nothing is written to disk unless you pass
154
+ `out`. Markup strings are served from a virtual origin through `page.route`, never from
155
+ the filesystem.
156
+
157
+ - **Chromium must be available in the deployment.** Playwright's Chromium builds need
158
+ glibc: use a Debian/Ubuntu base (`node:24-bookworm-slim` +
159
+ `npx playwright install --with-deps chromium`) or the
160
+ `mcr.microsoft.com/playwright:v1.65.1-noble` image. Alpine (musl) is not supported by
161
+ Playwright's browsers; there, run Chromium in a sidecar container
162
+ (`npx playwright run-server`) and pass `browser: await chromium.connect(wsEndpoint)`.
163
+ - Launch one browser and reuse it (`browser` option): launching costs ~0.5 s. With the
164
+ defaults (12 tiles + 48 heatmap frames) an inspection takes ~5-8 s, most of it one
165
+ browser round trip per frame; `frames: 8, heatFrames: 12` takes ~2 s.
166
+ - Untrusted input: `blockNetwork: true`, a `timeout`, a concurrency limit, and never
167
+ `out` paths derived from user input.
168
+
169
+ See [docs/contexter-skill.md](https://github.com/phil65/framesheet/blob/main/docs/contexter-skill.md)
170
+ for a worked sketch of an agent tool.
171
+
172
+ ## How time is controlled
173
+
174
+ Same as the Python package (see its README): SMIL `pauseAnimations()` +
175
+ `setCurrentTime(t)`; every `document.getAnimations()` entry paused with `currentTime`
176
+ set; JS clocks on Playwright's fake clock, advanced with `clock.runFor`. Duration
177
+ detection: SMIL `begin`/`dur`/`repeatCount` and CSS/Web Animation timing (alternate = 2x,
178
+ several loops = LCM when short enough, positive delays added, finite animations end);
179
+ `duration` overrides; no declarative animation -> 3 s and a `js-driven-motion` warning.
180
+
181
+ ## Checks
182
+
183
+ Static (source text; `inspect()` only by default): `malformed-xml`, `not-svg`,
184
+ `missing-xmlns`, `missing-viewbox`, `missing-title`, `script`, `foreign-object`,
185
+ `event-handler`, `external-url`, `positive-begin`, `duplicate-id`, `broken-ref`,
186
+ `css-external`, `no-reduced-motion`, `transform-origin-without-box`,
187
+ `transform-without-box`, `large-file`. Render (geometry and pixels over time):
188
+ `parked-at-origin`, `outside-bounds`, `text-overflow`, `svg-transform-box`,
189
+ `non-seamless-loop`, `js-driven-motion`, `no-visible-motion`, `no-motion`,
190
+ `console-error`. Codes are API; the schema pins them.
191
+
192
+ ## Development
193
+
194
+ The package lives in `js/` of the [framesheet repo](https://github.com/phil65/framesheet).
195
+
196
+ ```bash
197
+ cd js
198
+ npm ci && npx playwright install chromium
199
+ npm run build # embeds ../src/framesheet/runtime.js + font, compiles to dist/
200
+ npm run typecheck
201
+ npm test # vitest: Python fixtures, determinism, schema parity
202
+ npm run test:e2e # Playwright: expectAnimation demo (e2e/)
203
+ npm run check:runtime # dist/ embeds exactly ../src/framesheet/runtime.js
204
+ ```
205
+
206
+ Parity with Python is checked against `../schema/report.schema.json` and the golden
207
+ Python reports in `../schema/golden/` (regenerate both with
208
+ `uv run python scripts/sync_schema.py --golden` from the repo root; CI regenerates them
209
+ on the runner and compares strictly).
210
+
211
+ ## License
212
+
213
+ MIT
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Render checks on per-frame geometry (port of analysis.py).
3
+ *
4
+ * Each check is a function `(Geometry) => Finding[]` registered in {@link CHECKS}.
5
+ * Keep the logic, thresholds and messages in step with analysis.py.
6
+ */
7
+ import type { AnimationTiming, ElementTrack, Finding, Rect } from "./models.js";
8
+ /** Pixels an element may poke out of its container/canvas before it is reported. */
9
+ export declare const TOLERANCE = 1;
10
+ export declare const MAX_TRACKS = 30;
11
+ export declare const MAX_REPORTED = 12;
12
+ export declare const SMALL_FRACTION = 0.2;
13
+ export declare const CONTAINERS: Set<string>;
14
+ export interface Element {
15
+ index: number;
16
+ tag: string;
17
+ label: string;
18
+ svg: boolean;
19
+ parent: number;
20
+ }
21
+ /** `[index, clientRect, userRect | null, visible]` per rendered element (runtime `measure()`). */
22
+ export type GeometryEntry = [number, number[], number[] | null, boolean];
23
+ /** Everything captured at one sample time. */
24
+ export interface FrameGeometry {
25
+ t: number;
26
+ geometry: GeometryEntry[];
27
+ /** HTML text overflow `[index, dx, dy]`. */
28
+ overflow: [number, number, number][];
29
+ }
30
+ export interface Description {
31
+ i: number;
32
+ tag: string;
33
+ label: string;
34
+ svg: boolean;
35
+ parent: number;
36
+ }
37
+ /** Inputs shared by all render checks. */
38
+ export declare class Geometry {
39
+ elements: Map<number, Element>;
40
+ times: number[];
41
+ /** Client rect (CSS px) per element per frame; `null` = not rendered/invisible. */
42
+ client: Map<number, (Rect | null)[]>;
43
+ /** SVG user-space rect (outermost `<svg>`) per element per frame. */
44
+ user: Map<number, (Rect | null)[]>;
45
+ canvas: Rect;
46
+ viewbox: Rect | null;
47
+ targets: Map<number, string[]>;
48
+ animations: AnimationTiming[];
49
+ isSvgDoc: boolean;
50
+ /** `[index, dx, dy]` per frame. */
51
+ htmlOverflow: [number, number, number][][];
52
+ constructor(elements: Map<number, Element>, times: number[],
53
+ /** Client rect (CSS px) per element per frame; `null` = not rendered/invisible. */
54
+ client: Map<number, (Rect | null)[]>,
55
+ /** SVG user-space rect (outermost `<svg>`) per element per frame. */
56
+ user: Map<number, (Rect | null)[]>, canvas: Rect, viewbox: Rect | null, targets: Map<number, string[]>, animations: AnimationTiming[], isSvgDoc: boolean,
57
+ /** `[index, dx, dy]` per frame. */
58
+ htmlOverflow: [number, number, number][][]);
59
+ static build(description: Description[], snapshots: FrameGeometry[], opts: {
60
+ canvas: Rect;
61
+ viewbox: Rect | null;
62
+ targets: Record<string, string[]>;
63
+ animations: AnimationTiming[];
64
+ isSvgDoc: boolean;
65
+ }): Geometry;
66
+ ancestors(index: number): number[];
67
+ label(index: number): string;
68
+ moved(): Set<number>;
69
+ }
70
+ export declare function fmtTimes(times: number[]): string;
71
+ /** Per-frame boxes of animated elements (declared targets or anything that moved). */
72
+ export declare function tracks(geo: Geometry): ElementTrack[];
73
+ /** Elements extending past the viewBox (SVG) or viewport (HTML). */
74
+ export declare function checkOutside(geo: Geometry): Finding[];
75
+ /** Small SVG elements sitting on the user-space origin (0,0), e.g. before `begin`. */
76
+ export declare function checkParked(geo: Geometry): Finding[];
77
+ /** SVG `<text>` poking out of the `<rect>` painted under it; HTML text overflow. */
78
+ export declare function checkTextOverflow(geo: Geometry): Finding[];
79
+ /** CSS transform animations on SVG elements without `transform-box: fill-box`. */
80
+ export declare function checkTransformBox(geo: Geometry): Finding[];
81
+ /** Render checks run on every inspection, in order. Append to add a check. */
82
+ export declare const CHECKS: ((geo: Geometry) => Finding[])[];
83
+ export declare function runChecks(geo: Geometry): Finding[];
84
+ //# sourceMappingURL=analysis.d.ts.map
@@ -0,0 +1 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;QAClC,UAAU,EAAE,eAAe,EAAE,CAAC;QAC9B,QAAQ,EAAE,OAAO,CAAC;KACnB,GACA,QAAQ,CAqCV;IAED,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAQjC;IAED,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE3B;IAED,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,CAWnB;CACF;AAiBD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAKhD;AAQD,sFAAsF;AACtF,wBAAgB,MAAM,CAAC,GAAG,EAAE,QAAQ,GAAG,YAAY,EAAE,CAwBpD;AAED,oEAAoE;AACpE,wBAAgB,YAAY,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,EAAE,CAoDrD;AAED,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,EAAE,CAyBpD;AAmCD,oFAAoF;AACpF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,EAAE,CAuD1D;AAED,kFAAkF;AAClF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,EAAE,CAmB1D;AAED,8EAA8E;AAC9E,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,GAAG,EAAE,QAAQ,KAAK,OAAO,EAAE,CAAC,EAKlD,CAAC;AAEF,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,EAAE,CAgBlD"}
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Render checks on per-frame geometry (port of analysis.py).
3
+ *
4
+ * Each check is a function `(Geometry) => Finding[]` registered in {@link CHECKS}.
5
+ * Keep the logic, thresholds and messages in step with analysis.py.
6
+ */
7
+ import { asRect } from "./models.js";
8
+ import { fixed } from "./pyfmt.js";
9
+ /** Pixels an element may poke out of its container/canvas before it is reported. */
10
+ export const TOLERANCE = 1.0;
11
+ export const MAX_TRACKS = 30;
12
+ export const MAX_REPORTED = 12;
13
+ export const SMALL_FRACTION = 0.2;
14
+ export const CONTAINERS = new Set(["g", "svg", "a", "switch", "div", "section", "main", "article", "span"]);
15
+ /** Inputs shared by all render checks. */
16
+ export class Geometry {
17
+ elements;
18
+ times;
19
+ client;
20
+ user;
21
+ canvas;
22
+ viewbox;
23
+ targets;
24
+ animations;
25
+ isSvgDoc;
26
+ htmlOverflow;
27
+ constructor(elements, times,
28
+ /** Client rect (CSS px) per element per frame; `null` = not rendered/invisible. */
29
+ client,
30
+ /** SVG user-space rect (outermost `<svg>`) per element per frame. */
31
+ user, canvas, viewbox, targets, animations, isSvgDoc,
32
+ /** `[index, dx, dy]` per frame. */
33
+ htmlOverflow) {
34
+ this.elements = elements;
35
+ this.times = times;
36
+ this.client = client;
37
+ this.user = user;
38
+ this.canvas = canvas;
39
+ this.viewbox = viewbox;
40
+ this.targets = targets;
41
+ this.animations = animations;
42
+ this.isSvgDoc = isSvgDoc;
43
+ this.htmlOverflow = htmlOverflow;
44
+ }
45
+ static build(description, snapshots, opts) {
46
+ const elements = new Map();
47
+ for (const d of description) {
48
+ elements.set(d.i, { index: d.i, tag: d.tag, label: d.label, svg: d.svg, parent: d.parent });
49
+ }
50
+ const n = snapshots.length;
51
+ const client = new Map();
52
+ const user = new Map();
53
+ const slot = (m, i) => {
54
+ let v = m.get(i);
55
+ if (!v) {
56
+ v = new Array(n).fill(null);
57
+ m.set(i, v);
58
+ }
59
+ return v;
60
+ };
61
+ snapshots.forEach((snap, k) => {
62
+ for (const [index, rect, userRect, visible] of snap.geometry) {
63
+ if (!visible)
64
+ continue;
65
+ slot(client, index)[k] = asRect(rect);
66
+ if (userRect != null)
67
+ slot(user, index)[k] = asRect(userRect);
68
+ }
69
+ });
70
+ const targets = new Map();
71
+ for (const [k, v] of Object.entries(opts.targets))
72
+ targets.set(Number(k), v);
73
+ return new Geometry(elements, snapshots.map((s) => s.t), client, user, opts.canvas, opts.viewbox, targets, opts.animations, opts.isSvgDoc, snapshots.map((s) => s.overflow));
74
+ }
75
+ ancestors(index) {
76
+ const out = [];
77
+ let parent = this.elements.get(index)?.parent ?? -1;
78
+ while (parent !== -1 && this.elements.has(parent)) {
79
+ out.push(parent);
80
+ parent = this.elements.get(parent).parent;
81
+ }
82
+ return out;
83
+ }
84
+ label(index) {
85
+ return this.elements.get(index)?.label ?? `element ${index}`;
86
+ }
87
+ moved() {
88
+ const out = new Set();
89
+ for (const [index, rects] of this.client) {
90
+ const present = rects.filter((r) => r !== null);
91
+ if (present.length !== rects.length && present.length) {
92
+ out.add(index); // appears / disappears
93
+ continue;
94
+ }
95
+ if (present.length && present.slice(1).some((r) => differs(present[0], r)))
96
+ out.add(index);
97
+ }
98
+ return out;
99
+ }
100
+ }
101
+ function differs(a, b, tol = 0.5) {
102
+ return a.some((x, i) => Math.abs(x - b[i]) > tol);
103
+ }
104
+ /** Drop flagged elements that have a flagged descendant (report the innermost). */
105
+ function leaves(geo, flagged) {
106
+ const covered = new Set();
107
+ for (const i of flagged)
108
+ for (const a of geo.ancestors(i))
109
+ covered.add(a);
110
+ return new Set([...flagged].filter((i) => !covered.has(i)));
111
+ }
112
+ function timesAt(geo, ks) {
113
+ return ks.map((k) => geo.times[k]);
114
+ }
115
+ export function fmtTimes(times) {
116
+ if (times.length > 4) {
117
+ return `t=${fixed(times[0], 2)}s..${fixed(times[times.length - 1], 2)}s (${times.length} frames)`;
118
+ }
119
+ return `t=${times.map((t) => `${fixed(t, 2)}s`).join(", ")}`;
120
+ }
121
+ function finding(code, message, element, times) {
122
+ return { severity: "warning", code, message, check: "render", element, times };
123
+ }
124
+ const byNumber = (a, b) => a - b;
125
+ /** Per-frame boxes of animated elements (declared targets or anything that moved). */
126
+ export function tracks(geo) {
127
+ const moved = geo.moved();
128
+ const targetSet = new Set(geo.targets.keys());
129
+ // A moving group moves all its children: keep the outermost mover. A group whose box
130
+ // only changes because an animated descendant moves is not reported on its own.
131
+ const explained = new Set();
132
+ for (const i of targetSet)
133
+ for (const a of geo.ancestors(i))
134
+ if (!targetSet.has(a))
135
+ explained.add(a);
136
+ const movers = new Set([...moved].filter((i) => !explained.has(i)));
137
+ const indices = new Set(targetSet);
138
+ for (const i of movers)
139
+ if (!geo.ancestors(i).some((a) => movers.has(a)))
140
+ indices.add(i);
141
+ const out = [];
142
+ for (const index of [...indices].sort(byNumber).slice(0, MAX_TRACKS)) {
143
+ const boxes = geo.user.get(index) ?? geo.client.get(index);
144
+ if (!boxes)
145
+ continue;
146
+ const kinds = [...(geo.targets.get(index) ?? [])];
147
+ if (moved.has(index))
148
+ kinds.push("moved");
149
+ out.push({
150
+ element: geo.label(index),
151
+ animated_by: kinds,
152
+ units: geo.user.has(index) ? "viewBox" : "px",
153
+ boxes,
154
+ });
155
+ }
156
+ return out;
157
+ }
158
+ /** Elements extending past the viewBox (SVG) or viewport (HTML). */
159
+ export function checkOutside(geo) {
160
+ const [cx, cy, cw, ch] = geo.canvas;
161
+ const hits = new Map();
162
+ const amounts = new Map();
163
+ for (const [index, rects] of geo.client) {
164
+ rects.forEach((rect, k) => {
165
+ if (rect === null)
166
+ return;
167
+ const [x, y, w, h] = rect;
168
+ const over = [
169
+ ["left", cx - x],
170
+ ["top", cy - y],
171
+ ["right", x + w - (cx + cw)],
172
+ ["bottom", y + h - (cy + ch)],
173
+ ];
174
+ const worst = over.filter(([, v]) => v > TOLERANCE);
175
+ if (worst.length) {
176
+ (hits.get(index) ?? hits.set(index, []).get(index)).push(k);
177
+ const agg = amounts.get(index) ?? amounts.set(index, new Map()).get(index);
178
+ for (const [side, v] of worst)
179
+ agg.set(side, Math.max(agg.get(side) ?? 0, v));
180
+ }
181
+ });
182
+ }
183
+ const keep = leaves(geo, new Set(hits.keys()));
184
+ const area = geo.isSvgDoc ? "viewBox" : "viewport";
185
+ const out = [];
186
+ const worstOf = (i) => Math.max(...amounts.get(i).values());
187
+ // Python sorts a set of small ints (ascending iteration order) by the worst amount.
188
+ const ordered = [...keep].sort(byNumber).sort((a, b) => worstOf(b) - worstOf(a));
189
+ for (const index of ordered.slice(0, MAX_REPORTED)) {
190
+ const ks = hits.get(index);
191
+ const sides = [...amounts.get(index).entries()].map(([side, v]) => `${fixed(v, 0)}px ${side}`).join(", ");
192
+ const when = ks.length === geo.times.length ? "at every frame" : `at ${fmtTimes(timesAt(geo, ks))}`;
193
+ out.push(finding("outside-bounds", `${geo.label(index)} extends outside the ${area} ${when} (up to ${sides}).`, geo.label(index), timesAt(geo, ks)));
194
+ }
195
+ if (ordered.length > MAX_REPORTED) {
196
+ out.push(finding("outside-bounds", `... and ${ordered.length - MAX_REPORTED} more element(s) outside the ${area}.`, null, null));
197
+ }
198
+ return out;
199
+ }
200
+ /** Small SVG elements sitting on the user-space origin (0,0), e.g. before `begin`. */
201
+ export function checkParked(geo) {
202
+ if (geo.viewbox === null)
203
+ return [];
204
+ const [, , vw, vh] = geo.viewbox;
205
+ const hits = new Map();
206
+ for (const [index, rects] of geo.user) {
207
+ const element = geo.elements.get(index);
208
+ if (!element || CONTAINERS.has(element.tag))
209
+ continue;
210
+ rects.forEach((rect, k) => {
211
+ if (rect === null)
212
+ return;
213
+ const [x, y, w, h] = rect;
214
+ const small = w < SMALL_FRACTION * vw && h < SMALL_FRACTION * vh;
215
+ const coversOrigin = x <= TOLERANCE && y <= TOLERANCE && x + w >= 0 && y + h >= 0;
216
+ if (small && coversOrigin)
217
+ (hits.get(index) ?? hits.set(index, []).get(index)).push(k);
218
+ });
219
+ }
220
+ return [...leaves(geo, new Set(hits.keys()))].sort(byNumber).map((index) => {
221
+ const times = timesAt(geo, hits.get(index));
222
+ return finding("parked-at-origin", `${geo.label(index)} sits at the SVG origin (0,0) at ${fmtTimes(times)}; ` +
223
+ "typical cause: <animateMotion> with a positive begin, or a missing x/y/cx/cy.", geo.label(index), times);
224
+ });
225
+ }
226
+ const rectArea = (r) => r[2] * r[3];
227
+ function overlap(a, b) {
228
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
229
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
230
+ return Math.max(0, w) * Math.max(0, h);
231
+ }
232
+ function excess(inner, outer) {
233
+ return Math.max(outer[0] - inner[0], outer[1] - inner[1], inner[0] + inner[2] - (outer[0] + outer[2]), inner[1] + inner[3] - (outer[1] + outer[3]));
234
+ }
235
+ /** Smallest rect painted before `text` that covers at least 30% of it. */
236
+ function container(geo, text, box, rects, k) {
237
+ let best = null;
238
+ let bestArea = Infinity;
239
+ for (const index of rects) {
240
+ if (index > text || !geo.client.has(index))
241
+ continue;
242
+ const rect = geo.client.get(index)[k];
243
+ if (rect === null || rectArea(box) === 0)
244
+ continue;
245
+ if (overlap(box, rect) / rectArea(box) >= 0.3 && rectArea(rect) < bestArea) {
246
+ best = index;
247
+ bestArea = rectArea(rect);
248
+ }
249
+ }
250
+ return best;
251
+ }
252
+ /** SVG `<text>` poking out of the `<rect>` painted under it; HTML text overflow. */
253
+ export function checkTextOverflow(geo) {
254
+ const hits = new Map();
255
+ const amounts = new Map();
256
+ const rects = [...geo.elements.values()].filter((el) => el.tag === "rect").map((el) => el.index);
257
+ for (const [index, el] of geo.elements) {
258
+ if (el.tag !== "text" || !geo.client.has(index))
259
+ continue;
260
+ geo.client.get(index).forEach((textBox, k) => {
261
+ if (textBox === null)
262
+ return;
263
+ const box = container(geo, index, textBox, rects, k);
264
+ if (box === null)
265
+ return;
266
+ const containerBox = geo.client.get(box)[k];
267
+ if (containerBox === null)
268
+ return;
269
+ const ex = excess(textBox, containerBox);
270
+ if (ex > TOLERANCE) {
271
+ const key = `${index},${box}`;
272
+ (hits.get(key) ?? hits.set(key, []).get(key)).push(k);
273
+ amounts.set(key, Math.max(amounts.get(key) ?? 0, ex));
274
+ }
275
+ });
276
+ }
277
+ const keyed = [...hits.entries()]
278
+ .map(([key, ks]) => ({ key, ks, pair: key.split(",").map(Number) }))
279
+ .sort((a, b) => a.pair[0] - b.pair[0] || a.pair[1] - b.pair[1]);
280
+ const out = keyed.map(({ key, ks, pair: [text, box] }) => finding("text-overflow", `${geo.label(text)} overflows its container ${geo.label(box)} by up to ` +
281
+ `${fixed(amounts.get(key), 0)}px at ${fmtTimes(timesAt(geo, ks))}.`, geo.label(text), timesAt(geo, ks)));
282
+ const htmlHits = new Map();
283
+ const htmlAmount = new Map();
284
+ geo.htmlOverflow.forEach((items, k) => {
285
+ for (const [index, dx, dy] of items) {
286
+ (htmlHits.get(index) ?? htmlHits.set(index, []).get(index)).push(k);
287
+ const [ox, oy] = htmlAmount.get(index) ?? [0, 0];
288
+ htmlAmount.set(index, [Math.max(ox, dx), Math.max(oy, dy)]);
289
+ }
290
+ });
291
+ for (const index of [...htmlHits.keys()].sort(byNumber)) {
292
+ const ks = htmlHits.get(index);
293
+ const [dx, dy] = htmlAmount.get(index);
294
+ out.push(finding("text-overflow", `${geo.label(index)} content is larger than its box (${fixed(dx, 0)}px wider, ` +
295
+ `${fixed(dy, 0)}px taller) at ${fmtTimes(timesAt(geo, ks))}.`, geo.label(index), timesAt(geo, ks)));
296
+ }
297
+ return out;
298
+ }
299
+ /** CSS transform animations on SVG elements without `transform-box: fill-box`. */
300
+ export function checkTransformBox(geo) {
301
+ const out = [];
302
+ const seen = new Set();
303
+ for (const anim of geo.animations) {
304
+ if (anim.transform_box !== "view-box" || !anim.target || seen.has(anim.target))
305
+ continue;
306
+ seen.add(anim.target);
307
+ out.push(finding("svg-transform-box", `CSS animation '${anim.name}' on ${anim.target} animates transform with ` +
308
+ "transform-box: view-box (the SVG default), so it rotates/scales around the " +
309
+ "SVG origin, not the element. Add transform-box: fill-box; " +
310
+ "transform-origin: center.", anim.target, null));
311
+ }
312
+ return out;
313
+ }
314
+ /** Render checks run on every inspection, in order. Append to add a check. */
315
+ export const CHECKS = [
316
+ checkParked,
317
+ checkOutside,
318
+ checkTextOverflow,
319
+ checkTransformBox,
320
+ ];
321
+ export function runChecks(geo) {
322
+ const findings = CHECKS.flatMap((check) => check(geo));
323
+ // An element parked at (0,0) usually pokes out of the top-left corner too: report once.
324
+ const parked = new Set();
325
+ for (const f of findings) {
326
+ if (f.code === "parked-at-origin")
327
+ for (const t of f.times ?? [])
328
+ parked.add(`${f.element}@${t}`);
329
+ }
330
+ return findings.filter((f) => !(f.code === "outside-bounds" &&
331
+ f.times &&
332
+ f.times.length &&
333
+ f.times.every((t) => parked.has(`${f.element}@${t}`))));
334
+ }
335
+ //# sourceMappingURL=analysis.js.map